1use std::{
72 borrow::Cow,
73 path::{Component, Path, PathBuf},
74};
75
76use serde_json::{Map, Value};
77
78#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct HostPattern(String);
82
83impl HostPattern {
84 pub fn new(pattern: &str) -> Result<Self, String> {
86 let p = pattern.trim().to_ascii_lowercase();
87 let host = p.strip_prefix("*.").unwrap_or(&p);
88 let valid = p == "*"
89 || (!host.is_empty()
90 && host.chars().all(|c| {
91 c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | ':' | '[' | ']')
92 }));
93 if valid {
94 Ok(Self(p))
95 } else {
96 Err(format!("invalid host pattern `{pattern}`"))
97 }
98 }
99
100 pub fn matches(&self, host: &str) -> bool {
102 match self.0.strip_prefix("*.") {
103 _ if self.0 == "*" => true,
104 Some(suffix) => {
105 host.len() > suffix.len() + 1 && host.ends_with(suffix) && {
106 let dot = host.len() - suffix.len() - 1;
107 host.as_bytes()[dot] == b'.'
108 }
109 }
110 None => self.0 == host,
111 }
112 }
113
114 pub fn as_str(&self) -> &str {
116 &self.0
117 }
118
119 fn is_any(&self) -> bool {
121 self.0 == "*"
122 }
123}
124
125#[derive(Debug, Clone, PartialEq, Eq)]
128#[non_exhaustive]
129pub struct HttpGrant {
130 pub host: HostPattern,
132 pub methods: Vec<String>,
134 pub schemes: Vec<String>,
136 pub port: Option<u16>,
138 pub paths: Vec<String>,
142 pub path_prefixes: Vec<String>,
146}
147
148impl Default for HttpGrant {
149 fn default() -> Self {
150 Self {
151 host: HostPattern(String::new()),
152 methods: Vec::new(),
153 schemes: Vec::new(),
154 port: None,
155 paths: Vec::new(),
156 path_prefixes: Vec::new(),
157 }
158 }
159}
160
161impl HttpGrant {
162 fn allows(&self, method: &str, url: &UrlParts<'_>) -> bool {
163 let default_port = match url.scheme.as_str() {
164 "https" | "wss" => 443,
165 _ => 80,
166 };
167 let path = url.path.split(['?', '#']).next().unwrap_or("/");
168 let path = if path.is_empty() { "/" } else { path };
169 self.host.matches(&url.host)
170 && (self.methods.is_empty()
171 || self.methods.iter().any(|m| m.eq_ignore_ascii_case(method)))
172 && (self.schemes.is_empty() || self.schemes.contains(&url.scheme))
173 && self
174 .port
175 .is_none_or(|p| url.port.unwrap_or(default_port) == p)
176 && ((self.paths.is_empty() && self.path_prefixes.is_empty())
177 || self.paths.iter().any(|allowed| allowed == path)
178 || self.path_prefixes.iter().any(|prefix| {
179 path.strip_prefix(prefix.as_str()).is_some_and(|tail| {
180 tail.is_empty() || prefix.ends_with('/') || tail.starts_with('/')
181 })
182 }))
183 }
184
185 fn allows_anywhere(&self, method: &str, scheme: &str) -> bool {
188 self.host.is_any()
189 && (self.methods.is_empty()
190 || self.methods.iter().any(|m| m.eq_ignore_ascii_case(method)))
191 && (self.schemes.is_empty() || self.schemes.iter().any(|s| s == scheme))
192 && self.port.is_none()
193 && self.paths.is_empty()
194 && self.path_prefixes.is_empty()
195 }
196}
197
198#[derive(Debug, Clone, PartialEq, Eq, Default)]
200#[non_exhaustive]
201pub struct NetworkGrants {
202 pub hosts: Vec<HostPattern>,
204 pub http: Vec<HttpGrant>,
206 pub sockets: Vec<SocketGrant>,
208}
209
210#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct SocketGrant {
215 host: String,
216 port: u16,
217}
218
219impl SocketGrant {
220 pub fn new(grant: &str) -> Result<Self, String> {
222 let invalid = || {
223 format!(
224 "invalid socket grant `{grant}`: expected an exact `host:port` (`[::1]:port` for IPv6), without wildcards"
225 )
226 };
227 let (host, port) = grant.trim().rsplit_once(':').ok_or_else(invalid)?;
228 let port = port
229 .parse::<u16>()
230 .ok()
231 .filter(|p| *p != 0)
232 .ok_or_else(invalid)?;
233 let host = host.to_ascii_lowercase();
234 let host = match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
235 Some(v6)
236 if !v6.is_empty()
237 && v6
238 .chars()
239 .all(|c| c.is_ascii_hexdigit() || matches!(c, ':' | '.')) =>
240 {
241 v6.to_owned()
242 }
243 Some(_) => return Err(invalid()),
244 None if !host.is_empty()
245 && host
246 .chars()
247 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')) =>
248 {
249 host.trim_end_matches('.').to_owned()
250 }
251 None => return Err(invalid()),
252 };
253 Ok(Self { host, port })
254 }
255
256 pub fn host(&self) -> &str {
258 &self.host
259 }
260
261 pub fn port(&self) -> u16 {
263 self.port
264 }
265
266 pub fn to_string_form(&self) -> String {
268 if self.host.contains(':') {
269 format!("[{}]:{}", self.host, self.port)
270 } else {
271 format!("{}:{}", self.host, self.port)
272 }
273 }
274}
275
276#[derive(Debug, Clone, PartialEq, Eq, Default)]
278#[non_exhaustive]
279pub struct ProcessGrants {
280 pub execute: Vec<String>,
282 pub exit: bool,
284 pub env: Vec<String>,
286}
287
288#[derive(Debug, Clone, PartialEq, Eq, Default)]
291#[non_exhaustive]
292pub struct FileGrants {
293 pub read: Vec<String>,
295 pub write: Vec<String>,
297}
298
299#[derive(Debug, Clone, PartialEq, Eq, Default)]
301#[non_exhaustive]
302pub struct TrustedPaths {
303 pub plugin_dir: Option<PathBuf>,
305 pub home_dir: Option<PathBuf>,
307}
308impl TrustedPaths {
309 pub fn resolve_root(&self, root: &str, data_dir: &Path) -> Result<PathBuf, String> {
312 validate_path_pattern(root)?;
313 for (placeholder, anchor) in [
314 ("${dataDir}", Some(data_dir)),
315 ("${pluginDir}", self.plugin_dir.as_deref()),
316 ("${homeDir}", self.home_dir.as_deref()),
317 ] {
318 if let Some(tail) = root.strip_prefix(placeholder) {
319 let anchor = anchor
320 .filter(|p| absolute(p))
321 .ok_or_else(|| format!("host anchor {placeholder} unavailable"))?;
322 let tail: PathBuf = tail.split('/').filter(|part| !part.is_empty()).collect();
325 return within(anchor, &tail, root);
326 }
327 }
328 let path = PathBuf::from(root);
329 if absolute(&path) {
330 Ok(path)
331 } else {
332 let anchor = self
333 .plugin_dir
334 .as_deref()
335 .filter(|p| absolute(p))
336 .ok_or_else(|| {
337 "host application directory unavailable for relative filesystem root".to_owned()
338 })?;
339 within(anchor, &path, root)
340 }
341 }
342}
343
344pub(crate) fn lexical(path: &Path) -> PathBuf {
346 use std::path::Component;
347 let mut out = PathBuf::new();
348 for part in path.components() {
349 match part {
350 Component::ParentDir => {
351 out.pop();
352 }
353 Component::CurDir => (),
354 other => out.push(other.as_os_str()),
355 }
356 }
357 out
358}
359
360#[cfg(not(target_arch = "wasm32"))]
363pub(crate) fn resolved(path: &Path) -> Result<PathBuf, String> {
364 let mut current = path.to_path_buf();
365 let mut tail = Vec::new();
366 loop {
367 if let Ok(mut real) = canonicalize(¤t) {
368 real.extend(tail.into_iter().rev());
369 return Ok(real);
370 }
371 let name = current
372 .file_name()
373 .ok_or("invalid filesystem path")?
374 .to_owned();
375 if !current.pop() {
376 return Err("invalid filesystem path".into());
377 }
378 tail.push(name);
379 }
380}
381
382pub(crate) fn inside(path: &Path, root: &Path) -> Option<PathBuf> {
385 let mut rest = path.components();
386 for part in root.components() {
387 let next = rest.next()?;
388 let same = if cfg!(windows) {
389 next.as_os_str()
390 .to_string_lossy()
391 .eq_ignore_ascii_case(&part.as_os_str().to_string_lossy())
392 } else {
393 next == part
394 };
395 if !same {
396 return None;
397 }
398 }
399 Some(rest.collect())
400}
401
402#[cfg(not(target_arch = "wasm32"))]
405pub(crate) fn in_root(path: &Path, (expanded, canonical): &(PathBuf, PathBuf)) -> Option<PathBuf> {
406 inside(path, canonical).or_else(|| inside(path, expanded))
407}
408
409pub fn native_files(os: crate::platform::Os) -> bool {
416 cfg!(not(target_arch = "wasm32")) && os != crate::platform::Os::Web
417}
418
419#[derive(Debug, Clone, Default)]
425#[non_exhaustive]
426#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
427pub struct MediaFiles {
428 declared: Vec<(PathBuf, PathBuf)>,
431 granted: Option<Vec<(PathBuf, PathBuf)>>,
433}
434
435impl MediaFiles {
436 pub fn new(
440 access: &Access,
441 data_dir: Option<&Path>,
442 paths: &TrustedPaths,
443 available: bool,
444 ) -> Self {
445 #[cfg(target_arch = "wasm32")]
446 {
447 let _ = (access, data_dir, paths, available);
448 Self::default()
449 }
450 #[cfg(not(target_arch = "wasm32"))]
451 {
452 if !available {
453 return Self::default();
454 }
455 let data = data_dir.map(Path::to_path_buf).unwrap_or_default();
456 let roots = |grants: &Capabilities| {
457 grants
458 .fs
459 .read
460 .iter()
461 .filter_map(|root| {
462 let expanded = lexical(&paths.resolve_root(root, &data).ok()?);
463 let canonical = resolved(&expanded).ok()?;
464 Some((expanded, canonical))
465 })
466 .collect()
467 };
468 Self {
469 declared: roots(&access.declared),
470 granted: access.granted.as_ref().map(roots),
471 }
472 }
473 }
474
475 #[cfg(not(target_arch = "wasm32"))]
481 pub(crate) fn open(&self, path: &Path) -> Option<std::io::Result<std::fs::File>> {
482 if self.declared.is_empty() {
483 return None;
484 }
485 let refused = || std::io::Error::new(std::io::ErrorKind::PermissionDenied, "not granted");
486 let path = lexical(path);
487 if !self
488 .declared
489 .iter()
490 .any(|root| in_root(&path, root).is_some())
491 {
492 return Some(Err(refused()));
493 }
494 let granted: Vec<&(PathBuf, PathBuf)> = match &self.granted {
498 Some(roots) => roots
499 .iter()
500 .filter(|(_, canonical)| {
501 self.declared
502 .iter()
503 .any(|(_, declared)| inside(canonical, declared).is_some())
504 })
505 .collect(),
506 None => self.declared.iter().collect(),
507 };
508 let Some(((_, canonical), relative)) = granted
511 .into_iter()
512 .filter_map(|root| Some((root, in_root(&path, root)?)))
513 .max_by_key(|((_, canonical), _)| canonical.components().count())
514 else {
515 return Some(Err(refused()));
516 };
517 Some((|| {
518 let dir = crate::runtime::fs::confined::open_root(canonical)?;
519 let file = crate::runtime::fs::confined::open_file(&dir, &relative, false)?;
520 Ok(file.into_std())
521 })())
522 }
523
524 fn readable(&self, path: &Path) -> Option<PathBuf> {
529 #[cfg(target_arch = "wasm32")]
530 {
531 let _ = path;
532 None
533 }
534 #[cfg(not(target_arch = "wasm32"))]
535 {
536 if !absolute(path) || self.declared.is_empty() {
537 return None;
538 }
539 let path = lexical(path);
542 let within = |roots: &[(PathBuf, PathBuf)]| {
543 roots.iter().any(|root| in_root(&path, root).is_some())
544 };
545 if !within(&self.declared) || !self.granted.as_deref().is_none_or(within) {
546 return None;
547 }
548 #[cfg(test)]
553 RESOLVES.with(|n| n.set(n.get() + 1));
554 let real = resolved_path(&path).ok()?;
555 let holds = |roots: &[(PathBuf, PathBuf)]| {
556 roots
557 .iter()
558 .any(|(_, canonical)| inside(&real, canonical).is_some())
559 };
560 (holds(&self.declared) && self.granted.as_deref().is_none_or(holds)).then_some(real)
561 }
562 }
563}
564
565#[cfg(test)]
566thread_local! {
567 static RESOLVES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
570}
571
572#[cfg(test)]
574pub(crate) fn resolves() -> usize {
575 RESOLVES.with(std::cell::Cell::get)
576}
577
578pub(crate) fn absolute(path: &Path) -> bool {
581 if cfg!(target_arch = "wasm32") {
582 path.has_root()
583 } else {
584 path.is_absolute()
585 }
586}
587
588fn within(anchor: &Path, tail: &Path, root: &str) -> Result<PathBuf, String> {
592 use std::path::Component;
593 let names = tail
594 .components()
595 .all(|c| matches!(c, Component::Normal(_) | Component::CurDir));
596 let mut path = anchor.to_path_buf();
597 path.extend(tail.components().filter(|c| *c != Component::CurDir));
598 if names && path.starts_with(anchor) {
599 Ok(path)
600 } else {
601 Err(format!("filesystem root `{root}` leaves its anchor"))
602 }
603}
604
605pub(crate) fn env_names_match(a: &str, b: &str) -> bool {
609 if cfg!(windows) {
610 a.eq_ignore_ascii_case(b)
611 } else {
612 a == b
613 }
614}
615
616#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
618pub enum WebMedia {
619 Microphone,
621 Camera,
623}
624
625impl WebMedia {
626 pub fn as_str(self) -> &'static str {
628 match self {
629 Self::Microphone => "microphone",
630 Self::Camera => "camera",
631 }
632 }
633}
634
635#[derive(Debug, Clone, PartialEq, Eq, Default)]
639#[non_exhaustive]
640pub struct Capabilities {
641 pub process: ProcessGrants,
643 pub fs: FileGrants,
645 pub network: NetworkGrants,
647 pub webview: Option<Vec<HostPattern>>,
649 pub webview_input: bool,
652 pub webview_runtime_origin: bool,
656 pub webview_media: Vec<WebMedia>,
659 pub status_bar: bool,
661 pub clipboard: bool,
663 pub picker: bool,
666 pub share: bool,
670 pub speech: bool,
674 pub notifications: bool,
677 pub audio: bool,
679 pub application: bool,
684 pub home_dir: bool,
686 pub host: Vec<String>,
690 pub open_url: Option<OpenUrlGrant>,
693 pub windows: Option<WindowsGrant>,
697}
698
699#[derive(Debug, Clone, PartialEq, Eq, Default)]
703#[non_exhaustive]
704pub struct WindowsGrant {
705 pub kinds: Vec<crate::desktop::WindowKind>,
708 pub levels: Vec<crate::desktop::WindowLevel>,
710 pub max: Option<u32>,
713 pub overlay: bool,
716}
717
718impl WindowsGrant {
719 fn allows_kind(&self, kind: crate::desktop::WindowKind) -> bool {
720 use crate::desktop::WindowKind;
721 if kind == WindowKind::Overlay && !self.overlay {
722 return false;
723 }
724 self.kinds.is_empty() || self.kinds.contains(&kind)
725 }
726
727 fn allows_level(&self, level: crate::desktop::WindowLevel) -> bool {
728 self.levels.is_empty() || self.levels.contains(&level)
729 }
730}
731
732#[derive(Debug, Clone, PartialEq, Eq, Default)]
734#[non_exhaustive]
735pub struct OpenUrlGrant {
736 pub schemes: Vec<String>,
739}
740
741impl OpenUrlGrant {
742 pub fn allows(&self, scheme: &str) -> bool {
744 self.schemes.is_empty() || self.schemes.iter().any(|s| s == scheme)
745 }
746}
747
748#[derive(Debug, Clone, PartialEq, Eq)]
750pub struct UrlParts<'a> {
751 pub scheme: String,
753 pub host: String,
755 pub path: &'a str,
757 pub port: Option<u16>,
759}
760
761pub fn parse_url(url: &str) -> Option<UrlParts<'_>> {
766 read_url(url).ok()
767}
768
769pub(crate) fn grant_advice(url: &str, capability: &str) -> String {
773 match parse_url(url) {
774 Some(parts) => format!(
775 "add `{}` to capabilities.{capability} in nsh.json",
776 parts.host
777 ),
778 None => NO_HOST_ADVICE.to_owned(),
779 }
780}
781
782pub(crate) fn media_grant_advice(uri: &str, base: Option<&str>) -> String {
787 if native_relative(uri, base) {
788 return RELATIVE_ADVICE.to_owned();
789 }
790 if starts_with_ignoring_case(uri, "asset:") && !is_inside_assets(uri) {
791 return ASSET_ADVICE.to_owned();
792 }
793 if media_capability(uri, base) == "fs" {
794 return LOCAL_FILE_ADVICE.to_owned();
795 }
796 let unambiguous = !uri.contains('\\') && !uri.bytes().any(|b| b.is_ascii_control());
797 if scheme_of(uri).is_none() && uri.starts_with("//") && unambiguous {
798 let resolved = base
799 .and_then(|base| url::Url::parse(base).ok())
800 .and_then(|base| base.join(uri).ok());
801 return match resolved {
802 Some(url) => grant_advice(url.as_str(), "network"),
803 None => NO_SCHEME_ADVICE.to_owned(),
804 };
805 }
806 grant_advice(uri, "network")
807}
808
809pub(crate) fn media_capability(uri: &str, base: Option<&str>) -> &'static str {
813 if starts_with_ignoring_case(uri, "asset:") || native_relative(uri, base) {
814 return "fs";
815 }
816 let local =
817 (base.is_none() || starts_with_ignoring_case(uri, "file:")) && local_file(uri).is_some();
818 if local { "fs" } else { "network" }
819}
820
821const RELATIVE_ADVICE: &str = "a relative path names no file in a native app: name a bundled file as `asset:/…`, or import it";
823
824const ASSET_ADVICE: &str = "bundled files are named by a path inside the app's files";
827
828const LOCAL_FILE_ADVICE: &str =
830 "a local file is read under capabilities.fs.read in nsh.json: add a root that holds it";
831
832const NO_SCHEME_ADVICE: &str =
834 "it names no scheme and has no page to take one from: write it as an http(s) URL";
835
836const 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";
838
839fn is_own_media(uri: &str) -> bool {
843 ["asset:", "data:", "blob:"]
844 .iter()
845 .any(|prefix| starts_with_ignoring_case(uri, prefix))
846}
847
848pub fn is_inside_assets(url: &str) -> bool {
858 let Some(path) = url.get(6..).and_then(|rest| rest.strip_prefix('/')) else {
859 return false;
860 };
861 path.split('/').all(|segment| {
862 let bytes = segment.as_bytes();
863 let encoded = |code: &[u8; 3]| bytes.windows(3).any(|w| w.eq_ignore_ascii_case(code));
864 !only_dots(bytes)
865 && !bytes.iter().any(|b| matches!(b, b'\\' | b'\0' | b':'))
866 && ![b"%2f", b"%5c", b"%00", b"%3a"]
867 .iter()
868 .any(|code| encoded(code))
869 })
870}
871
872fn only_dots(segment: &[u8]) -> bool {
875 let (mut dots, mut at) = (0, 0);
876 while at < segment.len() {
877 if segment[at] == b'.' {
878 at += 1;
879 } else if segment[at..].len() >= 3
880 && segment[at] == b'%'
881 && segment[at + 1] == b'2'
882 && segment[at + 2].eq_ignore_ascii_case(&b'e')
883 {
884 at += 3;
885 } else {
886 return false;
887 }
888 dots += 1;
889 if dots > 2 {
890 return false;
891 }
892 }
893 true
894}
895
896fn names_host(uri: &str) -> bool {
899 let stripped = whatwg_stripped(uri);
900 scheme_of(&stripped).is_some()
901 || stripped.starts_with("//")
902 || stripped.starts_with('\\')
903 || stripped.starts_with("/\\")
904}
905
906fn native_relative(uri: &str, base: Option<&str>) -> bool {
909 base.is_none()
910 && !uri.trim().is_empty()
911 && !is_own_media(uri)
912 && local_file(uri).is_none()
913 && !names_host(uri)
914}
915
916fn path_as_sent(path: &str) -> Option<String> {
921 let path: String = path
923 .chars()
924 .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
925 .map(|c| if c == '\\' { '/' } else { c })
926 .collect();
927 let dots = path.split('/').any(|segment| {
928 let segment = segment.to_ascii_lowercase().replace("%2e", ".");
929 segment == "." || segment == ".."
930 });
931 if dots {
932 return None;
933 }
934 let url = url::Url::parse(&format!("http://h{path}")).ok()?;
935 Some(url.path().to_owned())
936}
937
938fn starts_with_ignoring_case(text: &str, prefix: &str) -> bool {
940 text.get(..prefix.len())
941 .is_some_and(|head| head.eq_ignore_ascii_case(prefix))
942}
943
944fn local_file(uri: &str) -> Option<Option<PathBuf>> {
949 if starts_with_ignoring_case(uri, "file:") {
950 return Some(file_url_path(uri));
951 }
952 let drive = matches!(uri.as_bytes(), [d, b':', b'\\' | b'/', ..] if d.is_ascii_alphabetic());
953 let rooted = uri.starts_with('/') && !uri.starts_with("//") && !uri.starts_with("/\\");
954 (drive || rooted).then(|| Some(PathBuf::from(uri)))
955}
956
957#[doc(hidden)]
962pub fn file_url_path(uri: &str) -> Option<PathBuf> {
963 #[cfg(target_arch = "wasm32")]
964 {
965 let _ = uri;
966 None
967 }
968 #[cfg(not(target_arch = "wasm32"))]
969 {
970 url::Url::parse(uri).ok()?.to_file_path().ok()
971 }
972}
973
974fn file_url_of(path: &Path) -> Option<String> {
976 #[cfg(target_arch = "wasm32")]
977 {
978 let _ = path;
979 None
980 }
981 #[cfg(not(target_arch = "wasm32"))]
982 {
983 url::Url::from_file_path(path).ok().map(String::from)
984 }
985}
986
987fn whatwg_stripped(uri: &str) -> Cow<'_, str> {
990 let trimmed = uri.trim_matches(|c: char| c <= ' ');
991 if trimmed.contains(['\t', '\n', '\r']) {
992 Cow::Owned(trimmed.replace(['\t', '\n', '\r'], ""))
993 } else {
994 Cow::Borrowed(trimmed)
995 }
996}
997
998fn scheme_of(uri: &str) -> Option<&str> {
1000 let (scheme, _) = uri.split_once(':')?;
1001 let mut chars = scheme.chars();
1002 (chars.next()?.is_ascii_alphabetic()
1003 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')))
1004 .then_some(scheme)
1005}
1006
1007fn media_as_written(uri: &str, allows_http: impl Fn(&str) -> bool) -> bool {
1011 !uri.contains("://") || is_own_media(uri) || local_file(uri).is_some() || allows_http(uri)
1012}
1013
1014fn written_or(written: &str, serialized: String) -> Cow<'_, str> {
1016 if serialized == written {
1017 Cow::Borrowed(written)
1018 } else {
1019 Cow::Owned(serialized)
1020 }
1021}
1022
1023enum Unread {
1025 NotUrl,
1027 Ambiguous(String),
1030}
1031
1032fn read_url(url: &str) -> Result<UrlParts<'_>, Unread> {
1034 let (scheme, rest) = url.split_once("://").ok_or(Unread::NotUrl)?;
1035 if scheme.is_empty()
1036 || !scheme
1037 .chars()
1038 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
1039 {
1040 return Err(Unread::NotUrl);
1041 }
1042 let scheme = scheme.to_ascii_lowercase();
1043 let head = url.split(['?', '#']).next().unwrap_or(url);
1049 if head.contains('\\') || url.bytes().any(|b| b.is_ascii_control()) {
1050 return Err(Unread::Ambiguous(scheme));
1051 }
1052 let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
1053 let (authority, path) = rest.split_at(end);
1054 let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
1056 let host = if let Some(v6) = host_port.strip_prefix('[') {
1057 format!("[{}]", v6.split_once(']').ok_or(Unread::NotUrl)?.0)
1058 } else {
1059 host_port.split(':').next().unwrap_or_default().to_owned()
1060 };
1061 if host.is_empty() {
1062 return Err(Unread::NotUrl);
1063 }
1064 if host.contains(['%', ' ', '<', '>', '^', '|'])
1067 || (!host_port.starts_with('[') && host.contains(['[', ']']))
1068 {
1069 return Err(Unread::Ambiguous(scheme));
1070 }
1071 let port = if host_port.starts_with('[') {
1072 host_port
1073 .split_once(']')
1074 .and_then(|(_, rest)| rest.strip_prefix(':'))
1075 .map(str::parse::<u16>)
1076 .transpose()
1077 } else {
1078 host_port
1079 .split_once(':')
1080 .map(|(_, port)| port.parse::<u16>())
1081 .transpose()
1082 }
1083 .map_err(|_| Unread::NotUrl)?;
1084 Ok(UrlParts {
1085 scheme,
1086 host: host.to_ascii_lowercase().trim_end_matches('.').to_owned(),
1087 path: if path.is_empty() { "/" } else { path },
1088 port,
1089 })
1090}
1091
1092#[derive(Debug, Clone, PartialEq, Eq)]
1099#[non_exhaustive]
1100pub struct WebOrigin {
1101 scheme: String,
1102 host: String,
1103 port: u16,
1104}
1105
1106impl WebOrigin {
1107 pub fn parse(origin: &str) -> Result<Self, String> {
1111 let refused = |why: &str| Err(format!("`{origin}` is not an origin: {why}"));
1112 let Some((scheme, rest)) = origin.split_once("://") else {
1113 return refused("it is not `http://host` or `https://host`");
1114 };
1115 let scheme = scheme.to_ascii_lowercase();
1116 if !matches!(scheme.as_str(), "http" | "https") {
1117 return refused("its scheme is not http or https");
1118 }
1119 let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
1120 let (authority, after) = rest.split_at(end);
1121 if !matches!(after, "" | "/") {
1122 return refused("it has a path, a query or a fragment");
1123 }
1124 if authority.contains('@') {
1125 return refused("it has user info");
1126 }
1127 if !authority.is_ascii() || authority.contains('*') {
1128 return refused("its host is not an ASCII host name or address");
1129 }
1130 let Ok(parts) = read_url(origin) else {
1131 return refused("its host or port cannot be read");
1132 };
1133 let port = parts.port.unwrap_or(default_port(&scheme));
1134 Ok(Self {
1135 scheme,
1136 host: parts.host,
1137 port,
1138 })
1139 }
1140
1141 pub fn contains(&self, url: &str) -> bool {
1145 let url = blob_origin(url).unwrap_or(url);
1146 read_url(url).is_ok_and(|parts| {
1147 parts.scheme == self.scheme
1148 && parts.host == self.host
1149 && parts.port.unwrap_or(default_port(&parts.scheme)) == self.port
1150 })
1151 }
1152}
1153
1154impl std::fmt::Display for WebOrigin {
1156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1157 write!(f, "{}://{}", self.scheme, self.host)?;
1158 if self.port != default_port(&self.scheme) {
1159 write!(f, ":{}", self.port)?;
1160 }
1161 Ok(())
1162 }
1163}
1164
1165#[derive(Debug, Clone, PartialEq, Eq, Default)]
1174pub struct WebHosts(Vec<HostPattern>);
1175
1176impl WebHosts {
1177 pub fn parse<S: AsRef<str>>(patterns: &[S]) -> Result<Self, String> {
1179 patterns
1180 .iter()
1181 .map(|p| HostPattern::new(p.as_ref()))
1182 .collect::<Result<Vec<_>, _>>()
1183 .map(Self)
1184 }
1185
1186 pub fn allows(&self, url: &str) -> bool {
1189 let url = blob_origin(url).unwrap_or(url);
1190 let scheme = url.split_once(':').map(|(s, _)| s.to_ascii_lowercase());
1191 if !matches!(scheme.as_deref(), Some("http" | "https")) {
1192 return true;
1193 }
1194 match read_url(url) {
1195 Ok(parts) => self.0.iter().any(|h| h.matches(&parts.host)),
1196 Err(Unread::Ambiguous(_)) => self.0.iter().any(HostPattern::is_any),
1197 Err(Unread::NotUrl) => false,
1198 }
1199 }
1200
1201 pub fn patterns(&self) -> impl Iterator<Item = &str> {
1203 self.0.iter().map(HostPattern::as_str)
1204 }
1205}
1206
1207impl std::fmt::Display for WebHosts {
1210 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1211 for (i, p) in self.0.iter().enumerate() {
1212 if i > 0 {
1213 f.write_str("\n")?;
1214 }
1215 f.write_str(p.as_str())?;
1216 }
1217 Ok(())
1218 }
1219}
1220
1221fn default_port(scheme: &str) -> u16 {
1223 match scheme {
1224 "http" => 80,
1225 "https" => 443,
1226 _ => 0,
1227 }
1228}
1229
1230fn blob_origin(url: &str) -> Option<&str> {
1235 url.get(..5)
1236 .is_some_and(|scheme| scheme.eq_ignore_ascii_case("blob:"))
1237 .then(|| &url[5..])
1238 .filter(|origin| !origin.is_empty())
1239}
1240
1241impl Capabilities {
1242 pub fn all() -> Self {
1246 let any = vec![HostPattern("*".into())];
1247 Self {
1248 network: NetworkGrants {
1249 hosts: any.clone(),
1250 http: Vec::new(),
1251 sockets: Vec::new(),
1252 },
1253 webview: Some(any),
1254 status_bar: true,
1255 clipboard: true,
1256 picker: true,
1257 share: true,
1258 speech: true,
1259 notifications: true,
1260 audio: true,
1261 application: true,
1262 home_dir: true,
1263 open_url: Some(OpenUrlGrant::default()),
1264 windows: Some(WindowsGrant::default()),
1266 ..Self::default()
1268 }
1269 }
1270
1271 pub fn from_json(value: &Value) -> Result<Self, String> {
1276 Self::parse(value, None)
1277 }
1278
1279 pub fn from_json_lenient(value: &Value) -> Result<(Self, Vec<String>), String> {
1290 let mut dropped = Vec::new();
1291 let Value::Object(obj) = value else {
1292 dropped.push(format!(
1293 "capabilities ({value} is not an object): all of them"
1294 ));
1295 return Ok((Self::default(), dropped));
1296 };
1297 let mut readable = Map::new();
1299 for (key, v) in obj {
1300 let one = Value::Object(Map::from_iter([(key.clone(), v.clone())]));
1301 let mut its_dropped = Vec::new();
1302 match Self::parse(&one, Some(&mut its_dropped)) {
1303 Ok(_) => {
1304 dropped.append(&mut its_dropped);
1305 readable.insert(key.clone(), v.clone());
1306 }
1307 Err(e) => dropped.push(format!("capabilities.{key} ({e})")),
1308 }
1309 }
1310 let caps = Self::parse(&Value::Object(readable), Some(&mut Vec::new()))?;
1311 Ok((caps, dropped))
1312 }
1313
1314 fn parse(value: &Value, mut dropped: Option<&mut Vec<String>>) -> Result<Self, String> {
1317 const KNOWN: [&str; 16] = [
1318 "windows",
1319 "network",
1320 "webview",
1321 "statusBar",
1322 "clipboard",
1323 "picker",
1324 "share",
1325 "speech",
1326 "notifications",
1327 "audio",
1328 "application",
1329 "homeDir",
1330 "openUrl",
1331 "process",
1332 "fs",
1333 "host",
1334 ];
1335 let obj = object(value, "capabilities")?;
1336 for key in obj.keys().filter(|k| !KNOWN.contains(&k.as_str())) {
1337 match dropped.as_deref_mut() {
1338 Some(dropped) => dropped.push(format!("capabilities.{key}")),
1340 None => return Err(unknown_key("capabilities", key, &KNOWN)),
1341 }
1342 }
1343 let lenient = dropped.is_some();
1344 let mut http_dropped = Vec::new();
1347 let mut check = |obj: &Map<String, Value>,
1350 what: &str,
1351 keys: &[&str],
1352 name: &str|
1353 -> Result<bool, String> {
1354 let Some(key) = obj.keys().find(|k| !keys.contains(&k.as_str())) else {
1355 return Ok(true);
1356 };
1357 match dropped.as_deref_mut() {
1358 Some(dropped) => {
1359 dropped.push(format!("{name} (unknown key `{key}`)"));
1360 Ok(false)
1361 }
1362 None => Err(unknown_key(what, key, keys)),
1363 }
1364 };
1365 let mut caps = Capabilities::default();
1366 if let Some(network) = obj.get("network") {
1367 let network = object(network, "capabilities.network")?;
1368 if check(
1369 network,
1370 "capabilities.network",
1371 &["hosts", "http", "sockets"],
1372 "capabilities.network",
1373 )? {
1374 if let Some(hosts) = network.get("hosts") {
1375 caps.network.hosts = patterns(hosts, "capabilities.network.hosts")?;
1376 }
1377 if let Some(sockets) = network.get("sockets") {
1378 caps.network.sockets = strings(sockets, "capabilities.network.sockets")?
1379 .iter()
1380 .map(|s| SocketGrant::new(s))
1381 .collect::<Result<_, _>>()?;
1382 }
1383 if let Some(http) = network.get("http") {
1384 let list = http
1385 .as_array()
1386 .ok_or("capabilities.network.http must be an array")?;
1387 for (i, grant) in list.iter().enumerate() {
1388 let name = format!("capabilities.network.http[{i}]");
1389 let parsed = object(grant, "capabilities.network.http[]").and_then(|g| {
1390 let keys = [
1391 "host",
1392 "methods",
1393 "scheme",
1394 "schemes",
1395 "port",
1396 "paths",
1397 "pathPrefix",
1398 "pathPrefixes",
1399 "path_prefixes",
1400 ];
1401 Ok(
1402 match check(g, "capabilities.network.http[]", &keys, &name)? {
1403 true => Some(http_grant(g)?),
1404 false => None,
1405 },
1406 )
1407 });
1408 match parsed {
1409 Ok(Some(grant)) => caps.network.http.push(grant),
1410 Ok(None) => {}
1411 Err(e) if lenient => http_dropped.push(format!("{name} ({e})")),
1414 Err(e) => return Err(e),
1415 }
1416 }
1417 }
1418 }
1419 }
1420 if let Some(webview) = obj.get("webview") {
1421 let webview = object(webview, "capabilities.webview")?;
1422 if check(
1423 webview,
1424 "capabilities.webview",
1425 &["hosts", "input", "media", "runtimeOrigin"],
1426 "capabilities.webview",
1427 )? {
1428 caps.webview = Some(match webview.get("hosts") {
1429 Some(hosts) => patterns(hosts, "capabilities.webview.hosts")?,
1430 None => Vec::new(),
1431 });
1432 if let Some(input) = webview.get("input") {
1433 caps.webview_input = input
1434 .as_bool()
1435 .ok_or("capabilities.webview.input must be a boolean")?;
1436 }
1437 if let Some(runtime_origin) = webview.get("runtimeOrigin") {
1438 caps.webview_runtime_origin = runtime_origin
1439 .as_bool()
1440 .ok_or("capabilities.webview.runtimeOrigin must be a boolean")?;
1441 }
1442 if let Some(media) = webview.get("media") {
1443 caps.webview_media = strings(media, "capabilities.webview.media")?
1444 .iter()
1445 .map(|kind| match kind.as_str() {
1446 "microphone" => Ok(WebMedia::Microphone),
1447 "camera" => Ok(WebMedia::Camera),
1448 _ => Err(format!(
1449 "capabilities.webview.media takes `microphone` and `camera`, not `{kind}`"
1450 )),
1451 })
1452 .collect::<Result<_, _>>()?;
1453 }
1454 }
1455 }
1456 if let Some(status_bar) = obj.get("statusBar") {
1457 caps.status_bar = status_bar
1458 .as_bool()
1459 .ok_or("capabilities.statusBar must be a boolean")?;
1460 }
1461 if let Some(clipboard) = obj.get("clipboard") {
1462 caps.clipboard = clipboard
1463 .as_bool()
1464 .ok_or("capabilities.clipboard must be a boolean")?;
1465 }
1466 if let Some(picker) = obj.get("picker") {
1467 caps.picker = picker
1468 .as_bool()
1469 .ok_or("capabilities.picker must be a boolean")?;
1470 }
1471 if let Some(share) = obj.get("share") {
1472 caps.share = share
1473 .as_bool()
1474 .ok_or("capabilities.share must be a boolean")?;
1475 }
1476 if let Some(speech) = obj.get("speech") {
1477 caps.speech = speech
1478 .as_bool()
1479 .ok_or("capabilities.speech must be a boolean")?;
1480 }
1481 if let Some(notifications) = obj.get("notifications") {
1482 caps.notifications = notifications
1483 .as_bool()
1484 .ok_or("capabilities.notifications must be a boolean")?;
1485 }
1486 if let Some(audio) = obj.get("audio") {
1487 caps.audio = audio
1488 .as_bool()
1489 .ok_or("capabilities.audio must be a boolean")?;
1490 }
1491 if let Some(application) = obj.get("application") {
1492 caps.application = application
1493 .as_bool()
1494 .ok_or("capabilities.application must be a boolean")?;
1495 }
1496 if let Some(home_dir) = obj.get("homeDir") {
1497 caps.home_dir = home_dir
1498 .as_bool()
1499 .ok_or("capabilities.homeDir must be a boolean")?;
1500 }
1501 if let Some(open_url) = obj.get("openUrl") {
1502 match open_url {
1503 Value::Bool(granted) => {
1504 caps.open_url = granted.then(OpenUrlGrant::default);
1505 }
1506 Value::Object(grant) => {
1507 if check(
1508 grant,
1509 "capabilities.openUrl",
1510 &["schemes"],
1511 "capabilities.openUrl",
1512 )? {
1513 let schemes = match grant.get("schemes") {
1514 Some(schemes) => strings(schemes, "capabilities.openUrl.schemes")?,
1515 None => Vec::new(),
1516 };
1517 if schemes.iter().any(|s| {
1518 s.is_empty()
1519 || !s.starts_with(|c: char| c.is_ascii_alphabetic())
1520 || !s
1521 .chars()
1522 .all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c))
1523 }) {
1524 return Err(
1525 "capabilities.openUrl.schemes needs URL schemes (`https`, `mailto`)"
1526 .into(),
1527 );
1528 }
1529 caps.open_url = Some(OpenUrlGrant {
1530 schemes: schemes.iter().map(|s| s.to_ascii_lowercase()).collect(),
1531 });
1532 }
1533 }
1534 _ => {
1535 return Err(
1536 "capabilities.openUrl must be a boolean or an object of `schemes`".into(),
1537 );
1538 }
1539 }
1540 }
1541 if let Some(process) = obj.get("process") {
1542 let process = object(process, "capabilities.process")?;
1543 if check(
1544 process,
1545 "capabilities.process",
1546 &["execute", "exit", "env"],
1547 "capabilities.process",
1548 )? {
1549 if let Some(execute) = process.get("execute") {
1550 caps.process.execute = strings(execute, "capabilities.process.execute")?;
1551 if caps.process.execute.iter().any(|s| !valid_command(s)) {
1552 return Err("capabilities.process.execute needs exact executable names or absolute paths".into());
1553 }
1554 }
1555 if let Some(exit) = process.get("exit") {
1556 caps.process.exit = exit
1557 .as_bool()
1558 .ok_or("capabilities.process.exit must be a boolean")?;
1559 }
1560 if let Some(env) = process.get("env") {
1561 caps.process.env = strings(env, "capabilities.process.env")?;
1562 if caps
1563 .process
1564 .env
1565 .iter()
1566 .any(|name| name.is_empty() || name.contains(['=', '\0']))
1567 {
1568 return Err(
1569 "capabilities.process.env needs nonempty environment variable names"
1570 .into(),
1571 );
1572 }
1573 }
1574 }
1575 }
1576 if let Some(fs) = obj.get("fs") {
1577 let fs = object(fs, "capabilities.fs")?;
1578 if check(fs, "capabilities.fs", &["read", "write"], "capabilities.fs")? {
1579 for (key, target) in [("read", &mut caps.fs.read), ("write", &mut caps.fs.write)] {
1580 if let Some(value) = fs.get(key) {
1581 *target = strings(value, &format!("capabilities.fs.{key}"))?;
1582 for root in target.iter() {
1583 validate_path_pattern(root)?;
1584 }
1585 }
1586 }
1587 }
1588 }
1589 if let Some(windows) = obj.get("windows") {
1590 match windows {
1591 Value::Bool(granted) => caps.windows = granted.then(WindowsGrant::default),
1592 Value::Object(grant) => {
1593 if check(
1594 grant,
1595 "capabilities.windows",
1596 &["kinds", "levels", "max", "overlay"],
1597 "capabilities.windows",
1598 )? {
1599 caps.windows = Some(windows_grant(grant)?);
1600 }
1601 }
1602 _ => {
1603 return Err(
1604 "capabilities.windows must be a boolean or an object of `kinds`, `levels`, `max` and `overlay`"
1605 .into(),
1606 );
1607 }
1608 }
1609 }
1610 if let Some(host) = obj.get("host") {
1611 caps.host = match host {
1612 Value::Bool(all) => {
1613 if *all {
1614 vec!["*".into()]
1615 } else {
1616 Vec::new()
1617 }
1618 }
1619 _ => {
1620 let names = strings(host, "capabilities.host")
1621 .map_err(|e| format!("{e} (or a boolean)"))?;
1622 if let Some(bad) = names.iter().find(|n| match n.strip_suffix('*') {
1623 Some(prefix) => !prefix.is_empty() && !valid_host_name(prefix),
1624 None => !valid_host_name(n),
1625 }) {
1626 return Err(format!(
1627 "capabilities.host: invalid function `{bad}` (a name of {HOST_NAME_CHARS}, or a prefix of them ending in `*`)"
1628 ));
1629 }
1630 names
1631 }
1632 };
1633 }
1634 if let Some(dropped) = dropped {
1635 dropped.append(&mut http_dropped);
1636 }
1637 Ok(caps)
1638 }
1639
1640 pub fn to_json(&self) -> Value {
1642 let mut obj = self.to_json_without_windows();
1643 if let (Value::Object(obj), Some(w)) = (&mut obj, &self.windows) {
1645 let mut o = Map::new();
1646 if !w.kinds.is_empty() {
1647 o.insert(
1648 "kinds".into(),
1649 w.kinds
1650 .iter()
1651 .map(|k| window_kind_name(*k))
1652 .collect::<Vec<_>>()
1653 .into(),
1654 );
1655 }
1656 if !w.levels.is_empty() {
1657 o.insert(
1658 "levels".into(),
1659 w.levels
1660 .iter()
1661 .map(|l| window_level_name(*l))
1662 .collect::<Vec<_>>()
1663 .into(),
1664 );
1665 }
1666 if let Some(max) = w.max {
1667 o.insert("max".into(), max.into());
1668 }
1669 if w.overlay {
1670 o.insert("overlay".into(), true.into());
1671 }
1672 obj.insert("windows".into(), Value::Object(o));
1673 }
1674 obj
1675 }
1676
1677 fn to_json_without_windows(&self) -> Value {
1678 let list =
1679 |l: &[HostPattern]| Value::from(l.iter().map(|p| p.0.clone()).collect::<Vec<_>>());
1680 let mut network = Map::new();
1681 network.insert("hosts".into(), list(&self.network.hosts));
1682 let http: Vec<Value> = self
1683 .network
1684 .http
1685 .iter()
1686 .map(|g| {
1687 let mut o = Map::new();
1688 o.insert("host".into(), g.host.0.clone().into());
1689 if !g.methods.is_empty() {
1690 o.insert("methods".into(), g.methods.clone().into());
1691 }
1692 if !g.schemes.is_empty() {
1693 o.insert("schemes".into(), g.schemes.clone().into());
1694 }
1695 if let Some(port) = g.port {
1696 o.insert("port".into(), port.into());
1697 }
1698 if !g.paths.is_empty() {
1699 o.insert("paths".into(), g.paths.clone().into());
1700 }
1701 if !g.path_prefixes.is_empty() {
1702 o.insert("pathPrefixes".into(), g.path_prefixes.clone().into());
1703 }
1704 Value::Object(o)
1705 })
1706 .collect();
1707 network.insert("http".into(), http.into());
1708 if !self.network.sockets.is_empty() {
1709 let sockets: Vec<String> = self
1710 .network
1711 .sockets
1712 .iter()
1713 .map(SocketGrant::to_string_form)
1714 .collect();
1715 network.insert("sockets".into(), sockets.into());
1716 }
1717 let mut obj = Map::new();
1718 obj.insert("network".into(), Value::Object(network));
1719 obj.insert(
1720 "process".into(),
1721 serde_json::json!({"execute": self.process.execute, "exit": self.process.exit, "env": self.process.env}),
1722 );
1723 obj.insert(
1724 "fs".into(),
1725 serde_json::json!({"read": self.fs.read, "write": self.fs.write}),
1726 );
1727 if let Some(hosts) = &self.webview {
1728 let mut w = Map::new();
1729 w.insert("hosts".into(), list(hosts));
1730 if self.webview_input {
1732 w.insert("input".into(), true.into());
1733 }
1734 if self.webview_runtime_origin {
1735 w.insert("runtimeOrigin".into(), true.into());
1736 }
1737 if !self.webview_media.is_empty() {
1738 let media = self.webview_media.iter().map(|m| m.as_str().into());
1739 w.insert("media".into(), Value::Array(media.collect()));
1740 }
1741 obj.insert("webview".into(), Value::Object(w));
1742 }
1743 obj.insert("statusBar".into(), self.status_bar.into());
1744 obj.insert("clipboard".into(), self.clipboard.into());
1745 obj.insert("picker".into(), self.picker.into());
1746 if self.share {
1748 obj.insert("share".into(), true.into());
1749 }
1750 if self.speech {
1751 obj.insert("speech".into(), true.into());
1752 }
1753 if self.notifications {
1754 obj.insert("notifications".into(), true.into());
1755 }
1756 if self.audio {
1757 obj.insert("audio".into(), true.into());
1758 }
1759 if self.application {
1760 obj.insert("application".into(), true.into());
1761 }
1762 if self.home_dir {
1763 obj.insert("homeDir".into(), true.into());
1764 }
1765 if !self.host.is_empty() {
1766 obj.insert("host".into(), self.host.clone().into());
1767 }
1768 obj.insert(
1769 "openUrl".into(),
1770 match &self.open_url {
1771 None => false.into(),
1772 Some(grant) if grant.schemes.is_empty() => true.into(),
1773 Some(grant) => serde_json::json!({ "schemes": grant.schemes }),
1774 },
1775 );
1776 Value::Object(obj)
1777 }
1778
1779 fn allows_http(&self, method: &str, url: &UrlParts<'_>) -> bool {
1780 if !matches!(url.scheme.as_str(), "http" | "https" | "ws" | "wss") {
1781 return false;
1782 }
1783 self.network.hosts.iter().any(|h| h.matches(&url.host))
1784 || self.network.http.iter().any(|g| g.allows(method, url))
1785 }
1786
1787 fn allows_http_anywhere(&self, method: &str, scheme: &str) -> bool {
1789 matches!(scheme, "http" | "https" | "ws" | "wss")
1790 && (self.network.hosts.iter().any(HostPattern::is_any)
1791 || self
1792 .network
1793 .http
1794 .iter()
1795 .any(|g| g.allows_anywhere(method, scheme)))
1796 }
1797
1798 fn allows_host(&self, name: &str) -> bool {
1799 self.host.iter().any(|g| match g.strip_suffix('*') {
1800 Some(prefix) => name.starts_with(prefix),
1801 None => g == name,
1802 })
1803 }
1804
1805 fn allows_webview(&self, url: &UrlParts<'_>) -> bool {
1806 matches!(url.scheme.as_str(), "http" | "https")
1807 && self
1808 .webview
1809 .as_ref()
1810 .is_some_and(|hosts| hosts.iter().any(|h| h.matches(&url.host)))
1811 }
1812
1813 fn allows_webview_anywhere(&self, scheme: &str) -> bool {
1815 matches!(scheme, "http" | "https")
1816 && self
1817 .webview
1818 .as_ref()
1819 .is_some_and(|hosts| hosts.iter().any(HostPattern::is_any))
1820 }
1821}
1822
1823pub const HOST_NAME_CHARS: &str = "1 to 128 of A-Z a-z 0-9 _ . : -, without `..`";
1825
1826pub fn valid_host_name(name: &str) -> bool {
1830 (1..=128).contains(&name.len())
1831 && name
1832 .bytes()
1833 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b':' | b'-'))
1834 && !name.contains("..")
1835}
1836
1837fn valid_command(command: &str) -> bool {
1838 !command.is_empty()
1839 && !command.contains(['\0', '*'])
1840 && (Path::new(command).has_root()
1846 || absolute(Path::new(command))
1847 || (!command.contains(['/', '\\', ':']) && command != "." && command != "..")
1850 || command.starts_with("asset:/"))
1853}
1854
1855fn validate_path_pattern(path: &str) -> Result<(), String> {
1856 if [
1857 "$HOME",
1858 "${HOME}",
1859 "$USERPROFILE",
1860 "${USERPROFILE}",
1861 "%USERPROFILE%",
1862 "~",
1863 ]
1864 .into_iter()
1865 .any(|prefix| {
1866 path.strip_prefix(prefix)
1867 .is_some_and(|tail| tail.is_empty() || tail.starts_with(['/', '\\']))
1868 }) {
1869 return Err("use ${homeDir} for the native home directory".into());
1870 }
1871 let placeholder = ["${dataDir}", "${pluginDir}", "${homeDir}"]
1872 .into_iter()
1873 .find(|prefix| path.starts_with(prefix));
1874 let tail = placeholder.and_then(|prefix| path.strip_prefix(prefix));
1875 if path.is_empty()
1876 || path.contains(['\0', '*'])
1877 || tail.is_some_and(|s| !s.is_empty() && !s.starts_with('/'))
1878 || (placeholder.is_none() && path.contains("${"))
1879 || tail.is_some_and(|s| s.contains("${"))
1880 || Path::new(path)
1881 .components()
1882 .any(|p| matches!(p, Component::ParentDir))
1883 {
1884 return Err(
1885 "filesystem roots must use valid host placeholders and contain no traversal".into(),
1886 );
1887 }
1888 Ok(())
1889}
1890
1891pub fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
1897 let path = std::fs::canonicalize(path)?;
1898 #[cfg(windows)]
1899 if let Some(plain) = path.to_str().and_then(without_verbatim_prefix) {
1900 return Ok(PathBuf::from(plain));
1901 }
1902 Ok(path)
1903}
1904
1905#[cfg_attr(not(windows), allow(dead_code))]
1913fn without_verbatim_prefix(path: &str) -> Option<String> {
1914 let rest = path.strip_prefix(r"\\?\")?;
1915 let (plain, tail) = if let Some(unc) = rest.strip_prefix(r"UNC\") {
1916 (format!(r"\\{unc}"), unc)
1917 } else {
1918 let bytes = rest.as_bytes();
1919 if bytes.len() < 3 || !bytes[0].is_ascii_alphabetic() || &bytes[1..3] != b":\\" {
1920 return None;
1921 }
1922 (rest.to_owned(), &rest[3..])
1923 };
1924 if plain.len() >= 260 {
1925 return None;
1926 }
1927 let tail = tail.strip_suffix('\\').unwrap_or(tail);
1929 let device = |name: &str| {
1930 let stem = name.split('.').next().unwrap_or(name).trim_end();
1931 ["CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"]
1932 .iter()
1933 .any(|d| stem.eq_ignore_ascii_case(d))
1934 || (stem.len() == 4
1935 && ["COM", "LPT"]
1936 .iter()
1937 .any(|d| stem[..3].eq_ignore_ascii_case(d))
1938 && matches!(stem.as_bytes()[3], b'1'..=b'9'))
1939 };
1940 let plain_component = |c: &str| {
1941 !c.is_empty()
1942 && c != "."
1943 && c != ".."
1944 && !c.contains('/')
1945 && !c.ends_with(['.', ' '])
1946 && !device(c)
1947 };
1948 (tail.is_empty() || tail.split('\\').all(plain_component)).then_some(plain)
1949}
1950
1951#[derive(Debug, Clone, PartialEq, Eq)]
1955#[non_exhaustive]
1956pub enum FileRefusal {
1957 Invalid(String),
1960 NotGranted(String),
1962}
1963
1964impl std::fmt::Display for FileRefusal {
1965 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1966 match self {
1967 FileRefusal::Invalid(why) | FileRefusal::NotGranted(why) => f.write_str(why),
1968 }
1969 }
1970}
1971
1972fn resolved_path(path: &Path) -> Result<PathBuf, String> {
1973 if !absolute(path) || path.components().any(|p| matches!(p, Component::ParentDir)) {
1974 return Err("filesystem paths must be absolute and contain no parent traversal".into());
1975 }
1976 let mut cursor = path;
1977 let mut tail = Vec::new();
1978 loop {
1979 match std::fs::symlink_metadata(cursor) {
1980 Ok(_) => {
1981 let mut resolved = canonicalize(cursor).map_err(|e| e.to_string())?;
1982 for part in tail.into_iter().rev() {
1983 resolved.push(part);
1984 }
1985 return Ok(resolved);
1986 }
1987 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1988 tail.push(
1989 cursor
1990 .file_name()
1991 .ok_or("invalid filesystem path")?
1992 .to_owned(),
1993 );
1994 cursor = cursor.parent().ok_or("invalid filesystem path")?;
1995 }
1996 Err(e) => return Err(e.to_string()),
1997 }
1998 }
1999}
2000
2001fn object<'a>(value: &'a Value, what: &str) -> Result<&'a Map<String, Value>, String> {
2002 value
2003 .as_object()
2004 .ok_or_else(|| format!("{what} must be an object"))
2005}
2006
2007const WINDOW_KINDS: [(&str, crate::desktop::WindowKind); 5] = [
2008 ("normal", crate::desktop::WindowKind::Normal),
2009 ("dialog", crate::desktop::WindowKind::Dialog),
2010 ("panel", crate::desktop::WindowKind::Panel),
2011 ("popup", crate::desktop::WindowKind::Popup),
2012 ("overlay", crate::desktop::WindowKind::Overlay),
2013];
2014
2015const WINDOW_LEVELS: [(&str, crate::desktop::WindowLevel); 4] = [
2016 ("normal", crate::desktop::WindowLevel::Normal),
2017 ("floating", crate::desktop::WindowLevel::Floating),
2018 ("aboveDock", crate::desktop::WindowLevel::AboveDock),
2019 ("desktopIcon", crate::desktop::WindowLevel::DesktopIcon),
2020];
2021
2022fn window_kind_name(kind: crate::desktop::WindowKind) -> &'static str {
2023 WINDOW_KINDS
2024 .iter()
2025 .find(|(_, k)| *k == kind)
2026 .map_or("normal", |(n, _)| n)
2027}
2028
2029fn window_level_name(level: crate::desktop::WindowLevel) -> &'static str {
2030 WINDOW_LEVELS
2031 .iter()
2032 .find(|(_, l)| *l == level)
2033 .map_or("normal", |(n, _)| n)
2034}
2035
2036fn windows_grant(grant: &Map<String, Value>) -> Result<WindowsGrant, String> {
2038 let mut out = WindowsGrant::default();
2039 if let Some(kinds) = grant.get("kinds") {
2040 for name in strings(kinds, "capabilities.windows.kinds")? {
2041 let Some((_, kind)) = WINDOW_KINDS.iter().find(|(n, _)| *n == name) else {
2042 return Err(format!(
2043 "capabilities.windows.kinds: unknown kind `{name}` (normal, dialog, panel, popup or overlay)"
2044 ));
2045 };
2046 out.kinds.push(*kind);
2047 }
2048 }
2049 if let Some(levels) = grant.get("levels") {
2050 for name in strings(levels, "capabilities.windows.levels")? {
2051 let Some((_, level)) = WINDOW_LEVELS.iter().find(|(n, _)| *n == name) else {
2052 return Err(format!(
2053 "capabilities.windows.levels: unknown level `{name}` (normal, floating, aboveDock or desktopIcon)"
2054 ));
2055 };
2056 out.levels.push(*level);
2057 }
2058 }
2059 if let Some(max) = grant.get("max") {
2060 out.max = Some(
2061 max.as_u64()
2062 .and_then(|m| u32::try_from(m).ok())
2063 .ok_or("capabilities.windows.max must be a whole number")?,
2064 );
2065 }
2066 if let Some(v) = grant.get("overlay") {
2067 out.overlay = v
2068 .as_bool()
2069 .ok_or("capabilities.windows.overlay must be a boolean")?;
2070 }
2071 Ok(out)
2072}
2073
2074fn unknown_key(what: &str, key: &str, known: &[&str]) -> String {
2075 format!("{what}: unknown key `{key}` (known: {})", known.join(", "))
2076}
2077
2078fn strings(value: &Value, what: &str) -> Result<Vec<String>, String> {
2079 value
2080 .as_array()
2081 .and_then(|a| a.iter().map(|v| v.as_str().map(str::to_owned)).collect())
2082 .ok_or_else(|| format!("{what} must be an array of strings"))
2083}
2084
2085fn http_grant(g: &Map<String, Value>) -> Result<HttpGrant, String> {
2089 let what = "capabilities.network.http[]";
2090 let host = g
2091 .get("host")
2092 .and_then(Value::as_str)
2093 .ok_or_else(|| format!("{what} needs a `host`"))?;
2094 let list = |key: &str| -> Result<Vec<String>, String> {
2096 match g.get(key) {
2097 None => Ok(Vec::new()),
2098 Some(Value::String(s)) => Ok(vec![s.clone()]),
2099 Some(v) => strings(v, &format!("{what}.{key}")),
2100 }
2101 };
2102 let methods = list("methods")?
2103 .into_iter()
2104 .map(|m| {
2105 if !m.is_empty() && m.bytes().all(|b| b.is_ascii_alphabetic() || b == b'-') {
2106 Ok(m.to_ascii_uppercase())
2107 } else {
2108 Err(format!("{what}.methods: `{m}` is not an HTTP method"))
2109 }
2110 })
2111 .collect::<Result<Vec<_>, _>>()?;
2112 let mut schemes = Vec::new();
2113 for scheme in list("scheme")?.into_iter().chain(list("schemes")?) {
2114 let scheme = scheme.to_ascii_lowercase();
2115 if !matches!(scheme.as_str(), "http" | "https" | "ws" | "wss") {
2116 return Err(format!(
2117 "{what}.schemes: `{scheme}` is not http, https, ws or wss"
2118 ));
2119 }
2120 if !schemes.contains(&scheme) {
2121 schemes.push(scheme);
2122 }
2123 }
2124 let port = match g.get("port") {
2125 None => None,
2126 Some(v) => Some(
2127 v.as_u64()
2128 .and_then(|p| u16::try_from(p).ok())
2129 .filter(|&p| p != 0)
2130 .ok_or_else(|| format!("{what}.port must be a port from 1 to 65535"))?,
2131 ),
2132 };
2133 let paths = list("paths")?;
2134 let mut path_prefixes = Vec::new();
2135 for prefix in list("pathPrefix")?
2136 .into_iter()
2137 .chain(list("pathPrefixes")?)
2138 .chain(list("path_prefixes")?)
2139 {
2140 if !path_prefixes.contains(&prefix) {
2141 path_prefixes.push(prefix);
2142 }
2143 }
2144 if let Some(bad) = paths
2146 .iter()
2147 .chain(&path_prefixes)
2148 .find(|p| !p.starts_with('/') || p.contains(['*', '?', '#']))
2149 {
2150 return Err(format!(
2151 "{what}: path `{bad}` must start with / and has no `*`, `?` or `#` (paths match as written)"
2152 ));
2153 }
2154 let as_sent = |list: Vec<String>| -> Result<Vec<String>, String> {
2157 let mut sent = Vec::new();
2158 for path in list {
2159 let path = path_as_sent(&path).ok_or_else(|| {
2160 format!("{what}: path `{path}` has a `.` or `..` segment, which no request sends")
2161 })?;
2162 if !sent.contains(&path) {
2163 sent.push(path);
2164 }
2165 }
2166 Ok(sent)
2167 };
2168 let paths = as_sent(paths)?;
2169 let path_prefixes = as_sent(path_prefixes)?;
2170 Ok(HttpGrant {
2171 host: HostPattern::new(host)?,
2172 methods,
2173 schemes,
2174 port,
2175 paths,
2176 path_prefixes,
2177 })
2178}
2179
2180fn patterns(value: &Value, what: &str) -> Result<Vec<HostPattern>, String> {
2181 strings(value, what)?
2182 .iter()
2183 .map(|p| HostPattern::new(p))
2184 .collect()
2185}
2186
2187#[derive(Debug, Clone, PartialEq, Eq)]
2190pub struct Access {
2191 pub declared: Capabilities,
2193 pub granted: Option<Capabilities>,
2195}
2196
2197impl Default for Access {
2198 fn default() -> Self {
2199 Self::all()
2200 }
2201}
2202
2203impl Access {
2204 pub fn all() -> Self {
2206 Self {
2207 declared: Capabilities::all(),
2208 granted: None,
2209 }
2210 }
2211
2212 fn each(&self, f: impl Fn(&Capabilities) -> bool) -> bool {
2213 f(&self.declared) && self.granted.as_ref().is_none_or(f)
2214 }
2215
2216 pub fn is_unrestricted(&self) -> bool {
2219 let all = Capabilities::all();
2220 self.declared == all && self.granted.as_ref().is_none_or(|g| *g == all)
2221 }
2222
2223 pub fn allows_process(&self, command: &str) -> bool {
2226 valid_command(command) && self.each(|c| c.process.execute.iter().any(|p| p == command))
2227 }
2228
2229 pub fn allows_exit(&self) -> bool {
2232 self.each(|caps| caps.process.exit)
2233 }
2234
2235 pub fn allows_env(&self, name: &str) -> bool {
2238 let defaults = include_str!("default-env").lines().filter_map(|line| {
2239 let name = line.split('#').next().unwrap_or_default().trim();
2240 (!name.is_empty()).then_some(name)
2241 });
2242 defaults
2243 .into_iter()
2244 .any(|allowed| env_names_match(allowed, name))
2245 || self.each(|caps| {
2246 caps.process
2247 .env
2248 .iter()
2249 .any(|allowed| env_names_match(allowed, name))
2250 })
2251 }
2252
2253 pub fn authorize_file(
2256 &self,
2257 path: &Path,
2258 data_dir: &Path,
2259 write: bool,
2260 ) -> Result<PathBuf, FileRefusal> {
2261 self.authorize_file_with_paths(path, data_dir, &TrustedPaths::default(), write)
2262 }
2263
2264 pub fn authorize_file_with_paths(
2266 &self,
2267 path: &Path,
2268 data_dir: &Path,
2269 paths: &TrustedPaths,
2270 write: bool,
2271 ) -> Result<PathBuf, FileRefusal> {
2272 let requested = if let Some(text) = path.to_str().filter(|s| s.starts_with("${")) {
2273 paths
2274 .resolve_root(text, data_dir)
2275 .map_err(FileRefusal::Invalid)?
2276 } else {
2277 path.to_owned()
2278 };
2279 let resolved = resolved_path(&requested).map_err(FileRefusal::Invalid)?;
2280 let allowed = self.each(|c| {
2281 let roots = if write { &c.fs.write } else { &c.fs.read };
2282 roots.iter().any(|root| {
2283 paths
2284 .resolve_root(root, data_dir)
2285 .and_then(|r| resolved_path(&r))
2286 .is_ok_and(|root| resolved.starts_with(root))
2287 })
2288 });
2289 if allowed {
2290 Ok(resolved)
2291 } else {
2292 Err(FileRefusal::NotGranted(format!(
2293 "filesystem {} is not granted by capabilities.fs",
2294 if write { "write" } else { "read" }
2295 )))
2296 }
2297 }
2298
2299 pub fn allows_socket(&self, host: &str, port: u16) -> bool {
2303 if host.is_empty() || host.contains(['/', '@', '?', '#', '\0']) {
2304 return false;
2305 }
2306 let host = host.to_ascii_lowercase();
2307 let host = host
2308 .strip_prefix('[')
2309 .and_then(|h| h.strip_suffix(']'))
2310 .unwrap_or(&host)
2311 .trim_end_matches('.');
2312 self.each(|c| {
2313 c.network
2314 .sockets
2315 .iter()
2316 .any(|grant| grant.port == port && grant.host == host)
2317 })
2318 }
2319
2320 pub fn allows_websocket(&self, url: &str) -> bool {
2324 let http = if let Some(rest) = url.strip_prefix("wss:") {
2325 format!("https:{rest}")
2326 } else if let Some(rest) = url.strip_prefix("ws:") {
2327 format!("http:{rest}")
2328 } else {
2329 return false;
2330 };
2331 self.allows_http("GET", &http) || self.allows_http("GET", url)
2332 }
2333
2334 pub fn allows_http(&self, method: &str, url: &str) -> bool {
2337 if url.starts_with("asset:") {
2338 return true;
2339 }
2340 match read_url(url) {
2341 Ok(parts) => {
2343 url::Url::parse(url).is_ok_and(|whatwg| self.allows_parts(method, parts, &whatwg))
2344 }
2345 Err(Unread::Ambiguous(scheme)) => {
2347 self.each(|c| c.allows_http_anywhere(method, &scheme))
2348 }
2349 Err(Unread::NotUrl) => false,
2350 }
2351 }
2352
2353 fn allows_parsed(&self, method: &str, url: &str, whatwg: &url::Url) -> bool {
2358 match read_url(url) {
2359 Ok(parts) => self.allows_parts(method, parts, whatwg),
2360 Err(Unread::Ambiguous(scheme)) => {
2361 self.each(|c| c.allows_http_anywhere(method, &scheme))
2362 }
2363 Err(Unread::NotUrl) => false,
2364 }
2365 }
2366
2367 fn allows_parts(&self, method: &str, parts: UrlParts<'_>, whatwg: &url::Url) -> bool {
2370 let parts = UrlParts {
2371 path: whatwg.path(),
2372 ..parts
2373 };
2374 self.each(|c| c.allows_http(method, &parts))
2375 }
2376
2377 pub fn http_url<'a>(&self, method: &str, url: &'a str) -> Option<Cow<'a, str>> {
2381 if url.starts_with("asset:") {
2382 return Some(Cow::Borrowed(url));
2383 }
2384 let whatwg = url::Url::parse(url).ok()?;
2385 self.allows_parsed(method, whatwg.as_str(), &whatwg)
2386 .then(|| written_or(url, whatwg.into()))
2387 }
2388
2389 pub fn allows_media(&self, uri: &str) -> bool {
2393 self.media_url(uri, None, None).is_some()
2394 }
2395
2396 pub fn media_url<'a>(
2416 &self,
2417 uri: &'a str,
2418 base: Option<&str>,
2419 files: Option<&MediaFiles>,
2420 ) -> Option<Cow<'a, str>> {
2421 if is_own_media(uri) {
2422 let inside = !starts_with_ignoring_case(uri, "asset:") || is_inside_assets(uri);
2425 return (inside || self.is_unrestricted()).then_some(Cow::Borrowed(uri));
2426 }
2427 if self.is_unrestricted() {
2428 return media_as_written(uri, |url| self.allows_http("GET", url))
2429 .then_some(Cow::Borrowed(uri));
2430 }
2431 let file_url = starts_with_ignoring_case(uri, "file:");
2432 if (base.is_none() || file_url)
2433 && let Some(path) = local_file(uri)
2434 {
2435 let real = files?.readable(&path?)?;
2436 let loads = if file_url {
2437 file_url_of(&real)?
2438 } else {
2439 real.into_os_string().into_string().ok()?
2440 };
2441 return Some(written_or(uri, loads));
2442 }
2443 let stripped = whatwg_stripped(uri);
2446 let scheme = scheme_of(&stripped);
2447 let names_host = scheme.is_some()
2448 || stripped.starts_with("//")
2449 || stripped.starts_with(['\\'])
2450 || stripped.starts_with("/\\");
2451 if !names_host {
2452 return (base.is_some() || uri.trim().is_empty()).then_some(Cow::Borrowed(uri));
2456 }
2457 let base = || base.and_then(|b| url::Url::parse(b).ok());
2459 let trimmed = uri.trim_matches(|c: char| c <= ' ');
2465 let head = trimmed.split(['?', '#']).next().unwrap_or(trimmed);
2466 if head.contains('\\')
2467 || trimmed.bytes().any(|b| b.is_ascii_control())
2468 || matches!(read_url(trimmed), Err(Unread::Ambiguous(_)))
2469 {
2470 let scheme = match scheme {
2471 Some(scheme) => scheme.to_ascii_lowercase(),
2472 None => base()?.scheme().to_owned(),
2473 };
2474 return self
2475 .each(|c| c.allows_http_anywhere("GET", &scheme))
2476 .then_some(Cow::Borrowed(uri));
2477 }
2478 let parsed = match scheme {
2479 Some(_) => url::Url::parse(trimmed),
2480 None => base()?.join(trimmed),
2481 }
2482 .ok()?;
2483 self.allows_parsed("GET", parsed.as_str(), &parsed)
2484 .then(|| written_or(uri, parsed.into()))
2485 }
2486
2487 pub fn media_redirect(&self, base: &str, location: &str) -> Result<String, String> {
2493 let url = resolve_reference(base, location);
2494 if !(url.starts_with("http://") || url.starts_with("https://")) {
2495 return Err(format!("redirect to `{url}` is not an http(s) URL"));
2496 }
2497 if !self.is_unrestricted() && !self.allows_media(&url) {
2498 return Err(format!(
2499 "redirect to `{url}` is not granted by capabilities.network"
2500 ));
2501 }
2502 Ok(url)
2503 }
2504
2505 pub fn allows_webviews(&self) -> bool {
2507 self.each(|c| c.webview.is_some())
2508 }
2509
2510 pub fn allows_webview(&self, url: &str) -> bool {
2517 if url == "about:blank" {
2518 return self.allows_webviews();
2519 }
2520 let url = blob_origin(url).unwrap_or(url);
2521 match read_url(url) {
2522 Ok(parts) => self.each(|c| c.allows_webview(&parts)),
2523 Err(Unread::Ambiguous(scheme)) => self.each(|c| c.allows_webview_anywhere(&scheme)),
2524 Err(Unread::NotUrl) => false,
2525 }
2526 }
2527
2528 pub fn allows_webview_with(&self, url: &str, origin: Option<&WebOrigin>) -> bool {
2533 self.allows_webview(url)
2534 || origin.is_some_and(|o| self.allows_runtime_origin() && o.contains(url))
2535 }
2536
2537 pub fn allows_webview_in(
2541 &self,
2542 url: &str,
2543 origin: Option<&WebOrigin>,
2544 hosts: Option<&WebHosts>,
2545 ) -> bool {
2546 hosts.is_none_or(|h| h.allows(url)) && self.allows_webview_with(url, origin)
2547 }
2548
2549 pub fn allows_runtime_origin(&self) -> bool {
2553 self.each(|c| c.webview.is_some() && c.webview_runtime_origin)
2554 }
2555
2556 pub fn allows_web_input(&self) -> bool {
2559 self.each(|c| c.webview.is_some() && c.webview_input)
2560 }
2561
2562 pub fn allows_web_media(&self, media: WebMedia) -> bool {
2566 self.each(|c| c.webview.is_some() && c.webview_media.contains(&media))
2567 }
2568
2569 pub fn check_window(
2574 &self,
2575 kind: crate::desktop::WindowKind,
2576 attributes: &crate::desktop::WindowAttributes,
2577 open: usize,
2578 ) -> Result<(), String> {
2579 if !self.each(|c| c.windows.is_some()) {
2580 return Err("windows of the app's own are not granted by capabilities.windows".into());
2581 }
2582 if !self.each(|c| c.windows.as_ref().is_some_and(|w| w.allows_kind(kind))) {
2583 return Err(format!(
2584 "a window of kind `{}` is not granted by capabilities.windows{}",
2585 window_kind_name(kind),
2586 if kind == crate::desktop::WindowKind::Overlay {
2587 " (overlays need `overlay: true`)"
2588 } else {
2589 ""
2590 }
2591 ));
2592 }
2593 if !self.each(|c| {
2594 c.windows
2595 .as_ref()
2596 .is_some_and(|w| w.max.is_none_or(|max| open < max as usize))
2597 }) {
2598 return Err("capabilities.windows.max windows are open already".into());
2599 }
2600 let mut own = attributes.clone();
2601 let level = own.level.take();
2603 let denied = self.deny_window_attributes(&mut own);
2604 if let Some(name) = denied.first() {
2605 return Err(format!(
2606 "the window attribute `{name}` is not granted by capabilities.windows"
2607 ));
2608 }
2609 if let Some(level) = level
2610 && !self.each(|c| c.windows.as_ref().is_some_and(|w| w.allows_level(level)))
2611 {
2612 return Err(format!(
2613 "the window level `{}` is not granted by capabilities.windows.levels",
2614 window_level_name(level)
2615 ));
2616 }
2617 Ok(())
2618 }
2619
2620 pub fn deny_window_attributes(
2626 &self,
2627 attributes: &mut crate::desktop::WindowAttributes,
2628 ) -> Vec<&'static str> {
2629 let mut denied = Vec::new();
2630 let grant = |f: &dyn Fn(&WindowsGrant) -> bool| {
2631 self.each(|c| match &c.windows {
2632 Some(w) => f(w),
2633 None => false,
2635 })
2636 };
2637 if let Some(level) = attributes.level
2638 && level != crate::desktop::WindowLevel::Normal
2639 && !grant(&|w| w.allows_level(level))
2640 {
2641 attributes.level = None;
2642 denied.push("level");
2643 }
2644 if attributes.passes_pointer() && !grant(&|w| w.overlay) {
2645 attributes.pointer_events = None;
2646 denied.push("pointerEvents");
2647 }
2648 denied
2649 }
2650
2651 pub fn allows_status_bar(&self) -> bool {
2653 self.each(|c| c.status_bar)
2654 }
2655
2656 pub fn allows_share(&self) -> bool {
2659 self.each(|c| c.share)
2660 }
2661
2662 pub fn allows_clipboard(&self) -> bool {
2664 self.each(|c| c.clipboard)
2665 }
2666
2667 pub fn allows_picker(&self) -> bool {
2669 self.each(|c| c.picker)
2670 }
2671
2672 pub fn allows_speech(&self) -> bool {
2675 self.each(|c| c.speech)
2676 }
2677
2678 pub fn allows_notifications(&self) -> bool {
2681 self.each(|c| c.notifications)
2682 }
2683
2684 pub fn allows_audio(&self) -> bool {
2686 self.each(|c| c.audio)
2687 }
2688
2689 pub fn allows_application(&self) -> bool {
2694 self.each(|c| c.application)
2695 }
2696
2697 pub fn allows_home_dir(&self) -> bool {
2699 self.each(|c| c.home_dir)
2700 }
2701
2702 pub fn allows_host(&self, name: &str) -> bool {
2704 self.each(|c| c.allows_host(name))
2705 }
2706
2707 pub fn allows_open_url(&self, url: &str) -> bool {
2710 let Some(scheme) = url
2711 .split_once(':')
2712 .map(|(scheme, _)| scheme.to_ascii_lowercase())
2713 else {
2714 return false;
2715 };
2716 self.each(|c| c.open_url.as_ref().is_some_and(|g| g.allows(&scheme)))
2717 }
2718}
2719
2720pub fn resolve_reference(base: &str, location: &str) -> String {
2726 match url::Url::parse(base).and_then(|base| base.join(location)) {
2727 Ok(url) => url.into(),
2728 Err(_) => location.to_owned(),
2729 }
2730}
2731
2732pub fn is_same_origin(a: &str, b: &str) -> bool {
2736 match (url::Url::parse(a), url::Url::parse(b)) {
2737 (Ok(a), Ok(b)) => {
2738 let origin = a.origin();
2739 origin.is_tuple() && origin == b.origin()
2740 }
2741 _ => false,
2742 }
2743}
2744
2745#[cfg(test)]
2746mod tests {
2747 #[test]
2748 fn verbatim_windows_paths_compare_in_their_plain_form() {
2749 use super::without_verbatim_prefix as plain;
2750 assert_eq!(plain(r"\\?\C:\Users\a").as_deref(), Some(r"C:\Users\a"));
2751 assert_eq!(plain(r"\\?\d:\").as_deref(), Some(r"d:\"));
2752 assert_eq!(plain(r"\\?\C:\app\").as_deref(), Some(r"C:\app\"));
2753 assert_eq!(
2754 plain(r"\\?\UNC\server\share\a").as_deref(),
2755 Some(r"\\server\share\a")
2756 );
2757 for path in [
2759 r"C:\a",
2760 r"\\server\share",
2761 "/home/a",
2762 r"\\?\Volume{x}\a",
2763 r"\\.\C:\a",
2764 ] {
2765 assert_eq!(plain(path), None, "{path}");
2766 }
2767 for path in [
2769 r"\\?\C:\a\NUL",
2770 r"\\?\C:\a\com1.txt",
2771 r"\\?\C:\a\Lpt9",
2772 r"\\?\C:\a\b.",
2773 r"\\?\C:\a\b ",
2774 r"\\?\C:\a\..\b",
2775 r"\\?\C:\a\.\b",
2776 r"\\?\C:\a\\b",
2777 r"\\?\C:\a/b",
2778 ] {
2779 assert_eq!(plain(path), None, "{path}");
2780 }
2781 assert_eq!(
2782 plain(r"\\?\C:\a\com10\console").as_deref(),
2783 Some(r"C:\a\com10\console")
2784 );
2785 let long = format!(r"\\?\C:\{}", "a".repeat(260));
2786 assert_eq!(plain(&long), None);
2787 }
2788
2789 #[test]
2790 fn anchored_roots_join_their_tail_component_by_component() {
2791 let app = PathBuf::from(if cfg!(windows) { r"C:\app" } else { "/app" });
2792 let paths = super::TrustedPaths {
2793 plugin_dir: Some(app.clone()),
2794 home_dir: None,
2795 };
2796 let root = paths.resolve_root("${pluginDir}/a//b/", &app).unwrap();
2797 assert_eq!(root, app.join("a").join("b"));
2798 let names = root.components().rev().take(2).collect::<Vec<_>>();
2799 assert_eq!(
2800 names,
2801 [
2802 Component::Normal("b".as_ref()),
2803 Component::Normal("a".as_ref())
2804 ]
2805 );
2806 }
2807 use super::*;
2808
2809 fn caps(json: &str) -> Capabilities {
2810 Capabilities::from_json(&serde_json::from_str(json).unwrap()).unwrap()
2811 }
2812
2813 #[test]
2814 fn windows_are_granted_by_kind_level_and_count() {
2815 use crate::desktop::{WindowAttributes, WindowKind, WindowLevel, WindowPointerEvents};
2816 let none = WindowAttributes::default();
2817 let all = Access::all();
2820 assert!(all.check_window(WindowKind::Panel, &none, 10).is_ok());
2821 assert!(all.check_window(WindowKind::Overlay, &none, 0).is_err());
2822 let click_through = WindowAttributes {
2823 pointer_events: Some(WindowPointerEvents::None),
2824 ..Default::default()
2825 };
2826 assert!(
2827 all.check_window(WindowKind::Normal, &click_through, 0)
2828 .is_err()
2829 );
2830 let box_none = WindowAttributes {
2832 pointer_events: Some(WindowPointerEvents::BoxNone),
2833 ..Default::default()
2834 };
2835 assert!(all.check_window(WindowKind::Popup, &box_none, 0).is_err());
2836 let declared = |json: &str| Access {
2838 declared: caps(json),
2839 granted: None,
2840 };
2841 assert!(
2842 declared(r#"{"process":{"exit":true}}"#)
2843 .check_window(WindowKind::Normal, &none, 0)
2844 .is_err()
2845 );
2846 let limited = declared(
2847 r#"{"windows":{"kinds":["normal","dialog"],"levels":["normal","floating"],"max":2}}"#,
2848 );
2849 assert!(limited.check_window(WindowKind::Dialog, &none, 1).is_ok());
2850 assert!(limited.check_window(WindowKind::Popup, &none, 0).is_err());
2851 assert!(limited.check_window(WindowKind::Normal, &none, 2).is_err());
2852 let above = WindowAttributes {
2853 level: Some(WindowLevel::AboveDock),
2854 ..Default::default()
2855 };
2856 assert!(limited.check_window(WindowKind::Normal, &above, 0).is_err());
2857 let overlay = declared(r#"{"windows":{"overlay":true}}"#);
2858 assert!(
2859 overlay
2860 .check_window(WindowKind::Overlay, &click_through, 0)
2861 .is_ok()
2862 );
2863 assert!(
2864 overlay
2865 .check_window(WindowKind::Popup, &box_none, 0)
2866 .is_ok()
2867 );
2868 let mut asked = WindowAttributes {
2870 title: Some("Notes".into()),
2871 level: Some(WindowLevel::AboveDock),
2872 ..Default::default()
2873 };
2874 assert_eq!(limited.deny_window_attributes(&mut asked), ["level"]);
2875 assert_eq!(asked.title.as_deref(), Some("Notes"));
2876 assert_eq!(asked.level, None);
2877 }
2878
2879 #[test]
2880 fn environment_names_match_exactly_except_on_windows() {
2881 let access = Access {
2882 declared: caps(r#"{"process":{"env":["MY_TOKEN"]}}"#),
2883 granted: None,
2884 };
2885 assert!(access.allows_env("MY_TOKEN"));
2886 assert_eq!(access.allows_env("my_token"), cfg!(windows));
2887 assert_eq!(super::env_names_match("Path", "PATH"), cfg!(windows));
2888 }
2889
2890 #[test]
2891 fn roots_stay_within_their_anchor_and_bare_commands_have_no_drive() {
2892 let anchor = Path::new(if cfg!(windows) { "C:\\app" } else { "/app" });
2893 assert!(super::within(anchor, Path::new("data/x"), "r").is_ok());
2894 assert!(super::within(anchor, Path::new("/etc"), "r").is_err());
2895 #[cfg(windows)]
2896 for tail in ["C:/Windows", "\\\\srv\\share", "\\Users", "D:x"] {
2897 assert!(
2898 super::within(anchor, Path::new(tail), "r").is_err(),
2899 "{tail}"
2900 );
2901 }
2902 assert!(!super::valid_command("C:git"));
2903 assert!(super::valid_command("git"));
2904 }
2905
2906 #[test]
2907 fn a_manifest_with_absolute_commands_and_roots_parses() {
2908 let declared = caps(
2911 r#"{"process":{"execute":["/bin/sh","/usr/bin/open","git"]},"fs":{"read":["/Applications"]}}"#,
2912 );
2913 assert_eq!(
2914 declared.process.execute,
2915 ["/bin/sh", "/usr/bin/open", "git"]
2916 );
2917 if !cfg!(windows) {
2918 assert!(super::valid_command("/bin/sh"));
2919 assert!(super::absolute(Path::new("/Applications")));
2920 }
2921 }
2922
2923 #[test]
2924 fn system_capabilities_are_explicit_and_intersected() {
2925 let declared = caps(
2926 r#"{"process":{"execute":["claude","codex"]},"fs":{"read":["${dataDir}"],"write":["${dataDir}"]}}"#,
2927 );
2928 assert_eq!(
2929 Capabilities::from_json(&declared.to_json()).unwrap(),
2930 declared
2931 );
2932 let access = Access {
2933 declared,
2934 granted: Some(caps(
2935 r#"{"process":{"execute":["codex"]},"fs":{"read":["${dataDir}/conversations"]}}"#,
2936 )),
2937 };
2938 assert!(access.allows_process("codex"));
2939 assert!(!access.allows_process("claude"));
2940 assert!(!access.allows_process("/usr/bin/codex"));
2941 assert!(!Access::all().allows_process("codex"));
2942 let root = std::env::current_dir().unwrap();
2943 assert!(
2944 access
2945 .authorize_file(&root.join("conversations/new.json"), &root, false)
2946 .is_ok()
2947 );
2948 assert!(
2949 access
2950 .authorize_file(&root.join("other.json"), &root, false)
2951 .is_err()
2952 );
2953 assert!(
2954 access
2955 .authorize_file(&root.join("conversations/new.json"), &root, true)
2956 .is_err()
2957 );
2958 assert!(Access::all().authorize_file(&root, &root, false).is_err());
2959 assert!(
2960 access
2961 .authorize_file(&root.join("../secret"), &root, false)
2962 .is_err()
2963 );
2964 for bad in [
2965 r#"{"process":{"execut":[]}}"#,
2966 r#"{"fs":{"reads":[]}}"#,
2967 r#"{"fs":{"read":["${dataDir}/../outside"]}}"#,
2968 r#"{"process":{"execute":["*"]}}"#,
2969 ] {
2970 assert!(Capabilities::from_json(&serde_json::from_str(bad).unwrap()).is_err());
2971 }
2972 }
2973
2974 #[test]
2975 fn trusted_host_anchors_expand_without_implicit_grants() {
2976 let root = std::env::current_dir().unwrap();
2977 let anchors = TrustedPaths {
2978 plugin_dir: Some(root.clone()),
2979 home_dir: Some(root.join("native-home")),
2980 };
2981 let access = Access {
2982 declared: caps(
2983 r#"{"fs":{"read":["assets","${homeDir}/settings","${pluginDir}/content"]}}"#,
2984 ),
2985 granted: None,
2986 };
2987 for path in ["assets/file", "native-home/settings/file", "content/file"] {
2988 assert!(
2989 access
2990 .authorize_file_with_paths(&root.join(path), &root, &anchors, false)
2991 .is_ok()
2992 );
2993 }
2994 assert!(
2995 access
2996 .authorize_file(&root.join("content/file"), &root, false)
2997 .is_err()
2998 );
2999 assert!(
3000 access
3001 .authorize_file_with_paths(&root.join("other/file"), &root, &anchors, false)
3002 .is_err()
3003 );
3004 assert!(
3005 TrustedPaths::default()
3006 .resolve_root("${homeDir}/settings", &root)
3007 .is_err()
3008 );
3009 assert!(
3010 TrustedPaths::default()
3011 .resolve_root("assets", &root)
3012 .is_err()
3013 );
3014 }
3015
3016 #[test]
3017 fn http_rules_are_one_form_whose_keys_all_narrow() {
3018 let allows = |rule: serde_json::Value, method: &str, url: &str| {
3019 Access {
3020 declared: Capabilities::from_json(&serde_json::json!({"network":{"http":[rule]}}))
3021 .unwrap(),
3022 granted: None,
3023 }
3024 .allows_http(method, url)
3025 };
3026 let plain = serde_json::json!({"host": "api.example.com", "methods": ["GET"]});
3028 assert!(allows(plain.clone(), "GET", "https://api.example.com/"));
3029 assert!(allows(
3030 plain.clone(),
3031 "GET",
3032 "http://api.example.com:8080/any/path"
3033 ));
3034 assert!(!allows(plain.clone(), "POST", "https://api.example.com/"));
3035 assert!(allows(
3036 serde_json::json!({"host": "api.example.com"}),
3037 "PUT",
3038 "https://api.example.com/x"
3039 ));
3040 let scoped = serde_json::json!({
3042 "host": "api.example.com", "methods": ["GET"], "scheme": "https", "port": 443,
3043 "paths": ["/exact"], "pathPrefixes": ["/v1"]
3044 });
3045 assert!(allows(
3046 scoped.clone(),
3047 "GET",
3048 "https://api.example.com/exact?q=1"
3049 ));
3050 assert!(allows(scoped.clone(), "GET", "https://api.example.com/v1"));
3051 assert!(allows(
3052 scoped.clone(),
3053 "GET",
3054 "https://api.example.com/v1/child"
3055 ));
3056 assert!(!allows(
3057 scoped.clone(),
3058 "GET",
3059 "https://api.example.com/v10"
3060 ));
3061 assert!(!allows(
3062 scoped.clone(),
3063 "GET",
3064 "https://api.example.com/exact/more"
3065 ));
3066 assert!(!allows(
3067 scoped.clone(),
3068 "GET",
3069 "http://api.example.com/exact"
3070 ));
3071 assert!(!allows(
3072 scoped.clone(),
3073 "GET",
3074 "https://api.example.com:444/exact"
3075 ));
3076 assert!(allows(scoped, "GET", "https://api.example.com:443/exact"));
3077 let legacy = serde_json::json!({"host": "*.example.com", "schemes": ["https", "wss"], "pathPrefix": "/v1/"});
3079 assert!(allows(
3080 legacy.clone(),
3081 "GET",
3082 "https://quotes.example.com/v1/quote"
3083 ));
3084 assert!(!allows(legacy, "GET", "https://quotes.example.com/v2/"));
3085 let mixed = caps(
3087 r#"{"network":{"http":[{"host":"a.example.com","methods":["get"],"scheme":"https","schemes":["wss","https"],"pathPrefix":"/a","path_prefixes":["/b"],"pathPrefixes":["/a","/c"]}]}}"#,
3088 );
3089 let grant = &mixed.network.http[0];
3090 assert_eq!(grant.methods, ["GET"]);
3091 assert_eq!(grant.schemes, ["https", "wss"]);
3092 assert_eq!(grant.path_prefixes, ["/a", "/c", "/b"]);
3093 assert_eq!(
3094 mixed.to_json()["network"]["http"][0],
3095 serde_json::json!({"host":"a.example.com","methods":["GET"],"schemes":["https","wss"],"pathPrefixes":["/a","/c","/b"]})
3096 );
3097 assert_eq!(Capabilities::from_json(&mixed.to_json()).unwrap(), mixed);
3098 for bad in [
3100 serde_json::json!({"host": "a.example.com", "schemes": ["ftp"]}),
3101 serde_json::json!({"host": "a.example.com", "port": 0}),
3102 serde_json::json!({"host": "a.example.com", "port": 70000}),
3103 serde_json::json!({"host": "a.example.com", "paths": ["relative"]}),
3104 serde_json::json!({"host": "a.example.com", "pathPrefixes": ["/v1/*"]}),
3105 serde_json::json!({"host": "a.example.com", "methods": ["*"]}),
3106 serde_json::json!({"host": "a.example.com", "paths": "/x", "query": true}),
3107 serde_json::json!({"methods": ["GET"]}),
3108 ] {
3109 assert!(
3110 Capabilities::from_json(&serde_json::json!({"network":{"http":[bad.clone()]}}))
3111 .is_err(),
3112 "{bad}"
3113 );
3114 }
3115 }
3116
3117 #[test]
3118 fn exit_and_environment_permissions_intersect() {
3119 let declared = caps(r#"{"process":{"env":["NSH_SECRET","OTHER"],"exit":true}}"#);
3120 assert_eq!(
3121 Capabilities::from_json(&declared.to_json()).unwrap(),
3122 declared
3123 );
3124 let access = Access {
3125 declared,
3126 granted: Some(caps(r#"{"process":{"env":["NSH_SECRET"]}}"#)),
3127 };
3128 assert!(access.allows_env("NSH_SECRET"));
3129 assert!(!access.allows_env("OTHER"));
3130 assert!(!access.allows_exit());
3131 assert!(!Access::all().allows_exit());
3132 assert!(!Access::all().allows_env("NSH_SECRET"));
3133 assert!(Access::all().allows_env("LANG"));
3134 assert_eq!(Access::all().allows_env("lang"), cfg!(windows));
3135 assert!(Access::all().allows_env("TZ"));
3136 for name in [
3138 "HOME",
3139 "USER",
3140 "USERNAME",
3141 "HOSTNAME",
3142 "COMPUTERNAME",
3143 "PATH",
3144 "TMPDIR",
3145 "XDG_RUNTIME_DIR",
3146 "APPDATA",
3147 "http_proxy",
3148 "HTTPS_PROXY",
3149 "ALL_PROXY",
3150 "NO_PROXY",
3151 "DISPLAY",
3152 ] {
3153 assert!(!Access::all().allows_env(name), "{name}");
3154 }
3155 assert!(!Access::all().allows_env("SSH_AUTH_SOCK"));
3156 assert!(!Access::all().allows_env("DBUS_SESSION_BUS_ADDRESS"));
3157 assert!(Capabilities::from_json(&serde_json::json!({"process":{"exit":"true"}})).is_err());
3158 assert!(
3159 Capabilities::from_json(&serde_json::json!({"process":{"env":["BAD=NAME"]}})).is_err()
3160 );
3161 }
3162
3163 #[test]
3164 fn default_environment_entries_are_upper_case_names() {
3165 for line in include_str!("default-env").lines() {
3166 let name = line.split('#').next().unwrap_or_default().trim();
3167 assert!(
3168 name.is_empty()
3169 || name
3170 .chars()
3171 .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'),
3172 "{line}"
3173 );
3174 }
3175 }
3176
3177 #[test]
3178 fn sockets_need_exact_host_and_port_grants() {
3179 let declared = caps(
3180 r#"{"network":{"hosts":["*"],"sockets":["MQTT.example.com:8883","[::1]:9000","127.0.0.1:22"]}}"#,
3181 );
3182 assert_eq!(
3183 Capabilities::from_json(&declared.to_json()).unwrap(),
3184 declared
3185 );
3186 let access = Access {
3187 declared,
3188 granted: None,
3189 };
3190 assert!(access.allows_socket("mqtt.example.com", 8883));
3191 assert!(access.allows_socket("MQTT.example.com.", 8883));
3192 assert!(!access.allows_socket("mqtt.example.com", 1883));
3193 assert!(!access.allows_socket("example.com", 8883));
3194 assert!(!access.allows_socket("a.mqtt.example.com", 8883));
3195 assert!(access.allows_socket("::1", 9000));
3196 assert!(access.allows_socket("[::1]", 9000));
3197 assert!(access.allows_socket("127.0.0.1", 22));
3198 assert!(!access.allows_socket("127.0.0.1", 0));
3199 assert!(!access.allows_socket("localhost", 22));
3201 assert!(!Access::all().allows_socket("127.0.0.1", 22));
3202 assert!(!Access::all().allows_socket("example.com", 443));
3203 let narrowed = Access {
3204 granted: Some(caps(r#"{"network":{"sockets":["127.0.0.1:22"]}}"#)),
3205 ..access
3206 };
3207 assert!(narrowed.allows_socket("127.0.0.1", 22));
3208 assert!(!narrowed.allows_socket("mqtt.example.com", 8883));
3209 for bad in [
3210 "*.example.com:443",
3211 "*:443",
3212 "example.com",
3213 "example.com:0",
3214 "example.com:65536",
3215 "example.com:*",
3216 ":443",
3217 "::1:443",
3218 "[]:443",
3219 "exa mple.com:1",
3220 ] {
3221 assert!(
3222 Capabilities::from_json(&serde_json::json!({"network":{"sockets":[bad]}}))
3223 .unwrap_err()
3224 .contains("invalid socket grant"),
3225 "{bad}"
3226 );
3227 }
3228 }
3229
3230 #[test]
3231 fn websockets_follow_http_grants() {
3232 let access = Access {
3233 declared: caps(
3234 r#"{"network":{"hosts":["ws.example.com"],"http":[
3235 {"host":"chat.example.com","methods":["GET"],"scheme":"https","paths":["/socket"]},
3236 {"host":"legacy.example.com","schemes":["wss"]}
3237 ]}}"#,
3238 ),
3239 granted: None,
3240 };
3241 assert!(access.allows_websocket("ws://ws.example.com:8080/x"));
3242 assert!(access.allows_websocket("wss://chat.example.com/socket"));
3243 assert!(!access.allows_websocket("ws://chat.example.com/socket"));
3244 assert!(!access.allows_websocket("wss://chat.example.com/other"));
3245 assert!(access.allows_websocket("wss://legacy.example.com/"));
3246 assert!(!access.allows_websocket("ws://legacy.example.com/"));
3247 assert!(!access.allows_websocket("https://ws.example.com/"));
3248 assert!(!access.allows_socket("ws.example.com", 8080));
3249 }
3250
3251 #[cfg(unix)]
3252 #[test]
3253 fn filesystem_symlinks_cannot_escape_granted_roots() {
3254 use std::os::unix::fs::symlink;
3255 let base = std::env::var_os("TMPDIR")
3256 .map(PathBuf::from)
3257 .unwrap_or_else(|| {
3258 PathBuf::from(std::env::var_os("HOME").unwrap()).join(".cache/nsh-benchs-test-tmp")
3259 });
3260 let root = base.join(format!("access-policy-{}", std::process::id()));
3261 std::fs::create_dir_all(root.join("allowed")).unwrap();
3262 std::fs::create_dir_all(root.join("outside")).unwrap();
3263 symlink(root.join("outside"), root.join("allowed/link")).unwrap();
3264 let access = Access {
3265 declared: caps(r#"{"fs":{"read":["${dataDir}"],"write":["${dataDir}"]}}"#),
3266 granted: None,
3267 };
3268 for write in [false, true] {
3269 assert!(
3270 access
3271 .authorize_file(
3272 &root.join("allowed/link/missing/file"),
3273 &root.join("allowed"),
3274 write
3275 )
3276 .is_err()
3277 );
3278 assert!(
3279 access
3280 .authorize_file(&root.join("allowed/new/file"), &root.join("allowed"), write)
3281 .is_ok()
3282 );
3283 }
3284 std::fs::remove_dir_all(root).unwrap();
3285 }
3286
3287 #[test]
3288 fn the_share_sheet_is_granted_by_both_sides() {
3289 let declared = caps(r#"{ "share": true }"#);
3290 assert!(declared.share);
3291 assert_eq!(declared.to_json()["share"], serde_json::json!(true));
3292 assert!(
3293 Access {
3294 declared: declared.clone(),
3295 granted: None,
3296 }
3297 .allows_share()
3298 );
3299 assert!(
3301 !Access {
3302 declared,
3303 granted: Some(caps("{}")),
3304 }
3305 .allows_share()
3306 );
3307 assert!(Access::all().allows_share());
3309 assert!(Capabilities::from_json(&serde_json::json!({ "share": "yes" })).is_err());
3310 }
3311
3312 #[test]
3313 fn denies_unless_listed() {
3314 let access = Access {
3315 declared: caps("{}"),
3316 granted: None,
3317 };
3318 assert!(!access.allows_http("GET", "https://example.com/"));
3319 assert!(!access.allows_media("https://example.com/a.png"));
3320 assert!(access.allows_media("asset:/logo.png"));
3321 assert!(!access.allows_media("logo.png"));
3323 assert!(!access.allows_media("/home/a/logo.png"));
3326 assert!(!access.allows_media("file:///home/a/logo.png"));
3327 assert!(access.allows_media("data:image/png;base64,iVBORw0KGgo="));
3328 assert!(!access.allows_webview("https://example.com/"));
3329 assert!(!access.allows_status_bar());
3330 assert!(!access.allows_clipboard());
3331 assert!(!access.allows_picker());
3332 assert!(!access.allows_share());
3333 assert!(!access.allows_speech());
3334 assert!(!access.allows_audio());
3335 assert!(!access.allows_application());
3336 assert!(!access.allows_home_dir());
3337 assert!(!access.allows_host("getUserInfo"));
3338 assert!(Access::all().is_unrestricted());
3339 }
3340
3341 #[test]
3342 fn the_application_and_the_home_directory_are_capabilities() {
3343 let all = Access::all();
3345 assert!(all.allows_application() && all.allows_home_dir());
3346 let access = |declared: &str, granted: Option<&str>| Access {
3348 declared: caps(declared),
3349 granted: granted.map(caps),
3350 };
3351 let listed = access(r#"{ "application": true, "homeDir": true }"#, None);
3352 assert!(listed.allows_application() && listed.allows_home_dir());
3353 let application = access(r#"{ "application": true }"#, None);
3354 assert!(application.allows_application() && !application.allows_home_dir());
3355 let narrowed = access(
3356 r#"{ "application": true, "homeDir": true }"#,
3357 Some(r#"{ "homeDir": true }"#),
3358 );
3359 assert!(!narrowed.allows_application() && narrowed.allows_home_dir());
3360 assert!(!access(r#"{ "application": false }"#, None).allows_application());
3361 assert!(Capabilities::from_json(&serde_json::json!({ "application": "yes" })).is_err());
3362 assert!(Capabilities::from_json(&serde_json::json!({ "homeDir": 1 })).is_err());
3363 let both = caps(r#"{ "application": true, "homeDir": true }"#);
3365 assert_eq!(Capabilities::from_json(&both.to_json()).unwrap(), both);
3366 let none = Capabilities::default().to_json();
3367 assert!(none.get("application").is_none() && none.get("homeDir").is_none());
3368 }
3369
3370 #[test]
3371 fn host_functions_need_an_explicit_grant() {
3372 let all = Access::all();
3375 assert!(all.allows_clipboard());
3376 assert!(!all.allows_host("getUserInfo"));
3377 let access = |json: &str| Access {
3378 declared: caps(json),
3379 granted: None,
3380 };
3381 let every = access(r#"{ "host": true }"#);
3382 assert!(every.allows_host("getUserInfo") && every.allows_host("bridge.call"));
3383 assert!(!access(r#"{ "host": false }"#).allows_host("getUserInfo"));
3384 let listed = access(r#"{ "host": ["getUserInfo", "bridge.*"] }"#);
3385 assert!(listed.allows_host("getUserInfo"));
3386 assert!(listed.allows_host("bridge.share"));
3387 assert!(!listed.allows_host("getUserInfoX"));
3388 assert!(!listed.allows_host("bridge"));
3389 assert!(Capabilities::from_json(&serde_json::json!({ "host": ["a*b"] })).is_err());
3390 assert!(Capabilities::from_json(&serde_json::json!({ "host": [""] })).is_err());
3391 let narrowed = Access {
3393 declared: caps(r#"{ "host": true }"#),
3394 granted: Some(caps(r#"{ "host": ["bridge.*"] }"#)),
3395 };
3396 assert!(narrowed.allows_host("bridge.call") && !narrowed.allows_host("getUserInfo"));
3397 }
3398
3399 #[test]
3400 fn a_runtime_origin_is_exact() {
3401 let o = |s: &str| WebOrigin::parse(s).unwrap();
3402 let lan = o("http://192.168.1.5:9876");
3403 for url in [
3404 "http://192.168.1.5:9876/session-page/T/index.html",
3405 "http://192.168.1.5:9876",
3406 "HTTP://192.168.1.5:9876/x",
3407 "blob:http://192.168.1.5:9876/6f3c2f0e",
3408 ] {
3409 assert!(lan.contains(url), "{url}");
3410 }
3411 for url in [
3412 "http://192.168.1.5:9877/",
3413 "https://192.168.1.5:9876/",
3414 "http://a.192.168.1.5:9876/",
3415 "http://192.168.1.5:9876@evil.com/",
3416 "http://192.168.1.5:9876.evil.com/",
3417 "blob:null/6f3c2f0e",
3418 "file:///etc/passwd",
3419 "javascript:alert(1)",
3420 "data:text/html,hi",
3421 "http://192.168.1.5\\@evil.com:9876/",
3422 ] {
3423 assert!(!lan.contains(url), "{url}");
3424 }
3425 let named = o("https://Name.Example.net:443");
3426 assert_eq!(named.to_string(), "https://name.example.net");
3427 assert!(named.contains("https://name.example.net/x"));
3428 assert!(named.contains("https://NAME.example.net:443/x"));
3429 for url in [
3430 "https://evil.name.example.net/",
3431 "https://name.example.net.evil.com/",
3432 "http://name.example.net/",
3433 ] {
3434 assert!(!named.contains(url), "{url}");
3435 }
3436 assert_eq!(o("http://h:80/").to_string(), "http://h");
3437 assert_eq!(o("http://[::1]:8080").to_string(), "http://[::1]:8080");
3438 for bad in [
3439 "http://h/path",
3440 "http://h?q",
3441 "http://h#f",
3442 "http://u@h",
3443 "*",
3444 "http://*",
3445 "ftp://h",
3446 "h:80",
3447 "http://",
3448 "http://h:99999",
3449 "http://bücher.example",
3450 ] {
3451 assert!(WebOrigin::parse(bad).is_err(), "{bad}");
3452 }
3453 }
3454
3455 #[test]
3456 fn allow_navigation_only_narrows_a_web_view() {
3457 let access = Access {
3458 declared: caps(r#"{ "webview": { "hosts": ["*"] } }"#),
3459 granted: None,
3460 };
3461 let hosts = WebHosts::parse(&["127.0.0.1", "*.localhost"]).unwrap();
3462 let ok = |url: &str| access.allows_webview_in(url, None, Some(&hosts));
3463 assert!(ok("http://127.0.0.1:8001/"));
3464 assert!(ok("http://app.localhost:3000/a"));
3465 assert!(ok("blob:http://127.0.0.1:8001/1234"));
3466 assert!(!ok("http://127.0.0.1.evil.test:8002/leaked"));
3467 assert!(!ok("https://example.com/"));
3468 assert!(!ok("http://localhost/"));
3469 assert!(ok("about:blank"));
3471 let narrow = Access {
3473 declared: caps(r#"{ "webview": { "hosts": ["example.com"] } }"#),
3474 granted: None,
3475 };
3476 assert!(!narrow.allows_webview_in("http://127.0.0.1/", None, Some(&hosts)));
3477 assert!(narrow.allows_webview_in("https://example.com/", None, None));
3478 let none = WebHosts::default();
3480 assert!(!access.allows_webview_in("https://example.com/", None, Some(&none)));
3481 assert!(WebHosts::parse(&["http://127.0.0.1"]).is_err());
3483 let text = hosts.to_string();
3484 let lines: Vec<&str> = text.lines().collect();
3485 assert_eq!(WebHosts::parse(&lines).unwrap(), hosts);
3486 }
3487
3488 #[test]
3489 fn a_runtime_origin_needs_an_explicit_grant() {
3490 let access = |json: &str| Access {
3491 declared: caps(json),
3492 granted: None,
3493 };
3494 let lan = WebOrigin::parse("http://192.168.1.5:9876").unwrap();
3495 let page = "http://192.168.1.5:9876/index.html";
3496 let declared = r#"{ "webview": { "hosts": ["127.0.0.1"], "runtimeOrigin": true } }"#;
3497 assert!(access(declared).allows_runtime_origin());
3498 assert!(access(declared).allows_webview_with(page, Some(&lan)));
3499 assert!(!access(declared).allows_webview_with(page, None));
3500 assert!(access(declared).allows_webview_with("http://127.0.0.1:1/", Some(&lan)));
3501 let hosts = r#"{ "webview": { "hosts": ["127.0.0.1"] } }"#;
3504 assert!(!access(hosts).allows_runtime_origin());
3505 assert!(!access(hosts).allows_webview_with(page, Some(&lan)));
3506 assert!(!Access::all().allows_runtime_origin());
3507 assert!(Access::all().allows_webview_with(page, None));
3508 assert!(
3509 Capabilities::from_json(&serde_json::json!({ "webview": { "runtimeOrigin": 1 } }))
3510 .is_err()
3511 );
3512 assert_eq!(
3514 Capabilities::from_json(&caps(declared).to_json()),
3515 Ok(caps(declared))
3516 );
3517 let narrowed = Access {
3518 declared: caps(declared),
3519 granted: Some(caps(r#"{ "webview": { "hosts": ["*"] } }"#)),
3520 };
3521 assert!(!narrowed.allows_runtime_origin());
3522 }
3523
3524 #[test]
3525 fn trusted_web_input_needs_an_explicit_grant() {
3526 let all = Access::all();
3528 assert!(all.allows_webviews() && !all.allows_web_input());
3529 let access = |json: &str| Access {
3530 declared: caps(json),
3531 granted: None,
3532 };
3533 let input = r#"{ "webview": { "hosts": ["example.com"], "input": true } }"#;
3534 assert!(access(input).allows_web_input());
3535 assert!(!access(r#"{ "webview": { "hosts": ["example.com"] } }"#).allows_web_input());
3536 assert!(!access(r#"{ "webview": { "input": false } }"#).allows_web_input());
3537 assert!(
3538 Capabilities::from_json(&serde_json::json!({ "webview": { "input": "yes" } })).is_err()
3539 );
3540 assert_eq!(
3542 Capabilities::from_json(&caps(input).to_json()),
3543 Ok(caps(input))
3544 );
3545 let narrowed = Access {
3546 declared: caps(input),
3547 granted: Some(caps(r#"{ "webview": { "hosts": ["*"] } }"#)),
3548 };
3549 assert!(!narrowed.allows_web_input());
3550 }
3551
3552 #[test]
3553 fn web_media_needs_an_explicit_grant() {
3554 let all = Access::all();
3555 assert!(!all.allows_web_media(WebMedia::Microphone));
3556 let access = |json: &str| Access {
3557 declared: caps(json),
3558 granted: None,
3559 };
3560 let mic = r#"{ "webview": { "hosts": ["example.com"], "media": ["microphone"] } }"#;
3561 assert!(access(mic).allows_web_media(WebMedia::Microphone));
3562 assert!(!access(mic).allows_web_media(WebMedia::Camera));
3563 assert!(
3564 Capabilities::from_json(&serde_json::json!({ "webview": { "media": ["screen"] } }))
3565 .is_err()
3566 );
3567 assert_eq!(Capabilities::from_json(&caps(mic).to_json()), Ok(caps(mic)));
3568 let narrowed = Access {
3569 declared: caps(mic),
3570 granted: Some(caps(r#"{ "webview": { "hosts": ["*"] } }"#)),
3571 };
3572 assert!(!narrowed.allows_web_media(WebMedia::Microphone));
3573 }
3574
3575 #[test]
3580 fn page_owned_blob_urls_follow_the_origin_they_embed() {
3581 let a = Access {
3582 declared: caps(
3583 r#"{ "webview": { "hosts": ["app.example.com", "*.app.example.com"] } }"#,
3584 ),
3585 granted: None,
3586 };
3587 for url in [
3588 "blob:https://app.example.com/uuid",
3589 "blob:http://app.example.com:6711/uuid",
3590 "blob:https://docs.app.example.com/uuid",
3591 "BLOB:HTTPS://APP.EXAMPLE.COM/uuid",
3592 ] {
3593 assert!(a.allows_webview(url), "{url}");
3594 }
3595 for url in [
3596 "blob:https://bank.example/uuid",
3597 "blob:https://app.example.com.evil.example/uuid",
3598 "blob:https://app.example.com@bank.example/uuid",
3599 "blob:null/uuid",
3600 "blob:data:text/html,hi",
3601 "blob:file:///etc/passwd",
3602 "blob:",
3603 "blob:https://",
3604 ] {
3605 assert!(!a.allows_webview(url), "{url}");
3606 }
3607 let denied = Access {
3609 declared: caps("{}"),
3610 granted: None,
3611 };
3612 assert!(!denied.allows_webview("blob:https://app.example.com/uuid"));
3613 let narrowed = Access {
3615 granted: Some(caps(r#"{ "webview": { "hosts": ["app.example.com"] } }"#)),
3616 ..a.clone()
3617 };
3618 assert!(narrowed.allows_webview("blob:https://app.example.com/uuid"));
3619 assert!(!narrowed.allows_webview("blob:https://docs.app.example.com/uuid"));
3620 let local = Access {
3622 declared: caps(r#"{ "webview": { "hosts": ["127.0.0.1"] } }"#),
3623 granted: None,
3624 };
3625 assert!(
3626 local.allows_webview("blob:http://127.0.0.1:6711/6f3c2f0e-8a1d-4c5e-9b7a-0d2e4f6a8b1c")
3627 );
3628 assert!(a.allows_webview("https://app.example.com/page"));
3631 assert!(!a.allows_webview("https://bank.example/page"));
3632 let ambiguous = "blob:https://app.example.com\\@bank.example/uuid";
3635 assert!(!a.allows_webview(ambiguous));
3636 let any = Access {
3637 declared: caps(r#"{ "webview": { "hosts": ["*"] } }"#),
3638 granted: None,
3639 };
3640 assert!(any.allows_webview(ambiguous));
3641 }
3642
3643 #[test]
3644 fn host_function_names_and_grants_keep_to_their_charset() {
3645 for good in ["getUserInfo", "user.info", "a-b_c:d.E9", &"a".repeat(128)] {
3646 assert!(valid_host_name(good), "{good}");
3647 }
3648 for bad in [
3649 "",
3650 "user.x/../../admin",
3651 "a..b",
3652 "user x",
3653 "a\\b",
3654 "caf\u{e9}",
3655 "ok\u{0}",
3656 "a*",
3657 &"a".repeat(129),
3658 ] {
3659 assert!(!valid_host_name(bad), "{bad:?}");
3660 }
3661 let parses =
3662 |grant: &str| Capabilities::from_json(&serde_json::json!({ "host": [grant] })).is_ok();
3663 assert!(parses("*") && parses("user.*") && parses("user.info"));
3664 for bad in ["user/*", "a..*", "../*", "a b", "**"] {
3665 assert!(!parses(bad), "{bad}");
3666 }
3667 }
3668
3669 #[test]
3670 fn hosts_and_finer_grants() {
3671 let c = caps(
3672 r#"{ "network": {
3673 "hosts": ["*.example.org"],
3674 "http": [{ "host": "api.example.com", "methods": ["get"], "pathPrefix": "/v1/" }]
3675 } }"#,
3676 );
3677 let a = Access {
3678 declared: c,
3679 granted: None,
3680 };
3681 assert!(a.allows_http("POST", "https://api.example.org/x"));
3682 assert!(!a.allows_http("GET", "https://example.org/"));
3683 assert!(!a.allows_http("GET", "https://example.org.evil.io/"));
3684 assert!(!a.allows_http("GET", "https://evilexample.org/"));
3685 assert!(a.allows_http("GET", "https://API.example.com/v1/quote"));
3686 assert!(!a.allows_http("POST", "https://api.example.com/v1/quote"));
3687 assert!(!a.allows_http("GET", "https://api.example.com/v2/"));
3688 assert!(!a.allows_http("GET", "file://api.example.com/v1/"));
3689 assert!(!a.allows_http("GET", "https://api.example.org@evil.io/"));
3691 assert!(a.allows_http("GET", "https://user:pw@api.example.org:8443/"));
3692 }
3693
3694 #[test]
3701 fn urls_that_parsers_read_as_different_hosts_are_refused() {
3702 let hosts = r#"["docs.example.com", "*.docs.example.com"]"#;
3703 let a = Access {
3704 declared: caps(&format!(
3705 r#"{{ "network": {{ "hosts": {hosts} }}, "webview": {{ "hosts": {hosts} }} }}"#
3706 )),
3707 granted: None,
3708 };
3709 for url in [
3710 "https://bank.example\\@docs.example.com/",
3712 "https://bank.example:443\\@docs.example.com/",
3713 "https://[::1]\\@docs.example.com/",
3714 "https://bank.example\\.docs.example.com/",
3716 "https://docs.example.com\\@bank.example/",
3718 "https://docs.example.com/a\\..\\b",
3720 "https://bank.example\0.docs.example.com/",
3722 "https://bank.example\t.docs.example.com/",
3723 "https://bank.example\n.docs.example.com/",
3724 "https://bank.example .docs.example.com/",
3725 "https://bank.example[.docs.example.com/",
3726 "https://x]y.docs.example.com/",
3727 "https://bank%2Eexample.docs.example.com/",
3729 ] {
3730 assert!(!a.allows_webview(url), "{url:?}");
3731 assert!(!a.allows_http("GET", url), "{url:?}");
3732 assert!(!a.allows_media(url), "{url:?}");
3733 }
3734 assert!(!a.allows_websocket("wss://bank.example\\@docs.example.com/"));
3735 for url in [
3738 "https://docs.example.com/a%5Cb",
3739 "https://x.docs.example.com/?q=C:\\x#a\\b",
3740 "https://user:pw@docs.example.com/a b",
3741 ] {
3742 assert!(a.allows_webview(url), "{url:?}");
3743 assert!(a.allows_http("GET", url), "{url:?}");
3744 }
3745 let all = Access {
3747 declared: Capabilities::all(),
3748 granted: None,
3749 };
3750 let query = url::Url::parse("wss://x.example/?q=a\\b").unwrap();
3751 assert!(all.allows_websocket(query.as_str()), "{query}");
3752 assert!(all.allows_media("https://x.example/i.png?p=a\\b"));
3753 }
3754
3755 #[test]
3760 fn only_grants_of_every_host_cover_ambiguous_urls() {
3761 let url = "https://x.example/a\\b.png";
3762 let all = Access {
3763 declared: Capabilities::all(),
3764 granted: None,
3765 };
3766 let any = Access {
3767 declared: caps(r#"{ "network": { "hosts": ["*"] }, "webview": { "hosts": ["*"] } }"#),
3768 granted: None,
3769 };
3770 for a in [&all, &any] {
3771 assert!(a.allows_http("GET", url));
3772 assert!(a.allows_media(url));
3773 assert!(a.allows_webview(url));
3774 assert!(!a.allows_http("GET", "ftp://x.example/a\\b"));
3775 assert!(!a.allows_webview("file://x.example/a\\b"));
3776 assert!(!a.allows_webview("not a url"));
3777 assert!(!a.allows_http("GET", "https://"));
3778 }
3779 let rule = |rule: &str| Access {
3780 declared: caps(&format!(r#"{{ "network": {{ "http": [{rule}] }} }}"#)),
3781 granted: None,
3782 };
3783 let methods = rule(r#"{ "host": "*", "methods": ["get"], "schemes": ["https"] }"#);
3784 assert!(methods.allows_http("GET", url));
3785 assert!(!methods.allows_http("POST", url));
3786 assert!(!methods.allows_http("GET", "http://x.example/a\\b.png"));
3787 for narrowed in [
3788 r#"{ "host": "*", "port": 443 }"#,
3789 r#"{ "host": "*", "pathPrefix": "/a" }"#,
3790 r#"{ "host": "*", "paths": ["/a/b.png"] }"#,
3791 r#"{ "host": "x.example" }"#,
3792 ] {
3793 assert!(!rule(narrowed).allows_http("GET", url), "{narrowed}");
3794 }
3795 }
3796
3797 #[test]
3800 fn granted_urls_are_granted_hosts_for_whatwg() {
3801 let pattern = |p: &str| HostPattern::new(p).unwrap();
3802 let granted = [pattern("docs.example.com"), pattern("*.docs.example.com")];
3803 let a = Access {
3804 declared: caps(
3805 r#"{ "webview": { "hosts": ["docs.example.com", "*.docs.example.com"] } }"#,
3806 ),
3807 granted: None,
3808 };
3809 for url in [
3810 "https://docs.example.com/a",
3811 "https://DOCS.Example.COM/",
3812 "https://docs.example.com./",
3813 "https://x.docs.example.com:8443/",
3814 "https://user:pw@docs.example.com/",
3815 "https://docs.example.com#@bank.example/",
3816 "https://docs.example.com?@bank.example/",
3817 "https://docs.example.com:pass@bank.example/",
3818 "https://docs.example.com%2F@bank.example/",
3819 "https://bank.example\\@docs.example.com/",
3820 "https://bank.example:443\\@docs.example.com/",
3821 "https://[::1]\\@docs.example.com/",
3822 "https://bank.example\\.docs.example.com/",
3823 "https://docs.example.com\\@bank.example/",
3824 "https://bank.example\0.docs.example.com/",
3825 "https://bank.example\t.docs.example.com/",
3826 "https://docs.example.com\n.bank.example/",
3827 "https://bank%2Eexample.docs.example.com/",
3828 "https://docs\u{FF0E}example\u{FF0E}com/",
3829 "https://d\u{043E}cs.example.com/",
3830 "https:\\\\docs.example.com\\",
3831 " https://docs.example.com/",
3832 "https://docs.example.com /",
3833 "https://bank.example .docs.example.com/",
3834 "https://bank.example^.docs.example.com/",
3835 "https://bank.example[.docs.example.com/",
3836 "https://x]y.docs.example.com/",
3837 "https://a@bank.example@docs.example.com/",
3838 "https://..docs.example.com/",
3839 "HTTPS://DOCS.EXAMPLE.COM/",
3840 "https://x.docs.example.com/?q=C:\\x",
3841 ] {
3842 if a.allows_webview(url) {
3843 let whatwg = url::Url::parse(url).unwrap_or_else(|e| panic!("{url:?}: {e}"));
3844 let host = whatwg.host_str().unwrap_or_default().trim_end_matches('.');
3845 assert!(granted.iter().any(|p| p.matches(host)), "{url:?}: {host}");
3846 }
3847 }
3848 }
3849
3850 #[test]
3851 fn the_embedder_grants_at_most() {
3852 let a = Access {
3853 declared: caps(
3854 r#"{ "network": { "hosts": ["a.com", "b.com"] }, "statusBar": true, "clipboard": true, "picker": true, "speech": true, "audio": true }"#,
3855 ),
3856 granted: Some(caps(
3857 r#"{ "network": { "hosts": ["b.com"] }, "clipboard": true }"#,
3858 )),
3859 };
3860 assert!(a.allows_clipboard());
3861 assert!(!a.allows_http("GET", "https://a.com/"));
3862 assert!(!a.allows_picker());
3863 assert!(!a.allows_speech());
3864 assert!(!a.allows_audio());
3865 assert!(a.allows_http("GET", "https://b.com/"));
3866 assert!(!a.allows_status_bar());
3867 }
3868
3869 #[test]
3870 fn typos_are_errors() {
3871 let bad =
3872 |json: &str| Capabilities::from_json(&serde_json::from_str(json).unwrap()).unwrap_err();
3873 assert!(bad(r#"{ "netwrok": {} }"#).contains("unknown key `netwrok`"));
3874 assert!(bad(r#"{ "network": { "host": [] } }"#).contains("unknown key `host`"));
3875 assert!(bad(r#"{ "network": { "hosts": ["exa mple.com"] } }"#).contains("invalid host"));
3876 let c = caps(
3877 r#"{ "network": { "hosts": ["a.com"], "http": [{ "host": "b.com", "methods": ["GET"] }] }, "webview": { "hosts": ["*"] } }"#,
3878 );
3879 assert_eq!(Capabilities::from_json(&c.to_json()).unwrap(), c);
3880 }
3881
3882 #[test]
3885 fn unknown_keys_in_packages_grant_nothing() {
3886 let lenient =
3887 |json: &str| Capabilities::from_json_lenient(&serde_json::from_str(json).unwrap());
3888 let (c, dropped) = lenient(
3889 r#"{ "bluetooth": true, "clipboard": true,
3890 "network": { "hosts": ["a.com"], "http": [
3891 { "host": "b.com", "ports": [443] },
3892 { "host": "c.com", "methods": ["GET"] }
3893 ] } }"#,
3894 )
3895 .unwrap();
3896 assert!(c.clipboard);
3897 assert_eq!(c.network.hosts, [HostPattern::new("a.com").unwrap()]);
3898 assert_eq!(c.network.http.len(), 1);
3899 assert_eq!(c.network.http[0].host.as_str(), "c.com");
3900 assert_eq!(
3901 dropped,
3902 [
3903 "capabilities.bluetooth",
3904 "capabilities.network.http[0] (unknown key `ports`)"
3905 ]
3906 );
3907 let (c, dropped) =
3908 lenient(r#"{ "network": { "hosts": ["a.com"], "ipv6": false }, "webview": { "hosts": ["*"], "x": 1 } }"#)
3909 .unwrap();
3910 assert_eq!(c, Capabilities::default());
3911 assert_eq!(dropped.len(), 2);
3912 let (c, dropped) = lenient(
3916 r#"{ "statusBar": "yes", "clipboard": true,
3917 "network": { "hosts": ["exa mple.com"] }, "webview": { "hosts": ["a.com"] } }"#,
3918 )
3919 .unwrap();
3920 assert!(!c.status_bar);
3921 assert!(c.clipboard);
3922 assert!(c.network.hosts.is_empty());
3923 assert_eq!(c.webview, Some(vec![HostPattern::new("a.com").unwrap()]));
3924 assert_eq!(dropped.len(), 2, "{dropped:?}");
3925 assert!(
3926 dropped
3927 .iter()
3928 .any(|d| d.starts_with("capabilities.statusBar ("))
3929 );
3930 assert!(
3931 dropped
3932 .iter()
3933 .any(|d| d.starts_with("capabilities.network ("))
3934 );
3935 let (c, dropped) = lenient(
3937 r#"{ "network": { "hosts": ["a.com"], "http": [
3938 { "host": "b.com", "port": "any" }, { "host": "c.com" } ] } }"#,
3939 )
3940 .unwrap();
3941 assert_eq!(c.network.hosts.len(), 1);
3942 assert_eq!(c.network.http.len(), 1);
3943 assert_eq!(c.network.http[0].host.as_str(), "c.com");
3944 assert_eq!(dropped.len(), 1, "{dropped:?}");
3945 assert!(dropped[0].starts_with("capabilities.network.http[0] ("));
3946 let (c, dropped) = lenient(r#""everything""#).unwrap();
3948 assert_eq!(c, Capabilities::default());
3949 assert_eq!(dropped.len(), 1);
3950 assert!(Capabilities::from_json(&serde_json::json!({ "statusBar": "yes" })).is_err());
3952 let json = serde_json::json!({ "network": { "hosts": ["a.com"] }, "statusBar": true });
3954 let (c, dropped) = Capabilities::from_json_lenient(&json).unwrap();
3955 assert_eq!(c, Capabilities::from_json(&json).unwrap());
3956 assert!(dropped.is_empty());
3957 }
3958
3959 #[test]
3960 fn media_redirects_are_checked() {
3961 let a = Access {
3962 declared: Capabilities::from_json(
3963 &serde_json::json!({ "network": { "hosts": ["a.com"] } }),
3964 )
3965 .unwrap(),
3966 granted: None,
3967 };
3968 let from = "https://a.com/x/y.png";
3969 assert_eq!(
3970 a.media_redirect(from, "/z.png").unwrap(),
3971 "https://a.com/z.png"
3972 );
3973 assert_eq!(
3974 a.media_redirect(from, "z.png").unwrap(),
3975 "https://a.com/x/z.png"
3976 );
3977 assert!(a.media_redirect(from, "https://b.com/z.png").is_err());
3978 assert!(a.media_redirect(from, "//b.com/z.png").is_err());
3979 assert!(a.media_redirect(from, "file:///etc/passwd").is_err());
3980 assert!(
3981 Access::default()
3982 .media_redirect(from, "//b.com/z.png")
3983 .is_ok()
3984 );
3985 assert!(
3986 Access::default()
3987 .media_redirect(from, "ftp://b.com/z.png")
3988 .is_err()
3989 );
3990 }
3991
3992 #[test]
3996 fn http_paths_are_matched_as_whatwg_resolves_them() {
3997 let a = Access {
3998 declared: caps(
3999 r#"{ "network": { "http": [{ "host": "api.example.com", "pathPrefix": "/public" }] } }"#,
4000 ),
4001 granted: None,
4002 };
4003 for url in [
4004 "https://api.example.com/public/../private",
4005 "https://api.example.com/public/%2e%2e/private",
4006 "https://api.example.com/public/%2E%2E/private",
4007 "https://api.example.com/public/.%2e/private",
4008 "https://api.example.com/public/./../private",
4009 ] {
4010 assert!(!a.allows_http("GET", url), "{url}");
4011 assert!(!a.allows_media(url), "{url}");
4012 }
4013 for url in [
4014 "https://api.example.com/public/x",
4015 "https://api.example.com/private/../public/x",
4016 "https://api.example.com/public/./x",
4017 ] {
4018 assert!(a.allows_http("GET", url), "{url}");
4019 }
4020 }
4021
4022 #[test]
4025 fn redirects_resolve_dot_segments() {
4026 assert_eq!(
4027 resolve_reference("https://api.example.com/public/x", "../private"),
4028 "https://api.example.com/private"
4029 );
4030 assert_eq!(
4031 resolve_reference("https://api.example.com/public/x", "%2e%2e/private"),
4032 "https://api.example.com/private"
4033 );
4034 let a = Access {
4035 declared: caps(
4036 r#"{ "network": { "http": [{ "host": "api.example.com", "pathPrefix": "/public" }] } }"#,
4037 ),
4038 granted: None,
4039 };
4040 let from = "https://api.example.com/public/a.png";
4041 assert!(a.media_redirect(from, "b.png").is_ok());
4042 assert!(a.media_redirect(from, "../private.png").is_err());
4043 assert!(a.media_redirect(from, "/public/../private.png").is_err());
4044 }
4045
4046 #[test]
4050 fn media_sources_that_name_a_host_are_checked() {
4051 let a = Access {
4052 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
4053 granted: None,
4054 };
4055 for uri in [
4056 "//bank.example/x.png",
4057 "\\\\bank.example\\x.png",
4058 "/\\bank.example/x.png",
4059 "https:\\\\bank.example\\x.png",
4060 "https:/bank.example/x.png",
4061 "HTTPS://bank.example/x.png",
4062 ] {
4063 assert!(!a.allows_media(uri), "{uri}");
4064 }
4065 for uri in [
4067 "asset:/a.png",
4068 "data:image/png;base64,AAAA",
4069 "blob:https://app.example/1",
4070 "https://docs.example.com/x.png",
4071 ] {
4072 assert!(a.allows_media(uri), "{uri}");
4073 }
4074 assert!(!a.allows_media("img/a.png"));
4077 assert!(Access::default().allows_media("//bank.example/x.png"));
4079 }
4080
4081 #[test]
4085 fn media_sources_are_read_after_whatwg_strips_them() {
4086 let a = Access {
4087 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
4088 granted: None,
4089 };
4090 let page = Some("https://app.example/index.html");
4091 for uri in [
4092 "\t//bank.example/x.png",
4093 "\n//bank.example/x.png",
4094 "/\t/bank.example/x.png",
4095 " https://bank.example/x.png",
4096 "https://bank.example/x.png ",
4097 "ht\ttps://bank.example/x.png",
4098 "\u{1}https://bank.example/x.png",
4099 ] {
4100 assert_eq!(a.media_url(uri, page, None), None, "{uri:?} on the web");
4101 assert_eq!(
4102 a.media_url(uri, None, None),
4103 None,
4104 "{uri:?} in a native app"
4105 );
4106 }
4107 assert_eq!(
4109 a.media_url(" icons/a.png", page, None),
4110 Some(Cow::Borrowed(" icons/a.png"))
4111 );
4112 let local = Access {
4114 declared: caps(r#"{ "network": { "hosts": ["127.0.0.1"] } }"#),
4115 granted: None,
4116 };
4117 assert_eq!(
4118 local.media_url("http://0x7f.1/a.png", None, None),
4119 Some(Cow::Owned("http://127.0.0.1/a.png".into()))
4120 );
4121 assert_eq!(a.media_url("http://0x7f.1/a.png", None, None), None);
4122 for own in [
4124 "DATA:image/png;base64,AA",
4125 "Asset:/a.png",
4126 "BLOB:https://app.example/1",
4127 ] {
4128 assert_eq!(
4129 a.media_url(own, page, None),
4130 Some(Cow::Borrowed(own)),
4131 "{own}"
4132 );
4133 }
4134 }
4135
4136 #[test]
4142 fn whitespace_around_a_granted_url_loads_its_serialization() {
4143 let a = Access {
4144 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
4145 granted: None,
4146 };
4147 let page = Some("https://app.example/index.html");
4148 for (uri, base) in [
4149 ("https://docs.example.com/x.png ", None),
4150 (" https://docs.example.com/x.png", None),
4151 ("\u{1}https://docs.example.com/x.png", None),
4152 ("\t//docs.example.com/x.png", page),
4153 ] {
4154 assert_eq!(
4155 a.media_url(uri, base, None),
4156 Some(Cow::Owned("https://docs.example.com/x.png".into())),
4157 "{uri:?}"
4158 );
4159 }
4160 assert_eq!(a.media_url("https://bank.example/x.png ", None, None), None);
4163 for inside in [
4164 "https://docs.example.com/x\u{1}.png",
4165 "https://docs.ex\tample.com/x.png",
4166 "ht\ntps://docs.example.com/x.png",
4167 ] {
4168 assert_eq!(a.media_url(inside, None, None), None, "{inside:?}");
4169 }
4170 }
4171
4172 #[test]
4177 fn grant_paths_match_as_requests_send_them() {
4178 let a = Access {
4179 declared: caps(
4180 r#"{ "network": { "http": [
4181 { "host": "cdn.example.com", "pathPrefix": "/my photos" },
4182 { "host": "cdn.example.com", "paths": ["/über.png", "/{id}.png"] }
4183 ] } }"#,
4184 ),
4185 granted: None,
4186 };
4187 for url in [
4188 "https://cdn.example.com/my photos/a.png",
4189 "https://cdn.example.com/my%20photos/a.png",
4190 "https://cdn.example.com/über.png",
4191 "https://cdn.example.com/{id}.png",
4192 ] {
4193 assert!(a.allows_http("GET", url), "{url}");
4194 assert!(a.media_url(url, None, None).is_some(), "{url}");
4195 }
4196 assert!(!a.allows_http("GET", "https://cdn.example.com/my photosx/a.png"));
4197 for bad in [
4200 "/a/../b",
4201 "/./a",
4202 "/a/%2e%2e/b",
4203 "/a/.%2E",
4204 "/public\\..\\private",
4205 "/a/.\t./b",
4206 "/a/.\n/b",
4207 ] {
4208 let json = serde_json::json!({ "network": { "http": [{ "host": "h.example", "pathPrefix": bad }] } });
4209 assert!(Capabilities::from_json(&json).is_err(), "{bad}");
4210 }
4211 }
4212
4213 #[cfg(unix)]
4219 #[test]
4220 fn paths_outside_the_roots_are_refused_without_disk_work() {
4221 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
4222 let root = base.join(format!("media-text-{}", std::process::id()));
4223 let _ = std::fs::remove_dir_all(&root);
4224 std::fs::create_dir_all(root.join("allowed")).unwrap();
4225 std::fs::create_dir_all(root.join("elsewhere")).unwrap();
4226 std::fs::write(root.join("allowed/a.png"), b"png").unwrap();
4227 std::os::unix::fs::symlink(root.join("allowed"), root.join("elsewhere/in")).unwrap();
4229 let allowed = root.join("allowed");
4230 let access = Access {
4231 declared: Capabilities::from_json(
4232 &serde_json::json!({ "fs": { "read": [allowed.to_str().unwrap()] } }),
4233 )
4234 .unwrap(),
4235 granted: None,
4236 };
4237 let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
4238 let resolves = || RESOLVES.with(std::cell::Cell::get);
4239 let before = resolves();
4240 for outside in [
4241 root.join("elsewhere/x.png"),
4242 root.join("elsewhere/in/a.png"),
4243 PathBuf::from("/Volumes/hung/x.png"),
4244 ] {
4245 assert_eq!(files.readable(&outside), None, "{}", outside.display());
4246 }
4247 assert_eq!(
4248 resolves(),
4249 before,
4250 "outside the roots, nothing was resolved"
4251 );
4252 assert!(files.readable(&allowed.join("a.png")).is_some());
4254 assert!(
4255 files
4256 .readable(&canonicalize(&allowed).unwrap().join("a.png"))
4257 .is_some()
4258 );
4259 assert_eq!(resolves(), before + 2);
4260 let _ = std::fs::remove_dir_all(&root);
4261 }
4262
4263 #[cfg(unix)]
4267 #[test]
4268 fn a_granted_file_replaced_by_a_symlink_is_refused() {
4269 use std::os::unix::fs::symlink;
4270 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
4271 let root = base.join(format!("media-swap-{}", std::process::id()));
4272 let _ = std::fs::remove_dir_all(&root);
4273 std::fs::create_dir_all(root.join("allowed")).unwrap();
4274 let root = canonicalize(&root).unwrap();
4275 std::fs::write(root.join("allowed/image.png"), b"public").unwrap();
4276 std::fs::write(root.join("secret.png"), b"secret").unwrap();
4277 let allowed = root.join("allowed").to_str().unwrap().to_owned();
4278 let access = Access {
4279 declared: Capabilities::from_json(
4280 &serde_json::json!({ "fs": { "read": [allowed.clone()] } }),
4281 )
4282 .unwrap(),
4283 granted: None,
4284 };
4285 let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
4286 let src = format!("{allowed}/image.png");
4287 assert!(access.media_url(&src, None, Some(&files)).is_some());
4288 std::fs::remove_file(root.join("allowed/image.png")).unwrap();
4289 symlink(root.join("secret.png"), root.join("allowed/image.png")).unwrap();
4290 assert_eq!(access.media_url(&src, None, Some(&files)), None);
4291 let _ = std::fs::remove_dir_all(&root);
4292 }
4293
4294 #[test]
4299 fn bundled_files_stay_inside_the_app_files() {
4300 let a = Access {
4301 declared: caps(r#"{ "network": { "hosts": ["*"] } }"#),
4302 granted: None,
4303 };
4304 for escape in [
4305 "asset:/../outside.png",
4306 "asset:/sub/../../outside.png",
4307 "asset:/%2E%2e/outside.png",
4308 "asset:/..%2Foutside.png",
4309 "asset:/a%5c..%5c..%5coutside.png",
4310 "asset:/a.png?/../../outside.png",
4311 "asset:/a.png#/../../outside.png",
4312 "asset://Users/a/outside.png",
4313 "asset:/C:/outside.png",
4314 "asset:/./a.png",
4315 "asset:../outside.png",
4316 "ASSET:/../outside.png",
4317 ] {
4318 assert_eq!(a.media_url(escape, None, None), None, "{escape}");
4319 assert_eq!(
4320 a.media_url(escape, Some("https://app.example/"), None),
4321 None,
4322 "{escape} on the web"
4323 );
4324 assert_eq!(media_grant_advice(escape, None), ASSET_ADVICE, "{escape}");
4325 assert_eq!(media_capability(escape, None), "fs", "{escape}");
4326 }
4327 for inside in [
4328 "asset:/a.png",
4329 "asset:/@app/icons/a.png",
4330 "asset:/a.png?v=2",
4331 "asset:/a%20b.png",
4332 "asset:/sub/a..b.png",
4333 "ASSET:/a.png",
4334 ] {
4335 assert_eq!(
4336 a.media_url(inside, None, None),
4337 Some(Cow::Borrowed(inside)),
4338 "{inside}"
4339 );
4340 }
4341 assert_eq!(
4343 Access::default().media_url("asset:/../outside.png", None, None),
4344 Some(Cow::Borrowed("asset:/../outside.png"))
4345 );
4346 }
4347
4348 #[test]
4353 fn relative_paths_name_no_file_in_a_native_app() {
4354 let a = Access {
4355 declared: caps(r#"{ "network": { "hosts": ["*"] } }"#),
4356 granted: None,
4357 };
4358 for relative in [
4359 "clip.mp4",
4360 "./clip.mp4",
4361 "Users/a/secret.mp4",
4362 "../etc/x.png",
4363 " /etc/x.png",
4364 ] {
4365 assert_eq!(a.media_url(relative, None, None), None, "{relative}");
4366 assert_eq!(media_capability(relative, None), "fs", "{relative}");
4367 assert_eq!(
4368 media_grant_advice(relative, None),
4369 RELATIVE_ADVICE,
4370 "{relative}"
4371 );
4372 assert_eq!(
4373 a.media_url(relative, Some("https://app.example/"), None),
4374 Some(Cow::Borrowed(relative)),
4375 "{relative} on the web"
4376 );
4377 assert_eq!(
4378 Access::default().media_url(relative, None, None),
4379 Some(Cow::Borrowed(relative)),
4380 "{relative} without capabilities"
4381 );
4382 }
4383 for empty in ["", " "] {
4385 assert_eq!(a.media_url(empty, None, None), Some(Cow::Borrowed(empty)));
4386 }
4387 }
4388
4389 #[cfg(unix)]
4392 #[test]
4393 fn media_files_open_inside_their_root() {
4394 use std::io::Read;
4395 let base = std::env::temp_dir().join(format!("media-open-{}", std::process::id()));
4396 let _ = std::fs::remove_dir_all(&base);
4397 std::fs::create_dir_all(base.join("allowed")).unwrap();
4398 let base = canonicalize(&base).unwrap();
4399 std::fs::write(base.join("allowed/a.png"), b"public").unwrap();
4400 std::fs::write(base.join("secret.png"), b"secret").unwrap();
4401 let allowed = base.join("allowed");
4402 let access = Access {
4403 declared: Capabilities::from_json(
4404 &serde_json::json!({ "fs": { "read": [allowed.to_str().unwrap()] } }),
4405 )
4406 .unwrap(),
4407 granted: None,
4408 };
4409 let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
4410 let path = allowed.join("a.png");
4411 let read = |path: &Path| {
4412 let mut text = String::new();
4413 files.open(path)?.ok()?.read_to_string(&mut text).ok()?;
4414 Some(text)
4415 };
4416 assert_eq!(read(&path).as_deref(), Some("public"));
4417 std::fs::remove_file(&path).unwrap();
4419 std::os::unix::fs::symlink(base.join("secret.png"), &path).unwrap();
4420 assert!(matches!(files.open(&path), Some(Err(_))));
4421 assert!(matches!(files.open(&base.join("secret.png")), Some(Err(_))));
4422 assert!(MediaFiles::default().open(&path).is_none());
4424 std::fs::create_dir_all(base.join("allowed/sub")).unwrap();
4427 std::fs::write(base.join("allowed/sub/ok.png"), b"ok").unwrap();
4428 std::os::unix::fs::symlink(
4429 base.join("allowed/a.png"),
4430 base.join("allowed/sub/link.png"),
4431 )
4432 .unwrap();
4433 std::fs::remove_file(&path).unwrap();
4434 std::fs::write(&path, b"public").unwrap();
4435 let narrowed = Access {
4436 declared: access.declared.clone(),
4437 granted: Some(
4438 Capabilities::from_json(&serde_json::json!({
4439 "fs": { "read": [allowed.join("sub").to_str().unwrap()] }
4440 }))
4441 .unwrap(),
4442 ),
4443 };
4444 let files = MediaFiles::new(&narrowed, None, &TrustedPaths::default(), true);
4445 let mut text = String::new();
4446 files
4447 .open(&allowed.join("sub/ok.png"))
4448 .unwrap()
4449 .unwrap()
4450 .read_to_string(&mut text)
4451 .unwrap();
4452 assert_eq!(text, "ok");
4453 assert!(matches!(
4454 files.open(&allowed.join("sub/link.png")),
4455 Some(Err(_))
4456 ));
4457 assert!(matches!(files.open(&path), Some(Err(_))));
4458 let localhost = format!("file://localhost{}", allowed.join("sub/link.png").display());
4460 assert_eq!(narrowed.media_url(&localhost, None, Some(&files)), None);
4461 let ok = format!("file://localhost{}", allowed.join("sub/ok.png").display());
4462 assert!(narrowed.media_url(&ok, None, Some(&files)).is_some());
4463 let _ = std::fs::remove_dir_all(&base);
4464 }
4465
4466 #[cfg(unix)]
4470 #[test]
4471 fn a_dangling_symlink_in_a_granted_root_is_refused() {
4472 use std::os::unix::fs::symlink;
4473 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
4474 let root = base.join(format!("media-dangling-{}", std::process::id()));
4475 let _ = std::fs::remove_dir_all(&root);
4476 std::fs::create_dir_all(root.join("allowed")).unwrap();
4477 let root = canonicalize(&root).unwrap();
4478 symlink(root.join("secret.png"), root.join("allowed/link.png")).unwrap();
4479 let allowed = root.join("allowed").to_str().unwrap().to_owned();
4480 let access = Access {
4481 declared: Capabilities::from_json(
4482 &serde_json::json!({ "fs": { "read": [allowed.clone()] } }),
4483 )
4484 .unwrap(),
4485 granted: None,
4486 };
4487 let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
4488 assert_eq!(
4489 access.media_url(&format!("{allowed}/link.png"), None, Some(&files)),
4490 None
4491 );
4492 let missing = format!("{allowed}/later.png");
4494 assert_eq!(
4495 access.media_url(&missing, None, Some(&files)),
4496 Some(Cow::Borrowed(missing.as_str()))
4497 );
4498 let _ = std::fs::remove_dir_all(&root);
4499 }
4500
4501 #[cfg(unix)]
4506 #[test]
4507 fn local_media_files_need_an_fs_read_grant() {
4508 use std::os::unix::fs::symlink;
4509 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
4510 let root = base.join(format!("media-files-{}", std::process::id()));
4511 let _ = std::fs::remove_dir_all(&root);
4512 std::fs::create_dir_all(root.join("allowed")).unwrap();
4513 std::fs::create_dir_all(root.join("outside")).unwrap();
4514 std::fs::write(root.join("allowed/a.png"), b"png").unwrap();
4515 std::fs::write(root.join("outside/b.png"), b"png").unwrap();
4516 symlink(root.join("outside"), root.join("allowed/link")).unwrap();
4517 let root = canonicalize(&root).unwrap();
4519 let data = root.join("allowed");
4520 let access = Access {
4521 declared: caps(
4522 r#"{ "network": { "hosts": ["docs.example.com"] }, "fs": { "read": ["${dataDir}"] } }"#,
4523 ),
4524 granted: None,
4525 };
4526 let files = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), true);
4527 let real = canonicalize(&data).unwrap();
4528 let path = |p: &Path| p.to_str().unwrap().to_owned();
4529 let load = |uri: &str| {
4530 access
4531 .media_url(uri, None, Some(&files))
4532 .map(Cow::into_owned)
4533 };
4534
4535 let granted = path(&real.join("a.png"));
4536 assert_eq!(load(&path(&data.join("a.png"))), Some(granted.clone()));
4537 assert_eq!(
4538 load(&format!("file://{}", path(&data.join("a.png")))),
4539 Some(format!("file://{granted}"))
4540 );
4541 assert_eq!(
4542 load(&format!("FILE://{}", path(&data.join("a.png")))),
4543 Some(format!("file://{granted}"))
4544 );
4545 assert_eq!(load(&path(&data.join("../outside/b.png"))), None);
4547 assert_eq!(
4548 load(&format!("file://{}/%2e%2e/outside/b.png", path(&data))),
4549 None
4550 );
4551 assert_eq!(load(&path(&data.join("link/b.png"))), None);
4552 assert_eq!(load(&path(&root.join("outside/b.png"))), None);
4553 assert_eq!(
4555 access.media_url(&path(&data.join("a.png")), None, None),
4556 None
4557 );
4558 let mobile = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), false);
4559 assert_eq!(
4560 access.media_url(&path(&data.join("a.png")), None, Some(&mobile)),
4561 None
4562 );
4563 let network_only = Access {
4564 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
4565 granted: None,
4566 };
4567 let none = MediaFiles::new(&network_only, Some(&data), &TrustedPaths::default(), true);
4568 assert_eq!(
4569 network_only.media_url(&path(&data.join("a.png")), None, Some(&none)),
4570 None
4571 );
4572 let narrowed = Access {
4574 declared: caps(r#"{ "fs": { "read": ["${dataDir}"] } }"#),
4575 granted: Some(caps(r#"{ "fs": { "read": ["${dataDir}/sub"] } }"#)),
4576 };
4577 let files = MediaFiles::new(&narrowed, Some(&data), &TrustedPaths::default(), true);
4578 assert_eq!(
4579 narrowed.media_url(&path(&data.join("a.png")), None, Some(&files)),
4580 None
4581 );
4582 let page = Some("https://app.example/index.html");
4585 assert_eq!(
4586 access.media_url("/icons/a.png", page, None),
4587 Some(Cow::Borrowed("/icons/a.png"))
4588 );
4589 for local in [
4592 path(&root.join("outside/b.png")),
4593 format!("FILE://{}", path(&root.join("outside/b.png"))),
4594 "C:\\pictures\\x.png".to_owned(),
4595 "/x.png".to_owned(),
4596 ] {
4597 assert_eq!(
4598 Access::default().media_url(&local, None, None),
4599 Some(Cow::Borrowed(local.as_str())),
4600 "{local}"
4601 );
4602 }
4603 let files = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), true);
4605 for _ in 0..2 {
4606 let again = |uri: &str| {
4607 access
4608 .media_url(uri, None, Some(&files))
4609 .map(Cow::into_owned)
4610 };
4611 assert_eq!(again(&path(&data.join("a.png"))), Some(granted.clone()));
4612 assert_eq!(again(&path(&data.join("link/b.png"))), None);
4613 }
4614 let _ = std::fs::remove_dir_all(&root);
4615 }
4616
4617 #[test]
4620 fn every_native_os_has_the_files_the_capability_gates() {
4621 use crate::platform::Os;
4622 for os in [Os::MacOs, Os::Windows, Os::Linux, Os::Ios, Os::Android] {
4623 assert!(native_files(os), "{os:?}");
4624 }
4625 assert!(!native_files(Os::Web));
4626 }
4627
4628 #[cfg(not(target_arch = "wasm32"))]
4631 #[test]
4632 fn file_urls_name_their_decoded_path() {
4633 #[cfg(unix)]
4634 {
4635 assert_eq!(
4636 file_url_path("file:///tmp/a%20b.png"),
4637 Some(PathBuf::from("/tmp/a b.png"))
4638 );
4639 assert_eq!(
4640 file_url_path("file://localhost/tmp/a.png"),
4641 Some(PathBuf::from("/tmp/a.png"))
4642 );
4643 assert_eq!(file_url_path("file://host/tmp/a.png"), None);
4644 }
4645 #[cfg(windows)]
4646 {
4647 assert_eq!(
4652 file_url_path("file:///C:/a%20b.png"),
4653 Some(PathBuf::from("C:\\a b.png"))
4654 );
4655 assert_eq!(
4656 file_url_path("file://localhost/C:/a.png"),
4657 Some(PathBuf::from("C:\\a.png"))
4658 );
4659 assert_eq!(file_url_path("file:///tmp/a.png"), None);
4660 assert_eq!(file_url_path("file://localhost/tmp/a.png"), None);
4661 }
4662 assert_eq!(file_url_path("not a url"), None);
4663 assert_eq!(file_url_path("https://a/b"), None);
4664 }
4665
4666 #[test]
4669 fn refused_media_sources_advise_the_host_they_resolve_to() {
4670 let page = Some("http://localhost:8080/index.html");
4671 assert_eq!(
4673 media_grant_advice("//127.0.0.1:9000/a.png", page),
4674 "add `127.0.0.1` to capabilities.network in nsh.json"
4675 );
4676 assert_eq!(
4678 media_grant_advice("//127.0.0.1:9000/a.png", None),
4679 NO_SCHEME_ADVICE
4680 );
4681 assert_eq!(
4683 media_grant_advice("//127.0.0.1\\a.png", page),
4684 NO_HOST_ADVICE
4685 );
4686 assert_eq!(
4687 media_grant_advice("https://cdn.example.com/a.png", page),
4688 "add `cdn.example.com` to capabilities.network in nsh.json"
4689 );
4690 assert_eq!(
4693 media_grant_advice("/Users/a/x.png", None),
4694 LOCAL_FILE_ADVICE
4695 );
4696 assert_eq!(
4697 media_grant_advice("file:///Users/a/x.png", page),
4698 LOCAL_FILE_ADVICE
4699 );
4700 assert_eq!(media_capability("/Users/a/x.png", None), "fs");
4702 assert_eq!(media_capability("C:\\pictures\\x.png", None), "fs");
4703 assert_eq!(media_capability("FILE:///Users/a/x.png", page), "fs");
4704 assert_eq!(media_capability("/icons/a.png", page), "network");
4705 assert_eq!(
4706 media_capability("https://cdn.example.com/a.png", None),
4707 "network"
4708 );
4709 }
4710
4711 #[test]
4716 fn media_sources_load_the_url_the_check_granted() {
4717 let a = Access {
4718 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
4719 granted: None,
4720 };
4721 let https = Some("https://app.example/index.html");
4722 let http = Some("http://127.0.0.1:8080/");
4723 let loads = |uri, base| a.media_url(uri, base, None).map(|u| u.into_owned());
4724 assert_eq!(
4725 loads("https://DOCS.example.com/a/../x.png", None).as_deref(),
4726 Some("https://docs.example.com/x.png")
4727 );
4728 assert_eq!(
4729 loads("//docs.example.com/x.png", https).as_deref(),
4730 Some("https://docs.example.com/x.png")
4731 );
4732 assert_eq!(
4733 loads("//docs.example.com/x.png", http).as_deref(),
4734 Some("http://docs.example.com/x.png")
4735 );
4736 assert_eq!(loads("\\\\docs.example.com\\x.png", https), None);
4740 assert_eq!(loads("//docs.example.com/x.png", None), None);
4741 assert_eq!(loads("//bank.example/x.png", https), None);
4742 for own in ["asset:/a.png", "img/a.png", "data:image/png;base64,AAAA"] {
4743 assert!(
4744 matches!(a.media_url(own, https, None), Some(std::borrow::Cow::Borrowed(u)) if u == own),
4745 "{own}"
4746 );
4747 }
4748 assert!(matches!(
4750 Access::default().media_url("//bank.example/x.png", None, None),
4751 Some(std::borrow::Cow::Borrowed("//bank.example/x.png"))
4752 ));
4753 }
4754
4755 #[test]
4756 fn opening_urls_is_granted_by_scheme() {
4757 let caps = |json: serde_json::Value| Capabilities::from_json(&json).unwrap();
4758 let access =
4759 |declared: Capabilities, granted: Option<Capabilities>| Access { declared, granted };
4760 let any = access(caps(serde_json::json!({ "openUrl": true })), None);
4761 assert!(any.allows_open_url("https://a.com"));
4762 assert!(any.allows_open_url("tel:+15550100"));
4763 let some = access(
4764 caps(serde_json::json!({ "openUrl": { "schemes": ["HTTPS", "mailto"] } })),
4765 None,
4766 );
4767 assert!(some.allows_open_url("https://a.com"));
4768 assert!(some.allows_open_url("MAILTO:a@b.c"));
4769 assert!(!some.allows_open_url("tel:1"));
4770 let narrowed = access(
4772 caps(serde_json::json!({ "openUrl": true })),
4773 Some(caps(
4774 serde_json::json!({ "openUrl": { "schemes": ["https"] } }),
4775 )),
4776 );
4777 assert!(narrowed.allows_open_url("https://a.com"));
4778 assert!(!narrowed.allows_open_url("mailto:a@b.c"));
4779 let none = access(caps(serde_json::json!({ "openUrl": false })), None);
4780 assert!(!none.allows_open_url("https://a.com"));
4781 assert!(!access(caps(serde_json::json!({})), None).allows_open_url("https://a.com"));
4782 assert!(Access::default().allows_open_url("https://a.com"));
4783 for bad in [
4784 serde_json::json!({ "openUrl": "yes" }),
4785 serde_json::json!({ "openUrl": { "schemes": ["ht tp"] } }),
4786 serde_json::json!({ "openUrl": { "hosts": ["a.com"] } }),
4787 ] {
4788 assert!(Capabilities::from_json(&bad).is_err(), "{bad}");
4789 }
4790 for json in [
4792 serde_json::json!(true),
4793 serde_json::json!(false),
4794 serde_json::json!({ "schemes": ["https"] }),
4795 ] {
4796 let c = caps(serde_json::json!({ "openUrl": json }));
4797 assert_eq!(c.to_json()["openUrl"], json);
4798 }
4799 }
4800}