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