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/// The href a renderer may navigate to (Link, markdown links, FileUpload
362/// file urls), or `None` when the URL policy denies it.
363pub fn safe_href(policy: Option<&UrlPolicy>, url: &str) -> Option<String> {
364    if url.is_empty() {
365        return None;
366    }
367    let d = decide_url(policy, url);
368    if d.allowed {
369        d.url
370    } else {
371        None
372    }
373}
374
375/// Width × height from an image's header (PNG, JPEG, GIF, WebP, BMP) or an
376/// SVG's root `width`/`height`/`viewBox` without decoding it — what a
377/// loader checks against [`super::contract::MEDIA_MAX_PIXELS`] BEFORE
378/// decoding. `None` = not a header this reads (truncated bytes, another
379/// format). VAPP-103 rfix: an SVG has a size ([`svg_dimensions`]).
380pub fn image_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
381    if is_svg(bytes) {
382        return svg_dimensions(bytes);
383    }
384    let be16 = |i: usize| bytes.get(i..i + 2).map(|b| u16::from_be_bytes([b[0], b[1]]) as u32);
385    let le16 = |i: usize| bytes.get(i..i + 2).map(|b| u16::from_le_bytes([b[0], b[1]]) as u32);
386    let be32 = |i: usize| bytes.get(i..i + 4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]));
387    let le32 = |i: usize| bytes.get(i..i + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
388    let le24 = |i: usize| bytes.get(i..i + 3).map(|b| u32::from_le_bytes([b[0], b[1], b[2], 0]));
389    if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
390        return Some((be32(16)?, be32(20)?));
391    }
392    if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
393        return Some((le16(6)?, le16(8)?));
394    }
395    if bytes.starts_with(b"BM") {
396        let h = le32(22)? as i32;
397        return Some((le32(18)?, h.unsigned_abs()));
398    }
399    if bytes.len() >= 30 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
400        return match &bytes[12..16] {
401            b"VP8 " => Some((le16(26)? & 0x3fff, le16(28)? & 0x3fff)),
402            b"VP8L" => {
403                let b = le32(21)?;
404                Some(((b & 0x3fff) + 1, ((b >> 14) & 0x3fff) + 1))
405            }
406            b"VP8X" => Some((le24(24)? + 1, le24(27)? + 1)),
407            _ => None,
408        };
409    }
410    if bytes.starts_with(b"\xff\xd8") {
411        let mut i = 2;
412        while i + 4 <= bytes.len() {
413            if bytes[i] != 0xff {
414                i += 1;
415                continue;
416            }
417            let marker = bytes[i + 1];
418            if marker == 0xff {
419                i += 1;
420                continue;
421            }
422            if marker == 0xd8 || marker == 0x01 || (0xd0..=0xd7).contains(&marker) {
423                i += 2;
424                continue;
425            }
426            let len = be16(i + 2)? as usize;
427            // SOF0..SOF15 except DHT (c4), JPG (c8), DAC (cc).
428            if (0xc0..=0xcf).contains(&marker) && marker != 0xc4 && marker != 0xc8 && marker != 0xcc {
429                return Some((be16(i + 7)?, be16(i + 5)?));
430            }
431            i += 2 + len;
432        }
433        return None;
434    }
435    None
436}
437
438/// An SVG by its first non-blank bytes (`<svg` or `<?xml`), like the
439/// loaders sniff it.
440fn is_svg(bytes: &[u8]) -> bool {
441    let head = &bytes[..bytes.len().min(256)];
442    let start = head.iter().position(|b| !b.is_ascii_whitespace()).unwrap_or(head.len());
443    let head = &head[start..];
444    let lower = |p: &[u8]| head.len() >= p.len() && head[..p.len()].eq_ignore_ascii_case(p);
445    lower(b"<svg") || lower(b"<?xml")
446}
447
448/// The size an SVG rasterizes at: its root's `width`/`height` (px, or
449/// pt/pc/in/cm/mm/em/ex converted at 96 dpi and a 16 px em; `%` = unset);
450/// a missing one follows the `viewBox` aspect, both missing = the
451/// `viewBox` size, no `viewBox` = 100 (usvg's default). `None` = no `<svg`
452/// root tag.
453pub fn svg_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
454    let at = bytes.windows(4).position(|w| w == b"<svg")?;
455    let end = bytes[at..].iter().position(|b| *b == b'>').map_or(bytes.len(), |e| at + e);
456    let tag = String::from_utf8_lossy(&bytes[at + 4..end]);
457    let (mut width, mut height, mut view_box) = (None, None, None);
458    let t = tag.as_bytes();
459    let mut i = 0;
460    while i < t.len() {
461        if !(t[i].is_ascii_alphabetic() || t[i] == b'_' || t[i] == b':') || i == 0 || !t[i - 1].is_ascii_whitespace() {
462            i += 1;
463            continue;
464        }
465        let name_start = i;
466        while i < t.len() && (t[i].is_ascii_alphanumeric() || matches!(t[i], b'_' | b':' | b'-' | b'.')) {
467            i += 1;
468        }
469        let name = &tag[name_start..i];
470        while i < t.len() && t[i].is_ascii_whitespace() {
471            i += 1;
472        }
473        if t.get(i) != Some(&b'=') {
474            continue;
475        }
476        i += 1;
477        while i < t.len() && t[i].is_ascii_whitespace() {
478            i += 1;
479        }
480        let Some(&q) = t.get(i).filter(|q| **q == b'"' || **q == b'\'') else { continue };
481        let value_start = i + 1;
482        let value_end = t[value_start..].iter().position(|b| *b == q).map_or(t.len(), |e| value_start + e);
483        let value = &tag[value_start..value_end];
484        match name {
485            "width" => width = svg_length(value),
486            "height" => height = svg_length(value),
487            "viewBox" => view_box = svg_view_box(value),
488            _ => {}
489        }
490        i = value_end + 1;
491    }
492    let (w, h) = match (width, height, view_box) {
493        (Some(w), Some(h), _) => (w, h),
494        (Some(w), None, Some((vw, vh))) => (w, w * vh / vw),
495        (None, Some(h), Some((vw, vh))) => (h * vw / vh, h),
496        (Some(w), None, None) => (w, 100.0),
497        (None, Some(h), None) => (100.0, h),
498        (None, None, Some((vw, vh))) => (vw, vh),
499        (None, None, None) => (100.0, 100.0),
500    };
501    let px = |v: f64| if v.is_finite() { v.ceil().clamp(0.0, u32::MAX as f64) as u32 } else { u32::MAX };
502    Some((px(w), px(h)))
503}
504
505/// An SVG length in px (`None` = a percentage, unknown unit, negative or
506/// not a number).
507fn svg_length(value: &str) -> Option<f64> {
508    let v = value.trim();
509    let split = v.find(|c: char| !(c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E'))).unwrap_or(v.len());
510    // An exponent `e` followed by no digit belongs to the unit (`em`, `ex`).
511    let (mut num, mut unit) = v.split_at(split);
512    if let Some(stripped) = num.strip_suffix(['e', 'E']) {
513        num = stripped;
514        unit = &v[num.len()..];
515    }
516    let n: f64 = num.parse().ok()?;
517    let scale = match unit.trim() {
518        "" | "px" => 1.0,
519        "pt" => 4.0 / 3.0,
520        "pc" => 16.0,
521        "in" => 96.0,
522        "cm" => 96.0 / 2.54,
523        "mm" => 96.0 / 25.4,
524        "em" => 16.0,
525        "ex" => 8.0,
526        _ => return None,
527    };
528    (n.is_finite() && n >= 0.0).then_some(n * scale)
529}
530
531/// A `viewBox`'s width and height (`None` unless both are > 0).
532fn svg_view_box(value: &str) -> Option<(f64, f64)> {
533    let parts: Vec<f64> = value.split(|c: char| c.is_ascii_whitespace() || c == ',').filter(|p| !p.is_empty()).map(str::parse).collect::<Result<_, _>>().ok()?;
534    match parts[..] {
535        [_, _, w, h] if w > 0.0 && h > 0.0 && w.is_finite() && h.is_finite() => Some((w, h)),
536        _ => None,
537    }
538}
539
540/// The frames an image decodes into: a GIF's image descriptors, an APNG's
541/// `acTL` count, an animated WebP's `ANMF` chunks; 1 otherwise (and for a
542/// truncated header, the frames found).
543pub fn image_frames(bytes: &[u8]) -> u32 {
544    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);
545    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);
546    let frames = if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
547        let skip_blocks = |mut i: usize| -> usize {
548            while let Some(&n) = bytes.get(i) {
549                i += 1 + n as usize;
550                if n == 0 {
551                    break;
552                }
553            }
554            i
555        };
556        let table = |packed: u8| if packed & 0x80 != 0 { 3usize << ((packed & 7) + 1) } else { 0 };
557        let mut i = 13 + bytes.get(10).map_or(0, |p| table(*p));
558        let mut count = 0u32;
559        loop {
560            match bytes.get(i) {
561                Some(0x2c) => {
562                    count = count.saturating_add(1);
563                    let Some(&packed) = bytes.get(i + 9) else { break };
564                    i = skip_blocks(i + 10 + table(packed) + 1);
565                }
566                Some(0x21) => i = skip_blocks(i + 2),
567                _ => break,
568            }
569        }
570        count
571    } else if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
572        let mut i = 8;
573        let mut count = 1;
574        while let (Some(len), Some(kind)) = (be32(i), bytes.get(i + 4..i + 8)) {
575            if kind == b"acTL" {
576                count = be32(i + 8).map_or(1, |n| n.min(u32::MAX as usize) as u32);
577                break;
578            }
579            if kind == b"IDAT" {
580                break;
581            }
582            i = match i.checked_add(12 + len) {
583                Some(next) => next,
584                None => break,
585            };
586        }
587        count
588    } else if bytes.len() >= 21 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" && &bytes[12..16] == b"VP8X" && bytes[20] & 0x02 != 0 {
589        let mut i = 12;
590        let mut count = 0u32;
591        while let (Some(kind), Some(size)) = (bytes.get(i..i + 4), le32(i + 4)) {
592            if kind == b"ANMF" {
593                count = count.saturating_add(1);
594            }
595            i = match i.checked_add(8 + size + (size & 1)) {
596                Some(next) => next,
597                None => break,
598            };
599        }
600        count
601    } else {
602        1
603    };
604    frames.max(1)
605}
606
607/// What a whole image's bytes say before any decode (VAPP-103): no known
608/// image format, a raster (PNG, JPEG, GIF, WebP, BMP) or SVG whose size
609/// cannot be read, or its size and [`image_frames`]. Every renderer's
610/// pixel cap reads this ONE answer (the natives through the FFI).
611#[derive(Debug, Clone, Copy, PartialEq, Eq)]
612pub enum ImageHeader {
613    Unknown,
614    Unreadable,
615    Size { width: u32, height: u32, frames: u32 },
616}
617
618pub fn image_header(bytes: &[u8]) -> ImageHeader {
619    let raster = bytes.starts_with(b"\x89PNG\r\n\x1a\n")
620        || bytes.starts_with(b"GIF87a")
621        || bytes.starts_with(b"GIF89a")
622        || bytes.starts_with(b"BM")
623        || bytes.starts_with(b"\xff\xd8")
624        || (bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP");
625    if !raster && !is_svg(bytes) {
626        return ImageHeader::Unknown;
627    }
628    match image_dimensions(bytes) {
629        Some((width, height)) => ImageHeader::Size { width, height, frames: image_frames(bytes) },
630        None => ImageHeader::Unreadable,
631    }
632}
633
634/// VAPP-103 rfix: the pixel cap on a whole image before it decodes, under
635/// `max_bytes` / `max_pixels`: a raster format or an SVG whose size cannot
636/// be read is REFUSED (`media: image dimensions unreadable`), and width ×
637/// height × [`image_frames`] must fit `max_pixels` (`media is W×H × N
638/// frames, over … pixels`). Bytes of no known image format pass (the
639/// decoder refuses them).
640pub fn media_image_check(bytes: &[u8], max_bytes: u64, max_pixels: u64) -> Result<(), String> {
641    if bytes.len() as u64 > max_bytes {
642        return Err(format!("media is over {max_bytes} bytes"));
643    }
644    match image_header(bytes) {
645        ImageHeader::Unknown => Ok(()),
646        ImageHeader::Unreadable => Err("media: image dimensions unreadable".into()),
647        ImageHeader::Size { width: w, height: h, frames } if frames <= 1 => {
648            if w as u128 * h as u128 > max_pixels as u128 {
649                return Err(format!("media is {w}×{h}, over {max_pixels} pixels"));
650            }
651            Ok(())
652        }
653        ImageHeader::Size { width: w, height: h, frames } => {
654            if w as u128 * h as u128 * frames as u128 > max_pixels as u128 {
655                return Err(format!("media is {w}×{h} × {frames} frames, over {max_pixels} pixels"));
656            }
657            Ok(())
658        }
659    }
660}
661
662/// [`media_image_check`] under the contract's `media.limits`.
663pub fn media_image_within_limits(bytes: &[u8]) -> Result<(), String> {
664    use super::contract::{MEDIA_MAX_BYTES, MEDIA_MAX_PIXELS};
665    media_image_check(bytes, MEDIA_MAX_BYTES, MEDIA_MAX_PIXELS)
666}
667
668/// Whether a load fits `media.limits`: `bytes` read so far (or the
669/// Content-Length) and, once the header is in, the image's pixels.
670pub fn media_within_limits(bytes: u64, dimensions: Option<(u32, u32)>) -> Result<(), String> {
671    use super::contract::{MEDIA_MAX_BYTES, MEDIA_MAX_PIXELS};
672    if bytes > MEDIA_MAX_BYTES {
673        return Err(format!("media is over {MEDIA_MAX_BYTES} bytes"));
674    }
675    if let Some((w, h)) = dimensions {
676        if w as u64 * h as u64 > MEDIA_MAX_PIXELS {
677            return Err(format!("media is {w}×{h}, over {MEDIA_MAX_PIXELS} pixels"));
678        }
679    }
680    Ok(())
681}
682
683#[cfg(test)]
684mod tests {
685    use super::*;
686
687    /// VAPP-103 rfix: SVGs have a size, frames multiply the pixels, and a
688    /// raster whose dimensions cannot be read is refused (it failed open).
689    #[test]
690    fn svg_sizes_animation_frames_and_unreadable_rasters_meet_the_pixel_cap() {
691        assert_eq!(svg_dimensions(br#"<svg xmlns="http://www.w3.org/2000/svg" width="20000" height="20000"/>"#), Some((20_000, 20_000)));
692        assert!(media_image_within_limits(br#"<svg width="20000" height="20000"></svg>"#).unwrap_err().contains("20000×20000"));
693        assert_eq!(svg_dimensions(br#"<?xml version="1.0"?><svg viewBox="0 0 300 150"/>"#), Some((300, 150)));
694        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");
695        assert_eq!(svg_dimensions(br#"<svg width="2in" height="10em">"#), Some((192, 160)));
696        assert_eq!(svg_dimensions(br#"<svg width="50%">"#), Some((100, 100)));
697        assert_eq!(svg_dimensions(b"<svg>"), Some((100, 100)));
698        assert!(media_image_within_limits(br#"<svg width="24" height="24"/>"#).is_ok());
699        assert!(media_image_within_limits(b"<?xml version='1.0'?><note/>").unwrap_err().contains("unreadable"));
700        // A 1000×1000 GIF with 40 frames: 40 Mpx decoded.
701        let mut gif = b"GIF89a".to_vec();
702        gif.extend_from_slice(&1000u16.to_le_bytes());
703        gif.extend_from_slice(&1000u16.to_le_bytes());
704        gif.extend_from_slice(&[0, 0, 0]);
705        for _ in 0..40 {
706            gif.extend_from_slice(&[0x21, 0xf9, 4, 0, 0, 0, 0, 0]);
707            gif.extend_from_slice(&[0x2c, 0, 0, 0, 0, 0xe8, 3, 0xe8, 3, 0, 2, 2, 0x4c, 1, 0]);
708        }
709        gif.push(0x3b);
710        assert_eq!(image_frames(&gif), 40);
711        assert!(media_image_within_limits(&gif).unwrap_err().contains("40 frames"));
712        assert_eq!(image_frames(&gif[..gif.len() / 2]), 20, "a truncated GIF counts the frames it holds");
713        // An APNG announcing 100 frames of 1000×1000.
714        let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
715        png.extend_from_slice(&1000u32.to_be_bytes());
716        png.extend_from_slice(&1000u32.to_be_bytes());
717        png.extend_from_slice(&[8, 6, 0, 0, 0, 0, 0, 0, 0]);
718        png.extend_from_slice(b"\0\0\0\x08acTL");
719        png.extend_from_slice(&100u32.to_be_bytes());
720        png.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]);
721        assert_eq!(image_frames(&png), 100);
722        assert!(media_image_within_limits(&png).is_err());
723        // An animated WebP canvas of 2000×2000 with 10 ANMF chunks.
724        let mut webp = b"RIFF\0\0\0\0WEBPVP8X\x0a\0\0\0\x02\0\0\0".to_vec();
725        webp.extend_from_slice(&1999u32.to_le_bytes()[..3]);
726        webp.extend_from_slice(&1999u32.to_le_bytes()[..3]);
727        for _ in 0..10 {
728            webp.extend_from_slice(b"ANMF\x02\0\0\0ab");
729        }
730        assert_eq!(image_dimensions(&webp), Some((2000, 2000)));
731        assert_eq!(image_frames(&webp), 10);
732        assert!(media_image_within_limits(&webp).unwrap_err().contains("10 frames"));
733        // A raster header too short to read is refused, not passed.
734        assert!(media_image_within_limits(b"\x89PNG\r\n\x1a\n\0\0").unwrap_err().contains("unreadable"));
735        assert!(media_image_within_limits(b"\xff\xd8\xff\xe0").unwrap_err().contains("unreadable"));
736        assert!(media_image_within_limits(b"{\"not\": \"an image\"}").is_ok());
737        assert!(media_image_within_limits(b"GIF89a\x10\0\x20\0").is_ok());
738    }
739
740    #[test]
741    fn image_headers_give_dimensions_without_decoding() {
742        let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
743        png.extend_from_slice(&40_000u32.to_be_bytes());
744        png.extend_from_slice(&30_000u32.to_be_bytes());
745        assert_eq!(image_dimensions(&png), Some((40_000, 30_000)));
746        assert!(media_within_limits(1024, image_dimensions(&png)).is_err());
747        assert_eq!(image_dimensions(b"GIF89a\x10\0\x20\0"), Some((16, 32)));
748        // JPEG: SOI, an APP0 segment, then SOF0 (height 0x0100, width 0x0200).
749        let jpeg = b"\xff\xd8\xff\xe0\0\x04ab\xff\xc0\0\x11\x08\x01\x00\x02\x00\x03";
750        assert_eq!(image_dimensions(jpeg), Some((512, 256)));
751        assert_eq!(image_dimensions(b"<svg/>"), Some((100, 100)));
752        assert!(media_within_limits(crate::host::MEDIA_MAX_BYTES + 1, None).is_err());
753        assert!(media_within_limits(10, Some((100, 100))).is_ok());
754    }
755
756    /// VAPP-107: the literal forms the WHATWG parser leaves behind.
757    #[test]
758    fn private_hosts_are_literals_in_every_normalized_form() {
759        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]"] {
760            assert!(is_private_host(h), "{h} is private");
761        }
762        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::]"] {
763            assert!(!is_private_host(h), "{h} is not private");
764        }
765        assert_eq!(decide_url(None, "http://[::FFFF:127.0.0.1]/").reason.as_deref(), Some("private"));
766        let opt = UrlPolicy { allow_private: Some(vec!["localhost".into()]), ..Default::default() };
767        assert!(decide_url(Some(&opt), "http://localhost:3000/").allowed);
768        assert_eq!(decide_url(Some(&opt), "http://127.0.0.1:3000/").reason.as_deref(), Some("private"));
769    }
770
771    #[test]
772    fn hrefs_pass_the_url_policy() {
773        assert_eq!(safe_href(None, "javascript:alert(1)"), None);
774        assert_eq!(safe_href(None, "https://exponential.at/x").as_deref(), Some("https://exponential.at/x"));
775        let hosts = UrlPolicy { hosts: Some(vec!["exponential.at".into()]), ..Default::default() };
776        assert_eq!(safe_href(Some(&hosts), "https://evil.example/"), None);
777    }
778}