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, and unknown keys are errors, so a
6//! typo is caught at build time rather than becoming a missing grant.
7//! Signed packages are read leniently ([`Capabilities::from_json_lenient`]):
8//! a newer signer may declare what this runtime does not know, which is
9//! then not granted.
10//!
11//! ```json
12//! "capabilities": {
13//!   "network": {
14//!     "hosts": ["api.example.com", "*.cdn.example.com"],
15//!     "http": [{ "host": "quotes.example.com", "methods": ["GET"], "pathPrefix": "/v1/" }],
16//!     "sockets": ["mqtt.example.com:8883"]
17//!   },
18//!   "webview": { "hosts": ["*.example.com"] },
19//!   "statusBar": true,
20//!   "host": ["getUserInfo", "bridge.*"],
21//!   "openUrl": { "schemes": ["https", "mailto"] }
22//! }
23//! ```
24//!
25//! `openUrl` lets the app open URLs outside it (`openUrl` of `nsh/device`,
26//! [`crate::open_url`]: the browser, the mail or phone app, other apps'
27//! schemes): `true` for every scheme, `{ "schemes": [...] }` for those
28//! listed. `network` covers `fetch` (every redirect is checked again), remote
29//! images (also canvas images and `Image.getSize` / `prefetch`) and video
30//! sources; `asset:` URIs are always allowed. WebSockets are HTTP upgrades:
31//! a `ws:` / `wss:` URL is checked as a GET of the same URL over `http:` /
32//! `https:` (or under its own scheme, for legacy rules that list it).
33//! `network.sockets` grants raw TCP (`net.connect`) to exact `host:port`
34//! pairs only: no wildcards, and neither `hosts` nor `http` grants imply
35//! one. `webview` lists the hosts a web view may show and navigate to (its
36//! pages' own subresources are the web content's business). `host` lists
37//! the functions of the embedding app `nsh/host` may call: names (1 to 128
38//! of `[A-Za-z0-9_.:-]`, without `..`; the core refuses calls of any other
39//! name), or prefixes of them ending in `*` (`true`: all of them); the
40//! host's events need no grant, the host sends them. An app without
41//! `"capabilities"` (a standalone app, its developer's own) retains
42//! unrestricted HTTP, web views, the status bar, the clipboard, the picker
43//! and opening URLs; raw sockets, processes, the filesystem and the host's
44//! functions always require an explicit declaration.
45
46//! A `network.http` rule names a `host` (a pattern, as in `hosts`); every
47//! other key narrows it and is optional: `methods` (any when left out),
48//! `schemes` or `scheme` (any of http, https, ws, wss), `port` (any),
49//! `paths` (exact) and `pathPrefixes` / `pathPrefix` / `path_prefixes`
50//! (whole segments: `/v1` covers `/v1` and `/v1/x`, not `/v10`). Without
51//! paths or prefixes a rule covers every path. Rules serialize in one form:
52//! `schemes` and `pathPrefixes`.
53
54use std::path::{Component, Path, PathBuf};
55
56use serde_json::{Map, Value};
57
58/// A host pattern: `*` (any host), `*.example.com` (its subdomains) or a
59/// host name.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct HostPattern(String);
62
63impl HostPattern {
64    /// Parses a pattern (lower-cased).
65    pub fn new(pattern: &str) -> Result<Self, String> {
66        let p = pattern.trim().to_ascii_lowercase();
67        let host = p.strip_prefix("*.").unwrap_or(&p);
68        let valid = p == "*"
69            || (!host.is_empty()
70                && host.chars().all(|c| {
71                    c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | ':' | '[' | ']')
72                }));
73        if valid {
74            Ok(Self(p))
75        } else {
76            Err(format!("invalid host pattern `{pattern}`"))
77        }
78    }
79
80    /// Whether `host` (lower case) matches.
81    pub fn matches(&self, host: &str) -> bool {
82        match self.0.strip_prefix("*.") {
83            _ if self.0 == "*" => true,
84            Some(suffix) => {
85                host.len() > suffix.len() + 1 && host.ends_with(suffix) && {
86                    let dot = host.len() - suffix.len() - 1;
87                    host.as_bytes()[dot] == b'.'
88                }
89            }
90            None => self.0 == host,
91        }
92    }
93
94    /// The pattern as written (lower case).
95    pub fn as_str(&self) -> &str {
96        &self.0
97    }
98}
99
100/// A finer HTTP grant: a host, narrowed by any of methods, schemes, a port,
101/// exact paths and path prefixes (each left empty: any).
102#[derive(Debug, Clone, PartialEq, Eq)]
103#[non_exhaustive]
104pub struct HttpGrant {
105    /// The host.
106    pub host: HostPattern,
107    /// Upper-case methods; empty: any.
108    pub methods: Vec<String>,
109    /// Lower-case schemes (`http`, `https`, `ws`, `wss`); empty: any of them.
110    pub schemes: Vec<String>,
111    /// The port, the scheme's default when the URL has none; `None`: any.
112    pub port: Option<u16>,
113    /// Exact paths (without the query).
114    pub paths: Vec<String>,
115    /// Path prefixes, matching whole segments (`/v1` covers `/v1/x`, not
116    /// `/v10`). With `paths`, a path matching either is covered; with
117    /// neither, every path is.
118    pub path_prefixes: Vec<String>,
119}
120
121impl Default for HttpGrant {
122    fn default() -> Self {
123        Self {
124            host: HostPattern(String::new()),
125            methods: Vec::new(),
126            schemes: Vec::new(),
127            port: None,
128            paths: Vec::new(),
129            path_prefixes: Vec::new(),
130        }
131    }
132}
133
134impl HttpGrant {
135    fn allows(&self, method: &str, url: &UrlParts<'_>) -> bool {
136        let default_port = match url.scheme.as_str() {
137            "https" | "wss" => 443,
138            _ => 80,
139        };
140        let path = url.path.split(['?', '#']).next().unwrap_or("/");
141        let path = if path.is_empty() { "/" } else { path };
142        self.host.matches(&url.host)
143            && (self.methods.is_empty()
144                || self.methods.iter().any(|m| m.eq_ignore_ascii_case(method)))
145            && (self.schemes.is_empty() || self.schemes.contains(&url.scheme))
146            && self
147                .port
148                .is_none_or(|p| url.port.unwrap_or(default_port) == p)
149            && ((self.paths.is_empty() && self.path_prefixes.is_empty())
150                || self.paths.iter().any(|allowed| allowed == path)
151                || self.path_prefixes.iter().any(|prefix| {
152                    path.strip_prefix(prefix.as_str()).is_some_and(|tail| {
153                        tail.is_empty() || prefix.ends_with('/') || tail.starts_with('/')
154                    })
155                }))
156    }
157}
158
159/// `capabilities.network`.
160#[derive(Debug, Clone, PartialEq, Eq, Default)]
161#[non_exhaustive]
162pub struct NetworkGrants {
163    /// Reachable with any method.
164    pub hosts: Vec<HostPattern>,
165    /// Finer grants.
166    pub http: Vec<HttpGrant>,
167    /// Raw TCP destinations (`net.connect`).
168    pub sockets: Vec<SocketGrant>,
169}
170
171/// One raw TCP destination: an exact host and port, written `host:port`
172/// (`[::1]:port` for IPv6). A socket bypasses every HTTP rule (methods,
173/// paths, schemes), so it is granted per port and never by a pattern.
174#[derive(Debug, Clone, PartialEq, Eq)]
175pub struct SocketGrant {
176    host: String,
177    port: u16,
178}
179
180impl SocketGrant {
181    /// Parses `host:port` (host lower-cased; port 1 to 65535).
182    pub fn new(grant: &str) -> Result<Self, String> {
183        let invalid = || {
184            format!(
185                "invalid socket grant `{grant}`: expected an exact `host:port` (`[::1]:port` for IPv6), without wildcards"
186            )
187        };
188        let (host, port) = grant.trim().rsplit_once(':').ok_or_else(invalid)?;
189        let port = port
190            .parse::<u16>()
191            .ok()
192            .filter(|p| *p != 0)
193            .ok_or_else(invalid)?;
194        let host = host.to_ascii_lowercase();
195        let host = match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
196            Some(v6)
197                if !v6.is_empty()
198                    && v6
199                        .chars()
200                        .all(|c| c.is_ascii_hexdigit() || matches!(c, ':' | '.')) =>
201            {
202                v6.to_owned()
203            }
204            Some(_) => return Err(invalid()),
205            None if !host.is_empty()
206                && host
207                    .chars()
208                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')) =>
209            {
210                host.trim_end_matches('.').to_owned()
211            }
212            None => return Err(invalid()),
213        };
214        Ok(Self { host, port })
215    }
216
217    /// The host (lower case, IPv6 without brackets).
218    pub fn host(&self) -> &str {
219        &self.host
220    }
221
222    /// The port.
223    pub fn port(&self) -> u16 {
224        self.port
225    }
226
227    /// The `host:port` form [`Self::new`] reads.
228    pub fn to_string_form(&self) -> String {
229        if self.host.contains(':') {
230            format!("[{}]:{}", self.host, self.port)
231        } else {
232            format!("{}:{}", self.host, self.port)
233        }
234    }
235}
236
237/// Commands an app may execute. Names are exact, without shell expansion.
238#[derive(Debug, Clone, PartialEq, Eq, Default)]
239#[non_exhaustive]
240pub struct ProcessGrants {
241    /// Exact executable names or absolute executable paths.
242    pub execute: Vec<String>,
243    /// The app may ask its host to handle an exit request.
244    pub exit: bool,
245    /// Additional environment variable names visible to the app.
246    pub env: Vec<String>,
247}
248
249/// Filesystem roots an app may read or write. `${dataDir}` is resolved by
250/// the host to this app's own data directory, never to a JS supplied root.
251#[derive(Debug, Clone, PartialEq, Eq, Default)]
252#[non_exhaustive]
253pub struct FileGrants {
254    /// Roots available for read operations.
255    pub read: Vec<String>,
256    /// Roots available for mutation operations.
257    pub write: Vec<String>,
258}
259
260/// Host-selected anchors for manifest paths. Apps cannot supply these roots.
261#[derive(Debug, Clone, PartialEq, Eq, Default)]
262#[non_exhaustive]
263pub struct TrustedPaths {
264    /// The application source/package directory.
265    pub plugin_dir: Option<PathBuf>,
266    /// The native user's home directory, when known.
267    pub home_dir: Option<PathBuf>,
268}
269impl TrustedPaths {
270    /// Expand one manifest root against host anchors. Relative roots are
271    /// anchored to the application directory. Unknown anchors never grant access.
272    pub fn resolve_root(&self, root: &str, data_dir: &Path) -> Result<PathBuf, String> {
273        validate_path_pattern(root)?;
274        for (placeholder, anchor) in [
275            ("${dataDir}", Some(data_dir)),
276            ("${pluginDir}", self.plugin_dir.as_deref()),
277            ("${homeDir}", self.home_dir.as_deref()),
278        ] {
279            if let Some(tail) = root.strip_prefix(placeholder) {
280                let anchor = anchor
281                    .filter(|p| absolute(p))
282                    .ok_or_else(|| format!("host anchor {placeholder} unavailable"))?;
283                // Component by component: `/` separates nothing in a
284                // verbatim Windows anchor.
285                let tail: PathBuf = tail.split('/').filter(|part| !part.is_empty()).collect();
286                return within(anchor, &tail, root);
287            }
288        }
289        let path = PathBuf::from(root);
290        if absolute(&path) {
291            Ok(path)
292        } else {
293            let anchor = self
294                .plugin_dir
295                .as_deref()
296                .filter(|p| absolute(p))
297                .ok_or_else(|| {
298                    "host application directory unavailable for relative filesystem root".to_owned()
299                })?;
300            within(anchor, &path, root)
301        }
302    }
303}
304
305/// Virtual browser paths use Unix roots. `Path::is_absolute` on
306/// wasm32-unknown-unknown always returns false because it has no OS prefix.
307pub(crate) fn absolute(path: &Path) -> bool {
308    if cfg!(target_arch = "wasm32") {
309        path.has_root()
310    } else {
311        path.is_absolute()
312    }
313}
314
315/// `tail` joined to `anchor`, when it stays there: names only. On Windows
316/// a drive (`C:/Windows`), a share (`\\srv\share`) or a rooted path
317/// (`\Users`) would replace or leave the anchor in `join`.
318fn within(anchor: &Path, tail: &Path, root: &str) -> Result<PathBuf, String> {
319    use std::path::Component;
320    let names = tail
321        .components()
322        .all(|c| matches!(c, Component::Normal(_) | Component::CurDir));
323    let mut path = anchor.to_path_buf();
324    path.extend(tail.components().filter(|c| *c != Component::CurDir));
325    if names && path.starts_with(anchor) {
326        Ok(path)
327    } else {
328        Err(format!("filesystem root `{root}` leaves its anchor"))
329    }
330}
331
332/// Whether environment names `a` and `b` are one variable: ignoring ASCII
333/// case on Windows, whose environment does; exactly elsewhere (`lang` is
334/// not `LANG` on Unix).
335pub(crate) fn env_names_match(a: &str, b: &str) -> bool {
336    if cfg!(windows) {
337        a.eq_ignore_ascii_case(b)
338    } else {
339        a == b
340    }
341}
342
343/// What an app may do (one declaration, or one grant).
344/// Start with [`Self::default`] and set the fields to grant; new capabilities
345/// default to denied.
346#[derive(Debug, Clone, PartialEq, Eq, Default)]
347#[non_exhaustive]
348pub struct Capabilities {
349    /// Explicit native subprocess grants.
350    pub process: ProcessGrants,
351    /// Explicit native filesystem grants.
352    pub fs: FileGrants,
353    /// `fetch`, remote images and video.
354    pub network: NetworkGrants,
355    /// The hosts web views may show; `None`: no web views.
356    pub webview: Option<Vec<HostPattern>>,
357    /// The app may set the status bar.
358    pub status_bar: bool,
359    /// The app may read and write the system clipboard (`nsh/clipboard`).
360    pub clipboard: bool,
361    /// The app may show the system's picker (`nsh/picker`): the files the
362    /// user picks in it reach the app.
363    pub picker: bool,
364    /// The functions of the embedding app `nsh/host` may call: names, or
365    /// prefixes ending in `*` (`"*"`: all); empty: none, also for apps
366    /// without a declaration ([`Capabilities::all`]).
367    pub host: Vec<String>,
368    /// The URLs the app may open outside it (`openUrl` of `nsh/device`);
369    /// `None`: none.
370    pub open_url: Option<OpenUrlGrant>,
371}
372
373/// Which URLs an app may open outside it (`capabilities.openUrl`).
374#[derive(Debug, Clone, PartialEq, Eq, Default)]
375#[non_exhaustive]
376pub struct OpenUrlGrant {
377    /// The schemes it may open, lower case (`https`, `mailto`, `tel`);
378    /// empty: every scheme (`"openUrl": true`).
379    pub schemes: Vec<String>,
380}
381
382impl OpenUrlGrant {
383    /// Whether it grants URLs of `scheme` (lower case).
384    pub fn allows(&self, scheme: &str) -> bool {
385        self.schemes.is_empty() || self.schemes.iter().any(|s| s == scheme)
386    }
387}
388
389/// The parts of a URL the checks look at.
390#[derive(Debug, Clone, PartialEq, Eq)]
391pub struct UrlParts<'a> {
392    /// Lower-case scheme.
393    pub scheme: String,
394    /// Lower-case host (without port or user info).
395    pub host: String,
396    /// The path (and query), `/` when empty.
397    pub path: &'a str,
398    /// Explicit URL port.
399    pub port: Option<u16>,
400}
401
402/// Splits an absolute URL into scheme, host and path; `None` when it has no
403/// `scheme://host`.
404pub fn parse_url(url: &str) -> Option<UrlParts<'_>> {
405    let (scheme, rest) = url.split_once("://")?;
406    if scheme.is_empty()
407        || !scheme
408            .chars()
409            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
410    {
411        return None;
412    }
413    let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
414    let (authority, path) = rest.split_at(end);
415    // User info ends at the last `@`: `https://good.com@evil.com/` is evil.com.
416    let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
417    let host = if let Some(v6) = host_port.strip_prefix('[') {
418        format!("[{}]", v6.split_once(']')?.0)
419    } else {
420        host_port.split(':').next().unwrap_or_default().to_owned()
421    };
422    if host.is_empty() {
423        return None;
424    }
425    let port = if host_port.starts_with('[') {
426        host_port
427            .split_once(']')
428            .and_then(|(_, rest)| rest.strip_prefix(':'))
429            .map(str::parse::<u16>)
430            .transpose()
431            .ok()?
432    } else {
433        host_port
434            .split_once(':')
435            .map(|(_, port)| port.parse::<u16>())
436            .transpose()
437            .ok()?
438    };
439    Some(UrlParts {
440        scheme: scheme.to_ascii_lowercase(),
441        host: host.to_ascii_lowercase().trim_end_matches('.').to_owned(),
442        path: if path.is_empty() { "/" } else { path },
443        port,
444    })
445}
446
447impl Capabilities {
448    /// Legacy unrestricted APIs for apps without a declaration. Socket,
449    /// process, filesystem and host function grants stay empty and always
450    /// require explicit opt-in.
451    pub fn all() -> Self {
452        let any = vec![HostPattern("*".into())];
453        Self {
454            network: NetworkGrants {
455                hosts: any.clone(),
456                http: Vec::new(),
457                sockets: Vec::new(),
458            },
459            webview: Some(any),
460            status_bar: true,
461            clipboard: true,
462            picker: true,
463            open_url: Some(OpenUrlGrant::default()),
464            // The host's functions are never granted without a declaration.
465            ..Self::default()
466        }
467    }
468
469    /// Parses `capabilities` from `nsh.json` (or a grant in the same form).
470    /// Unknown keys are errors: a typo is caught when the app is built.
471    pub fn from_json(value: &Value) -> Result<Self, String> {
472        Self::parse(value, None)
473    }
474
475    /// Parses the capabilities a signed package declares, which a newer
476    /// signer may have written: unknown keys never grant anything. An
477    /// unknown capability is not granted; an unknown key inside one (a
478    /// restriction this runtime cannot apply) drops what it is in, the
479    /// whole capability or the `http` grant. Returns what was dropped
480    /// (`capabilities.bluetooth`, ...) with the capabilities.
481    pub fn from_json_lenient(value: &Value) -> Result<(Self, Vec<String>), String> {
482        let mut dropped = Vec::new();
483        let caps = Self::parse(value, Some(&mut dropped))?;
484        Ok((caps, dropped))
485    }
486
487    /// `dropped`: lenient, recording what unknown keys dropped; `None`:
488    /// strict.
489    fn parse(value: &Value, mut dropped: Option<&mut Vec<String>>) -> Result<Self, String> {
490        const KNOWN: [&str; 9] = [
491            "network",
492            "webview",
493            "statusBar",
494            "clipboard",
495            "picker",
496            "openUrl",
497            "process",
498            "fs",
499            "host",
500        ];
501        let obj = object(value, "capabilities")?;
502        for key in obj.keys().filter(|k| !KNOWN.contains(&k.as_str())) {
503            match dropped.as_deref_mut() {
504                // A capability of a newer runtime: not granted.
505                Some(dropped) => dropped.push(format!("capabilities.{key}")),
506                None => return Err(unknown_key("capabilities", key, &KNOWN)),
507            }
508        }
509        // Whether `obj` (`what`) has only `keys`; lenient, an unknown key
510        // drops `name` (what it is in): recorded, and `false` returned.
511        let mut check = |obj: &Map<String, Value>,
512                         what: &str,
513                         keys: &[&str],
514                         name: &str|
515         -> Result<bool, String> {
516            let Some(key) = obj.keys().find(|k| !keys.contains(&k.as_str())) else {
517                return Ok(true);
518            };
519            match dropped.as_deref_mut() {
520                Some(dropped) => {
521                    dropped.push(format!("{name} (unknown key `{key}`)"));
522                    Ok(false)
523                }
524                None => Err(unknown_key(what, key, keys)),
525            }
526        };
527        let mut caps = Capabilities::default();
528        if let Some(network) = obj.get("network") {
529            let network = object(network, "capabilities.network")?;
530            if check(
531                network,
532                "capabilities.network",
533                &["hosts", "http", "sockets"],
534                "capabilities.network",
535            )? {
536                if let Some(hosts) = network.get("hosts") {
537                    caps.network.hosts = patterns(hosts, "capabilities.network.hosts")?;
538                }
539                if let Some(sockets) = network.get("sockets") {
540                    caps.network.sockets = strings(sockets, "capabilities.network.sockets")?
541                        .iter()
542                        .map(|s| SocketGrant::new(s))
543                        .collect::<Result<_, _>>()?;
544                }
545                if let Some(http) = network.get("http") {
546                    let list = http
547                        .as_array()
548                        .ok_or("capabilities.network.http must be an array")?;
549                    for (i, grant) in list.iter().enumerate() {
550                        let g = object(grant, "capabilities.network.http[]")?;
551                        if check(
552                            g,
553                            "capabilities.network.http[]",
554                            &[
555                                "host",
556                                "methods",
557                                "scheme",
558                                "schemes",
559                                "port",
560                                "paths",
561                                "pathPrefix",
562                                "pathPrefixes",
563                                "path_prefixes",
564                            ],
565                            &format!("capabilities.network.http[{i}]"),
566                        )? {
567                            caps.network.http.push(http_grant(g)?);
568                        }
569                    }
570                }
571            }
572        }
573        if let Some(webview) = obj.get("webview") {
574            let webview = object(webview, "capabilities.webview")?;
575            if check(
576                webview,
577                "capabilities.webview",
578                &["hosts"],
579                "capabilities.webview",
580            )? {
581                caps.webview = Some(match webview.get("hosts") {
582                    Some(hosts) => patterns(hosts, "capabilities.webview.hosts")?,
583                    None => Vec::new(),
584                });
585            }
586        }
587        if let Some(status_bar) = obj.get("statusBar") {
588            caps.status_bar = status_bar
589                .as_bool()
590                .ok_or("capabilities.statusBar must be a boolean")?;
591        }
592        if let Some(clipboard) = obj.get("clipboard") {
593            caps.clipboard = clipboard
594                .as_bool()
595                .ok_or("capabilities.clipboard must be a boolean")?;
596        }
597        if let Some(picker) = obj.get("picker") {
598            caps.picker = picker
599                .as_bool()
600                .ok_or("capabilities.picker must be a boolean")?;
601        }
602        if let Some(open_url) = obj.get("openUrl") {
603            match open_url {
604                Value::Bool(granted) => {
605                    caps.open_url = granted.then(OpenUrlGrant::default);
606                }
607                Value::Object(grant) => {
608                    if check(
609                        grant,
610                        "capabilities.openUrl",
611                        &["schemes"],
612                        "capabilities.openUrl",
613                    )? {
614                        let schemes = match grant.get("schemes") {
615                            Some(schemes) => strings(schemes, "capabilities.openUrl.schemes")?,
616                            None => Vec::new(),
617                        };
618                        if schemes.iter().any(|s| {
619                            s.is_empty()
620                                || !s.starts_with(|c: char| c.is_ascii_alphabetic())
621                                || !s
622                                    .chars()
623                                    .all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c))
624                        }) {
625                            return Err(
626                                "capabilities.openUrl.schemes needs URL schemes (`https`, `mailto`)"
627                                    .into(),
628                            );
629                        }
630                        caps.open_url = Some(OpenUrlGrant {
631                            schemes: schemes.iter().map(|s| s.to_ascii_lowercase()).collect(),
632                        });
633                    }
634                }
635                _ => {
636                    return Err(
637                        "capabilities.openUrl must be a boolean or an object of `schemes`".into(),
638                    );
639                }
640            }
641        }
642        if let Some(process) = obj.get("process") {
643            let process = object(process, "capabilities.process")?;
644            if check(
645                process,
646                "capabilities.process",
647                &["execute", "exit", "env"],
648                "capabilities.process",
649            )? {
650                if let Some(execute) = process.get("execute") {
651                    caps.process.execute = strings(execute, "capabilities.process.execute")?;
652                    if caps.process.execute.iter().any(|s| !valid_command(s)) {
653                        return Err("capabilities.process.execute needs exact executable names or absolute paths".into());
654                    }
655                }
656                if let Some(exit) = process.get("exit") {
657                    caps.process.exit = exit
658                        .as_bool()
659                        .ok_or("capabilities.process.exit must be a boolean")?;
660                }
661                if let Some(env) = process.get("env") {
662                    caps.process.env = strings(env, "capabilities.process.env")?;
663                    if caps
664                        .process
665                        .env
666                        .iter()
667                        .any(|name| name.is_empty() || name.contains(['=', '\0']))
668                    {
669                        return Err(
670                            "capabilities.process.env needs nonempty environment variable names"
671                                .into(),
672                        );
673                    }
674                }
675            }
676        }
677        if let Some(fs) = obj.get("fs") {
678            let fs = object(fs, "capabilities.fs")?;
679            if check(fs, "capabilities.fs", &["read", "write"], "capabilities.fs")? {
680                for (key, target) in [("read", &mut caps.fs.read), ("write", &mut caps.fs.write)] {
681                    if let Some(value) = fs.get(key) {
682                        *target = strings(value, &format!("capabilities.fs.{key}"))?;
683                        for root in target.iter() {
684                            validate_path_pattern(root)?;
685                        }
686                    }
687                }
688            }
689        }
690        if let Some(host) = obj.get("host") {
691            caps.host = match host {
692                Value::Bool(all) => {
693                    if *all {
694                        vec!["*".into()]
695                    } else {
696                        Vec::new()
697                    }
698                }
699                _ => {
700                    let names = strings(host, "capabilities.host")
701                        .map_err(|e| format!("{e} (or a boolean)"))?;
702                    if let Some(bad) = names.iter().find(|n| match n.strip_suffix('*') {
703                        Some(prefix) => !prefix.is_empty() && !valid_host_name(prefix),
704                        None => !valid_host_name(n),
705                    }) {
706                        return Err(format!(
707                            "capabilities.host: invalid function `{bad}` (a name of {HOST_NAME_CHARS}, or a prefix of them ending in `*`)"
708                        ));
709                    }
710                    names
711                }
712            };
713        }
714        Ok(caps)
715    }
716
717    /// The JSON form [`Capabilities::from_json`] reads.
718    pub fn to_json(&self) -> Value {
719        let list =
720            |l: &[HostPattern]| Value::from(l.iter().map(|p| p.0.clone()).collect::<Vec<_>>());
721        let mut network = Map::new();
722        network.insert("hosts".into(), list(&self.network.hosts));
723        let http: Vec<Value> = self
724            .network
725            .http
726            .iter()
727            .map(|g| {
728                let mut o = Map::new();
729                o.insert("host".into(), g.host.0.clone().into());
730                if !g.methods.is_empty() {
731                    o.insert("methods".into(), g.methods.clone().into());
732                }
733                if !g.schemes.is_empty() {
734                    o.insert("schemes".into(), g.schemes.clone().into());
735                }
736                if let Some(port) = g.port {
737                    o.insert("port".into(), port.into());
738                }
739                if !g.paths.is_empty() {
740                    o.insert("paths".into(), g.paths.clone().into());
741                }
742                if !g.path_prefixes.is_empty() {
743                    o.insert("pathPrefixes".into(), g.path_prefixes.clone().into());
744                }
745                Value::Object(o)
746            })
747            .collect();
748        network.insert("http".into(), http.into());
749        if !self.network.sockets.is_empty() {
750            let sockets: Vec<String> = self
751                .network
752                .sockets
753                .iter()
754                .map(SocketGrant::to_string_form)
755                .collect();
756            network.insert("sockets".into(), sockets.into());
757        }
758        let mut obj = Map::new();
759        obj.insert("network".into(), Value::Object(network));
760        obj.insert(
761            "process".into(),
762            serde_json::json!({"execute": self.process.execute, "exit": self.process.exit, "env": self.process.env}),
763        );
764        obj.insert(
765            "fs".into(),
766            serde_json::json!({"read": self.fs.read, "write": self.fs.write}),
767        );
768        if let Some(hosts) = &self.webview {
769            let mut w = Map::new();
770            w.insert("hosts".into(), list(hosts));
771            obj.insert("webview".into(), Value::Object(w));
772        }
773        obj.insert("statusBar".into(), self.status_bar.into());
774        obj.insert("clipboard".into(), self.clipboard.into());
775        obj.insert("picker".into(), self.picker.into());
776        // Only when granted: older runtimes read what newer signers write.
777        if !self.host.is_empty() {
778            obj.insert("host".into(), self.host.clone().into());
779        }
780        obj.insert(
781            "openUrl".into(),
782            match &self.open_url {
783                None => false.into(),
784                Some(grant) if grant.schemes.is_empty() => true.into(),
785                Some(grant) => serde_json::json!({ "schemes": grant.schemes }),
786            },
787        );
788        Value::Object(obj)
789    }
790
791    fn allows_http(&self, method: &str, url: &UrlParts<'_>) -> bool {
792        if !matches!(url.scheme.as_str(), "http" | "https" | "ws" | "wss") {
793            return false;
794        }
795        self.network.hosts.iter().any(|h| h.matches(&url.host))
796            || self.network.http.iter().any(|g| g.allows(method, url))
797    }
798
799    fn allows_host(&self, name: &str) -> bool {
800        self.host.iter().any(|g| match g.strip_suffix('*') {
801            Some(prefix) => name.starts_with(prefix),
802            None => g == name,
803        })
804    }
805
806    fn allows_webview(&self, url: &UrlParts<'_>) -> bool {
807        matches!(url.scheme.as_str(), "http" | "https")
808            && self
809                .webview
810                .as_ref()
811                .is_some_and(|hosts| hosts.iter().any(|h| h.matches(&url.host)))
812    }
813}
814
815/// What host function names (`nsh/host`) are made of, for messages.
816pub const HOST_NAME_CHARS: &str = "1 to 128 of A-Z a-z 0-9 _ . : -, without `..`";
817
818/// Whether `name` may name a function of the embedding host: 1 to 128 of
819/// `[A-Za-z0-9_.:-]`, without `..`. Hosts may put a name in a path or a URL,
820/// so no name escapes the prefix a grant gives it.
821pub fn valid_host_name(name: &str) -> bool {
822    (1..=128).contains(&name.len())
823        && name
824            .bytes()
825            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b':' | b'-'))
826        && !name.contains("..")
827}
828
829fn valid_command(command: &str) -> bool {
830    !command.is_empty()
831        && !command.contains(['\0', '*'])
832        && (Path::new(command).is_absolute()
833            // A bare name has no drive (`C:git` is relative to the host's
834            // directory on drive C).
835            || (!command.contains(['/', '\\', ':']) && command != "." && command != ".."))
836}
837
838fn validate_path_pattern(path: &str) -> Result<(), String> {
839    if [
840        "$HOME",
841        "${HOME}",
842        "$USERPROFILE",
843        "${USERPROFILE}",
844        "%USERPROFILE%",
845        "~",
846    ]
847    .into_iter()
848    .any(|prefix| {
849        path.strip_prefix(prefix)
850            .is_some_and(|tail| tail.is_empty() || tail.starts_with(['/', '\\']))
851    }) {
852        return Err("use ${homeDir} for the native home directory".into());
853    }
854    let placeholder = ["${dataDir}", "${pluginDir}", "${homeDir}"]
855        .into_iter()
856        .find(|prefix| path.starts_with(prefix));
857    let tail = placeholder.and_then(|prefix| path.strip_prefix(prefix));
858    if path.is_empty()
859        || path.contains(['\0', '*'])
860        || tail.is_some_and(|s| !s.is_empty() && !s.starts_with('/'))
861        || (placeholder.is_none() && path.contains("${"))
862        || tail.is_some_and(|s| s.contains("${"))
863        || Path::new(path)
864            .components()
865            .any(|p| matches!(p, Component::ParentDir))
866    {
867        return Err(
868            "filesystem roots must use valid host placeholders and contain no traversal".into(),
869        );
870    }
871    Ok(())
872}
873
874/// `path` resolved as [`std::fs::canonicalize`] resolves it, in the plain
875/// form where Windows has one: canonicalizing there gives verbatim paths
876/// (`\\?\C:\app`), which no path a host or app writes starts with, and
877/// in which `/` separates nothing. Grants, requests and trusted anchors
878/// are all compared in this form.
879pub fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
880    let path = std::fs::canonicalize(path)?;
881    #[cfg(windows)]
882    if let Some(plain) = path.to_str().and_then(without_verbatim_prefix) {
883        return Ok(PathBuf::from(plain));
884    }
885    Ok(path)
886}
887
888/// The plain form of the Windows verbatim path `path` (`\\?\C:\a` →
889/// `C:\a`, `\\?\UNC\server\share\a` → `\\server\share\a`), when it
890/// names the same file: under the legacy length limit, and no component
891/// that the plain form would read otherwise (empty, `.` or `..`, holding
892/// `/`, ending in a dot or space, or a device name such as `NUL` or
893/// `com1.txt`). `None` for any other path, which then stays as it is.
894/// Text only, so its tests run on every platform.
895#[cfg_attr(not(windows), allow(dead_code))]
896fn without_verbatim_prefix(path: &str) -> Option<String> {
897    let rest = path.strip_prefix(r"\\?\")?;
898    let (plain, tail) = if let Some(unc) = rest.strip_prefix(r"UNC\") {
899        (format!(r"\\{unc}"), unc)
900    } else {
901        let bytes = rest.as_bytes();
902        if bytes.len() < 3 || !bytes[0].is_ascii_alphabetic() || &bytes[1..3] != b":\\" {
903            return None;
904        }
905        (rest.to_owned(), &rest[3..])
906    };
907    if plain.len() >= 260 {
908        return None;
909    }
910    // A trailing separator ends a root (`C:\`) or a directory.
911    let tail = tail.strip_suffix('\\').unwrap_or(tail);
912    let device = |name: &str| {
913        let stem = name.split('.').next().unwrap_or(name).trim_end();
914        ["CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"]
915            .iter()
916            .any(|d| stem.eq_ignore_ascii_case(d))
917            || (stem.len() == 4
918                && ["COM", "LPT"]
919                    .iter()
920                    .any(|d| stem[..3].eq_ignore_ascii_case(d))
921                && matches!(stem.as_bytes()[3], b'1'..=b'9'))
922    };
923    let plain_component = |c: &str| {
924        !c.is_empty()
925            && c != "."
926            && c != ".."
927            && !c.contains('/')
928            && !c.ends_with(['.', ' '])
929            && !device(c)
930    };
931    (tail.is_empty() || tail.split('\\').all(plain_component)).then_some(plain)
932}
933
934// Resolve every existing ancestor, including symlinks. Missing tails are
935// permitted so creation receives the same boundary checks as reads.
936fn resolved_path(path: &Path) -> Result<PathBuf, String> {
937    if !path.is_absolute() || path.components().any(|p| matches!(p, Component::ParentDir)) {
938        return Err("filesystem paths must be absolute and contain no parent traversal".into());
939    }
940    let mut cursor = path;
941    let mut tail = Vec::new();
942    loop {
943        match std::fs::symlink_metadata(cursor) {
944            Ok(_) => {
945                let mut resolved = canonicalize(cursor).map_err(|e| e.to_string())?;
946                for part in tail.into_iter().rev() {
947                    resolved.push(part);
948                }
949                return Ok(resolved);
950            }
951            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
952                tail.push(
953                    cursor
954                        .file_name()
955                        .ok_or("invalid filesystem path")?
956                        .to_owned(),
957                );
958                cursor = cursor.parent().ok_or("invalid filesystem path")?;
959            }
960            Err(e) => return Err(e.to_string()),
961        }
962    }
963}
964
965fn object<'a>(value: &'a Value, what: &str) -> Result<&'a Map<String, Value>, String> {
966    value
967        .as_object()
968        .ok_or_else(|| format!("{what} must be an object"))
969}
970
971fn unknown_key(what: &str, key: &str, known: &[&str]) -> String {
972    format!("{what}: unknown key `{key}` (known: {})", known.join(", "))
973}
974
975fn strings(value: &Value, what: &str) -> Result<Vec<String>, String> {
976    value
977        .as_array()
978        .and_then(|a| a.iter().map(|v| v.as_str().map(str::to_owned)).collect())
979        .ok_or_else(|| format!("{what} must be an array of strings"))
980}
981
982/// One `network.http` rule: `host`, and any of `methods`, `scheme` /
983/// `schemes`, `port`, `paths` and `pathPrefix` / `pathPrefixes` /
984/// `path_prefixes` (the spellings of one key are merged).
985fn http_grant(g: &Map<String, Value>) -> Result<HttpGrant, String> {
986    let what = "capabilities.network.http[]";
987    let host = g
988        .get("host")
989        .and_then(Value::as_str)
990        .ok_or_else(|| format!("{what} needs a `host`"))?;
991    // A key as a string or an array of strings.
992    let list = |key: &str| -> Result<Vec<String>, String> {
993        match g.get(key) {
994            None => Ok(Vec::new()),
995            Some(Value::String(s)) => Ok(vec![s.clone()]),
996            Some(v) => strings(v, &format!("{what}.{key}")),
997        }
998    };
999    let methods = list("methods")?
1000        .into_iter()
1001        .map(|m| {
1002            if !m.is_empty() && m.bytes().all(|b| b.is_ascii_alphabetic() || b == b'-') {
1003                Ok(m.to_ascii_uppercase())
1004            } else {
1005                Err(format!("{what}.methods: `{m}` is not an HTTP method"))
1006            }
1007        })
1008        .collect::<Result<Vec<_>, _>>()?;
1009    let mut schemes = Vec::new();
1010    for scheme in list("scheme")?.into_iter().chain(list("schemes")?) {
1011        let scheme = scheme.to_ascii_lowercase();
1012        if !matches!(scheme.as_str(), "http" | "https" | "ws" | "wss") {
1013            return Err(format!(
1014                "{what}.schemes: `{scheme}` is not http, https, ws or wss"
1015            ));
1016        }
1017        if !schemes.contains(&scheme) {
1018            schemes.push(scheme);
1019        }
1020    }
1021    let port = match g.get("port") {
1022        None => None,
1023        Some(v) => Some(
1024            v.as_u64()
1025                .and_then(|p| u16::try_from(p).ok())
1026                .filter(|&p| p != 0)
1027                .ok_or_else(|| format!("{what}.port must be a port from 1 to 65535"))?,
1028        ),
1029    };
1030    let paths = list("paths")?;
1031    let mut path_prefixes = Vec::new();
1032    for prefix in list("pathPrefix")?
1033        .into_iter()
1034        .chain(list("pathPrefixes")?)
1035        .chain(list("path_prefixes")?)
1036    {
1037        if !path_prefixes.contains(&prefix) {
1038            path_prefixes.push(prefix);
1039        }
1040    }
1041    // A path is matched as written: a pattern in it would match nothing.
1042    if let Some(bad) = paths
1043        .iter()
1044        .chain(&path_prefixes)
1045        .find(|p| !p.starts_with('/') || p.contains(['*', '?', '#']))
1046    {
1047        return Err(format!(
1048            "{what}: path `{bad}` must start with / and has no `*`, `?` or `#` (paths match as written)"
1049        ));
1050    }
1051    Ok(HttpGrant {
1052        host: HostPattern::new(host)?,
1053        methods,
1054        schemes,
1055        port,
1056        paths,
1057        path_prefixes,
1058    })
1059}
1060
1061fn patterns(value: &Value, what: &str) -> Result<Vec<HostPattern>, String> {
1062    strings(value, what)?
1063        .iter()
1064        .map(|p| HostPattern::new(p))
1065        .collect()
1066}
1067
1068/// What an app may do: its declaration and the embedder's grant (when the
1069/// embedder limits it); an action must be allowed by both.
1070#[derive(Debug, Clone, PartialEq, Eq)]
1071pub struct Access {
1072    /// What the app declared (everything without a declaration).
1073    pub declared: Capabilities,
1074    /// What the embedding app grants it at most (`None`: what it declared).
1075    pub granted: Option<Capabilities>,
1076}
1077
1078impl Default for Access {
1079    fn default() -> Self {
1080        Self::all()
1081    }
1082}
1083
1084impl Access {
1085    /// Everything allowed.
1086    pub fn all() -> Self {
1087        Self {
1088            declared: Capabilities::all(),
1089            granted: None,
1090        }
1091    }
1092
1093    fn each(&self, f: impl Fn(&Capabilities) -> bool) -> bool {
1094        f(&self.declared) && self.granted.as_ref().is_none_or(f)
1095    }
1096
1097    /// True when nothing is restricted (no check needed, redirects may be
1098    /// followed by the platform).
1099    pub fn is_unrestricted(&self) -> bool {
1100        let all = Capabilities::all();
1101        self.declared == all && self.granted.as_ref().is_none_or(|g| *g == all)
1102    }
1103
1104    /// Whether an exact command is declared and granted. These capabilities
1105    /// always require explicit opt-in, including for legacy standalone apps.
1106    pub fn allows_process(&self, command: &str) -> bool {
1107        valid_command(command) && self.each(|c| c.process.execute.iter().any(|p| p == command))
1108    }
1109
1110    /// Whether the app may request an exit from its host. This never exits the
1111    /// embedding process by itself; the host supplies the meaning of the request.
1112    pub fn allows_exit(&self) -> bool {
1113        self.each(|caps| caps.process.exit)
1114    }
1115
1116    /// Whether an environment variable is visible. The built-in metadata names
1117    /// are always visible; other names require both app and host permission.
1118    pub fn allows_env(&self, name: &str) -> bool {
1119        let defaults = include_str!("default-env").lines().filter_map(|line| {
1120            let name = line.split('#').next().unwrap_or_default().trim();
1121            (!name.is_empty()).then_some(name)
1122        });
1123        defaults
1124            .into_iter()
1125            .any(|allowed| env_names_match(allowed, name))
1126            || self.each(|caps| {
1127                caps.process
1128                    .env
1129                    .iter()
1130                    .any(|allowed| env_names_match(allowed, name))
1131            })
1132    }
1133
1134    /// Resolve a filesystem path within both the declaration and host grant.
1135    /// `data_dir` is an app-specific directory supplied only by the host.
1136    pub fn authorize_file(
1137        &self,
1138        path: &Path,
1139        data_dir: &Path,
1140        write: bool,
1141    ) -> Result<PathBuf, String> {
1142        self.authorize_file_with_paths(path, data_dir, &TrustedPaths::default(), write)
1143    }
1144
1145    /// Authorize a file with trusted host source and home directory anchors.
1146    pub fn authorize_file_with_paths(
1147        &self,
1148        path: &Path,
1149        data_dir: &Path,
1150        paths: &TrustedPaths,
1151        write: bool,
1152    ) -> Result<PathBuf, String> {
1153        let requested = if let Some(text) = path.to_str().filter(|s| s.starts_with("${")) {
1154            paths.resolve_root(text, data_dir)?
1155        } else {
1156            path.to_owned()
1157        };
1158        let resolved = resolved_path(&requested)?;
1159        let allowed = self.each(|c| {
1160            let roots = if write { &c.fs.write } else { &c.fs.read };
1161            roots.iter().any(|root| {
1162                paths
1163                    .resolve_root(root, data_dir)
1164                    .and_then(|r| resolved_path(&r))
1165                    .is_ok_and(|root| resolved.starts_with(root))
1166            })
1167        });
1168        if allowed {
1169            Ok(resolved)
1170        } else {
1171            Err(format!(
1172                "filesystem {} is not granted by capabilities.fs",
1173                if write { "write" } else { "read" }
1174            ))
1175        }
1176    }
1177
1178    /// Whether a raw TCP connection to `host:port` may be opened: only an
1179    /// exact `network.sockets` grant allows it, never `hosts` or `http`
1180    /// grants, and [`Capabilities::all`] grants none.
1181    pub fn allows_socket(&self, host: &str, port: u16) -> bool {
1182        if host.is_empty() || host.contains(['/', '@', '?', '#', '\0']) {
1183            return false;
1184        }
1185        let host = host.to_ascii_lowercase();
1186        let host = host
1187            .strip_prefix('[')
1188            .and_then(|h| h.strip_suffix(']'))
1189            .unwrap_or(&host)
1190            .trim_end_matches('.');
1191        self.each(|c| {
1192            c.network
1193                .sockets
1194                .iter()
1195                .any(|grant| grant.port == port && grant.host == host)
1196        })
1197    }
1198
1199    /// Whether a WebSocket to `url` (`ws:` / `wss:`) may connect. The
1200    /// handshake is an HTTP GET, so it is checked as a GET of the same URL
1201    /// over `http:` / `https:`; legacy rules may also list `ws` / `wss`.
1202    pub fn allows_websocket(&self, url: &str) -> bool {
1203        let http = if let Some(rest) = url.strip_prefix("wss:") {
1204            format!("https:{rest}")
1205        } else if let Some(rest) = url.strip_prefix("ws:") {
1206            format!("http:{rest}")
1207        } else {
1208            return false;
1209        };
1210        self.allows_http("GET", &http) || self.allows_http("GET", url)
1211    }
1212
1213    /// Whether `fetch(url, { method })` may go out. `asset:` URIs are always
1214    /// allowed.
1215    pub fn allows_http(&self, method: &str, url: &str) -> bool {
1216        if url.starts_with("asset:") {
1217            return true;
1218        }
1219        let Some(parts) = parse_url(url) else {
1220            return false;
1221        };
1222        self.each(|c| c.allows_http(method, &parts))
1223    }
1224
1225    /// Whether a media URL (image, video, canvas image) may be loaded.
1226    /// Relative and `asset:` URIs are the app's own files; `data:` URIs and
1227    /// `blob:` URLs (`URL.createObjectURL`) are bytes the app already has.
1228    pub fn allows_media(&self, uri: &str) -> bool {
1229        if !uri.contains("://")
1230            || uri.starts_with("asset:")
1231            || uri.starts_with("data:")
1232            || uri.starts_with("blob:")
1233        {
1234            return true;
1235        }
1236        self.allows_http("GET", uri)
1237    }
1238
1239    /// The next URL of a media load that was redirected from `base` to
1240    /// `location`, if the app may load it: the redirect must stay on
1241    /// `http(s)` and pass the same check as a first request, so loaders
1242    /// follow redirects themselves, one hop at a time, and never contact
1243    /// a target the app is not granted.
1244    pub fn media_redirect(&self, base: &str, location: &str) -> Result<String, String> {
1245        let url = resolve_reference(base, location);
1246        if !(url.starts_with("http://") || url.starts_with("https://")) {
1247            return Err(format!("redirect to `{url}` is not an http(s) URL"));
1248        }
1249        if !self.is_unrestricted() && !self.allows_media(&url) {
1250            return Err(format!(
1251                "redirect to `{url}` is not granted by capabilities.network"
1252            ));
1253        }
1254        Ok(url)
1255    }
1256
1257    /// Whether web views are granted at all (inline HTML needs only this).
1258    pub fn allows_webviews(&self) -> bool {
1259        self.each(|c| c.webview.is_some())
1260    }
1261
1262    /// Whether a web view may show (or navigate to) `url`; `about:blank`
1263    /// whenever web views are granted.
1264    pub fn allows_webview(&self, url: &str) -> bool {
1265        if url == "about:blank" {
1266            return self.allows_webviews();
1267        }
1268        let Some(parts) = parse_url(url) else {
1269            return false;
1270        };
1271        self.each(|c| c.allows_webview(&parts))
1272    }
1273
1274    /// Whether the app may set the status bar.
1275    pub fn allows_status_bar(&self) -> bool {
1276        self.each(|c| c.status_bar)
1277    }
1278
1279    /// Whether the app may read and write the system clipboard.
1280    pub fn allows_clipboard(&self) -> bool {
1281        self.each(|c| c.clipboard)
1282    }
1283
1284    /// Whether the app may show the system's picker (`nsh/picker`).
1285    pub fn allows_picker(&self) -> bool {
1286        self.each(|c| c.picker)
1287    }
1288
1289    /// Whether `nsh/host` may call the embedding app's function `name`.
1290    pub fn allows_host(&self, name: &str) -> bool {
1291        self.each(|c| c.allows_host(name))
1292    }
1293
1294    /// Whether the app may open `url` outside it (`openUrl` of
1295    /// `nsh/device`): its scheme is granted.
1296    pub fn allows_open_url(&self, url: &str) -> bool {
1297        let Some(scheme) = url
1298            .split_once(':')
1299            .map(|(scheme, _)| scheme.to_ascii_lowercase())
1300        else {
1301            return false;
1302        };
1303        self.each(|c| c.open_url.as_ref().is_some_and(|g| g.allows(&scheme)))
1304    }
1305}
1306
1307/// `location` against `base` (absolute, scheme-relative, absolute-path or
1308/// relative references), as a redirect's `Location` is read.
1309pub fn resolve_reference(base: &str, location: &str) -> String {
1310    if location.contains("://") {
1311        return location.to_owned();
1312    }
1313    let Some((scheme, rest)) = base.split_once("://") else {
1314        return location.to_owned();
1315    };
1316    if let Some(net) = location.strip_prefix("//") {
1317        return format!("{scheme}://{net}");
1318    }
1319    let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
1320    let origin = format!("{scheme}://{}", &rest[..authority_end]);
1321    if location.starts_with('/') {
1322        return format!("{origin}{location}");
1323    }
1324    let path = &rest[authority_end..];
1325    let path = path.split(['?', '#']).next().unwrap_or_default();
1326    let dir = path.rsplit_once('/').map_or("", |(d, _)| d);
1327    format!("{origin}{dir}/{location}")
1328}
1329
1330#[cfg(test)]
1331mod tests {
1332    #[test]
1333    fn verbatim_windows_paths_compare_in_their_plain_form() {
1334        use super::without_verbatim_prefix as plain;
1335        assert_eq!(plain(r"\\?\C:\Users\a").as_deref(), Some(r"C:\Users\a"));
1336        assert_eq!(plain(r"\\?\d:\").as_deref(), Some(r"d:\"));
1337        assert_eq!(plain(r"\\?\C:\app\").as_deref(), Some(r"C:\app\"));
1338        assert_eq!(
1339            plain(r"\\?\UNC\server\share\a").as_deref(),
1340            Some(r"\\server\share\a")
1341        );
1342        // Plain paths, and verbatim ones of other kinds, stay as they are.
1343        for path in [
1344            r"C:\a",
1345            r"\\server\share",
1346            "/home/a",
1347            r"\\?\Volume{x}\a",
1348            r"\\.\C:\a",
1349        ] {
1350            assert_eq!(plain(path), None, "{path}");
1351        }
1352        // Components the plain form reads otherwise keep the verbatim form.
1353        for path in [
1354            r"\\?\C:\a\NUL",
1355            r"\\?\C:\a\com1.txt",
1356            r"\\?\C:\a\Lpt9",
1357            r"\\?\C:\a\b.",
1358            r"\\?\C:\a\b ",
1359            r"\\?\C:\a\..\b",
1360            r"\\?\C:\a\.\b",
1361            r"\\?\C:\a\\b",
1362            r"\\?\C:\a/b",
1363        ] {
1364            assert_eq!(plain(path), None, "{path}");
1365        }
1366        assert_eq!(
1367            plain(r"\\?\C:\a\com10\console").as_deref(),
1368            Some(r"C:\a\com10\console")
1369        );
1370        let long = format!(r"\\?\C:\{}", "a".repeat(260));
1371        assert_eq!(plain(&long), None);
1372    }
1373
1374    #[test]
1375    fn anchored_roots_join_their_tail_component_by_component() {
1376        let app = PathBuf::from(if cfg!(windows) { r"C:\app" } else { "/app" });
1377        let paths = super::TrustedPaths {
1378            plugin_dir: Some(app.clone()),
1379            home_dir: None,
1380        };
1381        let root = paths.resolve_root("${pluginDir}/a//b/", &app).unwrap();
1382        assert_eq!(root, app.join("a").join("b"));
1383        let names = root.components().rev().take(2).collect::<Vec<_>>();
1384        assert_eq!(
1385            names,
1386            [
1387                Component::Normal("b".as_ref()),
1388                Component::Normal("a".as_ref())
1389            ]
1390        );
1391    }
1392    use super::*;
1393
1394    fn caps(json: &str) -> Capabilities {
1395        Capabilities::from_json(&serde_json::from_str(json).unwrap()).unwrap()
1396    }
1397
1398    #[test]
1399    fn environment_names_match_exactly_except_on_windows() {
1400        let access = Access {
1401            declared: caps(r#"{"process":{"env":["MY_TOKEN"]}}"#),
1402            granted: None,
1403        };
1404        assert!(access.allows_env("MY_TOKEN"));
1405        assert_eq!(access.allows_env("my_token"), cfg!(windows));
1406        assert_eq!(super::env_names_match("Path", "PATH"), cfg!(windows));
1407    }
1408
1409    #[test]
1410    fn roots_stay_within_their_anchor_and_bare_commands_have_no_drive() {
1411        let anchor = Path::new(if cfg!(windows) { "C:\\app" } else { "/app" });
1412        assert!(super::within(anchor, Path::new("data/x"), "r").is_ok());
1413        assert!(super::within(anchor, Path::new("/etc"), "r").is_err());
1414        #[cfg(windows)]
1415        for tail in ["C:/Windows", "\\\\srv\\share", "\\Users", "D:x"] {
1416            assert!(
1417                super::within(anchor, Path::new(tail), "r").is_err(),
1418                "{tail}"
1419            );
1420        }
1421        assert!(!super::valid_command("C:git"));
1422        assert!(super::valid_command("git"));
1423    }
1424
1425    #[test]
1426    fn system_capabilities_are_explicit_and_intersected() {
1427        let declared = caps(
1428            r#"{"process":{"execute":["claude","codex"]},"fs":{"read":["${dataDir}"],"write":["${dataDir}"]}}"#,
1429        );
1430        assert_eq!(
1431            Capabilities::from_json(&declared.to_json()).unwrap(),
1432            declared
1433        );
1434        let access = Access {
1435            declared,
1436            granted: Some(caps(
1437                r#"{"process":{"execute":["codex"]},"fs":{"read":["${dataDir}/conversations"]}}"#,
1438            )),
1439        };
1440        assert!(access.allows_process("codex"));
1441        assert!(!access.allows_process("claude"));
1442        assert!(!access.allows_process("/usr/bin/codex"));
1443        assert!(!Access::all().allows_process("codex"));
1444        let root = std::env::current_dir().unwrap();
1445        assert!(
1446            access
1447                .authorize_file(&root.join("conversations/new.json"), &root, false)
1448                .is_ok()
1449        );
1450        assert!(
1451            access
1452                .authorize_file(&root.join("other.json"), &root, false)
1453                .is_err()
1454        );
1455        assert!(
1456            access
1457                .authorize_file(&root.join("conversations/new.json"), &root, true)
1458                .is_err()
1459        );
1460        assert!(Access::all().authorize_file(&root, &root, false).is_err());
1461        assert!(
1462            access
1463                .authorize_file(&root.join("../secret"), &root, false)
1464                .is_err()
1465        );
1466        for bad in [
1467            r#"{"process":{"execut":[]}}"#,
1468            r#"{"fs":{"reads":[]}}"#,
1469            r#"{"fs":{"read":["${dataDir}/../outside"]}}"#,
1470            r#"{"process":{"execute":["*"]}}"#,
1471        ] {
1472            assert!(Capabilities::from_json(&serde_json::from_str(bad).unwrap()).is_err());
1473        }
1474    }
1475
1476    #[test]
1477    fn trusted_host_anchors_expand_without_implicit_grants() {
1478        let root = std::env::current_dir().unwrap();
1479        let anchors = TrustedPaths {
1480            plugin_dir: Some(root.clone()),
1481            home_dir: Some(root.join("native-home")),
1482        };
1483        let access = Access {
1484            declared: caps(
1485                r#"{"fs":{"read":["assets","${homeDir}/settings","${pluginDir}/content"]}}"#,
1486            ),
1487            granted: None,
1488        };
1489        for path in ["assets/file", "native-home/settings/file", "content/file"] {
1490            assert!(
1491                access
1492                    .authorize_file_with_paths(&root.join(path), &root, &anchors, false)
1493                    .is_ok()
1494            );
1495        }
1496        assert!(
1497            access
1498                .authorize_file(&root.join("content/file"), &root, false)
1499                .is_err()
1500        );
1501        assert!(
1502            access
1503                .authorize_file_with_paths(&root.join("other/file"), &root, &anchors, false)
1504                .is_err()
1505        );
1506        assert!(
1507            TrustedPaths::default()
1508                .resolve_root("${homeDir}/settings", &root)
1509                .is_err()
1510        );
1511        assert!(
1512            TrustedPaths::default()
1513                .resolve_root("assets", &root)
1514                .is_err()
1515        );
1516    }
1517
1518    #[test]
1519    fn http_rules_are_one_form_whose_keys_all_narrow() {
1520        let allows = |rule: serde_json::Value, method: &str, url: &str| {
1521            Access {
1522                declared: Capabilities::from_json(&serde_json::json!({"network":{"http":[rule]}}))
1523                    .unwrap(),
1524                granted: None,
1525            }
1526            .allows_http(method, url)
1527        };
1528        // `{host, methods}` covers every path, scheme and port, as manifests had it.
1529        let plain = serde_json::json!({"host": "api.example.com", "methods": ["GET"]});
1530        assert!(allows(plain.clone(), "GET", "https://api.example.com/"));
1531        assert!(allows(
1532            plain.clone(),
1533            "GET",
1534            "http://api.example.com:8080/any/path"
1535        ));
1536        assert!(!allows(plain.clone(), "POST", "https://api.example.com/"));
1537        assert!(allows(
1538            serde_json::json!({"host": "api.example.com"}),
1539            "PUT",
1540            "https://api.example.com/x"
1541        ));
1542        // Paths are exact, prefixes whole segments; either one covers a path.
1543        let scoped = serde_json::json!({
1544            "host": "api.example.com", "methods": ["GET"], "scheme": "https", "port": 443,
1545            "paths": ["/exact"], "pathPrefixes": ["/v1"]
1546        });
1547        assert!(allows(
1548            scoped.clone(),
1549            "GET",
1550            "https://api.example.com/exact?q=1"
1551        ));
1552        assert!(allows(scoped.clone(), "GET", "https://api.example.com/v1"));
1553        assert!(allows(
1554            scoped.clone(),
1555            "GET",
1556            "https://api.example.com/v1/child"
1557        ));
1558        assert!(!allows(
1559            scoped.clone(),
1560            "GET",
1561            "https://api.example.com/v10"
1562        ));
1563        assert!(!allows(
1564            scoped.clone(),
1565            "GET",
1566            "https://api.example.com/exact/more"
1567        ));
1568        assert!(!allows(
1569            scoped.clone(),
1570            "GET",
1571            "http://api.example.com/exact"
1572        ));
1573        assert!(!allows(
1574            scoped.clone(),
1575            "GET",
1576            "https://api.example.com:444/exact"
1577        ));
1578        assert!(allows(scoped, "GET", "https://api.example.com:443/exact"));
1579        // Main's spelling still reads, and a prefix ending in `/` covers what follows it.
1580        let legacy = serde_json::json!({"host": "*.example.com", "schemes": ["https", "wss"], "pathPrefix": "/v1/"});
1581        assert!(allows(
1582            legacy.clone(),
1583            "GET",
1584            "https://quotes.example.com/v1/quote"
1585        ));
1586        assert!(!allows(legacy, "GET", "https://quotes.example.com/v2/"));
1587        // Every spelling of a key is merged, and one form is written back.
1588        let mixed = caps(
1589            r#"{"network":{"http":[{"host":"a.example.com","methods":["get"],"scheme":"https","schemes":["wss","https"],"pathPrefix":"/a","path_prefixes":["/b"],"pathPrefixes":["/a","/c"]}]}}"#,
1590        );
1591        let grant = &mixed.network.http[0];
1592        assert_eq!(grant.methods, ["GET"]);
1593        assert_eq!(grant.schemes, ["https", "wss"]);
1594        assert_eq!(grant.path_prefixes, ["/a", "/c", "/b"]);
1595        assert_eq!(
1596            mixed.to_json()["network"]["http"][0],
1597            serde_json::json!({"host":"a.example.com","methods":["GET"],"schemes":["https","wss"],"pathPrefixes":["/a","/c","/b"]})
1598        );
1599        assert_eq!(Capabilities::from_json(&mixed.to_json()).unwrap(), mixed);
1600        // What cannot match is an error, not a rule that grants nothing.
1601        for bad in [
1602            serde_json::json!({"host": "a.example.com", "schemes": ["ftp"]}),
1603            serde_json::json!({"host": "a.example.com", "port": 0}),
1604            serde_json::json!({"host": "a.example.com", "port": 70000}),
1605            serde_json::json!({"host": "a.example.com", "paths": ["relative"]}),
1606            serde_json::json!({"host": "a.example.com", "pathPrefixes": ["/v1/*"]}),
1607            serde_json::json!({"host": "a.example.com", "methods": ["*"]}),
1608            serde_json::json!({"host": "a.example.com", "paths": "/x", "query": true}),
1609            serde_json::json!({"methods": ["GET"]}),
1610        ] {
1611            assert!(
1612                Capabilities::from_json(&serde_json::json!({"network":{"http":[bad.clone()]}}))
1613                    .is_err(),
1614                "{bad}"
1615            );
1616        }
1617    }
1618
1619    #[test]
1620    fn exit_and_environment_permissions_intersect() {
1621        let declared = caps(r#"{"process":{"env":["NSH_SECRET","OTHER"],"exit":true}}"#);
1622        assert_eq!(
1623            Capabilities::from_json(&declared.to_json()).unwrap(),
1624            declared
1625        );
1626        let access = Access {
1627            declared,
1628            granted: Some(caps(r#"{"process":{"env":["NSH_SECRET"]}}"#)),
1629        };
1630        assert!(access.allows_env("NSH_SECRET"));
1631        assert!(!access.allows_env("OTHER"));
1632        assert!(!access.allows_exit());
1633        assert!(!Access::all().allows_exit());
1634        assert!(!Access::all().allows_env("NSH_SECRET"));
1635        assert!(Access::all().allows_env("LANG"));
1636        assert_eq!(Access::all().allows_env("lang"), cfg!(windows));
1637        assert!(Access::all().allows_env("TZ"));
1638        // Identity, paths and proxy credentials need an explicit grant.
1639        for name in [
1640            "HOME",
1641            "USER",
1642            "USERNAME",
1643            "HOSTNAME",
1644            "COMPUTERNAME",
1645            "PATH",
1646            "TMPDIR",
1647            "XDG_RUNTIME_DIR",
1648            "APPDATA",
1649            "http_proxy",
1650            "HTTPS_PROXY",
1651            "ALL_PROXY",
1652            "NO_PROXY",
1653            "DISPLAY",
1654        ] {
1655            assert!(!Access::all().allows_env(name), "{name}");
1656        }
1657        assert!(!Access::all().allows_env("SSH_AUTH_SOCK"));
1658        assert!(!Access::all().allows_env("DBUS_SESSION_BUS_ADDRESS"));
1659        assert!(Capabilities::from_json(&serde_json::json!({"process":{"exit":"true"}})).is_err());
1660        assert!(
1661            Capabilities::from_json(&serde_json::json!({"process":{"env":["BAD=NAME"]}})).is_err()
1662        );
1663    }
1664
1665    #[test]
1666    fn default_environment_entries_are_upper_case_names() {
1667        for line in include_str!("default-env").lines() {
1668            let name = line.split('#').next().unwrap_or_default().trim();
1669            assert!(
1670                name.is_empty()
1671                    || name
1672                        .chars()
1673                        .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'),
1674                "{line}"
1675            );
1676        }
1677    }
1678
1679    #[test]
1680    fn sockets_need_exact_host_and_port_grants() {
1681        let declared = caps(
1682            r#"{"network":{"hosts":["*"],"sockets":["MQTT.example.com:8883","[::1]:9000","127.0.0.1:22"]}}"#,
1683        );
1684        assert_eq!(
1685            Capabilities::from_json(&declared.to_json()).unwrap(),
1686            declared
1687        );
1688        let access = Access {
1689            declared,
1690            granted: None,
1691        };
1692        assert!(access.allows_socket("mqtt.example.com", 8883));
1693        assert!(access.allows_socket("MQTT.example.com.", 8883));
1694        assert!(!access.allows_socket("mqtt.example.com", 1883));
1695        assert!(!access.allows_socket("example.com", 8883));
1696        assert!(!access.allows_socket("a.mqtt.example.com", 8883));
1697        assert!(access.allows_socket("::1", 9000));
1698        assert!(access.allows_socket("[::1]", 9000));
1699        assert!(access.allows_socket("127.0.0.1", 22));
1700        assert!(!access.allows_socket("127.0.0.1", 0));
1701        // `hosts: ["*"]` (and the unrestricted default) grant no sockets.
1702        assert!(!access.allows_socket("localhost", 22));
1703        assert!(!Access::all().allows_socket("127.0.0.1", 22));
1704        assert!(!Access::all().allows_socket("example.com", 443));
1705        let narrowed = Access {
1706            granted: Some(caps(r#"{"network":{"sockets":["127.0.0.1:22"]}}"#)),
1707            ..access
1708        };
1709        assert!(narrowed.allows_socket("127.0.0.1", 22));
1710        assert!(!narrowed.allows_socket("mqtt.example.com", 8883));
1711        for bad in [
1712            "*.example.com:443",
1713            "*:443",
1714            "example.com",
1715            "example.com:0",
1716            "example.com:65536",
1717            "example.com:*",
1718            ":443",
1719            "::1:443",
1720            "[]:443",
1721            "exa mple.com:1",
1722        ] {
1723            assert!(
1724                Capabilities::from_json(&serde_json::json!({"network":{"sockets":[bad]}}))
1725                    .unwrap_err()
1726                    .contains("invalid socket grant"),
1727                "{bad}"
1728            );
1729        }
1730    }
1731
1732    #[test]
1733    fn websockets_follow_http_grants() {
1734        let access = Access {
1735            declared: caps(
1736                r#"{"network":{"hosts":["ws.example.com"],"http":[
1737                    {"host":"chat.example.com","methods":["GET"],"scheme":"https","paths":["/socket"]},
1738                    {"host":"legacy.example.com","schemes":["wss"]}
1739                ]}}"#,
1740            ),
1741            granted: None,
1742        };
1743        assert!(access.allows_websocket("ws://ws.example.com:8080/x"));
1744        assert!(access.allows_websocket("wss://chat.example.com/socket"));
1745        assert!(!access.allows_websocket("ws://chat.example.com/socket"));
1746        assert!(!access.allows_websocket("wss://chat.example.com/other"));
1747        assert!(access.allows_websocket("wss://legacy.example.com/"));
1748        assert!(!access.allows_websocket("ws://legacy.example.com/"));
1749        assert!(!access.allows_websocket("https://ws.example.com/"));
1750        assert!(!access.allows_socket("ws.example.com", 8080));
1751    }
1752
1753    #[cfg(unix)]
1754    #[test]
1755    fn filesystem_symlinks_cannot_escape_granted_roots() {
1756        use std::os::unix::fs::symlink;
1757        let base = std::env::var_os("TMPDIR")
1758            .map(PathBuf::from)
1759            .unwrap_or_else(|| {
1760                PathBuf::from(std::env::var_os("HOME").unwrap()).join(".cache/nsh-benchs-test-tmp")
1761            });
1762        let root = base.join(format!("access-policy-{}", std::process::id()));
1763        std::fs::create_dir_all(root.join("allowed")).unwrap();
1764        std::fs::create_dir_all(root.join("outside")).unwrap();
1765        symlink(root.join("outside"), root.join("allowed/link")).unwrap();
1766        let access = Access {
1767            declared: caps(r#"{"fs":{"read":["${dataDir}"],"write":["${dataDir}"]}}"#),
1768            granted: None,
1769        };
1770        for write in [false, true] {
1771            assert!(
1772                access
1773                    .authorize_file(
1774                        &root.join("allowed/link/missing/file"),
1775                        &root.join("allowed"),
1776                        write
1777                    )
1778                    .is_err()
1779            );
1780            assert!(
1781                access
1782                    .authorize_file(&root.join("allowed/new/file"), &root.join("allowed"), write)
1783                    .is_ok()
1784            );
1785        }
1786        std::fs::remove_dir_all(root).unwrap();
1787    }
1788
1789    #[test]
1790    fn denies_unless_listed() {
1791        let access = Access {
1792            declared: caps("{}"),
1793            granted: None,
1794        };
1795        assert!(!access.allows_http("GET", "https://example.com/"));
1796        assert!(!access.allows_media("https://example.com/a.png"));
1797        assert!(access.allows_media("asset:/logo.png"));
1798        assert!(access.allows_media("logo.png"));
1799        assert!(!access.allows_webview("https://example.com/"));
1800        assert!(!access.allows_status_bar());
1801        assert!(!access.allows_clipboard());
1802        assert!(!access.allows_picker());
1803        assert!(!access.allows_host("getUserInfo"));
1804        assert!(Access::all().is_unrestricted());
1805    }
1806
1807    #[test]
1808    fn host_functions_need_an_explicit_grant() {
1809        // Undeclared, the other capabilities are all granted; the host's
1810        // functions are not.
1811        let all = Access::all();
1812        assert!(all.allows_clipboard());
1813        assert!(!all.allows_host("getUserInfo"));
1814        let access = |json: &str| Access {
1815            declared: caps(json),
1816            granted: None,
1817        };
1818        let every = access(r#"{ "host": true }"#);
1819        assert!(every.allows_host("getUserInfo") && every.allows_host("bridge.call"));
1820        assert!(!access(r#"{ "host": false }"#).allows_host("getUserInfo"));
1821        let listed = access(r#"{ "host": ["getUserInfo", "bridge.*"] }"#);
1822        assert!(listed.allows_host("getUserInfo"));
1823        assert!(listed.allows_host("bridge.share"));
1824        assert!(!listed.allows_host("getUserInfoX"));
1825        assert!(!listed.allows_host("bridge"));
1826        assert!(Capabilities::from_json(&serde_json::json!({ "host": ["a*b"] })).is_err());
1827        assert!(Capabilities::from_json(&serde_json::json!({ "host": [""] })).is_err());
1828        // The embedding app may grant less.
1829        let narrowed = Access {
1830            declared: caps(r#"{ "host": true }"#),
1831            granted: Some(caps(r#"{ "host": ["bridge.*"] }"#)),
1832        };
1833        assert!(narrowed.allows_host("bridge.call") && !narrowed.allows_host("getUserInfo"));
1834    }
1835
1836    #[test]
1837    fn host_function_names_and_grants_keep_to_their_charset() {
1838        for good in ["getUserInfo", "user.info", "a-b_c:d.E9", &"a".repeat(128)] {
1839            assert!(valid_host_name(good), "{good}");
1840        }
1841        for bad in [
1842            "",
1843            "user.x/../../admin",
1844            "a..b",
1845            "user x",
1846            "a\\b",
1847            "caf\u{e9}",
1848            "ok\u{0}",
1849            "a*",
1850            &"a".repeat(129),
1851        ] {
1852            assert!(!valid_host_name(bad), "{bad:?}");
1853        }
1854        let parses =
1855            |grant: &str| Capabilities::from_json(&serde_json::json!({ "host": [grant] })).is_ok();
1856        assert!(parses("*") && parses("user.*") && parses("user.info"));
1857        for bad in ["user/*", "a..*", "../*", "a b", "**"] {
1858            assert!(!parses(bad), "{bad}");
1859        }
1860    }
1861
1862    #[test]
1863    fn hosts_and_finer_grants() {
1864        let c = caps(
1865            r#"{ "network": {
1866                "hosts": ["*.example.org"],
1867                "http": [{ "host": "api.example.com", "methods": ["get"], "pathPrefix": "/v1/" }]
1868            } }"#,
1869        );
1870        let a = Access {
1871            declared: c,
1872            granted: None,
1873        };
1874        assert!(a.allows_http("POST", "https://api.example.org/x"));
1875        assert!(!a.allows_http("GET", "https://example.org/"));
1876        assert!(!a.allows_http("GET", "https://example.org.evil.io/"));
1877        assert!(!a.allows_http("GET", "https://evilexample.org/"));
1878        assert!(a.allows_http("GET", "https://API.example.com/v1/quote"));
1879        assert!(!a.allows_http("POST", "https://api.example.com/v1/quote"));
1880        assert!(!a.allows_http("GET", "https://api.example.com/v2/"));
1881        assert!(!a.allows_http("GET", "file://api.example.com/v1/"));
1882        // User info does not fool the host check.
1883        assert!(!a.allows_http("GET", "https://api.example.org@evil.io/"));
1884        assert!(a.allows_http("GET", "https://user:pw@api.example.org:8443/"));
1885    }
1886
1887    #[test]
1888    fn the_embedder_grants_at_most() {
1889        let a = Access {
1890            declared: caps(
1891                r#"{ "network": { "hosts": ["a.com", "b.com"] }, "statusBar": true, "clipboard": true, "picker": true }"#,
1892            ),
1893            granted: Some(caps(
1894                r#"{ "network": { "hosts": ["b.com"] }, "clipboard": true }"#,
1895            )),
1896        };
1897        assert!(a.allows_clipboard());
1898        assert!(!a.allows_http("GET", "https://a.com/"));
1899        assert!(!a.allows_picker());
1900        assert!(a.allows_http("GET", "https://b.com/"));
1901        assert!(!a.allows_status_bar());
1902    }
1903
1904    #[test]
1905    fn typos_are_errors() {
1906        let bad =
1907            |json: &str| Capabilities::from_json(&serde_json::from_str(json).unwrap()).unwrap_err();
1908        assert!(bad(r#"{ "netwrok": {} }"#).contains("unknown key `netwrok`"));
1909        assert!(bad(r#"{ "network": { "host": [] } }"#).contains("unknown key `host`"));
1910        assert!(bad(r#"{ "network": { "hosts": ["exa mple.com"] } }"#).contains("invalid host"));
1911        let c = caps(
1912            r#"{ "network": { "hosts": ["a.com"], "http": [{ "host": "b.com", "methods": ["GET"] }] }, "webview": { "hosts": ["*"] } }"#,
1913        );
1914        assert_eq!(Capabilities::from_json(&c.to_json()).unwrap(), c);
1915    }
1916
1917    /// Packages from newer signers: what this runtime does not know is never
1918    /// granted, and an unknown restriction drops what it restricts.
1919    #[test]
1920    fn unknown_keys_in_packages_grant_nothing() {
1921        let lenient =
1922            |json: &str| Capabilities::from_json_lenient(&serde_json::from_str(json).unwrap());
1923        let (c, dropped) = lenient(
1924            r#"{ "bluetooth": true, "clipboard": true,
1925                 "network": { "hosts": ["a.com"], "http": [
1926                     { "host": "b.com", "ports": [443] },
1927                     { "host": "c.com", "methods": ["GET"] }
1928                 ] } }"#,
1929        )
1930        .unwrap();
1931        assert!(c.clipboard);
1932        assert_eq!(c.network.hosts, [HostPattern::new("a.com").unwrap()]);
1933        assert_eq!(c.network.http.len(), 1);
1934        assert_eq!(c.network.http[0].host.as_str(), "c.com");
1935        assert_eq!(
1936            dropped,
1937            [
1938                "capabilities.bluetooth",
1939                "capabilities.network.http[0] (unknown key `ports`)"
1940            ]
1941        );
1942        let (c, dropped) =
1943            lenient(r#"{ "network": { "hosts": ["a.com"], "ipv6": false }, "webview": { "hosts": ["*"], "x": 1 } }"#)
1944                .unwrap();
1945        assert_eq!(c, Capabilities::default());
1946        assert_eq!(dropped.len(), 2);
1947        // What it knows is still checked.
1948        assert!(lenient(r#"{ "statusBar": "yes" }"#).is_err());
1949        assert!(lenient(r#"{ "network": { "hosts": ["exa mple.com"] } }"#).is_err());
1950        // Nothing unknown: the same as the strict parse.
1951        let json = serde_json::json!({ "network": { "hosts": ["a.com"] }, "statusBar": true });
1952        let (c, dropped) = Capabilities::from_json_lenient(&json).unwrap();
1953        assert_eq!(c, Capabilities::from_json(&json).unwrap());
1954        assert!(dropped.is_empty());
1955    }
1956
1957    #[test]
1958    fn media_redirects_are_checked() {
1959        let a = Access {
1960            declared: Capabilities::from_json(
1961                &serde_json::json!({ "network": { "hosts": ["a.com"] } }),
1962            )
1963            .unwrap(),
1964            granted: None,
1965        };
1966        let from = "https://a.com/x/y.png";
1967        assert_eq!(
1968            a.media_redirect(from, "/z.png").unwrap(),
1969            "https://a.com/z.png"
1970        );
1971        assert_eq!(
1972            a.media_redirect(from, "z.png").unwrap(),
1973            "https://a.com/x/z.png"
1974        );
1975        assert!(a.media_redirect(from, "https://b.com/z.png").is_err());
1976        assert!(a.media_redirect(from, "//b.com/z.png").is_err());
1977        assert!(a.media_redirect(from, "file:///etc/passwd").is_err());
1978        assert!(
1979            Access::default()
1980                .media_redirect(from, "//b.com/z.png")
1981                .is_ok()
1982        );
1983        assert!(
1984            Access::default()
1985                .media_redirect(from, "ftp://b.com/z.png")
1986                .is_err()
1987        );
1988    }
1989
1990    #[test]
1991    fn opening_urls_is_granted_by_scheme() {
1992        let caps = |json: serde_json::Value| Capabilities::from_json(&json).unwrap();
1993        let access =
1994            |declared: Capabilities, granted: Option<Capabilities>| Access { declared, granted };
1995        let any = access(caps(serde_json::json!({ "openUrl": true })), None);
1996        assert!(any.allows_open_url("https://a.com"));
1997        assert!(any.allows_open_url("tel:+15550100"));
1998        let some = access(
1999            caps(serde_json::json!({ "openUrl": { "schemes": ["HTTPS", "mailto"] } })),
2000            None,
2001        );
2002        assert!(some.allows_open_url("https://a.com"));
2003        assert!(some.allows_open_url("MAILTO:a@b.c"));
2004        assert!(!some.allows_open_url("tel:1"));
2005        // The embedding app grants less.
2006        let narrowed = access(
2007            caps(serde_json::json!({ "openUrl": true })),
2008            Some(caps(
2009                serde_json::json!({ "openUrl": { "schemes": ["https"] } }),
2010            )),
2011        );
2012        assert!(narrowed.allows_open_url("https://a.com"));
2013        assert!(!narrowed.allows_open_url("mailto:a@b.c"));
2014        let none = access(caps(serde_json::json!({ "openUrl": false })), None);
2015        assert!(!none.allows_open_url("https://a.com"));
2016        assert!(!access(caps(serde_json::json!({})), None).allows_open_url("https://a.com"));
2017        assert!(Access::default().allows_open_url("https://a.com"));
2018        for bad in [
2019            serde_json::json!({ "openUrl": "yes" }),
2020            serde_json::json!({ "openUrl": { "schemes": ["ht tp"] } }),
2021            serde_json::json!({ "openUrl": { "hosts": ["a.com"] } }),
2022        ] {
2023            assert!(Capabilities::from_json(&bad).is_err(), "{bad}");
2024        }
2025        // Round trip.
2026        for json in [
2027            serde_json::json!(true),
2028            serde_json::json!(false),
2029            serde_json::json!({ "schemes": ["https"] }),
2030        ] {
2031            let c = caps(serde_json::json!({ "openUrl": json }));
2032            assert_eq!(c.to_json()["openUrl"], json);
2033        }
2034    }
2035}