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

+11 -5
View File
@@ -4,7 +4,9 @@
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::domain::js::parse_json;
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()
}
/// A frozen canvas golden with the declared trigger-name change applied.
fn golden(name: &str, sheet: &LoadedSheet) -> Value {
let text = common::repo_file(&format!("apps/app/tests/fixtures/goldens/r3/{name}"));
/// A frozen canvas golden with the declared changes applied: trigger names, ids scoped per
/// view.
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();
with_trigger_names_per_language(&mut frozen, &view_names(&sheet.document));
with_ids_scoped_per_view(&mut frozen, view);
frozen
}
@@ -50,7 +56,7 @@ fn each_view_answers_the_frozen_canvas() {
let svg = out["value"]["svg"].as_str().unwrap();
assert_eq!(
tree_value(&parse_svg(svg).unwrap()),
golden(&format!("canvas.{view}.json"), &sheet),
golden(view, &sheet),
"{view}"
);
}
+11 -9
View File
@@ -11,7 +11,9 @@ mod common;
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::layer::render_layer;
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).
fn canvas_golden(name: &str) -> Value {
let text = common::repo_file(&format!("apps/app/tests/fixtures/goldens/r3/{name}"));
/// A frozen canvas golden with the declared changes applied: trigger names (draft views) and
/// ids scoped per view.
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();
with_trigger_names_per_language(&mut frozen, &view_names(&draft()));
with_ids_scoped_per_view(&mut frozen, view);
frozen
}
@@ -110,11 +116,7 @@ fn every_canvas_equals_the_frozen_tree_and_every_state_set_its_layer() {
let draft = draft();
for view in ["main", "head"] {
let canvas = compose_canvas(&draft, view, &horse).unwrap();
assert_eq!(
reread(&canvas),
canvas_golden(&format!("canvas.{view}.json")),
"{view}"
);
assert_eq!(reread(&canvas), canvas_golden(view), "{view}");
let layers: Value = serde_json::from_str(&common::repo_file(&format!(
"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`.
pub fn view_names(
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 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 {
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)),
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];
assert_eq!(
kind(verify_asset(&entry_for(binary), binary)),
+15 -5
View File
@@ -6,19 +6,29 @@ None is edited by hand.
| 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>`) |
| `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-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/`)
The editors an administrator actually uses (Inkscape, Illustrator, Figma, Affinity) are not
installed on the development machine; the owner exports a small drawing from each and puts
Illustrator, Figma and Affinity are not available on the development machine (Inkscape is
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
`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
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.
@@ -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")
);
}
/// 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};
const ASSET: &str = "11111111-2222-4333-8444-555555555555";
const DRAWING: &str =
r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><path d="M0 0L5 5"/></svg>"#;
/// A drawing in its stored form (`serialize::stored_form`), as the page's cleaning uploads it.
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 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`.
fn with_annotations(count: usize) -> Value {
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
//! 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
//! over generated drawings proves the fixpoint: a cleaned text reads back with no removal and
//! cleans to itself. The strict reader of stored drawings is unchanged.
//! over generated drawings proves the fixpoint: a stored text reads back with no removal and
//! 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)]
mod common;
use faunosteo_core::anatomy::svg::clean::{CleaningOutcome, SvgCleaning, clean_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;
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-self-cycle.svg", Rejected, Some("reference_cycle")),
("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.
("id-grammar.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-prefix-rebound.svg", Cleanable, None),
// Nothing removed (comments, stray text and clamped values are no removal).
("dangling-references.svg", Clean, None),
("duplicate-ids.svg", Clean, None),
("osteo-halo-id.svg", Clean, None),
("root-without-namespace.svg", Clean, None),
@@ -93,11 +100,11 @@ fn the_hostile_corpus_answers_as_the_contract_table() {
"{file}"
),
Cleanable => assert!(
cleaning.active.is_empty() && cleaning.cleaned.is_some(),
cleaning.active.is_empty() && cleaning.stored.is_some(),
"{file}"
),
Clean => assert!(
cleaning.removed.is_empty() && cleaning.cleaned.is_none(),
cleaning.removed.is_empty() && cleaning.stored.is_some(),
"{file}"
),
}
@@ -109,8 +116,8 @@ fn active_names_are_listed_and_ordinary_removals_are_not() {
let css = clean_svg(&fixture("hostile/css.svg"));
assert_eq!(
(css.removed.len(), css.active.len()),
(6, 4),
"rgb() and attr() alone would be cleaned"
(5, 4),
"attr() alone would be cleaned; the strict rgb() is kept"
);
let events = clean_svg(&fixture("hostile/events.svg"));
assert_eq!(
@@ -230,7 +237,7 @@ fn a_plain_style_sheet_is_cleaned_and_named() {
let cleaning = clean_svg(styled);
assert_eq!(outcome(&cleaning), (Cleanable, None));
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_eq!(
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]
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(
"supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg",
))
.unwrap();
let cleaning = clean_svg(&horse);
assert_eq!(outcome(&cleaning), (Clean, None));
assert_eq!(
cleaning.stored.as_deref().map(str::as_bytes),
Some(&horse[..])
);
assert_eq!(
cleaning.sha256.as_deref(),
Some("0ea5202fa3b95bac167b87c12ee969ab0272e085b60c2d34dbca6202c5f08541")
);
assert_eq!(cleaning.byte_size, Some(132_997));
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!(
outcome(&clean_svg(b"\xff\xfe<svg/>")),
(Rejected, Some("malformed"))
@@ -274,7 +317,7 @@ fn a_clean_file_is_uploaded_as_it_is_and_shown_as_read() {
#[test]
fn the_vector_tool_exports_are_read_or_refused_for_their_raster() {
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",
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"));
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"));
assert_eq!(
shapes.removed,
[
"stop@stop-color",
"stop@stop-color",
"path@stroke",
"path@fill",
"g@fill"
]
}
/// Real Inkscape 1.4.3 exports (owner go 2026-10-29; `exports/generate-inkscape.sh`): its
/// editor metadata and namespaces and the `text` it keeps as text are removed and named, so
/// each is cleanable; shapes, gradient, clip path, internal references and colours stay; the
/// stored text is a fixpoint.
#[test]
fn the_inkscape_exports_are_cleaned_with_their_shapes() {
let cases: [(&str, &[&str]); 3] = [
(
"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}"
);
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\"")
);
assert_fixpoint(shapes.cleaned.as_deref().unwrap());
}
/// 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]
@@ -330,8 +514,7 @@ fn the_owner_editor_exports_are_cleaned_or_refused_with_a_reason() {
}
match cleaning.outcome {
Rejected => assert!(cleaning.reason.is_some(), "{name}"),
Cleanable => assert_fixpoint(cleaning.cleaned.as_deref().unwrap()),
Clean => {}
Cleanable | Clean => assert_fixpoint(cleaning.stored.as_deref().unwrap()),
}
println!(
"{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.
fn assert_fixpoint(cleaned: &str) {
let read = read_svg(cleaned).unwrap_or_else(|e| panic!("{e:?}: {cleaned}"));
assert!(read.removed.is_empty(), "{:?}: {cleaned}", read.removed);
let again = clean_svg(cleaned.as_bytes());
assert_eq!(again.outcome, Clean, "{cleaned}");
assert_eq!(again.preview.as_deref(), Some(cleaned));
/// A stored text reads back with nothing removed, is clean and is its own stored form.
fn assert_fixpoint(stored: &str) {
let read = read_svg(stored).unwrap_or_else(|e| panic!("{e:?}: {stored}"));
assert!(read.removed.is_empty(), "{:?}: {stored}", read.removed);
let again = clean_svg(stored.as_bytes());
assert_eq!(again.outcome, Clean, "{stored}");
assert_eq!(again.stored.as_deref(), Some(stored));
assert_eq!(stored_form(&read.root), stored);
}
#[test]
fn every_cleanable_file_of_the_corpus_reaches_the_fixpoint() {
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());
if let Some(cleaned) = cleaning.cleaned {
assert_fixpoint(&cleaned);
if let Some(stored) = cleaning.stored {
assert_fixpoint(&stored);
}
}
}
@@ -479,6 +663,11 @@ fn drawing(rng: &mut Rng) -> String {
for _ in 0..1 + rng.next() % 4 {
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
}
@@ -495,19 +684,22 @@ fn generated_drawings_clean_to_a_fixpoint() {
Clean => clean += 1,
Cleanable => {
cleanable += 1;
assert_fixpoint(cleaning.cleaned.as_deref().unwrap());
assert_fixpoint(cleaning.stored.as_deref().unwrap());
}
Rejected => {
rejected += 1;
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;
}
}
}
println!("generated: {clean} clean, {cleanable} cleanable, {rejected} rejected {reasons:?}");
assert!(
cleanable > 1000 && clean > 100,
"{clean} {cleanable} {rejected}"
cleanable > 1000 && clean > 100 && reasons.len() == 2,
"{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).
"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.
"root-class-style.svg" => json!({ "removed": ["svg@class", "svg@style"] }),
_ => 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).
fn strip_unicode_spaced_refs(tree: &mut Value) {
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) => {
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();
if expected["strip_unicode_spaced_refs"] == true {
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);
}