fix(anatomy): V1-2.2 owner arbitrations on SVG references and bytes

Refuse local references to ids a drawing does not define, scope canvas
ids per view, upload every drawing in one stored form checked by the
verdict and the preview, keep strict numeric rgb() colours, and commit
real Inkscape 1.4.3 exports with their generator.
This commit is contained in:
bchanot committed 2026-10-29 16:24:07 +01:00
1 parent 17d919971e
commit e823655f09
31 files changed
+1362 -110

No files matched your search

+25
View File
@@ -101,3 +101,28 @@ export function withTriggerNamesPerLanguage(tree: unknown, views: readonly ViewN
visit(copy) visit(copy)
return copy return copy
} }
/**
* Owner decision 2026-10-29 (V1-2.2): the canvas, inlined in the page, scopes the drawing's
* ids and the references to them to its view (`fv.<view>.<id>`). Applied to a frozen tree (a
* deep copy), written apart from the core's rewrite: every `id`, every `#id` href and every
* plain `url(#` (the only spelling of the product drawing). Mirrors
* `crates/core/tests/common/svg_tree.rs`.
*/
export function withIdsScopedPerView(tree: unknown, viewId: string): unknown {
const copy = structuredClone(tree)
const scope = `fv.${viewId}.`
const visit = (node: unknown): void => {
if (typeof node !== 'object' || node === null) return
const n = node as { attrs?: Record<string, string>; children?: unknown[] }
for (const [name, value] of Object.entries(n.attrs ?? {})) {
if (name === 'id') n.attrs![name] = `${scope}${value}`
else if ((name === 'href' || name === 'xlink:href') && value.startsWith('#')) {
n.attrs![name] = `#${scope}${value.slice(1)}`
} else n.attrs![name] = value.replaceAll('url(#', `url(#${scope}`)
}
n.children?.forEach(visit)
}
visit(copy)
return copy
}
+5 -1
View File
@@ -21,6 +21,7 @@ import {
import { import {
checkR3Golden, checkR3Golden,
treeOf, treeOf,
withIdsScopedPerView,
withTriggerNamesPerLanguage, withTriggerNamesPerLanguage,
type TreeNode, type TreeNode,
} from '../helpers/svgTree' } from '../helpers/svgTree'
@@ -81,7 +82,10 @@ describe.each(VIEWS)('the %s canvas', (viewId) => {
it('builds the frozen tree with no state', () => { it('builds the frozen tree with no state', () => {
const build = buildViewSvg(sheet, viewId) const build = buildViewSvg(sheet, viewId)
if (!build.ok) throw new Error(`canvas ${viewId}: ${build.failure}`) if (!build.ok) throw new Error(`canvas ${viewId}: ${build.failure}`)
checkR3Golden(`canvas.${viewId}.json`, treeOf(build.svg), declared) // and the owner's decision 2026-10-29: the drawing's ids scoped to the view
checkR3Golden(`canvas.${viewId}.json`, treeOf(build.svg), (frozen) =>
withIdsScopedPerView(declared(frozen), viewId),
)
}) })
it('shows the frozen layer for every state set of the reference reports', async () => { it('shows the frozen layer for every state set of the reference reports', async () => {
+36
View File
@@ -4,10 +4,18 @@
//! is known, the interactive layer) and the PDF highlight (`packages/anatomy/src/render/ //! is known, the interactive layer) and the PDF highlight (`packages/anatomy/src/render/
//! compose.ts`: the asset's root framed in place, the selected markers only, recoloured, the //! compose.ts`: the asset's root framed in place, the selected markers only, recoloured, the
//! halo filter on request). Both take a sanitised tree, never text. //! halo filter on request). Both take a sanitised tree, never text.
//!
//! The canvas is inlined into the page, where `#id` resolves against the whole document: its
//! ids and the references to them are scoped to the view (`fv.<view id>.<id>`, owner decision
//! 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.
use std::collections::HashSet; use std::collections::HashSet;
use super::layer::{LayerError, find_view, render_layer, view_box_of}; use super::layer::{LayerError, find_view, render_layer, view_box_of};
use super::svg::sanitize::{local_reference_text, scope_url_targets};
use super::svg::serialize::is_xml_text; use super::svg::serialize::is_xml_text;
use super::svg::{Element, Node}; use super::svg::{Element, Node};
use crate::domain::sheet::AnatomicalSheetDocument; use crate::domain::sheet::AnatomicalSheetDocument;
@@ -73,11 +81,39 @@ pub fn compose_canvas(
.or_else(|| asset.attr("viewBox").map(str::to_owned)) .or_else(|| asset.attr("viewBox").map(str::to_owned))
.unwrap_or_else(|| CANVAS_FALLBACK_VIEW_BOX.to_owned()); .unwrap_or_else(|| CANVAS_FALLBACK_VIEW_BOX.to_owned());
root.set_attr("viewBox", view_box); root.set_attr("viewBox", view_box);
scope_ids(&mut root, &id_scope(view_id));
let layer = render_layer(document, view_id, &HashSet::new())?; let layer = render_layer(document, view_id, &HashSet::new())?;
root.children.push(Node::Element(checked(layer)?)); root.children.push(Node::Element(checked(layer)?));
Ok(root) Ok(root)
} }
/// The prefix of a view's ids in its canvas. Stable ids hold no `.`, so the scope of one view
/// is never the start of another's, and no page id starts with `fv.`.
pub fn id_scope(view_id: &str) -> String {
format!("fv.{view_id}.")
}
/// Every `id`, every local `href` / `xlink:href` and every `url(#id)` of the drawing, with
/// `scope` written in front of the id.
fn scope_ids(element: &mut Element, scope: &str) {
for attr in &mut element.attrs {
attr.value = match attr.qname.as_str() {
"id" => format!("{scope}{}", attr.value),
"href" | "xlink:href" => match local_reference_text(&attr.value).strip_prefix('#') {
Some(id) => format!("#{scope}{id}"),
None => continue,
},
_ if attr.value.contains('(') => scope_url_targets(&attr.value, scope),
_ => continue,
};
}
for child in &mut element.children {
if let Node::Element(child) = child {
scope_ids(child, scope);
}
}
}
/// The PDF view of `view_id`: `asset` (sanitised, consumed) framed on the view, the markers /// 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`.
pub fn compose_highlight( pub fn compose_highlight(
+37 -32
View File
@@ -3,24 +3,28 @@
//! //!
//! - rejected: a hard rejection of the reader (with its reason), a text that is not UTF-8 //! - rejected: a hard rejection of the reader (with its reason), a text that is not UTF-8
//! (`malformed`), or any removal of active or external content, or a processing //! (`malformed`), or any removal of active or external content, or a processing
//! instruction (`svg_active_content`, the names in `active`, a PI as `?<target>`); no //! instruction (`svg_active_content`, the names in `active`, a PI as `?<target>`), or, once
//! cleaning is offered; //! 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;
//! - cleanable: only other removals (editor metadata and namespaces, `data-*`, `<style>`, //! - cleanable: only other removals (editor metadata and namespaces, `data-*`, `<style>`,
//! `class` or `style` on the root, ids outside the grammar, unsupported elements, long //! `class` or `style` on the root, ids outside the grammar, unsupported elements, long
//! titles or descriptions): the cleaned text is the sanitised tree serialised, and it is //! titles or descriptions): the admin confirms them;
//! that text, read back with no removal, that is hashed and uploaded; //! - clean: no removal, nothing to confirm.
//! - clean: no removal; the original bytes are uploaded as they are.
//! //!
//! In every case but a rejection, `preview` is the drawing as the core reads it: the page //! In both accepted cases the bytes hashed and uploaded are `stored`, the drawing's stored
//! form (`serialize::stored_form`, owner decision 2026-10-29: never the original bytes, whose
//! declaration, comments or escapes a browser could read otherwise), checked to read back with
//! no removal and to give itself again. `preview` is the drawing as the core reads it: the page
//! shows that, never the original file. Stored drawings are never repaired afterwards //! shows that, never the original file. Stored drawings are never repaired afterwards
//! (LRN-055): the verdict reads each one again and refuses any removal. //! (LRN-055): the verdict reads each one again and refuses any removal or another form.
use serde::Serialize; use serde::Serialize;
#[cfg(feature = "ts")] #[cfg(feature = "ts")]
use ts_rs::TS; use ts_rs::TS;
use super::prescan::SVG_CAPS; use super::prescan::SVG_CAPS;
use super::serialize::serialize; use super::refs::check_targets;
use super::serialize::{serialize, stored_form};
use super::{processing_instructions, read_svg, read_svg_for_cleaning}; use super::{processing_instructions, read_svg, read_svg_for_cleaning};
use crate::domain::sheet::verdict::sha256_hex; use crate::domain::sheet::verdict::sha256_hex;
@@ -52,9 +56,9 @@ pub struct SvgCleaning {
pub style_removed: bool, pub style_removed: bool,
/// The drawing as the core reads it (sanitised, serialised). /// The drawing as the core reads it (sanitised, serialised).
pub preview: Option<String>, pub preview: Option<String>,
/// Cleanable only: the text to upload. /// Clean or cleanable: the text to upload, the drawing's stored form.
pub cleaned: Option<String>, pub stored: Option<String>,
/// SHA-256 and size of the bytes to upload: the original (clean) or the cleaned text. /// SHA-256 and size of `stored`, the bytes to upload.
pub sha256: Option<String>, pub sha256: Option<String>,
#[cfg_attr(feature = "ts", ts(type = "number | null"))] #[cfg_attr(feature = "ts", ts(type = "number | null"))]
pub byte_size: Option<u64>, pub byte_size: Option<u64>,
@@ -68,7 +72,7 @@ fn rejected(reason: &str, removed: Vec<String>, active: Vec<String>) -> SvgClean
removed, removed,
active, active,
preview: None, preview: None,
cleaned: None, stored: None,
sha256: None, sha256: None,
byte_size: None, byte_size: None,
} }
@@ -95,34 +99,34 @@ pub fn clean_svg(bytes: &[u8]) -> SvgCleaning {
if !active.is_empty() { if !active.is_empty() {
return rejected(ACTIVE_CONTENT, read.removed, active); return rejected(ACTIVE_CONTENT, read.removed, active);
} }
if let Err(rejection) = check_targets(&read.root) {
return rejected(rejection.reason(), read.removed, read.active);
}
let preview = serialize(&read.root); let preview = serialize(&read.root);
if preview.len() > MAX_PREVIEW_BYTES { if preview.len() > MAX_PREVIEW_BYTES {
return rejected("too_large", read.removed, read.active); return rejected("too_large", read.removed, read.active);
} }
if read.removed.is_empty() { let stored = stored_form(&read.root);
return accepted(CleaningOutcome::Clean, bytes, preview, Vec::new()); if stored.len() > SVG_CAPS.max_bytes {
}
if preview.len() > SVG_CAPS.max_bytes {
return rejected("too_large", read.removed, read.active); return rejected("too_large", read.removed, read.active);
} }
if !reads_back_clean(&preview) { if !reads_back_clean(&stored) {
return rejected("cleaning_unstable", read.removed, read.active); return rejected("cleaning_unstable", read.removed, read.active);
} }
accepted( let outcome = if read.removed.is_empty() {
CleaningOutcome::Cleanable, CleaningOutcome::Clean
preview.as_bytes(), } else {
preview.clone(), CleaningOutcome::Cleanable
read.removed, };
) accepted(outcome, stored, preview, read.removed)
} }
fn accepted( fn accepted(
outcome: CleaningOutcome, outcome: CleaningOutcome,
upload: &[u8], stored: String,
preview: String, preview: String,
removed: Vec<String>, removed: Vec<String>,
) -> SvgCleaning { ) -> SvgCleaning {
let cleaned = (outcome == CleaningOutcome::Cleanable).then(|| preview.clone());
SvgCleaning { SvgCleaning {
outcome, outcome,
reason: None, reason: None,
@@ -130,15 +134,16 @@ fn accepted(
removed, removed,
active: Vec::new(), active: Vec::new(),
preview: Some(preview), preview: Some(preview),
cleaned, sha256: Some(sha256_hex(stored.as_bytes())),
sha256: Some(sha256_hex(upload)), byte_size: Some(stored.len() as u64),
byte_size: Some(upload.len() as u64), stored: Some(stored),
} }
} }
/// The cleaned text reads back with nothing to remove and serialises to itself, so what the /// The stored text reads back with nothing to remove and gives itself again, so what the
/// admin confirms is what every reader draws (the fixpoint the property test of /// admin confirms is what every reader draws and what the verdict accepts (the fixpoint the
/// `tests/svg_clean.rs` proves; checked here too, so no upload rests on it alone). /// property test of `tests/svg_clean.rs` proves; checked here too, so no upload rests on it
/// alone).
fn reads_back_clean(text: &str) -> bool { fn reads_back_clean(text: &str) -> bool {
read_svg(text).is_ok_and(|read| read.removed.is_empty() && serialize(&read.root) == text) read_svg(text).is_ok_and(|read| read.removed.is_empty() && stored_form(&read.root) == text)
} }
+5 -2
View File
@@ -12,16 +12,19 @@ pub mod tree;
pub use sanitize::Sanitized; pub use sanitize::Sanitized;
pub use tree::{Element, Node, SvgRejection}; pub use tree::{Element, Node, SvgRejection};
/// Bounds, parses, sanitises and checks the references of an SVG text. /// Bounds, parses, sanitises and checks the references of an SVG text: no cycle, within the
/// expansion budget, each naming an id the drawing defines.
pub fn read_svg(text: &str) -> Result<Sanitized, SvgRejection> { pub fn read_svg(text: &str) -> Result<Sanitized, SvgRejection> {
let root = tree::parse_svg(text)?; let root = tree::parse_svg(text)?;
let sanitized = sanitize::sanitize(root)?; let sanitized = sanitize::sanitize(root)?;
refs::check_references(&sanitized.root)?; refs::check_references(&sanitized.root)?;
refs::check_targets(&sanitized.root)?;
Ok(sanitized) Ok(sanitized)
} }
/// `read_svg` as the cleaning reads a file picked for upload: an oversized `title` or `desc` /// `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`). /// 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`).
pub fn read_svg_for_cleaning(text: &str) -> Result<Sanitized, SvgRejection> { pub fn read_svg_for_cleaning(text: &str) -> Result<Sanitized, SvgRejection> {
let root = tree::parse_svg(text)?; let root = tree::parse_svg(text)?;
let sanitized = sanitize::sanitize_for_cleaning(root)?; let sanitized = sanitize::sanitize_for_cleaning(root)?;
+68 -2
View File
@@ -6,8 +6,10 @@
//! adds the expanded size of its target, so 256 `<use>` of a large group, nested uses or a //! adds the expanded size of its target, so 256 `<use>` of a large group, nested uses or a
//! clip path instantiated many times are all counted. The walk is iterative (reference //! clip path instantiated many times are all counted. The walk is iterative (reference
//! chains are not bounded by the depth cap) and saturating, with an early exit. //! 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.
use std::collections::HashMap; use std::collections::{HashMap, HashSet};
use super::sanitize::{local_reference_text, url_targets}; use super::sanitize::{local_reference_text, url_targets};
use super::tree::{Element, Node, SvgRejection}; use super::tree::{Element, Node, SvgRejection};
@@ -34,6 +36,35 @@ pub fn check_references(root: &Element) -> Result<u64, SvgRejection> {
expanded_size(&graph) expanded_size(&graph)
} }
/// Every reference of `root` names an id defined in it.
pub fn check_targets(root: &Element) -> Result<(), SvgRejection> {
let mut ids = HashSet::new();
collect_all_ids(root, &mut ids);
if references_resolve(root, &ids) {
Ok(())
} else {
Err(SvgRejection::DanglingReference)
}
}
fn collect_all_ids<'a>(element: &'a Element, ids: &mut HashSet<&'a str>) {
if let Some(id) = element.attr("id") {
ids.insert(id);
}
for child in element.element_children() {
collect_all_ids(child, ids);
}
}
fn references_resolve(element: &Element, ids: &HashSet<&str>) -> bool {
reference_ids(element)
.iter()
.all(|id| ids.contains(id.as_str()))
&& element
.element_children()
.all(|child| references_resolve(child, ids))
}
/// Elements in document order with their child edges, and the reference ids of each. /// Elements in document order with their child edges, and the reference ids of each.
fn flatten(root: &Element) -> (Vec<Flat>, Vec<(usize, Vec<String>)>) { fn flatten(root: &Element) -> (Vec<Flat>, Vec<(usize, Vec<String>)>) {
let mut flat = Vec::new(); let mut flat = Vec::new();
@@ -158,7 +189,8 @@ mod tests {
check("<path id=\"p\"/><use href=\"#p\"/><use href=\"#p\"/><use xlink:href=\"#p\"/>"), check("<path id=\"p\"/><use href=\"#p\"/><use href=\"#p\"/><use xlink:href=\"#p\"/>"),
Ok(8) Ok(8)
); );
// a dangling reference adds nothing; a colour is not a reference // a dangling reference adds nothing (`check_targets` refuses it); a colour is not a
// reference
assert_eq!(check("<path fill=\"url(#none)\"/>"), Ok(2)); assert_eq!(check("<path fill=\"url(#none)\"/>"), Ok(2));
assert_eq!( assert_eq!(
check("<g id=\"ff9500\"><path fill=\"#ff9500\"/></g>"), check("<g id=\"ff9500\"><path fill=\"#ff9500\"/></g>"),
@@ -166,6 +198,40 @@ mod tests {
); );
} }
fn targets(body: &str) -> Result<(), SvgRejection> {
let text = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">{body}</svg>"
);
check_targets(&parse_svg(&text).unwrap_or_else(|e| panic!("{e:?}")))
}
#[test]
fn refuses_a_reference_to_an_id_the_drawing_does_not_define() {
assert_eq!(
targets("<path id=\"p\"/><use href=\"#p\"/><use xlink:href=\"#p\"/>"),
Ok(())
);
assert_eq!(
targets("<path fill=\"url( '#g')\"/><g><linearGradient id=\"g\"/></g>"),
Ok(())
);
let dangling = Err(SvgRejection::DanglingReference);
assert_eq!(targets("<use href=\"#nope\"/>"), dangling);
assert_eq!(
targets("<g><path id=\"p\" fill=\"url(#p) url(#q)\"/></g>"),
dangling
);
assert_eq!(
targets("<linearGradient id=\"a\" xlink:href=\"#A\"/>"),
dangling
);
// a colour, an empty `url()` target and a non-local href are not references here
assert_eq!(
targets("<path fill=\"#ff9500\" stroke=\"url(#)\"/>"),
Ok(())
);
}
#[test] #[test]
fn refuses_cycles_through_use_paint_and_clip_paths() { fn refuses_cycles_through_use_paint_and_clip_paths() {
assert_eq!( assert_eq!(
+171 -3
View File
@@ -497,12 +497,34 @@ pub fn url_targets(value: &str) -> Vec<String> {
.collect() .collect()
} }
/// The value with `scope` written after the `#` of each `url(#id)` that `url_targets` reads
/// (a non-empty id), everything else kept byte for byte.
pub fn scope_url_targets(value: &str, scope: &str) -> String {
let mut out = String::with_capacity(value.len());
let mut kept_from = 0;
for at in url_openings(value) {
let next = skip_url_prefix(value, at);
let named = value[next..].strip_prefix('#').is_some_and(|rest| {
rest.starts_with(|c: char| {
c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | ':' | '-')
})
});
if named {
out.push_str(&value[kept_from..=next]);
out.push_str(scope);
kept_from = next + 1;
}
}
out.push_str(&value[kept_from..]);
out
}
/// Every `url(` in the value points inside the document (`url(#…)`). /// Every `url(` in the value points inside the document (`url(#…)`).
fn urls_are_local(value: &str) -> bool { fn urls_are_local(value: &str) -> bool {
url_openings(value).all(|at| value[skip_url_prefix(value, at)..].starts_with('#')) url_openings(value).all(|at| value[skip_url_prefix(value, at)..].starts_with('#'))
} }
/// No `(` once the `url(#` openings are taken out. /// No `(` once the `url(#` openings and the strict colour functions are taken out.
fn calls_only_local_url(value: &str) -> bool { fn calls_only_local_url(value: &str) -> bool {
let mut cut = String::with_capacity(value.len()); let mut cut = String::with_capacity(value.len());
let mut kept_from = 0; let mut kept_from = 0;
@@ -514,7 +536,99 @@ fn calls_only_local_url(value: &str) -> bool {
} }
} }
cut.push_str(&value[kept_from..]); cut.push_str(&value[kept_from..]);
!cut.contains('(') !without_colour_functions(&cut).contains('(')
}
/// The text without its strict colour functions (V1-2.2 owner decision 2026-10-29: cairo writes
/// its colours `rgb(20%, 40%, 70%)`). Only lowercase `rgb(` with three components and `rgba(`
/// with four, not glued to a longer name: numbers (`12`, `52.94`) all bare up to 255 or all
/// percentages up to 100, an alpha up to 1 or 100 %, separated by commas, CSS whitespace
/// around them. Anything else keeps its `(` and is refused as before.
fn without_colour_functions(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut from = 0;
while let Some(found) = text[from..].find("rgb") {
let at = from + found;
match colour_function_end(text, at) {
Some(end) => {
out.push_str(&text[from..at]);
from = end;
}
None => {
out.push_str(&text[from..at + 3]);
from = at + 3;
}
}
}
out.push_str(&text[from..]);
out
}
/// The end of the strict colour function starting at `at`, if there is one.
fn colour_function_end(text: &str, at: usize) -> Option<usize> {
let glued = text[..at]
.chars()
.next_back()
.is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '\\'));
let rest = &text[at..];
let (components, open) = match () {
_ if glued => return None,
_ if rest.starts_with("rgba(") => (4, 5),
_ if rest.starts_with("rgb(") => (3, 4),
_ => return None,
};
let bytes = rest.as_bytes();
let mut index = open;
let mut percentages = None;
for component in 0..components {
let (end, value, percent) = colour_number(bytes, skip_css_spaces(bytes, index))?;
let limit = match component {
3 if percent => 100.0,
3 => 1.0,
_ if *percentages.get_or_insert(percent) != percent => return None,
_ if percent => 100.0,
_ => 255.0,
};
index = skip_css_spaces(bytes, end);
let separator = if component + 1 == components {
b')'
} else {
b','
};
if value > limit || bytes.get(index) != Some(&separator) {
return None;
}
index += 1;
}
Some(at + index)
}
fn skip_css_spaces(bytes: &[u8], mut index: usize) -> usize {
while bytes
.get(index)
.is_some_and(|&b| is_css_space(char::from(b)))
{
index += 1;
}
index
}
/// `[0-9]+(\.[0-9]+)?%?` at `index`: its end, its value, whether it is a percentage.
fn colour_number(bytes: &[u8], index: usize) -> Option<(usize, f64, bool)> {
let digits = |from: usize| {
let count = bytes[from..]
.iter()
.take_while(|b| b.is_ascii_digit())
.count();
(count > 0).then_some(from + count)
};
let mut end = digits(index)?;
if bytes.get(end) == Some(&b'.') {
end = digits(end + 1)?;
}
let value: f64 = std::str::from_utf8(&bytes[index..end]).ok()?.parse().ok()?;
let percent = bytes.get(end) == Some(&b'%');
Some((end + usize::from(percent), value, percent))
} }
fn style_forbidden(value: &str) -> bool { fn style_forbidden(value: &str) -> bool {
@@ -556,7 +670,61 @@ mod tests {
// JavaScript's `\s` takes the newline, then `#` follows: local. // JavaScript's `\s` takes the newline, then `#` follows: local.
assert!(urls_are_local("url(\n#a)")); assert!(urls_are_local("url(\n#a)"));
assert!(calls_only_local_url("url(#a) url( \"#b\")")); assert!(calls_only_local_url("url(#a) url( \"#b\")"));
assert!(!calls_only_local_url("rgb(1,2,3)") && !calls_only_local_url("url(#a) blur(2)")); assert!(!calls_only_local_url("url(#a) blur(2)"));
}
#[test]
fn strict_colour_functions_only() {
for kept in [
"rgb(20%, 40%, 70%)",
"rgb(0,0,0)",
"rgb( 255 , 128.5 ,0 )",
"rgba(10, 20, 30, 0.5)",
"rgba(10%,20%,30%,50%)",
"fill:rgb(100%, 0%, 0%);stroke:url(#a);opacity:0.5",
"rgb(1,2,3) rgb(4,5,6)",
] {
assert!(calls_only_local_url(kept), "{kept}");
}
for refused in [
"RGB(1,2,3)",
"rgb (1,2,3)",
"rgb(1,2)",
"rgb(1,2,3,0.5)",
"rgba(1,2,3)",
"rgb(1%,2,3)",
"rgb(256,0,0)",
"rgb(101%,0%,0%)",
"rgba(1,2,3,1.5)",
"rgb(-1,2,3)",
"rgb(1e2,2,3)",
"rgb(.5,2,3)",
"rgb(1,2,3",
"rgb(1,2,var(--x))",
"xrgb(1,2,3)",
"-rgb(1,2,3)",
"\\72 gb(1,2,3)",
"rgb(1,2,3)expression(alert(1))",
"hsl(1,2%,3%)",
] {
assert!(!calls_only_local_url(refused), "{refused}");
}
}
#[test]
fn scoping_rewrites_exactly_the_targets_url_targets_reads() {
let value = "url(#a) URL( '#b') url(#) url(\n#c.d) #e";
let scoped = scope_url_targets(value, "fv.main.");
assert_eq!(
scoped,
"url(#fv.main.a) URL( '#fv.main.b') url(#) url(\n#fv.main.c.d) #e"
);
let targets: Vec<String> = url_targets(value)
.iter()
.map(|id| format!("fv.main.{id}"))
.collect();
assert_eq!(url_targets(&scoped), targets);
assert_eq!(scope_url_targets("none", "fv.main."), "none");
} }
#[test] #[test]
+13
View File
@@ -6,6 +6,19 @@
use super::tree::{Element, Node, SVG_NS}; use super::tree::{Element, Node, SVG_NS};
/// The prolog of a stored drawing: the XML declaration naming UTF-8, then a line feed.
pub const STORED_PROLOG: &str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
/// The one form a drawing is stored in (contract §9.2, owner decision 2026-10-29): the prolog,
/// then the tree serialised. No encoding to guess, no comment, PI, CDATA or entity, one
/// spelling of every escape: what a browser fetching the object reads is what the core read.
/// The equine drawing of the seed (`draft/assets/horse.svg`) is already in that form.
pub fn stored_form(root: &Element) -> String {
let mut out = String::from(STORED_PROLOG);
out.push_str(&serialize(root));
out
}
/// The text of `root` and its subtree. /// The text of `root` and its subtree.
pub fn serialize(root: &Element) -> String { pub fn serialize(root: &Element) -> String {
let mut out = String::with_capacity(4096); let mut out = String::with_capacity(4096);
+5
View File
@@ -104,6 +104,10 @@ pub enum SvgRejection {
TooManyUses, TooManyUses,
TooComplex, TooComplex,
ReferenceCycle, ReferenceCycle,
/// A local reference (`href="#id"`, `url(#id)`) to an id the drawing does not define:
/// inlined in a page it would resolve against another view or the page (owner decision
/// 2026-10-29).
DanglingReference,
} }
impl SvgRejection { impl SvgRejection {
@@ -118,6 +122,7 @@ impl SvgRejection {
Self::TooManyUses => "too_many_uses", Self::TooManyUses => "too_many_uses",
Self::TooComplex => "too_complex", Self::TooComplex => "too_complex",
Self::ReferenceCycle => "reference_cycle", Self::ReferenceCycle => "reference_cycle",
Self::DanglingReference => "dangling_reference",
} }
} }
} }
+5 -2
View File
@@ -8,6 +8,7 @@ use serde::Deserialize;
use url::{Host, Url}; use url::{Host, Url};
use crate::anatomy::svg::read_svg; use crate::anatomy::svg::read_svg;
use crate::anatomy::svg::serialize::stored_form;
use crate::curation::ids::sha256_hex; use crate::curation::ids::sha256_hex;
/// The private Storage bucket of the sheet drawings (`20261009100000_sheet_asset_storage`). /// The private Storage bucket of the sheet drawings (`20261009100000_sheet_asset_storage`).
@@ -155,7 +156,8 @@ pub fn parse_manifest(text: &str) -> Result<Vec<AssetEntry>, UploadError> {
} }
/// The bytes on disk are what the manifest recorded, and a drawing the product accepts: the /// The bytes on disk are what the manifest recorded, and a drawing the product accepts: the
/// core's one SVG reader keeps every element (nothing removed), as a load of the sheet would. /// core's one SVG reader keeps every element (nothing removed), as a load of the sheet would,
/// and the bytes are in the stored form the verdict requires (`serialize::stored_form`).
pub fn verify_asset(entry: &AssetEntry, bytes: &[u8]) -> Result<(), UploadError> { pub fn verify_asset(entry: &AssetEntry, bytes: &[u8]) -> Result<(), UploadError> {
let bad = |what: &str| refuse(UploadKind::Content, format!("{}: {what}", entry.file)); let bad = |what: &str| refuse(UploadKind::Content, format!("{}: {what}", entry.file));
if bytes.len() != entry.byte_size || sha256_hex(bytes) != entry.sha256 { if bytes.len() != entry.byte_size || sha256_hex(bytes) != entry.sha256 {
@@ -163,7 +165,8 @@ pub fn verify_asset(entry: &AssetEntry, bytes: &[u8]) -> Result<(), UploadError>
} }
let text = std::str::from_utf8(bytes).map_err(|_| bad("not UTF-8 text"))?; let text = std::str::from_utf8(bytes).map_err(|_| bad("not UTF-8 text"))?;
match read_svg(text) { match read_svg(text) {
Ok(read) if read.removed.is_empty() => Ok(()), Ok(read) if read.removed.is_empty() && stored_form(&read.root) == text => Ok(()),
Ok(read) if read.removed.is_empty() => Err(bad("not in the stored form")),
Ok(_) => Err(bad("the SVG reader would remove content")), Ok(_) => Err(bad("the SVG reader would remove content")),
Err(error) => Err(bad(&format!("refused by the SVG reader: {error:?}"))), Err(error) => Err(bad(&format!("refused by the SVG reader: {error:?}"))),
} }
+8 -2
View File
@@ -26,6 +26,7 @@ use super::review::DigestError;
use super::schema::{AnatomicalSheetDocument, LocalizedText}; use super::schema::{AnatomicalSheetDocument, LocalizedText};
use super::verdict::{read_document, sha256_hex}; use super::verdict::{read_document, sha256_hex};
use crate::anatomy::svg::processing_instructions; use crate::anatomy::svg::processing_instructions;
use crate::anatomy::svg::serialize::stored_form;
use crate::domain::archive::SnapshotCaps; use crate::domain::archive::SnapshotCaps;
use crate::domain::js; use crate::domain::js;
@@ -113,12 +114,17 @@ impl PreviewFailure {
/// uploads of one editing session (each one at most 2 MiB, refused above). /// uploads of one editing session (each one at most 2 MiB, refused above).
pub const MAX_HELD_DRAWINGS: usize = 16; pub const MAX_HELD_DRAWINGS: usize = 16;
/// A drawing as the verdict would read it: a processing instruction refuses it here too. /// A drawing as the verdict would read it: a processing instruction or bytes outside the
/// stored form refuse it here too.
fn preview_drawing(text: &str) -> Drawing { fn preview_drawing(text: &str) -> Drawing {
if !processing_instructions(text).is_empty() { if !processing_instructions(text).is_empty() {
return Err("processing_instruction".to_owned()); return Err("processing_instruction".to_owned());
} }
read_drawing(text) let root = read_drawing(text)?;
if stored_form(&root) != text {
return Err("not_canonical".to_owned());
}
Ok(root)
} }
struct Asset { struct Asset {
+7
View File
@@ -25,6 +25,7 @@ use super::review::{Completeness, ElementChange, ReviewGroup, change_list};
use super::schema::AnatomicalSheetDocument; use super::schema::AnatomicalSheetDocument;
use super::size::document_text_bytes; use super::size::document_text_bytes;
use super::validate::{SheetIssue, SheetIssueSeverity}; use super::validate::{SheetIssue, SheetIssueSeverity};
use crate::anatomy::svg::serialize::stored_form;
use crate::anatomy::svg::{processing_instructions, read_svg}; use crate::anatomy::svg::{processing_instructions, read_svg};
use crate::domain::js::parse_json; use crate::domain::js::parse_json;
@@ -47,6 +48,7 @@ pub mod codes {
pub const OBJECT_CONFLICT: &str = "verification.integrity.object_conflict"; pub const OBJECT_CONFLICT: &str = "verification.integrity.object_conflict";
pub const SVG_REJECTED: &str = "verification.integrity.svg_rejected"; pub const SVG_REJECTED: &str = "verification.integrity.svg_rejected";
pub const SVG_REMOVAL: &str = "verification.integrity.svg_removal"; pub const SVG_REMOVAL: &str = "verification.integrity.svg_removal";
pub const SVG_NOT_CANONICAL: &str = "verification.integrity.svg_not_canonical";
pub const FINGERPRINT: &str = "verification.integrity.fingerprint"; pub const FINGERPRINT: &str = "verification.integrity.fingerprint";
} }
@@ -101,6 +103,9 @@ pub enum DrawingResult {
SvgRejected, SvgRejected,
/// The reader would take something out of it (names in `detail`); never repaired. /// The reader would take something out of it (names in `detail`); never repaired.
SvgRemoval, SvgRemoval,
/// Read with no removal but not in the stored form (`serialize::stored_form`): bytes the
/// page's cleaning did not write (owner decision 2026-10-29).
SvgNotCanonical,
} }
/// One drawing the views reference, as the verdict found it. /// One drawing the views reference, as the verdict found it.
@@ -340,6 +345,7 @@ fn check_bytes(row: &VerdictDrawing<'_>) -> (DrawingResult, Option<String>) {
DrawingResult::SvgRejected, DrawingResult::SvgRejected,
Some("processing_instruction".to_owned()), Some("processing_instruction".to_owned()),
), ),
Ok(read) if stored_form(&read.root) != text => (DrawingResult::SvgNotCanonical, None),
Ok(_) => (DrawingResult::Ok, None), Ok(_) => (DrawingResult::Ok, None),
} }
} }
@@ -351,6 +357,7 @@ fn drawing_failures(drawings: &[CheckedDrawing]) -> Vec<&'static str> {
(DrawingResult::HashMismatch, codes::OBJECT_CONFLICT), (DrawingResult::HashMismatch, codes::OBJECT_CONFLICT),
(DrawingResult::SvgRejected, codes::SVG_REJECTED), (DrawingResult::SvgRejected, codes::SVG_REJECTED),
(DrawingResult::SvgRemoval, codes::SVG_REMOVAL), (DrawingResult::SvgRemoval, codes::SVG_REMOVAL),
(DrawingResult::SvgNotCanonical, codes::SVG_NOT_CANONICAL),
]; ];
order order
.into_iter() .into_iter()
+11 -5
View File
@@ -4,7 +4,9 @@
mod common; mod common;
use common::svg_tree::{tree_value, view_names, with_trigger_names_per_language}; use common::svg_tree::{
tree_value, view_names, with_ids_scoped_per_view, with_trigger_names_per_language,
};
use faunosteo_core::anatomy::svg::tree::parse_svg; use faunosteo_core::anatomy::svg::tree::parse_svg;
use faunosteo_core::domain::js::parse_json; use faunosteo_core::domain::js::parse_json;
use faunosteo_core::domain::sheet::{BundledSheetData, LoadedSheet}; use faunosteo_core::domain::sheet::{BundledSheetData, LoadedSheet};
@@ -33,11 +35,15 @@ fn call(sheet: &LoadedSheet, input: Value) -> Value {
serde_json::from_str(&call_with_sheet(sheet, "view.canvas", &input.to_string())).unwrap() serde_json::from_str(&call_with_sheet(sheet, "view.canvas", &input.to_string())).unwrap()
} }
/// A frozen canvas golden with the declared trigger-name change applied. /// A frozen canvas golden with the declared changes applied: trigger names, ids scoped per
fn golden(name: &str, sheet: &LoadedSheet) -> Value { /// view.
let text = common::repo_file(&format!("apps/app/tests/fixtures/goldens/r3/{name}")); fn golden(view: &str, sheet: &LoadedSheet) -> Value {
let text = common::repo_file(&format!(
"apps/app/tests/fixtures/goldens/r3/canvas.{view}.json"
));
let mut frozen: Value = serde_json::from_str(&text).unwrap(); let mut frozen: Value = serde_json::from_str(&text).unwrap();
with_trigger_names_per_language(&mut frozen, &view_names(&sheet.document)); with_trigger_names_per_language(&mut frozen, &view_names(&sheet.document));
with_ids_scoped_per_view(&mut frozen, view);
frozen frozen
} }
@@ -50,7 +56,7 @@ fn each_view_answers_the_frozen_canvas() {
let svg = out["value"]["svg"].as_str().unwrap(); let svg = out["value"]["svg"].as_str().unwrap();
assert_eq!( assert_eq!(
tree_value(&parse_svg(svg).unwrap()), tree_value(&parse_svg(svg).unwrap()),
golden(&format!("canvas.{view}.json"), &sheet), golden(view, &sheet),
"{view}" "{view}"
); );
} }
+11 -9
View File
@@ -11,7 +11,9 @@ mod common;
use std::collections::HashSet; use std::collections::HashSet;
use common::svg_tree::{reread, tree_value, view_names, with_trigger_names_per_language}; 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::{asset_id_of_view, compose_canvas, compose_highlight};
use faunosteo_core::anatomy::layer::render_layer; use faunosteo_core::anatomy::layer::render_layer;
use faunosteo_core::anatomy::svg::{Element, read_svg}; use faunosteo_core::anatomy::svg::{Element, read_svg};
@@ -96,11 +98,15 @@ fn every_highlighted_view_equals_the_engine_tree() {
} }
} }
/// A frozen canvas golden with the declared trigger-name change applied (draft views). /// A frozen canvas golden with the declared changes applied: trigger names (draft views) and
fn canvas_golden(name: &str) -> Value { /// ids scoped per view.
let text = common::repo_file(&format!("apps/app/tests/fixtures/goldens/r3/{name}")); fn canvas_golden(view: &str) -> Value {
let text = common::repo_file(&format!(
"apps/app/tests/fixtures/goldens/r3/canvas.{view}.json"
));
let mut frozen: Value = serde_json::from_str(&text).unwrap(); let mut frozen: Value = serde_json::from_str(&text).unwrap();
with_trigger_names_per_language(&mut frozen, &view_names(&draft())); with_trigger_names_per_language(&mut frozen, &view_names(&draft()));
with_ids_scoped_per_view(&mut frozen, view);
frozen frozen
} }
@@ -110,11 +116,7 @@ fn every_canvas_equals_the_frozen_tree_and_every_state_set_its_layer() {
let draft = draft(); let draft = draft();
for view in ["main", "head"] { for view in ["main", "head"] {
let canvas = compose_canvas(&draft, view, &horse).unwrap(); let canvas = compose_canvas(&draft, view, &horse).unwrap();
assert_eq!( assert_eq!(reread(&canvas), canvas_golden(view), "{view}");
reread(&canvas),
canvas_golden(&format!("canvas.{view}.json")),
"{view}"
);
let layers: Value = serde_json::from_str(&common::repo_file(&format!( let layers: Value = serde_json::from_str(&common::repo_file(&format!(
"apps/app/tests/fixtures/goldens/r3/canvas.{view}.layers.json" "apps/app/tests/fixtures/goldens/r3/canvas.{view}.layers.json"
))) )))
+24
View File
@@ -67,6 +67,30 @@ pub fn with_trigger_names_per_language(tree: &mut Value, views: &[(String, Strin
} }
} }
/// Owner decision 2026-10-29 (V1-2.2): the canvas, inlined in the page, scopes the drawing's
/// ids and the references to them to its view (`fv.<view>.<id>`). Applied to a frozen canvas
/// tree before comparing, written apart from the core's rewrite: every `id`, every `#id`
/// href and every plain `url(#` (the only spelling of the product drawing).
pub fn with_ids_scoped_per_view(tree: &mut Value, view_id: &str) {
let scope = format!("fv.{view_id}.");
if let Some(attrs) = tree.get_mut("attrs").and_then(Value::as_object_mut) {
for (name, value) in attrs.iter_mut() {
let Some(text) = value.as_str() else { continue };
let scoped = match name.as_str() {
"id" => format!("{scope}{text}"),
"href" | "xlink:href" if text.starts_with('#') => format!("#{scope}{}", &text[1..]),
_ => text.replace("url(#", &format!("url(#{scope}")),
};
*value = Value::String(scoped);
}
}
if let Some(children) = tree.get_mut("children").and_then(Value::as_array_mut) {
for child in children {
with_ids_scoped_per_view(child, view_id);
}
}
}
/// (view id, FR name, EN name) of a document, for `with_trigger_names_per_language`. /// (view id, FR name, EN name) of a document, for `with_trigger_names_per_language`.
pub fn view_names( pub fn view_names(
document: &faunosteo_core::domain::sheet::AnatomicalSheetDocument, document: &faunosteo_core::domain::sheet::AnatomicalSheetDocument,
+8 -1
View File
@@ -10,7 +10,8 @@ use faunosteo_core::curation::upload::{
const SEED: &str = "../../supabase/seed/anatomical-sheets/equine/draft"; const SEED: &str = "../../supabase/seed/anatomical-sheets/equine/draft";
const UUID: &str = "7f767f74-3b36-51a7-8465-52dd7e2ead4a"; const UUID: &str = "7f767f74-3b36-51a7-8465-52dd7e2ead4a";
const SVG: &[u8] = b"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 10 10\"><g/></svg>"; /// A drawing in its stored form (`serialize::stored_form`), as the verdict requires it.
const SVG: &[u8] = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 10 10\"><g/></svg>";
fn entry_for(bytes: &[u8]) -> AssetEntry { fn entry_for(bytes: &[u8]) -> AssetEntry {
AssetEntry { AssetEntry {
@@ -118,6 +119,12 @@ fn only_bytes_that_match_and_that_the_svg_reader_keeps_whole_are_uploaded() {
kind(verify_asset(&entry_for(not_svg), not_svg)), kind(verify_asset(&entry_for(not_svg), not_svg)),
UploadKind::Content UploadKind::Content
); );
// Read with no removal but outside the stored form: the verdict would refuse it.
let loose = &SVG[SVG.iter().position(|&b| b == b'\n').unwrap() + 1..];
assert_eq!(
kind(verify_asset(&entry_for(loose), loose)),
UploadKind::Content
);
let binary: &[u8] = &[0xff, 0xfe, 0x00]; let binary: &[u8] = &[0xff, 0xfe, 0x00];
assert_eq!( assert_eq!(
kind(verify_asset(&entry_for(binary), binary)), kind(verify_asset(&entry_for(binary), binary)),
+15 -5
View File
@@ -6,19 +6,29 @@ None is edited by hand.
| File | Tool | How | Expected | | File | Tool | How | Expected |
|---|---|---|---| |---|---|---|---|
| `cairo-1.18.4-pycairo-1.27.0-shapes.svg` | cairo 1.18.4 through pycairo 1.27.0 | `generate.sh`: curves, gradient, dash, clip, alpha, text as glyph paths | cleanable: its colours are written `rgb(20%, 40%, 70%)`, a function the allowlist takes out of presentation attributes (`stop@stop-color`, `path@stroke`, `path@fill`, `g@fill`), so the cleaned drawing keeps its shapes and loses its colours | | `cairo-1.18.4-pycairo-1.27.0-shapes.svg` | cairo 1.18.4 through pycairo 1.27.0 | `generate.sh`: curves, gradient, dash, clip, alpha, text as glyph paths | read with no removal: its colours are written `rgb(20%, 40%, 70%)`, the strict numeric colour function the reader keeps since the owner's decision of 2026-10-29 (before it, the four colours were removed) |
| `cairo-1.18.4-pycairo-1.27.0-raster.svg` | same | `generate.sh`: an 8 × 8 image surface painted | refused, `svg_active_content` (an embedded raster `<image>`) | | `cairo-1.18.4-pycairo-1.27.0-raster.svg` | same | `generate.sh`: an 8 × 8 image surface painted | refused, `svg_active_content` (an embedded raster `<image>`) |
| `inkscape-1.4.3-inkscape-svg.svg` | Inkscape 1.4.3 (0d15f75042, 2025-12-25) | `generate-inkscape.sh`: `inkscape-source.svg` opened and exported as Inkscape SVG (`--export-type=svg`) | cleanable: `sodipodi:namedview`, the editor namespaces, `sodipodi:docname`, `xmlns:svg` and the `text` element removed and named; shapes, gradient, clip path, references and colours kept |
| `inkscape-1.4.3-plain-svg.svg` | same | `generate-inkscape.sh`: Plain SVG (`--export-plain-svg`) | cleanable: `xmlns:svg` and `text` removed |
| `inkscape-1.4.3-paths.svg` | same | `generate-inkscape.sh`: Plain SVG, every object to a path, text to outlines (`--actions='select-all:all;object-to-path'`, `--export-text-to-path`) | cleanable: `xmlns:svg` and `path@aria-label` removed; the outlined text stays as paths |
| `imagemagick-7.1.2-18-draw.svg` | ImageMagick 7.1.2-18 Q16 | `generate.sh`: `-draw` circle, rectangle, polyline | read with no removal | | `imagemagick-7.1.2-18-draw.svg` | ImageMagick 7.1.2-18 Q16 | `generate.sh`: `-draw` circle, rectangle, polyline | read with no removal |
| `imagemagick-7.1.2-18-mvg.svg` | same | `generate.sh`: an MVG file (its style settings land as bare text between elements, which the reader drops) | read with no removal | | `imagemagick-7.1.2-18-mvg.svg` | same | `generate.sh`: an MVG file (its style settings land as bare text between elements, which the reader drops) | read with no removal |
`bash generate.sh` rewrites them from the tools installed here (no network). `bash generate.sh` rewrites the cairo and ImageMagick files from the tools installed here (no
network). `inkscape-source.svg` is not an export: a small drawing written by hand that Inkscape
opens; `bash generate-inkscape.sh <inkscape binary>` writes the three Inkscape files from it.
Inkscape is not installed on the development machine: on 2026-10-29 (owner go) the Ubuntu
archive package `inkscape_1.4.3-0ubuntu2_amd64.deb` (sha256 `24a2e922…918326e`, equal to the
archive index) and its missing libraries were downloaded with `apt-get download` into the
session's scratch folder, unpacked with `dpkg-deb -x` and run from there (no install, no
sudo); inkscape.org, where the AppImage lives, answered 504 and timed out that day.
## Editor exports, supplied by the owner (`owner/`) ## Editor exports, supplied by the owner (`owner/`)
The editors an administrator actually uses (Inkscape, Illustrator, Figma, Affinity) are not Illustrator, Figma and Affinity are not available on the development machine (Inkscape is
installed on the development machine; the owner exports a small drawing from each and puts covered above by a real 1.4.3 export); the owner exports a small drawing from each and puts
the files in `owner/`, named `<tool>-<version>-<what>.svg` (for example the files in `owner/`, named `<tool>-<version>-<what>.svg` (for example
`inkscape-1.4.2-plain-svg.svg`, `illustrator-29.3-export-as.svg`). The suite reads every file `illustrator-29.3-export-as.svg`, `figma-125.8-export.svg`). The suite reads every file
there: each must be refused (with a closed reason) or cleaned into a drawing that reads back there: each must be refused (with a closed reason) or cleaned into a drawing that reads back
with no removal, and a file whose name contains `-active-` must be refused for active content. with no removal, and a file whose name contains `-active-` must be refused for active content.
Until files arrive, that test runs on an empty folder and the report of V1-2.2 says so. Until files arrive, that test runs on an empty folder and the report of V1-2.2 says so.
@@ -0,0 +1,21 @@
#!/usr/bin/env bash
# Writes the Inkscape exports of `tests/svg_clean.rs` (V1-2.2, contract §9.2, owner decision
# 2026-10-29) from `inkscape-source.svg`, a small drawing written by hand that Inkscape opens
# and exports; the output files are Inkscape's own serialisation. Run from this folder with
# the Inkscape binary as the only argument: bash generate-inkscape.sh /path/to/inkscape
# (no network; the version goes in the file names).
set -euo pipefail
inkscape="$1"
version=$("$inkscape" --version 2>/dev/null | sed -n 's/^Inkscape \([0-9.]*\).*/\1/p')
prefix="inkscape-${version}"
# Inkscape SVG (the editor's own format: sodipodi / inkscape namespaces, metadata).
"$inkscape" inkscape-source.svg --export-type=svg --export-filename="${prefix}-inkscape-svg.svg"
# Plain SVG (« Enregistrer une copie… » › SVG simple).
"$inkscape" inkscape-source.svg --export-plain-svg --export-filename="${prefix}-plain-svg.svg"
# Plain SVG with every object converted to a path and the text to outlines, as a drawing is
# usually prepared before it is handed over.
"$inkscape" inkscape-source.svg --export-plain-svg --export-text-to-path \
--actions='select-all:all;object-to-path' --export-filename="${prefix}-paths.svg"
ls -1 "${prefix}"-*.svg
@@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
width="200"
height="150"
viewBox="0 0 200 150"
version="1.1"
id="svg3"
sodipodi:docname="inkscape-source.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<sodipodi:namedview
id="namedview3"
pagecolor="#ffffff"
bordercolor="#000000"
borderopacity="0.25"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1" />
<defs
id="defs2">
<linearGradient
id="coat"
x1="0"
y1="0"
x2="1"
y2="0">
<stop
offset="0"
stop-color="#8a5a3c"
id="stop1" />
<stop
offset="1"
stop-color="#d9b48f"
stop-opacity="0.8"
id="stop2" />
</linearGradient>
<clipPath
id="frame">
<rect
x="10"
y="10"
width="180"
height="130"
id="rect2" />
</clipPath>
</defs>
<g
id="body"
clip-path="url(#frame)">
<path
d="M20 110 C40 40 150 30 180 100 L170 120 L30 125 Z"
fill="url(#coat)"
stroke="#333"
stroke-width="2"
stroke-dasharray="6 3"
id="path2" />
<ellipse
cx="160"
cy="55"
rx="18"
ry="12"
fill="#c49a6c"
id="ellipse2" />
<rect
x="60"
y="60"
width="40"
height="20"
rx="4"
fill="rgb(51, 102, 179)"
fill-opacity="0.5"
id="rect3" />
</g>
<text
x="70"
y="140"
font-family="DejaVu Sans"
font-size="12"
id="text3">Garrot</text>
</svg>

After

Width:  |  Height:  |  Size: 1.8 KiB

@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
width="200"
height="150"
viewBox="0 0 200 150"
version="1.1"
id="svg3"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs2">
<linearGradient
id="coat"
x1="0"
y1="0"
x2="1"
y2="0">
<stop
offset="0"
stop-color="#8a5a3c"
id="stop1" />
<stop
offset="1"
stop-color="#d9b48f"
stop-opacity="0.8"
id="stop2" />
</linearGradient>
<clipPath
id="frame">
<rect
x="10"
y="10"
width="180"
height="130"
id="rect2" />
</clipPath>
</defs>
<g
id="body"
clip-path="url(#frame)">
<path
d="M20 110 C40 40 150 30 180 100 L170 120 L30 125 Z"
fill="url(#coat)"
stroke="#333"
stroke-width="2"
stroke-dasharray="6 3"
id="path2" />
<path
id="ellipse2"
style="fill:#c49a6c"
d="M 178,55 A 18,12 0 0 1 160,67 18,12 0 0 1 142,55 18,12 0 0 1 160,43 18,12 0 0 1 178,55 Z" />
<path
id="rect3"
style="fill:#3366b3;fill-opacity:0.5"
d="m 64,60 h 32 c 2.216,0 4,1.784 4,4 v 12 c 0,2.216 -1.784,4 -4,4 H 64 c -2.216,0 -4,-1.784 -4,-4 V 64 c 0,-2.216 1.784,-4 4,-4 z" />
</g>
<path
d="m 77.142578,138.75195 v -2.34961 h -1.933594 v -0.97265 h 3.105469 v 3.75586 q -0.685547,0.48632 -1.511719,0.73828 -0.826172,0.24609 -1.763672,0.24609 -2.050781,0 -3.210937,-1.19531 -1.154297,-1.20117 -1.154297,-3.33984 0,-2.14454 1.154297,-3.33985 1.160156,-1.20117 3.210937,-1.20117 0.855469,0 1.623047,0.21094 0.773438,0.21093 1.423828,0.62109 v 1.25977 q -0.65625,-0.55664 -1.394531,-0.83789 -0.738281,-0.28125 -1.552734,-0.28125 -1.605469,0 -2.414063,0.89648 -0.802734,0.89648 -0.802734,2.67188 0,1.76953 0.802734,2.66601 0.808594,0.89649 2.414063,0.89649 0.626953,0 1.11914,-0.10547 0.492188,-0.11133 0.884766,-0.33985 z m 6.269531,-2.05078 q -1.30664,0 -1.810547,0.29883 -0.503906,0.29883 -0.503906,1.01953 0,0.57422 0.375,0.91406 0.38086,0.33399 1.03125,0.33399 0.896485,0 1.435547,-0.63281 0.544922,-0.63868 0.544922,-1.69336 v -0.24024 z M 85.5625,136.25586 V 140 h -1.078125 v -0.99609 q -0.369141,0.59765 -0.919922,0.88476 -0.550781,0.28125 -1.347656,0.28125 -1.007813,0 -1.605469,-0.5625 -0.591797,-0.56836 -0.591797,-1.51758 0,-1.10742 0.738281,-1.66992 0.744141,-0.5625 2.214844,-0.5625 h 1.511719 v -0.10547 q 0,-0.74414 -0.492188,-1.14843 -0.486328,-0.41016 -1.371093,-0.41016 -0.5625,0 -1.095703,0.13476 -0.533204,0.13477 -1.025391,0.4043 v -0.99609 q 0.591797,-0.22852 1.148437,-0.33985 0.556641,-0.11718 1.083985,-0.11718 1.423828,0 2.126953,0.73828 0.703125,0.73828 0.703125,2.23828 z m 6.023437,-1.81055 q -0.18164,-0.10547 -0.398437,-0.15234 -0.210938,-0.0527 -0.46875,-0.0527 -0.914063,0 -1.40625,0.59766 -0.486328,0.5918 -0.486328,1.70508 V 140 h -1.083985 v -6.5625 h 1.083985 v 1.01953 q 0.339844,-0.59766 0.884765,-0.88476 0.544922,-0.29297 1.324219,-0.29297 0.111328,0 0.246094,0.0176 0.134766,0.0117 0.298828,0.041 z m 4.722657,0 q -0.181641,-0.10547 -0.398438,-0.15234 -0.210937,-0.0527 -0.46875,-0.0527 -0.914062,0 -1.40625,0.59766 -0.486328,0.5918 -0.486328,1.70508 V 140 h -1.083984 v -6.5625 h 1.083984 v 1.01953 q 0.339844,-0.59766 0.884766,-0.88476 0.544922,-0.29297 1.324218,-0.29297 0.111329,0 0.246094,0.0176 0.134766,0.0117 0.298828,0.041 z m 3.410156,-0.25195 q -0.867188,0 -1.371094,0.67969 -0.503906,0.67382 -0.503906,1.85156 0,1.17773 0.498047,1.85742 0.503906,0.67383 1.376953,0.67383 0.86133,0 1.36523,-0.67969 0.50391,-0.67969 0.50391,-1.85156 0,-1.16602 -0.50391,-1.8457 -0.5039,-0.68555 -1.36523,-0.68555 z m 0,-0.91406 q 1.40625,0 2.20898,0.91406 0.80274,0.91406 0.80274,2.53125 0,1.61133 -0.80274,2.53125 -0.80273,0.91406 -2.20898,0.91406 -1.412109,0 -2.214844,-0.91406 -0.796875,-0.91992 -0.796875,-2.53125 0,-1.61719 0.796875,-2.53125 0.802735,-0.91406 2.214844,-0.91406 z m 5.86523,-1.70508 v 1.86328 h 2.22071 v 0.83789 h -2.22071 v 3.5625 q 0,0.80273 0.2168,1.03125 0.22266,0.22852 0.89649,0.22852 h 1.10742 V 140 h -1.10742 q -1.24805,0 -1.72266,-0.46289 Q 104.5,139.06836 104.5,137.83789 v -3.5625 h -0.79102 V 133.4375 H 104.5 v -1.86328 z"
id="text3"
style="font-size:12px;font-family:'DejaVu Sans'"
aria-label="Garrot" />
</svg>

After

Width:  |  Height:  |  Size: 4.3 KiB

@@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
width="200"
height="150"
viewBox="0 0 200 150"
version="1.1"
id="svg3"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs2">
<linearGradient
id="coat"
x1="0"
y1="0"
x2="1"
y2="0">
<stop
offset="0"
stop-color="#8a5a3c"
id="stop1" />
<stop
offset="1"
stop-color="#d9b48f"
stop-opacity="0.8"
id="stop2" />
</linearGradient>
<clipPath
id="frame">
<rect
x="10"
y="10"
width="180"
height="130"
id="rect2" />
</clipPath>
</defs>
<g
id="body"
clip-path="url(#frame)">
<path
d="M20 110 C40 40 150 30 180 100 L170 120 L30 125 Z"
fill="url(#coat)"
stroke="#333"
stroke-width="2"
stroke-dasharray="6 3"
id="path2" />
<ellipse
cx="160"
cy="55"
rx="18"
ry="12"
fill="#c49a6c"
id="ellipse2" />
<rect
x="60"
y="60"
width="40"
height="20"
rx="4"
fill="rgb(51, 102, 179)"
fill-opacity="0.5"
id="rect3" />
</g>
<text
x="70"
y="140"
font-family="DejaVu Sans"
font-size="12"
id="text3">Garrot</text>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

@@ -0,0 +1,15 @@
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="150" viewBox="0 0 200 150">
<defs>
<linearGradient id="coat" x1="0" y1="0" x2="1" y2="0">
<stop offset="0" stop-color="#8a5a3c"/>
<stop offset="1" stop-color="#d9b48f" stop-opacity="0.8"/>
</linearGradient>
<clipPath id="frame"><rect x="10" y="10" width="180" height="130"/></clipPath>
</defs>
<g id="body" clip-path="url(#frame)">
<path d="M20 110 C40 40 150 30 180 100 L170 120 L30 125 Z" fill="url(#coat)" stroke="#333" stroke-width="2" stroke-dasharray="6 3"/>
<ellipse cx="160" cy="55" rx="18" ry="12" fill="#c49a6c"/>
<rect x="60" y="60" width="40" height="20" rx="4" fill="rgb(51, 102, 179)" fill-opacity="0.5"/>
</g>
<text x="70" y="140" font-family="DejaVu Sans" font-size="12">Garrot</text>
</svg>

After

Width:  |  Height:  |  Size: 814 B

+30
View File
@@ -436,3 +436,33 @@ fn a_replaced_asset_releases_its_parse_and_a_pi_drawing_shows_rejected() {
Some("processing_instruction") Some("processing_instruction")
); );
} }
/// Owner decision 2026-10-29: a stored drawing outside the stored form shows rejected
/// (`not_canonical`), as the verdict refuses it; the equine drawing is in that form.
#[test]
fn a_drawing_outside_the_stored_form_shows_rejected() {
let asset = "33333333-0000-4000-8000-000000000002";
let mut doc = parse_json(&document_text()).unwrap();
doc["views"][0]["svg_asset_id"] = json!(asset);
let horse_text = String::from_utf8(horse()).unwrap();
let loose = horse_text.split_once('\n').unwrap().1.as_bytes().to_vec();
let preview = PreviewSheet::load(
input(PreviewStatus::Draft, doc.to_string(), None),
vec![PreviewDrawing {
asset_id: asset.into(),
sha256: faunosteo_core::domain::sheet::verdict::sha256_hex(&loose),
bytes: loose,
}],
)
.unwrap();
let state = state(&preview);
assert_eq!(state.drawings[0].state, PreviewDrawingStatus::Rejected);
assert_eq!(state.drawings[0].detail.as_deref(), Some("not_canonical"));
let input = json!({ "viewId": "main" }).to_string();
let refused = canvas(call_with_preview(&preview, "view.canvas", &input));
assert_eq!(refused["detail"], json!("not_canonical"));
assert_eq!(
self::state(&published()).drawings[0].state,
PreviewDrawingStatus::Ok
);
}
+42 -2
View File
@@ -15,8 +15,11 @@ use faunosteo_core::domain::sheet::verdict::{
use serde_json::{Value, json}; use serde_json::{Value, json};
const ASSET: &str = "11111111-2222-4333-8444-555555555555"; const ASSET: &str = "11111111-2222-4333-8444-555555555555";
const DRAWING: &str = /// A drawing in its stored form (`serialize::stored_form`), as the page's cleaning uploads it.
r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><path d="M0 0L5 5"/></svg>"#; const DRAWING: &str = concat!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n",
r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><path d="M0 0L5 5"/></svg>"#
);
const SEED: &str = "supabase/seed/anatomical-sheets/equine/draft"; const SEED: &str = "supabase/seed/anatomical-sheets/equine/draft";
const HORSE_ID: &str = "7f767f74-3b36-51a7-8465-52dd7e2ead4a"; const HORSE_ID: &str = "7f767f74-3b36-51a7-8465-52dd7e2ead4a";
@@ -281,6 +284,43 @@ fn each_drawing_fault_fails_with_its_code() {
} }
} }
/// Owner decision 2026-10-29: a stored drawing must be in the stored form the page's cleaning
/// writes; bytes read with no removal but written otherwise (original export bytes, another
/// declared encoding, an HTML-only comment form, another quoting) fail, never repaired.
#[test]
fn a_drawing_outside_the_stored_form_fails() {
let doc = document();
let body = DRAWING.split_once('\n').unwrap().1;
let export = std::fs::read(common::repo_path(
"crates/core/tests/fixtures/svg/exports/imagemagick-7.1.2-18-draw.svg",
))
.unwrap();
let mut doc_on_export = doc.clone();
doc_on_export["views"][0]["view_box"] = Value::Null;
for bytes in [
body.as_bytes().to_vec(),
format!("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n{body}").into_bytes(),
DRAWING.replace("<path", "<!-->--><path").into_bytes(),
DRAWING
.replace("viewBox=\"0 0 10 10\"", "viewBox='0 0 10 10'")
.into_bytes(),
format!("{DRAWING}\n").into_bytes(),
export,
] {
let v = verdict_of(&doc, vec![row(&bytes)]);
assert_eq!(
failures(&v),
[codes::SVG_NOT_CANONICAL],
"{}",
String::from_utf8_lossy(&bytes)
);
assert_eq!(v.drawings[0].result, DrawingResult::SvgNotCanonical);
assert!(v.fingerprint.is_some());
}
let v = verdict_of(&doc, vec![row(DRAWING.as_bytes())]);
assert_eq!(v.drawings[0].result, DrawingResult::Ok);
}
/// `count` annotations drawn in the main view, all in zone `z1`. /// `count` annotations drawn in the main view, all in zone `z1`.
fn with_annotations(count: usize) -> Value { fn with_annotations(count: usize) -> Value {
let mut doc = document(); let mut doc = document();
+230 -38
View File
@@ -2,14 +2,16 @@
//! corpus of R3 answers as the table of §9.2 says, file by file; the committed vector-tool //! corpus of R3 answers as the table of §9.2 says, file by file; the committed vector-tool
//! exports and the product drawing read clean or are refused for their raster; the owner's //! exports and the product drawing read clean or are refused for their raster; the owner's
//! editor exports (`fixtures/svg/exports/owner`) are read when present; and a property test //! editor exports (`fixtures/svg/exports/owner`) are read when present; and a property test
//! over generated drawings proves the fixpoint: a cleaned text reads back with no removal and //! over generated drawings proves the fixpoint: a stored text reads back with no removal and
//! cleans to itself. The strict reader of stored drawings is unchanged. //! gives itself again. Every accepted file is uploaded in the stored form (owner decision
//! 2026-10-29), never as its original bytes. The strict reader of stored drawings is unchanged.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)] #![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common; mod common;
use faunosteo_core::anatomy::svg::clean::{CleaningOutcome, SvgCleaning, clean_svg}; use faunosteo_core::anatomy::svg::clean::{CleaningOutcome, SvgCleaning, clean_svg};
use faunosteo_core::anatomy::svg::read_svg; use faunosteo_core::anatomy::svg::read_svg;
use faunosteo_core::anatomy::svg::serialize::{STORED_PROLOG, serialize, stored_form};
use faunosteo_core::domain::sheet::verdict::sha256_hex; use faunosteo_core::domain::sheet::verdict::sha256_hex;
const FIXTURES: &str = "crates/core/tests/fixtures/svg"; const FIXTURES: &str = "crates/core/tests/fixtures/svg";
@@ -62,6 +64,12 @@ fn the_hostile_corpus_answers_as_the_contract_table() {
("use-mutual-cycle.svg", Rejected, Some("reference_cycle")), ("use-mutual-cycle.svg", Rejected, Some("reference_cycle")),
("use-self-cycle.svg", Rejected, Some("reference_cycle")), ("use-self-cycle.svg", Rejected, Some("reference_cycle")),
("wrong-root-namespace.svg", Rejected, Some("not_svg")), ("wrong-root-namespace.svg", Rejected, Some("not_svg")),
// A reference to an id the drawing does not define (owner decision 2026-10-29).
(
"dangling-references.svg",
Rejected,
Some("dangling_reference"),
),
// Other removals: cleaning offered. // Other removals: cleaning offered.
("id-grammar.svg", Cleanable, None), ("id-grammar.svg", Cleanable, None),
("long-title.svg", Cleanable, None), ("long-title.svg", Cleanable, None),
@@ -73,7 +81,6 @@ fn the_hostile_corpus_answers_as_the_contract_table() {
("xlink-other-prefix.svg", Cleanable, None), ("xlink-other-prefix.svg", Cleanable, None),
("xlink-prefix-rebound.svg", Cleanable, None), ("xlink-prefix-rebound.svg", Cleanable, None),
// Nothing removed (comments, stray text and clamped values are no removal). // Nothing removed (comments, stray text and clamped values are no removal).
("dangling-references.svg", Clean, None),
("duplicate-ids.svg", Clean, None), ("duplicate-ids.svg", Clean, None),
("osteo-halo-id.svg", Clean, None), ("osteo-halo-id.svg", Clean, None),
("root-without-namespace.svg", Clean, None), ("root-without-namespace.svg", Clean, None),
@@ -93,11 +100,11 @@ fn the_hostile_corpus_answers_as_the_contract_table() {
"{file}" "{file}"
), ),
Cleanable => assert!( Cleanable => assert!(
cleaning.active.is_empty() && cleaning.cleaned.is_some(), cleaning.active.is_empty() && cleaning.stored.is_some(),
"{file}" "{file}"
), ),
Clean => assert!( Clean => assert!(
cleaning.removed.is_empty() && cleaning.cleaned.is_none(), cleaning.removed.is_empty() && cleaning.stored.is_some(),
"{file}" "{file}"
), ),
} }
@@ -109,8 +116,8 @@ fn active_names_are_listed_and_ordinary_removals_are_not() {
let css = clean_svg(&fixture("hostile/css.svg")); let css = clean_svg(&fixture("hostile/css.svg"));
assert_eq!( assert_eq!(
(css.removed.len(), css.active.len()), (css.removed.len(), css.active.len()),
(6, 4), (5, 4),
"rgb() and attr() alone would be cleaned" "attr() alone would be cleaned; the strict rgb() is kept"
); );
let events = clean_svg(&fixture("hostile/events.svg")); let events = clean_svg(&fixture("hostile/events.svg"));
assert_eq!( assert_eq!(
@@ -230,7 +237,7 @@ fn a_plain_style_sheet_is_cleaned_and_named() {
let cleaning = clean_svg(styled); let cleaning = clean_svg(styled);
assert_eq!(outcome(&cleaning), (Cleanable, None)); assert_eq!(outcome(&cleaning), (Cleanable, None));
assert!(cleaning.style_removed); assert!(cleaning.style_removed);
let cleaned = cleaning.cleaned.as_deref().unwrap(); let cleaned = cleaning.stored.as_deref().unwrap();
assert!(!cleaned.contains("<style") && cleaned.contains("class=\"st0\"")); assert!(!cleaned.contains("<style") && cleaned.contains("class=\"st0\""));
assert_eq!( assert_eq!(
cleaning.sha256.as_deref(), cleaning.sha256.as_deref(),
@@ -247,20 +254,56 @@ fn a_plain_style_sheet_is_cleaned_and_named() {
} }
} }
/// Owner decision 2026-10-29: the bytes uploaded are the stored form, never the original. The
/// seed's equine drawing already is in that form, so its sha256 does not move; another clean
/// file loses its declaration, comments, CDATA, entity spellings and quoting, nothing else.
#[test] #[test]
fn a_clean_file_is_uploaded_as_it_is_and_shown_as_read() { fn a_clean_file_is_uploaded_in_its_stored_form_and_shown_as_read() {
let horse = std::fs::read(common::repo_path( let horse = std::fs::read(common::repo_path(
"supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg", "supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg",
)) ))
.unwrap(); .unwrap();
let cleaning = clean_svg(&horse); let cleaning = clean_svg(&horse);
assert_eq!(outcome(&cleaning), (Clean, None)); assert_eq!(outcome(&cleaning), (Clean, None));
assert_eq!(
cleaning.stored.as_deref().map(str::as_bytes),
Some(&horse[..])
);
assert_eq!( assert_eq!(
cleaning.sha256.as_deref(), cleaning.sha256.as_deref(),
Some("0ea5202fa3b95bac167b87c12ee969ab0272e085b60c2d34dbca6202c5f08541") Some("0ea5202fa3b95bac167b87c12ee969ab0272e085b60c2d34dbca6202c5f08541")
); );
assert_eq!(cleaning.byte_size, Some(132_997)); assert_eq!(cleaning.byte_size, Some(132_997));
assert!(cleaning.preview.unwrap().starts_with("<svg")); assert!(cleaning.preview.unwrap().starts_with("<svg"));
let loose = "<?xml version='1.0' encoding='ISO-8859-1' standalone='no'?>\n<!-- editor -->\
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 4'><!-->--><title><![CDATA[a < b]]> &#233;</title>\
<path d='M0 0h1' fill='#ABC'/></svg>";
let cleaning = clean_svg(loose.as_bytes());
assert_eq!(outcome(&cleaning), (Clean, None));
let stored = cleaning.stored.as_deref().unwrap();
assert_eq!(
stored,
format!(
"{STORED_PROLOG}<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 4 4\"><title>a &lt; b é</title>\
<path d=\"M0 0h1\" fill=\"#ABC\"/></svg>"
)
);
assert_eq!(
cleaning.sha256.as_deref(),
Some(sha256_hex(stored.as_bytes()).as_str())
);
assert_eq!(cleaning.byte_size, Some(stored.len() as u64));
assert_eq!(
cleaning.preview.as_deref(),
stored.strip_prefix(STORED_PROLOG)
);
assert_fixpoint(stored);
assert_eq!(
serialize(&read_svg(stored).unwrap().root),
cleaning.preview.unwrap()
);
assert_eq!( assert_eq!(
outcome(&clean_svg(b"\xff\xfe<svg/>")), outcome(&clean_svg(b"\xff\xfe<svg/>")),
(Rejected, Some("malformed")) (Rejected, Some("malformed"))
@@ -274,7 +317,7 @@ fn a_clean_file_is_uploaded_as_it_is_and_shown_as_read() {
#[test] #[test]
fn the_vector_tool_exports_are_read_or_refused_for_their_raster() { fn the_vector_tool_exports_are_read_or_refused_for_their_raster() {
let table = [ let table = [
("cairo-1.18.4-pycairo-1.27.0-shapes.svg", Cleanable, None), ("cairo-1.18.4-pycairo-1.27.0-shapes.svg", Clean, None),
( (
"cairo-1.18.4-pycairo-1.27.0-raster.svg", "cairo-1.18.4-pycairo-1.27.0-raster.svg",
Rejected, Rejected,
@@ -292,20 +335,161 @@ fn the_vector_tool_exports_are_read_or_refused_for_their_raster() {
} }
let raster = clean_svg(&fixture("exports/cairo-1.18.4-pycairo-1.27.0-raster.svg")); let raster = clean_svg(&fixture("exports/cairo-1.18.4-pycairo-1.27.0-raster.svg"));
assert_eq!(raster.active, ["image"]); assert_eq!(raster.active, ["image"]);
// cairo writes its colours as `rgb(20%, 40%, 70%)`: the allowlist takes any function out }
// of a presentation attribute, so the cleaned drawing keeps its shapes, not its colours.
let shapes = clean_svg(&fixture("exports/cairo-1.18.4-pycairo-1.27.0-shapes.svg")); /// Real Inkscape 1.4.3 exports (owner go 2026-10-29; `exports/generate-inkscape.sh`): its
assert_eq!( /// editor metadata and namespaces and the `text` it keeps as text are removed and named, so
shapes.removed, /// each is cleanable; shapes, gradient, clip path, internal references and colours stay; the
[ /// stored text is a fixpoint.
"stop@stop-color", #[test]
"stop@stop-color", fn the_inkscape_exports_are_cleaned_with_their_shapes() {
"path@stroke", let cases: [(&str, &[&str]); 3] = [
"path@fill", (
"g@fill" "inkscape-1.4.3-inkscape-svg.svg",
] &[
"svg@xmlns:inkscape",
"svg@xmlns:sodipodi",
"svg@xmlns:svg",
"svg@sodipodi:docname",
"sodipodi:namedview",
"text",
],
),
("inkscape-1.4.3-plain-svg.svg", &["svg@xmlns:svg", "text"]),
(
"inkscape-1.4.3-paths.svg",
&["svg@xmlns:svg", "path@aria-label"],
),
];
for (file, removed) in cases {
let cleaning = clean_svg(&fixture(&format!("exports/{file}")));
assert_eq!(outcome(&cleaning), (Cleanable, None), "{file}");
assert_eq!(cleaning.removed, removed, "{file}");
assert!(
cleaning.active.is_empty() && !cleaning.style_removed,
"{file}"
); );
assert_fixpoint(shapes.cleaned.as_deref().unwrap()); let stored = cleaning.stored.as_deref().unwrap();
for kept in [
"<linearGradient",
"<clipPath",
"clip-path=\"url(#frame)\"",
"fill=\"url(#coat)\"",
"stroke-dasharray=\"6 3\"",
] {
assert!(stored.contains(kept), "{file}: {kept}");
}
assert_fixpoint(stored);
}
let plain = clean_svg(&fixture("exports/inkscape-1.4.3-plain-svg.svg"));
assert!(plain.stored.unwrap().contains("fill=\"rgb(51, 102, 179)\""));
let paths = clean_svg(&fixture("exports/inkscape-1.4.3-paths.svg"));
assert!(
paths
.stored
.unwrap()
.contains("style=\"fill:#3366b3;fill-opacity:0.5\"")
);
}
/// Owner decision 2026-10-29: cairo writes its colours `rgb(20%, 40%, 70%)`; the strict
/// numeric `rgb()` is kept, so its export reads with no removal, colours, shapes and internal
/// references included, and its text is stable.
#[test]
fn the_cairo_export_keeps_its_colours_shapes_and_references() {
let bytes = fixture("exports/cairo-1.18.4-pycairo-1.27.0-shapes.svg");
let shapes = clean_svg(&bytes);
assert!(shapes.removed.is_empty(), "{:?}", shapes.removed);
let preview = shapes.preview.as_deref().unwrap();
for colour in [
"stop-color=\"rgb(60%, 30%, 20%)\"",
"stop-color=\"rgb(90%, 80%, 60%)\"",
"stroke=\"rgb(20%, 20%, 20%)\"",
"fill=\"rgb(20%, 40%, 70%)\"",
"fill=\"rgb(0%, 0%, 0%)\"",
] {
assert!(preview.contains(colour), "{colour}");
}
let original = std::str::from_utf8(&bytes).unwrap();
let count = |text: &str, tag: &str| text.matches(tag).count();
for tag in ["<path", "<use", "<g", "<clipPath", "<linearGradient"] {
assert_eq!(count(preview, tag), count(original, tag), "{tag}");
}
for reference in [
"clip-path=\"url(#clip-0)\"",
"fill=\"url(#linear-pattern-0)\"",
"xlink:href=\"#glyph-0-0\"",
] {
assert!(preview.contains(reference), "{reference}");
}
assert!(read_svg(preview).is_ok_and(|read| read.removed.is_empty()));
assert_eq!(
clean_svg(preview.as_bytes()).preview.as_deref(),
Some(preview)
);
}
/// The colour exception opens nothing else: a reference outside the document, an active CSS
/// token or a script next to a colour still refuses the file; any other function, or a colour
/// outside the strict form, is still removed (and cleaned, never kept).
#[test]
fn colours_open_no_way_for_active_or_unknown_functions() {
let svg = |body: &str| {
format!("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 10 10\">{body}</svg>")
};
for (body, active) in [
(
"<path d=\"M0 0\" fill=\"rgb(1,2,3) url(http://e/x)\"/>",
"path@fill",
),
(
"<path d=\"M0 0\" style=\"fill:rgb(1,2,3);background:url(x)\"/>",
"path@style",
),
(
"<path d=\"M0 0\" style=\"fill:rgb(1,2,expression(alert(1)))\"/>",
"path@style",
),
(
"<path d=\"M0 0\" fill=\"rgb(1,2,3)\" onclick=\"x()\"/>",
"path@onclick",
),
(
"<path d=\"M0 0\" style=\"fill:rgb(1,2,3);@import 'x'\"/>",
"path@style",
),
("<path d=\"M0 0\" fill=\"\\72 gb(1,2,3)\"/>", "path@fill"),
(
"<path d=\"M0 0\" fill=\"rgb(1,2,3)\"/><script>alert(1)</script>",
"script",
),
] {
let cleaning = clean_svg(svg(body).as_bytes());
assert_eq!(
outcome(&cleaning),
(Rejected, Some("svg_active_content")),
"{body}"
);
assert_eq!(cleaning.active, [active], "{body}");
}
for (body, removed) in [
("<path d=\"M0 0\" fill=\"rgb(1,2,var(--x))\"/>", "path@fill"),
("<path d=\"M0 0\" fill=\"RGB(1,2,3)\"/>", "path@fill"),
("<path d=\"M0 0\" stroke=\"rgb(300,0,0)\"/>", "path@stroke"),
(
"<path d=\"M0 0\" style=\"fill:hsl(1,2%,3%)\"/>",
"path@style",
),
("<stop stop-color=\"rgba(1,2,3)\"/>", "stop@stop-color"),
] {
let cleaning = clean_svg(svg(body).as_bytes());
assert_eq!(outcome(&cleaning), (Cleanable, None), "{body}");
assert_eq!(cleaning.removed, [removed], "{body}");
assert_fixpoint(cleaning.stored.as_deref().unwrap());
}
let kept =
svg("<path d=\"M0 0\" fill=\"rgba(10%, 20%, 30%, 50%)\" style=\"stroke:rgb(1, 2, 3)\"/>");
assert_eq!(outcome(&clean_svg(kept.as_bytes())), (Clean, None));
} }
#[test] #[test]
@@ -330,8 +514,7 @@ fn the_owner_editor_exports_are_cleaned_or_refused_with_a_reason() {
} }
match cleaning.outcome { match cleaning.outcome {
Rejected => assert!(cleaning.reason.is_some(), "{name}"), Rejected => assert!(cleaning.reason.is_some(), "{name}"),
Cleanable => assert_fixpoint(cleaning.cleaned.as_deref().unwrap()), Cleanable | Clean => assert_fixpoint(cleaning.stored.as_deref().unwrap()),
Clean => {}
} }
println!( println!(
"{name}: {:?} {:?} {:?}", "{name}: {:?} {:?} {:?}",
@@ -340,21 +523,22 @@ fn the_owner_editor_exports_are_cleaned_or_refused_with_a_reason() {
} }
} }
/// A cleaned text reads back with nothing removed and cleans to itself. /// A stored text reads back with nothing removed, is clean and is its own stored form.
fn assert_fixpoint(cleaned: &str) { fn assert_fixpoint(stored: &str) {
let read = read_svg(cleaned).unwrap_or_else(|e| panic!("{e:?}: {cleaned}")); let read = read_svg(stored).unwrap_or_else(|e| panic!("{e:?}: {stored}"));
assert!(read.removed.is_empty(), "{:?}: {cleaned}", read.removed); assert!(read.removed.is_empty(), "{:?}: {stored}", read.removed);
let again = clean_svg(cleaned.as_bytes()); let again = clean_svg(stored.as_bytes());
assert_eq!(again.outcome, Clean, "{cleaned}"); assert_eq!(again.outcome, Clean, "{stored}");
assert_eq!(again.preview.as_deref(), Some(cleaned)); assert_eq!(again.stored.as_deref(), Some(stored));
assert_eq!(stored_form(&read.root), stored);
} }
#[test] #[test]
fn every_cleanable_file_of_the_corpus_reaches_the_fixpoint() { fn every_cleanable_file_of_the_corpus_reaches_the_fixpoint() {
for file in std::fs::read_dir(common::repo_path(&format!("{FIXTURES}/hostile"))).unwrap() { for file in std::fs::read_dir(common::repo_path(&format!("{FIXTURES}/hostile"))).unwrap() {
let cleaning = clean_svg(&std::fs::read(file.unwrap().path()).unwrap()); let cleaning = clean_svg(&std::fs::read(file.unwrap().path()).unwrap());
if let Some(cleaned) = cleaning.cleaned { if let Some(stored) = cleaning.stored {
assert_fixpoint(&cleaned); assert_fixpoint(&stored);
} }
} }
} }
@@ -479,6 +663,11 @@ fn drawing(rng: &mut Rng) -> String {
for _ in 0..1 + rng.next() % 4 { for _ in 0..1 + rng.next() % 4 {
element(rng, 1, &mut out, editor); element(rng, 1, &mut out, editor);
} }
// Most drawings define the ids the references name, after the generated ones (which stay
// first, so their cycles still count); the others may dangle.
if !rng.next().is_multiple_of(4) {
out.push_str("<defs><linearGradient id=\"a1\"/><path id=\"b_2\" d=\"M0 0\"/></defs>");
}
out.push_str("</svg>"); out.push_str("</svg>");
out out
} }
@@ -495,19 +684,22 @@ fn generated_drawings_clean_to_a_fixpoint() {
Clean => clean += 1, Clean => clean += 1,
Cleanable => { Cleanable => {
cleanable += 1; cleanable += 1;
assert_fixpoint(cleaning.cleaned.as_deref().unwrap()); assert_fixpoint(cleaning.stored.as_deref().unwrap());
} }
Rejected => { Rejected => {
rejected += 1; rejected += 1;
let reason = cleaning.reason.unwrap(); let reason = cleaning.reason.unwrap();
assert_eq!(reason, "reference_cycle", "{text}"); assert!(
matches!(reason.as_str(), "reference_cycle" | "dangling_reference"),
"{reason}: {text}"
);
*reasons.entry(reason).or_insert(0) += 1; *reasons.entry(reason).or_insert(0) += 1;
} }
} }
} }
println!("generated: {clean} clean, {cleanable} cleanable, {rejected} rejected {reasons:?}"); println!("generated: {clean} clean, {cleanable} cleanable, {rejected} rejected {reasons:?}");
assert!( assert!(
cleanable > 1000 && clean > 100, cleanable > 1000 && clean > 100 && reasons.len() == 2,
"{clean} {cleanable} {rejected}" "{clean} {cleanable} {rejected} {reasons:?}"
); );
} }
+36
View File
@@ -52,6 +52,15 @@ fn declared(file: &str) -> Option<Value> {
} }
// C2: the prescan's per-element attribute cap (TS removes the 3,000 data-like names). // C2: the prescan's per-element attribute cap (TS removes the 3,000 data-like names).
"comment-desync-attributes.svg" => json!({ "rejected": "too_complex" }), "comment-desync-attributes.svg" => json!({ "rejected": "too_complex" }),
// 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 decision 2026-10-29: a strict numeric `rgb()` colour is kept (TS removed
// any function); the five other styles stay removed.
"css.svg" => {
json!({ "removed": ["path@style", "path@style", "path@style", "path@style", "path@style"],
"rust_keeps": [["path", "style", "fill:rgb(1,2,3)"]] })
}
// C3 root: no class or style on the inline root. // C3 root: no class or style on the inline root.
"root-class-style.svg" => json!({ "removed": ["svg@class", "svg@style"] }), "root-class-style.svg" => json!({ "removed": ["svg@class", "svg@style"] }),
_ => return None, _ => return None,
@@ -82,6 +91,25 @@ fn strip(tree: &mut Value, element: &str, attribute: &str) {
} }
} }
/// Removes the attribute holding exactly `value` from elements of that local name (a value
/// the Rust reader keeps on purpose); whether one was found.
fn strip_value(tree: &mut Value, element: &str, attribute: &str, value: &str) -> bool {
let mut found = false;
if tree["name"] == element
&& let Some(attrs) = tree["attrs"].as_object_mut()
&& attrs.get(attribute).and_then(Value::as_str) == Some(value)
{
attrs.remove(attribute);
found = true;
}
if let Some(children) = tree["children"].as_array_mut() {
for child in children {
found |= strip_value(child, element, attribute, value);
}
}
found
}
/// Removes `href`/`xlink:href` values that start with a non-ASCII character (a declared removal). /// Removes `href`/`xlink:href` values that start with a non-ASCII character (a declared removal).
fn strip_unicode_spaced_refs(tree: &mut Value) { fn strip_unicode_spaced_refs(tree: &mut Value) {
if let Some(attrs) = tree["attrs"].as_object_mut() { if let Some(attrs) = tree["attrs"].as_object_mut() {
@@ -158,6 +186,14 @@ fn every_hostile_case_gives_the_typescript_verdict_or_a_declared_one() {
} }
Some(expected) => { Some(expected) => {
assert_eq!(rust["removed"], expected["removed"], "{file}"); assert_eq!(rust["removed"], expected["removed"], "{file}");
let mut rust = rust.clone();
for kept in expected["rust_keeps"].as_array().into_iter().flatten() {
let [element, attribute, value] = [0, 1, 2].map(|i| kept[i].as_str().unwrap());
assert!(
strip_value(&mut rust["tree"], element, attribute, value),
"{file}"
);
}
let mut tree = declared_tree(&ts["tree"], false, true).unwrap(); let mut tree = declared_tree(&ts["tree"], false, true).unwrap();
if expected["strip_unicode_spaced_refs"] == true { if expected["strip_unicode_spaced_refs"] == true {
strip_unicode_spaced_refs(&mut tree); strip_unicode_spaced_refs(&mut tree);
+276
View File
@@ -0,0 +1,276 @@
//! 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);
}
+12
View File
@@ -73,6 +73,18 @@ engine keeps whatever the asset has. A detail view with its own
chain. The root's `width` and `height` are removed; its other attributes are chain. The root's `width` and `height` are removed; its other attributes are
kept (after sanitising). kept (after sanitising).
The editor canvas is inlined in the page, where `#id` resolves against the
whole document. Since V1-2.2 (owner decision 2026-10-29) the core writes
`fv.<view id>.` in front of every `id` of the drawing and of every local
reference to it (`href`, `xlink:href`, `url(#…)`), so each view resolves its
gradients, clip paths and `<use>` targets in its own drawing only, never in
another view's or in the page; a drawing whose reference names an id it does
not define is refused by the reader (`dangling_reference`). The annotation
layer carries no `id`. The PDF view keeps the drawing's ids: it is rasterised
as a document of its own. The R3 canvas goldens stay frozen; the tests apply
this declared change to them (`withIdsScopedPerView`,
`with_ids_scoped_per_view`).
## Styling and states ## Styling and states
The application stylesheet: `.svg-canvas [data-state='current']` fills the The application stylesheet: `.svg-canvas [data-state='current']` fills the
+26 -2
View File
@@ -3,7 +3,10 @@
* index, the fingerprint and the canvases of the bundled sheet; hash and fingerprint * index, the fingerprint and the canvases of the bundled sheet; hash and fingerprint
* mismatches refuse the build with their closed kind; a draft's document is replaced and * mismatches refuse the build with their closed kind; a draft's document is replaced and
* redrawn; the edit commands run through `call`; every hostile SVG and flood gets a closed * redrawn; the edit commands run through `call`; every hostile SVG and flood gets a closed
* cleaning answer with no trap. The Rust suites hold the rules; this proves the facade. * cleaning answer with no trap. The owner's decisions of 2026-10-29 too: canvases scope their
* ids per view, dangling references and removals that leave a dependent are refused, the
* stored form is what a file uploads, cairo's `rgb()` colours are kept. The Rust suites hold
* the rules; this proves the facade.
*/ */
import { readFileSync, readdirSync } from 'node:fs' import { readFileSync, readdirSync } from 'node:fs'
import { fileURLToPath } from 'node:url' import { fileURLToPath } from 'node:url'
@@ -16,6 +19,8 @@ const SEED = `${ROOT}supabase/seed/anatomical-sheets/equine/draft/`
const HOSTILE = `${ROOT}crates/core/tests/fixtures/svg/hostile/` const HOSTILE = `${ROOT}crates/core/tests/fixtures/svg/hostile/`
const HORSE_ID = '7f767f74-3b36-51a7-8465-52dd7e2ead4a' const HORSE_ID = '7f767f74-3b36-51a7-8465-52dd7e2ead4a'
const HORSE_SHA = '0ea5202fa3b95bac167b87c12ee969ab0272e085b60c2d34dbca6202c5f08541' const HORSE_SHA = '0ea5202fa3b95bac167b87c12ee969ab0272e085b60c2d34dbca6202c5f08541'
const EXPORTS = `${ROOT}crates/core/tests/fixtures/svg/exports/`
const PROLOG = '<?xml version="1.0" encoding="UTF-8"?>\n'
const FINGERPRINT = '12d788727c1e532641bd5b3a7ecf39dbdd25e70350f8a76be5ca917b262874e2' const FINGERPRINT = '12d788727c1e532641bd5b3a7ecf39dbdd25e70350f8a76be5ca917b262874e2'
const path = (p: string) => fileURLToPath(new URL(p, import.meta.url)) const path = (p: string) => fileURLToPath(new URL(p, import.meta.url))
const text = (p: string) => readFileSync(path(p), 'utf8') const text = (p: string) => readFileSync(path(p), 'utf8')
@@ -78,6 +83,12 @@ describe('PreviewSheet through the shipped module', () => {
for (const viewId of ['main', 'head']) { for (const viewId of ['main', 'head']) {
const input = JSON.stringify({ viewId }) const input = JSON.stringify({ viewId })
expect(preview.call('view.canvas', input)).toBe(handle.call('view.canvas', input)) expect(preview.call('view.canvas', input)).toBe(handle.call('view.canvas', input))
const svg: string = value(preview.call('view.canvas', input)).svg
const ids = [...svg.matchAll(/ id="([^"]*)"/g)].map((m) => m[1])
expect(ids.length).toBeGreaterThan(100)
expect(ids.every((id) => id.startsWith(`fv.${viewId}.`))).toBe(true)
const refs = [...svg.matchAll(/(?:href="#|url\(#)([^")]*)/g)].map((m) => m[1])
expect(refs.every((ref) => ids.includes(ref))).toBe(true)
} }
handle.free() handle.free()
preview.free() preview.free()
@@ -121,6 +132,10 @@ describe('PreviewSheet through the shipped module', () => {
glue.call('sheet.dependents', JSON.stringify({ document, key: { kind: 'view', id: 'head' } })), glue.call('sheet.dependents', JSON.stringify({ document, key: { kind: 'view', id: 'head' } })),
) )
expect(head.dependents.length).toBeGreaterThan(0) expect(head.dependents.length).toBeGreaterThan(0)
const named = JSON.parse(
glue.call('sheet.edit', JSON.stringify({ document, command: { op: 'remove', key: { kind: 'view', id: 'head' } } })),
)
expect(named.kind).toBe('has_dependents')
}) })
}) })
@@ -147,7 +162,16 @@ describe('clean_svg through the shipped module', () => {
expect(value(glue.clean_svg(new Uint8Array(readFileSync(path(`${HOSTILE}script.svg`))))).reason).toBe( expect(value(glue.clean_svg(new Uint8Array(readFileSync(path(`${HOSTILE}script.svg`))))).reason).toBe(
'svg_active_content', 'svg_active_content',
) )
expect(value(glue.clean_svg(horse)).outcome).toBe('clean') const cleanHorse = value(glue.clean_svg(horse))
expect([cleanHorse.outcome, cleanHorse.sha256]).toEqual(['clean', HORSE_SHA])
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')
const cairo = value(
glue.clean_svg(new Uint8Array(readFileSync(path(`${EXPORTS}cairo-1.18.4-pycairo-1.27.0-shapes.svg`)))),
)
expect([cairo.outcome, cairo.removed]).toEqual(['clean', []])
expect(cairo.stored.startsWith(PROLOG) && cairo.stored.includes('fill="rgb(20%, 40%, 70%)"')).toBe(true)
console.info(`[core-wasm] clean_svg: ${inputs.length} inputs, slowest ${slowest.toFixed(1)} ms`) console.info(`[core-wasm] clean_svg: ${inputs.length} inputs, slowest ${slowest.toFixed(1)} ms`)
expect(glue.core_version()).toMatch(/^\d+\.\d+\.\d+$/) expect(glue.core_version()).toMatch(/^\d+\.\d+\.\d+$/)
}) })
+1 -1
View File
@@ -1,3 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type DrawingResult = "ok" | "missing" | "size_mismatch" | "hash_mismatch" | "svg_rejected" | "svg_removal"; export type DrawingResult = "ok" | "missing" | "size_mismatch" | "hash_mismatch" | "svg_rejected" | "svg_removal" | "svg_not_canonical";
+3 -3
View File
@@ -23,10 +23,10 @@ style_removed: boolean,
*/ */
preview: string | null, preview: string | null,
/** /**
* Cleanable only: the text to upload. * Clean or cleanable: the text to upload, the drawing's stored form.
*/ */
cleaned: string | null, stored: string | null,
/** /**
* SHA-256 and size of the bytes to upload: the original (clean) or the cleaned text. * SHA-256 and size of `stored`, the bytes to upload.
*/ */
sha256: string | null, byte_size: number | null, }; sha256: string | null, byte_size: number | null, };