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