Skip to main content

nsh_core/
access.rs

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