Skip to main content

eui_core/host/
policy.rs

1//! The policy rules every host applies before a client function, a URL open
2//! or a media load (`catalog/host.json` functions / urls / media). Pure;
3//! `fixtures/host-policy.json` locks them on every platform.
4
5use std::collections::BTreeMap;
6
7use serde::{Deserialize, Serialize};
8use url::Url;
9
10use super::contract::{DEFAULT_MEDIA_SCHEMES, DEFAULT_URL_SCHEMES};
11use super::js_trim;
12
13/// The catalog's built-in client functions: the basic 14 + round 1's 15
14/// core ones (`FUNCTION_NAMES`).
15pub const BUILTIN_FUNCTIONS: &[&str] = crate::generated::catalog::FUNCTION_NAMES;
16
17pub fn is_builtin_function(name: &str) -> bool {
18    BUILTIN_FUNCTIONS.contains(&name)
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(rename_all = "snake_case")]
23pub enum FunctionDecision {
24    Allow,
25    Ask,
26    Deny,
27    NotFound,
28}
29
30impl FunctionDecision {
31    pub fn as_str(self) -> &'static str {
32        match self {
33            FunctionDecision::Allow => "allow",
34            FunctionDecision::Ask => "ask",
35            FunctionDecision::Deny => "deny",
36            FunctionDecision::NotFound => "not_found",
37        }
38    }
39
40    pub fn parse(s: &str) -> Option<FunctionDecision> {
41        Some(match s {
42            "allow" => FunctionDecision::Allow,
43            "ask" => FunctionDecision::Ask,
44            "deny" => FunctionDecision::Deny,
45            "not_found" => FunctionDecision::NotFound,
46            _ => return None,
47        })
48    }
49
50    fn rank(self) -> u8 {
51        match self {
52            FunctionDecision::Allow => 0,
53            FunctionDecision::Ask => 1,
54            FunctionDecision::Deny => 2,
55            FunctionDecision::NotFound => 3,
56        }
57    }
58}
59
60#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
61pub struct FunctionPolicy {
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    pub allow: Option<Vec<String>>,
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub ask: Option<Vec<String>>,
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub deny: Option<Vec<String>>,
68    /// For a registered name no list matches; default `allow`.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub default: Option<FunctionDecision>,
71}
72
73/// `harness.*` matches `harness.toast`; anything else is exact.
74pub fn matches_pattern(pattern: &str, name: &str) -> bool {
75    match pattern.strip_suffix('*') {
76        Some(prefix) => name.starts_with(prefix),
77        None => pattern == name,
78    }
79}
80
81/// The gate: built-ins always run; an unregistered name is `not_found`; then
82/// deny wins, then allow, then ask, then the policy's default.
83pub fn decide_function(policy: Option<&FunctionPolicy>, name: &str, registered: bool) -> FunctionDecision {
84    if is_builtin_function(name) {
85        return FunctionDecision::Allow;
86    }
87    if !registered {
88        return FunctionDecision::NotFound;
89    }
90    let empty = FunctionPolicy::default();
91    let p = policy.unwrap_or(&empty);
92    let any = |list: &Option<Vec<String>>| list.iter().flatten().any(|pattern| matches_pattern(pattern, name));
93    if any(&p.deny) {
94        return FunctionDecision::Deny;
95    }
96    if any(&p.allow) {
97        return FunctionDecision::Allow;
98    }
99    if any(&p.ask) {
100        return FunctionDecision::Ask;
101    }
102    p.default.unwrap_or(FunctionDecision::Allow)
103}
104
105/// Two policies stacked (a package's allowlist under the host's own): the
106/// stricter decision wins.
107pub fn combine_decisions(a: FunctionDecision, b: FunctionDecision) -> FunctionDecision {
108    if a.rank() >= b.rank() {
109        a
110    } else {
111        b
112    }
113}
114
115/// A declarative package's `functions` list as a policy: listed = allow,
116/// anything else = deny.
117pub fn package_policy(functions: Option<&[String]>) -> FunctionPolicy {
118    FunctionPolicy { allow: Some(functions.map(<[String]>::to_vec).unwrap_or_default()), ask: None, deny: None, default: Some(FunctionDecision::Deny) }
119}
120
121#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
122pub struct UrlPolicy {
123    /// The schemes allowed; default [`DEFAULT_URL_SCHEMES`] (https, http,
124    /// mailto, tel). `["https"]` = https only.
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub schemes: Option<Vec<String>>,
127    /// http(s) hosts allowed: exact or `*.example.com`; unset = any.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub hosts: Option<Vec<String>>,
130    /// VAPP-107: private, loopback and link-local hosts
131    /// ([`is_private_host`]) are DENIED for http(s) unless listed here:
132    /// exact, `*.suffix`, or `*` for every private address. A `hosts`
133    /// allowlist does not opt one in.
134    #[serde(default, rename = "allowPrivate", skip_serializing_if = "Option::is_none")]
135    pub allow_private: Option<Vec<String>>,
136    #[serde(default, rename = "baseUrl", skip_serializing_if = "Option::is_none")]
137    pub base_url: Option<String>,
138}
139
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub struct UrlDecision {
142    pub allowed: bool,
143    /// The absolute url when it parses.
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub url: Option<String>,
146    /// `invalid` | `scheme` | `host` | `private`.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub reason: Option<String>,
149}
150
151/// `new URL(url)`, else `new URL(url, baseUrl)` (WHATWG both).
152fn absolute(url: &str, base_url: Option<&str>) -> Option<Url> {
153    if let Ok(u) = Url::parse(url) {
154        return Some(u);
155    }
156    let base = Url::parse(base_url?).ok()?;
157    base.join(url).ok()
158}
159
160fn host_matches(pattern: &str, host: &str) -> bool {
161    let p = pattern.to_lowercase();
162    match p.strip_prefix('*') {
163        Some(suffix) if p.starts_with("*.") => host.ends_with(suffix) && host.len() > suffix.len(),
164        _ => host == p,
165    }
166}
167
168/// The dotted-decimal IPv4 a WHATWG-parsed hostname is (the parser has
169/// already normalized `0x7f.1`, `2130706433` and the like), else `None`.
170fn ipv4(host: &str) -> Option<[u8; 4]> {
171    let mut out = [0u8; 4];
172    let mut n = 0;
173    for part in host.split('.') {
174        if n == 4 || part.is_empty() || part.len() > 3 || !part.bytes().all(|b| b.is_ascii_digit()) {
175            return None;
176        }
177        out[n] = part.parse().ok()?;
178        n += 1;
179    }
180    (n == 4).then_some(out)
181}
182
183/// A WHATWG-serialized IPv6 (`[...]`, lower-case hex, `::` once) as its
184/// eight 16-bit pieces, else `None`.
185fn ipv6(host: &str) -> Option<[u16; 8]> {
186    let text = host.strip_prefix('[')?.strip_suffix(']')?;
187    let pieces = |part: &str| -> Option<Vec<u16>> {
188        if part.is_empty() {
189            return Some(Vec::new());
190        }
191        part.split(':').map(|p| if (1..=4).contains(&p.len()) && p.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) { u16::from_str_radix(p, 16).ok() } else { None }).collect()
192    };
193    let mut out = [0u16; 8];
194    match text.split_once("::") {
195        None => {
196            let all = pieces(text)?;
197            if all.len() != 8 {
198                return None;
199            }
200            out.copy_from_slice(&all);
201        }
202        Some((head, tail)) => {
203            if tail.contains("::") {
204                return None;
205            }
206            let (head, tail) = (pieces(head)?, pieces(tail)?);
207            if head.len() + tail.len() > 7 {
208                return None;
209            }
210            out[..head.len()].copy_from_slice(&head);
211            out[8 - tail.len()..].copy_from_slice(&tail);
212        }
213    }
214    Some(out)
215}
216
217fn private_v4([a, b, _, _]: [u8; 4]) -> bool {
218    // 0.0.0.0/8 ("this" network), 10/8, 100.64/10 (CGNAT, release train
219    // 2026-10-23: a carrier's or a tailnet's internal range), 127/8
220    // (loopback), 169.254/16 (link-local), 172.16/12, 192.168/16.
221    a == 0 || a == 10 || (a == 100 && b & 0xc0 == 64) || a == 127 || (a == 169 && b == 254) || (a == 172 && (16..=31).contains(&b)) || (a == 192 && b == 168)
222}
223
224/// The IPv4 two 16-bit pieces carry.
225fn v4_of(hi: u16, lo: u16) -> [u8; 4] {
226    [(hi >> 8) as u8, (hi & 0xff) as u8, (lo >> 8) as u8, (lo & 0xff) as u8]
227}
228
229/// VAPP-107: is a parsed, lower-cased hostname one the URL and media policy
230/// deny by default (`catalog/host.json` urls.privateHosts)? `localhost` and
231/// `*.localhost`, `*.local` (mDNS), the IPv4 blocks 0/8, 10/8, 127/8,
232/// 169.254/16, 172.16/12, 192.168/16, 100.64/10, and IPv6 `::`, `::1`,
233/// fe80::/10, fc00::/7 plus a private IPv4 embedded IPv4-mapped
234/// (`::ffff:a.b.c.d`), IPv4-compatible (`::a.b.c.d`), NAT64
235/// (`64:ff9b::a.b.c.d`) or 6to4 (`2002:AABB:CCDD::`). LITERALS only:
236/// the policy never resolves names (a public name that resolves privately
237/// is the host network's job).
238pub fn is_private_host(hostname: &str) -> bool {
239    let lower = hostname.to_lowercase();
240    let host = lower.strip_suffix('.').unwrap_or(&lower);
241    if host == "localhost" || host.ends_with(".localhost") || host.ends_with(".local") {
242        return true;
243    }
244    if let Some(v4) = ipv4(host) {
245        return private_v4(v4);
246    }
247    let Some(v6) = ipv6(host) else { return false };
248    if v6.iter().all(|p| *p == 0) {
249        return true;
250    }
251    if v6[..7].iter().all(|p| *p == 0) && v6[7] == 1 {
252        return true;
253    }
254    if v6[0] & 0xffc0 == 0xfe80 || v6[0] & 0xfe00 == 0xfc00 {
255        return true;
256    }
257    // Release train 2026-10-23: every form that embeds an IPv4 reaches it
258    // (mapped ::ffff:0:0/96, compatible ::/96, NAT64 64:ff9b::/96, 6to4 2002::/16).
259    let mapped = v6[..5].iter().all(|p| *p == 0) && (v6[5] == 0xffff || v6[5] == 0);
260    let nat64 = v6[0] == 0x64 && v6[1] == 0xff9b && v6[2..6].iter().all(|p| *p == 0);
261    if mapped || nat64 {
262        return private_v4(v4_of(v6[6], v6[7]));
263    }
264    if v6[0] == 0x2002 {
265        return private_v4(v4_of(v6[1], v6[2]));
266    }
267    false
268}
269
270fn private_allowed(allow: Option<&Vec<String>>, host: &str) -> bool {
271    allow.iter().flat_map(|l| l.iter()).any(|p| p == "*" || host_matches(p, host))
272}
273
274/// The decision for a url: it must parse (relative against `base_url`), use
275/// one of `schemes`, and for http(s) match `hosts` when set and not be a
276/// private host unless `allow_private` covers it.
277pub fn decide_url(policy: Option<&UrlPolicy>, url: &str) -> UrlDecision {
278    let Some(parsed) = absolute(js_trim(url), policy.and_then(|p| p.base_url.as_deref())) else {
279        return UrlDecision { allowed: false, url: None, reason: Some("invalid".into()) };
280    };
281    let scheme = parsed.scheme().to_lowercase();
282    let href = parsed.as_str().to_string();
283    let allowed_scheme = match policy.and_then(|p| p.schemes.as_ref()) {
284        Some(list) => list.contains(&scheme),
285        None => DEFAULT_URL_SCHEMES.contains(&scheme.as_str()),
286    };
287    if !allowed_scheme {
288        return UrlDecision { allowed: false, url: Some(href), reason: Some("scheme".into()) };
289    }
290    if scheme == "http" || scheme == "https" {
291        let host = parsed.host_str().unwrap_or("").to_lowercase();
292        if let Some(hosts) = policy.and_then(|p| p.hosts.as_ref()) {
293            if !hosts.iter().any(|h| host_matches(h, &host)) {
294                return UrlDecision { allowed: false, url: Some(href), reason: Some("host".into()) };
295            }
296        }
297        if is_private_host(&host) && !private_allowed(policy.and_then(|p| p.allow_private.as_ref()), &host) {
298            return UrlDecision { allowed: false, url: Some(href), reason: Some("private".into()) };
299        }
300    }
301    UrlDecision { allowed: true, url: Some(href), reason: None }
302}
303
304#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
305pub struct MediaRule {
306    pub prefix: String,
307    #[serde(default)]
308    pub headers: BTreeMap<String, String>,
309}
310
311#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
312pub struct MediaOptions {
313    #[serde(default, rename = "baseUrl", skip_serializing_if = "Option::is_none")]
314    pub base_url: Option<String>,
315    #[serde(default, skip_serializing_if = "Option::is_none")]
316    pub rules: Option<Vec<MediaRule>>,
317    /// The schemes a src may use; default [`DEFAULT_MEDIA_SCHEMES`] (https,
318    /// http, data). `file` only when listed.
319    #[serde(default, skip_serializing_if = "Option::is_none")]
320    pub schemes: Option<Vec<String>>,
321    /// http(s) hosts media may load from: exact or `*.example.com`; unset = any.
322    #[serde(default, skip_serializing_if = "Option::is_none")]
323    pub hosts: Option<Vec<String>>,
324    /// VAPP-107: the private hosts media may load from ([`UrlPolicy::allow_private`]).
325    #[serde(default, rename = "allowPrivate", skip_serializing_if = "Option::is_none")]
326    pub allow_private: Option<Vec<String>>,
327}
328
329#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
330pub struct MediaRequest {
331    pub url: String,
332    /// Sorted by name.
333    pub headers: BTreeMap<String, String>,
334}
335
336/// The image / media loader's request: the absolute url plus the headers of
337/// every rule whose prefix it starts with (later rules win per header).
338/// `None` when the url does not resolve or the media policy (schemes, hosts)
339/// denies it: nothing loads.
340pub fn media_request(url: &str, options: &MediaOptions) -> Option<MediaRequest> {
341    let policy = UrlPolicy {
342        schemes: Some(options.schemes.clone().unwrap_or_else(|| DEFAULT_MEDIA_SCHEMES.iter().map(|s| s.to_string()).collect())),
343        hosts: options.hosts.clone(),
344        allow_private: options.allow_private.clone(),
345        base_url: options.base_url.clone(),
346    };
347    let decision = decide_url(Some(&policy), url);
348    if !decision.allowed {
349        return None;
350    }
351    let href = decision.url?;
352    let mut headers = BTreeMap::new();
353    for rule in options.rules.iter().flatten() {
354        if href.starts_with(&rule.prefix) {
355            headers.extend(rule.headers.iter().map(|(k, v)| (k.clone(), v.clone())));
356        }
357    }
358    Some(MediaRequest { url: href, headers })
359}
360
361/// #EXP-1674 (`catalog/host.json` urls): one piece of a host's `text_links`
362/// answer for a `hostLinks` Text.
363#[derive(Debug, Clone, PartialEq, Eq)]
364pub struct TextLink {
365    pub text: String,
366    pub href: Option<String>,
367}
368
369/// A host's `text_links` answer ready to paint, or `None` for the plain text:
370/// the segments must concatenate back to `text`; an href the policy denies
371/// stays text; no allowed link = plain.
372pub fn police_text_links(policy: Option<&UrlPolicy>, text: &str, segments: Vec<TextLink>) -> Option<Vec<TextLink>> {
373    if segments.iter().map(|segment| segment.text.as_str()).collect::<String>() != text {
374        return None;
375    }
376    let policed: Vec<TextLink> = segments
377        .into_iter()
378        .map(|segment| TextLink {
379            href: segment.href.and_then(|href| safe_href(policy, &href)),
380            text: segment.text,
381        })
382        .collect();
383    policed.iter().any(|segment| segment.href.is_some()).then_some(policed)
384}
385
386/// The href a renderer may navigate to (Link, markdown links, FileUpload
387/// file urls), or `None` when the URL policy denies it.
388pub fn safe_href(policy: Option<&UrlPolicy>, url: &str) -> Option<String> {
389    if url.is_empty() {
390        return None;
391    }
392    let d = decide_url(policy, url);
393    if d.allowed {
394        d.url
395    } else {
396        None
397    }
398}
399
400/// Width × height from an image's header (PNG, JPEG, GIF, WebP, BMP) or an
401/// SVG's root `width`/`height`/`viewBox` without decoding it — what a
402/// loader checks against [`super::contract::MEDIA_MAX_PIXELS`] BEFORE
403/// decoding. `None` = not a header this reads (truncated bytes, another
404/// format). VAPP-103 rfix: an SVG has a size ([`svg_dimensions`]).
405pub fn image_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
406    if is_svg(bytes) {
407        return svg_dimensions(bytes);
408    }
409    let be16 = |i: usize| bytes.get(i..i + 2).map(|b| u16::from_be_bytes([b[0], b[1]]) as u32);
410    let le16 = |i: usize| bytes.get(i..i + 2).map(|b| u16::from_le_bytes([b[0], b[1]]) as u32);
411    let be32 = |i: usize| bytes.get(i..i + 4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]));
412    let le32 = |i: usize| bytes.get(i..i + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
413    let le24 = |i: usize| bytes.get(i..i + 3).map(|b| u32::from_le_bytes([b[0], b[1], b[2], 0]));
414    if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
415        return Some((be32(16)?, be32(20)?));
416    }
417    if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
418        return Some((le16(6)?, le16(8)?));
419    }
420    if bytes.starts_with(b"BM") {
421        let h = le32(22)? as i32;
422        return Some((le32(18)?, h.unsigned_abs()));
423    }
424    if bytes.len() >= 30 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
425        return match &bytes[12..16] {
426            b"VP8 " => Some((le16(26)? & 0x3fff, le16(28)? & 0x3fff)),
427            b"VP8L" => {
428                let b = le32(21)?;
429                Some(((b & 0x3fff) + 1, ((b >> 14) & 0x3fff) + 1))
430            }
431            b"VP8X" => Some((le24(24)? + 1, le24(27)? + 1)),
432            _ => None,
433        };
434    }
435    if bytes.starts_with(b"\xff\xd8") {
436        let mut i = 2;
437        while i + 4 <= bytes.len() {
438            if bytes[i] != 0xff {
439                i += 1;
440                continue;
441            }
442            let marker = bytes[i + 1];
443            if marker == 0xff {
444                i += 1;
445                continue;
446            }
447            if marker == 0xd8 || marker == 0x01 || (0xd0..=0xd7).contains(&marker) {
448                i += 2;
449                continue;
450            }
451            let len = be16(i + 2)? as usize;
452            // SOF0..SOF15 except DHT (c4), JPG (c8), DAC (cc).
453            if (0xc0..=0xcf).contains(&marker) && marker != 0xc4 && marker != 0xc8 && marker != 0xcc {
454                return Some((be16(i + 7)?, be16(i + 5)?));
455            }
456            i += 2 + len;
457        }
458        return None;
459    }
460    None
461}
462
463/// An SVG by its first non-blank bytes (`<svg` or `<?xml`), like the
464/// loaders sniff it.
465fn is_svg(bytes: &[u8]) -> bool {
466    let head = &bytes[..bytes.len().min(256)];
467    let start = head.iter().position(|b| !b.is_ascii_whitespace()).unwrap_or(head.len());
468    let head = &head[start..];
469    let lower = |p: &[u8]| head.len() >= p.len() && head[..p.len()].eq_ignore_ascii_case(p);
470    lower(b"<svg") || lower(b"<?xml")
471}
472
473/// The size an SVG rasterizes at: its root's `width`/`height` (px, or
474/// pt/pc/in/cm/mm/em/ex converted at 96 dpi and a 16 px em; `%` = unset);
475/// a missing one follows the `viewBox` aspect, both missing = the
476/// `viewBox` size, no `viewBox` = 100 (usvg's default). `None` = no `<svg`
477/// root tag.
478pub fn svg_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
479    let at = bytes.windows(4).position(|w| w == b"<svg")?;
480    let end = bytes[at..].iter().position(|b| *b == b'>').map_or(bytes.len(), |e| at + e);
481    let tag = String::from_utf8_lossy(&bytes[at + 4..end]);
482    let (mut width, mut height, mut view_box) = (None, None, None);
483    let t = tag.as_bytes();
484    let mut i = 0;
485    while i < t.len() {
486        if !(t[i].is_ascii_alphabetic() || t[i] == b'_' || t[i] == b':') || i == 0 || !t[i - 1].is_ascii_whitespace() {
487            i += 1;
488            continue;
489        }
490        let name_start = i;
491        while i < t.len() && (t[i].is_ascii_alphanumeric() || matches!(t[i], b'_' | b':' | b'-' | b'.')) {
492            i += 1;
493        }
494        let name = &tag[name_start..i];
495        while i < t.len() && t[i].is_ascii_whitespace() {
496            i += 1;
497        }
498        if t.get(i) != Some(&b'=') {
499            continue;
500        }
501        i += 1;
502        while i < t.len() && t[i].is_ascii_whitespace() {
503            i += 1;
504        }
505        let Some(&q) = t.get(i).filter(|q| **q == b'"' || **q == b'\'') else { continue };
506        let value_start = i + 1;
507        let value_end = t[value_start..].iter().position(|b| *b == q).map_or(t.len(), |e| value_start + e);
508        let value = &tag[value_start..value_end];
509        match name {
510            "width" => width = svg_length(value),
511            "height" => height = svg_length(value),
512            "viewBox" => view_box = svg_view_box(value),
513            _ => {}
514        }
515        i = value_end + 1;
516    }
517    let (w, h) = match (width, height, view_box) {
518        (Some(w), Some(h), _) => (w, h),
519        (Some(w), None, Some((vw, vh))) => (w, w * vh / vw),
520        (None, Some(h), Some((vw, vh))) => (h * vw / vh, h),
521        (Some(w), None, None) => (w, 100.0),
522        (None, Some(h), None) => (100.0, h),
523        (None, None, Some((vw, vh))) => (vw, vh),
524        (None, None, None) => (100.0, 100.0),
525    };
526    let px = |v: f64| if v.is_finite() { v.ceil().clamp(0.0, u32::MAX as f64) as u32 } else { u32::MAX };
527    Some((px(w), px(h)))
528}
529
530/// An SVG length in px (`None` = a percentage, unknown unit, negative or
531/// not a number).
532fn svg_length(value: &str) -> Option<f64> {
533    let v = value.trim();
534    let split = v.find(|c: char| !(c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E'))).unwrap_or(v.len());
535    // An exponent `e` followed by no digit belongs to the unit (`em`, `ex`).
536    let (mut num, mut unit) = v.split_at(split);
537    if let Some(stripped) = num.strip_suffix(['e', 'E']) {
538        num = stripped;
539        unit = &v[num.len()..];
540    }
541    let n: f64 = num.parse().ok()?;
542    let scale = match unit.trim() {
543        "" | "px" => 1.0,
544        "pt" => 4.0 / 3.0,
545        "pc" => 16.0,
546        "in" => 96.0,
547        "cm" => 96.0 / 2.54,
548        "mm" => 96.0 / 25.4,
549        "em" => 16.0,
550        "ex" => 8.0,
551        _ => return None,
552    };
553    (n.is_finite() && n >= 0.0).then_some(n * scale)
554}
555
556/// A `viewBox`'s width and height (`None` unless both are > 0).
557fn svg_view_box(value: &str) -> Option<(f64, f64)> {
558    let parts: Vec<f64> = value.split(|c: char| c.is_ascii_whitespace() || c == ',').filter(|p| !p.is_empty()).map(str::parse).collect::<Result<_, _>>().ok()?;
559    match parts[..] {
560        [_, _, w, h] if w > 0.0 && h > 0.0 && w.is_finite() && h.is_finite() => Some((w, h)),
561        _ => None,
562    }
563}
564
565/// The frames an image decodes into: a GIF's image descriptors, an APNG's
566/// `acTL` count, an animated WebP's `ANMF` chunks; 1 otherwise (and for a
567/// truncated header, the frames found).
568pub fn image_frames(bytes: &[u8]) -> u32 {
569    let le32 = |i: usize| bytes.get(i..i + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize);
570    let be32 = |i: usize| bytes.get(i..i + 4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as usize);
571    let frames = if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
572        let skip_blocks = |mut i: usize| -> usize {
573            while let Some(&n) = bytes.get(i) {
574                i += 1 + n as usize;
575                if n == 0 {
576                    break;
577                }
578            }
579            i
580        };
581        let table = |packed: u8| if packed & 0x80 != 0 { 3usize << ((packed & 7) + 1) } else { 0 };
582        let mut i = 13 + bytes.get(10).map_or(0, |p| table(*p));
583        let mut count = 0u32;
584        loop {
585            match bytes.get(i) {
586                Some(0x2c) => {
587                    count = count.saturating_add(1);
588                    let Some(&packed) = bytes.get(i + 9) else { break };
589                    i = skip_blocks(i + 10 + table(packed) + 1);
590                }
591                Some(0x21) => i = skip_blocks(i + 2),
592                _ => break,
593            }
594        }
595        count
596    } else if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
597        let mut i = 8;
598        let mut count = 1;
599        while let (Some(len), Some(kind)) = (be32(i), bytes.get(i + 4..i + 8)) {
600            if kind == b"acTL" {
601                count = be32(i + 8).map_or(1, |n| n.min(u32::MAX as usize) as u32);
602                break;
603            }
604            if kind == b"IDAT" {
605                break;
606            }
607            i = match i.checked_add(12 + len) {
608                Some(next) => next,
609                None => break,
610            };
611        }
612        count
613    } else if bytes.len() >= 21 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" && &bytes[12..16] == b"VP8X" && bytes[20] & 0x02 != 0 {
614        let mut i = 12;
615        let mut count = 0u32;
616        while let (Some(kind), Some(size)) = (bytes.get(i..i + 4), le32(i + 4)) {
617            if kind == b"ANMF" {
618                count = count.saturating_add(1);
619            }
620            i = match i.checked_add(8 + size + (size & 1)) {
621                Some(next) => next,
622                None => break,
623            };
624        }
625        count
626    } else {
627        1
628    };
629    frames.max(1)
630}
631
632/// What a whole image's bytes say before any decode (VAPP-103): no known
633/// image format, a raster (PNG, JPEG, GIF, WebP, BMP) or SVG whose size
634/// cannot be read, or its size and [`image_frames`]. Every renderer's
635/// pixel cap reads this ONE answer (the natives through the FFI).
636#[derive(Debug, Clone, Copy, PartialEq, Eq)]
637pub enum ImageHeader {
638    Unknown,
639    Unreadable,
640    Size { width: u32, height: u32, frames: u32 },
641}
642
643pub fn image_header(bytes: &[u8]) -> ImageHeader {
644    let raster = bytes.starts_with(b"\x89PNG\r\n\x1a\n")
645        || bytes.starts_with(b"GIF87a")
646        || bytes.starts_with(b"GIF89a")
647        || bytes.starts_with(b"BM")
648        || bytes.starts_with(b"\xff\xd8")
649        || (bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP");
650    if !raster && !is_svg(bytes) {
651        return ImageHeader::Unknown;
652    }
653    match image_dimensions(bytes) {
654        Some((width, height)) => ImageHeader::Size { width, height, frames: image_frames(bytes) },
655        None => ImageHeader::Unreadable,
656    }
657}
658
659/// VAPP-103 rfix: the pixel cap on a whole image before it decodes, under
660/// `max_bytes` / `max_pixels`: a raster format or an SVG whose size cannot
661/// be read is REFUSED (`media: image dimensions unreadable`), and width ×
662/// height × [`image_frames`] must fit `max_pixels` (`media is W×H × N
663/// frames, over … pixels`). Bytes of no known image format pass (the
664/// decoder refuses them).
665pub fn media_image_check(bytes: &[u8], max_bytes: u64, max_pixels: u64) -> Result<(), String> {
666    if bytes.len() as u64 > max_bytes {
667        return Err(format!("media is over {max_bytes} bytes"));
668    }
669    match image_header(bytes) {
670        ImageHeader::Unknown => Ok(()),
671        ImageHeader::Unreadable => Err("media: image dimensions unreadable".into()),
672        ImageHeader::Size { width: w, height: h, frames } if frames <= 1 => {
673            if w as u128 * h as u128 > max_pixels as u128 {
674                return Err(format!("media is {w}×{h}, over {max_pixels} pixels"));
675            }
676            Ok(())
677        }
678        ImageHeader::Size { width: w, height: h, frames } => {
679            if w as u128 * h as u128 * frames as u128 > max_pixels as u128 {
680                return Err(format!("media is {w}×{h} × {frames} frames, over {max_pixels} pixels"));
681            }
682            Ok(())
683        }
684    }
685}
686
687/// [`media_image_check`] under the contract's `media.limits`.
688pub fn media_image_within_limits(bytes: &[u8]) -> Result<(), String> {
689    use super::contract::{MEDIA_MAX_BYTES, MEDIA_MAX_PIXELS};
690    media_image_check(bytes, MEDIA_MAX_BYTES, MEDIA_MAX_PIXELS)
691}
692
693/// Whether a load fits `media.limits`: `bytes` read so far (or the
694/// Content-Length) and, once the header is in, the image's pixels.
695pub fn media_within_limits(bytes: u64, dimensions: Option<(u32, u32)>) -> Result<(), String> {
696    use super::contract::{MEDIA_MAX_BYTES, MEDIA_MAX_PIXELS};
697    if bytes > MEDIA_MAX_BYTES {
698        return Err(format!("media is over {MEDIA_MAX_BYTES} bytes"));
699    }
700    if let Some((w, h)) = dimensions {
701        if w as u64 * h as u64 > MEDIA_MAX_PIXELS {
702            return Err(format!("media is {w}×{h}, over {MEDIA_MAX_PIXELS} pixels"));
703        }
704    }
705    Ok(())
706}
707
708#[cfg(test)]
709mod tests {
710    use super::*;
711
712    /// VAPP-103 rfix: SVGs have a size, frames multiply the pixels, and a
713    /// raster whose dimensions cannot be read is refused (it failed open).
714    #[test]
715    fn svg_sizes_animation_frames_and_unreadable_rasters_meet_the_pixel_cap() {
716        assert_eq!(svg_dimensions(br#"<svg xmlns="http://www.w3.org/2000/svg" width="20000" height="20000"/>"#), Some((20_000, 20_000)));
717        assert!(media_image_within_limits(br#"<svg width="20000" height="20000"></svg>"#).unwrap_err().contains("20000×20000"));
718        assert_eq!(svg_dimensions(br#"<?xml version="1.0"?><svg viewBox="0 0 300 150"/>"#), Some((300, 150)));
719        assert_eq!(svg_dimensions(br#"<svg width="100000" viewBox="0 0 1 1">"#), Some((100_000, 100_000)), "a missing height follows the viewBox aspect");
720        assert_eq!(svg_dimensions(br#"<svg width="2in" height="10em">"#), Some((192, 160)));
721        assert_eq!(svg_dimensions(br#"<svg width="50%">"#), Some((100, 100)));
722        assert_eq!(svg_dimensions(b"<svg>"), Some((100, 100)));
723        assert!(media_image_within_limits(br#"<svg width="24" height="24"/>"#).is_ok());
724        assert!(media_image_within_limits(b"<?xml version='1.0'?><note/>").unwrap_err().contains("unreadable"));
725        // A 1000×1000 GIF with 40 frames: 40 Mpx decoded.
726        let mut gif = b"GIF89a".to_vec();
727        gif.extend_from_slice(&1000u16.to_le_bytes());
728        gif.extend_from_slice(&1000u16.to_le_bytes());
729        gif.extend_from_slice(&[0, 0, 0]);
730        for _ in 0..40 {
731            gif.extend_from_slice(&[0x21, 0xf9, 4, 0, 0, 0, 0, 0]);
732            gif.extend_from_slice(&[0x2c, 0, 0, 0, 0, 0xe8, 3, 0xe8, 3, 0, 2, 2, 0x4c, 1, 0]);
733        }
734        gif.push(0x3b);
735        assert_eq!(image_frames(&gif), 40);
736        assert!(media_image_within_limits(&gif).unwrap_err().contains("40 frames"));
737        assert_eq!(image_frames(&gif[..gif.len() / 2]), 20, "a truncated GIF counts the frames it holds");
738        // An APNG announcing 100 frames of 1000×1000.
739        let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
740        png.extend_from_slice(&1000u32.to_be_bytes());
741        png.extend_from_slice(&1000u32.to_be_bytes());
742        png.extend_from_slice(&[8, 6, 0, 0, 0, 0, 0, 0, 0]);
743        png.extend_from_slice(b"\0\0\0\x08acTL");
744        png.extend_from_slice(&100u32.to_be_bytes());
745        png.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]);
746        assert_eq!(image_frames(&png), 100);
747        assert!(media_image_within_limits(&png).is_err());
748        // An animated WebP canvas of 2000×2000 with 10 ANMF chunks.
749        let mut webp = b"RIFF\0\0\0\0WEBPVP8X\x0a\0\0\0\x02\0\0\0".to_vec();
750        webp.extend_from_slice(&1999u32.to_le_bytes()[..3]);
751        webp.extend_from_slice(&1999u32.to_le_bytes()[..3]);
752        for _ in 0..10 {
753            webp.extend_from_slice(b"ANMF\x02\0\0\0ab");
754        }
755        assert_eq!(image_dimensions(&webp), Some((2000, 2000)));
756        assert_eq!(image_frames(&webp), 10);
757        assert!(media_image_within_limits(&webp).unwrap_err().contains("10 frames"));
758        // A raster header too short to read is refused, not passed.
759        assert!(media_image_within_limits(b"\x89PNG\r\n\x1a\n\0\0").unwrap_err().contains("unreadable"));
760        assert!(media_image_within_limits(b"\xff\xd8\xff\xe0").unwrap_err().contains("unreadable"));
761        assert!(media_image_within_limits(b"{\"not\": \"an image\"}").is_ok());
762        assert!(media_image_within_limits(b"GIF89a\x10\0\x20\0").is_ok());
763    }
764
765    #[test]
766    fn image_headers_give_dimensions_without_decoding() {
767        let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
768        png.extend_from_slice(&40_000u32.to_be_bytes());
769        png.extend_from_slice(&30_000u32.to_be_bytes());
770        assert_eq!(image_dimensions(&png), Some((40_000, 30_000)));
771        assert!(media_within_limits(1024, image_dimensions(&png)).is_err());
772        assert_eq!(image_dimensions(b"GIF89a\x10\0\x20\0"), Some((16, 32)));
773        // JPEG: SOI, an APP0 segment, then SOF0 (height 0x0100, width 0x0200).
774        let jpeg = b"\xff\xd8\xff\xe0\0\x04ab\xff\xc0\0\x11\x08\x01\x00\x02\x00\x03";
775        assert_eq!(image_dimensions(jpeg), Some((512, 256)));
776        assert_eq!(image_dimensions(b"<svg/>"), Some((100, 100)));
777        assert!(media_within_limits(crate::host::MEDIA_MAX_BYTES + 1, None).is_err());
778        assert!(media_within_limits(10, Some((100, 100))).is_ok());
779    }
780
781    /// VAPP-107: the literal forms the WHATWG parser leaves behind.
782    #[test]
783    fn private_hosts_are_literals_in_every_normalized_form() {
784        for h in ["localhost", "LOCALHOST.", "app.localhost", "printer.local", "127.0.0.1", "127.255.0.9", "10.1.2.3", "172.16.0.1", "172.31.9.9", "192.168.0.1", "169.254.169.254", "0.0.0.0", "[::1]", "[::]", "[fe80::1]", "[febf::1]", "[fc00::1]", "[fdab:1::2]", "[::ffff:7f00:1]", "[::ffff:c0a8:101]", "100.64.0.1", "100.127.255.255", "[::7f00:1]", "[64:ff9b::7f00:1]", "[2002:7f00:1::]", "[2002:a00:1::1]"] {
785            assert!(is_private_host(h), "{h} is private");
786        }
787        for h in ["exponential.at", "8.8.8.8", "172.32.0.1", "172.15.0.1", "11.0.0.1", "192.169.0.1", "[2001:db8::1]", "[::ffff:808:808]", "[fec0::1]", "localhost.example", "mylocal.example", "256.1.1.1", "1.2.3", "[::1", "[::ffff::1]", "100.63.255.255", "100.128.0.1", "[::808:808]", "[64:ff9b::808:808]", "[2002:808:808::]"] {
788            assert!(!is_private_host(h), "{h} is not private");
789        }
790        assert_eq!(decide_url(None, "http://[::FFFF:127.0.0.1]/").reason.as_deref(), Some("private"));
791        let opt = UrlPolicy { allow_private: Some(vec!["localhost".into()]), ..Default::default() };
792        assert!(decide_url(Some(&opt), "http://localhost:3000/").allowed);
793        assert_eq!(decide_url(Some(&opt), "http://127.0.0.1:3000/").reason.as_deref(), Some("private"));
794    }
795
796    #[test]
797    fn hrefs_pass_the_url_policy() {
798        assert_eq!(safe_href(None, "javascript:alert(1)"), None);
799        assert_eq!(safe_href(None, "https://exponential.at/x").as_deref(), Some("https://exponential.at/x"));
800        let hosts = UrlPolicy { hosts: Some(vec!["exponential.at".into()]), ..Default::default() };
801        assert_eq!(safe_href(Some(&hosts), "https://evil.example/"), None);
802    }
803}