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:
1 parent
17d919971e
commit
e823655f09
31 files changed
+1362
-110
No files matched your search
@@ -4,10 +4,18 @@
|
||||
//! 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
|
||||
//! 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 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::{Element, Node};
|
||||
use crate::domain::sheet::AnatomicalSheetDocument;
|
||||
@@ -73,11 +81,39 @@ pub fn compose_canvas(
|
||||
.or_else(|| asset.attr("viewBox").map(str::to_owned))
|
||||
.unwrap_or_else(|| CANVAS_FALLBACK_VIEW_BOX.to_owned());
|
||||
root.set_attr("viewBox", view_box);
|
||||
scope_ids(&mut root, &id_scope(view_id));
|
||||
let layer = render_layer(document, view_id, &HashSet::new())?;
|
||||
root.children.push(Node::Element(checked(layer)?));
|
||||
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
|
||||
/// of `annotation_ids` only, recoloured, with the halo filter when `halo`.
|
||||
pub fn compose_highlight(
|
||||
|
||||
@@ -3,24 +3,28 @@
|
||||
//!
|
||||
//! - 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
|
||||
//! instruction (`svg_active_content`, the names in `active`, a PI as `?<target>`); no
|
||||
//! cleaning is offered;
|
||||
//! instruction (`svg_active_content`, the names in `active`, a PI as `?<target>`), or, once
|
||||
//! no active content is found, a reference to an id the drawing does not define, in the
|
||||
//! file or after a removal (`dangling_reference`); no cleaning is offered;
|
||||
//! - cleanable: only other removals (editor metadata and namespaces, `data-*`, `<style>`,
|
||||
//! `class` or `style` on the root, ids outside the grammar, unsupported elements, long
|
||||
//! titles or descriptions): the cleaned text is the sanitised tree serialised, and it is
|
||||
//! that text, read back with no removal, that is hashed and uploaded;
|
||||
//! - clean: no removal; the original bytes are uploaded as they are.
|
||||
//! titles or descriptions): the admin confirms them;
|
||||
//! - clean: no removal, nothing to confirm.
|
||||
//!
|
||||
//! 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
|
||||
//! (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;
|
||||
#[cfg(feature = "ts")]
|
||||
use ts_rs::TS;
|
||||
|
||||
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 crate::domain::sheet::verdict::sha256_hex;
|
||||
|
||||
@@ -52,9 +56,9 @@ pub struct SvgCleaning {
|
||||
pub style_removed: bool,
|
||||
/// The drawing as the core reads it (sanitised, serialised).
|
||||
pub preview: Option<String>,
|
||||
/// Cleanable only: the text to upload.
|
||||
pub cleaned: Option<String>,
|
||||
/// SHA-256 and size of the bytes to upload: the original (clean) or the cleaned text.
|
||||
/// Clean or cleanable: the text to upload, the drawing's stored form.
|
||||
pub stored: Option<String>,
|
||||
/// SHA-256 and size of `stored`, the bytes to upload.
|
||||
pub sha256: Option<String>,
|
||||
#[cfg_attr(feature = "ts", ts(type = "number | null"))]
|
||||
pub byte_size: Option<u64>,
|
||||
@@ -68,7 +72,7 @@ fn rejected(reason: &str, removed: Vec<String>, active: Vec<String>) -> SvgClean
|
||||
removed,
|
||||
active,
|
||||
preview: None,
|
||||
cleaned: None,
|
||||
stored: None,
|
||||
sha256: None,
|
||||
byte_size: None,
|
||||
}
|
||||
@@ -95,34 +99,34 @@ pub fn clean_svg(bytes: &[u8]) -> SvgCleaning {
|
||||
if !active.is_empty() {
|
||||
return rejected(ACTIVE_CONTENT, read.removed, active);
|
||||
}
|
||||
if let Err(rejection) = check_targets(&read.root) {
|
||||
return rejected(rejection.reason(), read.removed, read.active);
|
||||
}
|
||||
let preview = serialize(&read.root);
|
||||
if preview.len() > MAX_PREVIEW_BYTES {
|
||||
return rejected("too_large", read.removed, read.active);
|
||||
}
|
||||
if read.removed.is_empty() {
|
||||
return accepted(CleaningOutcome::Clean, bytes, preview, Vec::new());
|
||||
}
|
||||
if preview.len() > SVG_CAPS.max_bytes {
|
||||
let stored = stored_form(&read.root);
|
||||
if stored.len() > SVG_CAPS.max_bytes {
|
||||
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);
|
||||
}
|
||||
accepted(
|
||||
CleaningOutcome::Cleanable,
|
||||
preview.as_bytes(),
|
||||
preview.clone(),
|
||||
read.removed,
|
||||
)
|
||||
let outcome = if read.removed.is_empty() {
|
||||
CleaningOutcome::Clean
|
||||
} else {
|
||||
CleaningOutcome::Cleanable
|
||||
};
|
||||
accepted(outcome, stored, preview, read.removed)
|
||||
}
|
||||
|
||||
fn accepted(
|
||||
outcome: CleaningOutcome,
|
||||
upload: &[u8],
|
||||
stored: String,
|
||||
preview: String,
|
||||
removed: Vec<String>,
|
||||
) -> SvgCleaning {
|
||||
let cleaned = (outcome == CleaningOutcome::Cleanable).then(|| preview.clone());
|
||||
SvgCleaning {
|
||||
outcome,
|
||||
reason: None,
|
||||
@@ -130,15 +134,16 @@ fn accepted(
|
||||
removed,
|
||||
active: Vec::new(),
|
||||
preview: Some(preview),
|
||||
cleaned,
|
||||
sha256: Some(sha256_hex(upload)),
|
||||
byte_size: Some(upload.len() as u64),
|
||||
sha256: Some(sha256_hex(stored.as_bytes())),
|
||||
byte_size: Some(stored.len() as u64),
|
||||
stored: Some(stored),
|
||||
}
|
||||
}
|
||||
|
||||
/// The cleaned text reads back with nothing to remove and serialises to itself, so what the
|
||||
/// admin confirms is what every reader draws (the fixpoint the property test of
|
||||
/// `tests/svg_clean.rs` proves; checked here too, so no upload rests on it alone).
|
||||
/// The stored text reads back with nothing to remove and gives itself again, so what the
|
||||
/// admin confirms is what every reader draws and what the verdict accepts (the fixpoint the
|
||||
/// 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 {
|
||||
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)
|
||||
}
|
||||
@@ -12,16 +12,19 @@ pub mod tree;
|
||||
pub use sanitize::Sanitized;
|
||||
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> {
|
||||
let root = tree::parse_svg(text)?;
|
||||
let sanitized = sanitize::sanitize(root)?;
|
||||
refs::check_references(&sanitized.root)?;
|
||||
refs::check_targets(&sanitized.root)?;
|
||||
Ok(sanitized)
|
||||
}
|
||||
|
||||
/// `read_svg` as the cleaning reads a file picked for upload: an oversized `title` or `desc`
|
||||
/// is a removal, not a refusal (`sanitize::sanitize_for_cleaning`).
|
||||
/// 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> {
|
||||
let root = tree::parse_svg(text)?;
|
||||
let sanitized = sanitize::sanitize_for_cleaning(root)?;
|
||||
|
||||
@@ -6,8 +6,10 @@
|
||||
//! 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
|
||||
//! 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::tree::{Element, Node, SvgRejection};
|
||||
@@ -34,6 +36,35 @@ pub fn check_references(root: &Element) -> Result<u64, SvgRejection> {
|
||||
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.
|
||||
fn flatten(root: &Element) -> (Vec<Flat>, Vec<(usize, Vec<String>)>) {
|
||||
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\"/>"),
|
||||
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("<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]
|
||||
fn refuses_cycles_through_use_paint_and_clip_paths() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -497,12 +497,34 @@ pub fn url_targets(value: &str) -> Vec<String> {
|
||||
.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(#…)`).
|
||||
fn urls_are_local(value: &str) -> bool {
|
||||
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 {
|
||||
let mut cut = String::with_capacity(value.len());
|
||||
let mut kept_from = 0;
|
||||
@@ -514,7 +536,99 @@ fn calls_only_local_url(value: &str) -> bool {
|
||||
}
|
||||
}
|
||||
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 {
|
||||
@@ -556,7 +670,61 @@ mod tests {
|
||||
// JavaScript's `\s` takes the newline, then `#` follows: local.
|
||||
assert!(urls_are_local("url(\n#a)"));
|
||||
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]
|
||||
|
||||
@@ -6,6 +6,19 @@
|
||||
|
||||
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.
|
||||
pub fn serialize(root: &Element) -> String {
|
||||
let mut out = String::with_capacity(4096);
|
||||
|
||||
@@ -104,6 +104,10 @@ pub enum SvgRejection {
|
||||
TooManyUses,
|
||||
TooComplex,
|
||||
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 {
|
||||
@@ -118,6 +122,7 @@ impl SvgRejection {
|
||||
Self::TooManyUses => "too_many_uses",
|
||||
Self::TooComplex => "too_complex",
|
||||
Self::ReferenceCycle => "reference_cycle",
|
||||
Self::DanglingReference => "dangling_reference",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ use serde::Deserialize;
|
||||
use url::{Host, Url};
|
||||
|
||||
use crate::anatomy::svg::read_svg;
|
||||
use crate::anatomy::svg::serialize::stored_form;
|
||||
use crate::curation::ids::sha256_hex;
|
||||
|
||||
/// 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
|
||||
/// 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> {
|
||||
let bad = |what: &str| refuse(UploadKind::Content, format!("{}: {what}", entry.file));
|
||||
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"))?;
|
||||
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")),
|
||||
Err(error) => Err(bad(&format!("refused by the SVG reader: {error:?}"))),
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ use super::review::DigestError;
|
||||
use super::schema::{AnatomicalSheetDocument, LocalizedText};
|
||||
use super::verdict::{read_document, sha256_hex};
|
||||
use crate::anatomy::svg::processing_instructions;
|
||||
use crate::anatomy::svg::serialize::stored_form;
|
||||
use crate::domain::archive::SnapshotCaps;
|
||||
use crate::domain::js;
|
||||
|
||||
@@ -113,12 +114,17 @@ impl PreviewFailure {
|
||||
/// uploads of one editing session (each one at most 2 MiB, refused above).
|
||||
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 {
|
||||
if !processing_instructions(text).is_empty() {
|
||||
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 {
|
||||
|
||||
@@ -25,6 +25,7 @@ use super::review::{Completeness, ElementChange, ReviewGroup, change_list};
|
||||
use super::schema::AnatomicalSheetDocument;
|
||||
use super::size::document_text_bytes;
|
||||
use super::validate::{SheetIssue, SheetIssueSeverity};
|
||||
use crate::anatomy::svg::serialize::stored_form;
|
||||
use crate::anatomy::svg::{processing_instructions, read_svg};
|
||||
use crate::domain::js::parse_json;
|
||||
|
||||
@@ -47,6 +48,7 @@ pub mod codes {
|
||||
pub const OBJECT_CONFLICT: &str = "verification.integrity.object_conflict";
|
||||
pub const SVG_REJECTED: &str = "verification.integrity.svg_rejected";
|
||||
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";
|
||||
}
|
||||
|
||||
@@ -101,6 +103,9 @@ pub enum DrawingResult {
|
||||
SvgRejected,
|
||||
/// The reader would take something out of it (names in `detail`); never repaired.
|
||||
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.
|
||||
@@ -340,6 +345,7 @@ fn check_bytes(row: &VerdictDrawing<'_>) -> (DrawingResult, Option<String>) {
|
||||
DrawingResult::SvgRejected,
|
||||
Some("processing_instruction".to_owned()),
|
||||
),
|
||||
Ok(read) if stored_form(&read.root) != text => (DrawingResult::SvgNotCanonical, None),
|
||||
Ok(_) => (DrawingResult::Ok, None),
|
||||
}
|
||||
}
|
||||
@@ -351,6 +357,7 @@ fn drawing_failures(drawings: &[CheckedDrawing]) -> Vec<&'static str> {
|
||||
(DrawingResult::HashMismatch, codes::OBJECT_CONFLICT),
|
||||
(DrawingResult::SvgRejected, codes::SVG_REJECTED),
|
||||
(DrawingResult::SvgRemoval, codes::SVG_REMOVAL),
|
||||
(DrawingResult::SvgNotCanonical, codes::SVG_NOT_CANONICAL),
|
||||
];
|
||||
order
|
||||
.into_iter()
|
||||
|
||||
Reference in new issue
Block a user