Skip to main content

nsh_core/
access.rs

1//! Capabilities: what an app may reach outside its VM.
2//!
3//! An app declares them in `nsh.json` (`"capabilities"`); the app embedding
4//! nsh may grant less ([`Access`]): a request must be allowed by both.
5//! Everything is denied unless listed. `nsh.json` and signed packages are
6//! read leniently ([`Capabilities::from_json_lenient`]): a newer NSH may
7//! declare what this one does not know, which is then not granted (the
8//! toolchain warns of it, so a typo is still seen at build time).
9//!
10//! ```json
11//! "capabilities": {
12//!   "network": {
13//!     "hosts": ["api.example.com", "*.cdn.example.com"],
14//!     "http": [{ "host": "quotes.example.com", "methods": ["GET"], "pathPrefix": "/v1/" }],
15//!     "sockets": ["mqtt.example.com:8883"]
16//!   },
17//!   "webview": { "hosts": ["*.example.com"], "input": true },
18//!   "statusBar": true,
19//!   "application": true,
20//!   "homeDir": true,
21//!   "host": ["getUserInfo", "bridge.*"],
22//!   "openUrl": { "schemes": ["https", "mailto"] }
23//! }
24//! ```
25//!
26//! `share` lets the app show the system's share sheet (`Share` of
27//! `nsh-extra`, which checks it): what it shares leaves the app where the user sends
28//! it, and the files it shares are also checked against `fs.read`.
29//! `openUrl` lets the app open URLs outside it (`openUrl` of `nsh/device`,
30//! [`crate::open_url`]: the browser, the mail or phone app, other apps'
31//! schemes): `true` for every scheme, `{ "schemes": [...] }` for those
32//! listed. `network` covers `fetch` (every redirect is checked again), remote
33//! images (also canvas images and `Image.getSize` / `prefetch`) and video
34//! sources; `asset:` URIs are always allowed. WebSockets are HTTP upgrades:
35//! a `ws:` / `wss:` URL is checked as a GET of the same URL over `http:` /
36//! `https:` (or under its own scheme, for legacy rules that list it).
37//! `network.sockets` grants raw TCP (`net.connect`) to exact `host:port`
38//! pairs only: no wildcards, and neither `hosts` nor `http` grants imply
39//! one. `webview` lists the hosts a web view may show and navigate to (its
40//! pages' own subresources are the web content's business); its `input`
41//! lets a web view's ref give the page trusted input (`sendInput`), which
42//! carries user activation and is granted only when declared, also for
43//! apps without a declaration; its `runtimeOrigin` lets a web view's
44//! `allowOrigin` prop add one origin, decided while the app runs, to the
45//! hosts that web view may show ([`WebOrigin`]), also granted only when
46//! declared. `host` lists
47//! the functions of the embedding app `nsh/host` may call: names (1 to 128
48//! of `[A-Za-z0-9_.:-]`, without `..`; the core refuses calls of any other
49//! name), or prefixes of them ending in `*` (`true`: all of them); the
50//! host's events need no grant, the host sends them. `application` lets
51//! the app act on the application as a whole (`nsh/desktop`'s main window,
52//! application menu, tray, global shortcuts, `Application.quit`, `restart`
53//! and `setLaunchAtLogin`, and `nsh/mobile`'s `AppSettings.open`, the app's
54//! page in the system's settings; context menus, shown in the app's own
55//! view, and the windows `windows` grants need none); `homeDir` lets `os.homedir()` tell the
56//! user's home directory. An app without `"capabilities"` (a standalone
57//! app, its developer's own) retains unrestricted HTTP, web views, the
58//! status bar, the clipboard, the picker, the share sheet, speech
59//! recognition, opening URLs, the application and the home directory; raw sockets, processes, the
60//! filesystem and the host's functions always require an explicit
61//! declaration.
62
63//! A `network.http` rule names a `host` (a pattern, as in `hosts`); every
64//! other key narrows it and is optional: `methods` (any when left out),
65//! `schemes` or `scheme` (any of http, https, ws, wss), `port` (any),
66//! `paths` (exact) and `pathPrefixes` / `pathPrefix` / `path_prefixes`
67//! (whole segments: `/v1` covers `/v1` and `/v1/x`, not `/v10`). Without
68//! paths or prefixes a rule covers every path. Rules serialize in one form:
69//! `schemes` and `pathPrefixes`.
70
71use std::{
72    borrow::Cow,
73    path::{Component, Path, PathBuf},
74};
75
76use serde_json::{Map, Value};
77
78/// A host pattern: `*` (any host), `*.example.com` (its subdomains) or a
79/// host name.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct HostPattern(String);
82
83impl HostPattern {
84    /// Parses a pattern (lower-cased).
85    pub fn new(pattern: &str) -> Result<Self, String> {
86        let p = pattern.trim().to_ascii_lowercase();
87        let host = p.strip_prefix("*.").unwrap_or(&p);
88        let valid = p == "*"
89            || (!host.is_empty()
90                && host.chars().all(|c| {
91                    c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | ':' | '[' | ']')
92                }));
93        if valid {
94            Ok(Self(p))
95        } else {
96            Err(format!("invalid host pattern `{pattern}`"))
97        }
98    }
99
100    /// Whether `host` (lower case) matches.
101    pub fn matches(&self, host: &str) -> bool {
102        match self.0.strip_prefix("*.") {
103            _ if self.0 == "*" => true,
104            Some(suffix) => {
105                host.len() > suffix.len() + 1 && host.ends_with(suffix) && {
106                    let dot = host.len() - suffix.len() - 1;
107                    host.as_bytes()[dot] == b'.'
108                }
109            }
110            None => self.0 == host,
111        }
112    }
113
114    /// The pattern as written (lower case).
115    pub fn as_str(&self) -> &str {
116        &self.0
117    }
118
119    /// Whether it is `*`, which covers every host.
120    fn is_any(&self) -> bool {
121        self.0 == "*"
122    }
123}
124
125/// A finer HTTP grant: a host, narrowed by any of methods, schemes, a port,
126/// exact paths and path prefixes (each left empty: any).
127#[derive(Debug, Clone, PartialEq, Eq)]
128#[non_exhaustive]
129pub struct HttpGrant {
130    /// The host.
131    pub host: HostPattern,
132    /// Upper-case methods; empty: any.
133    pub methods: Vec<String>,
134    /// Lower-case schemes (`http`, `https`, `ws`, `wss`); empty: any of them.
135    pub schemes: Vec<String>,
136    /// The port, the scheme's default when the URL has none; `None`: any.
137    pub port: Option<u16>,
138    /// Exact paths (without the query), as requests send them: WHATWG's
139    /// serialization (`/my%20photos`), which parsing a grant writes them
140    /// in; a path written otherwise matches nothing.
141    pub paths: Vec<String>,
142    /// Path prefixes, matching whole segments (`/v1` covers `/v1/x`, not
143    /// `/v10`). With `paths`, a path matching either is covered; with
144    /// neither, every path is. Written as `paths` are.
145    pub path_prefixes: Vec<String>,
146}
147
148impl Default for HttpGrant {
149    fn default() -> Self {
150        Self {
151            host: HostPattern(String::new()),
152            methods: Vec::new(),
153            schemes: Vec::new(),
154            port: None,
155            paths: Vec::new(),
156            path_prefixes: Vec::new(),
157        }
158    }
159}
160
161impl HttpGrant {
162    fn allows(&self, method: &str, url: &UrlParts<'_>) -> bool {
163        let default_port = match url.scheme.as_str() {
164            "https" | "wss" => 443,
165            _ => 80,
166        };
167        let path = url.path.split(['?', '#']).next().unwrap_or("/");
168        let path = if path.is_empty() { "/" } else { path };
169        self.host.matches(&url.host)
170            && (self.methods.is_empty()
171                || self.methods.iter().any(|m| m.eq_ignore_ascii_case(method)))
172            && (self.schemes.is_empty() || self.schemes.contains(&url.scheme))
173            && self
174                .port
175                .is_none_or(|p| url.port.unwrap_or(default_port) == p)
176            && ((self.paths.is_empty() && self.path_prefixes.is_empty())
177                || self.paths.iter().any(|allowed| allowed == path)
178                || self.path_prefixes.iter().any(|prefix| {
179                    path.strip_prefix(prefix.as_str()).is_some_and(|tail| {
180                        tail.is_empty() || prefix.ends_with('/') || tail.starts_with('/')
181                    })
182                }))
183    }
184
185    /// Whether it grants `method` on every host, port and path of `scheme`:
186    /// all a URL that parsers read differently can be held to.
187    fn allows_anywhere(&self, method: &str, scheme: &str) -> bool {
188        self.host.is_any()
189            && (self.methods.is_empty()
190                || self.methods.iter().any(|m| m.eq_ignore_ascii_case(method)))
191            && (self.schemes.is_empty() || self.schemes.iter().any(|s| s == scheme))
192            && self.port.is_none()
193            && self.paths.is_empty()
194            && self.path_prefixes.is_empty()
195    }
196}
197
198/// `capabilities.network`.
199#[derive(Debug, Clone, PartialEq, Eq, Default)]
200#[non_exhaustive]
201pub struct NetworkGrants {
202    /// Reachable with any method.
203    pub hosts: Vec<HostPattern>,
204    /// Finer grants.
205    pub http: Vec<HttpGrant>,
206    /// Raw TCP destinations (`net.connect`).
207    pub sockets: Vec<SocketGrant>,
208}
209
210/// One raw TCP destination: an exact host and port, written `host:port`
211/// (`[::1]:port` for IPv6). A socket bypasses every HTTP rule (methods,
212/// paths, schemes), so it is granted per port and never by a pattern.
213#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct SocketGrant {
215    host: String,
216    port: u16,
217}
218
219impl SocketGrant {
220    /// Parses `host:port` (host lower-cased; port 1 to 65535).
221    pub fn new(grant: &str) -> Result<Self, String> {
222        let invalid = || {
223            format!(
224                "invalid socket grant `{grant}`: expected an exact `host:port` (`[::1]:port` for IPv6), without wildcards"
225            )
226        };
227        let (host, port) = grant.trim().rsplit_once(':').ok_or_else(invalid)?;
228        let port = port
229            .parse::<u16>()
230            .ok()
231            .filter(|p| *p != 0)
232            .ok_or_else(invalid)?;
233        let host = host.to_ascii_lowercase();
234        let host = match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
235            Some(v6)
236                if !v6.is_empty()
237                    && v6
238                        .chars()
239                        .all(|c| c.is_ascii_hexdigit() || matches!(c, ':' | '.')) =>
240            {
241                v6.to_owned()
242            }
243            Some(_) => return Err(invalid()),
244            None if !host.is_empty()
245                && host
246                    .chars()
247                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')) =>
248            {
249                host.trim_end_matches('.').to_owned()
250            }
251            None => return Err(invalid()),
252        };
253        Ok(Self { host, port })
254    }
255
256    /// The host (lower case, IPv6 without brackets).
257    pub fn host(&self) -> &str {
258        &self.host
259    }
260
261    /// The port.
262    pub fn port(&self) -> u16 {
263        self.port
264    }
265
266    /// The `host:port` form [`Self::new`] reads.
267    pub fn to_string_form(&self) -> String {
268        if self.host.contains(':') {
269            format!("[{}]:{}", self.host, self.port)
270        } else {
271            format!("{}:{}", self.host, self.port)
272        }
273    }
274}
275
276/// Commands an app may execute. Names are exact, without shell expansion.
277#[derive(Debug, Clone, PartialEq, Eq, Default)]
278#[non_exhaustive]
279pub struct ProcessGrants {
280    /// Exact executable names or absolute executable paths.
281    pub execute: Vec<String>,
282    /// The app may ask its host to handle an exit request.
283    pub exit: bool,
284    /// Additional environment variable names visible to the app.
285    pub env: Vec<String>,
286}
287
288/// Filesystem roots an app may read or write. `${dataDir}` is resolved by
289/// the host to this app's own data directory, never to a JS supplied root.
290#[derive(Debug, Clone, PartialEq, Eq, Default)]
291#[non_exhaustive]
292pub struct FileGrants {
293    /// Roots available for read operations.
294    pub read: Vec<String>,
295    /// Roots available for mutation operations.
296    pub write: Vec<String>,
297}
298
299/// Host-selected anchors for manifest paths. Apps cannot supply these roots.
300#[derive(Debug, Clone, PartialEq, Eq, Default)]
301#[non_exhaustive]
302pub struct TrustedPaths {
303    /// The application source/package directory.
304    pub plugin_dir: Option<PathBuf>,
305    /// The native user's home directory, when known.
306    pub home_dir: Option<PathBuf>,
307}
308impl TrustedPaths {
309    /// Expand one manifest root against host anchors. Relative roots are
310    /// anchored to the application directory. Unknown anchors never grant access.
311    pub fn resolve_root(&self, root: &str, data_dir: &Path) -> Result<PathBuf, String> {
312        validate_path_pattern(root)?;
313        for (placeholder, anchor) in [
314            ("${dataDir}", Some(data_dir)),
315            ("${pluginDir}", self.plugin_dir.as_deref()),
316            ("${homeDir}", self.home_dir.as_deref()),
317        ] {
318            if let Some(tail) = root.strip_prefix(placeholder) {
319                let anchor = anchor
320                    .filter(|p| absolute(p))
321                    .ok_or_else(|| format!("host anchor {placeholder} unavailable"))?;
322                // Component by component: `/` separates nothing in a
323                // verbatim Windows anchor.
324                let tail: PathBuf = tail.split('/').filter(|part| !part.is_empty()).collect();
325                return within(anchor, &tail, root);
326            }
327        }
328        let path = PathBuf::from(root);
329        if absolute(&path) {
330            Ok(path)
331        } else {
332            let anchor = self
333                .plugin_dir
334                .as_deref()
335                .filter(|p| absolute(p))
336                .ok_or_else(|| {
337                    "host application directory unavailable for relative filesystem root".to_owned()
338                })?;
339            within(anchor, &path, root)
340        }
341    }
342}
343
344/// `path` without `.` and `..`, resolved by its text.
345pub(crate) fn lexical(path: &Path) -> PathBuf {
346    use std::path::Component;
347    let mut out = PathBuf::new();
348    for part in path.components() {
349        match part {
350            Component::ParentDir => {
351                out.pop();
352            }
353            Component::CurDir => (),
354            other => out.push(other.as_os_str()),
355        }
356    }
357    out
358}
359
360/// The canonical form of the nearest existing ancestor, with the rest
361/// appended.
362#[cfg(not(target_arch = "wasm32"))]
363pub(crate) fn resolved(path: &Path) -> Result<PathBuf, String> {
364    let mut current = path.to_path_buf();
365    let mut tail = Vec::new();
366    loop {
367        if let Ok(mut real) = canonicalize(&current) {
368            real.extend(tail.into_iter().rev());
369            return Ok(real);
370        }
371        let name = current
372            .file_name()
373            .ok_or("invalid filesystem path")?
374            .to_owned();
375        if !current.pop() {
376            return Err("invalid filesystem path".into());
377        }
378        tail.push(name);
379    }
380}
381
382/// The rest of `path` past `root`, when `path` is in it (component by
383/// component; ignoring ASCII case on Windows, as its file systems do).
384pub(crate) fn inside(path: &Path, root: &Path) -> Option<PathBuf> {
385    let mut rest = path.components();
386    for part in root.components() {
387        let next = rest.next()?;
388        let same = if cfg!(windows) {
389            next.as_os_str()
390                .to_string_lossy()
391                .eq_ignore_ascii_case(&part.as_os_str().to_string_lossy())
392        } else {
393            next == part
394        };
395        if !same {
396            return None;
397        }
398    }
399    Some(rest.collect())
400}
401
402/// The rest of `path` in root `(expanded, canonical)`: under either form
403/// (`/var/…` and `/private/var/…` on macOS).
404#[cfg(not(target_arch = "wasm32"))]
405pub(crate) fn in_root(path: &Path, (expanded, canonical): &(PathBuf, PathBuf)) -> Option<PathBuf> {
406    inside(path, canonical).or_else(|| inside(path, expanded))
407}
408
409/// Whether apps have the native file system here that `capabilities.fs`
410/// grants (`fs/promises`, local media files, shared files): on every
411/// native OS (the desktops, iOS, Android — the capability confines each
412/// call to the roots the app declares, whatever the sandbox around
413/// them), never on the web, whose `fs/promises` works on the host's
414/// private virtual file system and whose pages name no local file.
415pub fn native_files(os: crate::platform::Os) -> bool {
416    cfg!(not(target_arch = "wasm32")) && os != crate::platform::Os::Web
417}
418
419/// The `capabilities.fs.read` roots local media files are read under, as
420/// `fs/promises` reads files: the app's declared roots and the host's grant
421/// (which narrows them), their anchors (`${dataDir}`, `${pluginDir}`,
422/// `${homeDir}`) expanded and resolved once, when they are made
423/// ([`Access::media_url`]).
424#[derive(Debug, Clone, Default)]
425#[non_exhaustive]
426#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
427pub struct MediaFiles {
428    /// The declared roots, expanded and canonical (`/var/…` and
429    /// `/private/var/…` on macOS).
430    declared: Vec<(PathBuf, PathBuf)>,
431    /// The host grant's, when it has one.
432    granted: Option<Vec<(PathBuf, PathBuf)>>,
433}
434
435impl MediaFiles {
436    /// `access`'s read roots, expanded against `data_dir` and `paths`.
437    /// Where the platform has no file system for apps (`available`
438    /// false: the web, as for `fs/promises`), none.
439    pub fn new(
440        access: &Access,
441        data_dir: Option<&Path>,
442        paths: &TrustedPaths,
443        available: bool,
444    ) -> Self {
445        #[cfg(target_arch = "wasm32")]
446        {
447            let _ = (access, data_dir, paths, available);
448            Self::default()
449        }
450        #[cfg(not(target_arch = "wasm32"))]
451        {
452            if !available {
453                return Self::default();
454            }
455            let data = data_dir.map(Path::to_path_buf).unwrap_or_default();
456            let roots = |grants: &Capabilities| {
457                grants
458                    .fs
459                    .read
460                    .iter()
461                    .filter_map(|root| {
462                        let expanded = lexical(&paths.resolve_root(root, &data).ok()?);
463                        let canonical = resolved(&expanded).ok()?;
464                        Some((expanded, canonical))
465                    })
466                    .collect()
467            };
468            Self {
469                declared: roots(&access.declared),
470                granted: access.granted.as_ref().map(roots),
471            }
472        }
473    }
474
475    /// Opens `path` (what [`Access::media_url`] granted) to read through
476    /// the declared root that holds it, as `fs/promises` reads: every
477    /// component is opened inside the root, so a link made after the check
478    /// cannot lead out of it. `None` with no roots (an app reading what the
479    /// platform allows): the caller opens the path itself.
480    #[cfg(not(target_arch = "wasm32"))]
481    pub(crate) fn open(&self, path: &Path) -> Option<std::io::Result<std::fs::File>> {
482        if self.declared.is_empty() {
483            return None;
484        }
485        let refused = || std::io::Error::new(std::io::ErrorKind::PermissionDenied, "not granted");
486        let path = lexical(path);
487        if !self
488            .declared
489            .iter()
490            .any(|root| in_root(&path, root).is_some())
491        {
492            return Some(Err(refused()));
493        }
494        // Opened under the narrowest root that grants it: the host's grant
495        // when there is one (inside a declared root), so a link in it cannot
496        // reach the rest of a wider declared root.
497        let granted: Vec<&(PathBuf, PathBuf)> = match &self.granted {
498            Some(roots) => roots
499                .iter()
500                .filter(|(_, canonical)| {
501                    self.declared
502                        .iter()
503                        .any(|(_, declared)| inside(canonical, declared).is_some())
504                })
505                .collect(),
506            None => self.declared.iter().collect(),
507        };
508        // The innermost root holding it (a nested root may be reached
509        // through a link in its parent's).
510        let Some(((_, canonical), relative)) = granted
511            .into_iter()
512            .filter_map(|root| Some((root, in_root(&path, root)?)))
513            .max_by_key(|((_, canonical), _)| canonical.components().count())
514        else {
515            return Some(Err(refused()));
516        };
517        Some((|| {
518            let dir = crate::runtime::fs::confined::open_root(canonical)?;
519            let file = crate::runtime::fs::confined::open_file(&dir, &relative, false)?;
520            Ok(file.into_std())
521        })())
522    }
523
524    /// `path`'s canonical form, if a declared root holds it and the host's
525    /// grant does too. Symlinks are resolved here, not by the loader: the
526    /// platform's loaders open what they are given, with nothing to keep
527    /// them in a root (`fs/promises` works in the opened root instead).
528    fn readable(&self, path: &Path) -> Option<PathBuf> {
529        #[cfg(target_arch = "wasm32")]
530        {
531            let _ = path;
532            None
533        }
534        #[cfg(not(target_arch = "wasm32"))]
535        {
536            if !absolute(path) || self.declared.is_empty() {
537                return None;
538            }
539            // By its text first, as `fs/promises` checks: a path outside
540            // the roots is refused with no disk work on the engine thread.
541            let path = lexical(path);
542            let within = |roots: &[(PathBuf, PathBuf)]| {
543                roots.iter().any(|root| in_root(&path, root).is_some())
544            };
545            if !within(&self.declared) || !self.granted.as_deref().is_none_or(within) {
546                return None;
547            }
548            // Then resolved, on every check (a path granted once may be a
549            // link out of the root by the next), as `authorize_file`
550            // resolves: a link whose target does not exist is refused, not
551            // taken for a file to come.
552            #[cfg(test)]
553            RESOLVES.with(|n| n.set(n.get() + 1));
554            let real = resolved_path(&path).ok()?;
555            let holds = |roots: &[(PathBuf, PathBuf)]| {
556                roots
557                    .iter()
558                    .any(|(_, canonical)| inside(&real, canonical).is_some())
559            };
560            (holds(&self.declared) && self.granted.as_deref().is_none_or(holds)).then_some(real)
561        }
562    }
563}
564
565#[cfg(test)]
566thread_local! {
567    /// How many local media paths this thread resolved on the disk (a
568    /// test's evidence that a path outside the roots was not).
569    static RESOLVES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
570}
571
572/// How many local media paths this thread has resolved on the disk.
573#[cfg(test)]
574pub(crate) fn resolves() -> usize {
575    RESOLVES.with(std::cell::Cell::get)
576}
577
578/// Virtual browser paths use Unix roots. `Path::is_absolute` on
579/// wasm32-unknown-unknown always returns false because it has no OS prefix.
580pub(crate) fn absolute(path: &Path) -> bool {
581    if cfg!(target_arch = "wasm32") {
582        path.has_root()
583    } else {
584        path.is_absolute()
585    }
586}
587
588/// `tail` joined to `anchor`, when it stays there: names only. On Windows
589/// a drive (`C:/Windows`), a share (`\\srv\share`) or a rooted path
590/// (`\Users`) would replace or leave the anchor in `join`.
591fn within(anchor: &Path, tail: &Path, root: &str) -> Result<PathBuf, String> {
592    use std::path::Component;
593    let names = tail
594        .components()
595        .all(|c| matches!(c, Component::Normal(_) | Component::CurDir));
596    let mut path = anchor.to_path_buf();
597    path.extend(tail.components().filter(|c| *c != Component::CurDir));
598    if names && path.starts_with(anchor) {
599        Ok(path)
600    } else {
601        Err(format!("filesystem root `{root}` leaves its anchor"))
602    }
603}
604
605/// Whether environment names `a` and `b` are one variable: ignoring ASCII
606/// case on Windows, whose environment does; exactly elsewhere (`lang` is
607/// not `LANG` on Unix).
608pub(crate) fn env_names_match(a: &str, b: &str) -> bool {
609    if cfg!(windows) {
610        a.eq_ignore_ascii_case(b)
611    } else {
612        a == b
613    }
614}
615
616/// What a web view's page may capture (`capabilities.webview.media`).
617#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
618pub enum WebMedia {
619    /// `"microphone"`: audio input.
620    Microphone,
621    /// `"camera"`: video input.
622    Camera,
623}
624
625impl WebMedia {
626    /// Its name in `capabilities.webview.media`.
627    pub fn as_str(self) -> &'static str {
628        match self {
629            Self::Microphone => "microphone",
630            Self::Camera => "camera",
631        }
632    }
633}
634
635/// What an app may do (one declaration, or one grant).
636/// Start with [`Self::default`] and set the fields to grant; new capabilities
637/// default to denied.
638#[derive(Debug, Clone, PartialEq, Eq, Default)]
639#[non_exhaustive]
640pub struct Capabilities {
641    /// Explicit native subprocess grants.
642    pub process: ProcessGrants,
643    /// Explicit native filesystem grants.
644    pub fs: FileGrants,
645    /// `fetch`, remote images and video.
646    pub network: NetworkGrants,
647    /// The hosts web views may show; `None`: no web views.
648    pub webview: Option<Vec<HostPattern>>,
649    /// Web views may take trusted input (`sendInput`, `webview.input`):
650    /// never without a declaration ([`Capabilities::all`] leaves it off).
651    pub webview_input: bool,
652    /// A web view's `allowOrigin` adds one origin to the hosts it may show
653    /// (`webview.runtimeOrigin`): never without a declaration
654    /// ([`Capabilities::all`] leaves it off).
655    pub webview_runtime_origin: bool,
656    /// What web views' pages may capture (`webview.media`): never without a
657    /// declaration ([`Capabilities::all`] leaves it empty).
658    pub webview_media: Vec<WebMedia>,
659    /// The app may set the status bar.
660    pub status_bar: bool,
661    /// The app may read and write the system clipboard (`nsh/clipboard`).
662    pub clipboard: bool,
663    /// The app may show the system's picker (`nsh/picker`): the files the
664    /// user picks in it reach the app.
665    pub picker: bool,
666    /// The app may show the system's share sheet (`Share` of `nsh-extra`): the
667    /// text, links and files it shares leave the app where the user sends
668    /// them.
669    pub share: bool,
670    /// The app may recognize the user's speech (`Speech` of `nsh-extra`): the
671    /// microphone listens while a session runs, and the transcript reaches
672    /// the app.
673    pub speech: bool,
674    /// The app may show notifications and set its badge (`Notifications` of
675    /// `nsh`). The user's permission is the system's, on top of this.
676    pub notifications: bool,
677    /// The app may play sound (`Sound` and `AudioPlayer` of `nsh`).
678    pub audio: bool,
679    /// The app may act on the application as a whole: the main window, the
680    /// application menu, the tray, global shortcuts, quitting, restarting
681    /// and launching at login (`nsh/desktop`), and the app's page in the
682    /// system's settings (`nsh/mobile`'s `AppSettings`).
683    pub application: bool,
684    /// `os.homedir()` may tell the user's home directory.
685    pub home_dir: bool,
686    /// The functions of the embedding app `nsh/host` may call: names, or
687    /// prefixes ending in `*` (`"*"`: all); empty: none, also for apps
688    /// without a declaration ([`Capabilities::all`]).
689    pub host: Vec<String>,
690    /// The URLs the app may open outside it (`openUrl` of `nsh/device`);
691    /// `None`: none.
692    pub open_url: Option<OpenUrlGrant>,
693    /// The windows the app may open and what they may do (`nsh/desktop`'s
694    /// `Window`); `None`: no window of the app's own. The first window needs
695    /// the grant too: no window is privileged.
696    pub windows: Option<WindowsGrant>,
697}
698
699/// The windows an app may open (`capabilities.windows`). Overlays,
700/// click-through windows and capture protection, which can pass for the
701/// system's UI over other apps, are granted only when declared.
702#[derive(Debug, Clone, PartialEq, Eq, Default)]
703#[non_exhaustive]
704pub struct WindowsGrant {
705    /// The kinds it may open; empty: every kind but `overlay`, which needs
706    /// [`Self::overlay`] as well.
707    pub kinds: Vec<crate::desktop::WindowKind>,
708    /// The levels its windows may float at; empty: every level.
709    pub levels: Vec<crate::desktop::WindowLevel>,
710    /// How many windows it may have open at once, its first window included;
711    /// `None`: any number.
712    pub max: Option<u32>,
713    /// Overlays and click-through windows (`pointerEvents: "none"` or
714    /// `"box-none"`).
715    pub overlay: bool,
716}
717
718impl WindowsGrant {
719    fn allows_kind(&self, kind: crate::desktop::WindowKind) -> bool {
720        use crate::desktop::WindowKind;
721        if kind == WindowKind::Overlay && !self.overlay {
722            return false;
723        }
724        self.kinds.is_empty() || self.kinds.contains(&kind)
725    }
726
727    fn allows_level(&self, level: crate::desktop::WindowLevel) -> bool {
728        self.levels.is_empty() || self.levels.contains(&level)
729    }
730}
731
732/// Which URLs an app may open outside it (`capabilities.openUrl`).
733#[derive(Debug, Clone, PartialEq, Eq, Default)]
734#[non_exhaustive]
735pub struct OpenUrlGrant {
736    /// The schemes it may open, lower case (`https`, `mailto`, `tel`);
737    /// empty: every scheme (`"openUrl": true`).
738    pub schemes: Vec<String>,
739}
740
741impl OpenUrlGrant {
742    /// Whether it grants URLs of `scheme` (lower case).
743    pub fn allows(&self, scheme: &str) -> bool {
744        self.schemes.is_empty() || self.schemes.iter().any(|s| s == scheme)
745    }
746}
747
748/// The parts of a URL the checks look at.
749#[derive(Debug, Clone, PartialEq, Eq)]
750pub struct UrlParts<'a> {
751    /// Lower-case scheme.
752    pub scheme: String,
753    /// Lower-case host (without port or user info).
754    pub host: String,
755    /// The path (and query), `/` when empty.
756    pub path: &'a str,
757    /// Explicit URL port.
758    pub port: Option<u16>,
759}
760
761/// Splits an absolute URL into scheme, host and path; `None` when it has no
762/// `scheme://host`, or when URL parsers would read it differently: a
763/// backslash before the query, an ASCII control character, or a host with
764/// percent-encoding or a forbidden host code point.
765pub fn parse_url(url: &str) -> Option<UrlParts<'_>> {
766    read_url(url).ok()
767}
768
769/// What a refusal of `url` advises: the host to add to
770/// `capabilities.{capability}`, or, for a URL without parts, how to write
771/// it, since adding the URL itself would never grant it.
772pub(crate) fn grant_advice(url: &str, capability: &str) -> String {
773    match parse_url(url) {
774        Some(parts) => format!(
775            "add `{}` to capabilities.{capability} in nsh.json",
776            parts.host
777        ),
778        None => NO_HOST_ADVICE.to_owned(),
779    }
780}
781
782/// [`grant_advice`] for a media source, read as [`Access::media_url`] reads
783/// it: a local file is the `fs` capability's; a protocol-relative source
784/// (`//host/…`) names the host it resolves to against `base`, the page's
785/// address, and without one has no scheme to load with.
786pub(crate) fn media_grant_advice(uri: &str, base: Option<&str>) -> String {
787    if native_relative(uri, base) {
788        return RELATIVE_ADVICE.to_owned();
789    }
790    if starts_with_ignoring_case(uri, "asset:") && !is_inside_assets(uri) {
791        return ASSET_ADVICE.to_owned();
792    }
793    if media_capability(uri, base) == "fs" {
794        return LOCAL_FILE_ADVICE.to_owned();
795    }
796    let unambiguous = !uri.contains('\\') && !uri.bytes().any(|b| b.is_ascii_control());
797    if scheme_of(uri).is_none() && uri.starts_with("//") && unambiguous {
798        let resolved = base
799            .and_then(|base| url::Url::parse(base).ok())
800            .and_then(|base| base.join(uri).ok());
801        return match resolved {
802            Some(url) => grant_advice(url.as_str(), "network"),
803            None => NO_SCHEME_ADVICE.to_owned(),
804        };
805    }
806    grant_advice(uri, "network")
807}
808
809/// The capability that grants media source `uri` against `base`, as
810/// [`Access::media_url`] reads it: `"fs"` for a local file (a `file:` URL;
811/// with no base, an absolute or drive path), else `"network"`.
812pub(crate) fn media_capability(uri: &str, base: Option<&str>) -> &'static str {
813    if starts_with_ignoring_case(uri, "asset:") || native_relative(uri, base) {
814        return "fs";
815    }
816    let local =
817        (base.is_none() || starts_with_ignoring_case(uri, "file:")) && local_file(uri).is_some();
818    if local { "fs" } else { "network" }
819}
820
821/// [`media_grant_advice`] for a relative path in a native app.
822const RELATIVE_ADVICE: &str = "a relative path names no file in a native app: name a bundled file as `asset:/…`, or import it";
823
824/// [`media_grant_advice`] for a bundled file whose path leaves the app's
825/// files, which no grant covers.
826const ASSET_ADVICE: &str = "bundled files are named by a path inside the app's files";
827
828/// [`media_grant_advice`] for a local file.
829const LOCAL_FILE_ADVICE: &str =
830    "a local file is read under capabilities.fs.read in nsh.json: add a root that holds it";
831
832/// [`media_grant_advice`] for a protocol-relative source without a base.
833const NO_SCHEME_ADVICE: &str =
834    "it names no scheme and has no page to take one from: write it as an http(s) URL";
835
836/// [`grant_advice`] for a URL without parts.
837const NO_HOST_ADVICE: &str = "it names no host a grant could add: write it as an http(s) URL with a host, a backslash as `%5C` and no control characters";
838
839/// Whether media source `uri` is the app's own, which stays as written: a
840/// bundled file (`asset:`) or bytes it has (`data:`, `blob:`, an in-memory
841/// image's `data:…;nsh-key=` key).
842fn is_own_media(uri: &str) -> bool {
843    ["asset:", "data:", "blob:"]
844        .iter()
845        .any(|prefix| starts_with_ignoring_case(uri, prefix))
846}
847
848/// Whether the bundled file `url` (`asset:/<path>`, as the host joins it to
849/// its asset directory) stays inside the app's files whichever way a host
850/// maps it: the path is relative, and no segment is empty, `.` or `..`
851/// (encoded or not) or holds a backslash, a NUL or a colon (a Windows
852/// drive), raw or percent-encoded, or an encoded `/`. Hosts join the path
853/// to their directory as it comes, so they never see one that escapes it.
854/// `fetch` checks the path a request reads (`nsh-engine`); a media source
855/// is checked whole, query included, since the image loader joins it as
856/// written.
857pub fn is_inside_assets(url: &str) -> bool {
858    let Some(path) = url.get(6..).and_then(|rest| rest.strip_prefix('/')) else {
859        return false;
860    };
861    path.split('/').all(|segment| {
862        let bytes = segment.as_bytes();
863        let encoded = |code: &[u8; 3]| bytes.windows(3).any(|w| w.eq_ignore_ascii_case(code));
864        !only_dots(bytes)
865            && !bytes.iter().any(|b| matches!(b, b'\\' | b'\0' | b':'))
866            && ![b"%2f", b"%5c", b"%00", b"%3a"]
867                .iter()
868                .any(|code| encoded(code))
869    })
870}
871
872/// Whether `segment` is empty, `.` or `..`, a dot written as itself or as
873/// `%2e` (any case).
874fn only_dots(segment: &[u8]) -> bool {
875    let (mut dots, mut at) = (0, 0);
876    while at < segment.len() {
877        if segment[at] == b'.' {
878            at += 1;
879        } else if segment[at..].len() >= 3
880            && segment[at] == b'%'
881            && segment[at + 1] == b'2'
882            && segment[at + 2].eq_ignore_ascii_case(&b'e')
883        {
884            at += 3;
885        } else {
886            return false;
887        }
888        dots += 1;
889        if dots > 2 {
890            return false;
891        }
892    }
893    true
894}
895
896/// Whether `uri`, read as WHATWG's parser reads it, names a host: it has
897/// a scheme or starts with `//` or a backslash ([`Access::media_url`]).
898fn names_host(uri: &str) -> bool {
899    let stripped = whatwg_stripped(uri);
900    scheme_of(&stripped).is_some()
901        || stripped.starts_with("//")
902        || stripped.starts_with('\\')
903        || stripped.starts_with("/\\")
904}
905
906/// Whether media source `uri` is a relative path in a native app (no
907/// `base`), which names no file of the app's ([`Access::media_url`]).
908fn native_relative(uri: &str, base: Option<&str>) -> bool {
909    base.is_none()
910        && !uri.trim().is_empty()
911        && !is_own_media(uri)
912        && local_file(uri).is_none()
913        && !names_host(uri)
914}
915
916/// `path` (starting with `/`) as a request sends it: WHATWG's serialization
917/// (`/my photos` → `/my%20photos`, `/über` → `/%C3%BCber`). `None` when a
918/// segment is `.` or `..`, encoded or not and as WHATWG splits it (at `\\`
919/// too, tabs and newlines dropped), which a request never sends.
920fn path_as_sent(path: &str) -> Option<String> {
921    // Read as WHATWG reads it: tabs and newlines dropped, a backslash a `/`.
922    let path: String = path
923        .chars()
924        .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
925        .map(|c| if c == '\\' { '/' } else { c })
926        .collect();
927    let dots = path.split('/').any(|segment| {
928        let segment = segment.to_ascii_lowercase().replace("%2e", ".");
929        segment == "." || segment == ".."
930    });
931    if dots {
932        return None;
933    }
934    let url = url::Url::parse(&format!("http://h{path}")).ok()?;
935    Some(url.path().to_owned())
936}
937
938/// Whether `text` starts with `prefix`, ignoring ASCII case.
939fn starts_with_ignoring_case(text: &str, prefix: &str) -> bool {
940    text.get(..prefix.len())
941        .is_some_and(|head| head.eq_ignore_ascii_case(prefix))
942}
943
944/// The local file media source `uri` names, if it names one: a `file:` URL's
945/// path (`Some(None)` when it names none), an absolute path, or a Windows
946/// drive path (`C:\…`, `C:/…`, which WHATWG's parser would take for a
947/// one-letter scheme). A path starting with `//` or `/\` names a host.
948fn local_file(uri: &str) -> Option<Option<PathBuf>> {
949    if starts_with_ignoring_case(uri, "file:") {
950        return Some(file_url_path(uri));
951    }
952    let drive = matches!(uri.as_bytes(), [d, b':', b'\\' | b'/', ..] if d.is_ascii_alphabetic());
953    let rooted = uri.starts_with('/') && !uri.starts_with("//") && !uri.starts_with("/\\");
954    (drive || rooted).then(|| Some(PathBuf::from(uri)))
955}
956
957/// The path `file:` URL `uri` names, decoded as a URL is (percent
958/// encoding included). What [`media_url`] checks is what the platforms'
959/// loaders read: they resolve `file:` sources with this, never by
960/// stripping the prefix. The web has no local files to name.
961#[doc(hidden)]
962pub fn file_url_path(uri: &str) -> Option<PathBuf> {
963    #[cfg(target_arch = "wasm32")]
964    {
965        let _ = uri;
966        None
967    }
968    #[cfg(not(target_arch = "wasm32"))]
969    {
970        url::Url::parse(uri).ok()?.to_file_path().ok()
971    }
972}
973
974/// The `file:` URL of `path` (which [`file_url_path`] reads back).
975fn file_url_of(path: &Path) -> Option<String> {
976    #[cfg(target_arch = "wasm32")]
977    {
978        let _ = path;
979        None
980    }
981    #[cfg(not(target_arch = "wasm32"))]
982    {
983        url::Url::from_file_path(path).ok().map(String::from)
984    }
985}
986
987/// `uri` as WHATWG's parser reads it: without leading and trailing spaces
988/// and C0 controls, and without tabs and newlines.
989fn whatwg_stripped(uri: &str) -> Cow<'_, str> {
990    let trimmed = uri.trim_matches(|c: char| c <= ' ');
991    if trimmed.contains(['\t', '\n', '\r']) {
992        Cow::Owned(trimmed.replace(['\t', '\n', '\r'], ""))
993    } else {
994        Cow::Borrowed(trimmed)
995    }
996}
997
998/// The scheme `uri` starts with (`[A-Za-z][A-Za-z0-9+.-]*:`), if any.
999fn scheme_of(uri: &str) -> Option<&str> {
1000    let (scheme, _) = uri.split_once(':')?;
1001    let mut chars = scheme.chars();
1002    (chars.next()?.is_ascii_alphabetic()
1003        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')))
1004    .then_some(scheme)
1005}
1006
1007/// Whether an app without capabilities loads media source `uri`: as before
1008/// its sources were read as WHATWG's parser reads them, anything without
1009/// `://`, and URLs `allows_http` grants.
1010fn media_as_written(uri: &str, allows_http: impl Fn(&str) -> bool) -> bool {
1011    !uri.contains("://") || is_own_media(uri) || local_file(uri).is_some() || allows_http(uri)
1012}
1013
1014/// `serialized`, or `written` when the two are the same.
1015fn written_or(written: &str, serialized: String) -> Cow<'_, str> {
1016    if serialized == written {
1017        Cow::Borrowed(written)
1018    } else {
1019        Cow::Owned(serialized)
1020    }
1021}
1022
1023/// Why [`read_url`] gives no parts.
1024enum Unread {
1025    /// No `scheme://host`.
1026    NotUrl,
1027    /// A URL parsers read as different hosts, ports or paths, with its
1028    /// lower-case scheme: only a grant of every host covers it.
1029    Ambiguous(String),
1030}
1031
1032/// [`parse_url`], saying why a string has no parts.
1033fn read_url(url: &str) -> Result<UrlParts<'_>, Unread> {
1034    let (scheme, rest) = url.split_once("://").ok_or(Unread::NotUrl)?;
1035    if scheme.is_empty()
1036        || !scheme
1037            .chars()
1038            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
1039    {
1040        return Err(Unread::NotUrl);
1041    }
1042    let scheme = scheme.to_ascii_lowercase();
1043    // WHATWG's parser (the web views') ends the host at a backslash and reads
1044    // one in the path as `/`, and it drops tab, LF and CR; Foundation's
1045    // `NSURL` (native media loads) keeps a backslash in the user info. Before
1046    // the query, one could name a host or path here other than the one that
1047    // loads; in the query no parser reads it as a host or path.
1048    let head = url.split(['?', '#']).next().unwrap_or(url);
1049    if head.contains('\\') || url.bytes().any(|b| b.is_ascii_control()) {
1050        return Err(Unread::Ambiguous(scheme));
1051    }
1052    let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
1053    let (authority, path) = rest.split_at(end);
1054    // User info ends at the last `@`: `https://good.com@evil.com/` is evil.com.
1055    let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
1056    let host = if let Some(v6) = host_port.strip_prefix('[') {
1057        format!("[{}]", v6.split_once(']').ok_or(Unread::NotUrl)?.0)
1058    } else {
1059        host_port.split(':').next().unwrap_or_default().to_owned()
1060    };
1061    if host.is_empty() {
1062        return Err(Unread::NotUrl);
1063    }
1064    // WHATWG's parser decodes a host's percent-encoding and refuses its
1065    // forbidden host code points: a host with either is not the one granted.
1066    if host.contains(['%', ' ', '<', '>', '^', '|'])
1067        || (!host_port.starts_with('[') && host.contains(['[', ']']))
1068    {
1069        return Err(Unread::Ambiguous(scheme));
1070    }
1071    let port = if host_port.starts_with('[') {
1072        host_port
1073            .split_once(']')
1074            .and_then(|(_, rest)| rest.strip_prefix(':'))
1075            .map(str::parse::<u16>)
1076            .transpose()
1077    } else {
1078        host_port
1079            .split_once(':')
1080            .map(|(_, port)| port.parse::<u16>())
1081            .transpose()
1082    }
1083    .map_err(|_| Unread::NotUrl)?;
1084    Ok(UrlParts {
1085        scheme,
1086        host: host.to_ascii_lowercase().trim_end_matches('.').to_owned(),
1087        path: if path.is_empty() { "/" } else { path },
1088        port,
1089    })
1090}
1091
1092/// One origin a web view may show besides the hosts `webview.hosts`
1093/// grants: its `allowOrigin`, for an origin known only while the app runs
1094/// (a server the user named, a computer on the local network). Exact:
1095/// the same scheme (`http` or `https`), the same host (ASCII, compared in
1096/// lower case, never a subdomain or a suffix) and the same port (the
1097/// scheme's default when none is written).
1098#[derive(Debug, Clone, PartialEq, Eq)]
1099#[non_exhaustive]
1100pub struct WebOrigin {
1101    scheme: String,
1102    host: String,
1103    port: u16,
1104}
1105
1106impl WebOrigin {
1107    /// Reads `origin`, `scheme://host[:port]` with `http` or `https` and
1108    /// nothing else: no user info, no path but `/`, no query or fragment,
1109    /// an ASCII host (IDNA hosts are written in punycode) and no wildcard.
1110    pub fn parse(origin: &str) -> Result<Self, String> {
1111        let refused = |why: &str| Err(format!("`{origin}` is not an origin: {why}"));
1112        let Some((scheme, rest)) = origin.split_once("://") else {
1113            return refused("it is not `http://host` or `https://host`");
1114        };
1115        let scheme = scheme.to_ascii_lowercase();
1116        if !matches!(scheme.as_str(), "http" | "https") {
1117            return refused("its scheme is not http or https");
1118        }
1119        let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
1120        let (authority, after) = rest.split_at(end);
1121        if !matches!(after, "" | "/") {
1122            return refused("it has a path, a query or a fragment");
1123        }
1124        if authority.contains('@') {
1125            return refused("it has user info");
1126        }
1127        if !authority.is_ascii() || authority.contains('*') {
1128            return refused("its host is not an ASCII host name or address");
1129        }
1130        let Ok(parts) = read_url(origin) else {
1131            return refused("its host or port cannot be read");
1132        };
1133        let port = parts.port.unwrap_or(default_port(&scheme));
1134        Ok(Self {
1135            scheme,
1136            host: parts.host,
1137            port,
1138        })
1139    }
1140
1141    /// Whether `url` is at this origin: its scheme, host and port (the
1142    /// scheme's default when it writes none). A `blob:` URL is at the
1143    /// origin it embeds; an opaque one (`blob:null/…`) is at none.
1144    pub fn contains(&self, url: &str) -> bool {
1145        let url = blob_origin(url).unwrap_or(url);
1146        read_url(url).is_ok_and(|parts| {
1147            parts.scheme == self.scheme
1148                && parts.host == self.host
1149                && parts.port.unwrap_or(default_port(&parts.scheme)) == self.port
1150        })
1151    }
1152}
1153
1154/// `scheme://host`, with `:port` when it is not the scheme's default.
1155impl std::fmt::Display for WebOrigin {
1156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1157        write!(f, "{}://{}", self.scheme, self.host)?;
1158        if self.port != default_port(&self.scheme) {
1159            write!(f, ":{}", self.port)?;
1160        }
1161        Ok(())
1162    }
1163}
1164
1165/// The hosts one web view may show and navigate to, narrower than the
1166/// app's grant: its `allowNavigation`, the same host patterns as
1167/// `webview.hosts` (`*`, `*.example.com`, a host name). It only takes
1168/// away: an `http` or `https` URL must match one of them as well as be
1169/// granted by the app's capabilities, and an empty list refuses every web
1170/// page. URLs of other schemes (`about:blank`, the app's own `file://`
1171/// page and URL schemes) are left to the app's rules. The check runs where
1172/// the platform decides a navigation, before its request is made.
1173#[derive(Debug, Clone, PartialEq, Eq, Default)]
1174pub struct WebHosts(Vec<HostPattern>);
1175
1176impl WebHosts {
1177    /// Reads `patterns`, failing on the first that is not a host pattern.
1178    pub fn parse<S: AsRef<str>>(patterns: &[S]) -> Result<Self, String> {
1179        patterns
1180            .iter()
1181            .map(|p| HostPattern::new(p.as_ref()))
1182            .collect::<Result<Vec<_>, _>>()
1183            .map(Self)
1184    }
1185
1186    /// Whether `url` stays within these hosts: true for a URL that is not
1187    /// `http` or `https`.
1188    pub fn allows(&self, url: &str) -> bool {
1189        let url = blob_origin(url).unwrap_or(url);
1190        let scheme = url.split_once(':').map(|(s, _)| s.to_ascii_lowercase());
1191        if !matches!(scheme.as_deref(), Some("http" | "https")) {
1192            return true;
1193        }
1194        match read_url(url) {
1195            Ok(parts) => self.0.iter().any(|h| h.matches(&parts.host)),
1196            Err(Unread::Ambiguous(_)) => self.0.iter().any(HostPattern::is_any),
1197            Err(Unread::NotUrl) => false,
1198        }
1199    }
1200
1201    /// The patterns, as written (lower case).
1202    pub fn patterns(&self) -> impl Iterator<Item = &str> {
1203        self.0.iter().map(HostPattern::as_str)
1204    }
1205}
1206
1207/// The patterns one per line, which [`WebHosts::parse`] reads back after
1208/// splitting the lines.
1209impl std::fmt::Display for WebHosts {
1210    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1211        for (i, p) in self.0.iter().enumerate() {
1212            if i > 0 {
1213                f.write_str("\n")?;
1214            }
1215            f.write_str(p.as_str())?;
1216        }
1217        Ok(())
1218    }
1219}
1220
1221/// The port a URL of `scheme` uses when it writes none (0: none).
1222fn default_port(scheme: &str) -> u16 {
1223    match scheme {
1224        "http" => 80,
1225        "https" => 443,
1226        _ => 0,
1227    }
1228}
1229
1230/// The origin a `blob:` URL embeds (`blob:<origin>/<id>`, as
1231/// `URL.createObjectURL` writes it), when `url` is one. A blob's origin is
1232/// its creator's: a browser only makes a blob URL in the origin of the
1233/// document that made it, so checking the embedded origin checks the page.
1234fn blob_origin(url: &str) -> Option<&str> {
1235    url.get(..5)
1236        .is_some_and(|scheme| scheme.eq_ignore_ascii_case("blob:"))
1237        .then(|| &url[5..])
1238        .filter(|origin| !origin.is_empty())
1239}
1240
1241impl Capabilities {
1242    /// Legacy unrestricted APIs for apps without a declaration. Socket,
1243    /// process, filesystem and host function grants stay empty and always
1244    /// require explicit opt-in.
1245    pub fn all() -> Self {
1246        let any = vec![HostPattern("*".into())];
1247        Self {
1248            network: NetworkGrants {
1249                hosts: any.clone(),
1250                http: Vec::new(),
1251                sockets: Vec::new(),
1252            },
1253            webview: Some(any),
1254            status_bar: true,
1255            clipboard: true,
1256            picker: true,
1257            share: true,
1258            speech: true,
1259            notifications: true,
1260            audio: true,
1261            application: true,
1262            home_dir: true,
1263            open_url: Some(OpenUrlGrant::default()),
1264            // Every kind and level, but no overlays or capture protection.
1265            windows: Some(WindowsGrant::default()),
1266            // The host's functions are never granted without a declaration.
1267            ..Self::default()
1268        }
1269    }
1270
1271    /// Parses `capabilities` strictly: unknown keys are errors. What NSH
1272    /// itself reads (`nsh.json`, bundles, packages, grants) goes through
1273    /// [`Capabilities::from_json_lenient`], which a newer NSH's keys do not
1274    /// break.
1275    pub fn from_json(value: &Value) -> Result<Self, String> {
1276        Self::parse(value, None)
1277    }
1278
1279    /// Parses capabilities a newer NSH may have written (`nsh.json`,
1280    /// bundles, signed packages, grants): what it cannot read never grants
1281    /// anything. An unknown capability is not granted; an unknown key inside
1282    /// one (a restriction this runtime cannot apply) drops what it is in,
1283    /// the whole capability or the `http` grant; a value of a form it does
1284    /// not know drops its capability (or its `http` grant), and the others
1285    /// stay. Declared capabilities allow only what they list, so what is
1286    /// dropped is denied. Only a declaration that is no object is denied
1287    /// whole. Returns what was dropped (`capabilities.bluetooth`, ...) with
1288    /// the capabilities.
1289    pub fn from_json_lenient(value: &Value) -> Result<(Self, Vec<String>), String> {
1290        let mut dropped = Vec::new();
1291        let Value::Object(obj) = value else {
1292            dropped.push(format!(
1293                "capabilities ({value} is not an object): all of them"
1294            ));
1295            return Ok((Self::default(), dropped));
1296        };
1297        // Each capability on its own: one that fails is dropped, alone.
1298        let mut readable = Map::new();
1299        for (key, v) in obj {
1300            let one = Value::Object(Map::from_iter([(key.clone(), v.clone())]));
1301            let mut its_dropped = Vec::new();
1302            match Self::parse(&one, Some(&mut its_dropped)) {
1303                Ok(_) => {
1304                    dropped.append(&mut its_dropped);
1305                    readable.insert(key.clone(), v.clone());
1306                }
1307                Err(e) => dropped.push(format!("capabilities.{key} ({e})")),
1308            }
1309        }
1310        let caps = Self::parse(&Value::Object(readable), Some(&mut Vec::new()))?;
1311        Ok((caps, dropped))
1312    }
1313
1314    /// `dropped`: lenient, recording what unknown keys dropped; `None`:
1315    /// strict.
1316    fn parse(value: &Value, mut dropped: Option<&mut Vec<String>>) -> Result<Self, String> {
1317        const KNOWN: [&str; 16] = [
1318            "windows",
1319            "network",
1320            "webview",
1321            "statusBar",
1322            "clipboard",
1323            "picker",
1324            "share",
1325            "speech",
1326            "notifications",
1327            "audio",
1328            "application",
1329            "homeDir",
1330            "openUrl",
1331            "process",
1332            "fs",
1333            "host",
1334        ];
1335        let obj = object(value, "capabilities")?;
1336        for key in obj.keys().filter(|k| !KNOWN.contains(&k.as_str())) {
1337            match dropped.as_deref_mut() {
1338                // A capability of a newer runtime: not granted.
1339                Some(dropped) => dropped.push(format!("capabilities.{key}")),
1340                None => return Err(unknown_key("capabilities", key, &KNOWN)),
1341            }
1342        }
1343        let lenient = dropped.is_some();
1344        // The `http` grants dropped, recorded once `check` is done with
1345        // `dropped`.
1346        let mut http_dropped = Vec::new();
1347        // Whether `obj` (`what`) has only `keys`; lenient, an unknown key
1348        // drops `name` (what it is in): recorded, and `false` returned.
1349        let mut check = |obj: &Map<String, Value>,
1350                         what: &str,
1351                         keys: &[&str],
1352                         name: &str|
1353         -> Result<bool, String> {
1354            let Some(key) = obj.keys().find(|k| !keys.contains(&k.as_str())) else {
1355                return Ok(true);
1356            };
1357            match dropped.as_deref_mut() {
1358                Some(dropped) => {
1359                    dropped.push(format!("{name} (unknown key `{key}`)"));
1360                    Ok(false)
1361                }
1362                None => Err(unknown_key(what, key, keys)),
1363            }
1364        };
1365        let mut caps = Capabilities::default();
1366        if let Some(network) = obj.get("network") {
1367            let network = object(network, "capabilities.network")?;
1368            if check(
1369                network,
1370                "capabilities.network",
1371                &["hosts", "http", "sockets"],
1372                "capabilities.network",
1373            )? {
1374                if let Some(hosts) = network.get("hosts") {
1375                    caps.network.hosts = patterns(hosts, "capabilities.network.hosts")?;
1376                }
1377                if let Some(sockets) = network.get("sockets") {
1378                    caps.network.sockets = strings(sockets, "capabilities.network.sockets")?
1379                        .iter()
1380                        .map(|s| SocketGrant::new(s))
1381                        .collect::<Result<_, _>>()?;
1382                }
1383                if let Some(http) = network.get("http") {
1384                    let list = http
1385                        .as_array()
1386                        .ok_or("capabilities.network.http must be an array")?;
1387                    for (i, grant) in list.iter().enumerate() {
1388                        let name = format!("capabilities.network.http[{i}]");
1389                        let parsed = object(grant, "capabilities.network.http[]").and_then(|g| {
1390                            let keys = [
1391                                "host",
1392                                "methods",
1393                                "scheme",
1394                                "schemes",
1395                                "port",
1396                                "paths",
1397                                "pathPrefix",
1398                                "pathPrefixes",
1399                                "path_prefixes",
1400                            ];
1401                            Ok(
1402                                match check(g, "capabilities.network.http[]", &keys, &name)? {
1403                                    true => Some(http_grant(g)?),
1404                                    false => None,
1405                                },
1406                            )
1407                        });
1408                        match parsed {
1409                            Ok(Some(grant)) => caps.network.http.push(grant),
1410                            Ok(None) => {}
1411                            // Lenient: a grant of a form this runtime does
1412                            // not know is dropped alone.
1413                            Err(e) if lenient => http_dropped.push(format!("{name} ({e})")),
1414                            Err(e) => return Err(e),
1415                        }
1416                    }
1417                }
1418            }
1419        }
1420        if let Some(webview) = obj.get("webview") {
1421            let webview = object(webview, "capabilities.webview")?;
1422            if check(
1423                webview,
1424                "capabilities.webview",
1425                &["hosts", "input", "media", "runtimeOrigin"],
1426                "capabilities.webview",
1427            )? {
1428                caps.webview = Some(match webview.get("hosts") {
1429                    Some(hosts) => patterns(hosts, "capabilities.webview.hosts")?,
1430                    None => Vec::new(),
1431                });
1432                if let Some(input) = webview.get("input") {
1433                    caps.webview_input = input
1434                        .as_bool()
1435                        .ok_or("capabilities.webview.input must be a boolean")?;
1436                }
1437                if let Some(runtime_origin) = webview.get("runtimeOrigin") {
1438                    caps.webview_runtime_origin = runtime_origin
1439                        .as_bool()
1440                        .ok_or("capabilities.webview.runtimeOrigin must be a boolean")?;
1441                }
1442                if let Some(media) = webview.get("media") {
1443                    caps.webview_media = strings(media, "capabilities.webview.media")?
1444                        .iter()
1445                        .map(|kind| match kind.as_str() {
1446                            "microphone" => Ok(WebMedia::Microphone),
1447                            "camera" => Ok(WebMedia::Camera),
1448                            _ => Err(format!(
1449                                "capabilities.webview.media takes `microphone` and `camera`, not `{kind}`"
1450                            )),
1451                        })
1452                        .collect::<Result<_, _>>()?;
1453                }
1454            }
1455        }
1456        if let Some(status_bar) = obj.get("statusBar") {
1457            caps.status_bar = status_bar
1458                .as_bool()
1459                .ok_or("capabilities.statusBar must be a boolean")?;
1460        }
1461        if let Some(clipboard) = obj.get("clipboard") {
1462            caps.clipboard = clipboard
1463                .as_bool()
1464                .ok_or("capabilities.clipboard must be a boolean")?;
1465        }
1466        if let Some(picker) = obj.get("picker") {
1467            caps.picker = picker
1468                .as_bool()
1469                .ok_or("capabilities.picker must be a boolean")?;
1470        }
1471        if let Some(share) = obj.get("share") {
1472            caps.share = share
1473                .as_bool()
1474                .ok_or("capabilities.share must be a boolean")?;
1475        }
1476        if let Some(speech) = obj.get("speech") {
1477            caps.speech = speech
1478                .as_bool()
1479                .ok_or("capabilities.speech must be a boolean")?;
1480        }
1481        if let Some(notifications) = obj.get("notifications") {
1482            caps.notifications = notifications
1483                .as_bool()
1484                .ok_or("capabilities.notifications must be a boolean")?;
1485        }
1486        if let Some(audio) = obj.get("audio") {
1487            caps.audio = audio
1488                .as_bool()
1489                .ok_or("capabilities.audio must be a boolean")?;
1490        }
1491        if let Some(application) = obj.get("application") {
1492            caps.application = application
1493                .as_bool()
1494                .ok_or("capabilities.application must be a boolean")?;
1495        }
1496        if let Some(home_dir) = obj.get("homeDir") {
1497            caps.home_dir = home_dir
1498                .as_bool()
1499                .ok_or("capabilities.homeDir must be a boolean")?;
1500        }
1501        if let Some(open_url) = obj.get("openUrl") {
1502            match open_url {
1503                Value::Bool(granted) => {
1504                    caps.open_url = granted.then(OpenUrlGrant::default);
1505                }
1506                Value::Object(grant) => {
1507                    if check(
1508                        grant,
1509                        "capabilities.openUrl",
1510                        &["schemes"],
1511                        "capabilities.openUrl",
1512                    )? {
1513                        let schemes = match grant.get("schemes") {
1514                            Some(schemes) => strings(schemes, "capabilities.openUrl.schemes")?,
1515                            None => Vec::new(),
1516                        };
1517                        if schemes.iter().any(|s| {
1518                            s.is_empty()
1519                                || !s.starts_with(|c: char| c.is_ascii_alphabetic())
1520                                || !s
1521                                    .chars()
1522                                    .all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c))
1523                        }) {
1524                            return Err(
1525                                "capabilities.openUrl.schemes needs URL schemes (`https`, `mailto`)"
1526                                    .into(),
1527                            );
1528                        }
1529                        caps.open_url = Some(OpenUrlGrant {
1530                            schemes: schemes.iter().map(|s| s.to_ascii_lowercase()).collect(),
1531                        });
1532                    }
1533                }
1534                _ => {
1535                    return Err(
1536                        "capabilities.openUrl must be a boolean or an object of `schemes`".into(),
1537                    );
1538                }
1539            }
1540        }
1541        if let Some(process) = obj.get("process") {
1542            let process = object(process, "capabilities.process")?;
1543            if check(
1544                process,
1545                "capabilities.process",
1546                &["execute", "exit", "env"],
1547                "capabilities.process",
1548            )? {
1549                if let Some(execute) = process.get("execute") {
1550                    caps.process.execute = strings(execute, "capabilities.process.execute")?;
1551                    if caps.process.execute.iter().any(|s| !valid_command(s)) {
1552                        return Err("capabilities.process.execute needs exact executable names or absolute paths".into());
1553                    }
1554                }
1555                if let Some(exit) = process.get("exit") {
1556                    caps.process.exit = exit
1557                        .as_bool()
1558                        .ok_or("capabilities.process.exit must be a boolean")?;
1559                }
1560                if let Some(env) = process.get("env") {
1561                    caps.process.env = strings(env, "capabilities.process.env")?;
1562                    if caps
1563                        .process
1564                        .env
1565                        .iter()
1566                        .any(|name| name.is_empty() || name.contains(['=', '\0']))
1567                    {
1568                        return Err(
1569                            "capabilities.process.env needs nonempty environment variable names"
1570                                .into(),
1571                        );
1572                    }
1573                }
1574            }
1575        }
1576        if let Some(fs) = obj.get("fs") {
1577            let fs = object(fs, "capabilities.fs")?;
1578            if check(fs, "capabilities.fs", &["read", "write"], "capabilities.fs")? {
1579                for (key, target) in [("read", &mut caps.fs.read), ("write", &mut caps.fs.write)] {
1580                    if let Some(value) = fs.get(key) {
1581                        *target = strings(value, &format!("capabilities.fs.{key}"))?;
1582                        for root in target.iter() {
1583                            validate_path_pattern(root)?;
1584                        }
1585                    }
1586                }
1587            }
1588        }
1589        if let Some(windows) = obj.get("windows") {
1590            match windows {
1591                Value::Bool(granted) => caps.windows = granted.then(WindowsGrant::default),
1592                Value::Object(grant) => {
1593                    if check(
1594                        grant,
1595                        "capabilities.windows",
1596                        &["kinds", "levels", "max", "overlay"],
1597                        "capabilities.windows",
1598                    )? {
1599                        caps.windows = Some(windows_grant(grant)?);
1600                    }
1601                }
1602                _ => {
1603                    return Err(
1604                        "capabilities.windows must be a boolean or an object of `kinds`, `levels`, `max` and `overlay`"
1605                            .into(),
1606                    );
1607                }
1608            }
1609        }
1610        if let Some(host) = obj.get("host") {
1611            caps.host = match host {
1612                Value::Bool(all) => {
1613                    if *all {
1614                        vec!["*".into()]
1615                    } else {
1616                        Vec::new()
1617                    }
1618                }
1619                _ => {
1620                    let names = strings(host, "capabilities.host")
1621                        .map_err(|e| format!("{e} (or a boolean)"))?;
1622                    if let Some(bad) = names.iter().find(|n| match n.strip_suffix('*') {
1623                        Some(prefix) => !prefix.is_empty() && !valid_host_name(prefix),
1624                        None => !valid_host_name(n),
1625                    }) {
1626                        return Err(format!(
1627                            "capabilities.host: invalid function `{bad}` (a name of {HOST_NAME_CHARS}, or a prefix of them ending in `*`)"
1628                        ));
1629                    }
1630                    names
1631                }
1632            };
1633        }
1634        if let Some(dropped) = dropped {
1635            dropped.append(&mut http_dropped);
1636        }
1637        Ok(caps)
1638    }
1639
1640    /// The JSON form [`Capabilities::from_json`] reads.
1641    pub fn to_json(&self) -> Value {
1642        let mut obj = self.to_json_without_windows();
1643        // Only when granted: older runtimes read what newer signers write.
1644        if let (Value::Object(obj), Some(w)) = (&mut obj, &self.windows) {
1645            let mut o = Map::new();
1646            if !w.kinds.is_empty() {
1647                o.insert(
1648                    "kinds".into(),
1649                    w.kinds
1650                        .iter()
1651                        .map(|k| window_kind_name(*k))
1652                        .collect::<Vec<_>>()
1653                        .into(),
1654                );
1655            }
1656            if !w.levels.is_empty() {
1657                o.insert(
1658                    "levels".into(),
1659                    w.levels
1660                        .iter()
1661                        .map(|l| window_level_name(*l))
1662                        .collect::<Vec<_>>()
1663                        .into(),
1664                );
1665            }
1666            if let Some(max) = w.max {
1667                o.insert("max".into(), max.into());
1668            }
1669            if w.overlay {
1670                o.insert("overlay".into(), true.into());
1671            }
1672            obj.insert("windows".into(), Value::Object(o));
1673        }
1674        obj
1675    }
1676
1677    fn to_json_without_windows(&self) -> Value {
1678        let list =
1679            |l: &[HostPattern]| Value::from(l.iter().map(|p| p.0.clone()).collect::<Vec<_>>());
1680        let mut network = Map::new();
1681        network.insert("hosts".into(), list(&self.network.hosts));
1682        let http: Vec<Value> = self
1683            .network
1684            .http
1685            .iter()
1686            .map(|g| {
1687                let mut o = Map::new();
1688                o.insert("host".into(), g.host.0.clone().into());
1689                if !g.methods.is_empty() {
1690                    o.insert("methods".into(), g.methods.clone().into());
1691                }
1692                if !g.schemes.is_empty() {
1693                    o.insert("schemes".into(), g.schemes.clone().into());
1694                }
1695                if let Some(port) = g.port {
1696                    o.insert("port".into(), port.into());
1697                }
1698                if !g.paths.is_empty() {
1699                    o.insert("paths".into(), g.paths.clone().into());
1700                }
1701                if !g.path_prefixes.is_empty() {
1702                    o.insert("pathPrefixes".into(), g.path_prefixes.clone().into());
1703                }
1704                Value::Object(o)
1705            })
1706            .collect();
1707        network.insert("http".into(), http.into());
1708        if !self.network.sockets.is_empty() {
1709            let sockets: Vec<String> = self
1710                .network
1711                .sockets
1712                .iter()
1713                .map(SocketGrant::to_string_form)
1714                .collect();
1715            network.insert("sockets".into(), sockets.into());
1716        }
1717        let mut obj = Map::new();
1718        obj.insert("network".into(), Value::Object(network));
1719        obj.insert(
1720            "process".into(),
1721            serde_json::json!({"execute": self.process.execute, "exit": self.process.exit, "env": self.process.env}),
1722        );
1723        obj.insert(
1724            "fs".into(),
1725            serde_json::json!({"read": self.fs.read, "write": self.fs.write}),
1726        );
1727        if let Some(hosts) = &self.webview {
1728            let mut w = Map::new();
1729            w.insert("hosts".into(), list(hosts));
1730            // Only when granted: older runtimes read what newer signers write.
1731            if self.webview_input {
1732                w.insert("input".into(), true.into());
1733            }
1734            if self.webview_runtime_origin {
1735                w.insert("runtimeOrigin".into(), true.into());
1736            }
1737            if !self.webview_media.is_empty() {
1738                let media = self.webview_media.iter().map(|m| m.as_str().into());
1739                w.insert("media".into(), Value::Array(media.collect()));
1740            }
1741            obj.insert("webview".into(), Value::Object(w));
1742        }
1743        obj.insert("statusBar".into(), self.status_bar.into());
1744        obj.insert("clipboard".into(), self.clipboard.into());
1745        obj.insert("picker".into(), self.picker.into());
1746        // Only when granted: older runtimes read what newer signers write.
1747        if self.share {
1748            obj.insert("share".into(), true.into());
1749        }
1750        if self.speech {
1751            obj.insert("speech".into(), true.into());
1752        }
1753        if self.notifications {
1754            obj.insert("notifications".into(), true.into());
1755        }
1756        if self.audio {
1757            obj.insert("audio".into(), true.into());
1758        }
1759        if self.application {
1760            obj.insert("application".into(), true.into());
1761        }
1762        if self.home_dir {
1763            obj.insert("homeDir".into(), true.into());
1764        }
1765        if !self.host.is_empty() {
1766            obj.insert("host".into(), self.host.clone().into());
1767        }
1768        obj.insert(
1769            "openUrl".into(),
1770            match &self.open_url {
1771                None => false.into(),
1772                Some(grant) if grant.schemes.is_empty() => true.into(),
1773                Some(grant) => serde_json::json!({ "schemes": grant.schemes }),
1774            },
1775        );
1776        Value::Object(obj)
1777    }
1778
1779    fn allows_http(&self, method: &str, url: &UrlParts<'_>) -> bool {
1780        if !matches!(url.scheme.as_str(), "http" | "https" | "ws" | "wss") {
1781            return false;
1782        }
1783        self.network.hosts.iter().any(|h| h.matches(&url.host))
1784            || self.network.http.iter().any(|g| g.allows(method, url))
1785    }
1786
1787    /// Whether `method` may reach every host, port and path of `scheme`.
1788    fn allows_http_anywhere(&self, method: &str, scheme: &str) -> bool {
1789        matches!(scheme, "http" | "https" | "ws" | "wss")
1790            && (self.network.hosts.iter().any(HostPattern::is_any)
1791                || self
1792                    .network
1793                    .http
1794                    .iter()
1795                    .any(|g| g.allows_anywhere(method, scheme)))
1796    }
1797
1798    fn allows_host(&self, name: &str) -> bool {
1799        self.host.iter().any(|g| match g.strip_suffix('*') {
1800            Some(prefix) => name.starts_with(prefix),
1801            None => g == name,
1802        })
1803    }
1804
1805    fn allows_webview(&self, url: &UrlParts<'_>) -> bool {
1806        matches!(url.scheme.as_str(), "http" | "https")
1807            && self
1808                .webview
1809                .as_ref()
1810                .is_some_and(|hosts| hosts.iter().any(|h| h.matches(&url.host)))
1811    }
1812
1813    /// Whether a web view may show every host of `scheme`.
1814    fn allows_webview_anywhere(&self, scheme: &str) -> bool {
1815        matches!(scheme, "http" | "https")
1816            && self
1817                .webview
1818                .as_ref()
1819                .is_some_and(|hosts| hosts.iter().any(HostPattern::is_any))
1820    }
1821}
1822
1823/// What host function names (`nsh/host`) are made of, for messages.
1824pub const HOST_NAME_CHARS: &str = "1 to 128 of A-Z a-z 0-9 _ . : -, without `..`";
1825
1826/// Whether `name` may name a function of the embedding host: 1 to 128 of
1827/// `[A-Za-z0-9_.:-]`, without `..`. Hosts may put a name in a path or a URL,
1828/// so no name escapes the prefix a grant gives it.
1829pub fn valid_host_name(name: &str) -> bool {
1830    (1..=128).contains(&name.len())
1831        && name
1832            .bytes()
1833            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b':' | b'-'))
1834        && !name.contains("..")
1835}
1836
1837fn valid_command(command: &str) -> bool {
1838    !command.is_empty()
1839        && !command.contains(['\0', '*'])
1840        // `absolute`, not `Path::is_absolute`: in the browser that is false for
1841        // every path, so `/bin/sh` refused the whole manifest and the app never
1842        // started there. A rooted path counts on Windows too, where
1843        // `is_absolute` wants a drive (`/bin/sh`): one manifest serves every
1844        // platform.
1845        && (Path::new(command).has_root()
1846            || absolute(Path::new(command))
1847            // A bare name has no drive (`C:git` is relative to the host's
1848            // directory on drive C).
1849            || (!command.contains(['/', '\\', ':']) && command != "." && command != "..")
1850            // A bundled file of the app's, run where the host put it
1851            // (`process.run` of an `asset:/…` program resolves it there).
1852            || command.starts_with("asset:/"))
1853}
1854
1855fn validate_path_pattern(path: &str) -> Result<(), String> {
1856    if [
1857        "$HOME",
1858        "${HOME}",
1859        "$USERPROFILE",
1860        "${USERPROFILE}",
1861        "%USERPROFILE%",
1862        "~",
1863    ]
1864    .into_iter()
1865    .any(|prefix| {
1866        path.strip_prefix(prefix)
1867            .is_some_and(|tail| tail.is_empty() || tail.starts_with(['/', '\\']))
1868    }) {
1869        return Err("use ${homeDir} for the native home directory".into());
1870    }
1871    let placeholder = ["${dataDir}", "${pluginDir}", "${homeDir}"]
1872        .into_iter()
1873        .find(|prefix| path.starts_with(prefix));
1874    let tail = placeholder.and_then(|prefix| path.strip_prefix(prefix));
1875    if path.is_empty()
1876        || path.contains(['\0', '*'])
1877        || tail.is_some_and(|s| !s.is_empty() && !s.starts_with('/'))
1878        || (placeholder.is_none() && path.contains("${"))
1879        || tail.is_some_and(|s| s.contains("${"))
1880        || Path::new(path)
1881            .components()
1882            .any(|p| matches!(p, Component::ParentDir))
1883    {
1884        return Err(
1885            "filesystem roots must use valid host placeholders and contain no traversal".into(),
1886        );
1887    }
1888    Ok(())
1889}
1890
1891/// `path` resolved as [`std::fs::canonicalize`] resolves it, in the plain
1892/// form where Windows has one: canonicalizing there gives verbatim paths
1893/// (`\\?\C:\app`), which no path a host or app writes starts with, and
1894/// in which `/` separates nothing. Grants, requests and trusted anchors
1895/// are all compared in this form.
1896pub fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
1897    let path = std::fs::canonicalize(path)?;
1898    #[cfg(windows)]
1899    if let Some(plain) = path.to_str().and_then(without_verbatim_prefix) {
1900        return Ok(PathBuf::from(plain));
1901    }
1902    Ok(path)
1903}
1904
1905/// The plain form of the Windows verbatim path `path` (`\\?\C:\a` →
1906/// `C:\a`, `\\?\UNC\server\share\a` → `\\server\share\a`), when it
1907/// names the same file: under the legacy length limit, and no component
1908/// that the plain form would read otherwise (empty, `.` or `..`, holding
1909/// `/`, ending in a dot or space, or a device name such as `NUL` or
1910/// `com1.txt`). `None` for any other path, which then stays as it is.
1911/// Text only, so its tests run on every platform.
1912#[cfg_attr(not(windows), allow(dead_code))]
1913fn without_verbatim_prefix(path: &str) -> Option<String> {
1914    let rest = path.strip_prefix(r"\\?\")?;
1915    let (plain, tail) = if let Some(unc) = rest.strip_prefix(r"UNC\") {
1916        (format!(r"\\{unc}"), unc)
1917    } else {
1918        let bytes = rest.as_bytes();
1919        if bytes.len() < 3 || !bytes[0].is_ascii_alphabetic() || &bytes[1..3] != b":\\" {
1920            return None;
1921        }
1922        (rest.to_owned(), &rest[3..])
1923    };
1924    if plain.len() >= 260 {
1925        return None;
1926    }
1927    // A trailing separator ends a root (`C:\`) or a directory.
1928    let tail = tail.strip_suffix('\\').unwrap_or(tail);
1929    let device = |name: &str| {
1930        let stem = name.split('.').next().unwrap_or(name).trim_end();
1931        ["CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"]
1932            .iter()
1933            .any(|d| stem.eq_ignore_ascii_case(d))
1934            || (stem.len() == 4
1935                && ["COM", "LPT"]
1936                    .iter()
1937                    .any(|d| stem[..3].eq_ignore_ascii_case(d))
1938                && matches!(stem.as_bytes()[3], b'1'..=b'9'))
1939    };
1940    let plain_component = |c: &str| {
1941        !c.is_empty()
1942            && c != "."
1943            && c != ".."
1944            && !c.contains('/')
1945            && !c.ends_with(['.', ' '])
1946            && !device(c)
1947    };
1948    (tail.is_empty() || tail.split('\\').all(plain_component)).then_some(plain)
1949}
1950
1951// Resolve every existing ancestor, including symlinks. Missing tails are
1952// permitted so creation receives the same boundary checks as reads.
1953/// Why [`Access::authorize_file`] refused a path.
1954#[derive(Debug, Clone, PartialEq, Eq)]
1955#[non_exhaustive]
1956pub enum FileRefusal {
1957    /// It names no file it can check: relative, with `..`, an unknown
1958    /// anchor, or unreadable (why).
1959    Invalid(String),
1960    /// No grant of the capabilities covers it (why).
1961    NotGranted(String),
1962}
1963
1964impl std::fmt::Display for FileRefusal {
1965    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1966        match self {
1967            FileRefusal::Invalid(why) | FileRefusal::NotGranted(why) => f.write_str(why),
1968        }
1969    }
1970}
1971
1972fn resolved_path(path: &Path) -> Result<PathBuf, String> {
1973    if !absolute(path) || path.components().any(|p| matches!(p, Component::ParentDir)) {
1974        return Err("filesystem paths must be absolute and contain no parent traversal".into());
1975    }
1976    let mut cursor = path;
1977    let mut tail = Vec::new();
1978    loop {
1979        match std::fs::symlink_metadata(cursor) {
1980            Ok(_) => {
1981                let mut resolved = canonicalize(cursor).map_err(|e| e.to_string())?;
1982                for part in tail.into_iter().rev() {
1983                    resolved.push(part);
1984                }
1985                return Ok(resolved);
1986            }
1987            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1988                tail.push(
1989                    cursor
1990                        .file_name()
1991                        .ok_or("invalid filesystem path")?
1992                        .to_owned(),
1993                );
1994                cursor = cursor.parent().ok_or("invalid filesystem path")?;
1995            }
1996            Err(e) => return Err(e.to_string()),
1997        }
1998    }
1999}
2000
2001fn object<'a>(value: &'a Value, what: &str) -> Result<&'a Map<String, Value>, String> {
2002    value
2003        .as_object()
2004        .ok_or_else(|| format!("{what} must be an object"))
2005}
2006
2007const WINDOW_KINDS: [(&str, crate::desktop::WindowKind); 5] = [
2008    ("normal", crate::desktop::WindowKind::Normal),
2009    ("dialog", crate::desktop::WindowKind::Dialog),
2010    ("panel", crate::desktop::WindowKind::Panel),
2011    ("popup", crate::desktop::WindowKind::Popup),
2012    ("overlay", crate::desktop::WindowKind::Overlay),
2013];
2014
2015const WINDOW_LEVELS: [(&str, crate::desktop::WindowLevel); 4] = [
2016    ("normal", crate::desktop::WindowLevel::Normal),
2017    ("floating", crate::desktop::WindowLevel::Floating),
2018    ("aboveDock", crate::desktop::WindowLevel::AboveDock),
2019    ("desktopIcon", crate::desktop::WindowLevel::DesktopIcon),
2020];
2021
2022fn window_kind_name(kind: crate::desktop::WindowKind) -> &'static str {
2023    WINDOW_KINDS
2024        .iter()
2025        .find(|(_, k)| *k == kind)
2026        .map_or("normal", |(n, _)| n)
2027}
2028
2029fn window_level_name(level: crate::desktop::WindowLevel) -> &'static str {
2030    WINDOW_LEVELS
2031        .iter()
2032        .find(|(_, l)| *l == level)
2033        .map_or("normal", |(n, _)| n)
2034}
2035
2036/// `capabilities.windows` as an object.
2037fn windows_grant(grant: &Map<String, Value>) -> Result<WindowsGrant, String> {
2038    let mut out = WindowsGrant::default();
2039    if let Some(kinds) = grant.get("kinds") {
2040        for name in strings(kinds, "capabilities.windows.kinds")? {
2041            let Some((_, kind)) = WINDOW_KINDS.iter().find(|(n, _)| *n == name) else {
2042                return Err(format!(
2043                    "capabilities.windows.kinds: unknown kind `{name}` (normal, dialog, panel, popup or overlay)"
2044                ));
2045            };
2046            out.kinds.push(*kind);
2047        }
2048    }
2049    if let Some(levels) = grant.get("levels") {
2050        for name in strings(levels, "capabilities.windows.levels")? {
2051            let Some((_, level)) = WINDOW_LEVELS.iter().find(|(n, _)| *n == name) else {
2052                return Err(format!(
2053                    "capabilities.windows.levels: unknown level `{name}` (normal, floating, aboveDock or desktopIcon)"
2054                ));
2055            };
2056            out.levels.push(*level);
2057        }
2058    }
2059    if let Some(max) = grant.get("max") {
2060        out.max = Some(
2061            max.as_u64()
2062                .and_then(|m| u32::try_from(m).ok())
2063                .ok_or("capabilities.windows.max must be a whole number")?,
2064        );
2065    }
2066    if let Some(v) = grant.get("overlay") {
2067        out.overlay = v
2068            .as_bool()
2069            .ok_or("capabilities.windows.overlay must be a boolean")?;
2070    }
2071    Ok(out)
2072}
2073
2074fn unknown_key(what: &str, key: &str, known: &[&str]) -> String {
2075    format!("{what}: unknown key `{key}` (known: {})", known.join(", "))
2076}
2077
2078fn strings(value: &Value, what: &str) -> Result<Vec<String>, String> {
2079    value
2080        .as_array()
2081        .and_then(|a| a.iter().map(|v| v.as_str().map(str::to_owned)).collect())
2082        .ok_or_else(|| format!("{what} must be an array of strings"))
2083}
2084
2085/// One `network.http` rule: `host`, and any of `methods`, `scheme` /
2086/// `schemes`, `port`, `paths` and `pathPrefix` / `pathPrefixes` /
2087/// `path_prefixes` (the spellings of one key are merged).
2088fn http_grant(g: &Map<String, Value>) -> Result<HttpGrant, String> {
2089    let what = "capabilities.network.http[]";
2090    let host = g
2091        .get("host")
2092        .and_then(Value::as_str)
2093        .ok_or_else(|| format!("{what} needs a `host`"))?;
2094    // A key as a string or an array of strings.
2095    let list = |key: &str| -> Result<Vec<String>, String> {
2096        match g.get(key) {
2097            None => Ok(Vec::new()),
2098            Some(Value::String(s)) => Ok(vec![s.clone()]),
2099            Some(v) => strings(v, &format!("{what}.{key}")),
2100        }
2101    };
2102    let methods = list("methods")?
2103        .into_iter()
2104        .map(|m| {
2105            if !m.is_empty() && m.bytes().all(|b| b.is_ascii_alphabetic() || b == b'-') {
2106                Ok(m.to_ascii_uppercase())
2107            } else {
2108                Err(format!("{what}.methods: `{m}` is not an HTTP method"))
2109            }
2110        })
2111        .collect::<Result<Vec<_>, _>>()?;
2112    let mut schemes = Vec::new();
2113    for scheme in list("scheme")?.into_iter().chain(list("schemes")?) {
2114        let scheme = scheme.to_ascii_lowercase();
2115        if !matches!(scheme.as_str(), "http" | "https" | "ws" | "wss") {
2116            return Err(format!(
2117                "{what}.schemes: `{scheme}` is not http, https, ws or wss"
2118            ));
2119        }
2120        if !schemes.contains(&scheme) {
2121            schemes.push(scheme);
2122        }
2123    }
2124    let port = match g.get("port") {
2125        None => None,
2126        Some(v) => Some(
2127            v.as_u64()
2128                .and_then(|p| u16::try_from(p).ok())
2129                .filter(|&p| p != 0)
2130                .ok_or_else(|| format!("{what}.port must be a port from 1 to 65535"))?,
2131        ),
2132    };
2133    let paths = list("paths")?;
2134    let mut path_prefixes = Vec::new();
2135    for prefix in list("pathPrefix")?
2136        .into_iter()
2137        .chain(list("pathPrefixes")?)
2138        .chain(list("path_prefixes")?)
2139    {
2140        if !path_prefixes.contains(&prefix) {
2141            path_prefixes.push(prefix);
2142        }
2143    }
2144    // A path is matched as written: a pattern in it would match nothing.
2145    if let Some(bad) = paths
2146        .iter()
2147        .chain(&path_prefixes)
2148        .find(|p| !p.starts_with('/') || p.contains(['*', '?', '#']))
2149    {
2150        return Err(format!(
2151            "{what}: path `{bad}` must start with / and has no `*`, `?` or `#` (paths match as written)"
2152        ));
2153    }
2154    // Requests are matched as WHATWG's parser sends them (`/my%20photos`),
2155    // so the grant's paths are read the same way.
2156    let as_sent = |list: Vec<String>| -> Result<Vec<String>, String> {
2157        let mut sent = Vec::new();
2158        for path in list {
2159            let path = path_as_sent(&path).ok_or_else(|| {
2160                format!("{what}: path `{path}` has a `.` or `..` segment, which no request sends")
2161            })?;
2162            if !sent.contains(&path) {
2163                sent.push(path);
2164            }
2165        }
2166        Ok(sent)
2167    };
2168    let paths = as_sent(paths)?;
2169    let path_prefixes = as_sent(path_prefixes)?;
2170    Ok(HttpGrant {
2171        host: HostPattern::new(host)?,
2172        methods,
2173        schemes,
2174        port,
2175        paths,
2176        path_prefixes,
2177    })
2178}
2179
2180fn patterns(value: &Value, what: &str) -> Result<Vec<HostPattern>, String> {
2181    strings(value, what)?
2182        .iter()
2183        .map(|p| HostPattern::new(p))
2184        .collect()
2185}
2186
2187/// What an app may do: its declaration and the embedder's grant (when the
2188/// embedder limits it); an action must be allowed by both.
2189#[derive(Debug, Clone, PartialEq, Eq)]
2190pub struct Access {
2191    /// What the app declared (everything without a declaration).
2192    pub declared: Capabilities,
2193    /// What the embedding app grants it at most (`None`: what it declared).
2194    pub granted: Option<Capabilities>,
2195}
2196
2197impl Default for Access {
2198    fn default() -> Self {
2199        Self::all()
2200    }
2201}
2202
2203impl Access {
2204    /// Everything allowed.
2205    pub fn all() -> Self {
2206        Self {
2207            declared: Capabilities::all(),
2208            granted: None,
2209        }
2210    }
2211
2212    fn each(&self, f: impl Fn(&Capabilities) -> bool) -> bool {
2213        f(&self.declared) && self.granted.as_ref().is_none_or(f)
2214    }
2215
2216    /// True when nothing is restricted (no check needed, redirects may be
2217    /// followed by the platform).
2218    pub fn is_unrestricted(&self) -> bool {
2219        let all = Capabilities::all();
2220        self.declared == all && self.granted.as_ref().is_none_or(|g| *g == all)
2221    }
2222
2223    /// Whether an exact command is declared and granted. These capabilities
2224    /// always require explicit opt-in, including for legacy standalone apps.
2225    pub fn allows_process(&self, command: &str) -> bool {
2226        valid_command(command) && self.each(|c| c.process.execute.iter().any(|p| p == command))
2227    }
2228
2229    /// Whether the app may request an exit from its host. This never exits the
2230    /// embedding process by itself; the host supplies the meaning of the request.
2231    pub fn allows_exit(&self) -> bool {
2232        self.each(|caps| caps.process.exit)
2233    }
2234
2235    /// Whether an environment variable is visible. The built-in metadata names
2236    /// are always visible; other names require both app and host permission.
2237    pub fn allows_env(&self, name: &str) -> bool {
2238        let defaults = include_str!("default-env").lines().filter_map(|line| {
2239            let name = line.split('#').next().unwrap_or_default().trim();
2240            (!name.is_empty()).then_some(name)
2241        });
2242        defaults
2243            .into_iter()
2244            .any(|allowed| env_names_match(allowed, name))
2245            || self.each(|caps| {
2246                caps.process
2247                    .env
2248                    .iter()
2249                    .any(|allowed| env_names_match(allowed, name))
2250            })
2251    }
2252
2253    /// Resolve a filesystem path within both the declaration and host grant.
2254    /// `data_dir` is an app-specific directory supplied only by the host.
2255    pub fn authorize_file(
2256        &self,
2257        path: &Path,
2258        data_dir: &Path,
2259        write: bool,
2260    ) -> Result<PathBuf, FileRefusal> {
2261        self.authorize_file_with_paths(path, data_dir, &TrustedPaths::default(), write)
2262    }
2263
2264    /// Authorize a file with trusted host source and home directory anchors.
2265    pub fn authorize_file_with_paths(
2266        &self,
2267        path: &Path,
2268        data_dir: &Path,
2269        paths: &TrustedPaths,
2270        write: bool,
2271    ) -> Result<PathBuf, FileRefusal> {
2272        let requested = if let Some(text) = path.to_str().filter(|s| s.starts_with("${")) {
2273            paths
2274                .resolve_root(text, data_dir)
2275                .map_err(FileRefusal::Invalid)?
2276        } else {
2277            path.to_owned()
2278        };
2279        let resolved = resolved_path(&requested).map_err(FileRefusal::Invalid)?;
2280        let allowed = self.each(|c| {
2281            let roots = if write { &c.fs.write } else { &c.fs.read };
2282            roots.iter().any(|root| {
2283                paths
2284                    .resolve_root(root, data_dir)
2285                    .and_then(|r| resolved_path(&r))
2286                    .is_ok_and(|root| resolved.starts_with(root))
2287            })
2288        });
2289        if allowed {
2290            Ok(resolved)
2291        } else {
2292            Err(FileRefusal::NotGranted(format!(
2293                "filesystem {} is not granted by capabilities.fs",
2294                if write { "write" } else { "read" }
2295            )))
2296        }
2297    }
2298
2299    /// Whether a raw TCP connection to `host:port` may be opened: only an
2300    /// exact `network.sockets` grant allows it, never `hosts` or `http`
2301    /// grants, and [`Capabilities::all`] grants none.
2302    pub fn allows_socket(&self, host: &str, port: u16) -> bool {
2303        if host.is_empty() || host.contains(['/', '@', '?', '#', '\0']) {
2304            return false;
2305        }
2306        let host = host.to_ascii_lowercase();
2307        let host = host
2308            .strip_prefix('[')
2309            .and_then(|h| h.strip_suffix(']'))
2310            .unwrap_or(&host)
2311            .trim_end_matches('.');
2312        self.each(|c| {
2313            c.network
2314                .sockets
2315                .iter()
2316                .any(|grant| grant.port == port && grant.host == host)
2317        })
2318    }
2319
2320    /// Whether a WebSocket to `url` (`ws:` / `wss:`) may connect. The
2321    /// handshake is an HTTP GET, so it is checked as a GET of the same URL
2322    /// over `http:` / `https:`; legacy rules may also list `ws` / `wss`.
2323    pub fn allows_websocket(&self, url: &str) -> bool {
2324        let http = if let Some(rest) = url.strip_prefix("wss:") {
2325            format!("https:{rest}")
2326        } else if let Some(rest) = url.strip_prefix("ws:") {
2327            format!("http:{rest}")
2328        } else {
2329            return false;
2330        };
2331        self.allows_http("GET", &http) || self.allows_http("GET", url)
2332    }
2333
2334    /// Whether `fetch(url, { method })` may go out. `asset:` URIs are always
2335    /// allowed.
2336    pub fn allows_http(&self, method: &str, url: &str) -> bool {
2337        if url.starts_with("asset:") {
2338            return true;
2339        }
2340        match read_url(url) {
2341            // A URL WHATWG's parser cannot read is none the loaders load.
2342            Ok(parts) => {
2343                url::Url::parse(url).is_ok_and(|whatwg| self.allows_parts(method, parts, &whatwg))
2344            }
2345            // Whatever host a parser reads, a grant of every host covers it.
2346            Err(Unread::Ambiguous(scheme)) => {
2347                self.each(|c| c.allows_http_anywhere(method, &scheme))
2348            }
2349            Err(Unread::NotUrl) => false,
2350        }
2351    }
2352
2353    /// [`Self::allows_http`] for `url` that `whatwg` is WHATWG's parse of:
2354    /// a rule's paths are matched against the path a server is sent, dot
2355    /// segments, percent-encoded ones too, resolved as that parser resolves
2356    /// them.
2357    fn allows_parsed(&self, method: &str, url: &str, whatwg: &url::Url) -> bool {
2358        match read_url(url) {
2359            Ok(parts) => self.allows_parts(method, parts, whatwg),
2360            Err(Unread::Ambiguous(scheme)) => {
2361                self.each(|c| c.allows_http_anywhere(method, &scheme))
2362            }
2363            Err(Unread::NotUrl) => false,
2364        }
2365    }
2366
2367    /// Whether the rules grant `parts` with the path WHATWG's parse of the
2368    /// URL, `whatwg`, sends.
2369    fn allows_parts(&self, method: &str, parts: UrlParts<'_>, whatwg: &url::Url) -> bool {
2370        let parts = UrlParts {
2371            path: whatwg.path(),
2372            ..parts
2373        };
2374        self.each(|c| c.allows_http(method, &parts))
2375    }
2376
2377    /// The URL a request to `url` goes out with, if the app may make it:
2378    /// its WHATWG serialization, which [`Self::allows_http`] checks, so the
2379    /// loader requests what was granted. `asset:` URIs stay as written.
2380    pub fn http_url<'a>(&self, method: &str, url: &'a str) -> Option<Cow<'a, str>> {
2381        if url.starts_with("asset:") {
2382            return Some(Cow::Borrowed(url));
2383        }
2384        let whatwg = url::Url::parse(url).ok()?;
2385        self.allows_parsed(method, whatwg.as_str(), &whatwg)
2386            .then(|| written_or(url, whatwg.into()))
2387    }
2388
2389    /// Whether a media URL (image, video, canvas image) may be loaded:
2390    /// [`Self::media_url`] with no base, so a `//` source names no URL, and
2391    /// no file roots, so an app with capabilities loads no local file.
2392    pub fn allows_media(&self, uri: &str) -> bool {
2393        self.media_url(uri, None, None).is_some()
2394    }
2395
2396    /// What a media source (image, video, canvas image, sound) loads, if the
2397    /// app may load it. `asset:` URIs are the app's own files; `data:` URIs
2398    /// and `blob:` URLs (`URL.createObjectURL`) are bytes the app already
2399    /// has: these stay as written. A source with no scheme that does not
2400    /// start with `/` or a backslash is relative: the page's with a base,
2401    /// and with none (a native app, whose players read it against the
2402    /// working directory) it loads nothing. A local
2403    /// file (a `file:` URL; with no base, as in native apps, an absolute
2404    /// path; on the web `/…` is the page's) is read under `files`, the
2405    /// `capabilities.fs.read` roots ([`MediaFiles`]; `None`: none), and
2406    /// loads as its canonical path, in the form it was written. A source with a
2407    /// scheme, or one that starts with `//` (resolved against `base`, the
2408    /// page's URL on the web, whose scheme it takes; with no base it names
2409    /// no URL, as `fetch`'s), names a host: it is checked as WHATWG's parser
2410    /// reads it and loads as its serialization, so the loader loads what
2411    /// was granted. A backslash before the query or a control character is
2412    /// read differently by other parsers (Foundation's `NSURL`): only a
2413    /// grant of every host covers such a source, as written. An app without
2414    /// capabilities loads what it writes, unchecked.
2415    pub fn media_url<'a>(
2416        &self,
2417        uri: &'a str,
2418        base: Option<&str>,
2419        files: Option<&MediaFiles>,
2420    ) -> Option<Cow<'a, str>> {
2421        if is_own_media(uri) {
2422            // A bundled file's path stays in the app's files, as `fetch`
2423            // reads one; an app without capabilities reads what it names.
2424            let inside = !starts_with_ignoring_case(uri, "asset:") || is_inside_assets(uri);
2425            return (inside || self.is_unrestricted()).then_some(Cow::Borrowed(uri));
2426        }
2427        if self.is_unrestricted() {
2428            return media_as_written(uri, |url| self.allows_http("GET", url))
2429                .then_some(Cow::Borrowed(uri));
2430        }
2431        let file_url = starts_with_ignoring_case(uri, "file:");
2432        if (base.is_none() || file_url)
2433            && let Some(path) = local_file(uri)
2434        {
2435            let real = files?.readable(&path?)?;
2436            let loads = if file_url {
2437                file_url_of(&real)?
2438            } else {
2439                real.into_os_string().into_string().ok()?
2440            };
2441            return Some(written_or(uri, loads));
2442        }
2443        // WHATWG's parser reads the source with leading and trailing spaces
2444        // and C0 controls and every tab and newline dropped.
2445        let stripped = whatwg_stripped(uri);
2446        let scheme = scheme_of(&stripped);
2447        let names_host = scheme.is_some()
2448            || stripped.starts_with("//")
2449            || stripped.starts_with(['\\'])
2450            || stripped.starts_with("/\\");
2451        if !names_host {
2452            // A relative path is the page's on the web. A native app has no
2453            // page: the platforms read one against the process's working
2454            // directory (desktop videos, Android images) or not at all.
2455            return (base.is_some() || uri.trim().is_empty()).then_some(Cow::Borrowed(uri));
2456        }
2457        // Only a source without a scheme takes the base's.
2458        let base = || base.and_then(|b| url::Url::parse(b).ok());
2459        // Spaces and C0 controls around it, which WHATWG's parser drops,
2460        // are dropped here too, and the loader gets the serialization, never
2461        // the source as written. What other parsers read another way (a
2462        // backslash, a control inside, tabs and newlines included, an odd
2463        // host) is ambiguous (#979).
2464        let trimmed = uri.trim_matches(|c: char| c <= ' ');
2465        let head = trimmed.split(['?', '#']).next().unwrap_or(trimmed);
2466        if head.contains('\\')
2467            || trimmed.bytes().any(|b| b.is_ascii_control())
2468            || matches!(read_url(trimmed), Err(Unread::Ambiguous(_)))
2469        {
2470            let scheme = match scheme {
2471                Some(scheme) => scheme.to_ascii_lowercase(),
2472                None => base()?.scheme().to_owned(),
2473            };
2474            return self
2475                .each(|c| c.allows_http_anywhere("GET", &scheme))
2476                .then_some(Cow::Borrowed(uri));
2477        }
2478        let parsed = match scheme {
2479            Some(_) => url::Url::parse(trimmed),
2480            None => base()?.join(trimmed),
2481        }
2482        .ok()?;
2483        self.allows_parsed("GET", parsed.as_str(), &parsed)
2484            .then(|| written_or(uri, parsed.into()))
2485    }
2486
2487    /// The next URL of a media load that was redirected from `base` to
2488    /// `location`, if the app may load it: the redirect must stay on
2489    /// `http(s)` and pass the same check as a first request, so loaders
2490    /// follow redirects themselves, one hop at a time, and never contact
2491    /// a target the app is not granted.
2492    pub fn media_redirect(&self, base: &str, location: &str) -> Result<String, String> {
2493        let url = resolve_reference(base, location);
2494        if !(url.starts_with("http://") || url.starts_with("https://")) {
2495            return Err(format!("redirect to `{url}` is not an http(s) URL"));
2496        }
2497        if !self.is_unrestricted() && !self.allows_media(&url) {
2498            return Err(format!(
2499                "redirect to `{url}` is not granted by capabilities.network"
2500            ));
2501        }
2502        Ok(url)
2503    }
2504
2505    /// Whether web views are granted at all (inline HTML needs only this).
2506    pub fn allows_webviews(&self) -> bool {
2507        self.each(|c| c.webview.is_some())
2508    }
2509
2510    /// Whether a web view may show (or navigate to) `url`; `about:blank`
2511    /// whenever web views are granted. A `blob:` URL is the blob's
2512    /// creator's: it is granted when the origin it embeds is, so a page may
2513    /// show and download its own blobs, and a blob of a host it may not
2514    /// show is not granted. An opaque blob (`blob:null/…`) names no origin
2515    /// and is not granted.
2516    pub fn allows_webview(&self, url: &str) -> bool {
2517        if url == "about:blank" {
2518            return self.allows_webviews();
2519        }
2520        let url = blob_origin(url).unwrap_or(url);
2521        match read_url(url) {
2522            Ok(parts) => self.each(|c| c.allows_webview(&parts)),
2523            Err(Unread::Ambiguous(scheme)) => self.each(|c| c.allows_webview_anywhere(&scheme)),
2524            Err(Unread::NotUrl) => false,
2525        }
2526    }
2527
2528    /// Whether a web view may show (or navigate to) `url`, granted by
2529    /// `webview.hosts` ([`Self::allows_webview`]) or, when the app may add
2530    /// one at run time ([`Self::allows_runtime_origin`]), at `origin`, the
2531    /// web view's own `allowOrigin`.
2532    pub fn allows_webview_with(&self, url: &str, origin: Option<&WebOrigin>) -> bool {
2533        self.allows_webview(url)
2534            || origin.is_some_and(|o| self.allows_runtime_origin() && o.contains(url))
2535    }
2536
2537    /// [`Self::allows_webview_with`], narrowed by the web view's own
2538    /// `allowNavigation` (`hosts`, none: not narrowed). What a web view's
2539    /// backend checks each top-level navigation with.
2540    pub fn allows_webview_in(
2541        &self,
2542        url: &str,
2543        origin: Option<&WebOrigin>,
2544        hosts: Option<&WebHosts>,
2545    ) -> bool {
2546        hosts.is_none_or(|h| h.allows(url)) && self.allows_webview_with(url, origin)
2547    }
2548
2549    /// Whether a web view's `allowOrigin` may add an origin to the hosts
2550    /// it may show (`webview.runtimeOrigin`): declared and granted, never
2551    /// by default.
2552    pub fn allows_runtime_origin(&self) -> bool {
2553        self.each(|c| c.webview.is_some() && c.webview_runtime_origin)
2554    }
2555
2556    /// Whether a web view's ref may give its page trusted input
2557    /// (`sendInput`): declared and granted, never by default.
2558    pub fn allows_web_input(&self) -> bool {
2559        self.each(|c| c.webview.is_some() && c.webview_input)
2560    }
2561
2562    /// Whether a web view's page may capture `media` (`getUserMedia`):
2563    /// declared and granted, never by default. The system still asks the
2564    /// user.
2565    pub fn allows_web_media(&self, media: WebMedia) -> bool {
2566        self.each(|c| c.webview.is_some() && c.webview_media.contains(&media))
2567    }
2568
2569    /// Whether the app may open a window of `kind` with `attributes` (its
2570    /// own, before its kind's defaults) while `open` windows besides the
2571    /// main one are open; the message of the refusal otherwise (the call
2572    /// fails with `ERR_ACCESS_DENIED`, permission `windows`).
2573    pub fn check_window(
2574        &self,
2575        kind: crate::desktop::WindowKind,
2576        attributes: &crate::desktop::WindowAttributes,
2577        open: usize,
2578    ) -> Result<(), String> {
2579        if !self.each(|c| c.windows.is_some()) {
2580            return Err("windows of the app's own are not granted by capabilities.windows".into());
2581        }
2582        if !self.each(|c| c.windows.as_ref().is_some_and(|w| w.allows_kind(kind))) {
2583            return Err(format!(
2584                "a window of kind `{}` is not granted by capabilities.windows{}",
2585                window_kind_name(kind),
2586                if kind == crate::desktop::WindowKind::Overlay {
2587                    " (overlays need `overlay: true`)"
2588                } else {
2589                    ""
2590                }
2591            ));
2592        }
2593        if !self.each(|c| {
2594            c.windows
2595                .as_ref()
2596                .is_some_and(|w| w.max.is_none_or(|max| open < max as usize))
2597        }) {
2598            return Err("capabilities.windows.max windows are open already".into());
2599        }
2600        let mut own = attributes.clone();
2601        // The kind's own level is granted with the kind.
2602        let level = own.level.take();
2603        let denied = self.deny_window_attributes(&mut own);
2604        if let Some(name) = denied.first() {
2605            return Err(format!(
2606                "the window attribute `{name}` is not granted by capabilities.windows"
2607            ));
2608        }
2609        if let Some(level) = level
2610            && !self.each(|c| c.windows.as_ref().is_some_and(|w| w.allows_level(level)))
2611        {
2612            return Err(format!(
2613                "the window level `{}` is not granted by capabilities.windows.levels",
2614                window_level_name(level)
2615            ));
2616        }
2617        Ok(())
2618    }
2619
2620    /// Leaves out of `attributes` what the app's capabilities do not grant
2621    /// a window (an ungranted level, click-through without `overlay`) and
2622    /// returns their
2623    /// names, for a warning. Without a `windows` grant only the defaults
2624    /// remain; no window is privileged.
2625    pub fn deny_window_attributes(
2626        &self,
2627        attributes: &mut crate::desktop::WindowAttributes,
2628    ) -> Vec<&'static str> {
2629        let mut denied = Vec::new();
2630        let grant = |f: &dyn Fn(&WindowsGrant) -> bool| {
2631            self.each(|c| match &c.windows {
2632                Some(w) => f(w),
2633                // Without windows the main window keeps the safe defaults.
2634                None => false,
2635            })
2636        };
2637        if let Some(level) = attributes.level
2638            && level != crate::desktop::WindowLevel::Normal
2639            && !grant(&|w| w.allows_level(level))
2640        {
2641            attributes.level = None;
2642            denied.push("level");
2643        }
2644        if attributes.passes_pointer() && !grant(&|w| w.overlay) {
2645            attributes.pointer_events = None;
2646            denied.push("pointerEvents");
2647        }
2648        denied
2649    }
2650
2651    /// Whether the app may set the status bar.
2652    pub fn allows_status_bar(&self) -> bool {
2653        self.each(|c| c.status_bar)
2654    }
2655
2656    /// Whether the app may show the system's share sheet (`Share` of
2657    /// `nsh-extra`, which checks it).
2658    pub fn allows_share(&self) -> bool {
2659        self.each(|c| c.share)
2660    }
2661
2662    /// Whether the app may read and write the system clipboard.
2663    pub fn allows_clipboard(&self) -> bool {
2664        self.each(|c| c.clipboard)
2665    }
2666
2667    /// Whether the app may show the system's picker (`nsh/picker`).
2668    pub fn allows_picker(&self) -> bool {
2669        self.each(|c| c.picker)
2670    }
2671
2672    /// Whether the app may recognize the user's speech (`Speech` of
2673    /// `nsh-extra`, which checks it).
2674    pub fn allows_speech(&self) -> bool {
2675        self.each(|c| c.speech)
2676    }
2677
2678    /// Whether the app may show notifications and set its badge
2679    /// (`Notifications` of `nsh`).
2680    pub fn allows_notifications(&self) -> bool {
2681        self.each(|c| c.notifications)
2682    }
2683
2684    /// Whether the app may play sound (`Sound` and `AudioPlayer` of `nsh`).
2685    pub fn allows_audio(&self) -> bool {
2686        self.each(|c| c.audio)
2687    }
2688
2689    /// Whether the app may act on the application as a whole: the main
2690    /// window, the application menu, the tray, global shortcuts, quitting,
2691    /// restarting and launching at login (`nsh/desktop`), and the app's page
2692    /// in the system's settings (`nsh/mobile`'s `AppSettings`).
2693    pub fn allows_application(&self) -> bool {
2694        self.each(|c| c.application)
2695    }
2696
2697    /// Whether `os.homedir()` may tell the user's home directory.
2698    pub fn allows_home_dir(&self) -> bool {
2699        self.each(|c| c.home_dir)
2700    }
2701
2702    /// Whether `nsh/host` may call the embedding app's function `name`.
2703    pub fn allows_host(&self, name: &str) -> bool {
2704        self.each(|c| c.allows_host(name))
2705    }
2706
2707    /// Whether the app may open `url` outside it (`openUrl` of
2708    /// `nsh/device`): its scheme is granted.
2709    pub fn allows_open_url(&self, url: &str) -> bool {
2710        let Some(scheme) = url
2711            .split_once(':')
2712            .map(|(scheme, _)| scheme.to_ascii_lowercase())
2713        else {
2714            return false;
2715        };
2716        self.each(|c| c.open_url.as_ref().is_some_and(|g| g.allows(&scheme)))
2717    }
2718}
2719
2720/// `location` against `base` (absolute, scheme-relative, absolute-path or
2721/// relative references), as a redirect's `Location` is read: resolved as
2722/// WHATWG's parser resolves it, dot segments included, so a rule checks the
2723/// URL the next hop requests. A base that is no URL leaves the location as
2724/// written, which no check grants.
2725pub fn resolve_reference(base: &str, location: &str) -> String {
2726    match url::Url::parse(base).and_then(|base| base.join(location)) {
2727        Ok(url) => url.into(),
2728        Err(_) => location.to_owned(),
2729    }
2730}
2731
2732/// Whether URLs `a` and `b` have the same origin (scheme, host and port,
2733/// a scheme's default port included), as WHATWG's parser reads them. A URL
2734/// it cannot read, or one with an opaque origin, shares none.
2735pub fn is_same_origin(a: &str, b: &str) -> bool {
2736    match (url::Url::parse(a), url::Url::parse(b)) {
2737        (Ok(a), Ok(b)) => {
2738            let origin = a.origin();
2739            origin.is_tuple() && origin == b.origin()
2740        }
2741        _ => false,
2742    }
2743}
2744
2745#[cfg(test)]
2746mod tests {
2747    #[test]
2748    fn verbatim_windows_paths_compare_in_their_plain_form() {
2749        use super::without_verbatim_prefix as plain;
2750        assert_eq!(plain(r"\\?\C:\Users\a").as_deref(), Some(r"C:\Users\a"));
2751        assert_eq!(plain(r"\\?\d:\").as_deref(), Some(r"d:\"));
2752        assert_eq!(plain(r"\\?\C:\app\").as_deref(), Some(r"C:\app\"));
2753        assert_eq!(
2754            plain(r"\\?\UNC\server\share\a").as_deref(),
2755            Some(r"\\server\share\a")
2756        );
2757        // Plain paths, and verbatim ones of other kinds, stay as they are.
2758        for path in [
2759            r"C:\a",
2760            r"\\server\share",
2761            "/home/a",
2762            r"\\?\Volume{x}\a",
2763            r"\\.\C:\a",
2764        ] {
2765            assert_eq!(plain(path), None, "{path}");
2766        }
2767        // Components the plain form reads otherwise keep the verbatim form.
2768        for path in [
2769            r"\\?\C:\a\NUL",
2770            r"\\?\C:\a\com1.txt",
2771            r"\\?\C:\a\Lpt9",
2772            r"\\?\C:\a\b.",
2773            r"\\?\C:\a\b ",
2774            r"\\?\C:\a\..\b",
2775            r"\\?\C:\a\.\b",
2776            r"\\?\C:\a\\b",
2777            r"\\?\C:\a/b",
2778        ] {
2779            assert_eq!(plain(path), None, "{path}");
2780        }
2781        assert_eq!(
2782            plain(r"\\?\C:\a\com10\console").as_deref(),
2783            Some(r"C:\a\com10\console")
2784        );
2785        let long = format!(r"\\?\C:\{}", "a".repeat(260));
2786        assert_eq!(plain(&long), None);
2787    }
2788
2789    #[test]
2790    fn anchored_roots_join_their_tail_component_by_component() {
2791        let app = PathBuf::from(if cfg!(windows) { r"C:\app" } else { "/app" });
2792        let paths = super::TrustedPaths {
2793            plugin_dir: Some(app.clone()),
2794            home_dir: None,
2795        };
2796        let root = paths.resolve_root("${pluginDir}/a//b/", &app).unwrap();
2797        assert_eq!(root, app.join("a").join("b"));
2798        let names = root.components().rev().take(2).collect::<Vec<_>>();
2799        assert_eq!(
2800            names,
2801            [
2802                Component::Normal("b".as_ref()),
2803                Component::Normal("a".as_ref())
2804            ]
2805        );
2806    }
2807    use super::*;
2808
2809    fn caps(json: &str) -> Capabilities {
2810        Capabilities::from_json(&serde_json::from_str(json).unwrap()).unwrap()
2811    }
2812
2813    #[test]
2814    fn windows_are_granted_by_kind_level_and_count() {
2815        use crate::desktop::{WindowAttributes, WindowKind, WindowLevel, WindowPointerEvents};
2816        let none = WindowAttributes::default();
2817        // Without a declaration: every kind but overlays, no click-through,
2818        // no capture protection.
2819        let all = Access::all();
2820        assert!(all.check_window(WindowKind::Panel, &none, 10).is_ok());
2821        assert!(all.check_window(WindowKind::Overlay, &none, 0).is_err());
2822        let click_through = WindowAttributes {
2823            pointer_events: Some(WindowPointerEvents::None),
2824            ..Default::default()
2825        };
2826        assert!(
2827            all.check_window(WindowKind::Normal, &click_through, 0)
2828                .is_err()
2829        );
2830        // Through where nothing in it takes the pointer: the same grant.
2831        let box_none = WindowAttributes {
2832            pointer_events: Some(WindowPointerEvents::BoxNone),
2833            ..Default::default()
2834        };
2835        assert!(all.check_window(WindowKind::Popup, &box_none, 0).is_err());
2836        // Declared without `windows`: none.
2837        let declared = |json: &str| Access {
2838            declared: caps(json),
2839            granted: None,
2840        };
2841        assert!(
2842            declared(r#"{"process":{"exit":true}}"#)
2843                .check_window(WindowKind::Normal, &none, 0)
2844                .is_err()
2845        );
2846        let limited = declared(
2847            r#"{"windows":{"kinds":["normal","dialog"],"levels":["normal","floating"],"max":2}}"#,
2848        );
2849        assert!(limited.check_window(WindowKind::Dialog, &none, 1).is_ok());
2850        assert!(limited.check_window(WindowKind::Popup, &none, 0).is_err());
2851        assert!(limited.check_window(WindowKind::Normal, &none, 2).is_err());
2852        let above = WindowAttributes {
2853            level: Some(WindowLevel::AboveDock),
2854            ..Default::default()
2855        };
2856        assert!(limited.check_window(WindowKind::Normal, &above, 0).is_err());
2857        let overlay = declared(r#"{"windows":{"overlay":true}}"#);
2858        assert!(
2859            overlay
2860                .check_window(WindowKind::Overlay, &click_through, 0)
2861                .is_ok()
2862        );
2863        assert!(
2864            overlay
2865                .check_window(WindowKind::Popup, &box_none, 0)
2866                .is_ok()
2867        );
2868        // `set()` keeps what is granted and leaves out the rest.
2869        let mut asked = WindowAttributes {
2870            title: Some("Notes".into()),
2871            level: Some(WindowLevel::AboveDock),
2872            ..Default::default()
2873        };
2874        assert_eq!(limited.deny_window_attributes(&mut asked), ["level"]);
2875        assert_eq!(asked.title.as_deref(), Some("Notes"));
2876        assert_eq!(asked.level, None);
2877    }
2878
2879    #[test]
2880    fn environment_names_match_exactly_except_on_windows() {
2881        let access = Access {
2882            declared: caps(r#"{"process":{"env":["MY_TOKEN"]}}"#),
2883            granted: None,
2884        };
2885        assert!(access.allows_env("MY_TOKEN"));
2886        assert_eq!(access.allows_env("my_token"), cfg!(windows));
2887        assert_eq!(super::env_names_match("Path", "PATH"), cfg!(windows));
2888    }
2889
2890    #[test]
2891    fn roots_stay_within_their_anchor_and_bare_commands_have_no_drive() {
2892        let anchor = Path::new(if cfg!(windows) { "C:\\app" } else { "/app" });
2893        assert!(super::within(anchor, Path::new("data/x"), "r").is_ok());
2894        assert!(super::within(anchor, Path::new("/etc"), "r").is_err());
2895        #[cfg(windows)]
2896        for tail in ["C:/Windows", "\\\\srv\\share", "\\Users", "D:x"] {
2897            assert!(
2898                super::within(anchor, Path::new(tail), "r").is_err(),
2899                "{tail}"
2900            );
2901        }
2902        assert!(!super::valid_command("C:git"));
2903        assert!(super::valid_command("git"));
2904    }
2905
2906    #[test]
2907    fn a_manifest_with_absolute_commands_and_roots_parses() {
2908        // The manifest of an app that also runs in a browser: there `Path::is_absolute`
2909        // is false for every path, so these are checked with `absolute` (`has_root`).
2910        let declared = caps(
2911            r#"{"process":{"execute":["/bin/sh","/usr/bin/open","git"]},"fs":{"read":["/Applications"]}}"#,
2912        );
2913        assert_eq!(
2914            declared.process.execute,
2915            ["/bin/sh", "/usr/bin/open", "git"]
2916        );
2917        if !cfg!(windows) {
2918            assert!(super::valid_command("/bin/sh"));
2919            assert!(super::absolute(Path::new("/Applications")));
2920        }
2921    }
2922
2923    #[test]
2924    fn system_capabilities_are_explicit_and_intersected() {
2925        let declared = caps(
2926            r#"{"process":{"execute":["claude","codex"]},"fs":{"read":["${dataDir}"],"write":["${dataDir}"]}}"#,
2927        );
2928        assert_eq!(
2929            Capabilities::from_json(&declared.to_json()).unwrap(),
2930            declared
2931        );
2932        let access = Access {
2933            declared,
2934            granted: Some(caps(
2935                r#"{"process":{"execute":["codex"]},"fs":{"read":["${dataDir}/conversations"]}}"#,
2936            )),
2937        };
2938        assert!(access.allows_process("codex"));
2939        assert!(!access.allows_process("claude"));
2940        assert!(!access.allows_process("/usr/bin/codex"));
2941        assert!(!Access::all().allows_process("codex"));
2942        let root = std::env::current_dir().unwrap();
2943        assert!(
2944            access
2945                .authorize_file(&root.join("conversations/new.json"), &root, false)
2946                .is_ok()
2947        );
2948        assert!(
2949            access
2950                .authorize_file(&root.join("other.json"), &root, false)
2951                .is_err()
2952        );
2953        assert!(
2954            access
2955                .authorize_file(&root.join("conversations/new.json"), &root, true)
2956                .is_err()
2957        );
2958        assert!(Access::all().authorize_file(&root, &root, false).is_err());
2959        assert!(
2960            access
2961                .authorize_file(&root.join("../secret"), &root, false)
2962                .is_err()
2963        );
2964        for bad in [
2965            r#"{"process":{"execut":[]}}"#,
2966            r#"{"fs":{"reads":[]}}"#,
2967            r#"{"fs":{"read":["${dataDir}/../outside"]}}"#,
2968            r#"{"process":{"execute":["*"]}}"#,
2969        ] {
2970            assert!(Capabilities::from_json(&serde_json::from_str(bad).unwrap()).is_err());
2971        }
2972    }
2973
2974    #[test]
2975    fn trusted_host_anchors_expand_without_implicit_grants() {
2976        let root = std::env::current_dir().unwrap();
2977        let anchors = TrustedPaths {
2978            plugin_dir: Some(root.clone()),
2979            home_dir: Some(root.join("native-home")),
2980        };
2981        let access = Access {
2982            declared: caps(
2983                r#"{"fs":{"read":["assets","${homeDir}/settings","${pluginDir}/content"]}}"#,
2984            ),
2985            granted: None,
2986        };
2987        for path in ["assets/file", "native-home/settings/file", "content/file"] {
2988            assert!(
2989                access
2990                    .authorize_file_with_paths(&root.join(path), &root, &anchors, false)
2991                    .is_ok()
2992            );
2993        }
2994        assert!(
2995            access
2996                .authorize_file(&root.join("content/file"), &root, false)
2997                .is_err()
2998        );
2999        assert!(
3000            access
3001                .authorize_file_with_paths(&root.join("other/file"), &root, &anchors, false)
3002                .is_err()
3003        );
3004        assert!(
3005            TrustedPaths::default()
3006                .resolve_root("${homeDir}/settings", &root)
3007                .is_err()
3008        );
3009        assert!(
3010            TrustedPaths::default()
3011                .resolve_root("assets", &root)
3012                .is_err()
3013        );
3014    }
3015
3016    #[test]
3017    fn http_rules_are_one_form_whose_keys_all_narrow() {
3018        let allows = |rule: serde_json::Value, method: &str, url: &str| {
3019            Access {
3020                declared: Capabilities::from_json(&serde_json::json!({"network":{"http":[rule]}}))
3021                    .unwrap(),
3022                granted: None,
3023            }
3024            .allows_http(method, url)
3025        };
3026        // `{host, methods}` covers every path, scheme and port, as manifests had it.
3027        let plain = serde_json::json!({"host": "api.example.com", "methods": ["GET"]});
3028        assert!(allows(plain.clone(), "GET", "https://api.example.com/"));
3029        assert!(allows(
3030            plain.clone(),
3031            "GET",
3032            "http://api.example.com:8080/any/path"
3033        ));
3034        assert!(!allows(plain.clone(), "POST", "https://api.example.com/"));
3035        assert!(allows(
3036            serde_json::json!({"host": "api.example.com"}),
3037            "PUT",
3038            "https://api.example.com/x"
3039        ));
3040        // Paths are exact, prefixes whole segments; either one covers a path.
3041        let scoped = serde_json::json!({
3042            "host": "api.example.com", "methods": ["GET"], "scheme": "https", "port": 443,
3043            "paths": ["/exact"], "pathPrefixes": ["/v1"]
3044        });
3045        assert!(allows(
3046            scoped.clone(),
3047            "GET",
3048            "https://api.example.com/exact?q=1"
3049        ));
3050        assert!(allows(scoped.clone(), "GET", "https://api.example.com/v1"));
3051        assert!(allows(
3052            scoped.clone(),
3053            "GET",
3054            "https://api.example.com/v1/child"
3055        ));
3056        assert!(!allows(
3057            scoped.clone(),
3058            "GET",
3059            "https://api.example.com/v10"
3060        ));
3061        assert!(!allows(
3062            scoped.clone(),
3063            "GET",
3064            "https://api.example.com/exact/more"
3065        ));
3066        assert!(!allows(
3067            scoped.clone(),
3068            "GET",
3069            "http://api.example.com/exact"
3070        ));
3071        assert!(!allows(
3072            scoped.clone(),
3073            "GET",
3074            "https://api.example.com:444/exact"
3075        ));
3076        assert!(allows(scoped, "GET", "https://api.example.com:443/exact"));
3077        // Main's spelling still reads, and a prefix ending in `/` covers what follows it.
3078        let legacy = serde_json::json!({"host": "*.example.com", "schemes": ["https", "wss"], "pathPrefix": "/v1/"});
3079        assert!(allows(
3080            legacy.clone(),
3081            "GET",
3082            "https://quotes.example.com/v1/quote"
3083        ));
3084        assert!(!allows(legacy, "GET", "https://quotes.example.com/v2/"));
3085        // Every spelling of a key is merged, and one form is written back.
3086        let mixed = caps(
3087            r#"{"network":{"http":[{"host":"a.example.com","methods":["get"],"scheme":"https","schemes":["wss","https"],"pathPrefix":"/a","path_prefixes":["/b"],"pathPrefixes":["/a","/c"]}]}}"#,
3088        );
3089        let grant = &mixed.network.http[0];
3090        assert_eq!(grant.methods, ["GET"]);
3091        assert_eq!(grant.schemes, ["https", "wss"]);
3092        assert_eq!(grant.path_prefixes, ["/a", "/c", "/b"]);
3093        assert_eq!(
3094            mixed.to_json()["network"]["http"][0],
3095            serde_json::json!({"host":"a.example.com","methods":["GET"],"schemes":["https","wss"],"pathPrefixes":["/a","/c","/b"]})
3096        );
3097        assert_eq!(Capabilities::from_json(&mixed.to_json()).unwrap(), mixed);
3098        // What cannot match is an error, not a rule that grants nothing.
3099        for bad in [
3100            serde_json::json!({"host": "a.example.com", "schemes": ["ftp"]}),
3101            serde_json::json!({"host": "a.example.com", "port": 0}),
3102            serde_json::json!({"host": "a.example.com", "port": 70000}),
3103            serde_json::json!({"host": "a.example.com", "paths": ["relative"]}),
3104            serde_json::json!({"host": "a.example.com", "pathPrefixes": ["/v1/*"]}),
3105            serde_json::json!({"host": "a.example.com", "methods": ["*"]}),
3106            serde_json::json!({"host": "a.example.com", "paths": "/x", "query": true}),
3107            serde_json::json!({"methods": ["GET"]}),
3108        ] {
3109            assert!(
3110                Capabilities::from_json(&serde_json::json!({"network":{"http":[bad.clone()]}}))
3111                    .is_err(),
3112                "{bad}"
3113            );
3114        }
3115    }
3116
3117    #[test]
3118    fn exit_and_environment_permissions_intersect() {
3119        let declared = caps(r#"{"process":{"env":["NSH_SECRET","OTHER"],"exit":true}}"#);
3120        assert_eq!(
3121            Capabilities::from_json(&declared.to_json()).unwrap(),
3122            declared
3123        );
3124        let access = Access {
3125            declared,
3126            granted: Some(caps(r#"{"process":{"env":["NSH_SECRET"]}}"#)),
3127        };
3128        assert!(access.allows_env("NSH_SECRET"));
3129        assert!(!access.allows_env("OTHER"));
3130        assert!(!access.allows_exit());
3131        assert!(!Access::all().allows_exit());
3132        assert!(!Access::all().allows_env("NSH_SECRET"));
3133        assert!(Access::all().allows_env("LANG"));
3134        assert_eq!(Access::all().allows_env("lang"), cfg!(windows));
3135        assert!(Access::all().allows_env("TZ"));
3136        // Identity, paths and proxy credentials need an explicit grant.
3137        for name in [
3138            "HOME",
3139            "USER",
3140            "USERNAME",
3141            "HOSTNAME",
3142            "COMPUTERNAME",
3143            "PATH",
3144            "TMPDIR",
3145            "XDG_RUNTIME_DIR",
3146            "APPDATA",
3147            "http_proxy",
3148            "HTTPS_PROXY",
3149            "ALL_PROXY",
3150            "NO_PROXY",
3151            "DISPLAY",
3152        ] {
3153            assert!(!Access::all().allows_env(name), "{name}");
3154        }
3155        assert!(!Access::all().allows_env("SSH_AUTH_SOCK"));
3156        assert!(!Access::all().allows_env("DBUS_SESSION_BUS_ADDRESS"));
3157        assert!(Capabilities::from_json(&serde_json::json!({"process":{"exit":"true"}})).is_err());
3158        assert!(
3159            Capabilities::from_json(&serde_json::json!({"process":{"env":["BAD=NAME"]}})).is_err()
3160        );
3161    }
3162
3163    #[test]
3164    fn default_environment_entries_are_upper_case_names() {
3165        for line in include_str!("default-env").lines() {
3166            let name = line.split('#').next().unwrap_or_default().trim();
3167            assert!(
3168                name.is_empty()
3169                    || name
3170                        .chars()
3171                        .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'),
3172                "{line}"
3173            );
3174        }
3175    }
3176
3177    #[test]
3178    fn sockets_need_exact_host_and_port_grants() {
3179        let declared = caps(
3180            r#"{"network":{"hosts":["*"],"sockets":["MQTT.example.com:8883","[::1]:9000","127.0.0.1:22"]}}"#,
3181        );
3182        assert_eq!(
3183            Capabilities::from_json(&declared.to_json()).unwrap(),
3184            declared
3185        );
3186        let access = Access {
3187            declared,
3188            granted: None,
3189        };
3190        assert!(access.allows_socket("mqtt.example.com", 8883));
3191        assert!(access.allows_socket("MQTT.example.com.", 8883));
3192        assert!(!access.allows_socket("mqtt.example.com", 1883));
3193        assert!(!access.allows_socket("example.com", 8883));
3194        assert!(!access.allows_socket("a.mqtt.example.com", 8883));
3195        assert!(access.allows_socket("::1", 9000));
3196        assert!(access.allows_socket("[::1]", 9000));
3197        assert!(access.allows_socket("127.0.0.1", 22));
3198        assert!(!access.allows_socket("127.0.0.1", 0));
3199        // `hosts: ["*"]` (and the unrestricted default) grant no sockets.
3200        assert!(!access.allows_socket("localhost", 22));
3201        assert!(!Access::all().allows_socket("127.0.0.1", 22));
3202        assert!(!Access::all().allows_socket("example.com", 443));
3203        let narrowed = Access {
3204            granted: Some(caps(r#"{"network":{"sockets":["127.0.0.1:22"]}}"#)),
3205            ..access
3206        };
3207        assert!(narrowed.allows_socket("127.0.0.1", 22));
3208        assert!(!narrowed.allows_socket("mqtt.example.com", 8883));
3209        for bad in [
3210            "*.example.com:443",
3211            "*:443",
3212            "example.com",
3213            "example.com:0",
3214            "example.com:65536",
3215            "example.com:*",
3216            ":443",
3217            "::1:443",
3218            "[]:443",
3219            "exa mple.com:1",
3220        ] {
3221            assert!(
3222                Capabilities::from_json(&serde_json::json!({"network":{"sockets":[bad]}}))
3223                    .unwrap_err()
3224                    .contains("invalid socket grant"),
3225                "{bad}"
3226            );
3227        }
3228    }
3229
3230    #[test]
3231    fn websockets_follow_http_grants() {
3232        let access = Access {
3233            declared: caps(
3234                r#"{"network":{"hosts":["ws.example.com"],"http":[
3235                    {"host":"chat.example.com","methods":["GET"],"scheme":"https","paths":["/socket"]},
3236                    {"host":"legacy.example.com","schemes":["wss"]}
3237                ]}}"#,
3238            ),
3239            granted: None,
3240        };
3241        assert!(access.allows_websocket("ws://ws.example.com:8080/x"));
3242        assert!(access.allows_websocket("wss://chat.example.com/socket"));
3243        assert!(!access.allows_websocket("ws://chat.example.com/socket"));
3244        assert!(!access.allows_websocket("wss://chat.example.com/other"));
3245        assert!(access.allows_websocket("wss://legacy.example.com/"));
3246        assert!(!access.allows_websocket("ws://legacy.example.com/"));
3247        assert!(!access.allows_websocket("https://ws.example.com/"));
3248        assert!(!access.allows_socket("ws.example.com", 8080));
3249    }
3250
3251    #[cfg(unix)]
3252    #[test]
3253    fn filesystem_symlinks_cannot_escape_granted_roots() {
3254        use std::os::unix::fs::symlink;
3255        let base = std::env::var_os("TMPDIR")
3256            .map(PathBuf::from)
3257            .unwrap_or_else(|| {
3258                PathBuf::from(std::env::var_os("HOME").unwrap()).join(".cache/nsh-benchs-test-tmp")
3259            });
3260        let root = base.join(format!("access-policy-{}", std::process::id()));
3261        std::fs::create_dir_all(root.join("allowed")).unwrap();
3262        std::fs::create_dir_all(root.join("outside")).unwrap();
3263        symlink(root.join("outside"), root.join("allowed/link")).unwrap();
3264        let access = Access {
3265            declared: caps(r#"{"fs":{"read":["${dataDir}"],"write":["${dataDir}"]}}"#),
3266            granted: None,
3267        };
3268        for write in [false, true] {
3269            assert!(
3270                access
3271                    .authorize_file(
3272                        &root.join("allowed/link/missing/file"),
3273                        &root.join("allowed"),
3274                        write
3275                    )
3276                    .is_err()
3277            );
3278            assert!(
3279                access
3280                    .authorize_file(&root.join("allowed/new/file"), &root.join("allowed"), write)
3281                    .is_ok()
3282            );
3283        }
3284        std::fs::remove_dir_all(root).unwrap();
3285    }
3286
3287    #[test]
3288    fn the_share_sheet_is_granted_by_both_sides() {
3289        let declared = caps(r#"{ "share": true }"#);
3290        assert!(declared.share);
3291        assert_eq!(declared.to_json()["share"], serde_json::json!(true));
3292        assert!(
3293            Access {
3294                declared: declared.clone(),
3295                granted: None,
3296            }
3297            .allows_share()
3298        );
3299        // The embedding app grants less.
3300        assert!(
3301            !Access {
3302                declared,
3303                granted: Some(caps("{}")),
3304            }
3305            .allows_share()
3306        );
3307        // Apps without a declaration keep it.
3308        assert!(Access::all().allows_share());
3309        assert!(Capabilities::from_json(&serde_json::json!({ "share": "yes" })).is_err());
3310    }
3311
3312    #[test]
3313    fn denies_unless_listed() {
3314        let access = Access {
3315            declared: caps("{}"),
3316            granted: None,
3317        };
3318        assert!(!access.allows_http("GET", "https://example.com/"));
3319        assert!(!access.allows_media("https://example.com/a.png"));
3320        assert!(access.allows_media("asset:/logo.png"));
3321        // A relative path names no file of the app's in a native app.
3322        assert!(!access.allows_media("logo.png"));
3323        // Local files are `capabilities.fs.read`'s (#1180), which this
3324        // declaration does not grant.
3325        assert!(!access.allows_media("/home/a/logo.png"));
3326        assert!(!access.allows_media("file:///home/a/logo.png"));
3327        assert!(access.allows_media("data:image/png;base64,iVBORw0KGgo="));
3328        assert!(!access.allows_webview("https://example.com/"));
3329        assert!(!access.allows_status_bar());
3330        assert!(!access.allows_clipboard());
3331        assert!(!access.allows_picker());
3332        assert!(!access.allows_share());
3333        assert!(!access.allows_speech());
3334        assert!(!access.allows_audio());
3335        assert!(!access.allows_application());
3336        assert!(!access.allows_home_dir());
3337        assert!(!access.allows_host("getUserInfo"));
3338        assert!(Access::all().is_unrestricted());
3339    }
3340
3341    #[test]
3342    fn the_application_and_the_home_directory_are_capabilities() {
3343        // Undeclared: granted, as they always were.
3344        let all = Access::all();
3345        assert!(all.allows_application() && all.allows_home_dir());
3346        // Declared: only when listed, and the embedder may take them away.
3347        let access = |declared: &str, granted: Option<&str>| Access {
3348            declared: caps(declared),
3349            granted: granted.map(caps),
3350        };
3351        let listed = access(r#"{ "application": true, "homeDir": true }"#, None);
3352        assert!(listed.allows_application() && listed.allows_home_dir());
3353        let application = access(r#"{ "application": true }"#, None);
3354        assert!(application.allows_application() && !application.allows_home_dir());
3355        let narrowed = access(
3356            r#"{ "application": true, "homeDir": true }"#,
3357            Some(r#"{ "homeDir": true }"#),
3358        );
3359        assert!(!narrowed.allows_application() && narrowed.allows_home_dir());
3360        assert!(!access(r#"{ "application": false }"#, None).allows_application());
3361        assert!(Capabilities::from_json(&serde_json::json!({ "application": "yes" })).is_err());
3362        assert!(Capabilities::from_json(&serde_json::json!({ "homeDir": 1 })).is_err());
3363        // Written only when granted, read back the same.
3364        let both = caps(r#"{ "application": true, "homeDir": true }"#);
3365        assert_eq!(Capabilities::from_json(&both.to_json()).unwrap(), both);
3366        let none = Capabilities::default().to_json();
3367        assert!(none.get("application").is_none() && none.get("homeDir").is_none());
3368    }
3369
3370    #[test]
3371    fn host_functions_need_an_explicit_grant() {
3372        // Undeclared, the other capabilities are all granted; the host's
3373        // functions are not.
3374        let all = Access::all();
3375        assert!(all.allows_clipboard());
3376        assert!(!all.allows_host("getUserInfo"));
3377        let access = |json: &str| Access {
3378            declared: caps(json),
3379            granted: None,
3380        };
3381        let every = access(r#"{ "host": true }"#);
3382        assert!(every.allows_host("getUserInfo") && every.allows_host("bridge.call"));
3383        assert!(!access(r#"{ "host": false }"#).allows_host("getUserInfo"));
3384        let listed = access(r#"{ "host": ["getUserInfo", "bridge.*"] }"#);
3385        assert!(listed.allows_host("getUserInfo"));
3386        assert!(listed.allows_host("bridge.share"));
3387        assert!(!listed.allows_host("getUserInfoX"));
3388        assert!(!listed.allows_host("bridge"));
3389        assert!(Capabilities::from_json(&serde_json::json!({ "host": ["a*b"] })).is_err());
3390        assert!(Capabilities::from_json(&serde_json::json!({ "host": [""] })).is_err());
3391        // The embedding app may grant less.
3392        let narrowed = Access {
3393            declared: caps(r#"{ "host": true }"#),
3394            granted: Some(caps(r#"{ "host": ["bridge.*"] }"#)),
3395        };
3396        assert!(narrowed.allows_host("bridge.call") && !narrowed.allows_host("getUserInfo"));
3397    }
3398
3399    #[test]
3400    fn a_runtime_origin_is_exact() {
3401        let o = |s: &str| WebOrigin::parse(s).unwrap();
3402        let lan = o("http://192.168.1.5:9876");
3403        for url in [
3404            "http://192.168.1.5:9876/session-page/T/index.html",
3405            "http://192.168.1.5:9876",
3406            "HTTP://192.168.1.5:9876/x",
3407            "blob:http://192.168.1.5:9876/6f3c2f0e",
3408        ] {
3409            assert!(lan.contains(url), "{url}");
3410        }
3411        for url in [
3412            "http://192.168.1.5:9877/",
3413            "https://192.168.1.5:9876/",
3414            "http://a.192.168.1.5:9876/",
3415            "http://192.168.1.5:9876@evil.com/",
3416            "http://192.168.1.5:9876.evil.com/",
3417            "blob:null/6f3c2f0e",
3418            "file:///etc/passwd",
3419            "javascript:alert(1)",
3420            "data:text/html,hi",
3421            "http://192.168.1.5\\@evil.com:9876/",
3422        ] {
3423            assert!(!lan.contains(url), "{url}");
3424        }
3425        let named = o("https://Name.Example.net:443");
3426        assert_eq!(named.to_string(), "https://name.example.net");
3427        assert!(named.contains("https://name.example.net/x"));
3428        assert!(named.contains("https://NAME.example.net:443/x"));
3429        for url in [
3430            "https://evil.name.example.net/",
3431            "https://name.example.net.evil.com/",
3432            "http://name.example.net/",
3433        ] {
3434            assert!(!named.contains(url), "{url}");
3435        }
3436        assert_eq!(o("http://h:80/").to_string(), "http://h");
3437        assert_eq!(o("http://[::1]:8080").to_string(), "http://[::1]:8080");
3438        for bad in [
3439            "http://h/path",
3440            "http://h?q",
3441            "http://h#f",
3442            "http://u@h",
3443            "*",
3444            "http://*",
3445            "ftp://h",
3446            "h:80",
3447            "http://",
3448            "http://h:99999",
3449            "http://bücher.example",
3450        ] {
3451            assert!(WebOrigin::parse(bad).is_err(), "{bad}");
3452        }
3453    }
3454
3455    #[test]
3456    fn allow_navigation_only_narrows_a_web_view() {
3457        let access = Access {
3458            declared: caps(r#"{ "webview": { "hosts": ["*"] } }"#),
3459            granted: None,
3460        };
3461        let hosts = WebHosts::parse(&["127.0.0.1", "*.localhost"]).unwrap();
3462        let ok = |url: &str| access.allows_webview_in(url, None, Some(&hosts));
3463        assert!(ok("http://127.0.0.1:8001/"));
3464        assert!(ok("http://app.localhost:3000/a"));
3465        assert!(ok("blob:http://127.0.0.1:8001/1234"));
3466        assert!(!ok("http://127.0.0.1.evil.test:8002/leaked"));
3467        assert!(!ok("https://example.com/"));
3468        assert!(!ok("http://localhost/"));
3469        // Other schemes stay with the app's own rules.
3470        assert!(ok("about:blank"));
3471        // It never widens what the app grants.
3472        let narrow = Access {
3473            declared: caps(r#"{ "webview": { "hosts": ["example.com"] } }"#),
3474            granted: None,
3475        };
3476        assert!(!narrow.allows_webview_in("http://127.0.0.1/", None, Some(&hosts)));
3477        assert!(narrow.allows_webview_in("https://example.com/", None, None));
3478        // An empty list refuses every web page.
3479        let none = WebHosts::default();
3480        assert!(!access.allows_webview_in("https://example.com/", None, Some(&none)));
3481        // Bad patterns do not read; the written form reads back.
3482        assert!(WebHosts::parse(&["http://127.0.0.1"]).is_err());
3483        let text = hosts.to_string();
3484        let lines: Vec<&str> = text.lines().collect();
3485        assert_eq!(WebHosts::parse(&lines).unwrap(), hosts);
3486    }
3487
3488    #[test]
3489    fn a_runtime_origin_needs_an_explicit_grant() {
3490        let access = |json: &str| Access {
3491            declared: caps(json),
3492            granted: None,
3493        };
3494        let lan = WebOrigin::parse("http://192.168.1.5:9876").unwrap();
3495        let page = "http://192.168.1.5:9876/index.html";
3496        let declared = r#"{ "webview": { "hosts": ["127.0.0.1"], "runtimeOrigin": true } }"#;
3497        assert!(access(declared).allows_runtime_origin());
3498        assert!(access(declared).allows_webview_with(page, Some(&lan)));
3499        assert!(!access(declared).allows_webview_with(page, None));
3500        assert!(access(declared).allows_webview_with("http://127.0.0.1:1/", Some(&lan)));
3501        // Not declared: the origin adds nothing, also for an app with every
3502        // host's grant (which has the page through `hosts`).
3503        let hosts = r#"{ "webview": { "hosts": ["127.0.0.1"] } }"#;
3504        assert!(!access(hosts).allows_runtime_origin());
3505        assert!(!access(hosts).allows_webview_with(page, Some(&lan)));
3506        assert!(!Access::all().allows_runtime_origin());
3507        assert!(Access::all().allows_webview_with(page, None));
3508        assert!(
3509            Capabilities::from_json(&serde_json::json!({ "webview": { "runtimeOrigin": 1 } }))
3510                .is_err()
3511        );
3512        // It round-trips, and the embedding app may withhold it.
3513        assert_eq!(
3514            Capabilities::from_json(&caps(declared).to_json()),
3515            Ok(caps(declared))
3516        );
3517        let narrowed = Access {
3518            declared: caps(declared),
3519            granted: Some(caps(r#"{ "webview": { "hosts": ["*"] } }"#)),
3520        };
3521        assert!(!narrowed.allows_runtime_origin());
3522    }
3523
3524    #[test]
3525    fn trusted_web_input_needs_an_explicit_grant() {
3526        // Undeclared, web views are granted; their trusted input is not.
3527        let all = Access::all();
3528        assert!(all.allows_webviews() && !all.allows_web_input());
3529        let access = |json: &str| Access {
3530            declared: caps(json),
3531            granted: None,
3532        };
3533        let input = r#"{ "webview": { "hosts": ["example.com"], "input": true } }"#;
3534        assert!(access(input).allows_web_input());
3535        assert!(!access(r#"{ "webview": { "hosts": ["example.com"] } }"#).allows_web_input());
3536        assert!(!access(r#"{ "webview": { "input": false } }"#).allows_web_input());
3537        assert!(
3538            Capabilities::from_json(&serde_json::json!({ "webview": { "input": "yes" } })).is_err()
3539        );
3540        // It round-trips, and the embedding app may withhold it.
3541        assert_eq!(
3542            Capabilities::from_json(&caps(input).to_json()),
3543            Ok(caps(input))
3544        );
3545        let narrowed = Access {
3546            declared: caps(input),
3547            granted: Some(caps(r#"{ "webview": { "hosts": ["*"] } }"#)),
3548        };
3549        assert!(!narrowed.allows_web_input());
3550    }
3551
3552    #[test]
3553    fn web_media_needs_an_explicit_grant() {
3554        let all = Access::all();
3555        assert!(!all.allows_web_media(WebMedia::Microphone));
3556        let access = |json: &str| Access {
3557            declared: caps(json),
3558            granted: None,
3559        };
3560        let mic = r#"{ "webview": { "hosts": ["example.com"], "media": ["microphone"] } }"#;
3561        assert!(access(mic).allows_web_media(WebMedia::Microphone));
3562        assert!(!access(mic).allows_web_media(WebMedia::Camera));
3563        assert!(
3564            Capabilities::from_json(&serde_json::json!({ "webview": { "media": ["screen"] } }))
3565                .is_err()
3566        );
3567        assert_eq!(Capabilities::from_json(&caps(mic).to_json()), Ok(caps(mic)));
3568        let narrowed = Access {
3569            declared: caps(mic),
3570            granted: Some(caps(r#"{ "webview": { "hosts": ["*"] } }"#)),
3571        };
3572        assert!(!narrowed.allows_web_media(WebMedia::Microphone));
3573    }
3574
3575    /// A page's `URL.createObjectURL` blob URL embeds its creator's origin:
3576    /// a web view may show and download it when that origin is a granted
3577    /// host, and never a blob of a host it may not show, an opaque one, or
3578    /// any without a `webview` grant.
3579    #[test]
3580    fn page_owned_blob_urls_follow_the_origin_they_embed() {
3581        let a = Access {
3582            declared: caps(
3583                r#"{ "webview": { "hosts": ["app.example.com", "*.app.example.com"] } }"#,
3584            ),
3585            granted: None,
3586        };
3587        for url in [
3588            "blob:https://app.example.com/uuid",
3589            "blob:http://app.example.com:6711/uuid",
3590            "blob:https://docs.app.example.com/uuid",
3591            "BLOB:HTTPS://APP.EXAMPLE.COM/uuid",
3592        ] {
3593            assert!(a.allows_webview(url), "{url}");
3594        }
3595        for url in [
3596            "blob:https://bank.example/uuid",
3597            "blob:https://app.example.com.evil.example/uuid",
3598            "blob:https://app.example.com@bank.example/uuid",
3599            "blob:null/uuid",
3600            "blob:data:text/html,hi",
3601            "blob:file:///etc/passwd",
3602            "blob:",
3603            "blob:https://",
3604        ] {
3605            assert!(!a.allows_webview(url), "{url}");
3606        }
3607        // Without a `webview` grant, a blob naming a host is still refused.
3608        let denied = Access {
3609            declared: caps("{}"),
3610            granted: None,
3611        };
3612        assert!(!denied.allows_webview("blob:https://app.example.com/uuid"));
3613        // The embedding app may narrow the hosts: both must grant the origin.
3614        let narrowed = Access {
3615            granted: Some(caps(r#"{ "webview": { "hosts": ["app.example.com"] } }"#)),
3616            ..a.clone()
3617        };
3618        assert!(narrowed.allows_webview("blob:https://app.example.com/uuid"));
3619        assert!(!narrowed.allows_webview("blob:https://docs.app.example.com/uuid"));
3620        // The shape WebKit reports for a page at a granted loopback host.
3621        let local = Access {
3622            declared: caps(r#"{ "webview": { "hosts": ["127.0.0.1"] } }"#),
3623            granted: None,
3624        };
3625        assert!(
3626            local.allows_webview("blob:http://127.0.0.1:6711/6f3c2f0e-8a1d-4c5e-9b7a-0d2e4f6a8b1c")
3627        );
3628        // HTTP(S) pages are checked as before: the origin either matches or
3629        // it does not.
3630        assert!(a.allows_webview("https://app.example.com/page"));
3631        assert!(!a.allows_webview("https://bank.example/page"));
3632        // A blob whose embedded origin parsers read differently is covered
3633        // only by a grant of every host, as any ambiguous URL is.
3634        let ambiguous = "blob:https://app.example.com\\@bank.example/uuid";
3635        assert!(!a.allows_webview(ambiguous));
3636        let any = Access {
3637            declared: caps(r#"{ "webview": { "hosts": ["*"] } }"#),
3638            granted: None,
3639        };
3640        assert!(any.allows_webview(ambiguous));
3641    }
3642
3643    #[test]
3644    fn host_function_names_and_grants_keep_to_their_charset() {
3645        for good in ["getUserInfo", "user.info", "a-b_c:d.E9", &"a".repeat(128)] {
3646            assert!(valid_host_name(good), "{good}");
3647        }
3648        for bad in [
3649            "",
3650            "user.x/../../admin",
3651            "a..b",
3652            "user x",
3653            "a\\b",
3654            "caf\u{e9}",
3655            "ok\u{0}",
3656            "a*",
3657            &"a".repeat(129),
3658        ] {
3659            assert!(!valid_host_name(bad), "{bad:?}");
3660        }
3661        let parses =
3662            |grant: &str| Capabilities::from_json(&serde_json::json!({ "host": [grant] })).is_ok();
3663        assert!(parses("*") && parses("user.*") && parses("user.info"));
3664        for bad in ["user/*", "a..*", "../*", "a b", "**"] {
3665            assert!(!parses(bad), "{bad}");
3666        }
3667    }
3668
3669    #[test]
3670    fn hosts_and_finer_grants() {
3671        let c = caps(
3672            r#"{ "network": {
3673                "hosts": ["*.example.org"],
3674                "http": [{ "host": "api.example.com", "methods": ["get"], "pathPrefix": "/v1/" }]
3675            } }"#,
3676        );
3677        let a = Access {
3678            declared: c,
3679            granted: None,
3680        };
3681        assert!(a.allows_http("POST", "https://api.example.org/x"));
3682        assert!(!a.allows_http("GET", "https://example.org/"));
3683        assert!(!a.allows_http("GET", "https://example.org.evil.io/"));
3684        assert!(!a.allows_http("GET", "https://evilexample.org/"));
3685        assert!(a.allows_http("GET", "https://API.example.com/v1/quote"));
3686        assert!(!a.allows_http("POST", "https://api.example.com/v1/quote"));
3687        assert!(!a.allows_http("GET", "https://api.example.com/v2/"));
3688        assert!(!a.allows_http("GET", "file://api.example.com/v1/"));
3689        // User info does not fool the host check.
3690        assert!(!a.allows_http("GET", "https://api.example.org@evil.io/"));
3691        assert!(a.allows_http("GET", "https://user:pw@api.example.org:8443/"));
3692    }
3693
3694    /// URLs that parsers read differently: WHATWG's (the web views') ends the
3695    /// host at a backslash, reads one in the path as `/` and drops tab, LF
3696    /// and CR, Foundation's `NSURL` keeps a backslash in the user info,
3697    /// and WHATWG's decodes a host's percent-encoding and refuses spaces in
3698    /// it. Granting one would let the app load a host or path it is not
3699    /// granted wherever another parser loads it.
3700    #[test]
3701    fn urls_that_parsers_read_as_different_hosts_are_refused() {
3702        let hosts = r#"["docs.example.com", "*.docs.example.com"]"#;
3703        let a = Access {
3704            declared: caps(&format!(
3705                r#"{{ "network": {{ "hosts": {hosts} }}, "webview": {{ "hosts": {hosts} }} }}"#
3706            )),
3707            granted: None,
3708        };
3709        for url in [
3710            // WHATWG: bank.example; the check read docs.example.com.
3711            "https://bank.example\\@docs.example.com/",
3712            "https://bank.example:443\\@docs.example.com/",
3713            "https://[::1]\\@docs.example.com/",
3714            // WHATWG: bank.example; the check read a subdomain.
3715            "https://bank.example\\.docs.example.com/",
3716            // Foundation's NSURL: bank.example; WHATWG: docs.example.com.
3717            "https://docs.example.com\\@bank.example/",
3718            // WHATWG: the path is `/b`; the check read `/a\..\b`.
3719            "https://docs.example.com/a\\..\\b",
3720            // WHATWG drops these or refuses the URL; the check read a subdomain.
3721            "https://bank.example\0.docs.example.com/",
3722            "https://bank.example\t.docs.example.com/",
3723            "https://bank.example\n.docs.example.com/",
3724            "https://bank.example .docs.example.com/",
3725            "https://bank.example[.docs.example.com/",
3726            "https://x]y.docs.example.com/",
3727            // WHATWG: bank.example.docs.example.com, decoded.
3728            "https://bank%2Eexample.docs.example.com/",
3729        ] {
3730            assert!(!a.allows_webview(url), "{url:?}");
3731            assert!(!a.allows_http("GET", url), "{url:?}");
3732            assert!(!a.allows_media(url), "{url:?}");
3733        }
3734        assert!(!a.allows_websocket("wss://bank.example\\@docs.example.com/"));
3735        // What every parser reads alike is unchanged: an escaped backslash,
3736        // a backslash in the query (WHATWG keeps it there), user info.
3737        for url in [
3738            "https://docs.example.com/a%5Cb",
3739            "https://x.docs.example.com/?q=C:\\x#a\\b",
3740            "https://user:pw@docs.example.com/a b",
3741        ] {
3742            assert!(a.allows_webview(url), "{url:?}");
3743            assert!(a.allows_http("GET", url), "{url:?}");
3744        }
3745        // Nor does it refuse what an app without capabilities loads.
3746        let all = Access {
3747            declared: Capabilities::all(),
3748            granted: None,
3749        };
3750        let query = url::Url::parse("wss://x.example/?q=a\\b").unwrap();
3751        assert!(all.allows_websocket(query.as_str()), "{query}");
3752        assert!(all.allows_media("https://x.example/i.png?p=a\\b"));
3753    }
3754
3755    /// A URL that parsers read differently names no one host, port or path:
3756    /// a grant of every host covers it (an app without `capabilities`, `*`),
3757    /// a narrower grant or a rule narrowing the port or path does not, and
3758    /// what is no URL stays refused.
3759    #[test]
3760    fn only_grants_of_every_host_cover_ambiguous_urls() {
3761        let url = "https://x.example/a\\b.png";
3762        let all = Access {
3763            declared: Capabilities::all(),
3764            granted: None,
3765        };
3766        let any = Access {
3767            declared: caps(r#"{ "network": { "hosts": ["*"] }, "webview": { "hosts": ["*"] } }"#),
3768            granted: None,
3769        };
3770        for a in [&all, &any] {
3771            assert!(a.allows_http("GET", url));
3772            assert!(a.allows_media(url));
3773            assert!(a.allows_webview(url));
3774            assert!(!a.allows_http("GET", "ftp://x.example/a\\b"));
3775            assert!(!a.allows_webview("file://x.example/a\\b"));
3776            assert!(!a.allows_webview("not a url"));
3777            assert!(!a.allows_http("GET", "https://"));
3778        }
3779        let rule = |rule: &str| Access {
3780            declared: caps(&format!(r#"{{ "network": {{ "http": [{rule}] }} }}"#)),
3781            granted: None,
3782        };
3783        let methods = rule(r#"{ "host": "*", "methods": ["get"], "schemes": ["https"] }"#);
3784        assert!(methods.allows_http("GET", url));
3785        assert!(!methods.allows_http("POST", url));
3786        assert!(!methods.allows_http("GET", "http://x.example/a\\b.png"));
3787        for narrowed in [
3788            r#"{ "host": "*", "port": 443 }"#,
3789            r#"{ "host": "*", "pathPrefix": "/a" }"#,
3790            r#"{ "host": "*", "paths": ["/a/b.png"] }"#,
3791            r#"{ "host": "x.example" }"#,
3792        ] {
3793            assert!(!rule(narrowed).allows_http("GET", url), "{narrowed}");
3794        }
3795    }
3796
3797    /// A URL the check grants names a granted host for WHATWG's parser too,
3798    /// the web views' (`url`'s): the check may refuse more, never less.
3799    #[test]
3800    fn granted_urls_are_granted_hosts_for_whatwg() {
3801        let pattern = |p: &str| HostPattern::new(p).unwrap();
3802        let granted = [pattern("docs.example.com"), pattern("*.docs.example.com")];
3803        let a = Access {
3804            declared: caps(
3805                r#"{ "webview": { "hosts": ["docs.example.com", "*.docs.example.com"] } }"#,
3806            ),
3807            granted: None,
3808        };
3809        for url in [
3810            "https://docs.example.com/a",
3811            "https://DOCS.Example.COM/",
3812            "https://docs.example.com./",
3813            "https://x.docs.example.com:8443/",
3814            "https://user:pw@docs.example.com/",
3815            "https://docs.example.com#@bank.example/",
3816            "https://docs.example.com?@bank.example/",
3817            "https://docs.example.com:pass@bank.example/",
3818            "https://docs.example.com%2F@bank.example/",
3819            "https://bank.example\\@docs.example.com/",
3820            "https://bank.example:443\\@docs.example.com/",
3821            "https://[::1]\\@docs.example.com/",
3822            "https://bank.example\\.docs.example.com/",
3823            "https://docs.example.com\\@bank.example/",
3824            "https://bank.example\0.docs.example.com/",
3825            "https://bank.example\t.docs.example.com/",
3826            "https://docs.example.com\n.bank.example/",
3827            "https://bank%2Eexample.docs.example.com/",
3828            "https://docs\u{FF0E}example\u{FF0E}com/",
3829            "https://d\u{043E}cs.example.com/",
3830            "https:\\\\docs.example.com\\",
3831            " https://docs.example.com/",
3832            "https://docs.example.com /",
3833            "https://bank.example .docs.example.com/",
3834            "https://bank.example^.docs.example.com/",
3835            "https://bank.example[.docs.example.com/",
3836            "https://x]y.docs.example.com/",
3837            "https://a@bank.example@docs.example.com/",
3838            "https://..docs.example.com/",
3839            "HTTPS://DOCS.EXAMPLE.COM/",
3840            "https://x.docs.example.com/?q=C:\\x",
3841        ] {
3842            if a.allows_webview(url) {
3843                let whatwg = url::Url::parse(url).unwrap_or_else(|e| panic!("{url:?}: {e}"));
3844                let host = whatwg.host_str().unwrap_or_default().trim_end_matches('.');
3845                assert!(granted.iter().any(|p| p.matches(host)), "{url:?}: {host}");
3846            }
3847        }
3848    }
3849
3850    #[test]
3851    fn the_embedder_grants_at_most() {
3852        let a = Access {
3853            declared: caps(
3854                r#"{ "network": { "hosts": ["a.com", "b.com"] }, "statusBar": true, "clipboard": true, "picker": true, "speech": true, "audio": true }"#,
3855            ),
3856            granted: Some(caps(
3857                r#"{ "network": { "hosts": ["b.com"] }, "clipboard": true }"#,
3858            )),
3859        };
3860        assert!(a.allows_clipboard());
3861        assert!(!a.allows_http("GET", "https://a.com/"));
3862        assert!(!a.allows_picker());
3863        assert!(!a.allows_speech());
3864        assert!(!a.allows_audio());
3865        assert!(a.allows_http("GET", "https://b.com/"));
3866        assert!(!a.allows_status_bar());
3867    }
3868
3869    #[test]
3870    fn typos_are_errors() {
3871        let bad =
3872            |json: &str| Capabilities::from_json(&serde_json::from_str(json).unwrap()).unwrap_err();
3873        assert!(bad(r#"{ "netwrok": {} }"#).contains("unknown key `netwrok`"));
3874        assert!(bad(r#"{ "network": { "host": [] } }"#).contains("unknown key `host`"));
3875        assert!(bad(r#"{ "network": { "hosts": ["exa mple.com"] } }"#).contains("invalid host"));
3876        let c = caps(
3877            r#"{ "network": { "hosts": ["a.com"], "http": [{ "host": "b.com", "methods": ["GET"] }] }, "webview": { "hosts": ["*"] } }"#,
3878        );
3879        assert_eq!(Capabilities::from_json(&c.to_json()).unwrap(), c);
3880    }
3881
3882    /// Packages from newer signers: what this runtime does not know is never
3883    /// granted, and an unknown restriction drops what it restricts.
3884    #[test]
3885    fn unknown_keys_in_packages_grant_nothing() {
3886        let lenient =
3887            |json: &str| Capabilities::from_json_lenient(&serde_json::from_str(json).unwrap());
3888        let (c, dropped) = lenient(
3889            r#"{ "bluetooth": true, "clipboard": true,
3890                 "network": { "hosts": ["a.com"], "http": [
3891                     { "host": "b.com", "ports": [443] },
3892                     { "host": "c.com", "methods": ["GET"] }
3893                 ] } }"#,
3894        )
3895        .unwrap();
3896        assert!(c.clipboard);
3897        assert_eq!(c.network.hosts, [HostPattern::new("a.com").unwrap()]);
3898        assert_eq!(c.network.http.len(), 1);
3899        assert_eq!(c.network.http[0].host.as_str(), "c.com");
3900        assert_eq!(
3901            dropped,
3902            [
3903                "capabilities.bluetooth",
3904                "capabilities.network.http[0] (unknown key `ports`)"
3905            ]
3906        );
3907        let (c, dropped) =
3908            lenient(r#"{ "network": { "hosts": ["a.com"], "ipv6": false }, "webview": { "hosts": ["*"], "x": 1 } }"#)
3909                .unwrap();
3910        assert_eq!(c, Capabilities::default());
3911        assert_eq!(dropped.len(), 2);
3912        // A value of a form it does not know (a newer NSH's, or a typo)
3913        // drops its capability, alone: denied, as nothing is granted
3914        // unless listed.
3915        let (c, dropped) = lenient(
3916            r#"{ "statusBar": "yes", "clipboard": true,
3917                 "network": { "hosts": ["exa mple.com"] }, "webview": { "hosts": ["a.com"] } }"#,
3918        )
3919        .unwrap();
3920        assert!(!c.status_bar);
3921        assert!(c.clipboard);
3922        assert!(c.network.hosts.is_empty());
3923        assert_eq!(c.webview, Some(vec![HostPattern::new("a.com").unwrap()]));
3924        assert_eq!(dropped.len(), 2, "{dropped:?}");
3925        assert!(
3926            dropped
3927                .iter()
3928                .any(|d| d.starts_with("capabilities.statusBar ("))
3929        );
3930        assert!(
3931            dropped
3932                .iter()
3933                .any(|d| d.starts_with("capabilities.network ("))
3934        );
3935        // An `http` grant of another form is dropped alone.
3936        let (c, dropped) = lenient(
3937            r#"{ "network": { "hosts": ["a.com"], "http": [
3938                 { "host": "b.com", "port": "any" }, { "host": "c.com" } ] } }"#,
3939        )
3940        .unwrap();
3941        assert_eq!(c.network.hosts.len(), 1);
3942        assert_eq!(c.network.http.len(), 1);
3943        assert_eq!(c.network.http[0].host.as_str(), "c.com");
3944        assert_eq!(dropped.len(), 1, "{dropped:?}");
3945        assert!(dropped[0].starts_with("capabilities.network.http[0] ("));
3946        // A declaration that is no object grants nothing.
3947        let (c, dropped) = lenient(r#""everything""#).unwrap();
3948        assert_eq!(c, Capabilities::default());
3949        assert_eq!(dropped.len(), 1);
3950        // The strict parse still refuses them.
3951        assert!(Capabilities::from_json(&serde_json::json!({ "statusBar": "yes" })).is_err());
3952        // Nothing unknown: the same as the strict parse.
3953        let json = serde_json::json!({ "network": { "hosts": ["a.com"] }, "statusBar": true });
3954        let (c, dropped) = Capabilities::from_json_lenient(&json).unwrap();
3955        assert_eq!(c, Capabilities::from_json(&json).unwrap());
3956        assert!(dropped.is_empty());
3957    }
3958
3959    #[test]
3960    fn media_redirects_are_checked() {
3961        let a = Access {
3962            declared: Capabilities::from_json(
3963                &serde_json::json!({ "network": { "hosts": ["a.com"] } }),
3964            )
3965            .unwrap(),
3966            granted: None,
3967        };
3968        let from = "https://a.com/x/y.png";
3969        assert_eq!(
3970            a.media_redirect(from, "/z.png").unwrap(),
3971            "https://a.com/z.png"
3972        );
3973        assert_eq!(
3974            a.media_redirect(from, "z.png").unwrap(),
3975            "https://a.com/x/z.png"
3976        );
3977        assert!(a.media_redirect(from, "https://b.com/z.png").is_err());
3978        assert!(a.media_redirect(from, "//b.com/z.png").is_err());
3979        assert!(a.media_redirect(from, "file:///etc/passwd").is_err());
3980        assert!(
3981            Access::default()
3982                .media_redirect(from, "//b.com/z.png")
3983                .is_ok()
3984        );
3985        assert!(
3986            Access::default()
3987                .media_redirect(from, "ftp://b.com/z.png")
3988                .is_err()
3989        );
3990    }
3991
3992    /// An HTTP rule's paths are matched against the path WHATWG's parser
3993    /// (the web views', the `url` crate's) reads, as a server receives it:
3994    /// dot segments, percent-encoded ones too, are resolved first.
3995    #[test]
3996    fn http_paths_are_matched_as_whatwg_resolves_them() {
3997        let a = Access {
3998            declared: caps(
3999                r#"{ "network": { "http": [{ "host": "api.example.com", "pathPrefix": "/public" }] } }"#,
4000            ),
4001            granted: None,
4002        };
4003        for url in [
4004            "https://api.example.com/public/../private",
4005            "https://api.example.com/public/%2e%2e/private",
4006            "https://api.example.com/public/%2E%2E/private",
4007            "https://api.example.com/public/.%2e/private",
4008            "https://api.example.com/public/./../private",
4009        ] {
4010            assert!(!a.allows_http("GET", url), "{url}");
4011            assert!(!a.allows_media(url), "{url}");
4012        }
4013        for url in [
4014            "https://api.example.com/public/x",
4015            "https://api.example.com/private/../public/x",
4016            "https://api.example.com/public/./x",
4017        ] {
4018            assert!(a.allows_http("GET", url), "{url}");
4019        }
4020    }
4021
4022    /// A redirect's location is resolved as WHATWG's parser resolves it,
4023    /// dot segments included, before the rules see it.
4024    #[test]
4025    fn redirects_resolve_dot_segments() {
4026        assert_eq!(
4027            resolve_reference("https://api.example.com/public/x", "../private"),
4028            "https://api.example.com/private"
4029        );
4030        assert_eq!(
4031            resolve_reference("https://api.example.com/public/x", "%2e%2e/private"),
4032            "https://api.example.com/private"
4033        );
4034        let a = Access {
4035            declared: caps(
4036                r#"{ "network": { "http": [{ "host": "api.example.com", "pathPrefix": "/public" }] } }"#,
4037            ),
4038            granted: None,
4039        };
4040        let from = "https://api.example.com/public/a.png";
4041        assert!(a.media_redirect(from, "b.png").is_ok());
4042        assert!(a.media_redirect(from, "../private.png").is_err());
4043        assert!(a.media_redirect(from, "/public/../private.png").is_err());
4044    }
4045
4046    /// A media source with a scheme, or one that starts with `//` or a
4047    /// backslash, names a host: it is checked as WHATWG's parser reads it,
4048    /// not taken for the app's own file.
4049    #[test]
4050    fn media_sources_that_name_a_host_are_checked() {
4051        let a = Access {
4052            declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
4053            granted: None,
4054        };
4055        for uri in [
4056            "//bank.example/x.png",
4057            "\\\\bank.example\\x.png",
4058            "/\\bank.example/x.png",
4059            "https:\\\\bank.example\\x.png",
4060            "https:/bank.example/x.png",
4061            "HTTPS://bank.example/x.png",
4062        ] {
4063            assert!(!a.allows_media(uri), "{uri}");
4064        }
4065        // The app's own files and bytes it has stay its own.
4066        for uri in [
4067            "asset:/a.png",
4068            "data:image/png;base64,AAAA",
4069            "blob:https://app.example/1",
4070            "https://docs.example.com/x.png",
4071        ] {
4072            assert!(a.allows_media(uri), "{uri}");
4073        }
4074        // A relative path names no file of the app's in a native app
4075        // (`relative_paths_name_no_file_in_a_native_app`).
4076        assert!(!a.allows_media("img/a.png"));
4077        // An app without capabilities is not checked, as before.
4078        assert!(Access::default().allows_media("//bank.example/x.png"));
4079    }
4080
4081    /// WHATWG's parser drops leading and trailing spaces and C0 controls and
4082    /// every tab and newline before it reads a URL, so a source those make
4083    /// into one naming a host is checked, never kept as a relative path.
4084    #[test]
4085    fn media_sources_are_read_after_whatwg_strips_them() {
4086        let a = Access {
4087            declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
4088            granted: None,
4089        };
4090        let page = Some("https://app.example/index.html");
4091        for uri in [
4092            "\t//bank.example/x.png",
4093            "\n//bank.example/x.png",
4094            "/\t/bank.example/x.png",
4095            " https://bank.example/x.png",
4096            "https://bank.example/x.png ",
4097            "ht\ttps://bank.example/x.png",
4098            "\u{1}https://bank.example/x.png",
4099        ] {
4100            assert_eq!(a.media_url(uri, page, None), None, "{uri:?} on the web");
4101            assert_eq!(
4102                a.media_url(uri, None, None),
4103                None,
4104                "{uri:?} in a native app"
4105            );
4106        }
4107        // What stays relative after stripping stays the app's own.
4108        assert_eq!(
4109            a.media_url(" icons/a.png", page, None),
4110            Some(Cow::Borrowed(" icons/a.png"))
4111        );
4112        // Hosts are checked as WHATWG writes them, and load as checked.
4113        let local = Access {
4114            declared: caps(r#"{ "network": { "hosts": ["127.0.0.1"] } }"#),
4115            granted: None,
4116        };
4117        assert_eq!(
4118            local.media_url("http://0x7f.1/a.png", None, None),
4119            Some(Cow::Owned("http://127.0.0.1/a.png".into()))
4120        );
4121        assert_eq!(a.media_url("http://0x7f.1/a.png", None, None), None);
4122        // Schemes ignore case, the app's own sources' too.
4123        for own in [
4124            "DATA:image/png;base64,AA",
4125            "Asset:/a.png",
4126            "BLOB:https://app.example/1",
4127        ] {
4128            assert_eq!(
4129                a.media_url(own, page, None),
4130                Some(Cow::Borrowed(own)),
4131                "{own}"
4132            );
4133        }
4134    }
4135
4136    /// Spaces and C0 controls around a source, which WHATWG's parser drops,
4137    /// are dropped before the check, and the loader gets the serialization:
4138    /// a granted URL a CMS left a trailing space on loads (it did before
4139    /// this branch), and no loader reads the source as written. A control
4140    /// inside, tabs and newlines included, stays ambiguous (#979).
4141    #[test]
4142    fn whitespace_around_a_granted_url_loads_its_serialization() {
4143        let a = Access {
4144            declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
4145            granted: None,
4146        };
4147        let page = Some("https://app.example/index.html");
4148        for (uri, base) in [
4149            ("https://docs.example.com/x.png ", None),
4150            (" https://docs.example.com/x.png", None),
4151            ("\u{1}https://docs.example.com/x.png", None),
4152            ("\t//docs.example.com/x.png", page),
4153        ] {
4154            assert_eq!(
4155                a.media_url(uri, base, None),
4156                Some(Cow::Owned("https://docs.example.com/x.png".into())),
4157                "{uri:?}"
4158            );
4159        }
4160        // A host it names is still checked, and a control inside stays
4161        // ambiguous.
4162        assert_eq!(a.media_url("https://bank.example/x.png ", None, None), None);
4163        for inside in [
4164            "https://docs.example.com/x\u{1}.png",
4165            "https://docs.ex\tample.com/x.png",
4166            "ht\ntps://docs.example.com/x.png",
4167        ] {
4168            assert_eq!(a.media_url(inside, None, None), None, "{inside:?}");
4169        }
4170    }
4171
4172    /// A grant's paths are read as a request sends them (WHATWG percent-
4173    /// encodes spaces, `{`, `}` and what is not ASCII), so a path written
4174    /// with them matches; one with dot segments could match nothing and is
4175    /// a parse error.
4176    #[test]
4177    fn grant_paths_match_as_requests_send_them() {
4178        let a = Access {
4179            declared: caps(
4180                r#"{ "network": { "http": [
4181                    { "host": "cdn.example.com", "pathPrefix": "/my photos" },
4182                    { "host": "cdn.example.com", "paths": ["/über.png", "/{id}.png"] }
4183                ] } }"#,
4184            ),
4185            granted: None,
4186        };
4187        for url in [
4188            "https://cdn.example.com/my photos/a.png",
4189            "https://cdn.example.com/my%20photos/a.png",
4190            "https://cdn.example.com/über.png",
4191            "https://cdn.example.com/{id}.png",
4192        ] {
4193            assert!(a.allows_http("GET", url), "{url}");
4194            assert!(a.media_url(url, None, None).is_some(), "{url}");
4195        }
4196        assert!(!a.allows_http("GET", "https://cdn.example.com/my photosx/a.png"));
4197        // WHATWG reads `\\` as `/` and drops tabs and newlines, so these
4198        // are dot segments too.
4199        for bad in [
4200            "/a/../b",
4201            "/./a",
4202            "/a/%2e%2e/b",
4203            "/a/.%2E",
4204            "/public\\..\\private",
4205            "/a/.\t./b",
4206            "/a/.\n/b",
4207        ] {
4208            let json = serde_json::json!({ "network": { "http": [{ "host": "h.example", "pathPrefix": bad }] } });
4209            assert!(Capabilities::from_json(&json).is_err(), "{bad}");
4210        }
4211    }
4212
4213    /// A local file is held to the roots by its text first, as
4214    /// `fs/promises` does: a path outside them is refused with no disk work
4215    /// on the engine thread (a hung mount, or a Windows share it would
4216    /// connect to), and only one inside is resolved to see that no link
4217    /// leads out.
4218    #[cfg(unix)]
4219    #[test]
4220    fn paths_outside_the_roots_are_refused_without_disk_work() {
4221        let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
4222        let root = base.join(format!("media-text-{}", std::process::id()));
4223        let _ = std::fs::remove_dir_all(&root);
4224        std::fs::create_dir_all(root.join("allowed")).unwrap();
4225        std::fs::create_dir_all(root.join("elsewhere")).unwrap();
4226        std::fs::write(root.join("allowed/a.png"), b"png").unwrap();
4227        // A link outside the root into it: its text is outside.
4228        std::os::unix::fs::symlink(root.join("allowed"), root.join("elsewhere/in")).unwrap();
4229        let allowed = root.join("allowed");
4230        let access = Access {
4231            declared: Capabilities::from_json(
4232                &serde_json::json!({ "fs": { "read": [allowed.to_str().unwrap()] } }),
4233            )
4234            .unwrap(),
4235            granted: None,
4236        };
4237        let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
4238        let resolves = || RESOLVES.with(std::cell::Cell::get);
4239        let before = resolves();
4240        for outside in [
4241            root.join("elsewhere/x.png"),
4242            root.join("elsewhere/in/a.png"),
4243            PathBuf::from("/Volumes/hung/x.png"),
4244        ] {
4245            assert_eq!(files.readable(&outside), None, "{}", outside.display());
4246        }
4247        assert_eq!(
4248            resolves(),
4249            before,
4250            "outside the roots, nothing was resolved"
4251        );
4252        // Under the root's expanded or canonical form, it is resolved.
4253        assert!(files.readable(&allowed.join("a.png")).is_some());
4254        assert!(
4255            files
4256                .readable(&canonicalize(&allowed).unwrap().join("a.png"))
4257                .is_some()
4258        );
4259        assert_eq!(resolves(), before + 2);
4260        let _ = std::fs::remove_dir_all(&root);
4261    }
4262
4263    /// Every check of a local file resolves it again: a file granted once
4264    /// and then replaced by a symlink out of the root is refused (#1417's
4265    /// review), never answered from an earlier check.
4266    #[cfg(unix)]
4267    #[test]
4268    fn a_granted_file_replaced_by_a_symlink_is_refused() {
4269        use std::os::unix::fs::symlink;
4270        let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
4271        let root = base.join(format!("media-swap-{}", std::process::id()));
4272        let _ = std::fs::remove_dir_all(&root);
4273        std::fs::create_dir_all(root.join("allowed")).unwrap();
4274        let root = canonicalize(&root).unwrap();
4275        std::fs::write(root.join("allowed/image.png"), b"public").unwrap();
4276        std::fs::write(root.join("secret.png"), b"secret").unwrap();
4277        let allowed = root.join("allowed").to_str().unwrap().to_owned();
4278        let access = Access {
4279            declared: Capabilities::from_json(
4280                &serde_json::json!({ "fs": { "read": [allowed.clone()] } }),
4281            )
4282            .unwrap(),
4283            granted: None,
4284        };
4285        let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
4286        let src = format!("{allowed}/image.png");
4287        assert!(access.media_url(&src, None, Some(&files)).is_some());
4288        std::fs::remove_file(root.join("allowed/image.png")).unwrap();
4289        symlink(root.join("secret.png"), root.join("allowed/image.png")).unwrap();
4290        assert_eq!(access.media_url(&src, None, Some(&files)), None);
4291        let _ = std::fs::remove_dir_all(&root);
4292    }
4293
4294    /// A bundled file (`asset:`) stays inside the app's files, as `fetch`
4295    /// reads one: a path that leaves them, however it is spelled, loads
4296    /// nothing for an app with capabilities. The loaders join the path to
4297    /// their directory as written, query included.
4298    #[test]
4299    fn bundled_files_stay_inside_the_app_files() {
4300        let a = Access {
4301            declared: caps(r#"{ "network": { "hosts": ["*"] } }"#),
4302            granted: None,
4303        };
4304        for escape in [
4305            "asset:/../outside.png",
4306            "asset:/sub/../../outside.png",
4307            "asset:/%2E%2e/outside.png",
4308            "asset:/..%2Foutside.png",
4309            "asset:/a%5c..%5c..%5coutside.png",
4310            "asset:/a.png?/../../outside.png",
4311            "asset:/a.png#/../../outside.png",
4312            "asset://Users/a/outside.png",
4313            "asset:/C:/outside.png",
4314            "asset:/./a.png",
4315            "asset:../outside.png",
4316            "ASSET:/../outside.png",
4317        ] {
4318            assert_eq!(a.media_url(escape, None, None), None, "{escape}");
4319            assert_eq!(
4320                a.media_url(escape, Some("https://app.example/"), None),
4321                None,
4322                "{escape} on the web"
4323            );
4324            assert_eq!(media_grant_advice(escape, None), ASSET_ADVICE, "{escape}");
4325            assert_eq!(media_capability(escape, None), "fs", "{escape}");
4326        }
4327        for inside in [
4328            "asset:/a.png",
4329            "asset:/@app/icons/a.png",
4330            "asset:/a.png?v=2",
4331            "asset:/a%20b.png",
4332            "asset:/sub/a..b.png",
4333            "ASSET:/a.png",
4334        ] {
4335            assert_eq!(
4336                a.media_url(inside, None, None),
4337                Some(Cow::Borrowed(inside)),
4338                "{inside}"
4339            );
4340        }
4341        // An app without capabilities reads what it names, as before.
4342        assert_eq!(
4343            Access::default().media_url("asset:/../outside.png", None, None),
4344            Some(Cow::Borrowed("asset:/../outside.png"))
4345        );
4346    }
4347
4348    /// A relative path names no file of the app's in a native app: the
4349    /// platforms read one against the process's working directory (desktop
4350    /// videos, Android images) or not at all, so an app with capabilities
4351    /// loads nothing from it. On the web it is the page's.
4352    #[test]
4353    fn relative_paths_name_no_file_in_a_native_app() {
4354        let a = Access {
4355            declared: caps(r#"{ "network": { "hosts": ["*"] } }"#),
4356            granted: None,
4357        };
4358        for relative in [
4359            "clip.mp4",
4360            "./clip.mp4",
4361            "Users/a/secret.mp4",
4362            "../etc/x.png",
4363            " /etc/x.png",
4364        ] {
4365            assert_eq!(a.media_url(relative, None, None), None, "{relative}");
4366            assert_eq!(media_capability(relative, None), "fs", "{relative}");
4367            assert_eq!(
4368                media_grant_advice(relative, None),
4369                RELATIVE_ADVICE,
4370                "{relative}"
4371            );
4372            assert_eq!(
4373                a.media_url(relative, Some("https://app.example/"), None),
4374                Some(Cow::Borrowed(relative)),
4375                "{relative} on the web"
4376            );
4377            assert_eq!(
4378                Access::default().media_url(relative, None, None),
4379                Some(Cow::Borrowed(relative)),
4380                "{relative} without capabilities"
4381            );
4382        }
4383        // No source is no refusal.
4384        for empty in ["", "  "] {
4385            assert_eq!(a.media_url(empty, None, None), Some(Cow::Borrowed(empty)));
4386        }
4387    }
4388
4389    /// A granted media file is read through its root: a link swapped in
4390    /// after the check does not lead the read out of it.
4391    #[cfg(unix)]
4392    #[test]
4393    fn media_files_open_inside_their_root() {
4394        use std::io::Read;
4395        let base = std::env::temp_dir().join(format!("media-open-{}", std::process::id()));
4396        let _ = std::fs::remove_dir_all(&base);
4397        std::fs::create_dir_all(base.join("allowed")).unwrap();
4398        let base = canonicalize(&base).unwrap();
4399        std::fs::write(base.join("allowed/a.png"), b"public").unwrap();
4400        std::fs::write(base.join("secret.png"), b"secret").unwrap();
4401        let allowed = base.join("allowed");
4402        let access = Access {
4403            declared: Capabilities::from_json(
4404                &serde_json::json!({ "fs": { "read": [allowed.to_str().unwrap()] } }),
4405            )
4406            .unwrap(),
4407            granted: None,
4408        };
4409        let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
4410        let path = allowed.join("a.png");
4411        let read = |path: &Path| {
4412            let mut text = String::new();
4413            files.open(path)?.ok()?.read_to_string(&mut text).ok()?;
4414            Some(text)
4415        };
4416        assert_eq!(read(&path).as_deref(), Some("public"));
4417        // Swapped for a link out of the root after the check.
4418        std::fs::remove_file(&path).unwrap();
4419        std::os::unix::fs::symlink(base.join("secret.png"), &path).unwrap();
4420        assert!(matches!(files.open(&path), Some(Err(_))));
4421        assert!(matches!(files.open(&base.join("secret.png")), Some(Err(_))));
4422        // No roots: the caller opens the path.
4423        assert!(MediaFiles::default().open(&path).is_none());
4424        // A grant narrower than the declared root: a link in the grant
4425        // to a file elsewhere in the declared root is refused (#1605).
4426        std::fs::create_dir_all(base.join("allowed/sub")).unwrap();
4427        std::fs::write(base.join("allowed/sub/ok.png"), b"ok").unwrap();
4428        std::os::unix::fs::symlink(
4429            base.join("allowed/a.png"),
4430            base.join("allowed/sub/link.png"),
4431        )
4432        .unwrap();
4433        std::fs::remove_file(&path).unwrap();
4434        std::fs::write(&path, b"public").unwrap();
4435        let narrowed = Access {
4436            declared: access.declared.clone(),
4437            granted: Some(
4438                Capabilities::from_json(&serde_json::json!({
4439                    "fs": { "read": [allowed.join("sub").to_str().unwrap()] }
4440                }))
4441                .unwrap(),
4442            ),
4443        };
4444        let files = MediaFiles::new(&narrowed, None, &TrustedPaths::default(), true);
4445        let mut text = String::new();
4446        files
4447            .open(&allowed.join("sub/ok.png"))
4448            .unwrap()
4449            .unwrap()
4450            .read_to_string(&mut text)
4451            .unwrap();
4452        assert_eq!(text, "ok");
4453        assert!(matches!(
4454            files.open(&allowed.join("sub/link.png")),
4455            Some(Err(_))
4456        ));
4457        assert!(matches!(files.open(&path), Some(Err(_))));
4458        // `file://localhost/` names the same local file, and is refused the same.
4459        let localhost = format!("file://localhost{}", allowed.join("sub/link.png").display());
4460        assert_eq!(narrowed.media_url(&localhost, None, Some(&files)), None);
4461        let ok = format!("file://localhost{}", allowed.join("sub/ok.png").display());
4462        assert!(narrowed.media_url(&ok, None, Some(&files)).is_some());
4463        let _ = std::fs::remove_dir_all(&base);
4464    }
4465
4466    /// A symlink in a granted root whose target does not exist yet is
4467    /// refused: it names no file to resolve, and the loader would follow it
4468    /// out of the root once the target appears.
4469    #[cfg(unix)]
4470    #[test]
4471    fn a_dangling_symlink_in_a_granted_root_is_refused() {
4472        use std::os::unix::fs::symlink;
4473        let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
4474        let root = base.join(format!("media-dangling-{}", std::process::id()));
4475        let _ = std::fs::remove_dir_all(&root);
4476        std::fs::create_dir_all(root.join("allowed")).unwrap();
4477        let root = canonicalize(&root).unwrap();
4478        symlink(root.join("secret.png"), root.join("allowed/link.png")).unwrap();
4479        let allowed = root.join("allowed").to_str().unwrap().to_owned();
4480        let access = Access {
4481            declared: Capabilities::from_json(
4482                &serde_json::json!({ "fs": { "read": [allowed.clone()] } }),
4483            )
4484            .unwrap(),
4485            granted: None,
4486        };
4487        let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
4488        assert_eq!(
4489            access.media_url(&format!("{allowed}/link.png"), None, Some(&files)),
4490            None
4491        );
4492        // A file that does not exist yet, and no link, is still the root's.
4493        let missing = format!("{allowed}/later.png");
4494        assert_eq!(
4495            access.media_url(&missing, None, Some(&files)),
4496            Some(Cow::Borrowed(missing.as_str()))
4497        );
4498        let _ = std::fs::remove_dir_all(&root);
4499    }
4500
4501    /// A local file in a media source (an absolute path, a `file:` URL) is
4502    /// read under `capabilities.fs.read`, as `fs/promises` reads it, and
4503    /// loads as its canonical path, so a symlink in a granted root cannot
4504    /// lead the platform's loader out of it.
4505    #[cfg(unix)]
4506    #[test]
4507    fn local_media_files_need_an_fs_read_grant() {
4508        use std::os::unix::fs::symlink;
4509        let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
4510        let root = base.join(format!("media-files-{}", std::process::id()));
4511        let _ = std::fs::remove_dir_all(&root);
4512        std::fs::create_dir_all(root.join("allowed")).unwrap();
4513        std::fs::create_dir_all(root.join("outside")).unwrap();
4514        std::fs::write(root.join("allowed/a.png"), b"png").unwrap();
4515        std::fs::write(root.join("outside/b.png"), b"png").unwrap();
4516        symlink(root.join("outside"), root.join("allowed/link")).unwrap();
4517        // Canonical, so only the symlink below differs from its text.
4518        let root = canonicalize(&root).unwrap();
4519        let data = root.join("allowed");
4520        let access = Access {
4521            declared: caps(
4522                r#"{ "network": { "hosts": ["docs.example.com"] }, "fs": { "read": ["${dataDir}"] } }"#,
4523            ),
4524            granted: None,
4525        };
4526        let files = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), true);
4527        let real = canonicalize(&data).unwrap();
4528        let path = |p: &Path| p.to_str().unwrap().to_owned();
4529        let load = |uri: &str| {
4530            access
4531                .media_url(uri, None, Some(&files))
4532                .map(Cow::into_owned)
4533        };
4534
4535        let granted = path(&real.join("a.png"));
4536        assert_eq!(load(&path(&data.join("a.png"))), Some(granted.clone()));
4537        assert_eq!(
4538            load(&format!("file://{}", path(&data.join("a.png")))),
4539            Some(format!("file://{granted}"))
4540        );
4541        assert_eq!(
4542            load(&format!("FILE://{}", path(&data.join("a.png")))),
4543            Some(format!("file://{granted}"))
4544        );
4545        // `..`, percent-encoded or not, and a symlink lead out of the root.
4546        assert_eq!(load(&path(&data.join("../outside/b.png"))), None);
4547        assert_eq!(
4548            load(&format!("file://{}/%2e%2e/outside/b.png", path(&data))),
4549            None
4550        );
4551        assert_eq!(load(&path(&data.join("link/b.png"))), None);
4552        assert_eq!(load(&path(&root.join("outside/b.png"))), None);
4553        // No roots to read from: none granted, or no file system here.
4554        assert_eq!(
4555            access.media_url(&path(&data.join("a.png")), None, None),
4556            None
4557        );
4558        let mobile = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), false);
4559        assert_eq!(
4560            access.media_url(&path(&data.join("a.png")), None, Some(&mobile)),
4561            None
4562        );
4563        let network_only = Access {
4564            declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
4565            granted: None,
4566        };
4567        let none = MediaFiles::new(&network_only, Some(&data), &TrustedPaths::default(), true);
4568        assert_eq!(
4569            network_only.media_url(&path(&data.join("a.png")), None, Some(&none)),
4570            None
4571        );
4572        // The host's grant narrows the app's.
4573        let narrowed = Access {
4574            declared: caps(r#"{ "fs": { "read": ["${dataDir}"] } }"#),
4575            granted: Some(caps(r#"{ "fs": { "read": ["${dataDir}/sub"] } }"#)),
4576        };
4577        let files = MediaFiles::new(&narrowed, Some(&data), &TrustedPaths::default(), true);
4578        assert_eq!(
4579            narrowed.media_url(&path(&data.join("a.png")), None, Some(&files)),
4580            None
4581        );
4582        // On the web, `/x` is the page's; an app without capabilities loads
4583        // what it names, as before.
4584        let page = Some("https://app.example/index.html");
4585        assert_eq!(
4586            access.media_url("/icons/a.png", page, None),
4587            Some(Cow::Borrowed("/icons/a.png"))
4588        );
4589        // An app without capabilities loads local files as written, as
4590        // before.
4591        for local in [
4592            path(&root.join("outside/b.png")),
4593            format!("FILE://{}", path(&root.join("outside/b.png"))),
4594            "C:\\pictures\\x.png".to_owned(),
4595            "/x.png".to_owned(),
4596        ] {
4597            assert_eq!(
4598                Access::default().media_url(&local, None, None),
4599                Some(Cow::Borrowed(local.as_str())),
4600                "{local}"
4601            );
4602        }
4603        // A path checked again answers the same.
4604        let files = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), true);
4605        for _ in 0..2 {
4606            let again = |uri: &str| {
4607                access
4608                    .media_url(uri, None, Some(&files))
4609                    .map(Cow::into_owned)
4610            };
4611            assert_eq!(again(&path(&data.join("a.png"))), Some(granted.clone()));
4612            assert_eq!(again(&path(&data.join("link/b.png"))), None);
4613        }
4614        let _ = std::fs::remove_dir_all(&root);
4615    }
4616
4617    /// `capabilities.fs` roots gate the file system every native OS has —
4618    /// the desktops', iOS's, Android's; the web has none to gate.
4619    #[test]
4620    fn every_native_os_has_the_files_the_capability_gates() {
4621        use crate::platform::Os;
4622        for os in [Os::MacOs, Os::Windows, Os::Linux, Os::Ios, Os::Android] {
4623            assert!(native_files(os), "{os:?}");
4624        }
4625        assert!(!native_files(Os::Web));
4626    }
4627
4628    /// A `file:` URL's path is the URL's decoded path: `%20` is a space,
4629    /// `file://localhost/` names no host that refuses.
4630    #[cfg(not(target_arch = "wasm32"))]
4631    #[test]
4632    fn file_urls_name_their_decoded_path() {
4633        #[cfg(unix)]
4634        {
4635            assert_eq!(
4636                file_url_path("file:///tmp/a%20b.png"),
4637                Some(PathBuf::from("/tmp/a b.png"))
4638            );
4639            assert_eq!(
4640                file_url_path("file://localhost/tmp/a.png"),
4641                Some(PathBuf::from("/tmp/a.png"))
4642            );
4643            assert_eq!(file_url_path("file://host/tmp/a.png"), None);
4644        }
4645        #[cfg(windows)]
4646        {
4647            // A `file:` URL there names a drive: a path without one is no
4648            // Windows path (this is what the URL standard says, and what
4649            // the loaders resolve), and `localhost` is still no host to
4650            // refuse.
4651            assert_eq!(
4652                file_url_path("file:///C:/a%20b.png"),
4653                Some(PathBuf::from("C:\\a b.png"))
4654            );
4655            assert_eq!(
4656                file_url_path("file://localhost/C:/a.png"),
4657                Some(PathBuf::from("C:\\a.png"))
4658            );
4659            assert_eq!(file_url_path("file:///tmp/a.png"), None);
4660            assert_eq!(file_url_path("file://localhost/tmp/a.png"), None);
4661        }
4662        assert_eq!(file_url_path("not a url"), None);
4663        assert_eq!(file_url_path("https://a/b"), None);
4664    }
4665
4666    /// A refused source's advice names the host it resolves to, as the
4667    /// check read it.
4668    #[test]
4669    fn refused_media_sources_advise_the_host_they_resolve_to() {
4670        let page = Some("http://localhost:8080/index.html");
4671        // Against the page, `//host` names the host a grant would add.
4672        assert_eq!(
4673            media_grant_advice("//127.0.0.1:9000/a.png", page),
4674            "add `127.0.0.1` to capabilities.network in nsh.json"
4675        );
4676        // Without one, it has no scheme to load with.
4677        assert_eq!(
4678            media_grant_advice("//127.0.0.1:9000/a.png", None),
4679            NO_SCHEME_ADVICE
4680        );
4681        // A backslash stays ambiguous, whatever the base.
4682        assert_eq!(
4683            media_grant_advice("//127.0.0.1\\a.png", page),
4684            NO_HOST_ADVICE
4685        );
4686        assert_eq!(
4687            media_grant_advice("https://cdn.example.com/a.png", page),
4688            "add `cdn.example.com` to capabilities.network in nsh.json"
4689        );
4690        // A local file is the `fs` capability's, in a native app; `/x` is
4691        // the page's on the web.
4692        assert_eq!(
4693            media_grant_advice("/Users/a/x.png", None),
4694            LOCAL_FILE_ADVICE
4695        );
4696        assert_eq!(
4697            media_grant_advice("file:///Users/a/x.png", page),
4698            LOCAL_FILE_ADVICE
4699        );
4700        // A refusal names the capability that would grant the source.
4701        assert_eq!(media_capability("/Users/a/x.png", None), "fs");
4702        assert_eq!(media_capability("C:\\pictures\\x.png", None), "fs");
4703        assert_eq!(media_capability("FILE:///Users/a/x.png", page), "fs");
4704        assert_eq!(media_capability("/icons/a.png", page), "network");
4705        assert_eq!(
4706            media_capability("https://cdn.example.com/a.png", None),
4707            "network"
4708        );
4709    }
4710
4711    /// What a loader loads is what the check granted: a source naming a host
4712    /// becomes its WHATWG serialization, `//` taking the base's scheme (the
4713    /// page's on the web; with no base it names no URL); the app's own stay
4714    /// as written.
4715    #[test]
4716    fn media_sources_load_the_url_the_check_granted() {
4717        let a = Access {
4718            declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
4719            granted: None,
4720        };
4721        let https = Some("https://app.example/index.html");
4722        let http = Some("http://127.0.0.1:8080/");
4723        let loads = |uri, base| a.media_url(uri, base, None).map(|u| u.into_owned());
4724        assert_eq!(
4725            loads("https://DOCS.example.com/a/../x.png", None).as_deref(),
4726            Some("https://docs.example.com/x.png")
4727        );
4728        assert_eq!(
4729            loads("//docs.example.com/x.png", https).as_deref(),
4730            Some("https://docs.example.com/x.png")
4731        );
4732        assert_eq!(
4733            loads("//docs.example.com/x.png", http).as_deref(),
4734            Some("http://docs.example.com/x.png")
4735        );
4736        // A backslash before the query is read differently by Foundation's
4737        // `NSURL` (`urls_that_parsers_read_as_different_hosts_are_refused`):
4738        // only a grant of every host covers it, `//`'s backslash forms too.
4739        assert_eq!(loads("\\\\docs.example.com\\x.png", https), None);
4740        assert_eq!(loads("//docs.example.com/x.png", None), None);
4741        assert_eq!(loads("//bank.example/x.png", https), None);
4742        for own in ["asset:/a.png", "img/a.png", "data:image/png;base64,AAAA"] {
4743            assert!(
4744                matches!(a.media_url(own, https, None), Some(std::borrow::Cow::Borrowed(u)) if u == own),
4745                "{own}"
4746            );
4747        }
4748        // Without capabilities, nothing is checked or rewritten.
4749        assert!(matches!(
4750            Access::default().media_url("//bank.example/x.png", None, None),
4751            Some(std::borrow::Cow::Borrowed("//bank.example/x.png"))
4752        ));
4753    }
4754
4755    #[test]
4756    fn opening_urls_is_granted_by_scheme() {
4757        let caps = |json: serde_json::Value| Capabilities::from_json(&json).unwrap();
4758        let access =
4759            |declared: Capabilities, granted: Option<Capabilities>| Access { declared, granted };
4760        let any = access(caps(serde_json::json!({ "openUrl": true })), None);
4761        assert!(any.allows_open_url("https://a.com"));
4762        assert!(any.allows_open_url("tel:+15550100"));
4763        let some = access(
4764            caps(serde_json::json!({ "openUrl": { "schemes": ["HTTPS", "mailto"] } })),
4765            None,
4766        );
4767        assert!(some.allows_open_url("https://a.com"));
4768        assert!(some.allows_open_url("MAILTO:a@b.c"));
4769        assert!(!some.allows_open_url("tel:1"));
4770        // The embedding app grants less.
4771        let narrowed = access(
4772            caps(serde_json::json!({ "openUrl": true })),
4773            Some(caps(
4774                serde_json::json!({ "openUrl": { "schemes": ["https"] } }),
4775            )),
4776        );
4777        assert!(narrowed.allows_open_url("https://a.com"));
4778        assert!(!narrowed.allows_open_url("mailto:a@b.c"));
4779        let none = access(caps(serde_json::json!({ "openUrl": false })), None);
4780        assert!(!none.allows_open_url("https://a.com"));
4781        assert!(!access(caps(serde_json::json!({})), None).allows_open_url("https://a.com"));
4782        assert!(Access::default().allows_open_url("https://a.com"));
4783        for bad in [
4784            serde_json::json!({ "openUrl": "yes" }),
4785            serde_json::json!({ "openUrl": { "schemes": ["ht tp"] } }),
4786            serde_json::json!({ "openUrl": { "hosts": ["a.com"] } }),
4787        ] {
4788            assert!(Capabilities::from_json(&bad).is_err(), "{bad}");
4789        }
4790        // Round trip.
4791        for json in [
4792            serde_json::json!(true),
4793            serde_json::json!(false),
4794            serde_json::json!({ "schemes": ["https"] }),
4795        ] {
4796            let c = caps(serde_json::json!({ "openUrl": json }));
4797            assert_eq!(c.to_json()["openUrl"], json);
4798        }
4799    }
4800}