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