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