Skip to main content

nsh_core/
access.rs

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