fix(anatomy): V1-2.2 read url() references in their strict spelling only

Security review BLOCK(1): url(#%61) passed the dangling check and the
per-view scoping and resolved in browsers. One strict reading now, other
spellings are active content; glued names are other functions; the
composer refuses an unscoped reference; owner export procedure.
This commit is contained in:
bchanot committed 2026-10-29 16:49:15 +01:00
1 parent 5281337412
commit a678faaa23
13 files changed
+553 -70

No files matched your search

+30 -2
View File
@@ -15,7 +15,7 @@
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::sanitize::{local_reference_text, scope_url_targets, url_targets, urls_are_local};
use super::svg::serialize::is_xml_text;
use super::svg::{Element, Node};
use crate::domain::sheet::AnatomicalSheetDocument;
@@ -31,6 +31,9 @@ pub enum ComposeError {
UnknownView,
/// A label or a path of the layer holds a code point XML 1.0 cannot carry.
InvalidCharacter,
/// A reference of the drawing kept outside its view's scope after scoping (fail-closed:
/// the reader keeps no such reference, so this never happens on a read drawing).
UnscopedReference,
}
impl From<LayerError> for ComposeError {
@@ -81,7 +84,11 @@ 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 scope = id_scope(view_id);
scope_ids(&mut root, &scope);
if !references_scoped(&root, &scope) {
return Err(ComposeError::UnscopedReference);
}
let layer = render_layer(document, view_id, &HashSet::new())?;
root.children.push(Node::Element(checked(layer)?));
Ok(root)
@@ -93,6 +100,27 @@ pub fn id_scope(view_id: &str) -> String {
format!("fv.{view_id}.")
}
/// Every `href` / `xlink:href` names `#<scope>…`, and every value holding `url(` holds only
/// local references whose ids start with `scope`.
fn references_scoped(element: &Element, scope: &str) -> bool {
let attrs_scoped = element.attrs.iter().all(|attr| match attr.qname.as_str() {
"href" | "xlink:href" => local_reference_text(&attr.value)
.strip_prefix('#')
.is_some_and(|id| id.starts_with(scope)),
_ if attr.value.to_ascii_lowercase().contains("url(") => {
urls_are_local(&attr.value)
&& url_targets(&attr.value)
.iter()
.all(|id| id.starts_with(scope))
}
_ => true,
});
attrs_scoped
&& element
.element_children()
.all(|child| references_scoped(child, scope))
}
/// 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) {
+74 -51
View File
@@ -453,75 +453,93 @@ pub fn is_reference_name(value: &str) -> bool {
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | ':' | '-'))
}
/// Byte offsets right after each case-insensitive `url(`.
/// A character that continues a CSS identifier before a function name: `xurl(` or `érgb(` is
/// another function, never `url(` or `rgb(` (V1-2.2 reviews).
fn continues_identifier(c: char) -> bool {
c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '\\') || !c.is_ascii()
}
/// Byte offsets right after each case-insensitive `url(` that is not the end of a longer
/// function name.
fn url_openings(value: &str) -> impl Iterator<Item = usize> + '_ {
let lower = value.to_ascii_lowercase();
let mut from = 0;
std::iter::from_fn(move || {
let at = lower.get(from..)?.find("url(")? + from;
from = at + 4;
Some(from)
loop {
let at = lower.get(from..)?.find("url(")? + from;
from = at + 4;
let glued = value[..at]
.chars()
.next_back()
.is_some_and(continues_identifier);
if !glued {
return Some(from);
}
}
})
}
/// After `url(`: whitespace, an optional quote, whitespace; returns the offset of the next
/// character. Only CSS whitespace is skipped, as the browser's CSS tokenizer skips it: the
/// engine skipped JavaScript spaces, so a no-break space before `#a` read as local but the
/// browser resolves it as a relative URL (security audit R3, pass 2).
fn skip_url_prefix(value: &str, at: usize) -> usize {
let rest = &value[at..];
let mut chars = rest.char_indices().peekable();
let skip_space = |chars: &mut std::iter::Peekable<std::str::CharIndices<'_>>| {
while chars.peek().is_some_and(|&(_, c)| is_css_space(c)) {
chars.next();
}
};
skip_space(&mut chars);
if chars.peek().is_some_and(|&(_, c)| c == '\'' || c == '"') {
chars.next();
/// A local reference after the `url(` opening ending at `at`, read as strictly as the reader
/// keeps it (owner decision 2026-10-29 and its security review): CSS whitespace, an optional
/// quote, `#`, an id in the reference grammar, the same quote, CSS whitespace, `)`. Anything a
/// browser could read differently (`%61`, a tab or a space inside the quotes, an empty or
/// non-ASCII id, an unbalanced quote) is not local. Answers the id's byte range in `value`.
fn local_url_target(value: &str, at: usize) -> Option<(usize, usize)> {
let bytes = value.as_bytes();
let mut index = skip_css_spaces(bytes, at);
let quote = bytes
.get(index)
.copied()
.filter(|b| matches!(b, b'\'' | b'"'));
index += usize::from(quote.is_some());
if bytes.get(index) != Some(&b'#') {
return None;
}
skip_space(&mut chars);
at + chars.peek().map_or(rest.len(), |&(i, _)| i)
let id_start = index + 1;
let id_len = value[id_start..]
.bytes()
.take_while(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b':' | b'-'))
.count();
let id_end = id_start + id_len;
if !is_reference_name(&value[id_start..id_end]) {
return None;
}
index = id_end;
if let Some(quote) = quote {
if bytes.get(index) != Some(&quote) {
return None;
}
index += 1;
}
index = skip_css_spaces(bytes, index);
(bytes.get(index) == Some(&b')')).then_some((id_start, id_end))
}
/// The ids of the value's `url(#id)` references, in order.
/// The ids of the value's local `url(#id)` references, in order.
pub fn url_targets(value: &str) -> Vec<String> {
url_openings(value)
.filter_map(|at| value[skip_url_prefix(value, at)..].strip_prefix('#'))
.map(|rest| {
rest.chars()
.take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | ':' | '-'))
.collect::<String>()
})
.filter(|id| !id.is_empty())
.filter_map(|at| local_url_target(value, at))
.map(|(start, end)| value[start..end].to_owned())
.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.
/// The value with `scope` written in front of the id of each local `url(#id)` that
/// `url_targets` reads, 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;
}
for (start, _) in url_openings(value).filter_map(|at| local_url_target(value, at)) {
out.push_str(&value[kept_from..start]);
out.push_str(scope);
kept_from = start;
}
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('#'))
/// Every `url(` in the value is a local reference (`local_url_target`).
pub fn urls_are_local(value: &str) -> bool {
url_openings(value).all(|at| local_url_target(value, at).is_some())
}
/// No `(` once the `url(#` openings and the strict colour functions are taken out.
@@ -529,10 +547,12 @@ fn calls_only_local_url(value: &str) -> bool {
let mut cut = String::with_capacity(value.len());
let mut kept_from = 0;
for at in url_openings(value) {
let next = skip_url_prefix(value, at);
if value[next..].starts_with('#') {
if let Some((_, id_end)) = local_url_target(value, at) {
cut.push_str(&value[kept_from..at - 4]);
kept_from = next + 1;
cut.push(' ');
kept_from = value[id_end..]
.find(')')
.map_or(value.len(), |i| id_end + i + 1);
}
}
cut.push_str(&value[kept_from..]);
@@ -569,7 +589,7 @@ 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, '_' | '-' | '\\'));
.is_some_and(continues_identifier);
let rest = &text[at..];
let (components, open) = match () {
_ if glued => return None,
@@ -600,7 +620,10 @@ fn colour_function_end(text: &str, at: usize) -> Option<usize> {
}
index += 1;
}
Some(at + index)
// The function is a whole value of a list or a declaration, never glued to what follows.
let after = bytes.get(index).copied();
let ends = after.is_none_or(|b| is_css_space(char::from(b)) || matches!(b, b';' | b',' | b'!'));
ends.then_some(at + index)
}
fn skip_css_spaces(bytes: &[u8], mut index: usize) -> usize {
+1
View File
@@ -477,6 +477,7 @@ fn canvas_of<'a>(
let canvas = compose_canvas(document, view_id, drawing).map_err(|e| match e {
ComposeError::UnknownView => Failure::new("unknown_view", view_id),
ComposeError::InvalidCharacter => Failure::new("invalid_character", view_id),
ComposeError::UnscopedReference => Failure::new("svg_rejected", "unscoped_reference"),
})?;
let svg = serialize(&canvas);
if svg.len() > MAX_COMPOSED_BYTES {
+1 -1
View File
@@ -6,7 +6,7 @@ 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 | 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-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 five 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 |
+46
View File
@@ -1 +1,47 @@
Owner-supplied editor exports land here (see ../README.md).
# What to export (A6, contract §9.2 and §15)
One small drawing per tool, made in that tool, never retouched by hand afterwards. Same
reference content as `../inkscape-source.svg`, so the results compare:
- an outline with a curve, filled with a two-stop linear gradient, a 2 px dashed stroke;
- an ellipse with a flat colour;
- a rounded rectangle at 50 % opacity;
- the whole group clipped by a rectangle (Illustrator: clipping mask; Figma: a frame with
« Clip content »);
- the word « Garrot » as live text.
Artboard or frame 200 × 150 px. Note the exact version (Illustrator: Aide › À propos
d'Illustrator; Figma: menu › Aide › À propos de Figma, or the desktop app's version).
## Illustrator
1. Fichier › Exporter › Exporter sous… › format SVG (`svg`), « Utiliser les plans de travail »
ticked.
2. Options SVG, two files:
- `illustrator-<version>-export-as.svg`: Style « Attributs de présentation », Police
« Vectoriser », Images « Incorporer », ID d'objet « Noms de calques », Décimales 2, Minifier
off, Responsive on;
- `illustrator-<version>-internal-css.svg`: the same with Style « CSS interne » (the export
most users keep by default; expected cleanable, its `<style>` named as removed).
3. If a third is easy: Fichier › Enregistrer sous… › SVG (`illustrator-<version>-save-as.svg`),
the older dialog, default settings.
## Figma
1. Select the frame, right panel › Exporter › « + » › format SVG.
2. Options, two files:
- `figma-<version>-export.svg`: defaults (« Contours du texte » ticked, « Inclure
l'attribut id » unticked);
- `figma-<version>-ids.svg`: « Inclure l'attribut id » ticked (the layer names become ids).
3. Exporter.
## Then
Copy the files here, unchanged, and tell Claude. The suite
`cargo test -p faunosteo-core --test svg_clean the_owner_editor_exports` reads every `.svg` in
this folder: each must be refused with a closed reason or cleaned into a stored form that reads
back with no removal. A file whose name contains `-active-` must be refused for active content
(useful if you want to try an export with a linked image or an animation). Nothing is uploaded
anywhere: these are test fixtures, committed with the tool and version in their names.
+72
View File
@@ -337,6 +337,78 @@ fn the_vector_tool_exports_are_read_or_refused_for_their_raster() {
assert_eq!(raster.active, ["image"]);
}
/// Security review of the arbitrations (2026-10-29): a `url(` is kept only when its target is
/// `#` and an id in the reference grammar, an optional matching quote and `)`; every spelling
/// a browser would normalise or read otherwise is active content, so the dangling check, the
/// per-view scoping and the expansion budget cannot be walked around. Names glued to `url(` or
/// `rgb(` are other functions, removed.
#[test]
fn every_url_spelling_but_the_strict_one_is_refused() {
let svg = |value: &str| {
format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 10 10\">\
<linearGradient id=\"a\"/><path d=\"M0 0\" fill=\"{value}\"/></svg>"
)
};
for value in [
"url(#%61)",
"url(#%66v.main.a)",
"url(\'#\ta\')",
"url(\'#a\tb\')",
"url(#)",
"url(# a)",
"url(\'#a)",
"url(&quot;#a\')",
"url(#é)",
"url(#1a)",
"url(#a b)",
"url(#a rgb(1,2,3))",
"url(#/a)",
"url(#a",
] {
let cleaning = clean_svg(svg(value).as_bytes());
assert_eq!(
outcome(&cleaning),
(Rejected, Some("svg_active_content")),
"{value}"
);
assert_eq!(cleaning.active, ["path@fill"], "{value}");
}
for value in [
"url(#a)",
"URL( \'#a\' )",
"url(&quot;#a&quot;)",
"url(\n#a)",
] {
assert_eq!(
outcome(&clean_svg(svg(value).as_bytes())),
(Clean, None),
"{value}"
);
}
for value in [
"érgb(1,2,3)",
"rgurl(#a(1,2,3)",
"xurl(#a)",
"rgb(1,2,3)rgb(4,5,6)",
"rgb(1,2,3)x",
] {
let cleaning = clean_svg(svg(value).as_bytes());
assert_eq!(outcome(&cleaning), (Cleanable, None), "{value}");
assert_eq!(cleaning.removed, ["path@fill"], "{value}");
}
// The expansion budget holds whatever the spelling: 250 000 references written `%61` are
// refused as active content, as the plain spelling is refused as too complex.
let flood = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\"><linearGradient id=\"a\"/><path d=\"M0 0\" fill=\"{}\"/></svg>",
"url(#%61) ".repeat(25_000)
);
assert_eq!(
outcome(&clean_svg(flood.as_bytes())).1,
Some("svg_active_content")
);
}
/// 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
+68
View File
@@ -274,3 +274,71 @@ fn composition_is_deterministic_and_repeatable() {
);
assert_eq!(preview.drawing_reads(), 2);
}
/// Every reference of `text` as a browser reads it, written apart from the core's reader:
/// each `href="…"` and each `url(…)` (any case), quotes and CSS whitespace trimmed, tab and
/// newline removed and `%XX` decoded as the URL parser does. Answers the fragment ids.
fn browser_references(text: &str) -> Vec<String> {
let normalise = |raw: &str| {
let trimmed = raw.trim_matches(|c: char| c.is_ascii_whitespace() || c == '\'' || c == '"');
let cleaned: String = trimmed
.chars()
.filter(|c| !matches!(c, '\t' | '\n' | '\r'))
.collect();
let mut bytes = Vec::new();
let raw = cleaned.as_bytes();
let mut i = 0;
while i < raw.len() {
let hex = raw
.get(i + 1..i + 3)
.and_then(|h| std::str::from_utf8(h).ok());
match (raw[i], hex.and_then(|h| u8::from_str_radix(h, 16).ok())) {
(b'%', Some(byte)) => {
bytes.push(byte);
i += 3;
}
(byte, _) => {
bytes.push(byte);
i += 1;
}
}
}
String::from_utf8_lossy(&bytes).into_owned()
};
let mut out = Vec::new();
for (index, _) in text.match_indices("href=\"") {
let rest = &text[index + 6..];
out.push(normalise(&rest[..rest.find('"').unwrap()]));
}
let lower = text.to_ascii_lowercase();
for (index, _) in lower.match_indices("url(") {
let rest = &text[index + 4..];
out.push(normalise(&rest[..rest.find(')').unwrap_or(rest.len())]));
}
out.into_iter()
.map(|reference| reference.strip_prefix('#').unwrap_or(&reference).to_owned())
.collect()
}
#[test]
fn every_reference_a_browser_reads_stays_in_its_view() {
let preview = preview(&detail_drawing());
for view in ["main", "detail"] {
let text = canvas(&preview, view);
let references = browser_references(&text);
assert!(references.len() >= 2, "{view}");
for reference in references {
assert!(
reference.starts_with(&format!("fv.{view}.")),
"{view}: {reference}"
);
}
}
// The hostile spellings never reach a canvas: the drawing is refused, nothing composed.
for value in ["url(#%66v.main.g)", "url(\'#\tg\')", "url(#%67)"] {
let hostile =
format!("{OPEN}<radialGradient id=\"g\"/><path fill=\"{value}\" d=\"M0 0\"/></svg>");
let refused = canvas_outcome(&self::preview(&hostile), "detail");
assert_eq!(refused["kind"], json!("svg_rejected"), "{value}");
}
}