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 {