1use std::{
57 borrow::Cow,
58 path::{Component, Path, PathBuf},
59};
60
61use serde_json::{Map, Value};
62
63#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct HostPattern(String);
67
68impl HostPattern {
69 pub fn new(pattern: &str) -> Result<Self, String> {
71 let p = pattern.trim().to_ascii_lowercase();
72 let host = p.strip_prefix("*.").unwrap_or(&p);
73 let valid = p == "*"
74 || (!host.is_empty()
75 && host.chars().all(|c| {
76 c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | ':' | '[' | ']')
77 }));
78 if valid {
79 Ok(Self(p))
80 } else {
81 Err(format!("invalid host pattern `{pattern}`"))
82 }
83 }
84
85 pub fn matches(&self, host: &str) -> bool {
87 match self.0.strip_prefix("*.") {
88 _ if self.0 == "*" => true,
89 Some(suffix) => {
90 host.len() > suffix.len() + 1 && host.ends_with(suffix) && {
91 let dot = host.len() - suffix.len() - 1;
92 host.as_bytes()[dot] == b'.'
93 }
94 }
95 None => self.0 == host,
96 }
97 }
98
99 pub fn as_str(&self) -> &str {
101 &self.0
102 }
103
104 fn is_any(&self) -> bool {
106 self.0 == "*"
107 }
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
113#[non_exhaustive]
114pub struct HttpGrant {
115 pub host: HostPattern,
117 pub methods: Vec<String>,
119 pub schemes: Vec<String>,
121 pub port: Option<u16>,
123 pub paths: Vec<String>,
127 pub path_prefixes: Vec<String>,
131}
132
133impl Default for HttpGrant {
134 fn default() -> Self {
135 Self {
136 host: HostPattern(String::new()),
137 methods: Vec::new(),
138 schemes: Vec::new(),
139 port: None,
140 paths: Vec::new(),
141 path_prefixes: Vec::new(),
142 }
143 }
144}
145
146impl HttpGrant {
147 fn allows(&self, method: &str, url: &UrlParts<'_>) -> bool {
148 let default_port = match url.scheme.as_str() {
149 "https" | "wss" => 443,
150 _ => 80,
151 };
152 let path = url.path.split(['?', '#']).next().unwrap_or("/");
153 let path = if path.is_empty() { "/" } else { path };
154 self.host.matches(&url.host)
155 && (self.methods.is_empty()
156 || self.methods.iter().any(|m| m.eq_ignore_ascii_case(method)))
157 && (self.schemes.is_empty() || self.schemes.contains(&url.scheme))
158 && self
159 .port
160 .is_none_or(|p| url.port.unwrap_or(default_port) == p)
161 && ((self.paths.is_empty() && self.path_prefixes.is_empty())
162 || self.paths.iter().any(|allowed| allowed == path)
163 || self.path_prefixes.iter().any(|prefix| {
164 path.strip_prefix(prefix.as_str()).is_some_and(|tail| {
165 tail.is_empty() || prefix.ends_with('/') || tail.starts_with('/')
166 })
167 }))
168 }
169
170 fn allows_anywhere(&self, method: &str, scheme: &str) -> bool {
173 self.host.is_any()
174 && (self.methods.is_empty()
175 || self.methods.iter().any(|m| m.eq_ignore_ascii_case(method)))
176 && (self.schemes.is_empty() || self.schemes.iter().any(|s| s == scheme))
177 && self.port.is_none()
178 && self.paths.is_empty()
179 && self.path_prefixes.is_empty()
180 }
181}
182
183#[derive(Debug, Clone, PartialEq, Eq, Default)]
185#[non_exhaustive]
186pub struct NetworkGrants {
187 pub hosts: Vec<HostPattern>,
189 pub http: Vec<HttpGrant>,
191 pub sockets: Vec<SocketGrant>,
193}
194
195#[derive(Debug, Clone, PartialEq, Eq)]
199pub struct SocketGrant {
200 host: String,
201 port: u16,
202}
203
204impl SocketGrant {
205 pub fn new(grant: &str) -> Result<Self, String> {
207 let invalid = || {
208 format!(
209 "invalid socket grant `{grant}`: expected an exact `host:port` (`[::1]:port` for IPv6), without wildcards"
210 )
211 };
212 let (host, port) = grant.trim().rsplit_once(':').ok_or_else(invalid)?;
213 let port = port
214 .parse::<u16>()
215 .ok()
216 .filter(|p| *p != 0)
217 .ok_or_else(invalid)?;
218 let host = host.to_ascii_lowercase();
219 let host = match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
220 Some(v6)
221 if !v6.is_empty()
222 && v6
223 .chars()
224 .all(|c| c.is_ascii_hexdigit() || matches!(c, ':' | '.')) =>
225 {
226 v6.to_owned()
227 }
228 Some(_) => return Err(invalid()),
229 None if !host.is_empty()
230 && host
231 .chars()
232 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')) =>
233 {
234 host.trim_end_matches('.').to_owned()
235 }
236 None => return Err(invalid()),
237 };
238 Ok(Self { host, port })
239 }
240
241 pub fn host(&self) -> &str {
243 &self.host
244 }
245
246 pub fn port(&self) -> u16 {
248 self.port
249 }
250
251 pub fn to_string_form(&self) -> String {
253 if self.host.contains(':') {
254 format!("[{}]:{}", self.host, self.port)
255 } else {
256 format!("{}:{}", self.host, self.port)
257 }
258 }
259}
260
261#[derive(Debug, Clone, PartialEq, Eq, Default)]
263#[non_exhaustive]
264pub struct ProcessGrants {
265 pub execute: Vec<String>,
267 pub exit: bool,
269 pub env: Vec<String>,
271}
272
273#[derive(Debug, Clone, PartialEq, Eq, Default)]
276#[non_exhaustive]
277pub struct FileGrants {
278 pub read: Vec<String>,
280 pub write: Vec<String>,
282}
283
284#[derive(Debug, Clone, PartialEq, Eq, Default)]
286#[non_exhaustive]
287pub struct TrustedPaths {
288 pub plugin_dir: Option<PathBuf>,
290 pub home_dir: Option<PathBuf>,
292}
293impl TrustedPaths {
294 pub fn resolve_root(&self, root: &str, data_dir: &Path) -> Result<PathBuf, String> {
297 validate_path_pattern(root)?;
298 for (placeholder, anchor) in [
299 ("${dataDir}", Some(data_dir)),
300 ("${pluginDir}", self.plugin_dir.as_deref()),
301 ("${homeDir}", self.home_dir.as_deref()),
302 ] {
303 if let Some(tail) = root.strip_prefix(placeholder) {
304 let anchor = anchor
305 .filter(|p| absolute(p))
306 .ok_or_else(|| format!("host anchor {placeholder} unavailable"))?;
307 let tail: PathBuf = tail.split('/').filter(|part| !part.is_empty()).collect();
310 return within(anchor, &tail, root);
311 }
312 }
313 let path = PathBuf::from(root);
314 if absolute(&path) {
315 Ok(path)
316 } else {
317 let anchor = self
318 .plugin_dir
319 .as_deref()
320 .filter(|p| absolute(p))
321 .ok_or_else(|| {
322 "host application directory unavailable for relative filesystem root".to_owned()
323 })?;
324 within(anchor, &path, root)
325 }
326 }
327}
328
329pub(crate) fn lexical(path: &Path) -> PathBuf {
331 use std::path::Component;
332 let mut out = PathBuf::new();
333 for part in path.components() {
334 match part {
335 Component::ParentDir => {
336 out.pop();
337 }
338 Component::CurDir => (),
339 other => out.push(other.as_os_str()),
340 }
341 }
342 out
343}
344
345#[cfg(not(target_arch = "wasm32"))]
348pub(crate) fn resolved(path: &Path) -> Result<PathBuf, String> {
349 let mut current = path.to_path_buf();
350 let mut tail = Vec::new();
351 loop {
352 if let Ok(mut real) = canonicalize(¤t) {
353 real.extend(tail.into_iter().rev());
354 return Ok(real);
355 }
356 let name = current
357 .file_name()
358 .ok_or("invalid filesystem path")?
359 .to_owned();
360 if !current.pop() {
361 return Err("invalid filesystem path".into());
362 }
363 tail.push(name);
364 }
365}
366
367pub(crate) fn inside(path: &Path, root: &Path) -> Option<PathBuf> {
370 let mut rest = path.components();
371 for part in root.components() {
372 let next = rest.next()?;
373 let same = if cfg!(windows) {
374 next.as_os_str()
375 .to_string_lossy()
376 .eq_ignore_ascii_case(&part.as_os_str().to_string_lossy())
377 } else {
378 next == part
379 };
380 if !same {
381 return None;
382 }
383 }
384 Some(rest.collect())
385}
386
387#[cfg(not(target_arch = "wasm32"))]
390pub(crate) fn in_root(path: &Path, (expanded, canonical): &(PathBuf, PathBuf)) -> Option<PathBuf> {
391 inside(path, canonical).or_else(|| inside(path, expanded))
392}
393
394pub fn native_files(os: crate::platform::Os) -> bool {
398 cfg!(any(
399 target_os = "linux",
400 target_os = "macos",
401 target_os = "windows"
402 )) && os.is_desktop()
403}
404
405#[derive(Debug, Clone, Default)]
411#[non_exhaustive]
412#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
413pub struct MediaFiles {
414 declared: Vec<(PathBuf, PathBuf)>,
417 granted: Option<Vec<(PathBuf, PathBuf)>>,
419}
420
421impl MediaFiles {
422 pub fn new(
426 access: &Access,
427 data_dir: Option<&Path>,
428 paths: &TrustedPaths,
429 available: bool,
430 ) -> Self {
431 #[cfg(target_arch = "wasm32")]
432 {
433 let _ = (access, data_dir, paths, available);
434 Self::default()
435 }
436 #[cfg(not(target_arch = "wasm32"))]
437 {
438 if !available {
439 return Self::default();
440 }
441 let data = data_dir.map(Path::to_path_buf).unwrap_or_default();
442 let roots = |grants: &Capabilities| {
443 grants
444 .fs
445 .read
446 .iter()
447 .filter_map(|root| {
448 let expanded = lexical(&paths.resolve_root(root, &data).ok()?);
449 let canonical = resolved(&expanded).ok()?;
450 Some((expanded, canonical))
451 })
452 .collect()
453 };
454 Self {
455 declared: roots(&access.declared),
456 granted: access.granted.as_ref().map(roots),
457 }
458 }
459 }
460
461 #[cfg(not(target_arch = "wasm32"))]
467 pub(crate) fn open(&self, path: &Path) -> Option<std::io::Result<std::fs::File>> {
468 if self.declared.is_empty() {
469 return None;
470 }
471 let refused = || std::io::Error::new(std::io::ErrorKind::PermissionDenied, "not granted");
472 let path = lexical(path);
473 if !self
474 .declared
475 .iter()
476 .any(|root| in_root(&path, root).is_some())
477 {
478 return Some(Err(refused()));
479 }
480 let granted: Vec<&(PathBuf, PathBuf)> = match &self.granted {
484 Some(roots) => roots
485 .iter()
486 .filter(|(_, canonical)| {
487 self.declared
488 .iter()
489 .any(|(_, declared)| inside(canonical, declared).is_some())
490 })
491 .collect(),
492 None => self.declared.iter().collect(),
493 };
494 let Some(((_, canonical), relative)) = granted
497 .into_iter()
498 .filter_map(|root| Some((root, in_root(&path, root)?)))
499 .max_by_key(|((_, canonical), _)| canonical.components().count())
500 else {
501 return Some(Err(refused()));
502 };
503 Some((|| {
504 let dir = crate::runtime::fs::confined::open_root(canonical)?;
505 let file = crate::runtime::fs::confined::open_file(&dir, &relative, false)?;
506 Ok(file.into_std())
507 })())
508 }
509
510 fn readable(&self, path: &Path) -> Option<PathBuf> {
515 #[cfg(target_arch = "wasm32")]
516 {
517 let _ = path;
518 None
519 }
520 #[cfg(not(target_arch = "wasm32"))]
521 {
522 if !absolute(path) || self.declared.is_empty() {
523 return None;
524 }
525 let path = lexical(path);
528 let within = |roots: &[(PathBuf, PathBuf)]| {
529 roots.iter().any(|root| in_root(&path, root).is_some())
530 };
531 if !within(&self.declared) || !self.granted.as_deref().is_none_or(within) {
532 return None;
533 }
534 #[cfg(test)]
539 RESOLVES.with(|n| n.set(n.get() + 1));
540 let real = resolved_path(&path).ok()?;
541 let holds = |roots: &[(PathBuf, PathBuf)]| {
542 roots
543 .iter()
544 .any(|(_, canonical)| inside(&real, canonical).is_some())
545 };
546 (holds(&self.declared) && self.granted.as_deref().is_none_or(holds)).then_some(real)
547 }
548 }
549}
550
551#[cfg(test)]
552thread_local! {
553 static RESOLVES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
556}
557
558pub(crate) fn absolute(path: &Path) -> bool {
561 if cfg!(target_arch = "wasm32") {
562 path.has_root()
563 } else {
564 path.is_absolute()
565 }
566}
567
568fn within(anchor: &Path, tail: &Path, root: &str) -> Result<PathBuf, String> {
572 use std::path::Component;
573 let names = tail
574 .components()
575 .all(|c| matches!(c, Component::Normal(_) | Component::CurDir));
576 let mut path = anchor.to_path_buf();
577 path.extend(tail.components().filter(|c| *c != Component::CurDir));
578 if names && path.starts_with(anchor) {
579 Ok(path)
580 } else {
581 Err(format!("filesystem root `{root}` leaves its anchor"))
582 }
583}
584
585pub(crate) fn env_names_match(a: &str, b: &str) -> bool {
589 if cfg!(windows) {
590 a.eq_ignore_ascii_case(b)
591 } else {
592 a == b
593 }
594}
595
596#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
598pub enum WebMedia {
599 Microphone,
601 Camera,
603}
604
605impl WebMedia {
606 pub fn as_str(self) -> &'static str {
608 match self {
609 Self::Microphone => "microphone",
610 Self::Camera => "camera",
611 }
612 }
613}
614
615#[derive(Debug, Clone, PartialEq, Eq, Default)]
619#[non_exhaustive]
620pub struct Capabilities {
621 pub process: ProcessGrants,
623 pub fs: FileGrants,
625 pub network: NetworkGrants,
627 pub webview: Option<Vec<HostPattern>>,
629 pub webview_input: bool,
632 pub webview_media: Vec<WebMedia>,
635 pub status_bar: bool,
637 pub clipboard: bool,
639 pub picker: bool,
642 pub speech: bool,
646 pub notifications: bool,
649 pub audio: bool,
651 pub host: Vec<String>,
655 pub open_url: Option<OpenUrlGrant>,
658 pub windows: Option<WindowsGrant>,
661}
662
663#[derive(Debug, Clone, PartialEq, Eq, Default)]
667#[non_exhaustive]
668pub struct WindowsGrant {
669 pub kinds: Vec<crate::desktop::WindowKind>,
672 pub levels: Vec<crate::desktop::WindowLevel>,
674 pub max: Option<u32>,
677 pub overlay: bool,
679}
680
681impl WindowsGrant {
682 fn allows_kind(&self, kind: crate::desktop::WindowKind) -> bool {
683 use crate::desktop::WindowKind;
684 if kind == WindowKind::Overlay && !self.overlay {
685 return false;
686 }
687 self.kinds.is_empty() || self.kinds.contains(&kind)
688 }
689
690 fn allows_level(&self, level: crate::desktop::WindowLevel) -> bool {
691 self.levels.is_empty() || self.levels.contains(&level)
692 }
693}
694
695#[derive(Debug, Clone, PartialEq, Eq, Default)]
697#[non_exhaustive]
698pub struct OpenUrlGrant {
699 pub schemes: Vec<String>,
702}
703
704impl OpenUrlGrant {
705 pub fn allows(&self, scheme: &str) -> bool {
707 self.schemes.is_empty() || self.schemes.iter().any(|s| s == scheme)
708 }
709}
710
711#[derive(Debug, Clone, PartialEq, Eq)]
713pub struct UrlParts<'a> {
714 pub scheme: String,
716 pub host: String,
718 pub path: &'a str,
720 pub port: Option<u16>,
722}
723
724pub fn parse_url(url: &str) -> Option<UrlParts<'_>> {
729 read_url(url).ok()
730}
731
732pub(crate) fn grant_advice(url: &str, capability: &str) -> String {
736 match parse_url(url) {
737 Some(parts) => format!(
738 "add `{}` to capabilities.{capability} in nsh.json",
739 parts.host
740 ),
741 None => NO_HOST_ADVICE.to_owned(),
742 }
743}
744
745pub(crate) fn media_grant_advice(uri: &str, base: Option<&str>) -> String {
750 if native_relative(uri, base) {
751 return RELATIVE_ADVICE.to_owned();
752 }
753 if starts_with_ignoring_case(uri, "asset:") && !is_inside_assets(uri) {
754 return ASSET_ADVICE.to_owned();
755 }
756 if media_capability(uri, base) == "fs" {
757 return LOCAL_FILE_ADVICE.to_owned();
758 }
759 let unambiguous = !uri.contains('\\') && !uri.bytes().any(|b| b.is_ascii_control());
760 if scheme_of(uri).is_none() && uri.starts_with("//") && unambiguous {
761 let resolved = base
762 .and_then(|base| url::Url::parse(base).ok())
763 .and_then(|base| base.join(uri).ok());
764 return match resolved {
765 Some(url) => grant_advice(url.as_str(), "network"),
766 None => NO_SCHEME_ADVICE.to_owned(),
767 };
768 }
769 grant_advice(uri, "network")
770}
771
772pub(crate) fn media_capability(uri: &str, base: Option<&str>) -> &'static str {
776 if starts_with_ignoring_case(uri, "asset:") || native_relative(uri, base) {
777 return "fs";
778 }
779 let local =
780 (base.is_none() || starts_with_ignoring_case(uri, "file:")) && local_file(uri).is_some();
781 if local { "fs" } else { "network" }
782}
783
784const RELATIVE_ADVICE: &str = "a relative path names no file in a native app: name a bundled file as `asset:/…`, or import it";
786
787const ASSET_ADVICE: &str = "bundled files are named by a path inside the app's files";
790
791const LOCAL_FILE_ADVICE: &str = "a local file is read under capabilities.fs.read in nsh.json: add a root that holds it (desktop apps)";
793
794const NO_SCHEME_ADVICE: &str =
796 "it names no scheme and has no page to take one from: write it as an http(s) URL";
797
798const NO_HOST_ADVICE: &str = "it names no host a grant could add: write it as an http(s) URL with a host, a backslash as `%5C` and no control characters";
800
801fn is_own_media(uri: &str) -> bool {
805 ["asset:", "data:", "blob:"]
806 .iter()
807 .any(|prefix| starts_with_ignoring_case(uri, prefix))
808}
809
810pub fn is_inside_assets(url: &str) -> bool {
820 let Some(path) = url.get(6..).and_then(|rest| rest.strip_prefix('/')) else {
821 return false;
822 };
823 path.split('/').all(|segment| {
824 let bytes = segment.as_bytes();
825 let encoded = |code: &[u8; 3]| bytes.windows(3).any(|w| w.eq_ignore_ascii_case(code));
826 !only_dots(bytes)
827 && !bytes.iter().any(|b| matches!(b, b'\\' | b'\0' | b':'))
828 && ![b"%2f", b"%5c", b"%00", b"%3a"]
829 .iter()
830 .any(|code| encoded(code))
831 })
832}
833
834fn only_dots(segment: &[u8]) -> bool {
837 let (mut dots, mut at) = (0, 0);
838 while at < segment.len() {
839 if segment[at] == b'.' {
840 at += 1;
841 } else if segment[at..].len() >= 3
842 && segment[at] == b'%'
843 && segment[at + 1] == b'2'
844 && segment[at + 2].eq_ignore_ascii_case(&b'e')
845 {
846 at += 3;
847 } else {
848 return false;
849 }
850 dots += 1;
851 if dots > 2 {
852 return false;
853 }
854 }
855 true
856}
857
858fn names_host(uri: &str) -> bool {
861 let stripped = whatwg_stripped(uri);
862 scheme_of(&stripped).is_some()
863 || stripped.starts_with("//")
864 || stripped.starts_with('\\')
865 || stripped.starts_with("/\\")
866}
867
868fn native_relative(uri: &str, base: Option<&str>) -> bool {
871 base.is_none()
872 && !uri.trim().is_empty()
873 && !is_own_media(uri)
874 && local_file(uri).is_none()
875 && !names_host(uri)
876}
877
878fn path_as_sent(path: &str) -> Option<String> {
883 let path: String = path
885 .chars()
886 .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
887 .map(|c| if c == '\\' { '/' } else { c })
888 .collect();
889 let dots = path.split('/').any(|segment| {
890 let segment = segment.to_ascii_lowercase().replace("%2e", ".");
891 segment == "." || segment == ".."
892 });
893 if dots {
894 return None;
895 }
896 let url = url::Url::parse(&format!("http://h{path}")).ok()?;
897 Some(url.path().to_owned())
898}
899
900fn starts_with_ignoring_case(text: &str, prefix: &str) -> bool {
902 text.get(..prefix.len())
903 .is_some_and(|head| head.eq_ignore_ascii_case(prefix))
904}
905
906fn local_file(uri: &str) -> Option<Option<PathBuf>> {
911 if starts_with_ignoring_case(uri, "file:") {
912 return Some(file_url_path(uri));
913 }
914 let drive = matches!(uri.as_bytes(), [d, b':', b'\\' | b'/', ..] if d.is_ascii_alphabetic());
915 let rooted = uri.starts_with('/') && !uri.starts_with("//") && !uri.starts_with("/\\");
916 (drive || rooted).then(|| Some(PathBuf::from(uri)))
917}
918
919fn file_url_path(uri: &str) -> Option<PathBuf> {
921 #[cfg(target_arch = "wasm32")]
922 {
923 let _ = uri;
924 None
925 }
926 #[cfg(not(target_arch = "wasm32"))]
927 {
928 url::Url::parse(uri).ok()?.to_file_path().ok()
929 }
930}
931
932fn file_url_of(path: &Path) -> Option<String> {
934 #[cfg(target_arch = "wasm32")]
935 {
936 let _ = path;
937 None
938 }
939 #[cfg(not(target_arch = "wasm32"))]
940 {
941 url::Url::from_file_path(path).ok().map(String::from)
942 }
943}
944
945fn whatwg_stripped(uri: &str) -> Cow<'_, str> {
948 let trimmed = uri.trim_matches(|c: char| c <= ' ');
949 if trimmed.contains(['\t', '\n', '\r']) {
950 Cow::Owned(trimmed.replace(['\t', '\n', '\r'], ""))
951 } else {
952 Cow::Borrowed(trimmed)
953 }
954}
955
956fn scheme_of(uri: &str) -> Option<&str> {
958 let (scheme, _) = uri.split_once(':')?;
959 let mut chars = scheme.chars();
960 (chars.next()?.is_ascii_alphabetic()
961 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')))
962 .then_some(scheme)
963}
964
965fn media_as_written(uri: &str, allows_http: impl Fn(&str) -> bool) -> bool {
969 !uri.contains("://") || is_own_media(uri) || local_file(uri).is_some() || allows_http(uri)
970}
971
972fn written_or(written: &str, serialized: String) -> Cow<'_, str> {
974 if serialized == written {
975 Cow::Borrowed(written)
976 } else {
977 Cow::Owned(serialized)
978 }
979}
980
981enum Unread {
983 NotUrl,
985 Ambiguous(String),
988}
989
990fn read_url(url: &str) -> Result<UrlParts<'_>, Unread> {
992 let (scheme, rest) = url.split_once("://").ok_or(Unread::NotUrl)?;
993 if scheme.is_empty()
994 || !scheme
995 .chars()
996 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
997 {
998 return Err(Unread::NotUrl);
999 }
1000 let scheme = scheme.to_ascii_lowercase();
1001 let head = url.split(['?', '#']).next().unwrap_or(url);
1007 if head.contains('\\') || url.bytes().any(|b| b.is_ascii_control()) {
1008 return Err(Unread::Ambiguous(scheme));
1009 }
1010 let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
1011 let (authority, path) = rest.split_at(end);
1012 let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
1014 let host = if let Some(v6) = host_port.strip_prefix('[') {
1015 format!("[{}]", v6.split_once(']').ok_or(Unread::NotUrl)?.0)
1016 } else {
1017 host_port.split(':').next().unwrap_or_default().to_owned()
1018 };
1019 if host.is_empty() {
1020 return Err(Unread::NotUrl);
1021 }
1022 if host.contains(['%', ' ', '<', '>', '^', '|'])
1025 || (!host_port.starts_with('[') && host.contains(['[', ']']))
1026 {
1027 return Err(Unread::Ambiguous(scheme));
1028 }
1029 let port = if host_port.starts_with('[') {
1030 host_port
1031 .split_once(']')
1032 .and_then(|(_, rest)| rest.strip_prefix(':'))
1033 .map(str::parse::<u16>)
1034 .transpose()
1035 } else {
1036 host_port
1037 .split_once(':')
1038 .map(|(_, port)| port.parse::<u16>())
1039 .transpose()
1040 }
1041 .map_err(|_| Unread::NotUrl)?;
1042 Ok(UrlParts {
1043 scheme,
1044 host: host.to_ascii_lowercase().trim_end_matches('.').to_owned(),
1045 path: if path.is_empty() { "/" } else { path },
1046 port,
1047 })
1048}
1049
1050impl Capabilities {
1051 pub fn all() -> Self {
1055 let any = vec![HostPattern("*".into())];
1056 Self {
1057 network: NetworkGrants {
1058 hosts: any.clone(),
1059 http: Vec::new(),
1060 sockets: Vec::new(),
1061 },
1062 webview: Some(any),
1063 status_bar: true,
1064 clipboard: true,
1065 picker: true,
1066 speech: true,
1067 notifications: true,
1068 audio: true,
1069 open_url: Some(OpenUrlGrant::default()),
1070 windows: Some(WindowsGrant::default()),
1072 ..Self::default()
1074 }
1075 }
1076
1077 pub fn from_json(value: &Value) -> Result<Self, String> {
1082 Self::parse(value, None)
1083 }
1084
1085 pub fn from_json_lenient(value: &Value) -> Result<(Self, Vec<String>), String> {
1096 let mut dropped = Vec::new();
1097 let Value::Object(obj) = value else {
1098 dropped.push(format!(
1099 "capabilities ({value} is not an object): all of them"
1100 ));
1101 return Ok((Self::default(), dropped));
1102 };
1103 let mut readable = Map::new();
1105 for (key, v) in obj {
1106 let one = Value::Object(Map::from_iter([(key.clone(), v.clone())]));
1107 let mut its_dropped = Vec::new();
1108 match Self::parse(&one, Some(&mut its_dropped)) {
1109 Ok(_) => {
1110 dropped.append(&mut its_dropped);
1111 readable.insert(key.clone(), v.clone());
1112 }
1113 Err(e) => dropped.push(format!("capabilities.{key} ({e})")),
1114 }
1115 }
1116 let caps = Self::parse(&Value::Object(readable), Some(&mut Vec::new()))?;
1117 Ok((caps, dropped))
1118 }
1119
1120 fn parse(value: &Value, mut dropped: Option<&mut Vec<String>>) -> Result<Self, String> {
1123 const KNOWN: [&str; 13] = [
1124 "windows",
1125 "network",
1126 "webview",
1127 "statusBar",
1128 "clipboard",
1129 "picker",
1130 "speech",
1131 "notifications",
1132 "audio",
1133 "openUrl",
1134 "process",
1135 "fs",
1136 "host",
1137 ];
1138 let obj = object(value, "capabilities")?;
1139 for key in obj.keys().filter(|k| !KNOWN.contains(&k.as_str())) {
1140 match dropped.as_deref_mut() {
1141 Some(dropped) => dropped.push(format!("capabilities.{key}")),
1143 None => return Err(unknown_key("capabilities", key, &KNOWN)),
1144 }
1145 }
1146 let lenient = dropped.is_some();
1147 let mut http_dropped = Vec::new();
1150 let mut check = |obj: &Map<String, Value>,
1153 what: &str,
1154 keys: &[&str],
1155 name: &str|
1156 -> Result<bool, String> {
1157 let Some(key) = obj.keys().find(|k| !keys.contains(&k.as_str())) else {
1158 return Ok(true);
1159 };
1160 match dropped.as_deref_mut() {
1161 Some(dropped) => {
1162 dropped.push(format!("{name} (unknown key `{key}`)"));
1163 Ok(false)
1164 }
1165 None => Err(unknown_key(what, key, keys)),
1166 }
1167 };
1168 let mut caps = Capabilities::default();
1169 if let Some(network) = obj.get("network") {
1170 let network = object(network, "capabilities.network")?;
1171 if check(
1172 network,
1173 "capabilities.network",
1174 &["hosts", "http", "sockets"],
1175 "capabilities.network",
1176 )? {
1177 if let Some(hosts) = network.get("hosts") {
1178 caps.network.hosts = patterns(hosts, "capabilities.network.hosts")?;
1179 }
1180 if let Some(sockets) = network.get("sockets") {
1181 caps.network.sockets = strings(sockets, "capabilities.network.sockets")?
1182 .iter()
1183 .map(|s| SocketGrant::new(s))
1184 .collect::<Result<_, _>>()?;
1185 }
1186 if let Some(http) = network.get("http") {
1187 let list = http
1188 .as_array()
1189 .ok_or("capabilities.network.http must be an array")?;
1190 for (i, grant) in list.iter().enumerate() {
1191 let name = format!("capabilities.network.http[{i}]");
1192 let parsed = object(grant, "capabilities.network.http[]").and_then(|g| {
1193 let keys = [
1194 "host",
1195 "methods",
1196 "scheme",
1197 "schemes",
1198 "port",
1199 "paths",
1200 "pathPrefix",
1201 "pathPrefixes",
1202 "path_prefixes",
1203 ];
1204 Ok(
1205 match check(g, "capabilities.network.http[]", &keys, &name)? {
1206 true => Some(http_grant(g)?),
1207 false => None,
1208 },
1209 )
1210 });
1211 match parsed {
1212 Ok(Some(grant)) => caps.network.http.push(grant),
1213 Ok(None) => {}
1214 Err(e) if lenient => http_dropped.push(format!("{name} ({e})")),
1217 Err(e) => return Err(e),
1218 }
1219 }
1220 }
1221 }
1222 }
1223 if let Some(webview) = obj.get("webview") {
1224 let webview = object(webview, "capabilities.webview")?;
1225 if check(
1226 webview,
1227 "capabilities.webview",
1228 &["hosts", "input", "media"],
1229 "capabilities.webview",
1230 )? {
1231 caps.webview = Some(match webview.get("hosts") {
1232 Some(hosts) => patterns(hosts, "capabilities.webview.hosts")?,
1233 None => Vec::new(),
1234 });
1235 if let Some(input) = webview.get("input") {
1236 caps.webview_input = input
1237 .as_bool()
1238 .ok_or("capabilities.webview.input must be a boolean")?;
1239 }
1240 if let Some(media) = webview.get("media") {
1241 caps.webview_media = strings(media, "capabilities.webview.media")?
1242 .iter()
1243 .map(|kind| match kind.as_str() {
1244 "microphone" => Ok(WebMedia::Microphone),
1245 "camera" => Ok(WebMedia::Camera),
1246 _ => Err(format!(
1247 "capabilities.webview.media takes `microphone` and `camera`, not `{kind}`"
1248 )),
1249 })
1250 .collect::<Result<_, _>>()?;
1251 }
1252 }
1253 }
1254 if let Some(status_bar) = obj.get("statusBar") {
1255 caps.status_bar = status_bar
1256 .as_bool()
1257 .ok_or("capabilities.statusBar must be a boolean")?;
1258 }
1259 if let Some(clipboard) = obj.get("clipboard") {
1260 caps.clipboard = clipboard
1261 .as_bool()
1262 .ok_or("capabilities.clipboard must be a boolean")?;
1263 }
1264 if let Some(picker) = obj.get("picker") {
1265 caps.picker = picker
1266 .as_bool()
1267 .ok_or("capabilities.picker must be a boolean")?;
1268 }
1269 if let Some(speech) = obj.get("speech") {
1270 caps.speech = speech
1271 .as_bool()
1272 .ok_or("capabilities.speech must be a boolean")?;
1273 }
1274 if let Some(notifications) = obj.get("notifications") {
1275 caps.notifications = notifications
1276 .as_bool()
1277 .ok_or("capabilities.notifications must be a boolean")?;
1278 }
1279 if let Some(audio) = obj.get("audio") {
1280 caps.audio = audio
1281 .as_bool()
1282 .ok_or("capabilities.audio must be a boolean")?;
1283 }
1284 if let Some(open_url) = obj.get("openUrl") {
1285 match open_url {
1286 Value::Bool(granted) => {
1287 caps.open_url = granted.then(OpenUrlGrant::default);
1288 }
1289 Value::Object(grant) => {
1290 if check(
1291 grant,
1292 "capabilities.openUrl",
1293 &["schemes"],
1294 "capabilities.openUrl",
1295 )? {
1296 let schemes = match grant.get("schemes") {
1297 Some(schemes) => strings(schemes, "capabilities.openUrl.schemes")?,
1298 None => Vec::new(),
1299 };
1300 if schemes.iter().any(|s| {
1301 s.is_empty()
1302 || !s.starts_with(|c: char| c.is_ascii_alphabetic())
1303 || !s
1304 .chars()
1305 .all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c))
1306 }) {
1307 return Err(
1308 "capabilities.openUrl.schemes needs URL schemes (`https`, `mailto`)"
1309 .into(),
1310 );
1311 }
1312 caps.open_url = Some(OpenUrlGrant {
1313 schemes: schemes.iter().map(|s| s.to_ascii_lowercase()).collect(),
1314 });
1315 }
1316 }
1317 _ => {
1318 return Err(
1319 "capabilities.openUrl must be a boolean or an object of `schemes`".into(),
1320 );
1321 }
1322 }
1323 }
1324 if let Some(process) = obj.get("process") {
1325 let process = object(process, "capabilities.process")?;
1326 if check(
1327 process,
1328 "capabilities.process",
1329 &["execute", "exit", "env"],
1330 "capabilities.process",
1331 )? {
1332 if let Some(execute) = process.get("execute") {
1333 caps.process.execute = strings(execute, "capabilities.process.execute")?;
1334 if caps.process.execute.iter().any(|s| !valid_command(s)) {
1335 return Err("capabilities.process.execute needs exact executable names or absolute paths".into());
1336 }
1337 }
1338 if let Some(exit) = process.get("exit") {
1339 caps.process.exit = exit
1340 .as_bool()
1341 .ok_or("capabilities.process.exit must be a boolean")?;
1342 }
1343 if let Some(env) = process.get("env") {
1344 caps.process.env = strings(env, "capabilities.process.env")?;
1345 if caps
1346 .process
1347 .env
1348 .iter()
1349 .any(|name| name.is_empty() || name.contains(['=', '\0']))
1350 {
1351 return Err(
1352 "capabilities.process.env needs nonempty environment variable names"
1353 .into(),
1354 );
1355 }
1356 }
1357 }
1358 }
1359 if let Some(fs) = obj.get("fs") {
1360 let fs = object(fs, "capabilities.fs")?;
1361 if check(fs, "capabilities.fs", &["read", "write"], "capabilities.fs")? {
1362 for (key, target) in [("read", &mut caps.fs.read), ("write", &mut caps.fs.write)] {
1363 if let Some(value) = fs.get(key) {
1364 *target = strings(value, &format!("capabilities.fs.{key}"))?;
1365 for root in target.iter() {
1366 validate_path_pattern(root)?;
1367 }
1368 }
1369 }
1370 }
1371 }
1372 if let Some(windows) = obj.get("windows") {
1373 match windows {
1374 Value::Bool(granted) => caps.windows = granted.then(WindowsGrant::default),
1375 Value::Object(grant) => {
1376 if check(
1377 grant,
1378 "capabilities.windows",
1379 &["kinds", "levels", "max", "overlay"],
1380 "capabilities.windows",
1381 )? {
1382 caps.windows = Some(windows_grant(grant)?);
1383 }
1384 }
1385 _ => {
1386 return Err(
1387 "capabilities.windows must be a boolean or an object of `kinds`, `levels`, `max` and `overlay`"
1388 .into(),
1389 );
1390 }
1391 }
1392 }
1393 if let Some(host) = obj.get("host") {
1394 caps.host = match host {
1395 Value::Bool(all) => {
1396 if *all {
1397 vec!["*".into()]
1398 } else {
1399 Vec::new()
1400 }
1401 }
1402 _ => {
1403 let names = strings(host, "capabilities.host")
1404 .map_err(|e| format!("{e} (or a boolean)"))?;
1405 if let Some(bad) = names.iter().find(|n| match n.strip_suffix('*') {
1406 Some(prefix) => !prefix.is_empty() && !valid_host_name(prefix),
1407 None => !valid_host_name(n),
1408 }) {
1409 return Err(format!(
1410 "capabilities.host: invalid function `{bad}` (a name of {HOST_NAME_CHARS}, or a prefix of them ending in `*`)"
1411 ));
1412 }
1413 names
1414 }
1415 };
1416 }
1417 if let Some(dropped) = dropped {
1418 dropped.append(&mut http_dropped);
1419 }
1420 Ok(caps)
1421 }
1422
1423 pub fn to_json(&self) -> Value {
1425 let mut obj = self.to_json_without_windows();
1426 if let (Value::Object(obj), Some(w)) = (&mut obj, &self.windows) {
1428 let mut o = Map::new();
1429 if !w.kinds.is_empty() {
1430 o.insert(
1431 "kinds".into(),
1432 w.kinds
1433 .iter()
1434 .map(|k| window_kind_name(*k))
1435 .collect::<Vec<_>>()
1436 .into(),
1437 );
1438 }
1439 if !w.levels.is_empty() {
1440 o.insert(
1441 "levels".into(),
1442 w.levels
1443 .iter()
1444 .map(|l| window_level_name(*l))
1445 .collect::<Vec<_>>()
1446 .into(),
1447 );
1448 }
1449 if let Some(max) = w.max {
1450 o.insert("max".into(), max.into());
1451 }
1452 if w.overlay {
1453 o.insert("overlay".into(), true.into());
1454 }
1455 obj.insert("windows".into(), Value::Object(o));
1456 }
1457 obj
1458 }
1459
1460 fn to_json_without_windows(&self) -> Value {
1461 let list =
1462 |l: &[HostPattern]| Value::from(l.iter().map(|p| p.0.clone()).collect::<Vec<_>>());
1463 let mut network = Map::new();
1464 network.insert("hosts".into(), list(&self.network.hosts));
1465 let http: Vec<Value> = self
1466 .network
1467 .http
1468 .iter()
1469 .map(|g| {
1470 let mut o = Map::new();
1471 o.insert("host".into(), g.host.0.clone().into());
1472 if !g.methods.is_empty() {
1473 o.insert("methods".into(), g.methods.clone().into());
1474 }
1475 if !g.schemes.is_empty() {
1476 o.insert("schemes".into(), g.schemes.clone().into());
1477 }
1478 if let Some(port) = g.port {
1479 o.insert("port".into(), port.into());
1480 }
1481 if !g.paths.is_empty() {
1482 o.insert("paths".into(), g.paths.clone().into());
1483 }
1484 if !g.path_prefixes.is_empty() {
1485 o.insert("pathPrefixes".into(), g.path_prefixes.clone().into());
1486 }
1487 Value::Object(o)
1488 })
1489 .collect();
1490 network.insert("http".into(), http.into());
1491 if !self.network.sockets.is_empty() {
1492 let sockets: Vec<String> = self
1493 .network
1494 .sockets
1495 .iter()
1496 .map(SocketGrant::to_string_form)
1497 .collect();
1498 network.insert("sockets".into(), sockets.into());
1499 }
1500 let mut obj = Map::new();
1501 obj.insert("network".into(), Value::Object(network));
1502 obj.insert(
1503 "process".into(),
1504 serde_json::json!({"execute": self.process.execute, "exit": self.process.exit, "env": self.process.env}),
1505 );
1506 obj.insert(
1507 "fs".into(),
1508 serde_json::json!({"read": self.fs.read, "write": self.fs.write}),
1509 );
1510 if let Some(hosts) = &self.webview {
1511 let mut w = Map::new();
1512 w.insert("hosts".into(), list(hosts));
1513 if self.webview_input {
1515 w.insert("input".into(), true.into());
1516 }
1517 if !self.webview_media.is_empty() {
1518 let media = self.webview_media.iter().map(|m| m.as_str().into());
1519 w.insert("media".into(), Value::Array(media.collect()));
1520 }
1521 obj.insert("webview".into(), Value::Object(w));
1522 }
1523 obj.insert("statusBar".into(), self.status_bar.into());
1524 obj.insert("clipboard".into(), self.clipboard.into());
1525 obj.insert("picker".into(), self.picker.into());
1526 if self.speech {
1528 obj.insert("speech".into(), true.into());
1529 }
1530 if self.notifications {
1531 obj.insert("notifications".into(), true.into());
1532 }
1533 if self.audio {
1534 obj.insert("audio".into(), true.into());
1535 }
1536 if !self.host.is_empty() {
1537 obj.insert("host".into(), self.host.clone().into());
1538 }
1539 obj.insert(
1540 "openUrl".into(),
1541 match &self.open_url {
1542 None => false.into(),
1543 Some(grant) if grant.schemes.is_empty() => true.into(),
1544 Some(grant) => serde_json::json!({ "schemes": grant.schemes }),
1545 },
1546 );
1547 Value::Object(obj)
1548 }
1549
1550 fn allows_http(&self, method: &str, url: &UrlParts<'_>) -> bool {
1551 if !matches!(url.scheme.as_str(), "http" | "https" | "ws" | "wss") {
1552 return false;
1553 }
1554 self.network.hosts.iter().any(|h| h.matches(&url.host))
1555 || self.network.http.iter().any(|g| g.allows(method, url))
1556 }
1557
1558 fn allows_http_anywhere(&self, method: &str, scheme: &str) -> bool {
1560 matches!(scheme, "http" | "https" | "ws" | "wss")
1561 && (self.network.hosts.iter().any(HostPattern::is_any)
1562 || self
1563 .network
1564 .http
1565 .iter()
1566 .any(|g| g.allows_anywhere(method, scheme)))
1567 }
1568
1569 fn allows_host(&self, name: &str) -> bool {
1570 self.host.iter().any(|g| match g.strip_suffix('*') {
1571 Some(prefix) => name.starts_with(prefix),
1572 None => g == name,
1573 })
1574 }
1575
1576 fn allows_webview(&self, url: &UrlParts<'_>) -> bool {
1577 matches!(url.scheme.as_str(), "http" | "https")
1578 && self
1579 .webview
1580 .as_ref()
1581 .is_some_and(|hosts| hosts.iter().any(|h| h.matches(&url.host)))
1582 }
1583
1584 fn allows_webview_anywhere(&self, scheme: &str) -> bool {
1586 matches!(scheme, "http" | "https")
1587 && self
1588 .webview
1589 .as_ref()
1590 .is_some_and(|hosts| hosts.iter().any(HostPattern::is_any))
1591 }
1592}
1593
1594pub const HOST_NAME_CHARS: &str = "1 to 128 of A-Z a-z 0-9 _ . : -, without `..`";
1596
1597pub fn valid_host_name(name: &str) -> bool {
1601 (1..=128).contains(&name.len())
1602 && name
1603 .bytes()
1604 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b':' | b'-'))
1605 && !name.contains("..")
1606}
1607
1608fn valid_command(command: &str) -> bool {
1609 !command.is_empty()
1610 && !command.contains(['\0', '*'])
1611 && (absolute(Path::new(command))
1615 || (!command.contains(['/', '\\', ':']) && command != "." && command != ".."))
1618}
1619
1620fn validate_path_pattern(path: &str) -> Result<(), String> {
1621 if [
1622 "$HOME",
1623 "${HOME}",
1624 "$USERPROFILE",
1625 "${USERPROFILE}",
1626 "%USERPROFILE%",
1627 "~",
1628 ]
1629 .into_iter()
1630 .any(|prefix| {
1631 path.strip_prefix(prefix)
1632 .is_some_and(|tail| tail.is_empty() || tail.starts_with(['/', '\\']))
1633 }) {
1634 return Err("use ${homeDir} for the native home directory".into());
1635 }
1636 let placeholder = ["${dataDir}", "${pluginDir}", "${homeDir}"]
1637 .into_iter()
1638 .find(|prefix| path.starts_with(prefix));
1639 let tail = placeholder.and_then(|prefix| path.strip_prefix(prefix));
1640 if path.is_empty()
1641 || path.contains(['\0', '*'])
1642 || tail.is_some_and(|s| !s.is_empty() && !s.starts_with('/'))
1643 || (placeholder.is_none() && path.contains("${"))
1644 || tail.is_some_and(|s| s.contains("${"))
1645 || Path::new(path)
1646 .components()
1647 .any(|p| matches!(p, Component::ParentDir))
1648 {
1649 return Err(
1650 "filesystem roots must use valid host placeholders and contain no traversal".into(),
1651 );
1652 }
1653 Ok(())
1654}
1655
1656pub fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
1662 let path = std::fs::canonicalize(path)?;
1663 #[cfg(windows)]
1664 if let Some(plain) = path.to_str().and_then(without_verbatim_prefix) {
1665 return Ok(PathBuf::from(plain));
1666 }
1667 Ok(path)
1668}
1669
1670#[cfg_attr(not(windows), allow(dead_code))]
1678fn without_verbatim_prefix(path: &str) -> Option<String> {
1679 let rest = path.strip_prefix(r"\\?\")?;
1680 let (plain, tail) = if let Some(unc) = rest.strip_prefix(r"UNC\") {
1681 (format!(r"\\{unc}"), unc)
1682 } else {
1683 let bytes = rest.as_bytes();
1684 if bytes.len() < 3 || !bytes[0].is_ascii_alphabetic() || &bytes[1..3] != b":\\" {
1685 return None;
1686 }
1687 (rest.to_owned(), &rest[3..])
1688 };
1689 if plain.len() >= 260 {
1690 return None;
1691 }
1692 let tail = tail.strip_suffix('\\').unwrap_or(tail);
1694 let device = |name: &str| {
1695 let stem = name.split('.').next().unwrap_or(name).trim_end();
1696 ["CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"]
1697 .iter()
1698 .any(|d| stem.eq_ignore_ascii_case(d))
1699 || (stem.len() == 4
1700 && ["COM", "LPT"]
1701 .iter()
1702 .any(|d| stem[..3].eq_ignore_ascii_case(d))
1703 && matches!(stem.as_bytes()[3], b'1'..=b'9'))
1704 };
1705 let plain_component = |c: &str| {
1706 !c.is_empty()
1707 && c != "."
1708 && c != ".."
1709 && !c.contains('/')
1710 && !c.ends_with(['.', ' '])
1711 && !device(c)
1712 };
1713 (tail.is_empty() || tail.split('\\').all(plain_component)).then_some(plain)
1714}
1715
1716#[derive(Debug, Clone, PartialEq, Eq)]
1720#[non_exhaustive]
1721pub enum FileRefusal {
1722 Invalid(String),
1725 NotGranted(String),
1727}
1728
1729impl std::fmt::Display for FileRefusal {
1730 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1731 match self {
1732 FileRefusal::Invalid(why) | FileRefusal::NotGranted(why) => f.write_str(why),
1733 }
1734 }
1735}
1736
1737fn resolved_path(path: &Path) -> Result<PathBuf, String> {
1738 if !absolute(path) || path.components().any(|p| matches!(p, Component::ParentDir)) {
1739 return Err("filesystem paths must be absolute and contain no parent traversal".into());
1740 }
1741 let mut cursor = path;
1742 let mut tail = Vec::new();
1743 loop {
1744 match std::fs::symlink_metadata(cursor) {
1745 Ok(_) => {
1746 let mut resolved = canonicalize(cursor).map_err(|e| e.to_string())?;
1747 for part in tail.into_iter().rev() {
1748 resolved.push(part);
1749 }
1750 return Ok(resolved);
1751 }
1752 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1753 tail.push(
1754 cursor
1755 .file_name()
1756 .ok_or("invalid filesystem path")?
1757 .to_owned(),
1758 );
1759 cursor = cursor.parent().ok_or("invalid filesystem path")?;
1760 }
1761 Err(e) => return Err(e.to_string()),
1762 }
1763 }
1764}
1765
1766fn object<'a>(value: &'a Value, what: &str) -> Result<&'a Map<String, Value>, String> {
1767 value
1768 .as_object()
1769 .ok_or_else(|| format!("{what} must be an object"))
1770}
1771
1772const WINDOW_KINDS: [(&str, crate::desktop::WindowKind); 5] = [
1773 ("normal", crate::desktop::WindowKind::Normal),
1774 ("dialog", crate::desktop::WindowKind::Dialog),
1775 ("panel", crate::desktop::WindowKind::Panel),
1776 ("popup", crate::desktop::WindowKind::Popup),
1777 ("overlay", crate::desktop::WindowKind::Overlay),
1778];
1779
1780const WINDOW_LEVELS: [(&str, crate::desktop::WindowLevel); 4] = [
1781 ("normal", crate::desktop::WindowLevel::Normal),
1782 ("floating", crate::desktop::WindowLevel::Floating),
1783 ("aboveDock", crate::desktop::WindowLevel::AboveDock),
1784 ("desktopIcon", crate::desktop::WindowLevel::DesktopIcon),
1785];
1786
1787fn window_kind_name(kind: crate::desktop::WindowKind) -> &'static str {
1788 WINDOW_KINDS
1789 .iter()
1790 .find(|(_, k)| *k == kind)
1791 .map_or("normal", |(n, _)| n)
1792}
1793
1794fn window_level_name(level: crate::desktop::WindowLevel) -> &'static str {
1795 WINDOW_LEVELS
1796 .iter()
1797 .find(|(_, l)| *l == level)
1798 .map_or("normal", |(n, _)| n)
1799}
1800
1801fn windows_grant(grant: &Map<String, Value>) -> Result<WindowsGrant, String> {
1803 let mut out = WindowsGrant::default();
1804 if let Some(kinds) = grant.get("kinds") {
1805 for name in strings(kinds, "capabilities.windows.kinds")? {
1806 let Some((_, kind)) = WINDOW_KINDS.iter().find(|(n, _)| *n == name) else {
1807 return Err(format!(
1808 "capabilities.windows.kinds: unknown kind `{name}` (normal, dialog, panel, popup or overlay)"
1809 ));
1810 };
1811 out.kinds.push(*kind);
1812 }
1813 }
1814 if let Some(levels) = grant.get("levels") {
1815 for name in strings(levels, "capabilities.windows.levels")? {
1816 let Some((_, level)) = WINDOW_LEVELS.iter().find(|(n, _)| *n == name) else {
1817 return Err(format!(
1818 "capabilities.windows.levels: unknown level `{name}` (normal, floating, aboveDock or desktopIcon)"
1819 ));
1820 };
1821 out.levels.push(*level);
1822 }
1823 }
1824 if let Some(max) = grant.get("max") {
1825 out.max = Some(
1826 max.as_u64()
1827 .and_then(|m| u32::try_from(m).ok())
1828 .ok_or("capabilities.windows.max must be a whole number")?,
1829 );
1830 }
1831 if let Some(v) = grant.get("overlay") {
1832 out.overlay = v
1833 .as_bool()
1834 .ok_or("capabilities.windows.overlay must be a boolean")?;
1835 }
1836 Ok(out)
1837}
1838
1839fn unknown_key(what: &str, key: &str, known: &[&str]) -> String {
1840 format!("{what}: unknown key `{key}` (known: {})", known.join(", "))
1841}
1842
1843fn strings(value: &Value, what: &str) -> Result<Vec<String>, String> {
1844 value
1845 .as_array()
1846 .and_then(|a| a.iter().map(|v| v.as_str().map(str::to_owned)).collect())
1847 .ok_or_else(|| format!("{what} must be an array of strings"))
1848}
1849
1850fn http_grant(g: &Map<String, Value>) -> Result<HttpGrant, String> {
1854 let what = "capabilities.network.http[]";
1855 let host = g
1856 .get("host")
1857 .and_then(Value::as_str)
1858 .ok_or_else(|| format!("{what} needs a `host`"))?;
1859 let list = |key: &str| -> Result<Vec<String>, String> {
1861 match g.get(key) {
1862 None => Ok(Vec::new()),
1863 Some(Value::String(s)) => Ok(vec![s.clone()]),
1864 Some(v) => strings(v, &format!("{what}.{key}")),
1865 }
1866 };
1867 let methods = list("methods")?
1868 .into_iter()
1869 .map(|m| {
1870 if !m.is_empty() && m.bytes().all(|b| b.is_ascii_alphabetic() || b == b'-') {
1871 Ok(m.to_ascii_uppercase())
1872 } else {
1873 Err(format!("{what}.methods: `{m}` is not an HTTP method"))
1874 }
1875 })
1876 .collect::<Result<Vec<_>, _>>()?;
1877 let mut schemes = Vec::new();
1878 for scheme in list("scheme")?.into_iter().chain(list("schemes")?) {
1879 let scheme = scheme.to_ascii_lowercase();
1880 if !matches!(scheme.as_str(), "http" | "https" | "ws" | "wss") {
1881 return Err(format!(
1882 "{what}.schemes: `{scheme}` is not http, https, ws or wss"
1883 ));
1884 }
1885 if !schemes.contains(&scheme) {
1886 schemes.push(scheme);
1887 }
1888 }
1889 let port = match g.get("port") {
1890 None => None,
1891 Some(v) => Some(
1892 v.as_u64()
1893 .and_then(|p| u16::try_from(p).ok())
1894 .filter(|&p| p != 0)
1895 .ok_or_else(|| format!("{what}.port must be a port from 1 to 65535"))?,
1896 ),
1897 };
1898 let paths = list("paths")?;
1899 let mut path_prefixes = Vec::new();
1900 for prefix in list("pathPrefix")?
1901 .into_iter()
1902 .chain(list("pathPrefixes")?)
1903 .chain(list("path_prefixes")?)
1904 {
1905 if !path_prefixes.contains(&prefix) {
1906 path_prefixes.push(prefix);
1907 }
1908 }
1909 if let Some(bad) = paths
1911 .iter()
1912 .chain(&path_prefixes)
1913 .find(|p| !p.starts_with('/') || p.contains(['*', '?', '#']))
1914 {
1915 return Err(format!(
1916 "{what}: path `{bad}` must start with / and has no `*`, `?` or `#` (paths match as written)"
1917 ));
1918 }
1919 let as_sent = |list: Vec<String>| -> Result<Vec<String>, String> {
1922 let mut sent = Vec::new();
1923 for path in list {
1924 let path = path_as_sent(&path).ok_or_else(|| {
1925 format!("{what}: path `{path}` has a `.` or `..` segment, which no request sends")
1926 })?;
1927 if !sent.contains(&path) {
1928 sent.push(path);
1929 }
1930 }
1931 Ok(sent)
1932 };
1933 let paths = as_sent(paths)?;
1934 let path_prefixes = as_sent(path_prefixes)?;
1935 Ok(HttpGrant {
1936 host: HostPattern::new(host)?,
1937 methods,
1938 schemes,
1939 port,
1940 paths,
1941 path_prefixes,
1942 })
1943}
1944
1945fn patterns(value: &Value, what: &str) -> Result<Vec<HostPattern>, String> {
1946 strings(value, what)?
1947 .iter()
1948 .map(|p| HostPattern::new(p))
1949 .collect()
1950}
1951
1952#[derive(Debug, Clone, PartialEq, Eq)]
1955pub struct Access {
1956 pub declared: Capabilities,
1958 pub granted: Option<Capabilities>,
1960}
1961
1962impl Default for Access {
1963 fn default() -> Self {
1964 Self::all()
1965 }
1966}
1967
1968impl Access {
1969 pub fn all() -> Self {
1971 Self {
1972 declared: Capabilities::all(),
1973 granted: None,
1974 }
1975 }
1976
1977 fn each(&self, f: impl Fn(&Capabilities) -> bool) -> bool {
1978 f(&self.declared) && self.granted.as_ref().is_none_or(f)
1979 }
1980
1981 pub fn is_unrestricted(&self) -> bool {
1984 let all = Capabilities::all();
1985 self.declared == all && self.granted.as_ref().is_none_or(|g| *g == all)
1986 }
1987
1988 pub fn allows_process(&self, command: &str) -> bool {
1991 valid_command(command) && self.each(|c| c.process.execute.iter().any(|p| p == command))
1992 }
1993
1994 pub fn allows_exit(&self) -> bool {
1997 self.each(|caps| caps.process.exit)
1998 }
1999
2000 pub fn allows_env(&self, name: &str) -> bool {
2003 let defaults = include_str!("default-env").lines().filter_map(|line| {
2004 let name = line.split('#').next().unwrap_or_default().trim();
2005 (!name.is_empty()).then_some(name)
2006 });
2007 defaults
2008 .into_iter()
2009 .any(|allowed| env_names_match(allowed, name))
2010 || self.each(|caps| {
2011 caps.process
2012 .env
2013 .iter()
2014 .any(|allowed| env_names_match(allowed, name))
2015 })
2016 }
2017
2018 pub fn authorize_file(
2021 &self,
2022 path: &Path,
2023 data_dir: &Path,
2024 write: bool,
2025 ) -> Result<PathBuf, FileRefusal> {
2026 self.authorize_file_with_paths(path, data_dir, &TrustedPaths::default(), write)
2027 }
2028
2029 pub fn authorize_file_with_paths(
2031 &self,
2032 path: &Path,
2033 data_dir: &Path,
2034 paths: &TrustedPaths,
2035 write: bool,
2036 ) -> Result<PathBuf, FileRefusal> {
2037 let requested = if let Some(text) = path.to_str().filter(|s| s.starts_with("${")) {
2038 paths
2039 .resolve_root(text, data_dir)
2040 .map_err(FileRefusal::Invalid)?
2041 } else {
2042 path.to_owned()
2043 };
2044 let resolved = resolved_path(&requested).map_err(FileRefusal::Invalid)?;
2045 let allowed = self.each(|c| {
2046 let roots = if write { &c.fs.write } else { &c.fs.read };
2047 roots.iter().any(|root| {
2048 paths
2049 .resolve_root(root, data_dir)
2050 .and_then(|r| resolved_path(&r))
2051 .is_ok_and(|root| resolved.starts_with(root))
2052 })
2053 });
2054 if allowed {
2055 Ok(resolved)
2056 } else {
2057 Err(FileRefusal::NotGranted(format!(
2058 "filesystem {} is not granted by capabilities.fs",
2059 if write { "write" } else { "read" }
2060 )))
2061 }
2062 }
2063
2064 pub fn allows_socket(&self, host: &str, port: u16) -> bool {
2068 if host.is_empty() || host.contains(['/', '@', '?', '#', '\0']) {
2069 return false;
2070 }
2071 let host = host.to_ascii_lowercase();
2072 let host = host
2073 .strip_prefix('[')
2074 .and_then(|h| h.strip_suffix(']'))
2075 .unwrap_or(&host)
2076 .trim_end_matches('.');
2077 self.each(|c| {
2078 c.network
2079 .sockets
2080 .iter()
2081 .any(|grant| grant.port == port && grant.host == host)
2082 })
2083 }
2084
2085 pub fn allows_websocket(&self, url: &str) -> bool {
2089 let http = if let Some(rest) = url.strip_prefix("wss:") {
2090 format!("https:{rest}")
2091 } else if let Some(rest) = url.strip_prefix("ws:") {
2092 format!("http:{rest}")
2093 } else {
2094 return false;
2095 };
2096 self.allows_http("GET", &http) || self.allows_http("GET", url)
2097 }
2098
2099 pub fn allows_http(&self, method: &str, url: &str) -> bool {
2102 if url.starts_with("asset:") {
2103 return true;
2104 }
2105 match read_url(url) {
2106 Ok(parts) => {
2108 url::Url::parse(url).is_ok_and(|whatwg| self.allows_parts(method, parts, &whatwg))
2109 }
2110 Err(Unread::Ambiguous(scheme)) => {
2112 self.each(|c| c.allows_http_anywhere(method, &scheme))
2113 }
2114 Err(Unread::NotUrl) => false,
2115 }
2116 }
2117
2118 fn allows_parsed(&self, method: &str, url: &str, whatwg: &url::Url) -> bool {
2123 match read_url(url) {
2124 Ok(parts) => self.allows_parts(method, parts, whatwg),
2125 Err(Unread::Ambiguous(scheme)) => {
2126 self.each(|c| c.allows_http_anywhere(method, &scheme))
2127 }
2128 Err(Unread::NotUrl) => false,
2129 }
2130 }
2131
2132 fn allows_parts(&self, method: &str, parts: UrlParts<'_>, whatwg: &url::Url) -> bool {
2135 let parts = UrlParts {
2136 path: whatwg.path(),
2137 ..parts
2138 };
2139 self.each(|c| c.allows_http(method, &parts))
2140 }
2141
2142 pub fn http_url<'a>(&self, method: &str, url: &'a str) -> Option<Cow<'a, str>> {
2146 if url.starts_with("asset:") {
2147 return Some(Cow::Borrowed(url));
2148 }
2149 let whatwg = url::Url::parse(url).ok()?;
2150 self.allows_parsed(method, whatwg.as_str(), &whatwg)
2151 .then(|| written_or(url, whatwg.into()))
2152 }
2153
2154 pub fn allows_media(&self, uri: &str) -> bool {
2158 self.media_url(uri, None, None).is_some()
2159 }
2160
2161 pub fn media_url<'a>(
2181 &self,
2182 uri: &'a str,
2183 base: Option<&str>,
2184 files: Option<&MediaFiles>,
2185 ) -> Option<Cow<'a, str>> {
2186 if is_own_media(uri) {
2187 let inside = !starts_with_ignoring_case(uri, "asset:") || is_inside_assets(uri);
2190 return (inside || self.is_unrestricted()).then_some(Cow::Borrowed(uri));
2191 }
2192 if self.is_unrestricted() {
2193 return media_as_written(uri, |url| self.allows_http("GET", url))
2194 .then_some(Cow::Borrowed(uri));
2195 }
2196 let file_url = starts_with_ignoring_case(uri, "file:");
2197 if (base.is_none() || file_url)
2198 && let Some(path) = local_file(uri)
2199 {
2200 let real = files?.readable(&path?)?;
2201 let loads = if file_url {
2202 file_url_of(&real)?
2203 } else {
2204 real.into_os_string().into_string().ok()?
2205 };
2206 return Some(written_or(uri, loads));
2207 }
2208 let stripped = whatwg_stripped(uri);
2211 let scheme = scheme_of(&stripped);
2212 let names_host = scheme.is_some()
2213 || stripped.starts_with("//")
2214 || stripped.starts_with(['\\'])
2215 || stripped.starts_with("/\\");
2216 if !names_host {
2217 return (base.is_some() || uri.trim().is_empty()).then_some(Cow::Borrowed(uri));
2221 }
2222 let base = || base.and_then(|b| url::Url::parse(b).ok());
2224 let trimmed = uri.trim_matches(|c: char| c <= ' ');
2230 let head = trimmed.split(['?', '#']).next().unwrap_or(trimmed);
2231 if head.contains('\\')
2232 || trimmed.bytes().any(|b| b.is_ascii_control())
2233 || matches!(read_url(trimmed), Err(Unread::Ambiguous(_)))
2234 {
2235 let scheme = match scheme {
2236 Some(scheme) => scheme.to_ascii_lowercase(),
2237 None => base()?.scheme().to_owned(),
2238 };
2239 return self
2240 .each(|c| c.allows_http_anywhere("GET", &scheme))
2241 .then_some(Cow::Borrowed(uri));
2242 }
2243 let parsed = match scheme {
2244 Some(_) => url::Url::parse(trimmed),
2245 None => base()?.join(trimmed),
2246 }
2247 .ok()?;
2248 self.allows_parsed("GET", parsed.as_str(), &parsed)
2249 .then(|| written_or(uri, parsed.into()))
2250 }
2251
2252 pub fn media_redirect(&self, base: &str, location: &str) -> Result<String, String> {
2258 let url = resolve_reference(base, location);
2259 if !(url.starts_with("http://") || url.starts_with("https://")) {
2260 return Err(format!("redirect to `{url}` is not an http(s) URL"));
2261 }
2262 if !self.is_unrestricted() && !self.allows_media(&url) {
2263 return Err(format!(
2264 "redirect to `{url}` is not granted by capabilities.network"
2265 ));
2266 }
2267 Ok(url)
2268 }
2269
2270 pub fn allows_webviews(&self) -> bool {
2272 self.each(|c| c.webview.is_some())
2273 }
2274
2275 pub fn allows_webview(&self, url: &str) -> bool {
2278 if url == "about:blank" {
2279 return self.allows_webviews();
2280 }
2281 match read_url(url) {
2282 Ok(parts) => self.each(|c| c.allows_webview(&parts)),
2283 Err(Unread::Ambiguous(scheme)) => self.each(|c| c.allows_webview_anywhere(&scheme)),
2284 Err(Unread::NotUrl) => false,
2285 }
2286 }
2287
2288 pub fn allows_web_input(&self) -> bool {
2291 self.each(|c| c.webview.is_some() && c.webview_input)
2292 }
2293
2294 pub fn allows_web_media(&self, media: WebMedia) -> bool {
2298 self.each(|c| c.webview.is_some() && c.webview_media.contains(&media))
2299 }
2300
2301 pub fn check_window(
2306 &self,
2307 kind: crate::desktop::WindowKind,
2308 attributes: &crate::desktop::WindowAttributes,
2309 open: usize,
2310 ) -> Result<(), String> {
2311 if !self.each(|c| c.windows.is_some()) {
2312 return Err("windows of the app's own are not granted by capabilities.windows".into());
2313 }
2314 if !self.each(|c| c.windows.as_ref().is_some_and(|w| w.allows_kind(kind))) {
2315 return Err(format!(
2316 "a window of kind `{}` is not granted by capabilities.windows{}",
2317 window_kind_name(kind),
2318 if kind == crate::desktop::WindowKind::Overlay {
2319 " (overlays need `overlay: true`)"
2320 } else {
2321 ""
2322 }
2323 ));
2324 }
2325 if !self.each(|c| {
2326 c.windows
2327 .as_ref()
2328 .is_some_and(|w| w.max.is_none_or(|max| open < max as usize))
2329 }) {
2330 return Err("capabilities.windows.max windows are open already".into());
2331 }
2332 let mut own = attributes.clone();
2333 let level = own.level.take();
2335 let denied = self.deny_window_attributes(&mut own);
2336 if let Some(name) = denied.first() {
2337 return Err(format!(
2338 "the window attribute `{name}` is not granted by capabilities.windows"
2339 ));
2340 }
2341 if let Some(level) = level
2342 && !self.each(|c| c.windows.as_ref().is_some_and(|w| w.allows_level(level)))
2343 {
2344 return Err(format!(
2345 "the window level `{}` is not granted by capabilities.windows.levels",
2346 window_level_name(level)
2347 ));
2348 }
2349 Ok(())
2350 }
2351
2352 pub fn deny_window_attributes(
2358 &self,
2359 attributes: &mut crate::desktop::WindowAttributes,
2360 ) -> Vec<&'static str> {
2361 let mut denied = Vec::new();
2362 let grant = |f: &dyn Fn(&WindowsGrant) -> bool| {
2363 self.each(|c| match &c.windows {
2364 Some(w) => f(w),
2365 None => false,
2367 })
2368 };
2369 if let Some(level) = attributes.level
2370 && level != crate::desktop::WindowLevel::Normal
2371 && !grant(&|w| w.allows_level(level))
2372 {
2373 attributes.level = None;
2374 denied.push("level");
2375 }
2376 if attributes.passes_pointer() && !grant(&|w| w.overlay) {
2377 attributes.pointer_events = None;
2378 denied.push("pointerEvents");
2379 }
2380 denied
2381 }
2382
2383 pub fn allows_status_bar(&self) -> bool {
2385 self.each(|c| c.status_bar)
2386 }
2387
2388 pub fn allows_clipboard(&self) -> bool {
2390 self.each(|c| c.clipboard)
2391 }
2392
2393 pub fn allows_picker(&self) -> bool {
2395 self.each(|c| c.picker)
2396 }
2397
2398 pub fn allows_speech(&self) -> bool {
2400 self.each(|c| c.speech)
2401 }
2402
2403 pub fn allows_notifications(&self) -> bool {
2406 self.each(|c| c.notifications)
2407 }
2408
2409 pub fn allows_audio(&self) -> bool {
2411 self.each(|c| c.audio)
2412 }
2413
2414 pub fn allows_host(&self, name: &str) -> bool {
2416 self.each(|c| c.allows_host(name))
2417 }
2418
2419 pub fn allows_open_url(&self, url: &str) -> bool {
2422 let Some(scheme) = url
2423 .split_once(':')
2424 .map(|(scheme, _)| scheme.to_ascii_lowercase())
2425 else {
2426 return false;
2427 };
2428 self.each(|c| c.open_url.as_ref().is_some_and(|g| g.allows(&scheme)))
2429 }
2430}
2431
2432pub fn resolve_reference(base: &str, location: &str) -> String {
2438 match url::Url::parse(base).and_then(|base| base.join(location)) {
2439 Ok(url) => url.into(),
2440 Err(_) => location.to_owned(),
2441 }
2442}
2443
2444#[cfg(test)]
2445mod tests {
2446 #[test]
2447 fn verbatim_windows_paths_compare_in_their_plain_form() {
2448 use super::without_verbatim_prefix as plain;
2449 assert_eq!(plain(r"\\?\C:\Users\a").as_deref(), Some(r"C:\Users\a"));
2450 assert_eq!(plain(r"\\?\d:\").as_deref(), Some(r"d:\"));
2451 assert_eq!(plain(r"\\?\C:\app\").as_deref(), Some(r"C:\app\"));
2452 assert_eq!(
2453 plain(r"\\?\UNC\server\share\a").as_deref(),
2454 Some(r"\\server\share\a")
2455 );
2456 for path in [
2458 r"C:\a",
2459 r"\\server\share",
2460 "/home/a",
2461 r"\\?\Volume{x}\a",
2462 r"\\.\C:\a",
2463 ] {
2464 assert_eq!(plain(path), None, "{path}");
2465 }
2466 for path in [
2468 r"\\?\C:\a\NUL",
2469 r"\\?\C:\a\com1.txt",
2470 r"\\?\C:\a\Lpt9",
2471 r"\\?\C:\a\b.",
2472 r"\\?\C:\a\b ",
2473 r"\\?\C:\a\..\b",
2474 r"\\?\C:\a\.\b",
2475 r"\\?\C:\a\\b",
2476 r"\\?\C:\a/b",
2477 ] {
2478 assert_eq!(plain(path), None, "{path}");
2479 }
2480 assert_eq!(
2481 plain(r"\\?\C:\a\com10\console").as_deref(),
2482 Some(r"C:\a\com10\console")
2483 );
2484 let long = format!(r"\\?\C:\{}", "a".repeat(260));
2485 assert_eq!(plain(&long), None);
2486 }
2487
2488 #[test]
2489 fn anchored_roots_join_their_tail_component_by_component() {
2490 let app = PathBuf::from(if cfg!(windows) { r"C:\app" } else { "/app" });
2491 let paths = super::TrustedPaths {
2492 plugin_dir: Some(app.clone()),
2493 home_dir: None,
2494 };
2495 let root = paths.resolve_root("${pluginDir}/a//b/", &app).unwrap();
2496 assert_eq!(root, app.join("a").join("b"));
2497 let names = root.components().rev().take(2).collect::<Vec<_>>();
2498 assert_eq!(
2499 names,
2500 [
2501 Component::Normal("b".as_ref()),
2502 Component::Normal("a".as_ref())
2503 ]
2504 );
2505 }
2506 use std::cell::Cell;
2507
2508 use super::*;
2509
2510 fn caps(json: &str) -> Capabilities {
2511 Capabilities::from_json(&serde_json::from_str(json).unwrap()).unwrap()
2512 }
2513
2514 #[test]
2515 fn windows_are_granted_by_kind_level_and_count() {
2516 use crate::desktop::{WindowAttributes, WindowKind, WindowLevel, WindowPointerEvents};
2517 let none = WindowAttributes::default();
2518 let all = Access::all();
2521 assert!(all.check_window(WindowKind::Panel, &none, 10).is_ok());
2522 assert!(all.check_window(WindowKind::Overlay, &none, 0).is_err());
2523 let click_through = WindowAttributes {
2524 pointer_events: Some(WindowPointerEvents::None),
2525 ..Default::default()
2526 };
2527 assert!(
2528 all.check_window(WindowKind::Normal, &click_through, 0)
2529 .is_err()
2530 );
2531 let declared = |json: &str| Access {
2533 declared: caps(json),
2534 granted: None,
2535 };
2536 assert!(
2537 declared(r#"{"process":{"exit":true}}"#)
2538 .check_window(WindowKind::Normal, &none, 0)
2539 .is_err()
2540 );
2541 let limited = declared(
2542 r#"{"windows":{"kinds":["normal","dialog"],"levels":["normal","floating"],"max":2}}"#,
2543 );
2544 assert!(limited.check_window(WindowKind::Dialog, &none, 1).is_ok());
2545 assert!(limited.check_window(WindowKind::Popup, &none, 0).is_err());
2546 assert!(limited.check_window(WindowKind::Normal, &none, 2).is_err());
2547 let above = WindowAttributes {
2548 level: Some(WindowLevel::AboveDock),
2549 ..Default::default()
2550 };
2551 assert!(limited.check_window(WindowKind::Normal, &above, 0).is_err());
2552 let overlay = declared(r#"{"windows":{"overlay":true}}"#);
2553 assert!(
2554 overlay
2555 .check_window(WindowKind::Overlay, &click_through, 0)
2556 .is_ok()
2557 );
2558 let mut asked = WindowAttributes {
2560 title: Some("Notes".into()),
2561 level: Some(WindowLevel::AboveDock),
2562 ..Default::default()
2563 };
2564 assert_eq!(limited.deny_window_attributes(&mut asked), ["level"]);
2565 assert_eq!(asked.title.as_deref(), Some("Notes"));
2566 assert_eq!(asked.level, None);
2567 }
2568
2569 #[test]
2570 fn environment_names_match_exactly_except_on_windows() {
2571 let access = Access {
2572 declared: caps(r#"{"process":{"env":["MY_TOKEN"]}}"#),
2573 granted: None,
2574 };
2575 assert!(access.allows_env("MY_TOKEN"));
2576 assert_eq!(access.allows_env("my_token"), cfg!(windows));
2577 assert_eq!(super::env_names_match("Path", "PATH"), cfg!(windows));
2578 }
2579
2580 #[test]
2581 fn roots_stay_within_their_anchor_and_bare_commands_have_no_drive() {
2582 let anchor = Path::new(if cfg!(windows) { "C:\\app" } else { "/app" });
2583 assert!(super::within(anchor, Path::new("data/x"), "r").is_ok());
2584 assert!(super::within(anchor, Path::new("/etc"), "r").is_err());
2585 #[cfg(windows)]
2586 for tail in ["C:/Windows", "\\\\srv\\share", "\\Users", "D:x"] {
2587 assert!(
2588 super::within(anchor, Path::new(tail), "r").is_err(),
2589 "{tail}"
2590 );
2591 }
2592 assert!(!super::valid_command("C:git"));
2593 assert!(super::valid_command("git"));
2594 }
2595
2596 #[test]
2597 fn a_manifest_with_absolute_commands_and_roots_parses() {
2598 let declared = caps(
2601 r#"{"process":{"execute":["/bin/sh","/usr/bin/open","git"]},"fs":{"read":["/Applications"]}}"#,
2602 );
2603 assert_eq!(
2604 declared.process.execute,
2605 ["/bin/sh", "/usr/bin/open", "git"]
2606 );
2607 if !cfg!(windows) {
2608 assert!(super::valid_command("/bin/sh"));
2609 assert!(super::absolute(Path::new("/Applications")));
2610 }
2611 }
2612
2613 #[test]
2614 fn system_capabilities_are_explicit_and_intersected() {
2615 let declared = caps(
2616 r#"{"process":{"execute":["claude","codex"]},"fs":{"read":["${dataDir}"],"write":["${dataDir}"]}}"#,
2617 );
2618 assert_eq!(
2619 Capabilities::from_json(&declared.to_json()).unwrap(),
2620 declared
2621 );
2622 let access = Access {
2623 declared,
2624 granted: Some(caps(
2625 r#"{"process":{"execute":["codex"]},"fs":{"read":["${dataDir}/conversations"]}}"#,
2626 )),
2627 };
2628 assert!(access.allows_process("codex"));
2629 assert!(!access.allows_process("claude"));
2630 assert!(!access.allows_process("/usr/bin/codex"));
2631 assert!(!Access::all().allows_process("codex"));
2632 let root = std::env::current_dir().unwrap();
2633 assert!(
2634 access
2635 .authorize_file(&root.join("conversations/new.json"), &root, false)
2636 .is_ok()
2637 );
2638 assert!(
2639 access
2640 .authorize_file(&root.join("other.json"), &root, false)
2641 .is_err()
2642 );
2643 assert!(
2644 access
2645 .authorize_file(&root.join("conversations/new.json"), &root, true)
2646 .is_err()
2647 );
2648 assert!(Access::all().authorize_file(&root, &root, false).is_err());
2649 assert!(
2650 access
2651 .authorize_file(&root.join("../secret"), &root, false)
2652 .is_err()
2653 );
2654 for bad in [
2655 r#"{"process":{"execut":[]}}"#,
2656 r#"{"fs":{"reads":[]}}"#,
2657 r#"{"fs":{"read":["${dataDir}/../outside"]}}"#,
2658 r#"{"process":{"execute":["*"]}}"#,
2659 ] {
2660 assert!(Capabilities::from_json(&serde_json::from_str(bad).unwrap()).is_err());
2661 }
2662 }
2663
2664 #[test]
2665 fn trusted_host_anchors_expand_without_implicit_grants() {
2666 let root = std::env::current_dir().unwrap();
2667 let anchors = TrustedPaths {
2668 plugin_dir: Some(root.clone()),
2669 home_dir: Some(root.join("native-home")),
2670 };
2671 let access = Access {
2672 declared: caps(
2673 r#"{"fs":{"read":["assets","${homeDir}/settings","${pluginDir}/content"]}}"#,
2674 ),
2675 granted: None,
2676 };
2677 for path in ["assets/file", "native-home/settings/file", "content/file"] {
2678 assert!(
2679 access
2680 .authorize_file_with_paths(&root.join(path), &root, &anchors, false)
2681 .is_ok()
2682 );
2683 }
2684 assert!(
2685 access
2686 .authorize_file(&root.join("content/file"), &root, false)
2687 .is_err()
2688 );
2689 assert!(
2690 access
2691 .authorize_file_with_paths(&root.join("other/file"), &root, &anchors, false)
2692 .is_err()
2693 );
2694 assert!(
2695 TrustedPaths::default()
2696 .resolve_root("${homeDir}/settings", &root)
2697 .is_err()
2698 );
2699 assert!(
2700 TrustedPaths::default()
2701 .resolve_root("assets", &root)
2702 .is_err()
2703 );
2704 }
2705
2706 #[test]
2707 fn http_rules_are_one_form_whose_keys_all_narrow() {
2708 let allows = |rule: serde_json::Value, method: &str, url: &str| {
2709 Access {
2710 declared: Capabilities::from_json(&serde_json::json!({"network":{"http":[rule]}}))
2711 .unwrap(),
2712 granted: None,
2713 }
2714 .allows_http(method, url)
2715 };
2716 let plain = serde_json::json!({"host": "api.example.com", "methods": ["GET"]});
2718 assert!(allows(plain.clone(), "GET", "https://api.example.com/"));
2719 assert!(allows(
2720 plain.clone(),
2721 "GET",
2722 "http://api.example.com:8080/any/path"
2723 ));
2724 assert!(!allows(plain.clone(), "POST", "https://api.example.com/"));
2725 assert!(allows(
2726 serde_json::json!({"host": "api.example.com"}),
2727 "PUT",
2728 "https://api.example.com/x"
2729 ));
2730 let scoped = serde_json::json!({
2732 "host": "api.example.com", "methods": ["GET"], "scheme": "https", "port": 443,
2733 "paths": ["/exact"], "pathPrefixes": ["/v1"]
2734 });
2735 assert!(allows(
2736 scoped.clone(),
2737 "GET",
2738 "https://api.example.com/exact?q=1"
2739 ));
2740 assert!(allows(scoped.clone(), "GET", "https://api.example.com/v1"));
2741 assert!(allows(
2742 scoped.clone(),
2743 "GET",
2744 "https://api.example.com/v1/child"
2745 ));
2746 assert!(!allows(
2747 scoped.clone(),
2748 "GET",
2749 "https://api.example.com/v10"
2750 ));
2751 assert!(!allows(
2752 scoped.clone(),
2753 "GET",
2754 "https://api.example.com/exact/more"
2755 ));
2756 assert!(!allows(
2757 scoped.clone(),
2758 "GET",
2759 "http://api.example.com/exact"
2760 ));
2761 assert!(!allows(
2762 scoped.clone(),
2763 "GET",
2764 "https://api.example.com:444/exact"
2765 ));
2766 assert!(allows(scoped, "GET", "https://api.example.com:443/exact"));
2767 let legacy = serde_json::json!({"host": "*.example.com", "schemes": ["https", "wss"], "pathPrefix": "/v1/"});
2769 assert!(allows(
2770 legacy.clone(),
2771 "GET",
2772 "https://quotes.example.com/v1/quote"
2773 ));
2774 assert!(!allows(legacy, "GET", "https://quotes.example.com/v2/"));
2775 let mixed = caps(
2777 r#"{"network":{"http":[{"host":"a.example.com","methods":["get"],"scheme":"https","schemes":["wss","https"],"pathPrefix":"/a","path_prefixes":["/b"],"pathPrefixes":["/a","/c"]}]}}"#,
2778 );
2779 let grant = &mixed.network.http[0];
2780 assert_eq!(grant.methods, ["GET"]);
2781 assert_eq!(grant.schemes, ["https", "wss"]);
2782 assert_eq!(grant.path_prefixes, ["/a", "/c", "/b"]);
2783 assert_eq!(
2784 mixed.to_json()["network"]["http"][0],
2785 serde_json::json!({"host":"a.example.com","methods":["GET"],"schemes":["https","wss"],"pathPrefixes":["/a","/c","/b"]})
2786 );
2787 assert_eq!(Capabilities::from_json(&mixed.to_json()).unwrap(), mixed);
2788 for bad in [
2790 serde_json::json!({"host": "a.example.com", "schemes": ["ftp"]}),
2791 serde_json::json!({"host": "a.example.com", "port": 0}),
2792 serde_json::json!({"host": "a.example.com", "port": 70000}),
2793 serde_json::json!({"host": "a.example.com", "paths": ["relative"]}),
2794 serde_json::json!({"host": "a.example.com", "pathPrefixes": ["/v1/*"]}),
2795 serde_json::json!({"host": "a.example.com", "methods": ["*"]}),
2796 serde_json::json!({"host": "a.example.com", "paths": "/x", "query": true}),
2797 serde_json::json!({"methods": ["GET"]}),
2798 ] {
2799 assert!(
2800 Capabilities::from_json(&serde_json::json!({"network":{"http":[bad.clone()]}}))
2801 .is_err(),
2802 "{bad}"
2803 );
2804 }
2805 }
2806
2807 #[test]
2808 fn exit_and_environment_permissions_intersect() {
2809 let declared = caps(r#"{"process":{"env":["NSH_SECRET","OTHER"],"exit":true}}"#);
2810 assert_eq!(
2811 Capabilities::from_json(&declared.to_json()).unwrap(),
2812 declared
2813 );
2814 let access = Access {
2815 declared,
2816 granted: Some(caps(r#"{"process":{"env":["NSH_SECRET"]}}"#)),
2817 };
2818 assert!(access.allows_env("NSH_SECRET"));
2819 assert!(!access.allows_env("OTHER"));
2820 assert!(!access.allows_exit());
2821 assert!(!Access::all().allows_exit());
2822 assert!(!Access::all().allows_env("NSH_SECRET"));
2823 assert!(Access::all().allows_env("LANG"));
2824 assert_eq!(Access::all().allows_env("lang"), cfg!(windows));
2825 assert!(Access::all().allows_env("TZ"));
2826 for name in [
2828 "HOME",
2829 "USER",
2830 "USERNAME",
2831 "HOSTNAME",
2832 "COMPUTERNAME",
2833 "PATH",
2834 "TMPDIR",
2835 "XDG_RUNTIME_DIR",
2836 "APPDATA",
2837 "http_proxy",
2838 "HTTPS_PROXY",
2839 "ALL_PROXY",
2840 "NO_PROXY",
2841 "DISPLAY",
2842 ] {
2843 assert!(!Access::all().allows_env(name), "{name}");
2844 }
2845 assert!(!Access::all().allows_env("SSH_AUTH_SOCK"));
2846 assert!(!Access::all().allows_env("DBUS_SESSION_BUS_ADDRESS"));
2847 assert!(Capabilities::from_json(&serde_json::json!({"process":{"exit":"true"}})).is_err());
2848 assert!(
2849 Capabilities::from_json(&serde_json::json!({"process":{"env":["BAD=NAME"]}})).is_err()
2850 );
2851 }
2852
2853 #[test]
2854 fn default_environment_entries_are_upper_case_names() {
2855 for line in include_str!("default-env").lines() {
2856 let name = line.split('#').next().unwrap_or_default().trim();
2857 assert!(
2858 name.is_empty()
2859 || name
2860 .chars()
2861 .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'),
2862 "{line}"
2863 );
2864 }
2865 }
2866
2867 #[test]
2868 fn sockets_need_exact_host_and_port_grants() {
2869 let declared = caps(
2870 r#"{"network":{"hosts":["*"],"sockets":["MQTT.example.com:8883","[::1]:9000","127.0.0.1:22"]}}"#,
2871 );
2872 assert_eq!(
2873 Capabilities::from_json(&declared.to_json()).unwrap(),
2874 declared
2875 );
2876 let access = Access {
2877 declared,
2878 granted: None,
2879 };
2880 assert!(access.allows_socket("mqtt.example.com", 8883));
2881 assert!(access.allows_socket("MQTT.example.com.", 8883));
2882 assert!(!access.allows_socket("mqtt.example.com", 1883));
2883 assert!(!access.allows_socket("example.com", 8883));
2884 assert!(!access.allows_socket("a.mqtt.example.com", 8883));
2885 assert!(access.allows_socket("::1", 9000));
2886 assert!(access.allows_socket("[::1]", 9000));
2887 assert!(access.allows_socket("127.0.0.1", 22));
2888 assert!(!access.allows_socket("127.0.0.1", 0));
2889 assert!(!access.allows_socket("localhost", 22));
2891 assert!(!Access::all().allows_socket("127.0.0.1", 22));
2892 assert!(!Access::all().allows_socket("example.com", 443));
2893 let narrowed = Access {
2894 granted: Some(caps(r#"{"network":{"sockets":["127.0.0.1:22"]}}"#)),
2895 ..access
2896 };
2897 assert!(narrowed.allows_socket("127.0.0.1", 22));
2898 assert!(!narrowed.allows_socket("mqtt.example.com", 8883));
2899 for bad in [
2900 "*.example.com:443",
2901 "*:443",
2902 "example.com",
2903 "example.com:0",
2904 "example.com:65536",
2905 "example.com:*",
2906 ":443",
2907 "::1:443",
2908 "[]:443",
2909 "exa mple.com:1",
2910 ] {
2911 assert!(
2912 Capabilities::from_json(&serde_json::json!({"network":{"sockets":[bad]}}))
2913 .unwrap_err()
2914 .contains("invalid socket grant"),
2915 "{bad}"
2916 );
2917 }
2918 }
2919
2920 #[test]
2921 fn websockets_follow_http_grants() {
2922 let access = Access {
2923 declared: caps(
2924 r#"{"network":{"hosts":["ws.example.com"],"http":[
2925 {"host":"chat.example.com","methods":["GET"],"scheme":"https","paths":["/socket"]},
2926 {"host":"legacy.example.com","schemes":["wss"]}
2927 ]}}"#,
2928 ),
2929 granted: None,
2930 };
2931 assert!(access.allows_websocket("ws://ws.example.com:8080/x"));
2932 assert!(access.allows_websocket("wss://chat.example.com/socket"));
2933 assert!(!access.allows_websocket("ws://chat.example.com/socket"));
2934 assert!(!access.allows_websocket("wss://chat.example.com/other"));
2935 assert!(access.allows_websocket("wss://legacy.example.com/"));
2936 assert!(!access.allows_websocket("ws://legacy.example.com/"));
2937 assert!(!access.allows_websocket("https://ws.example.com/"));
2938 assert!(!access.allows_socket("ws.example.com", 8080));
2939 }
2940
2941 #[cfg(unix)]
2942 #[test]
2943 fn filesystem_symlinks_cannot_escape_granted_roots() {
2944 use std::os::unix::fs::symlink;
2945 let base = std::env::var_os("TMPDIR")
2946 .map(PathBuf::from)
2947 .unwrap_or_else(|| {
2948 PathBuf::from(std::env::var_os("HOME").unwrap()).join(".cache/nsh-benchs-test-tmp")
2949 });
2950 let root = base.join(format!("access-policy-{}", std::process::id()));
2951 std::fs::create_dir_all(root.join("allowed")).unwrap();
2952 std::fs::create_dir_all(root.join("outside")).unwrap();
2953 symlink(root.join("outside"), root.join("allowed/link")).unwrap();
2954 let access = Access {
2955 declared: caps(r#"{"fs":{"read":["${dataDir}"],"write":["${dataDir}"]}}"#),
2956 granted: None,
2957 };
2958 for write in [false, true] {
2959 assert!(
2960 access
2961 .authorize_file(
2962 &root.join("allowed/link/missing/file"),
2963 &root.join("allowed"),
2964 write
2965 )
2966 .is_err()
2967 );
2968 assert!(
2969 access
2970 .authorize_file(&root.join("allowed/new/file"), &root.join("allowed"), write)
2971 .is_ok()
2972 );
2973 }
2974 std::fs::remove_dir_all(root).unwrap();
2975 }
2976
2977 #[test]
2978 fn denies_unless_listed() {
2979 let access = Access {
2980 declared: caps("{}"),
2981 granted: None,
2982 };
2983 assert!(!access.allows_http("GET", "https://example.com/"));
2984 assert!(!access.allows_media("https://example.com/a.png"));
2985 assert!(access.allows_media("asset:/logo.png"));
2986 assert!(!access.allows_media("logo.png"));
2988 assert!(!access.allows_media("/home/a/logo.png"));
2991 assert!(!access.allows_media("file:///home/a/logo.png"));
2992 assert!(access.allows_media("data:image/png;base64,iVBORw0KGgo="));
2993 assert!(!access.allows_webview("https://example.com/"));
2994 assert!(!access.allows_status_bar());
2995 assert!(!access.allows_clipboard());
2996 assert!(!access.allows_picker());
2997 assert!(!access.allows_speech());
2998 assert!(!access.allows_audio());
2999 assert!(!access.allows_host("getUserInfo"));
3000 assert!(Access::all().is_unrestricted());
3001 }
3002
3003 #[test]
3004 fn host_functions_need_an_explicit_grant() {
3005 let all = Access::all();
3008 assert!(all.allows_clipboard());
3009 assert!(!all.allows_host("getUserInfo"));
3010 let access = |json: &str| Access {
3011 declared: caps(json),
3012 granted: None,
3013 };
3014 let every = access(r#"{ "host": true }"#);
3015 assert!(every.allows_host("getUserInfo") && every.allows_host("bridge.call"));
3016 assert!(!access(r#"{ "host": false }"#).allows_host("getUserInfo"));
3017 let listed = access(r#"{ "host": ["getUserInfo", "bridge.*"] }"#);
3018 assert!(listed.allows_host("getUserInfo"));
3019 assert!(listed.allows_host("bridge.share"));
3020 assert!(!listed.allows_host("getUserInfoX"));
3021 assert!(!listed.allows_host("bridge"));
3022 assert!(Capabilities::from_json(&serde_json::json!({ "host": ["a*b"] })).is_err());
3023 assert!(Capabilities::from_json(&serde_json::json!({ "host": [""] })).is_err());
3024 let narrowed = Access {
3026 declared: caps(r#"{ "host": true }"#),
3027 granted: Some(caps(r#"{ "host": ["bridge.*"] }"#)),
3028 };
3029 assert!(narrowed.allows_host("bridge.call") && !narrowed.allows_host("getUserInfo"));
3030 }
3031
3032 #[test]
3033 fn trusted_web_input_needs_an_explicit_grant() {
3034 let all = Access::all();
3036 assert!(all.allows_webviews() && !all.allows_web_input());
3037 let access = |json: &str| Access {
3038 declared: caps(json),
3039 granted: None,
3040 };
3041 let input = r#"{ "webview": { "hosts": ["example.com"], "input": true } }"#;
3042 assert!(access(input).allows_web_input());
3043 assert!(!access(r#"{ "webview": { "hosts": ["example.com"] } }"#).allows_web_input());
3044 assert!(!access(r#"{ "webview": { "input": false } }"#).allows_web_input());
3045 assert!(
3046 Capabilities::from_json(&serde_json::json!({ "webview": { "input": "yes" } })).is_err()
3047 );
3048 assert_eq!(
3050 Capabilities::from_json(&caps(input).to_json()),
3051 Ok(caps(input))
3052 );
3053 let narrowed = Access {
3054 declared: caps(input),
3055 granted: Some(caps(r#"{ "webview": { "hosts": ["*"] } }"#)),
3056 };
3057 assert!(!narrowed.allows_web_input());
3058 }
3059
3060 #[test]
3061 fn web_media_needs_an_explicit_grant() {
3062 let all = Access::all();
3063 assert!(!all.allows_web_media(WebMedia::Microphone));
3064 let access = |json: &str| Access {
3065 declared: caps(json),
3066 granted: None,
3067 };
3068 let mic = r#"{ "webview": { "hosts": ["example.com"], "media": ["microphone"] } }"#;
3069 assert!(access(mic).allows_web_media(WebMedia::Microphone));
3070 assert!(!access(mic).allows_web_media(WebMedia::Camera));
3071 assert!(
3072 Capabilities::from_json(&serde_json::json!({ "webview": { "media": ["screen"] } }))
3073 .is_err()
3074 );
3075 assert_eq!(Capabilities::from_json(&caps(mic).to_json()), Ok(caps(mic)));
3076 let narrowed = Access {
3077 declared: caps(mic),
3078 granted: Some(caps(r#"{ "webview": { "hosts": ["*"] } }"#)),
3079 };
3080 assert!(!narrowed.allows_web_media(WebMedia::Microphone));
3081 }
3082
3083 #[test]
3084 fn host_function_names_and_grants_keep_to_their_charset() {
3085 for good in ["getUserInfo", "user.info", "a-b_c:d.E9", &"a".repeat(128)] {
3086 assert!(valid_host_name(good), "{good}");
3087 }
3088 for bad in [
3089 "",
3090 "user.x/../../admin",
3091 "a..b",
3092 "user x",
3093 "a\\b",
3094 "caf\u{e9}",
3095 "ok\u{0}",
3096 "a*",
3097 &"a".repeat(129),
3098 ] {
3099 assert!(!valid_host_name(bad), "{bad:?}");
3100 }
3101 let parses =
3102 |grant: &str| Capabilities::from_json(&serde_json::json!({ "host": [grant] })).is_ok();
3103 assert!(parses("*") && parses("user.*") && parses("user.info"));
3104 for bad in ["user/*", "a..*", "../*", "a b", "**"] {
3105 assert!(!parses(bad), "{bad}");
3106 }
3107 }
3108
3109 #[test]
3110 fn hosts_and_finer_grants() {
3111 let c = caps(
3112 r#"{ "network": {
3113 "hosts": ["*.example.org"],
3114 "http": [{ "host": "api.example.com", "methods": ["get"], "pathPrefix": "/v1/" }]
3115 } }"#,
3116 );
3117 let a = Access {
3118 declared: c,
3119 granted: None,
3120 };
3121 assert!(a.allows_http("POST", "https://api.example.org/x"));
3122 assert!(!a.allows_http("GET", "https://example.org/"));
3123 assert!(!a.allows_http("GET", "https://example.org.evil.io/"));
3124 assert!(!a.allows_http("GET", "https://evilexample.org/"));
3125 assert!(a.allows_http("GET", "https://API.example.com/v1/quote"));
3126 assert!(!a.allows_http("POST", "https://api.example.com/v1/quote"));
3127 assert!(!a.allows_http("GET", "https://api.example.com/v2/"));
3128 assert!(!a.allows_http("GET", "file://api.example.com/v1/"));
3129 assert!(!a.allows_http("GET", "https://api.example.org@evil.io/"));
3131 assert!(a.allows_http("GET", "https://user:pw@api.example.org:8443/"));
3132 }
3133
3134 #[test]
3141 fn urls_that_parsers_read_as_different_hosts_are_refused() {
3142 let hosts = r#"["docs.example.com", "*.docs.example.com"]"#;
3143 let a = Access {
3144 declared: caps(&format!(
3145 r#"{{ "network": {{ "hosts": {hosts} }}, "webview": {{ "hosts": {hosts} }} }}"#
3146 )),
3147 granted: None,
3148 };
3149 for url in [
3150 "https://bank.example\\@docs.example.com/",
3152 "https://bank.example:443\\@docs.example.com/",
3153 "https://[::1]\\@docs.example.com/",
3154 "https://bank.example\\.docs.example.com/",
3156 "https://docs.example.com\\@bank.example/",
3158 "https://docs.example.com/a\\..\\b",
3160 "https://bank.example\0.docs.example.com/",
3162 "https://bank.example\t.docs.example.com/",
3163 "https://bank.example\n.docs.example.com/",
3164 "https://bank.example .docs.example.com/",
3165 "https://bank.example[.docs.example.com/",
3166 "https://x]y.docs.example.com/",
3167 "https://bank%2Eexample.docs.example.com/",
3169 ] {
3170 assert!(!a.allows_webview(url), "{url:?}");
3171 assert!(!a.allows_http("GET", url), "{url:?}");
3172 assert!(!a.allows_media(url), "{url:?}");
3173 }
3174 assert!(!a.allows_websocket("wss://bank.example\\@docs.example.com/"));
3175 for url in [
3178 "https://docs.example.com/a%5Cb",
3179 "https://x.docs.example.com/?q=C:\\x#a\\b",
3180 "https://user:pw@docs.example.com/a b",
3181 ] {
3182 assert!(a.allows_webview(url), "{url:?}");
3183 assert!(a.allows_http("GET", url), "{url:?}");
3184 }
3185 let all = Access {
3187 declared: Capabilities::all(),
3188 granted: None,
3189 };
3190 let query = url::Url::parse("wss://x.example/?q=a\\b").unwrap();
3191 assert!(all.allows_websocket(query.as_str()), "{query}");
3192 assert!(all.allows_media("https://x.example/i.png?p=a\\b"));
3193 }
3194
3195 #[test]
3200 fn only_grants_of_every_host_cover_ambiguous_urls() {
3201 let url = "https://x.example/a\\b.png";
3202 let all = Access {
3203 declared: Capabilities::all(),
3204 granted: None,
3205 };
3206 let any = Access {
3207 declared: caps(r#"{ "network": { "hosts": ["*"] }, "webview": { "hosts": ["*"] } }"#),
3208 granted: None,
3209 };
3210 for a in [&all, &any] {
3211 assert!(a.allows_http("GET", url));
3212 assert!(a.allows_media(url));
3213 assert!(a.allows_webview(url));
3214 assert!(!a.allows_http("GET", "ftp://x.example/a\\b"));
3215 assert!(!a.allows_webview("file://x.example/a\\b"));
3216 assert!(!a.allows_webview("not a url"));
3217 assert!(!a.allows_http("GET", "https://"));
3218 }
3219 let rule = |rule: &str| Access {
3220 declared: caps(&format!(r#"{{ "network": {{ "http": [{rule}] }} }}"#)),
3221 granted: None,
3222 };
3223 let methods = rule(r#"{ "host": "*", "methods": ["get"], "schemes": ["https"] }"#);
3224 assert!(methods.allows_http("GET", url));
3225 assert!(!methods.allows_http("POST", url));
3226 assert!(!methods.allows_http("GET", "http://x.example/a\\b.png"));
3227 for narrowed in [
3228 r#"{ "host": "*", "port": 443 }"#,
3229 r#"{ "host": "*", "pathPrefix": "/a" }"#,
3230 r#"{ "host": "*", "paths": ["/a/b.png"] }"#,
3231 r#"{ "host": "x.example" }"#,
3232 ] {
3233 assert!(!rule(narrowed).allows_http("GET", url), "{narrowed}");
3234 }
3235 }
3236
3237 #[test]
3240 fn granted_urls_are_granted_hosts_for_whatwg() {
3241 let pattern = |p: &str| HostPattern::new(p).unwrap();
3242 let granted = [pattern("docs.example.com"), pattern("*.docs.example.com")];
3243 let a = Access {
3244 declared: caps(
3245 r#"{ "webview": { "hosts": ["docs.example.com", "*.docs.example.com"] } }"#,
3246 ),
3247 granted: None,
3248 };
3249 for url in [
3250 "https://docs.example.com/a",
3251 "https://DOCS.Example.COM/",
3252 "https://docs.example.com./",
3253 "https://x.docs.example.com:8443/",
3254 "https://user:pw@docs.example.com/",
3255 "https://docs.example.com#@bank.example/",
3256 "https://docs.example.com?@bank.example/",
3257 "https://docs.example.com:pass@bank.example/",
3258 "https://docs.example.com%2F@bank.example/",
3259 "https://bank.example\\@docs.example.com/",
3260 "https://bank.example:443\\@docs.example.com/",
3261 "https://[::1]\\@docs.example.com/",
3262 "https://bank.example\\.docs.example.com/",
3263 "https://docs.example.com\\@bank.example/",
3264 "https://bank.example\0.docs.example.com/",
3265 "https://bank.example\t.docs.example.com/",
3266 "https://docs.example.com\n.bank.example/",
3267 "https://bank%2Eexample.docs.example.com/",
3268 "https://docs\u{FF0E}example\u{FF0E}com/",
3269 "https://d\u{043E}cs.example.com/",
3270 "https:\\\\docs.example.com\\",
3271 " https://docs.example.com/",
3272 "https://docs.example.com /",
3273 "https://bank.example .docs.example.com/",
3274 "https://bank.example^.docs.example.com/",
3275 "https://bank.example[.docs.example.com/",
3276 "https://x]y.docs.example.com/",
3277 "https://a@bank.example@docs.example.com/",
3278 "https://..docs.example.com/",
3279 "HTTPS://DOCS.EXAMPLE.COM/",
3280 "https://x.docs.example.com/?q=C:\\x",
3281 ] {
3282 if a.allows_webview(url) {
3283 let whatwg = url::Url::parse(url).unwrap_or_else(|e| panic!("{url:?}: {e}"));
3284 let host = whatwg.host_str().unwrap_or_default().trim_end_matches('.');
3285 assert!(granted.iter().any(|p| p.matches(host)), "{url:?}: {host}");
3286 }
3287 }
3288 }
3289
3290 #[test]
3291 fn the_embedder_grants_at_most() {
3292 let a = Access {
3293 declared: caps(
3294 r#"{ "network": { "hosts": ["a.com", "b.com"] }, "statusBar": true, "clipboard": true, "picker": true, "speech": true, "audio": true }"#,
3295 ),
3296 granted: Some(caps(
3297 r#"{ "network": { "hosts": ["b.com"] }, "clipboard": true }"#,
3298 )),
3299 };
3300 assert!(a.allows_clipboard());
3301 assert!(!a.allows_http("GET", "https://a.com/"));
3302 assert!(!a.allows_picker());
3303 assert!(!a.allows_speech());
3304 assert!(!a.allows_audio());
3305 assert!(a.allows_http("GET", "https://b.com/"));
3306 assert!(!a.allows_status_bar());
3307 }
3308
3309 #[test]
3310 fn typos_are_errors() {
3311 let bad =
3312 |json: &str| Capabilities::from_json(&serde_json::from_str(json).unwrap()).unwrap_err();
3313 assert!(bad(r#"{ "netwrok": {} }"#).contains("unknown key `netwrok`"));
3314 assert!(bad(r#"{ "network": { "host": [] } }"#).contains("unknown key `host`"));
3315 assert!(bad(r#"{ "network": { "hosts": ["exa mple.com"] } }"#).contains("invalid host"));
3316 let c = caps(
3317 r#"{ "network": { "hosts": ["a.com"], "http": [{ "host": "b.com", "methods": ["GET"] }] }, "webview": { "hosts": ["*"] } }"#,
3318 );
3319 assert_eq!(Capabilities::from_json(&c.to_json()).unwrap(), c);
3320 }
3321
3322 #[test]
3325 fn unknown_keys_in_packages_grant_nothing() {
3326 let lenient =
3327 |json: &str| Capabilities::from_json_lenient(&serde_json::from_str(json).unwrap());
3328 let (c, dropped) = lenient(
3329 r#"{ "bluetooth": true, "clipboard": true,
3330 "network": { "hosts": ["a.com"], "http": [
3331 { "host": "b.com", "ports": [443] },
3332 { "host": "c.com", "methods": ["GET"] }
3333 ] } }"#,
3334 )
3335 .unwrap();
3336 assert!(c.clipboard);
3337 assert_eq!(c.network.hosts, [HostPattern::new("a.com").unwrap()]);
3338 assert_eq!(c.network.http.len(), 1);
3339 assert_eq!(c.network.http[0].host.as_str(), "c.com");
3340 assert_eq!(
3341 dropped,
3342 [
3343 "capabilities.bluetooth",
3344 "capabilities.network.http[0] (unknown key `ports`)"
3345 ]
3346 );
3347 let (c, dropped) =
3348 lenient(r#"{ "network": { "hosts": ["a.com"], "ipv6": false }, "webview": { "hosts": ["*"], "x": 1 } }"#)
3349 .unwrap();
3350 assert_eq!(c, Capabilities::default());
3351 assert_eq!(dropped.len(), 2);
3352 let (c, dropped) = lenient(
3356 r#"{ "statusBar": "yes", "clipboard": true,
3357 "network": { "hosts": ["exa mple.com"] }, "webview": { "hosts": ["a.com"] } }"#,
3358 )
3359 .unwrap();
3360 assert!(!c.status_bar);
3361 assert!(c.clipboard);
3362 assert!(c.network.hosts.is_empty());
3363 assert_eq!(c.webview, Some(vec![HostPattern::new("a.com").unwrap()]));
3364 assert_eq!(dropped.len(), 2, "{dropped:?}");
3365 assert!(
3366 dropped
3367 .iter()
3368 .any(|d| d.starts_with("capabilities.statusBar ("))
3369 );
3370 assert!(
3371 dropped
3372 .iter()
3373 .any(|d| d.starts_with("capabilities.network ("))
3374 );
3375 let (c, dropped) = lenient(
3377 r#"{ "network": { "hosts": ["a.com"], "http": [
3378 { "host": "b.com", "port": "any" }, { "host": "c.com" } ] } }"#,
3379 )
3380 .unwrap();
3381 assert_eq!(c.network.hosts.len(), 1);
3382 assert_eq!(c.network.http.len(), 1);
3383 assert_eq!(c.network.http[0].host.as_str(), "c.com");
3384 assert_eq!(dropped.len(), 1, "{dropped:?}");
3385 assert!(dropped[0].starts_with("capabilities.network.http[0] ("));
3386 let (c, dropped) = lenient(r#""everything""#).unwrap();
3388 assert_eq!(c, Capabilities::default());
3389 assert_eq!(dropped.len(), 1);
3390 assert!(Capabilities::from_json(&serde_json::json!({ "statusBar": "yes" })).is_err());
3392 let json = serde_json::json!({ "network": { "hosts": ["a.com"] }, "statusBar": true });
3394 let (c, dropped) = Capabilities::from_json_lenient(&json).unwrap();
3395 assert_eq!(c, Capabilities::from_json(&json).unwrap());
3396 assert!(dropped.is_empty());
3397 }
3398
3399 #[test]
3400 fn media_redirects_are_checked() {
3401 let a = Access {
3402 declared: Capabilities::from_json(
3403 &serde_json::json!({ "network": { "hosts": ["a.com"] } }),
3404 )
3405 .unwrap(),
3406 granted: None,
3407 };
3408 let from = "https://a.com/x/y.png";
3409 assert_eq!(
3410 a.media_redirect(from, "/z.png").unwrap(),
3411 "https://a.com/z.png"
3412 );
3413 assert_eq!(
3414 a.media_redirect(from, "z.png").unwrap(),
3415 "https://a.com/x/z.png"
3416 );
3417 assert!(a.media_redirect(from, "https://b.com/z.png").is_err());
3418 assert!(a.media_redirect(from, "//b.com/z.png").is_err());
3419 assert!(a.media_redirect(from, "file:///etc/passwd").is_err());
3420 assert!(
3421 Access::default()
3422 .media_redirect(from, "//b.com/z.png")
3423 .is_ok()
3424 );
3425 assert!(
3426 Access::default()
3427 .media_redirect(from, "ftp://b.com/z.png")
3428 .is_err()
3429 );
3430 }
3431
3432 #[test]
3436 fn http_paths_are_matched_as_whatwg_resolves_them() {
3437 let a = Access {
3438 declared: caps(
3439 r#"{ "network": { "http": [{ "host": "api.example.com", "pathPrefix": "/public" }] } }"#,
3440 ),
3441 granted: None,
3442 };
3443 for url in [
3444 "https://api.example.com/public/../private",
3445 "https://api.example.com/public/%2e%2e/private",
3446 "https://api.example.com/public/%2E%2E/private",
3447 "https://api.example.com/public/.%2e/private",
3448 "https://api.example.com/public/./../private",
3449 ] {
3450 assert!(!a.allows_http("GET", url), "{url}");
3451 assert!(!a.allows_media(url), "{url}");
3452 }
3453 for url in [
3454 "https://api.example.com/public/x",
3455 "https://api.example.com/private/../public/x",
3456 "https://api.example.com/public/./x",
3457 ] {
3458 assert!(a.allows_http("GET", url), "{url}");
3459 }
3460 }
3461
3462 #[test]
3465 fn redirects_resolve_dot_segments() {
3466 assert_eq!(
3467 resolve_reference("https://api.example.com/public/x", "../private"),
3468 "https://api.example.com/private"
3469 );
3470 assert_eq!(
3471 resolve_reference("https://api.example.com/public/x", "%2e%2e/private"),
3472 "https://api.example.com/private"
3473 );
3474 let a = Access {
3475 declared: caps(
3476 r#"{ "network": { "http": [{ "host": "api.example.com", "pathPrefix": "/public" }] } }"#,
3477 ),
3478 granted: None,
3479 };
3480 let from = "https://api.example.com/public/a.png";
3481 assert!(a.media_redirect(from, "b.png").is_ok());
3482 assert!(a.media_redirect(from, "../private.png").is_err());
3483 assert!(a.media_redirect(from, "/public/../private.png").is_err());
3484 }
3485
3486 #[test]
3490 fn media_sources_that_name_a_host_are_checked() {
3491 let a = Access {
3492 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
3493 granted: None,
3494 };
3495 for uri in [
3496 "//bank.example/x.png",
3497 "\\\\bank.example\\x.png",
3498 "/\\bank.example/x.png",
3499 "https:\\\\bank.example\\x.png",
3500 "https:/bank.example/x.png",
3501 "HTTPS://bank.example/x.png",
3502 ] {
3503 assert!(!a.allows_media(uri), "{uri}");
3504 }
3505 for uri in [
3507 "asset:/a.png",
3508 "data:image/png;base64,AAAA",
3509 "blob:https://app.example/1",
3510 "https://docs.example.com/x.png",
3511 ] {
3512 assert!(a.allows_media(uri), "{uri}");
3513 }
3514 assert!(!a.allows_media("img/a.png"));
3517 assert!(Access::default().allows_media("//bank.example/x.png"));
3519 }
3520
3521 #[test]
3525 fn media_sources_are_read_after_whatwg_strips_them() {
3526 let a = Access {
3527 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
3528 granted: None,
3529 };
3530 let page = Some("https://app.example/index.html");
3531 for uri in [
3532 "\t//bank.example/x.png",
3533 "\n//bank.example/x.png",
3534 "/\t/bank.example/x.png",
3535 " https://bank.example/x.png",
3536 "https://bank.example/x.png ",
3537 "ht\ttps://bank.example/x.png",
3538 "\u{1}https://bank.example/x.png",
3539 ] {
3540 assert_eq!(a.media_url(uri, page, None), None, "{uri:?} on the web");
3541 assert_eq!(
3542 a.media_url(uri, None, None),
3543 None,
3544 "{uri:?} in a native app"
3545 );
3546 }
3547 assert_eq!(
3549 a.media_url(" icons/a.png", page, None),
3550 Some(Cow::Borrowed(" icons/a.png"))
3551 );
3552 let local = Access {
3554 declared: caps(r#"{ "network": { "hosts": ["127.0.0.1"] } }"#),
3555 granted: None,
3556 };
3557 assert_eq!(
3558 local.media_url("http://0x7f.1/a.png", None, None),
3559 Some(Cow::Owned("http://127.0.0.1/a.png".into()))
3560 );
3561 assert_eq!(a.media_url("http://0x7f.1/a.png", None, None), None);
3562 for own in [
3564 "DATA:image/png;base64,AA",
3565 "Asset:/a.png",
3566 "BLOB:https://app.example/1",
3567 ] {
3568 assert_eq!(
3569 a.media_url(own, page, None),
3570 Some(Cow::Borrowed(own)),
3571 "{own}"
3572 );
3573 }
3574 }
3575
3576 #[test]
3582 fn whitespace_around_a_granted_url_loads_its_serialization() {
3583 let a = Access {
3584 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
3585 granted: None,
3586 };
3587 let page = Some("https://app.example/index.html");
3588 for (uri, base) in [
3589 ("https://docs.example.com/x.png ", None),
3590 (" https://docs.example.com/x.png", None),
3591 ("\u{1}https://docs.example.com/x.png", None),
3592 ("\t//docs.example.com/x.png", page),
3593 ] {
3594 assert_eq!(
3595 a.media_url(uri, base, None),
3596 Some(Cow::Owned("https://docs.example.com/x.png".into())),
3597 "{uri:?}"
3598 );
3599 }
3600 assert_eq!(a.media_url("https://bank.example/x.png ", None, None), None);
3603 for inside in [
3604 "https://docs.example.com/x\u{1}.png",
3605 "https://docs.ex\tample.com/x.png",
3606 "ht\ntps://docs.example.com/x.png",
3607 ] {
3608 assert_eq!(a.media_url(inside, None, None), None, "{inside:?}");
3609 }
3610 }
3611
3612 #[test]
3617 fn grant_paths_match_as_requests_send_them() {
3618 let a = Access {
3619 declared: caps(
3620 r#"{ "network": { "http": [
3621 { "host": "cdn.example.com", "pathPrefix": "/my photos" },
3622 { "host": "cdn.example.com", "paths": ["/über.png", "/{id}.png"] }
3623 ] } }"#,
3624 ),
3625 granted: None,
3626 };
3627 for url in [
3628 "https://cdn.example.com/my photos/a.png",
3629 "https://cdn.example.com/my%20photos/a.png",
3630 "https://cdn.example.com/über.png",
3631 "https://cdn.example.com/{id}.png",
3632 ] {
3633 assert!(a.allows_http("GET", url), "{url}");
3634 assert!(a.media_url(url, None, None).is_some(), "{url}");
3635 }
3636 assert!(!a.allows_http("GET", "https://cdn.example.com/my photosx/a.png"));
3637 for bad in [
3640 "/a/../b",
3641 "/./a",
3642 "/a/%2e%2e/b",
3643 "/a/.%2E",
3644 "/public\\..\\private",
3645 "/a/.\t./b",
3646 "/a/.\n/b",
3647 ] {
3648 let json = serde_json::json!({ "network": { "http": [{ "host": "h.example", "pathPrefix": bad }] } });
3649 assert!(Capabilities::from_json(&json).is_err(), "{bad}");
3650 }
3651 }
3652
3653 #[cfg(unix)]
3659 #[test]
3660 fn paths_outside_the_roots_are_refused_without_disk_work() {
3661 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
3662 let root = base.join(format!("media-text-{}", std::process::id()));
3663 let _ = std::fs::remove_dir_all(&root);
3664 std::fs::create_dir_all(root.join("allowed")).unwrap();
3665 std::fs::create_dir_all(root.join("elsewhere")).unwrap();
3666 std::fs::write(root.join("allowed/a.png"), b"png").unwrap();
3667 std::os::unix::fs::symlink(root.join("allowed"), root.join("elsewhere/in")).unwrap();
3669 let allowed = root.join("allowed");
3670 let access = Access {
3671 declared: Capabilities::from_json(
3672 &serde_json::json!({ "fs": { "read": [allowed.to_str().unwrap()] } }),
3673 )
3674 .unwrap(),
3675 granted: None,
3676 };
3677 let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
3678 let resolves = || RESOLVES.with(Cell::get);
3679 let before = resolves();
3680 for outside in [
3681 root.join("elsewhere/x.png"),
3682 root.join("elsewhere/in/a.png"),
3683 PathBuf::from("/Volumes/hung/x.png"),
3684 ] {
3685 assert_eq!(files.readable(&outside), None, "{}", outside.display());
3686 }
3687 assert_eq!(
3688 resolves(),
3689 before,
3690 "outside the roots, nothing was resolved"
3691 );
3692 assert!(files.readable(&allowed.join("a.png")).is_some());
3694 assert!(
3695 files
3696 .readable(&canonicalize(&allowed).unwrap().join("a.png"))
3697 .is_some()
3698 );
3699 assert_eq!(resolves(), before + 2);
3700 let _ = std::fs::remove_dir_all(&root);
3701 }
3702
3703 #[cfg(unix)]
3707 #[test]
3708 fn a_granted_file_replaced_by_a_symlink_is_refused() {
3709 use std::os::unix::fs::symlink;
3710 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
3711 let root = base.join(format!("media-swap-{}", std::process::id()));
3712 let _ = std::fs::remove_dir_all(&root);
3713 std::fs::create_dir_all(root.join("allowed")).unwrap();
3714 let root = canonicalize(&root).unwrap();
3715 std::fs::write(root.join("allowed/image.png"), b"public").unwrap();
3716 std::fs::write(root.join("secret.png"), b"secret").unwrap();
3717 let allowed = root.join("allowed").to_str().unwrap().to_owned();
3718 let access = Access {
3719 declared: Capabilities::from_json(
3720 &serde_json::json!({ "fs": { "read": [allowed.clone()] } }),
3721 )
3722 .unwrap(),
3723 granted: None,
3724 };
3725 let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
3726 let src = format!("{allowed}/image.png");
3727 assert!(access.media_url(&src, None, Some(&files)).is_some());
3728 std::fs::remove_file(root.join("allowed/image.png")).unwrap();
3729 symlink(root.join("secret.png"), root.join("allowed/image.png")).unwrap();
3730 assert_eq!(access.media_url(&src, None, Some(&files)), None);
3731 let _ = std::fs::remove_dir_all(&root);
3732 }
3733
3734 #[test]
3739 fn bundled_files_stay_inside_the_app_files() {
3740 let a = Access {
3741 declared: caps(r#"{ "network": { "hosts": ["*"] } }"#),
3742 granted: None,
3743 };
3744 for escape in [
3745 "asset:/../outside.png",
3746 "asset:/sub/../../outside.png",
3747 "asset:/%2E%2e/outside.png",
3748 "asset:/..%2Foutside.png",
3749 "asset:/a%5c..%5c..%5coutside.png",
3750 "asset:/a.png?/../../outside.png",
3751 "asset:/a.png#/../../outside.png",
3752 "asset://Users/a/outside.png",
3753 "asset:/C:/outside.png",
3754 "asset:/./a.png",
3755 "asset:../outside.png",
3756 "ASSET:/../outside.png",
3757 ] {
3758 assert_eq!(a.media_url(escape, None, None), None, "{escape}");
3759 assert_eq!(
3760 a.media_url(escape, Some("https://app.example/"), None),
3761 None,
3762 "{escape} on the web"
3763 );
3764 assert_eq!(media_grant_advice(escape, None), ASSET_ADVICE, "{escape}");
3765 assert_eq!(media_capability(escape, None), "fs", "{escape}");
3766 }
3767 for inside in [
3768 "asset:/a.png",
3769 "asset:/@app/icons/a.png",
3770 "asset:/a.png?v=2",
3771 "asset:/a%20b.png",
3772 "asset:/sub/a..b.png",
3773 "ASSET:/a.png",
3774 ] {
3775 assert_eq!(
3776 a.media_url(inside, None, None),
3777 Some(Cow::Borrowed(inside)),
3778 "{inside}"
3779 );
3780 }
3781 assert_eq!(
3783 Access::default().media_url("asset:/../outside.png", None, None),
3784 Some(Cow::Borrowed("asset:/../outside.png"))
3785 );
3786 }
3787
3788 #[test]
3793 fn relative_paths_name_no_file_in_a_native_app() {
3794 let a = Access {
3795 declared: caps(r#"{ "network": { "hosts": ["*"] } }"#),
3796 granted: None,
3797 };
3798 for relative in [
3799 "clip.mp4",
3800 "./clip.mp4",
3801 "Users/a/secret.mp4",
3802 "../etc/x.png",
3803 " /etc/x.png",
3804 ] {
3805 assert_eq!(a.media_url(relative, None, None), None, "{relative}");
3806 assert_eq!(media_capability(relative, None), "fs", "{relative}");
3807 assert_eq!(
3808 media_grant_advice(relative, None),
3809 RELATIVE_ADVICE,
3810 "{relative}"
3811 );
3812 assert_eq!(
3813 a.media_url(relative, Some("https://app.example/"), None),
3814 Some(Cow::Borrowed(relative)),
3815 "{relative} on the web"
3816 );
3817 assert_eq!(
3818 Access::default().media_url(relative, None, None),
3819 Some(Cow::Borrowed(relative)),
3820 "{relative} without capabilities"
3821 );
3822 }
3823 for empty in ["", " "] {
3825 assert_eq!(a.media_url(empty, None, None), Some(Cow::Borrowed(empty)));
3826 }
3827 }
3828
3829 #[cfg(unix)]
3832 #[test]
3833 fn media_files_open_inside_their_root() {
3834 use std::io::Read;
3835 let base = std::env::temp_dir().join(format!("media-open-{}", std::process::id()));
3836 let _ = std::fs::remove_dir_all(&base);
3837 std::fs::create_dir_all(base.join("allowed")).unwrap();
3838 let base = canonicalize(&base).unwrap();
3839 std::fs::write(base.join("allowed/a.png"), b"public").unwrap();
3840 std::fs::write(base.join("secret.png"), b"secret").unwrap();
3841 let allowed = base.join("allowed");
3842 let access = Access {
3843 declared: Capabilities::from_json(
3844 &serde_json::json!({ "fs": { "read": [allowed.to_str().unwrap()] } }),
3845 )
3846 .unwrap(),
3847 granted: None,
3848 };
3849 let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
3850 let path = allowed.join("a.png");
3851 let read = |path: &Path| {
3852 let mut text = String::new();
3853 files.open(path)?.ok()?.read_to_string(&mut text).ok()?;
3854 Some(text)
3855 };
3856 assert_eq!(read(&path).as_deref(), Some("public"));
3857 std::fs::remove_file(&path).unwrap();
3859 std::os::unix::fs::symlink(base.join("secret.png"), &path).unwrap();
3860 assert!(matches!(files.open(&path), Some(Err(_))));
3861 assert!(matches!(files.open(&base.join("secret.png")), Some(Err(_))));
3862 assert!(MediaFiles::default().open(&path).is_none());
3864 std::fs::create_dir_all(base.join("allowed/sub")).unwrap();
3867 std::fs::write(base.join("allowed/sub/ok.png"), b"ok").unwrap();
3868 std::os::unix::fs::symlink(
3869 base.join("allowed/a.png"),
3870 base.join("allowed/sub/link.png"),
3871 )
3872 .unwrap();
3873 std::fs::remove_file(&path).unwrap();
3874 std::fs::write(&path, b"public").unwrap();
3875 let narrowed = Access {
3876 declared: access.declared.clone(),
3877 granted: Some(
3878 Capabilities::from_json(&serde_json::json!({
3879 "fs": { "read": [allowed.join("sub").to_str().unwrap()] }
3880 }))
3881 .unwrap(),
3882 ),
3883 };
3884 let files = MediaFiles::new(&narrowed, None, &TrustedPaths::default(), true);
3885 let mut text = String::new();
3886 files
3887 .open(&allowed.join("sub/ok.png"))
3888 .unwrap()
3889 .unwrap()
3890 .read_to_string(&mut text)
3891 .unwrap();
3892 assert_eq!(text, "ok");
3893 assert!(matches!(
3894 files.open(&allowed.join("sub/link.png")),
3895 Some(Err(_))
3896 ));
3897 assert!(matches!(files.open(&path), Some(Err(_))));
3898 let localhost = format!("file://localhost{}", allowed.join("sub/link.png").display());
3900 assert_eq!(narrowed.media_url(&localhost, None, Some(&files)), None);
3901 let ok = format!("file://localhost{}", allowed.join("sub/ok.png").display());
3902 assert!(narrowed.media_url(&ok, None, Some(&files)).is_some());
3903 let _ = std::fs::remove_dir_all(&base);
3904 }
3905
3906 #[cfg(unix)]
3910 #[test]
3911 fn a_dangling_symlink_in_a_granted_root_is_refused() {
3912 use std::os::unix::fs::symlink;
3913 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
3914 let root = base.join(format!("media-dangling-{}", std::process::id()));
3915 let _ = std::fs::remove_dir_all(&root);
3916 std::fs::create_dir_all(root.join("allowed")).unwrap();
3917 let root = canonicalize(&root).unwrap();
3918 symlink(root.join("secret.png"), root.join("allowed/link.png")).unwrap();
3919 let allowed = root.join("allowed").to_str().unwrap().to_owned();
3920 let access = Access {
3921 declared: Capabilities::from_json(
3922 &serde_json::json!({ "fs": { "read": [allowed.clone()] } }),
3923 )
3924 .unwrap(),
3925 granted: None,
3926 };
3927 let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
3928 assert_eq!(
3929 access.media_url(&format!("{allowed}/link.png"), None, Some(&files)),
3930 None
3931 );
3932 let missing = format!("{allowed}/later.png");
3934 assert_eq!(
3935 access.media_url(&missing, None, Some(&files)),
3936 Some(Cow::Borrowed(missing.as_str()))
3937 );
3938 let _ = std::fs::remove_dir_all(&root);
3939 }
3940
3941 #[cfg(unix)]
3946 #[test]
3947 fn local_media_files_need_an_fs_read_grant() {
3948 use std::os::unix::fs::symlink;
3949 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
3950 let root = base.join(format!("media-files-{}", std::process::id()));
3951 let _ = std::fs::remove_dir_all(&root);
3952 std::fs::create_dir_all(root.join("allowed")).unwrap();
3953 std::fs::create_dir_all(root.join("outside")).unwrap();
3954 std::fs::write(root.join("allowed/a.png"), b"png").unwrap();
3955 std::fs::write(root.join("outside/b.png"), b"png").unwrap();
3956 symlink(root.join("outside"), root.join("allowed/link")).unwrap();
3957 let root = canonicalize(&root).unwrap();
3959 let data = root.join("allowed");
3960 let access = Access {
3961 declared: caps(
3962 r#"{ "network": { "hosts": ["docs.example.com"] }, "fs": { "read": ["${dataDir}"] } }"#,
3963 ),
3964 granted: None,
3965 };
3966 let files = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), true);
3967 let real = canonicalize(&data).unwrap();
3968 let path = |p: &Path| p.to_str().unwrap().to_owned();
3969 let load = |uri: &str| {
3970 access
3971 .media_url(uri, None, Some(&files))
3972 .map(Cow::into_owned)
3973 };
3974
3975 let granted = path(&real.join("a.png"));
3976 assert_eq!(load(&path(&data.join("a.png"))), Some(granted.clone()));
3977 assert_eq!(
3978 load(&format!("file://{}", path(&data.join("a.png")))),
3979 Some(format!("file://{granted}"))
3980 );
3981 assert_eq!(
3982 load(&format!("FILE://{}", path(&data.join("a.png")))),
3983 Some(format!("file://{granted}"))
3984 );
3985 assert_eq!(load(&path(&data.join("../outside/b.png"))), None);
3987 assert_eq!(
3988 load(&format!("file://{}/%2e%2e/outside/b.png", path(&data))),
3989 None
3990 );
3991 assert_eq!(load(&path(&data.join("link/b.png"))), None);
3992 assert_eq!(load(&path(&root.join("outside/b.png"))), None);
3993 assert_eq!(
3995 access.media_url(&path(&data.join("a.png")), None, None),
3996 None
3997 );
3998 let mobile = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), false);
3999 assert_eq!(
4000 access.media_url(&path(&data.join("a.png")), None, Some(&mobile)),
4001 None
4002 );
4003 let network_only = Access {
4004 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
4005 granted: None,
4006 };
4007 let none = MediaFiles::new(&network_only, Some(&data), &TrustedPaths::default(), true);
4008 assert_eq!(
4009 network_only.media_url(&path(&data.join("a.png")), None, Some(&none)),
4010 None
4011 );
4012 let narrowed = Access {
4014 declared: caps(r#"{ "fs": { "read": ["${dataDir}"] } }"#),
4015 granted: Some(caps(r#"{ "fs": { "read": ["${dataDir}/sub"] } }"#)),
4016 };
4017 let files = MediaFiles::new(&narrowed, Some(&data), &TrustedPaths::default(), true);
4018 assert_eq!(
4019 narrowed.media_url(&path(&data.join("a.png")), None, Some(&files)),
4020 None
4021 );
4022 let page = Some("https://app.example/index.html");
4025 assert_eq!(
4026 access.media_url("/icons/a.png", page, None),
4027 Some(Cow::Borrowed("/icons/a.png"))
4028 );
4029 for local in [
4032 path(&root.join("outside/b.png")),
4033 format!("FILE://{}", path(&root.join("outside/b.png"))),
4034 "C:\\pictures\\x.png".to_owned(),
4035 "/x.png".to_owned(),
4036 ] {
4037 assert_eq!(
4038 Access::default().media_url(&local, None, None),
4039 Some(Cow::Borrowed(local.as_str())),
4040 "{local}"
4041 );
4042 }
4043 let files = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), true);
4045 for _ in 0..2 {
4046 let again = |uri: &str| {
4047 access
4048 .media_url(uri, None, Some(&files))
4049 .map(Cow::into_owned)
4050 };
4051 assert_eq!(again(&path(&data.join("a.png"))), Some(granted.clone()));
4052 assert_eq!(again(&path(&data.join("link/b.png"))), None);
4053 }
4054 let _ = std::fs::remove_dir_all(&root);
4055 }
4056
4057 #[test]
4060 fn refused_media_sources_advise_the_host_they_resolve_to() {
4061 let page = Some("http://localhost:8080/index.html");
4062 assert_eq!(
4064 media_grant_advice("//127.0.0.1:9000/a.png", page),
4065 "add `127.0.0.1` to capabilities.network in nsh.json"
4066 );
4067 assert_eq!(
4069 media_grant_advice("//127.0.0.1:9000/a.png", None),
4070 NO_SCHEME_ADVICE
4071 );
4072 assert_eq!(
4074 media_grant_advice("//127.0.0.1\\a.png", page),
4075 NO_HOST_ADVICE
4076 );
4077 assert_eq!(
4078 media_grant_advice("https://cdn.example.com/a.png", page),
4079 "add `cdn.example.com` to capabilities.network in nsh.json"
4080 );
4081 assert_eq!(
4084 media_grant_advice("/Users/a/x.png", None),
4085 LOCAL_FILE_ADVICE
4086 );
4087 assert_eq!(
4088 media_grant_advice("file:///Users/a/x.png", page),
4089 LOCAL_FILE_ADVICE
4090 );
4091 assert_eq!(media_capability("/Users/a/x.png", None), "fs");
4093 assert_eq!(media_capability("C:\\pictures\\x.png", None), "fs");
4094 assert_eq!(media_capability("FILE:///Users/a/x.png", page), "fs");
4095 assert_eq!(media_capability("/icons/a.png", page), "network");
4096 assert_eq!(
4097 media_capability("https://cdn.example.com/a.png", None),
4098 "network"
4099 );
4100 }
4101
4102 #[test]
4107 fn media_sources_load_the_url_the_check_granted() {
4108 let a = Access {
4109 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
4110 granted: None,
4111 };
4112 let https = Some("https://app.example/index.html");
4113 let http = Some("http://127.0.0.1:8080/");
4114 let loads = |uri, base| a.media_url(uri, base, None).map(|u| u.into_owned());
4115 assert_eq!(
4116 loads("https://DOCS.example.com/a/../x.png", None).as_deref(),
4117 Some("https://docs.example.com/x.png")
4118 );
4119 assert_eq!(
4120 loads("//docs.example.com/x.png", https).as_deref(),
4121 Some("https://docs.example.com/x.png")
4122 );
4123 assert_eq!(
4124 loads("//docs.example.com/x.png", http).as_deref(),
4125 Some("http://docs.example.com/x.png")
4126 );
4127 assert_eq!(loads("\\\\docs.example.com\\x.png", https), None);
4131 assert_eq!(loads("//docs.example.com/x.png", None), None);
4132 assert_eq!(loads("//bank.example/x.png", https), None);
4133 for own in ["asset:/a.png", "img/a.png", "data:image/png;base64,AAAA"] {
4134 assert!(
4135 matches!(a.media_url(own, https, None), Some(std::borrow::Cow::Borrowed(u)) if u == own),
4136 "{own}"
4137 );
4138 }
4139 assert!(matches!(
4141 Access::default().media_url("//bank.example/x.png", None, None),
4142 Some(std::borrow::Cow::Borrowed("//bank.example/x.png"))
4143 ));
4144 }
4145
4146 #[test]
4147 fn opening_urls_is_granted_by_scheme() {
4148 let caps = |json: serde_json::Value| Capabilities::from_json(&json).unwrap();
4149 let access =
4150 |declared: Capabilities, granted: Option<Capabilities>| Access { declared, granted };
4151 let any = access(caps(serde_json::json!({ "openUrl": true })), None);
4152 assert!(any.allows_open_url("https://a.com"));
4153 assert!(any.allows_open_url("tel:+15550100"));
4154 let some = access(
4155 caps(serde_json::json!({ "openUrl": { "schemes": ["HTTPS", "mailto"] } })),
4156 None,
4157 );
4158 assert!(some.allows_open_url("https://a.com"));
4159 assert!(some.allows_open_url("MAILTO:a@b.c"));
4160 assert!(!some.allows_open_url("tel:1"));
4161 let narrowed = access(
4163 caps(serde_json::json!({ "openUrl": true })),
4164 Some(caps(
4165 serde_json::json!({ "openUrl": { "schemes": ["https"] } }),
4166 )),
4167 );
4168 assert!(narrowed.allows_open_url("https://a.com"));
4169 assert!(!narrowed.allows_open_url("mailto:a@b.c"));
4170 let none = access(caps(serde_json::json!({ "openUrl": false })), None);
4171 assert!(!none.allows_open_url("https://a.com"));
4172 assert!(!access(caps(serde_json::json!({})), None).allows_open_url("https://a.com"));
4173 assert!(Access::default().allows_open_url("https://a.com"));
4174 for bad in [
4175 serde_json::json!({ "openUrl": "yes" }),
4176 serde_json::json!({ "openUrl": { "schemes": ["ht tp"] } }),
4177 serde_json::json!({ "openUrl": { "hosts": ["a.com"] } }),
4178 ] {
4179 assert!(Capabilities::from_json(&bad).is_err(), "{bad}");
4180 }
4181 for json in [
4183 serde_json::json!(true),
4184 serde_json::json!(false),
4185 serde_json::json!({ "schemes": ["https"] }),
4186 ] {
4187 let c = caps(serde_json::json!({ "openUrl": json }));
4188 assert_eq!(c.to_json()["openUrl"], json);
4189 }
4190 }
4191}