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
572pub(crate) fn absolute(path: &Path) -> bool {
575 if cfg!(target_arch = "wasm32") {
576 path.has_root()
577 } else {
578 path.is_absolute()
579 }
580}
581
582fn within(anchor: &Path, tail: &Path, root: &str) -> Result<PathBuf, String> {
586 use std::path::Component;
587 let names = tail
588 .components()
589 .all(|c| matches!(c, Component::Normal(_) | Component::CurDir));
590 let mut path = anchor.to_path_buf();
591 path.extend(tail.components().filter(|c| *c != Component::CurDir));
592 if names && path.starts_with(anchor) {
593 Ok(path)
594 } else {
595 Err(format!("filesystem root `{root}` leaves its anchor"))
596 }
597}
598
599pub(crate) fn env_names_match(a: &str, b: &str) -> bool {
603 if cfg!(windows) {
604 a.eq_ignore_ascii_case(b)
605 } else {
606 a == b
607 }
608}
609
610#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
612pub enum WebMedia {
613 Microphone,
615 Camera,
617}
618
619impl WebMedia {
620 pub fn as_str(self) -> &'static str {
622 match self {
623 Self::Microphone => "microphone",
624 Self::Camera => "camera",
625 }
626 }
627}
628
629#[derive(Debug, Clone, PartialEq, Eq, Default)]
633#[non_exhaustive]
634pub struct Capabilities {
635 pub process: ProcessGrants,
637 pub fs: FileGrants,
639 pub network: NetworkGrants,
641 pub webview: Option<Vec<HostPattern>>,
643 pub webview_input: bool,
646 pub webview_runtime_origin: bool,
650 pub webview_media: Vec<WebMedia>,
653 pub status_bar: bool,
655 pub clipboard: bool,
657 pub picker: bool,
660 pub share: bool,
664 pub speech: bool,
668 pub notifications: bool,
671 pub audio: bool,
673 pub application: bool,
678 pub home_dir: bool,
680 pub host: Vec<String>,
684 pub open_url: Option<OpenUrlGrant>,
687 pub windows: Option<WindowsGrant>,
691}
692
693#[derive(Debug, Clone, PartialEq, Eq, Default)]
697#[non_exhaustive]
698pub struct WindowsGrant {
699 pub kinds: Vec<crate::desktop::WindowKind>,
702 pub levels: Vec<crate::desktop::WindowLevel>,
704 pub max: Option<u32>,
707 pub overlay: bool,
709}
710
711impl WindowsGrant {
712 fn allows_kind(&self, kind: crate::desktop::WindowKind) -> bool {
713 use crate::desktop::WindowKind;
714 if kind == WindowKind::Overlay && !self.overlay {
715 return false;
716 }
717 self.kinds.is_empty() || self.kinds.contains(&kind)
718 }
719
720 fn allows_level(&self, level: crate::desktop::WindowLevel) -> bool {
721 self.levels.is_empty() || self.levels.contains(&level)
722 }
723}
724
725#[derive(Debug, Clone, PartialEq, Eq, Default)]
727#[non_exhaustive]
728pub struct OpenUrlGrant {
729 pub schemes: Vec<String>,
732}
733
734impl OpenUrlGrant {
735 pub fn allows(&self, scheme: &str) -> bool {
737 self.schemes.is_empty() || self.schemes.iter().any(|s| s == scheme)
738 }
739}
740
741#[derive(Debug, Clone, PartialEq, Eq)]
743pub struct UrlParts<'a> {
744 pub scheme: String,
746 pub host: String,
748 pub path: &'a str,
750 pub port: Option<u16>,
752}
753
754pub fn parse_url(url: &str) -> Option<UrlParts<'_>> {
759 read_url(url).ok()
760}
761
762pub(crate) fn grant_advice(url: &str, capability: &str) -> String {
766 match parse_url(url) {
767 Some(parts) => format!(
768 "add `{}` to capabilities.{capability} in nsh.json",
769 parts.host
770 ),
771 None => NO_HOST_ADVICE.to_owned(),
772 }
773}
774
775pub(crate) fn media_grant_advice(uri: &str, base: Option<&str>) -> String {
780 if native_relative(uri, base) {
781 return RELATIVE_ADVICE.to_owned();
782 }
783 if starts_with_ignoring_case(uri, "asset:") && !is_inside_assets(uri) {
784 return ASSET_ADVICE.to_owned();
785 }
786 if media_capability(uri, base) == "fs" {
787 return LOCAL_FILE_ADVICE.to_owned();
788 }
789 let unambiguous = !uri.contains('\\') && !uri.bytes().any(|b| b.is_ascii_control());
790 if scheme_of(uri).is_none() && uri.starts_with("//") && unambiguous {
791 let resolved = base
792 .and_then(|base| url::Url::parse(base).ok())
793 .and_then(|base| base.join(uri).ok());
794 return match resolved {
795 Some(url) => grant_advice(url.as_str(), "network"),
796 None => NO_SCHEME_ADVICE.to_owned(),
797 };
798 }
799 grant_advice(uri, "network")
800}
801
802pub(crate) fn media_capability(uri: &str, base: Option<&str>) -> &'static str {
806 if starts_with_ignoring_case(uri, "asset:") || native_relative(uri, base) {
807 return "fs";
808 }
809 let local =
810 (base.is_none() || starts_with_ignoring_case(uri, "file:")) && local_file(uri).is_some();
811 if local { "fs" } else { "network" }
812}
813
814const RELATIVE_ADVICE: &str = "a relative path names no file in a native app: name a bundled file as `asset:/…`, or import it";
816
817const ASSET_ADVICE: &str = "bundled files are named by a path inside the app's files";
820
821const LOCAL_FILE_ADVICE: &str =
823 "a local file is read under capabilities.fs.read in nsh.json: add a root that holds it";
824
825const NO_SCHEME_ADVICE: &str =
827 "it names no scheme and has no page to take one from: write it as an http(s) URL";
828
829const 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";
831
832fn is_own_media(uri: &str) -> bool {
836 ["asset:", "data:", "blob:"]
837 .iter()
838 .any(|prefix| starts_with_ignoring_case(uri, prefix))
839}
840
841pub fn is_inside_assets(url: &str) -> bool {
851 let Some(path) = url.get(6..).and_then(|rest| rest.strip_prefix('/')) else {
852 return false;
853 };
854 path.split('/').all(|segment| {
855 let bytes = segment.as_bytes();
856 let encoded = |code: &[u8; 3]| bytes.windows(3).any(|w| w.eq_ignore_ascii_case(code));
857 !only_dots(bytes)
858 && !bytes.iter().any(|b| matches!(b, b'\\' | b'\0' | b':'))
859 && ![b"%2f", b"%5c", b"%00", b"%3a"]
860 .iter()
861 .any(|code| encoded(code))
862 })
863}
864
865fn only_dots(segment: &[u8]) -> bool {
868 let (mut dots, mut at) = (0, 0);
869 while at < segment.len() {
870 if segment[at] == b'.' {
871 at += 1;
872 } else if segment[at..].len() >= 3
873 && segment[at] == b'%'
874 && segment[at + 1] == b'2'
875 && segment[at + 2].eq_ignore_ascii_case(&b'e')
876 {
877 at += 3;
878 } else {
879 return false;
880 }
881 dots += 1;
882 if dots > 2 {
883 return false;
884 }
885 }
886 true
887}
888
889fn names_host(uri: &str) -> bool {
892 let stripped = whatwg_stripped(uri);
893 scheme_of(&stripped).is_some()
894 || stripped.starts_with("//")
895 || stripped.starts_with('\\')
896 || stripped.starts_with("/\\")
897}
898
899fn native_relative(uri: &str, base: Option<&str>) -> bool {
902 base.is_none()
903 && !uri.trim().is_empty()
904 && !is_own_media(uri)
905 && local_file(uri).is_none()
906 && !names_host(uri)
907}
908
909fn path_as_sent(path: &str) -> Option<String> {
914 let path: String = path
916 .chars()
917 .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
918 .map(|c| if c == '\\' { '/' } else { c })
919 .collect();
920 let dots = path.split('/').any(|segment| {
921 let segment = segment.to_ascii_lowercase().replace("%2e", ".");
922 segment == "." || segment == ".."
923 });
924 if dots {
925 return None;
926 }
927 let url = url::Url::parse(&format!("http://h{path}")).ok()?;
928 Some(url.path().to_owned())
929}
930
931fn starts_with_ignoring_case(text: &str, prefix: &str) -> bool {
933 text.get(..prefix.len())
934 .is_some_and(|head| head.eq_ignore_ascii_case(prefix))
935}
936
937fn local_file(uri: &str) -> Option<Option<PathBuf>> {
942 if starts_with_ignoring_case(uri, "file:") {
943 return Some(file_url_path(uri));
944 }
945 let drive = matches!(uri.as_bytes(), [d, b':', b'\\' | b'/', ..] if d.is_ascii_alphabetic());
946 let rooted = uri.starts_with('/') && !uri.starts_with("//") && !uri.starts_with("/\\");
947 (drive || rooted).then(|| Some(PathBuf::from(uri)))
948}
949
950#[doc(hidden)]
955pub fn file_url_path(uri: &str) -> Option<PathBuf> {
956 #[cfg(target_arch = "wasm32")]
957 {
958 let _ = uri;
959 None
960 }
961 #[cfg(not(target_arch = "wasm32"))]
962 {
963 url::Url::parse(uri).ok()?.to_file_path().ok()
964 }
965}
966
967fn file_url_of(path: &Path) -> Option<String> {
969 #[cfg(target_arch = "wasm32")]
970 {
971 let _ = path;
972 None
973 }
974 #[cfg(not(target_arch = "wasm32"))]
975 {
976 url::Url::from_file_path(path).ok().map(String::from)
977 }
978}
979
980fn whatwg_stripped(uri: &str) -> Cow<'_, str> {
983 let trimmed = uri.trim_matches(|c: char| c <= ' ');
984 if trimmed.contains(['\t', '\n', '\r']) {
985 Cow::Owned(trimmed.replace(['\t', '\n', '\r'], ""))
986 } else {
987 Cow::Borrowed(trimmed)
988 }
989}
990
991fn scheme_of(uri: &str) -> Option<&str> {
993 let (scheme, _) = uri.split_once(':')?;
994 let mut chars = scheme.chars();
995 (chars.next()?.is_ascii_alphabetic()
996 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')))
997 .then_some(scheme)
998}
999
1000fn media_as_written(uri: &str, allows_http: impl Fn(&str) -> bool) -> bool {
1004 !uri.contains("://") || is_own_media(uri) || local_file(uri).is_some() || allows_http(uri)
1005}
1006
1007fn written_or(written: &str, serialized: String) -> Cow<'_, str> {
1009 if serialized == written {
1010 Cow::Borrowed(written)
1011 } else {
1012 Cow::Owned(serialized)
1013 }
1014}
1015
1016enum Unread {
1018 NotUrl,
1020 Ambiguous(String),
1023}
1024
1025fn read_url(url: &str) -> Result<UrlParts<'_>, Unread> {
1027 let (scheme, rest) = url.split_once("://").ok_or(Unread::NotUrl)?;
1028 if scheme.is_empty()
1029 || !scheme
1030 .chars()
1031 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
1032 {
1033 return Err(Unread::NotUrl);
1034 }
1035 let scheme = scheme.to_ascii_lowercase();
1036 let head = url.split(['?', '#']).next().unwrap_or(url);
1042 if head.contains('\\') || url.bytes().any(|b| b.is_ascii_control()) {
1043 return Err(Unread::Ambiguous(scheme));
1044 }
1045 let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
1046 let (authority, path) = rest.split_at(end);
1047 let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
1049 let host = if let Some(v6) = host_port.strip_prefix('[') {
1050 format!("[{}]", v6.split_once(']').ok_or(Unread::NotUrl)?.0)
1051 } else {
1052 host_port.split(':').next().unwrap_or_default().to_owned()
1053 };
1054 if host.is_empty() {
1055 return Err(Unread::NotUrl);
1056 }
1057 if host.contains(['%', ' ', '<', '>', '^', '|'])
1060 || (!host_port.starts_with('[') && host.contains(['[', ']']))
1061 {
1062 return Err(Unread::Ambiguous(scheme));
1063 }
1064 let port = if host_port.starts_with('[') {
1065 host_port
1066 .split_once(']')
1067 .and_then(|(_, rest)| rest.strip_prefix(':'))
1068 .map(str::parse::<u16>)
1069 .transpose()
1070 } else {
1071 host_port
1072 .split_once(':')
1073 .map(|(_, port)| port.parse::<u16>())
1074 .transpose()
1075 }
1076 .map_err(|_| Unread::NotUrl)?;
1077 Ok(UrlParts {
1078 scheme,
1079 host: host.to_ascii_lowercase().trim_end_matches('.').to_owned(),
1080 path: if path.is_empty() { "/" } else { path },
1081 port,
1082 })
1083}
1084
1085#[derive(Debug, Clone, PartialEq, Eq)]
1092#[non_exhaustive]
1093pub struct WebOrigin {
1094 scheme: String,
1095 host: String,
1096 port: u16,
1097}
1098
1099impl WebOrigin {
1100 pub fn parse(origin: &str) -> Result<Self, String> {
1104 let refused = |why: &str| Err(format!("`{origin}` is not an origin: {why}"));
1105 let Some((scheme, rest)) = origin.split_once("://") else {
1106 return refused("it is not `http://host` or `https://host`");
1107 };
1108 let scheme = scheme.to_ascii_lowercase();
1109 if !matches!(scheme.as_str(), "http" | "https") {
1110 return refused("its scheme is not http or https");
1111 }
1112 let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
1113 let (authority, after) = rest.split_at(end);
1114 if !matches!(after, "" | "/") {
1115 return refused("it has a path, a query or a fragment");
1116 }
1117 if authority.contains('@') {
1118 return refused("it has user info");
1119 }
1120 if !authority.is_ascii() || authority.contains('*') {
1121 return refused("its host is not an ASCII host name or address");
1122 }
1123 let Ok(parts) = read_url(origin) else {
1124 return refused("its host or port cannot be read");
1125 };
1126 let port = parts.port.unwrap_or(default_port(&scheme));
1127 Ok(Self {
1128 scheme,
1129 host: parts.host,
1130 port,
1131 })
1132 }
1133
1134 pub fn contains(&self, url: &str) -> bool {
1138 let url = blob_origin(url).unwrap_or(url);
1139 read_url(url).is_ok_and(|parts| {
1140 parts.scheme == self.scheme
1141 && parts.host == self.host
1142 && parts.port.unwrap_or(default_port(&parts.scheme)) == self.port
1143 })
1144 }
1145}
1146
1147impl std::fmt::Display for WebOrigin {
1149 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1150 write!(f, "{}://{}", self.scheme, self.host)?;
1151 if self.port != default_port(&self.scheme) {
1152 write!(f, ":{}", self.port)?;
1153 }
1154 Ok(())
1155 }
1156}
1157
1158fn default_port(scheme: &str) -> u16 {
1160 match scheme {
1161 "http" => 80,
1162 "https" => 443,
1163 _ => 0,
1164 }
1165}
1166
1167fn blob_origin(url: &str) -> Option<&str> {
1172 url.get(..5)
1173 .is_some_and(|scheme| scheme.eq_ignore_ascii_case("blob:"))
1174 .then(|| &url[5..])
1175 .filter(|origin| !origin.is_empty())
1176}
1177
1178impl Capabilities {
1179 pub fn all() -> Self {
1183 let any = vec![HostPattern("*".into())];
1184 Self {
1185 network: NetworkGrants {
1186 hosts: any.clone(),
1187 http: Vec::new(),
1188 sockets: Vec::new(),
1189 },
1190 webview: Some(any),
1191 status_bar: true,
1192 clipboard: true,
1193 picker: true,
1194 share: true,
1195 speech: true,
1196 notifications: true,
1197 audio: true,
1198 application: true,
1199 home_dir: true,
1200 open_url: Some(OpenUrlGrant::default()),
1201 windows: Some(WindowsGrant::default()),
1203 ..Self::default()
1205 }
1206 }
1207
1208 pub fn from_json(value: &Value) -> Result<Self, String> {
1213 Self::parse(value, None)
1214 }
1215
1216 pub fn from_json_lenient(value: &Value) -> Result<(Self, Vec<String>), String> {
1227 let mut dropped = Vec::new();
1228 let Value::Object(obj) = value else {
1229 dropped.push(format!(
1230 "capabilities ({value} is not an object): all of them"
1231 ));
1232 return Ok((Self::default(), dropped));
1233 };
1234 let mut readable = Map::new();
1236 for (key, v) in obj {
1237 let one = Value::Object(Map::from_iter([(key.clone(), v.clone())]));
1238 let mut its_dropped = Vec::new();
1239 match Self::parse(&one, Some(&mut its_dropped)) {
1240 Ok(_) => {
1241 dropped.append(&mut its_dropped);
1242 readable.insert(key.clone(), v.clone());
1243 }
1244 Err(e) => dropped.push(format!("capabilities.{key} ({e})")),
1245 }
1246 }
1247 let caps = Self::parse(&Value::Object(readable), Some(&mut Vec::new()))?;
1248 Ok((caps, dropped))
1249 }
1250
1251 fn parse(value: &Value, mut dropped: Option<&mut Vec<String>>) -> Result<Self, String> {
1254 const KNOWN: [&str; 16] = [
1255 "windows",
1256 "network",
1257 "webview",
1258 "statusBar",
1259 "clipboard",
1260 "picker",
1261 "share",
1262 "speech",
1263 "notifications",
1264 "audio",
1265 "application",
1266 "homeDir",
1267 "openUrl",
1268 "process",
1269 "fs",
1270 "host",
1271 ];
1272 let obj = object(value, "capabilities")?;
1273 for key in obj.keys().filter(|k| !KNOWN.contains(&k.as_str())) {
1274 match dropped.as_deref_mut() {
1275 Some(dropped) => dropped.push(format!("capabilities.{key}")),
1277 None => return Err(unknown_key("capabilities", key, &KNOWN)),
1278 }
1279 }
1280 let lenient = dropped.is_some();
1281 let mut http_dropped = Vec::new();
1284 let mut check = |obj: &Map<String, Value>,
1287 what: &str,
1288 keys: &[&str],
1289 name: &str|
1290 -> Result<bool, String> {
1291 let Some(key) = obj.keys().find(|k| !keys.contains(&k.as_str())) else {
1292 return Ok(true);
1293 };
1294 match dropped.as_deref_mut() {
1295 Some(dropped) => {
1296 dropped.push(format!("{name} (unknown key `{key}`)"));
1297 Ok(false)
1298 }
1299 None => Err(unknown_key(what, key, keys)),
1300 }
1301 };
1302 let mut caps = Capabilities::default();
1303 if let Some(network) = obj.get("network") {
1304 let network = object(network, "capabilities.network")?;
1305 if check(
1306 network,
1307 "capabilities.network",
1308 &["hosts", "http", "sockets"],
1309 "capabilities.network",
1310 )? {
1311 if let Some(hosts) = network.get("hosts") {
1312 caps.network.hosts = patterns(hosts, "capabilities.network.hosts")?;
1313 }
1314 if let Some(sockets) = network.get("sockets") {
1315 caps.network.sockets = strings(sockets, "capabilities.network.sockets")?
1316 .iter()
1317 .map(|s| SocketGrant::new(s))
1318 .collect::<Result<_, _>>()?;
1319 }
1320 if let Some(http) = network.get("http") {
1321 let list = http
1322 .as_array()
1323 .ok_or("capabilities.network.http must be an array")?;
1324 for (i, grant) in list.iter().enumerate() {
1325 let name = format!("capabilities.network.http[{i}]");
1326 let parsed = object(grant, "capabilities.network.http[]").and_then(|g| {
1327 let keys = [
1328 "host",
1329 "methods",
1330 "scheme",
1331 "schemes",
1332 "port",
1333 "paths",
1334 "pathPrefix",
1335 "pathPrefixes",
1336 "path_prefixes",
1337 ];
1338 Ok(
1339 match check(g, "capabilities.network.http[]", &keys, &name)? {
1340 true => Some(http_grant(g)?),
1341 false => None,
1342 },
1343 )
1344 });
1345 match parsed {
1346 Ok(Some(grant)) => caps.network.http.push(grant),
1347 Ok(None) => {}
1348 Err(e) if lenient => http_dropped.push(format!("{name} ({e})")),
1351 Err(e) => return Err(e),
1352 }
1353 }
1354 }
1355 }
1356 }
1357 if let Some(webview) = obj.get("webview") {
1358 let webview = object(webview, "capabilities.webview")?;
1359 if check(
1360 webview,
1361 "capabilities.webview",
1362 &["hosts", "input", "media", "runtimeOrigin"],
1363 "capabilities.webview",
1364 )? {
1365 caps.webview = Some(match webview.get("hosts") {
1366 Some(hosts) => patterns(hosts, "capabilities.webview.hosts")?,
1367 None => Vec::new(),
1368 });
1369 if let Some(input) = webview.get("input") {
1370 caps.webview_input = input
1371 .as_bool()
1372 .ok_or("capabilities.webview.input must be a boolean")?;
1373 }
1374 if let Some(runtime_origin) = webview.get("runtimeOrigin") {
1375 caps.webview_runtime_origin = runtime_origin
1376 .as_bool()
1377 .ok_or("capabilities.webview.runtimeOrigin must be a boolean")?;
1378 }
1379 if let Some(media) = webview.get("media") {
1380 caps.webview_media = strings(media, "capabilities.webview.media")?
1381 .iter()
1382 .map(|kind| match kind.as_str() {
1383 "microphone" => Ok(WebMedia::Microphone),
1384 "camera" => Ok(WebMedia::Camera),
1385 _ => Err(format!(
1386 "capabilities.webview.media takes `microphone` and `camera`, not `{kind}`"
1387 )),
1388 })
1389 .collect::<Result<_, _>>()?;
1390 }
1391 }
1392 }
1393 if let Some(status_bar) = obj.get("statusBar") {
1394 caps.status_bar = status_bar
1395 .as_bool()
1396 .ok_or("capabilities.statusBar must be a boolean")?;
1397 }
1398 if let Some(clipboard) = obj.get("clipboard") {
1399 caps.clipboard = clipboard
1400 .as_bool()
1401 .ok_or("capabilities.clipboard must be a boolean")?;
1402 }
1403 if let Some(picker) = obj.get("picker") {
1404 caps.picker = picker
1405 .as_bool()
1406 .ok_or("capabilities.picker must be a boolean")?;
1407 }
1408 if let Some(share) = obj.get("share") {
1409 caps.share = share
1410 .as_bool()
1411 .ok_or("capabilities.share must be a boolean")?;
1412 }
1413 if let Some(speech) = obj.get("speech") {
1414 caps.speech = speech
1415 .as_bool()
1416 .ok_or("capabilities.speech must be a boolean")?;
1417 }
1418 if let Some(notifications) = obj.get("notifications") {
1419 caps.notifications = notifications
1420 .as_bool()
1421 .ok_or("capabilities.notifications must be a boolean")?;
1422 }
1423 if let Some(audio) = obj.get("audio") {
1424 caps.audio = audio
1425 .as_bool()
1426 .ok_or("capabilities.audio must be a boolean")?;
1427 }
1428 if let Some(application) = obj.get("application") {
1429 caps.application = application
1430 .as_bool()
1431 .ok_or("capabilities.application must be a boolean")?;
1432 }
1433 if let Some(home_dir) = obj.get("homeDir") {
1434 caps.home_dir = home_dir
1435 .as_bool()
1436 .ok_or("capabilities.homeDir must be a boolean")?;
1437 }
1438 if let Some(open_url) = obj.get("openUrl") {
1439 match open_url {
1440 Value::Bool(granted) => {
1441 caps.open_url = granted.then(OpenUrlGrant::default);
1442 }
1443 Value::Object(grant) => {
1444 if check(
1445 grant,
1446 "capabilities.openUrl",
1447 &["schemes"],
1448 "capabilities.openUrl",
1449 )? {
1450 let schemes = match grant.get("schemes") {
1451 Some(schemes) => strings(schemes, "capabilities.openUrl.schemes")?,
1452 None => Vec::new(),
1453 };
1454 if schemes.iter().any(|s| {
1455 s.is_empty()
1456 || !s.starts_with(|c: char| c.is_ascii_alphabetic())
1457 || !s
1458 .chars()
1459 .all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c))
1460 }) {
1461 return Err(
1462 "capabilities.openUrl.schemes needs URL schemes (`https`, `mailto`)"
1463 .into(),
1464 );
1465 }
1466 caps.open_url = Some(OpenUrlGrant {
1467 schemes: schemes.iter().map(|s| s.to_ascii_lowercase()).collect(),
1468 });
1469 }
1470 }
1471 _ => {
1472 return Err(
1473 "capabilities.openUrl must be a boolean or an object of `schemes`".into(),
1474 );
1475 }
1476 }
1477 }
1478 if let Some(process) = obj.get("process") {
1479 let process = object(process, "capabilities.process")?;
1480 if check(
1481 process,
1482 "capabilities.process",
1483 &["execute", "exit", "env"],
1484 "capabilities.process",
1485 )? {
1486 if let Some(execute) = process.get("execute") {
1487 caps.process.execute = strings(execute, "capabilities.process.execute")?;
1488 if caps.process.execute.iter().any(|s| !valid_command(s)) {
1489 return Err("capabilities.process.execute needs exact executable names or absolute paths".into());
1490 }
1491 }
1492 if let Some(exit) = process.get("exit") {
1493 caps.process.exit = exit
1494 .as_bool()
1495 .ok_or("capabilities.process.exit must be a boolean")?;
1496 }
1497 if let Some(env) = process.get("env") {
1498 caps.process.env = strings(env, "capabilities.process.env")?;
1499 if caps
1500 .process
1501 .env
1502 .iter()
1503 .any(|name| name.is_empty() || name.contains(['=', '\0']))
1504 {
1505 return Err(
1506 "capabilities.process.env needs nonempty environment variable names"
1507 .into(),
1508 );
1509 }
1510 }
1511 }
1512 }
1513 if let Some(fs) = obj.get("fs") {
1514 let fs = object(fs, "capabilities.fs")?;
1515 if check(fs, "capabilities.fs", &["read", "write"], "capabilities.fs")? {
1516 for (key, target) in [("read", &mut caps.fs.read), ("write", &mut caps.fs.write)] {
1517 if let Some(value) = fs.get(key) {
1518 *target = strings(value, &format!("capabilities.fs.{key}"))?;
1519 for root in target.iter() {
1520 validate_path_pattern(root)?;
1521 }
1522 }
1523 }
1524 }
1525 }
1526 if let Some(windows) = obj.get("windows") {
1527 match windows {
1528 Value::Bool(granted) => caps.windows = granted.then(WindowsGrant::default),
1529 Value::Object(grant) => {
1530 if check(
1531 grant,
1532 "capabilities.windows",
1533 &["kinds", "levels", "max", "overlay"],
1534 "capabilities.windows",
1535 )? {
1536 caps.windows = Some(windows_grant(grant)?);
1537 }
1538 }
1539 _ => {
1540 return Err(
1541 "capabilities.windows must be a boolean or an object of `kinds`, `levels`, `max` and `overlay`"
1542 .into(),
1543 );
1544 }
1545 }
1546 }
1547 if let Some(host) = obj.get("host") {
1548 caps.host = match host {
1549 Value::Bool(all) => {
1550 if *all {
1551 vec!["*".into()]
1552 } else {
1553 Vec::new()
1554 }
1555 }
1556 _ => {
1557 let names = strings(host, "capabilities.host")
1558 .map_err(|e| format!("{e} (or a boolean)"))?;
1559 if let Some(bad) = names.iter().find(|n| match n.strip_suffix('*') {
1560 Some(prefix) => !prefix.is_empty() && !valid_host_name(prefix),
1561 None => !valid_host_name(n),
1562 }) {
1563 return Err(format!(
1564 "capabilities.host: invalid function `{bad}` (a name of {HOST_NAME_CHARS}, or a prefix of them ending in `*`)"
1565 ));
1566 }
1567 names
1568 }
1569 };
1570 }
1571 if let Some(dropped) = dropped {
1572 dropped.append(&mut http_dropped);
1573 }
1574 Ok(caps)
1575 }
1576
1577 pub fn to_json(&self) -> Value {
1579 let mut obj = self.to_json_without_windows();
1580 if let (Value::Object(obj), Some(w)) = (&mut obj, &self.windows) {
1582 let mut o = Map::new();
1583 if !w.kinds.is_empty() {
1584 o.insert(
1585 "kinds".into(),
1586 w.kinds
1587 .iter()
1588 .map(|k| window_kind_name(*k))
1589 .collect::<Vec<_>>()
1590 .into(),
1591 );
1592 }
1593 if !w.levels.is_empty() {
1594 o.insert(
1595 "levels".into(),
1596 w.levels
1597 .iter()
1598 .map(|l| window_level_name(*l))
1599 .collect::<Vec<_>>()
1600 .into(),
1601 );
1602 }
1603 if let Some(max) = w.max {
1604 o.insert("max".into(), max.into());
1605 }
1606 if w.overlay {
1607 o.insert("overlay".into(), true.into());
1608 }
1609 obj.insert("windows".into(), Value::Object(o));
1610 }
1611 obj
1612 }
1613
1614 fn to_json_without_windows(&self) -> Value {
1615 let list =
1616 |l: &[HostPattern]| Value::from(l.iter().map(|p| p.0.clone()).collect::<Vec<_>>());
1617 let mut network = Map::new();
1618 network.insert("hosts".into(), list(&self.network.hosts));
1619 let http: Vec<Value> = self
1620 .network
1621 .http
1622 .iter()
1623 .map(|g| {
1624 let mut o = Map::new();
1625 o.insert("host".into(), g.host.0.clone().into());
1626 if !g.methods.is_empty() {
1627 o.insert("methods".into(), g.methods.clone().into());
1628 }
1629 if !g.schemes.is_empty() {
1630 o.insert("schemes".into(), g.schemes.clone().into());
1631 }
1632 if let Some(port) = g.port {
1633 o.insert("port".into(), port.into());
1634 }
1635 if !g.paths.is_empty() {
1636 o.insert("paths".into(), g.paths.clone().into());
1637 }
1638 if !g.path_prefixes.is_empty() {
1639 o.insert("pathPrefixes".into(), g.path_prefixes.clone().into());
1640 }
1641 Value::Object(o)
1642 })
1643 .collect();
1644 network.insert("http".into(), http.into());
1645 if !self.network.sockets.is_empty() {
1646 let sockets: Vec<String> = self
1647 .network
1648 .sockets
1649 .iter()
1650 .map(SocketGrant::to_string_form)
1651 .collect();
1652 network.insert("sockets".into(), sockets.into());
1653 }
1654 let mut obj = Map::new();
1655 obj.insert("network".into(), Value::Object(network));
1656 obj.insert(
1657 "process".into(),
1658 serde_json::json!({"execute": self.process.execute, "exit": self.process.exit, "env": self.process.env}),
1659 );
1660 obj.insert(
1661 "fs".into(),
1662 serde_json::json!({"read": self.fs.read, "write": self.fs.write}),
1663 );
1664 if let Some(hosts) = &self.webview {
1665 let mut w = Map::new();
1666 w.insert("hosts".into(), list(hosts));
1667 if self.webview_input {
1669 w.insert("input".into(), true.into());
1670 }
1671 if self.webview_runtime_origin {
1672 w.insert("runtimeOrigin".into(), true.into());
1673 }
1674 if !self.webview_media.is_empty() {
1675 let media = self.webview_media.iter().map(|m| m.as_str().into());
1676 w.insert("media".into(), Value::Array(media.collect()));
1677 }
1678 obj.insert("webview".into(), Value::Object(w));
1679 }
1680 obj.insert("statusBar".into(), self.status_bar.into());
1681 obj.insert("clipboard".into(), self.clipboard.into());
1682 obj.insert("picker".into(), self.picker.into());
1683 if self.share {
1685 obj.insert("share".into(), true.into());
1686 }
1687 if self.speech {
1688 obj.insert("speech".into(), true.into());
1689 }
1690 if self.notifications {
1691 obj.insert("notifications".into(), true.into());
1692 }
1693 if self.audio {
1694 obj.insert("audio".into(), true.into());
1695 }
1696 if self.application {
1697 obj.insert("application".into(), true.into());
1698 }
1699 if self.home_dir {
1700 obj.insert("homeDir".into(), true.into());
1701 }
1702 if !self.host.is_empty() {
1703 obj.insert("host".into(), self.host.clone().into());
1704 }
1705 obj.insert(
1706 "openUrl".into(),
1707 match &self.open_url {
1708 None => false.into(),
1709 Some(grant) if grant.schemes.is_empty() => true.into(),
1710 Some(grant) => serde_json::json!({ "schemes": grant.schemes }),
1711 },
1712 );
1713 Value::Object(obj)
1714 }
1715
1716 fn allows_http(&self, method: &str, url: &UrlParts<'_>) -> bool {
1717 if !matches!(url.scheme.as_str(), "http" | "https" | "ws" | "wss") {
1718 return false;
1719 }
1720 self.network.hosts.iter().any(|h| h.matches(&url.host))
1721 || self.network.http.iter().any(|g| g.allows(method, url))
1722 }
1723
1724 fn allows_http_anywhere(&self, method: &str, scheme: &str) -> bool {
1726 matches!(scheme, "http" | "https" | "ws" | "wss")
1727 && (self.network.hosts.iter().any(HostPattern::is_any)
1728 || self
1729 .network
1730 .http
1731 .iter()
1732 .any(|g| g.allows_anywhere(method, scheme)))
1733 }
1734
1735 fn allows_host(&self, name: &str) -> bool {
1736 self.host.iter().any(|g| match g.strip_suffix('*') {
1737 Some(prefix) => name.starts_with(prefix),
1738 None => g == name,
1739 })
1740 }
1741
1742 fn allows_webview(&self, url: &UrlParts<'_>) -> bool {
1743 matches!(url.scheme.as_str(), "http" | "https")
1744 && self
1745 .webview
1746 .as_ref()
1747 .is_some_and(|hosts| hosts.iter().any(|h| h.matches(&url.host)))
1748 }
1749
1750 fn allows_webview_anywhere(&self, scheme: &str) -> bool {
1752 matches!(scheme, "http" | "https")
1753 && self
1754 .webview
1755 .as_ref()
1756 .is_some_and(|hosts| hosts.iter().any(HostPattern::is_any))
1757 }
1758}
1759
1760pub const HOST_NAME_CHARS: &str = "1 to 128 of A-Z a-z 0-9 _ . : -, without `..`";
1762
1763pub fn valid_host_name(name: &str) -> bool {
1767 (1..=128).contains(&name.len())
1768 && name
1769 .bytes()
1770 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b':' | b'-'))
1771 && !name.contains("..")
1772}
1773
1774fn valid_command(command: &str) -> bool {
1775 !command.is_empty()
1776 && !command.contains(['\0', '*'])
1777 && (Path::new(command).has_root()
1783 || absolute(Path::new(command))
1784 || (!command.contains(['/', '\\', ':']) && command != "." && command != ".."))
1787}
1788
1789fn validate_path_pattern(path: &str) -> Result<(), String> {
1790 if [
1791 "$HOME",
1792 "${HOME}",
1793 "$USERPROFILE",
1794 "${USERPROFILE}",
1795 "%USERPROFILE%",
1796 "~",
1797 ]
1798 .into_iter()
1799 .any(|prefix| {
1800 path.strip_prefix(prefix)
1801 .is_some_and(|tail| tail.is_empty() || tail.starts_with(['/', '\\']))
1802 }) {
1803 return Err("use ${homeDir} for the native home directory".into());
1804 }
1805 let placeholder = ["${dataDir}", "${pluginDir}", "${homeDir}"]
1806 .into_iter()
1807 .find(|prefix| path.starts_with(prefix));
1808 let tail = placeholder.and_then(|prefix| path.strip_prefix(prefix));
1809 if path.is_empty()
1810 || path.contains(['\0', '*'])
1811 || tail.is_some_and(|s| !s.is_empty() && !s.starts_with('/'))
1812 || (placeholder.is_none() && path.contains("${"))
1813 || tail.is_some_and(|s| s.contains("${"))
1814 || Path::new(path)
1815 .components()
1816 .any(|p| matches!(p, Component::ParentDir))
1817 {
1818 return Err(
1819 "filesystem roots must use valid host placeholders and contain no traversal".into(),
1820 );
1821 }
1822 Ok(())
1823}
1824
1825pub fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
1831 let path = std::fs::canonicalize(path)?;
1832 #[cfg(windows)]
1833 if let Some(plain) = path.to_str().and_then(without_verbatim_prefix) {
1834 return Ok(PathBuf::from(plain));
1835 }
1836 Ok(path)
1837}
1838
1839#[cfg_attr(not(windows), allow(dead_code))]
1847fn without_verbatim_prefix(path: &str) -> Option<String> {
1848 let rest = path.strip_prefix(r"\\?\")?;
1849 let (plain, tail) = if let Some(unc) = rest.strip_prefix(r"UNC\") {
1850 (format!(r"\\{unc}"), unc)
1851 } else {
1852 let bytes = rest.as_bytes();
1853 if bytes.len() < 3 || !bytes[0].is_ascii_alphabetic() || &bytes[1..3] != b":\\" {
1854 return None;
1855 }
1856 (rest.to_owned(), &rest[3..])
1857 };
1858 if plain.len() >= 260 {
1859 return None;
1860 }
1861 let tail = tail.strip_suffix('\\').unwrap_or(tail);
1863 let device = |name: &str| {
1864 let stem = name.split('.').next().unwrap_or(name).trim_end();
1865 ["CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"]
1866 .iter()
1867 .any(|d| stem.eq_ignore_ascii_case(d))
1868 || (stem.len() == 4
1869 && ["COM", "LPT"]
1870 .iter()
1871 .any(|d| stem[..3].eq_ignore_ascii_case(d))
1872 && matches!(stem.as_bytes()[3], b'1'..=b'9'))
1873 };
1874 let plain_component = |c: &str| {
1875 !c.is_empty()
1876 && c != "."
1877 && c != ".."
1878 && !c.contains('/')
1879 && !c.ends_with(['.', ' '])
1880 && !device(c)
1881 };
1882 (tail.is_empty() || tail.split('\\').all(plain_component)).then_some(plain)
1883}
1884
1885#[derive(Debug, Clone, PartialEq, Eq)]
1889#[non_exhaustive]
1890pub enum FileRefusal {
1891 Invalid(String),
1894 NotGranted(String),
1896}
1897
1898impl std::fmt::Display for FileRefusal {
1899 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1900 match self {
1901 FileRefusal::Invalid(why) | FileRefusal::NotGranted(why) => f.write_str(why),
1902 }
1903 }
1904}
1905
1906fn resolved_path(path: &Path) -> Result<PathBuf, String> {
1907 if !absolute(path) || path.components().any(|p| matches!(p, Component::ParentDir)) {
1908 return Err("filesystem paths must be absolute and contain no parent traversal".into());
1909 }
1910 let mut cursor = path;
1911 let mut tail = Vec::new();
1912 loop {
1913 match std::fs::symlink_metadata(cursor) {
1914 Ok(_) => {
1915 let mut resolved = canonicalize(cursor).map_err(|e| e.to_string())?;
1916 for part in tail.into_iter().rev() {
1917 resolved.push(part);
1918 }
1919 return Ok(resolved);
1920 }
1921 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1922 tail.push(
1923 cursor
1924 .file_name()
1925 .ok_or("invalid filesystem path")?
1926 .to_owned(),
1927 );
1928 cursor = cursor.parent().ok_or("invalid filesystem path")?;
1929 }
1930 Err(e) => return Err(e.to_string()),
1931 }
1932 }
1933}
1934
1935fn object<'a>(value: &'a Value, what: &str) -> Result<&'a Map<String, Value>, String> {
1936 value
1937 .as_object()
1938 .ok_or_else(|| format!("{what} must be an object"))
1939}
1940
1941const WINDOW_KINDS: [(&str, crate::desktop::WindowKind); 5] = [
1942 ("normal", crate::desktop::WindowKind::Normal),
1943 ("dialog", crate::desktop::WindowKind::Dialog),
1944 ("panel", crate::desktop::WindowKind::Panel),
1945 ("popup", crate::desktop::WindowKind::Popup),
1946 ("overlay", crate::desktop::WindowKind::Overlay),
1947];
1948
1949const WINDOW_LEVELS: [(&str, crate::desktop::WindowLevel); 4] = [
1950 ("normal", crate::desktop::WindowLevel::Normal),
1951 ("floating", crate::desktop::WindowLevel::Floating),
1952 ("aboveDock", crate::desktop::WindowLevel::AboveDock),
1953 ("desktopIcon", crate::desktop::WindowLevel::DesktopIcon),
1954];
1955
1956fn window_kind_name(kind: crate::desktop::WindowKind) -> &'static str {
1957 WINDOW_KINDS
1958 .iter()
1959 .find(|(_, k)| *k == kind)
1960 .map_or("normal", |(n, _)| n)
1961}
1962
1963fn window_level_name(level: crate::desktop::WindowLevel) -> &'static str {
1964 WINDOW_LEVELS
1965 .iter()
1966 .find(|(_, l)| *l == level)
1967 .map_or("normal", |(n, _)| n)
1968}
1969
1970fn windows_grant(grant: &Map<String, Value>) -> Result<WindowsGrant, String> {
1972 let mut out = WindowsGrant::default();
1973 if let Some(kinds) = grant.get("kinds") {
1974 for name in strings(kinds, "capabilities.windows.kinds")? {
1975 let Some((_, kind)) = WINDOW_KINDS.iter().find(|(n, _)| *n == name) else {
1976 return Err(format!(
1977 "capabilities.windows.kinds: unknown kind `{name}` (normal, dialog, panel, popup or overlay)"
1978 ));
1979 };
1980 out.kinds.push(*kind);
1981 }
1982 }
1983 if let Some(levels) = grant.get("levels") {
1984 for name in strings(levels, "capabilities.windows.levels")? {
1985 let Some((_, level)) = WINDOW_LEVELS.iter().find(|(n, _)| *n == name) else {
1986 return Err(format!(
1987 "capabilities.windows.levels: unknown level `{name}` (normal, floating, aboveDock or desktopIcon)"
1988 ));
1989 };
1990 out.levels.push(*level);
1991 }
1992 }
1993 if let Some(max) = grant.get("max") {
1994 out.max = Some(
1995 max.as_u64()
1996 .and_then(|m| u32::try_from(m).ok())
1997 .ok_or("capabilities.windows.max must be a whole number")?,
1998 );
1999 }
2000 if let Some(v) = grant.get("overlay") {
2001 out.overlay = v
2002 .as_bool()
2003 .ok_or("capabilities.windows.overlay must be a boolean")?;
2004 }
2005 Ok(out)
2006}
2007
2008fn unknown_key(what: &str, key: &str, known: &[&str]) -> String {
2009 format!("{what}: unknown key `{key}` (known: {})", known.join(", "))
2010}
2011
2012fn strings(value: &Value, what: &str) -> Result<Vec<String>, String> {
2013 value
2014 .as_array()
2015 .and_then(|a| a.iter().map(|v| v.as_str().map(str::to_owned)).collect())
2016 .ok_or_else(|| format!("{what} must be an array of strings"))
2017}
2018
2019fn http_grant(g: &Map<String, Value>) -> Result<HttpGrant, String> {
2023 let what = "capabilities.network.http[]";
2024 let host = g
2025 .get("host")
2026 .and_then(Value::as_str)
2027 .ok_or_else(|| format!("{what} needs a `host`"))?;
2028 let list = |key: &str| -> Result<Vec<String>, String> {
2030 match g.get(key) {
2031 None => Ok(Vec::new()),
2032 Some(Value::String(s)) => Ok(vec![s.clone()]),
2033 Some(v) => strings(v, &format!("{what}.{key}")),
2034 }
2035 };
2036 let methods = list("methods")?
2037 .into_iter()
2038 .map(|m| {
2039 if !m.is_empty() && m.bytes().all(|b| b.is_ascii_alphabetic() || b == b'-') {
2040 Ok(m.to_ascii_uppercase())
2041 } else {
2042 Err(format!("{what}.methods: `{m}` is not an HTTP method"))
2043 }
2044 })
2045 .collect::<Result<Vec<_>, _>>()?;
2046 let mut schemes = Vec::new();
2047 for scheme in list("scheme")?.into_iter().chain(list("schemes")?) {
2048 let scheme = scheme.to_ascii_lowercase();
2049 if !matches!(scheme.as_str(), "http" | "https" | "ws" | "wss") {
2050 return Err(format!(
2051 "{what}.schemes: `{scheme}` is not http, https, ws or wss"
2052 ));
2053 }
2054 if !schemes.contains(&scheme) {
2055 schemes.push(scheme);
2056 }
2057 }
2058 let port = match g.get("port") {
2059 None => None,
2060 Some(v) => Some(
2061 v.as_u64()
2062 .and_then(|p| u16::try_from(p).ok())
2063 .filter(|&p| p != 0)
2064 .ok_or_else(|| format!("{what}.port must be a port from 1 to 65535"))?,
2065 ),
2066 };
2067 let paths = list("paths")?;
2068 let mut path_prefixes = Vec::new();
2069 for prefix in list("pathPrefix")?
2070 .into_iter()
2071 .chain(list("pathPrefixes")?)
2072 .chain(list("path_prefixes")?)
2073 {
2074 if !path_prefixes.contains(&prefix) {
2075 path_prefixes.push(prefix);
2076 }
2077 }
2078 if let Some(bad) = paths
2080 .iter()
2081 .chain(&path_prefixes)
2082 .find(|p| !p.starts_with('/') || p.contains(['*', '?', '#']))
2083 {
2084 return Err(format!(
2085 "{what}: path `{bad}` must start with / and has no `*`, `?` or `#` (paths match as written)"
2086 ));
2087 }
2088 let as_sent = |list: Vec<String>| -> Result<Vec<String>, String> {
2091 let mut sent = Vec::new();
2092 for path in list {
2093 let path = path_as_sent(&path).ok_or_else(|| {
2094 format!("{what}: path `{path}` has a `.` or `..` segment, which no request sends")
2095 })?;
2096 if !sent.contains(&path) {
2097 sent.push(path);
2098 }
2099 }
2100 Ok(sent)
2101 };
2102 let paths = as_sent(paths)?;
2103 let path_prefixes = as_sent(path_prefixes)?;
2104 Ok(HttpGrant {
2105 host: HostPattern::new(host)?,
2106 methods,
2107 schemes,
2108 port,
2109 paths,
2110 path_prefixes,
2111 })
2112}
2113
2114fn patterns(value: &Value, what: &str) -> Result<Vec<HostPattern>, String> {
2115 strings(value, what)?
2116 .iter()
2117 .map(|p| HostPattern::new(p))
2118 .collect()
2119}
2120
2121#[derive(Debug, Clone, PartialEq, Eq)]
2124pub struct Access {
2125 pub declared: Capabilities,
2127 pub granted: Option<Capabilities>,
2129}
2130
2131impl Default for Access {
2132 fn default() -> Self {
2133 Self::all()
2134 }
2135}
2136
2137impl Access {
2138 pub fn all() -> Self {
2140 Self {
2141 declared: Capabilities::all(),
2142 granted: None,
2143 }
2144 }
2145
2146 fn each(&self, f: impl Fn(&Capabilities) -> bool) -> bool {
2147 f(&self.declared) && self.granted.as_ref().is_none_or(f)
2148 }
2149
2150 pub fn is_unrestricted(&self) -> bool {
2153 let all = Capabilities::all();
2154 self.declared == all && self.granted.as_ref().is_none_or(|g| *g == all)
2155 }
2156
2157 pub fn allows_process(&self, command: &str) -> bool {
2160 valid_command(command) && self.each(|c| c.process.execute.iter().any(|p| p == command))
2161 }
2162
2163 pub fn allows_exit(&self) -> bool {
2166 self.each(|caps| caps.process.exit)
2167 }
2168
2169 pub fn allows_env(&self, name: &str) -> bool {
2172 let defaults = include_str!("default-env").lines().filter_map(|line| {
2173 let name = line.split('#').next().unwrap_or_default().trim();
2174 (!name.is_empty()).then_some(name)
2175 });
2176 defaults
2177 .into_iter()
2178 .any(|allowed| env_names_match(allowed, name))
2179 || self.each(|caps| {
2180 caps.process
2181 .env
2182 .iter()
2183 .any(|allowed| env_names_match(allowed, name))
2184 })
2185 }
2186
2187 pub fn authorize_file(
2190 &self,
2191 path: &Path,
2192 data_dir: &Path,
2193 write: bool,
2194 ) -> Result<PathBuf, FileRefusal> {
2195 self.authorize_file_with_paths(path, data_dir, &TrustedPaths::default(), write)
2196 }
2197
2198 pub fn authorize_file_with_paths(
2200 &self,
2201 path: &Path,
2202 data_dir: &Path,
2203 paths: &TrustedPaths,
2204 write: bool,
2205 ) -> Result<PathBuf, FileRefusal> {
2206 let requested = if let Some(text) = path.to_str().filter(|s| s.starts_with("${")) {
2207 paths
2208 .resolve_root(text, data_dir)
2209 .map_err(FileRefusal::Invalid)?
2210 } else {
2211 path.to_owned()
2212 };
2213 let resolved = resolved_path(&requested).map_err(FileRefusal::Invalid)?;
2214 let allowed = self.each(|c| {
2215 let roots = if write { &c.fs.write } else { &c.fs.read };
2216 roots.iter().any(|root| {
2217 paths
2218 .resolve_root(root, data_dir)
2219 .and_then(|r| resolved_path(&r))
2220 .is_ok_and(|root| resolved.starts_with(root))
2221 })
2222 });
2223 if allowed {
2224 Ok(resolved)
2225 } else {
2226 Err(FileRefusal::NotGranted(format!(
2227 "filesystem {} is not granted by capabilities.fs",
2228 if write { "write" } else { "read" }
2229 )))
2230 }
2231 }
2232
2233 pub fn allows_socket(&self, host: &str, port: u16) -> bool {
2237 if host.is_empty() || host.contains(['/', '@', '?', '#', '\0']) {
2238 return false;
2239 }
2240 let host = host.to_ascii_lowercase();
2241 let host = host
2242 .strip_prefix('[')
2243 .and_then(|h| h.strip_suffix(']'))
2244 .unwrap_or(&host)
2245 .trim_end_matches('.');
2246 self.each(|c| {
2247 c.network
2248 .sockets
2249 .iter()
2250 .any(|grant| grant.port == port && grant.host == host)
2251 })
2252 }
2253
2254 pub fn allows_websocket(&self, url: &str) -> bool {
2258 let http = if let Some(rest) = url.strip_prefix("wss:") {
2259 format!("https:{rest}")
2260 } else if let Some(rest) = url.strip_prefix("ws:") {
2261 format!("http:{rest}")
2262 } else {
2263 return false;
2264 };
2265 self.allows_http("GET", &http) || self.allows_http("GET", url)
2266 }
2267
2268 pub fn allows_http(&self, method: &str, url: &str) -> bool {
2271 if url.starts_with("asset:") {
2272 return true;
2273 }
2274 match read_url(url) {
2275 Ok(parts) => {
2277 url::Url::parse(url).is_ok_and(|whatwg| self.allows_parts(method, parts, &whatwg))
2278 }
2279 Err(Unread::Ambiguous(scheme)) => {
2281 self.each(|c| c.allows_http_anywhere(method, &scheme))
2282 }
2283 Err(Unread::NotUrl) => false,
2284 }
2285 }
2286
2287 fn allows_parsed(&self, method: &str, url: &str, whatwg: &url::Url) -> bool {
2292 match read_url(url) {
2293 Ok(parts) => self.allows_parts(method, parts, whatwg),
2294 Err(Unread::Ambiguous(scheme)) => {
2295 self.each(|c| c.allows_http_anywhere(method, &scheme))
2296 }
2297 Err(Unread::NotUrl) => false,
2298 }
2299 }
2300
2301 fn allows_parts(&self, method: &str, parts: UrlParts<'_>, whatwg: &url::Url) -> bool {
2304 let parts = UrlParts {
2305 path: whatwg.path(),
2306 ..parts
2307 };
2308 self.each(|c| c.allows_http(method, &parts))
2309 }
2310
2311 pub fn http_url<'a>(&self, method: &str, url: &'a str) -> Option<Cow<'a, str>> {
2315 if url.starts_with("asset:") {
2316 return Some(Cow::Borrowed(url));
2317 }
2318 let whatwg = url::Url::parse(url).ok()?;
2319 self.allows_parsed(method, whatwg.as_str(), &whatwg)
2320 .then(|| written_or(url, whatwg.into()))
2321 }
2322
2323 pub fn allows_media(&self, uri: &str) -> bool {
2327 self.media_url(uri, None, None).is_some()
2328 }
2329
2330 pub fn media_url<'a>(
2350 &self,
2351 uri: &'a str,
2352 base: Option<&str>,
2353 files: Option<&MediaFiles>,
2354 ) -> Option<Cow<'a, str>> {
2355 if is_own_media(uri) {
2356 let inside = !starts_with_ignoring_case(uri, "asset:") || is_inside_assets(uri);
2359 return (inside || self.is_unrestricted()).then_some(Cow::Borrowed(uri));
2360 }
2361 if self.is_unrestricted() {
2362 return media_as_written(uri, |url| self.allows_http("GET", url))
2363 .then_some(Cow::Borrowed(uri));
2364 }
2365 let file_url = starts_with_ignoring_case(uri, "file:");
2366 if (base.is_none() || file_url)
2367 && let Some(path) = local_file(uri)
2368 {
2369 let real = files?.readable(&path?)?;
2370 let loads = if file_url {
2371 file_url_of(&real)?
2372 } else {
2373 real.into_os_string().into_string().ok()?
2374 };
2375 return Some(written_or(uri, loads));
2376 }
2377 let stripped = whatwg_stripped(uri);
2380 let scheme = scheme_of(&stripped);
2381 let names_host = scheme.is_some()
2382 || stripped.starts_with("//")
2383 || stripped.starts_with(['\\'])
2384 || stripped.starts_with("/\\");
2385 if !names_host {
2386 return (base.is_some() || uri.trim().is_empty()).then_some(Cow::Borrowed(uri));
2390 }
2391 let base = || base.and_then(|b| url::Url::parse(b).ok());
2393 let trimmed = uri.trim_matches(|c: char| c <= ' ');
2399 let head = trimmed.split(['?', '#']).next().unwrap_or(trimmed);
2400 if head.contains('\\')
2401 || trimmed.bytes().any(|b| b.is_ascii_control())
2402 || matches!(read_url(trimmed), Err(Unread::Ambiguous(_)))
2403 {
2404 let scheme = match scheme {
2405 Some(scheme) => scheme.to_ascii_lowercase(),
2406 None => base()?.scheme().to_owned(),
2407 };
2408 return self
2409 .each(|c| c.allows_http_anywhere("GET", &scheme))
2410 .then_some(Cow::Borrowed(uri));
2411 }
2412 let parsed = match scheme {
2413 Some(_) => url::Url::parse(trimmed),
2414 None => base()?.join(trimmed),
2415 }
2416 .ok()?;
2417 self.allows_parsed("GET", parsed.as_str(), &parsed)
2418 .then(|| written_or(uri, parsed.into()))
2419 }
2420
2421 pub fn media_redirect(&self, base: &str, location: &str) -> Result<String, String> {
2427 let url = resolve_reference(base, location);
2428 if !(url.starts_with("http://") || url.starts_with("https://")) {
2429 return Err(format!("redirect to `{url}` is not an http(s) URL"));
2430 }
2431 if !self.is_unrestricted() && !self.allows_media(&url) {
2432 return Err(format!(
2433 "redirect to `{url}` is not granted by capabilities.network"
2434 ));
2435 }
2436 Ok(url)
2437 }
2438
2439 pub fn allows_webviews(&self) -> bool {
2441 self.each(|c| c.webview.is_some())
2442 }
2443
2444 pub fn allows_webview(&self, url: &str) -> bool {
2451 if url == "about:blank" {
2452 return self.allows_webviews();
2453 }
2454 let url = blob_origin(url).unwrap_or(url);
2455 match read_url(url) {
2456 Ok(parts) => self.each(|c| c.allows_webview(&parts)),
2457 Err(Unread::Ambiguous(scheme)) => self.each(|c| c.allows_webview_anywhere(&scheme)),
2458 Err(Unread::NotUrl) => false,
2459 }
2460 }
2461
2462 pub fn allows_webview_with(&self, url: &str, origin: Option<&WebOrigin>) -> bool {
2467 self.allows_webview(url)
2468 || origin.is_some_and(|o| self.allows_runtime_origin() && o.contains(url))
2469 }
2470
2471 pub fn allows_runtime_origin(&self) -> bool {
2475 self.each(|c| c.webview.is_some() && c.webview_runtime_origin)
2476 }
2477
2478 pub fn allows_web_input(&self) -> bool {
2481 self.each(|c| c.webview.is_some() && c.webview_input)
2482 }
2483
2484 pub fn allows_web_media(&self, media: WebMedia) -> bool {
2488 self.each(|c| c.webview.is_some() && c.webview_media.contains(&media))
2489 }
2490
2491 pub fn check_window(
2496 &self,
2497 kind: crate::desktop::WindowKind,
2498 attributes: &crate::desktop::WindowAttributes,
2499 open: usize,
2500 ) -> Result<(), String> {
2501 if !self.each(|c| c.windows.is_some()) {
2502 return Err("windows of the app's own are not granted by capabilities.windows".into());
2503 }
2504 if !self.each(|c| c.windows.as_ref().is_some_and(|w| w.allows_kind(kind))) {
2505 return Err(format!(
2506 "a window of kind `{}` is not granted by capabilities.windows{}",
2507 window_kind_name(kind),
2508 if kind == crate::desktop::WindowKind::Overlay {
2509 " (overlays need `overlay: true`)"
2510 } else {
2511 ""
2512 }
2513 ));
2514 }
2515 if !self.each(|c| {
2516 c.windows
2517 .as_ref()
2518 .is_some_and(|w| w.max.is_none_or(|max| open < max as usize))
2519 }) {
2520 return Err("capabilities.windows.max windows are open already".into());
2521 }
2522 let mut own = attributes.clone();
2523 let level = own.level.take();
2525 let denied = self.deny_window_attributes(&mut own);
2526 if let Some(name) = denied.first() {
2527 return Err(format!(
2528 "the window attribute `{name}` is not granted by capabilities.windows"
2529 ));
2530 }
2531 if let Some(level) = level
2532 && !self.each(|c| c.windows.as_ref().is_some_and(|w| w.allows_level(level)))
2533 {
2534 return Err(format!(
2535 "the window level `{}` is not granted by capabilities.windows.levels",
2536 window_level_name(level)
2537 ));
2538 }
2539 Ok(())
2540 }
2541
2542 pub fn deny_window_attributes(
2548 &self,
2549 attributes: &mut crate::desktop::WindowAttributes,
2550 ) -> Vec<&'static str> {
2551 let mut denied = Vec::new();
2552 let grant = |f: &dyn Fn(&WindowsGrant) -> bool| {
2553 self.each(|c| match &c.windows {
2554 Some(w) => f(w),
2555 None => false,
2557 })
2558 };
2559 if let Some(level) = attributes.level
2560 && level != crate::desktop::WindowLevel::Normal
2561 && !grant(&|w| w.allows_level(level))
2562 {
2563 attributes.level = None;
2564 denied.push("level");
2565 }
2566 if attributes.passes_pointer() && !grant(&|w| w.overlay) {
2567 attributes.pointer_events = None;
2568 denied.push("pointerEvents");
2569 }
2570 denied
2571 }
2572
2573 pub fn allows_status_bar(&self) -> bool {
2575 self.each(|c| c.status_bar)
2576 }
2577
2578 pub fn allows_share(&self) -> bool {
2581 self.each(|c| c.share)
2582 }
2583
2584 pub fn allows_clipboard(&self) -> bool {
2586 self.each(|c| c.clipboard)
2587 }
2588
2589 pub fn allows_picker(&self) -> bool {
2591 self.each(|c| c.picker)
2592 }
2593
2594 pub fn allows_speech(&self) -> bool {
2597 self.each(|c| c.speech)
2598 }
2599
2600 pub fn allows_notifications(&self) -> bool {
2603 self.each(|c| c.notifications)
2604 }
2605
2606 pub fn allows_audio(&self) -> bool {
2608 self.each(|c| c.audio)
2609 }
2610
2611 pub fn allows_application(&self) -> bool {
2616 self.each(|c| c.application)
2617 }
2618
2619 pub fn allows_home_dir(&self) -> bool {
2621 self.each(|c| c.home_dir)
2622 }
2623
2624 pub fn allows_host(&self, name: &str) -> bool {
2626 self.each(|c| c.allows_host(name))
2627 }
2628
2629 pub fn allows_open_url(&self, url: &str) -> bool {
2632 let Some(scheme) = url
2633 .split_once(':')
2634 .map(|(scheme, _)| scheme.to_ascii_lowercase())
2635 else {
2636 return false;
2637 };
2638 self.each(|c| c.open_url.as_ref().is_some_and(|g| g.allows(&scheme)))
2639 }
2640}
2641
2642pub fn resolve_reference(base: &str, location: &str) -> String {
2648 match url::Url::parse(base).and_then(|base| base.join(location)) {
2649 Ok(url) => url.into(),
2650 Err(_) => location.to_owned(),
2651 }
2652}
2653
2654pub fn is_same_origin(a: &str, b: &str) -> bool {
2658 match (url::Url::parse(a), url::Url::parse(b)) {
2659 (Ok(a), Ok(b)) => {
2660 let origin = a.origin();
2661 origin.is_tuple() && origin == b.origin()
2662 }
2663 _ => false,
2664 }
2665}
2666
2667#[cfg(test)]
2668mod tests {
2669 #[test]
2670 fn verbatim_windows_paths_compare_in_their_plain_form() {
2671 use super::without_verbatim_prefix as plain;
2672 assert_eq!(plain(r"\\?\C:\Users\a").as_deref(), Some(r"C:\Users\a"));
2673 assert_eq!(plain(r"\\?\d:\").as_deref(), Some(r"d:\"));
2674 assert_eq!(plain(r"\\?\C:\app\").as_deref(), Some(r"C:\app\"));
2675 assert_eq!(
2676 plain(r"\\?\UNC\server\share\a").as_deref(),
2677 Some(r"\\server\share\a")
2678 );
2679 for path in [
2681 r"C:\a",
2682 r"\\server\share",
2683 "/home/a",
2684 r"\\?\Volume{x}\a",
2685 r"\\.\C:\a",
2686 ] {
2687 assert_eq!(plain(path), None, "{path}");
2688 }
2689 for path in [
2691 r"\\?\C:\a\NUL",
2692 r"\\?\C:\a\com1.txt",
2693 r"\\?\C:\a\Lpt9",
2694 r"\\?\C:\a\b.",
2695 r"\\?\C:\a\b ",
2696 r"\\?\C:\a\..\b",
2697 r"\\?\C:\a\.\b",
2698 r"\\?\C:\a\\b",
2699 r"\\?\C:\a/b",
2700 ] {
2701 assert_eq!(plain(path), None, "{path}");
2702 }
2703 assert_eq!(
2704 plain(r"\\?\C:\a\com10\console").as_deref(),
2705 Some(r"C:\a\com10\console")
2706 );
2707 let long = format!(r"\\?\C:\{}", "a".repeat(260));
2708 assert_eq!(plain(&long), None);
2709 }
2710
2711 #[test]
2712 fn anchored_roots_join_their_tail_component_by_component() {
2713 let app = PathBuf::from(if cfg!(windows) { r"C:\app" } else { "/app" });
2714 let paths = super::TrustedPaths {
2715 plugin_dir: Some(app.clone()),
2716 home_dir: None,
2717 };
2718 let root = paths.resolve_root("${pluginDir}/a//b/", &app).unwrap();
2719 assert_eq!(root, app.join("a").join("b"));
2720 let names = root.components().rev().take(2).collect::<Vec<_>>();
2721 assert_eq!(
2722 names,
2723 [
2724 Component::Normal("b".as_ref()),
2725 Component::Normal("a".as_ref())
2726 ]
2727 );
2728 }
2729 use super::*;
2730
2731 fn caps(json: &str) -> Capabilities {
2732 Capabilities::from_json(&serde_json::from_str(json).unwrap()).unwrap()
2733 }
2734
2735 #[test]
2736 fn windows_are_granted_by_kind_level_and_count() {
2737 use crate::desktop::{WindowAttributes, WindowKind, WindowLevel, WindowPointerEvents};
2738 let none = WindowAttributes::default();
2739 let all = Access::all();
2742 assert!(all.check_window(WindowKind::Panel, &none, 10).is_ok());
2743 assert!(all.check_window(WindowKind::Overlay, &none, 0).is_err());
2744 let click_through = WindowAttributes {
2745 pointer_events: Some(WindowPointerEvents::None),
2746 ..Default::default()
2747 };
2748 assert!(
2749 all.check_window(WindowKind::Normal, &click_through, 0)
2750 .is_err()
2751 );
2752 let declared = |json: &str| Access {
2754 declared: caps(json),
2755 granted: None,
2756 };
2757 assert!(
2758 declared(r#"{"process":{"exit":true}}"#)
2759 .check_window(WindowKind::Normal, &none, 0)
2760 .is_err()
2761 );
2762 let limited = declared(
2763 r#"{"windows":{"kinds":["normal","dialog"],"levels":["normal","floating"],"max":2}}"#,
2764 );
2765 assert!(limited.check_window(WindowKind::Dialog, &none, 1).is_ok());
2766 assert!(limited.check_window(WindowKind::Popup, &none, 0).is_err());
2767 assert!(limited.check_window(WindowKind::Normal, &none, 2).is_err());
2768 let above = WindowAttributes {
2769 level: Some(WindowLevel::AboveDock),
2770 ..Default::default()
2771 };
2772 assert!(limited.check_window(WindowKind::Normal, &above, 0).is_err());
2773 let overlay = declared(r#"{"windows":{"overlay":true}}"#);
2774 assert!(
2775 overlay
2776 .check_window(WindowKind::Overlay, &click_through, 0)
2777 .is_ok()
2778 );
2779 let mut asked = WindowAttributes {
2781 title: Some("Notes".into()),
2782 level: Some(WindowLevel::AboveDock),
2783 ..Default::default()
2784 };
2785 assert_eq!(limited.deny_window_attributes(&mut asked), ["level"]);
2786 assert_eq!(asked.title.as_deref(), Some("Notes"));
2787 assert_eq!(asked.level, None);
2788 }
2789
2790 #[test]
2791 fn environment_names_match_exactly_except_on_windows() {
2792 let access = Access {
2793 declared: caps(r#"{"process":{"env":["MY_TOKEN"]}}"#),
2794 granted: None,
2795 };
2796 assert!(access.allows_env("MY_TOKEN"));
2797 assert_eq!(access.allows_env("my_token"), cfg!(windows));
2798 assert_eq!(super::env_names_match("Path", "PATH"), cfg!(windows));
2799 }
2800
2801 #[test]
2802 fn roots_stay_within_their_anchor_and_bare_commands_have_no_drive() {
2803 let anchor = Path::new(if cfg!(windows) { "C:\\app" } else { "/app" });
2804 assert!(super::within(anchor, Path::new("data/x"), "r").is_ok());
2805 assert!(super::within(anchor, Path::new("/etc"), "r").is_err());
2806 #[cfg(windows)]
2807 for tail in ["C:/Windows", "\\\\srv\\share", "\\Users", "D:x"] {
2808 assert!(
2809 super::within(anchor, Path::new(tail), "r").is_err(),
2810 "{tail}"
2811 );
2812 }
2813 assert!(!super::valid_command("C:git"));
2814 assert!(super::valid_command("git"));
2815 }
2816
2817 #[test]
2818 fn a_manifest_with_absolute_commands_and_roots_parses() {
2819 let declared = caps(
2822 r#"{"process":{"execute":["/bin/sh","/usr/bin/open","git"]},"fs":{"read":["/Applications"]}}"#,
2823 );
2824 assert_eq!(
2825 declared.process.execute,
2826 ["/bin/sh", "/usr/bin/open", "git"]
2827 );
2828 if !cfg!(windows) {
2829 assert!(super::valid_command("/bin/sh"));
2830 assert!(super::absolute(Path::new("/Applications")));
2831 }
2832 }
2833
2834 #[test]
2835 fn system_capabilities_are_explicit_and_intersected() {
2836 let declared = caps(
2837 r#"{"process":{"execute":["claude","codex"]},"fs":{"read":["${dataDir}"],"write":["${dataDir}"]}}"#,
2838 );
2839 assert_eq!(
2840 Capabilities::from_json(&declared.to_json()).unwrap(),
2841 declared
2842 );
2843 let access = Access {
2844 declared,
2845 granted: Some(caps(
2846 r#"{"process":{"execute":["codex"]},"fs":{"read":["${dataDir}/conversations"]}}"#,
2847 )),
2848 };
2849 assert!(access.allows_process("codex"));
2850 assert!(!access.allows_process("claude"));
2851 assert!(!access.allows_process("/usr/bin/codex"));
2852 assert!(!Access::all().allows_process("codex"));
2853 let root = std::env::current_dir().unwrap();
2854 assert!(
2855 access
2856 .authorize_file(&root.join("conversations/new.json"), &root, false)
2857 .is_ok()
2858 );
2859 assert!(
2860 access
2861 .authorize_file(&root.join("other.json"), &root, false)
2862 .is_err()
2863 );
2864 assert!(
2865 access
2866 .authorize_file(&root.join("conversations/new.json"), &root, true)
2867 .is_err()
2868 );
2869 assert!(Access::all().authorize_file(&root, &root, false).is_err());
2870 assert!(
2871 access
2872 .authorize_file(&root.join("../secret"), &root, false)
2873 .is_err()
2874 );
2875 for bad in [
2876 r#"{"process":{"execut":[]}}"#,
2877 r#"{"fs":{"reads":[]}}"#,
2878 r#"{"fs":{"read":["${dataDir}/../outside"]}}"#,
2879 r#"{"process":{"execute":["*"]}}"#,
2880 ] {
2881 assert!(Capabilities::from_json(&serde_json::from_str(bad).unwrap()).is_err());
2882 }
2883 }
2884
2885 #[test]
2886 fn trusted_host_anchors_expand_without_implicit_grants() {
2887 let root = std::env::current_dir().unwrap();
2888 let anchors = TrustedPaths {
2889 plugin_dir: Some(root.clone()),
2890 home_dir: Some(root.join("native-home")),
2891 };
2892 let access = Access {
2893 declared: caps(
2894 r#"{"fs":{"read":["assets","${homeDir}/settings","${pluginDir}/content"]}}"#,
2895 ),
2896 granted: None,
2897 };
2898 for path in ["assets/file", "native-home/settings/file", "content/file"] {
2899 assert!(
2900 access
2901 .authorize_file_with_paths(&root.join(path), &root, &anchors, false)
2902 .is_ok()
2903 );
2904 }
2905 assert!(
2906 access
2907 .authorize_file(&root.join("content/file"), &root, false)
2908 .is_err()
2909 );
2910 assert!(
2911 access
2912 .authorize_file_with_paths(&root.join("other/file"), &root, &anchors, false)
2913 .is_err()
2914 );
2915 assert!(
2916 TrustedPaths::default()
2917 .resolve_root("${homeDir}/settings", &root)
2918 .is_err()
2919 );
2920 assert!(
2921 TrustedPaths::default()
2922 .resolve_root("assets", &root)
2923 .is_err()
2924 );
2925 }
2926
2927 #[test]
2928 fn http_rules_are_one_form_whose_keys_all_narrow() {
2929 let allows = |rule: serde_json::Value, method: &str, url: &str| {
2930 Access {
2931 declared: Capabilities::from_json(&serde_json::json!({"network":{"http":[rule]}}))
2932 .unwrap(),
2933 granted: None,
2934 }
2935 .allows_http(method, url)
2936 };
2937 let plain = serde_json::json!({"host": "api.example.com", "methods": ["GET"]});
2939 assert!(allows(plain.clone(), "GET", "https://api.example.com/"));
2940 assert!(allows(
2941 plain.clone(),
2942 "GET",
2943 "http://api.example.com:8080/any/path"
2944 ));
2945 assert!(!allows(plain.clone(), "POST", "https://api.example.com/"));
2946 assert!(allows(
2947 serde_json::json!({"host": "api.example.com"}),
2948 "PUT",
2949 "https://api.example.com/x"
2950 ));
2951 let scoped = serde_json::json!({
2953 "host": "api.example.com", "methods": ["GET"], "scheme": "https", "port": 443,
2954 "paths": ["/exact"], "pathPrefixes": ["/v1"]
2955 });
2956 assert!(allows(
2957 scoped.clone(),
2958 "GET",
2959 "https://api.example.com/exact?q=1"
2960 ));
2961 assert!(allows(scoped.clone(), "GET", "https://api.example.com/v1"));
2962 assert!(allows(
2963 scoped.clone(),
2964 "GET",
2965 "https://api.example.com/v1/child"
2966 ));
2967 assert!(!allows(
2968 scoped.clone(),
2969 "GET",
2970 "https://api.example.com/v10"
2971 ));
2972 assert!(!allows(
2973 scoped.clone(),
2974 "GET",
2975 "https://api.example.com/exact/more"
2976 ));
2977 assert!(!allows(
2978 scoped.clone(),
2979 "GET",
2980 "http://api.example.com/exact"
2981 ));
2982 assert!(!allows(
2983 scoped.clone(),
2984 "GET",
2985 "https://api.example.com:444/exact"
2986 ));
2987 assert!(allows(scoped, "GET", "https://api.example.com:443/exact"));
2988 let legacy = serde_json::json!({"host": "*.example.com", "schemes": ["https", "wss"], "pathPrefix": "/v1/"});
2990 assert!(allows(
2991 legacy.clone(),
2992 "GET",
2993 "https://quotes.example.com/v1/quote"
2994 ));
2995 assert!(!allows(legacy, "GET", "https://quotes.example.com/v2/"));
2996 let mixed = caps(
2998 r#"{"network":{"http":[{"host":"a.example.com","methods":["get"],"scheme":"https","schemes":["wss","https"],"pathPrefix":"/a","path_prefixes":["/b"],"pathPrefixes":["/a","/c"]}]}}"#,
2999 );
3000 let grant = &mixed.network.http[0];
3001 assert_eq!(grant.methods, ["GET"]);
3002 assert_eq!(grant.schemes, ["https", "wss"]);
3003 assert_eq!(grant.path_prefixes, ["/a", "/c", "/b"]);
3004 assert_eq!(
3005 mixed.to_json()["network"]["http"][0],
3006 serde_json::json!({"host":"a.example.com","methods":["GET"],"schemes":["https","wss"],"pathPrefixes":["/a","/c","/b"]})
3007 );
3008 assert_eq!(Capabilities::from_json(&mixed.to_json()).unwrap(), mixed);
3009 for bad in [
3011 serde_json::json!({"host": "a.example.com", "schemes": ["ftp"]}),
3012 serde_json::json!({"host": "a.example.com", "port": 0}),
3013 serde_json::json!({"host": "a.example.com", "port": 70000}),
3014 serde_json::json!({"host": "a.example.com", "paths": ["relative"]}),
3015 serde_json::json!({"host": "a.example.com", "pathPrefixes": ["/v1/*"]}),
3016 serde_json::json!({"host": "a.example.com", "methods": ["*"]}),
3017 serde_json::json!({"host": "a.example.com", "paths": "/x", "query": true}),
3018 serde_json::json!({"methods": ["GET"]}),
3019 ] {
3020 assert!(
3021 Capabilities::from_json(&serde_json::json!({"network":{"http":[bad.clone()]}}))
3022 .is_err(),
3023 "{bad}"
3024 );
3025 }
3026 }
3027
3028 #[test]
3029 fn exit_and_environment_permissions_intersect() {
3030 let declared = caps(r#"{"process":{"env":["NSH_SECRET","OTHER"],"exit":true}}"#);
3031 assert_eq!(
3032 Capabilities::from_json(&declared.to_json()).unwrap(),
3033 declared
3034 );
3035 let access = Access {
3036 declared,
3037 granted: Some(caps(r#"{"process":{"env":["NSH_SECRET"]}}"#)),
3038 };
3039 assert!(access.allows_env("NSH_SECRET"));
3040 assert!(!access.allows_env("OTHER"));
3041 assert!(!access.allows_exit());
3042 assert!(!Access::all().allows_exit());
3043 assert!(!Access::all().allows_env("NSH_SECRET"));
3044 assert!(Access::all().allows_env("LANG"));
3045 assert_eq!(Access::all().allows_env("lang"), cfg!(windows));
3046 assert!(Access::all().allows_env("TZ"));
3047 for name in [
3049 "HOME",
3050 "USER",
3051 "USERNAME",
3052 "HOSTNAME",
3053 "COMPUTERNAME",
3054 "PATH",
3055 "TMPDIR",
3056 "XDG_RUNTIME_DIR",
3057 "APPDATA",
3058 "http_proxy",
3059 "HTTPS_PROXY",
3060 "ALL_PROXY",
3061 "NO_PROXY",
3062 "DISPLAY",
3063 ] {
3064 assert!(!Access::all().allows_env(name), "{name}");
3065 }
3066 assert!(!Access::all().allows_env("SSH_AUTH_SOCK"));
3067 assert!(!Access::all().allows_env("DBUS_SESSION_BUS_ADDRESS"));
3068 assert!(Capabilities::from_json(&serde_json::json!({"process":{"exit":"true"}})).is_err());
3069 assert!(
3070 Capabilities::from_json(&serde_json::json!({"process":{"env":["BAD=NAME"]}})).is_err()
3071 );
3072 }
3073
3074 #[test]
3075 fn default_environment_entries_are_upper_case_names() {
3076 for line in include_str!("default-env").lines() {
3077 let name = line.split('#').next().unwrap_or_default().trim();
3078 assert!(
3079 name.is_empty()
3080 || name
3081 .chars()
3082 .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'),
3083 "{line}"
3084 );
3085 }
3086 }
3087
3088 #[test]
3089 fn sockets_need_exact_host_and_port_grants() {
3090 let declared = caps(
3091 r#"{"network":{"hosts":["*"],"sockets":["MQTT.example.com:8883","[::1]:9000","127.0.0.1:22"]}}"#,
3092 );
3093 assert_eq!(
3094 Capabilities::from_json(&declared.to_json()).unwrap(),
3095 declared
3096 );
3097 let access = Access {
3098 declared,
3099 granted: None,
3100 };
3101 assert!(access.allows_socket("mqtt.example.com", 8883));
3102 assert!(access.allows_socket("MQTT.example.com.", 8883));
3103 assert!(!access.allows_socket("mqtt.example.com", 1883));
3104 assert!(!access.allows_socket("example.com", 8883));
3105 assert!(!access.allows_socket("a.mqtt.example.com", 8883));
3106 assert!(access.allows_socket("::1", 9000));
3107 assert!(access.allows_socket("[::1]", 9000));
3108 assert!(access.allows_socket("127.0.0.1", 22));
3109 assert!(!access.allows_socket("127.0.0.1", 0));
3110 assert!(!access.allows_socket("localhost", 22));
3112 assert!(!Access::all().allows_socket("127.0.0.1", 22));
3113 assert!(!Access::all().allows_socket("example.com", 443));
3114 let narrowed = Access {
3115 granted: Some(caps(r#"{"network":{"sockets":["127.0.0.1:22"]}}"#)),
3116 ..access
3117 };
3118 assert!(narrowed.allows_socket("127.0.0.1", 22));
3119 assert!(!narrowed.allows_socket("mqtt.example.com", 8883));
3120 for bad in [
3121 "*.example.com:443",
3122 "*:443",
3123 "example.com",
3124 "example.com:0",
3125 "example.com:65536",
3126 "example.com:*",
3127 ":443",
3128 "::1:443",
3129 "[]:443",
3130 "exa mple.com:1",
3131 ] {
3132 assert!(
3133 Capabilities::from_json(&serde_json::json!({"network":{"sockets":[bad]}}))
3134 .unwrap_err()
3135 .contains("invalid socket grant"),
3136 "{bad}"
3137 );
3138 }
3139 }
3140
3141 #[test]
3142 fn websockets_follow_http_grants() {
3143 let access = Access {
3144 declared: caps(
3145 r#"{"network":{"hosts":["ws.example.com"],"http":[
3146 {"host":"chat.example.com","methods":["GET"],"scheme":"https","paths":["/socket"]},
3147 {"host":"legacy.example.com","schemes":["wss"]}
3148 ]}}"#,
3149 ),
3150 granted: None,
3151 };
3152 assert!(access.allows_websocket("ws://ws.example.com:8080/x"));
3153 assert!(access.allows_websocket("wss://chat.example.com/socket"));
3154 assert!(!access.allows_websocket("ws://chat.example.com/socket"));
3155 assert!(!access.allows_websocket("wss://chat.example.com/other"));
3156 assert!(access.allows_websocket("wss://legacy.example.com/"));
3157 assert!(!access.allows_websocket("ws://legacy.example.com/"));
3158 assert!(!access.allows_websocket("https://ws.example.com/"));
3159 assert!(!access.allows_socket("ws.example.com", 8080));
3160 }
3161
3162 #[cfg(unix)]
3163 #[test]
3164 fn filesystem_symlinks_cannot_escape_granted_roots() {
3165 use std::os::unix::fs::symlink;
3166 let base = std::env::var_os("TMPDIR")
3167 .map(PathBuf::from)
3168 .unwrap_or_else(|| {
3169 PathBuf::from(std::env::var_os("HOME").unwrap()).join(".cache/nsh-benchs-test-tmp")
3170 });
3171 let root = base.join(format!("access-policy-{}", std::process::id()));
3172 std::fs::create_dir_all(root.join("allowed")).unwrap();
3173 std::fs::create_dir_all(root.join("outside")).unwrap();
3174 symlink(root.join("outside"), root.join("allowed/link")).unwrap();
3175 let access = Access {
3176 declared: caps(r#"{"fs":{"read":["${dataDir}"],"write":["${dataDir}"]}}"#),
3177 granted: None,
3178 };
3179 for write in [false, true] {
3180 assert!(
3181 access
3182 .authorize_file(
3183 &root.join("allowed/link/missing/file"),
3184 &root.join("allowed"),
3185 write
3186 )
3187 .is_err()
3188 );
3189 assert!(
3190 access
3191 .authorize_file(&root.join("allowed/new/file"), &root.join("allowed"), write)
3192 .is_ok()
3193 );
3194 }
3195 std::fs::remove_dir_all(root).unwrap();
3196 }
3197
3198 #[test]
3199 fn the_share_sheet_is_granted_by_both_sides() {
3200 let declared = caps(r#"{ "share": true }"#);
3201 assert!(declared.share);
3202 assert_eq!(declared.to_json()["share"], serde_json::json!(true));
3203 assert!(
3204 Access {
3205 declared: declared.clone(),
3206 granted: None,
3207 }
3208 .allows_share()
3209 );
3210 assert!(
3212 !Access {
3213 declared,
3214 granted: Some(caps("{}")),
3215 }
3216 .allows_share()
3217 );
3218 assert!(Access::all().allows_share());
3220 assert!(Capabilities::from_json(&serde_json::json!({ "share": "yes" })).is_err());
3221 }
3222
3223 #[test]
3224 fn denies_unless_listed() {
3225 let access = Access {
3226 declared: caps("{}"),
3227 granted: None,
3228 };
3229 assert!(!access.allows_http("GET", "https://example.com/"));
3230 assert!(!access.allows_media("https://example.com/a.png"));
3231 assert!(access.allows_media("asset:/logo.png"));
3232 assert!(!access.allows_media("logo.png"));
3234 assert!(!access.allows_media("/home/a/logo.png"));
3237 assert!(!access.allows_media("file:///home/a/logo.png"));
3238 assert!(access.allows_media("data:image/png;base64,iVBORw0KGgo="));
3239 assert!(!access.allows_webview("https://example.com/"));
3240 assert!(!access.allows_status_bar());
3241 assert!(!access.allows_clipboard());
3242 assert!(!access.allows_picker());
3243 assert!(!access.allows_share());
3244 assert!(!access.allows_speech());
3245 assert!(!access.allows_audio());
3246 assert!(!access.allows_application());
3247 assert!(!access.allows_home_dir());
3248 assert!(!access.allows_host("getUserInfo"));
3249 assert!(Access::all().is_unrestricted());
3250 }
3251
3252 #[test]
3253 fn the_application_and_the_home_directory_are_capabilities() {
3254 let all = Access::all();
3256 assert!(all.allows_application() && all.allows_home_dir());
3257 let access = |declared: &str, granted: Option<&str>| Access {
3259 declared: caps(declared),
3260 granted: granted.map(caps),
3261 };
3262 let listed = access(r#"{ "application": true, "homeDir": true }"#, None);
3263 assert!(listed.allows_application() && listed.allows_home_dir());
3264 let application = access(r#"{ "application": true }"#, None);
3265 assert!(application.allows_application() && !application.allows_home_dir());
3266 let narrowed = access(
3267 r#"{ "application": true, "homeDir": true }"#,
3268 Some(r#"{ "homeDir": true }"#),
3269 );
3270 assert!(!narrowed.allows_application() && narrowed.allows_home_dir());
3271 assert!(!access(r#"{ "application": false }"#, None).allows_application());
3272 assert!(Capabilities::from_json(&serde_json::json!({ "application": "yes" })).is_err());
3273 assert!(Capabilities::from_json(&serde_json::json!({ "homeDir": 1 })).is_err());
3274 let both = caps(r#"{ "application": true, "homeDir": true }"#);
3276 assert_eq!(Capabilities::from_json(&both.to_json()).unwrap(), both);
3277 let none = Capabilities::default().to_json();
3278 assert!(none.get("application").is_none() && none.get("homeDir").is_none());
3279 }
3280
3281 #[test]
3282 fn host_functions_need_an_explicit_grant() {
3283 let all = Access::all();
3286 assert!(all.allows_clipboard());
3287 assert!(!all.allows_host("getUserInfo"));
3288 let access = |json: &str| Access {
3289 declared: caps(json),
3290 granted: None,
3291 };
3292 let every = access(r#"{ "host": true }"#);
3293 assert!(every.allows_host("getUserInfo") && every.allows_host("bridge.call"));
3294 assert!(!access(r#"{ "host": false }"#).allows_host("getUserInfo"));
3295 let listed = access(r#"{ "host": ["getUserInfo", "bridge.*"] }"#);
3296 assert!(listed.allows_host("getUserInfo"));
3297 assert!(listed.allows_host("bridge.share"));
3298 assert!(!listed.allows_host("getUserInfoX"));
3299 assert!(!listed.allows_host("bridge"));
3300 assert!(Capabilities::from_json(&serde_json::json!({ "host": ["a*b"] })).is_err());
3301 assert!(Capabilities::from_json(&serde_json::json!({ "host": [""] })).is_err());
3302 let narrowed = Access {
3304 declared: caps(r#"{ "host": true }"#),
3305 granted: Some(caps(r#"{ "host": ["bridge.*"] }"#)),
3306 };
3307 assert!(narrowed.allows_host("bridge.call") && !narrowed.allows_host("getUserInfo"));
3308 }
3309
3310 #[test]
3311 fn a_runtime_origin_is_exact() {
3312 let o = |s: &str| WebOrigin::parse(s).unwrap();
3313 let lan = o("http://192.168.1.5:9876");
3314 for url in [
3315 "http://192.168.1.5:9876/session-page/T/index.html",
3316 "http://192.168.1.5:9876",
3317 "HTTP://192.168.1.5:9876/x",
3318 "blob:http://192.168.1.5:9876/6f3c2f0e",
3319 ] {
3320 assert!(lan.contains(url), "{url}");
3321 }
3322 for url in [
3323 "http://192.168.1.5:9877/",
3324 "https://192.168.1.5:9876/",
3325 "http://a.192.168.1.5:9876/",
3326 "http://192.168.1.5:9876@evil.com/",
3327 "http://192.168.1.5:9876.evil.com/",
3328 "blob:null/6f3c2f0e",
3329 "file:///etc/passwd",
3330 "javascript:alert(1)",
3331 "data:text/html,hi",
3332 "http://192.168.1.5\\@evil.com:9876/",
3333 ] {
3334 assert!(!lan.contains(url), "{url}");
3335 }
3336 let named = o("https://Name.Example.net:443");
3337 assert_eq!(named.to_string(), "https://name.example.net");
3338 assert!(named.contains("https://name.example.net/x"));
3339 assert!(named.contains("https://NAME.example.net:443/x"));
3340 for url in [
3341 "https://evil.name.example.net/",
3342 "https://name.example.net.evil.com/",
3343 "http://name.example.net/",
3344 ] {
3345 assert!(!named.contains(url), "{url}");
3346 }
3347 assert_eq!(o("http://h:80/").to_string(), "http://h");
3348 assert_eq!(o("http://[::1]:8080").to_string(), "http://[::1]:8080");
3349 for bad in [
3350 "http://h/path",
3351 "http://h?q",
3352 "http://h#f",
3353 "http://u@h",
3354 "*",
3355 "http://*",
3356 "ftp://h",
3357 "h:80",
3358 "http://",
3359 "http://h:99999",
3360 "http://bücher.example",
3361 ] {
3362 assert!(WebOrigin::parse(bad).is_err(), "{bad}");
3363 }
3364 }
3365
3366 #[test]
3367 fn a_runtime_origin_needs_an_explicit_grant() {
3368 let access = |json: &str| Access {
3369 declared: caps(json),
3370 granted: None,
3371 };
3372 let lan = WebOrigin::parse("http://192.168.1.5:9876").unwrap();
3373 let page = "http://192.168.1.5:9876/index.html";
3374 let declared = r#"{ "webview": { "hosts": ["127.0.0.1"], "runtimeOrigin": true } }"#;
3375 assert!(access(declared).allows_runtime_origin());
3376 assert!(access(declared).allows_webview_with(page, Some(&lan)));
3377 assert!(!access(declared).allows_webview_with(page, None));
3378 assert!(access(declared).allows_webview_with("http://127.0.0.1:1/", Some(&lan)));
3379 let hosts = r#"{ "webview": { "hosts": ["127.0.0.1"] } }"#;
3382 assert!(!access(hosts).allows_runtime_origin());
3383 assert!(!access(hosts).allows_webview_with(page, Some(&lan)));
3384 assert!(!Access::all().allows_runtime_origin());
3385 assert!(Access::all().allows_webview_with(page, None));
3386 assert!(
3387 Capabilities::from_json(&serde_json::json!({ "webview": { "runtimeOrigin": 1 } }))
3388 .is_err()
3389 );
3390 assert_eq!(
3392 Capabilities::from_json(&caps(declared).to_json()),
3393 Ok(caps(declared))
3394 );
3395 let narrowed = Access {
3396 declared: caps(declared),
3397 granted: Some(caps(r#"{ "webview": { "hosts": ["*"] } }"#)),
3398 };
3399 assert!(!narrowed.allows_runtime_origin());
3400 }
3401
3402 #[test]
3403 fn trusted_web_input_needs_an_explicit_grant() {
3404 let all = Access::all();
3406 assert!(all.allows_webviews() && !all.allows_web_input());
3407 let access = |json: &str| Access {
3408 declared: caps(json),
3409 granted: None,
3410 };
3411 let input = r#"{ "webview": { "hosts": ["example.com"], "input": true } }"#;
3412 assert!(access(input).allows_web_input());
3413 assert!(!access(r#"{ "webview": { "hosts": ["example.com"] } }"#).allows_web_input());
3414 assert!(!access(r#"{ "webview": { "input": false } }"#).allows_web_input());
3415 assert!(
3416 Capabilities::from_json(&serde_json::json!({ "webview": { "input": "yes" } })).is_err()
3417 );
3418 assert_eq!(
3420 Capabilities::from_json(&caps(input).to_json()),
3421 Ok(caps(input))
3422 );
3423 let narrowed = Access {
3424 declared: caps(input),
3425 granted: Some(caps(r#"{ "webview": { "hosts": ["*"] } }"#)),
3426 };
3427 assert!(!narrowed.allows_web_input());
3428 }
3429
3430 #[test]
3431 fn web_media_needs_an_explicit_grant() {
3432 let all = Access::all();
3433 assert!(!all.allows_web_media(WebMedia::Microphone));
3434 let access = |json: &str| Access {
3435 declared: caps(json),
3436 granted: None,
3437 };
3438 let mic = r#"{ "webview": { "hosts": ["example.com"], "media": ["microphone"] } }"#;
3439 assert!(access(mic).allows_web_media(WebMedia::Microphone));
3440 assert!(!access(mic).allows_web_media(WebMedia::Camera));
3441 assert!(
3442 Capabilities::from_json(&serde_json::json!({ "webview": { "media": ["screen"] } }))
3443 .is_err()
3444 );
3445 assert_eq!(Capabilities::from_json(&caps(mic).to_json()), Ok(caps(mic)));
3446 let narrowed = Access {
3447 declared: caps(mic),
3448 granted: Some(caps(r#"{ "webview": { "hosts": ["*"] } }"#)),
3449 };
3450 assert!(!narrowed.allows_web_media(WebMedia::Microphone));
3451 }
3452
3453 #[test]
3458 fn page_owned_blob_urls_follow_the_origin_they_embed() {
3459 let a = Access {
3460 declared: caps(
3461 r#"{ "webview": { "hosts": ["app.example.com", "*.app.example.com"] } }"#,
3462 ),
3463 granted: None,
3464 };
3465 for url in [
3466 "blob:https://app.example.com/uuid",
3467 "blob:http://app.example.com:6711/uuid",
3468 "blob:https://docs.app.example.com/uuid",
3469 "BLOB:HTTPS://APP.EXAMPLE.COM/uuid",
3470 ] {
3471 assert!(a.allows_webview(url), "{url}");
3472 }
3473 for url in [
3474 "blob:https://bank.example/uuid",
3475 "blob:https://app.example.com.evil.example/uuid",
3476 "blob:https://app.example.com@bank.example/uuid",
3477 "blob:null/uuid",
3478 "blob:data:text/html,hi",
3479 "blob:file:///etc/passwd",
3480 "blob:",
3481 "blob:https://",
3482 ] {
3483 assert!(!a.allows_webview(url), "{url}");
3484 }
3485 let denied = Access {
3487 declared: caps("{}"),
3488 granted: None,
3489 };
3490 assert!(!denied.allows_webview("blob:https://app.example.com/uuid"));
3491 let narrowed = Access {
3493 granted: Some(caps(r#"{ "webview": { "hosts": ["app.example.com"] } }"#)),
3494 ..a.clone()
3495 };
3496 assert!(narrowed.allows_webview("blob:https://app.example.com/uuid"));
3497 assert!(!narrowed.allows_webview("blob:https://docs.app.example.com/uuid"));
3498 let local = Access {
3500 declared: caps(r#"{ "webview": { "hosts": ["127.0.0.1"] } }"#),
3501 granted: None,
3502 };
3503 assert!(
3504 local.allows_webview("blob:http://127.0.0.1:6711/6f3c2f0e-8a1d-4c5e-9b7a-0d2e4f6a8b1c")
3505 );
3506 assert!(a.allows_webview("https://app.example.com/page"));
3509 assert!(!a.allows_webview("https://bank.example/page"));
3510 let ambiguous = "blob:https://app.example.com\\@bank.example/uuid";
3513 assert!(!a.allows_webview(ambiguous));
3514 let any = Access {
3515 declared: caps(r#"{ "webview": { "hosts": ["*"] } }"#),
3516 granted: None,
3517 };
3518 assert!(any.allows_webview(ambiguous));
3519 }
3520
3521 #[test]
3522 fn host_function_names_and_grants_keep_to_their_charset() {
3523 for good in ["getUserInfo", "user.info", "a-b_c:d.E9", &"a".repeat(128)] {
3524 assert!(valid_host_name(good), "{good}");
3525 }
3526 for bad in [
3527 "",
3528 "user.x/../../admin",
3529 "a..b",
3530 "user x",
3531 "a\\b",
3532 "caf\u{e9}",
3533 "ok\u{0}",
3534 "a*",
3535 &"a".repeat(129),
3536 ] {
3537 assert!(!valid_host_name(bad), "{bad:?}");
3538 }
3539 let parses =
3540 |grant: &str| Capabilities::from_json(&serde_json::json!({ "host": [grant] })).is_ok();
3541 assert!(parses("*") && parses("user.*") && parses("user.info"));
3542 for bad in ["user/*", "a..*", "../*", "a b", "**"] {
3543 assert!(!parses(bad), "{bad}");
3544 }
3545 }
3546
3547 #[test]
3548 fn hosts_and_finer_grants() {
3549 let c = caps(
3550 r#"{ "network": {
3551 "hosts": ["*.example.org"],
3552 "http": [{ "host": "api.example.com", "methods": ["get"], "pathPrefix": "/v1/" }]
3553 } }"#,
3554 );
3555 let a = Access {
3556 declared: c,
3557 granted: None,
3558 };
3559 assert!(a.allows_http("POST", "https://api.example.org/x"));
3560 assert!(!a.allows_http("GET", "https://example.org/"));
3561 assert!(!a.allows_http("GET", "https://example.org.evil.io/"));
3562 assert!(!a.allows_http("GET", "https://evilexample.org/"));
3563 assert!(a.allows_http("GET", "https://API.example.com/v1/quote"));
3564 assert!(!a.allows_http("POST", "https://api.example.com/v1/quote"));
3565 assert!(!a.allows_http("GET", "https://api.example.com/v2/"));
3566 assert!(!a.allows_http("GET", "file://api.example.com/v1/"));
3567 assert!(!a.allows_http("GET", "https://api.example.org@evil.io/"));
3569 assert!(a.allows_http("GET", "https://user:pw@api.example.org:8443/"));
3570 }
3571
3572 #[test]
3579 fn urls_that_parsers_read_as_different_hosts_are_refused() {
3580 let hosts = r#"["docs.example.com", "*.docs.example.com"]"#;
3581 let a = Access {
3582 declared: caps(&format!(
3583 r#"{{ "network": {{ "hosts": {hosts} }}, "webview": {{ "hosts": {hosts} }} }}"#
3584 )),
3585 granted: None,
3586 };
3587 for url in [
3588 "https://bank.example\\@docs.example.com/",
3590 "https://bank.example:443\\@docs.example.com/",
3591 "https://[::1]\\@docs.example.com/",
3592 "https://bank.example\\.docs.example.com/",
3594 "https://docs.example.com\\@bank.example/",
3596 "https://docs.example.com/a\\..\\b",
3598 "https://bank.example\0.docs.example.com/",
3600 "https://bank.example\t.docs.example.com/",
3601 "https://bank.example\n.docs.example.com/",
3602 "https://bank.example .docs.example.com/",
3603 "https://bank.example[.docs.example.com/",
3604 "https://x]y.docs.example.com/",
3605 "https://bank%2Eexample.docs.example.com/",
3607 ] {
3608 assert!(!a.allows_webview(url), "{url:?}");
3609 assert!(!a.allows_http("GET", url), "{url:?}");
3610 assert!(!a.allows_media(url), "{url:?}");
3611 }
3612 assert!(!a.allows_websocket("wss://bank.example\\@docs.example.com/"));
3613 for url in [
3616 "https://docs.example.com/a%5Cb",
3617 "https://x.docs.example.com/?q=C:\\x#a\\b",
3618 "https://user:pw@docs.example.com/a b",
3619 ] {
3620 assert!(a.allows_webview(url), "{url:?}");
3621 assert!(a.allows_http("GET", url), "{url:?}");
3622 }
3623 let all = Access {
3625 declared: Capabilities::all(),
3626 granted: None,
3627 };
3628 let query = url::Url::parse("wss://x.example/?q=a\\b").unwrap();
3629 assert!(all.allows_websocket(query.as_str()), "{query}");
3630 assert!(all.allows_media("https://x.example/i.png?p=a\\b"));
3631 }
3632
3633 #[test]
3638 fn only_grants_of_every_host_cover_ambiguous_urls() {
3639 let url = "https://x.example/a\\b.png";
3640 let all = Access {
3641 declared: Capabilities::all(),
3642 granted: None,
3643 };
3644 let any = Access {
3645 declared: caps(r#"{ "network": { "hosts": ["*"] }, "webview": { "hosts": ["*"] } }"#),
3646 granted: None,
3647 };
3648 for a in [&all, &any] {
3649 assert!(a.allows_http("GET", url));
3650 assert!(a.allows_media(url));
3651 assert!(a.allows_webview(url));
3652 assert!(!a.allows_http("GET", "ftp://x.example/a\\b"));
3653 assert!(!a.allows_webview("file://x.example/a\\b"));
3654 assert!(!a.allows_webview("not a url"));
3655 assert!(!a.allows_http("GET", "https://"));
3656 }
3657 let rule = |rule: &str| Access {
3658 declared: caps(&format!(r#"{{ "network": {{ "http": [{rule}] }} }}"#)),
3659 granted: None,
3660 };
3661 let methods = rule(r#"{ "host": "*", "methods": ["get"], "schemes": ["https"] }"#);
3662 assert!(methods.allows_http("GET", url));
3663 assert!(!methods.allows_http("POST", url));
3664 assert!(!methods.allows_http("GET", "http://x.example/a\\b.png"));
3665 for narrowed in [
3666 r#"{ "host": "*", "port": 443 }"#,
3667 r#"{ "host": "*", "pathPrefix": "/a" }"#,
3668 r#"{ "host": "*", "paths": ["/a/b.png"] }"#,
3669 r#"{ "host": "x.example" }"#,
3670 ] {
3671 assert!(!rule(narrowed).allows_http("GET", url), "{narrowed}");
3672 }
3673 }
3674
3675 #[test]
3678 fn granted_urls_are_granted_hosts_for_whatwg() {
3679 let pattern = |p: &str| HostPattern::new(p).unwrap();
3680 let granted = [pattern("docs.example.com"), pattern("*.docs.example.com")];
3681 let a = Access {
3682 declared: caps(
3683 r#"{ "webview": { "hosts": ["docs.example.com", "*.docs.example.com"] } }"#,
3684 ),
3685 granted: None,
3686 };
3687 for url in [
3688 "https://docs.example.com/a",
3689 "https://DOCS.Example.COM/",
3690 "https://docs.example.com./",
3691 "https://x.docs.example.com:8443/",
3692 "https://user:pw@docs.example.com/",
3693 "https://docs.example.com#@bank.example/",
3694 "https://docs.example.com?@bank.example/",
3695 "https://docs.example.com:pass@bank.example/",
3696 "https://docs.example.com%2F@bank.example/",
3697 "https://bank.example\\@docs.example.com/",
3698 "https://bank.example:443\\@docs.example.com/",
3699 "https://[::1]\\@docs.example.com/",
3700 "https://bank.example\\.docs.example.com/",
3701 "https://docs.example.com\\@bank.example/",
3702 "https://bank.example\0.docs.example.com/",
3703 "https://bank.example\t.docs.example.com/",
3704 "https://docs.example.com\n.bank.example/",
3705 "https://bank%2Eexample.docs.example.com/",
3706 "https://docs\u{FF0E}example\u{FF0E}com/",
3707 "https://d\u{043E}cs.example.com/",
3708 "https:\\\\docs.example.com\\",
3709 " https://docs.example.com/",
3710 "https://docs.example.com /",
3711 "https://bank.example .docs.example.com/",
3712 "https://bank.example^.docs.example.com/",
3713 "https://bank.example[.docs.example.com/",
3714 "https://x]y.docs.example.com/",
3715 "https://a@bank.example@docs.example.com/",
3716 "https://..docs.example.com/",
3717 "HTTPS://DOCS.EXAMPLE.COM/",
3718 "https://x.docs.example.com/?q=C:\\x",
3719 ] {
3720 if a.allows_webview(url) {
3721 let whatwg = url::Url::parse(url).unwrap_or_else(|e| panic!("{url:?}: {e}"));
3722 let host = whatwg.host_str().unwrap_or_default().trim_end_matches('.');
3723 assert!(granted.iter().any(|p| p.matches(host)), "{url:?}: {host}");
3724 }
3725 }
3726 }
3727
3728 #[test]
3729 fn the_embedder_grants_at_most() {
3730 let a = Access {
3731 declared: caps(
3732 r#"{ "network": { "hosts": ["a.com", "b.com"] }, "statusBar": true, "clipboard": true, "picker": true, "speech": true, "audio": true }"#,
3733 ),
3734 granted: Some(caps(
3735 r#"{ "network": { "hosts": ["b.com"] }, "clipboard": true }"#,
3736 )),
3737 };
3738 assert!(a.allows_clipboard());
3739 assert!(!a.allows_http("GET", "https://a.com/"));
3740 assert!(!a.allows_picker());
3741 assert!(!a.allows_speech());
3742 assert!(!a.allows_audio());
3743 assert!(a.allows_http("GET", "https://b.com/"));
3744 assert!(!a.allows_status_bar());
3745 }
3746
3747 #[test]
3748 fn typos_are_errors() {
3749 let bad =
3750 |json: &str| Capabilities::from_json(&serde_json::from_str(json).unwrap()).unwrap_err();
3751 assert!(bad(r#"{ "netwrok": {} }"#).contains("unknown key `netwrok`"));
3752 assert!(bad(r#"{ "network": { "host": [] } }"#).contains("unknown key `host`"));
3753 assert!(bad(r#"{ "network": { "hosts": ["exa mple.com"] } }"#).contains("invalid host"));
3754 let c = caps(
3755 r#"{ "network": { "hosts": ["a.com"], "http": [{ "host": "b.com", "methods": ["GET"] }] }, "webview": { "hosts": ["*"] } }"#,
3756 );
3757 assert_eq!(Capabilities::from_json(&c.to_json()).unwrap(), c);
3758 }
3759
3760 #[test]
3763 fn unknown_keys_in_packages_grant_nothing() {
3764 let lenient =
3765 |json: &str| Capabilities::from_json_lenient(&serde_json::from_str(json).unwrap());
3766 let (c, dropped) = lenient(
3767 r#"{ "bluetooth": true, "clipboard": true,
3768 "network": { "hosts": ["a.com"], "http": [
3769 { "host": "b.com", "ports": [443] },
3770 { "host": "c.com", "methods": ["GET"] }
3771 ] } }"#,
3772 )
3773 .unwrap();
3774 assert!(c.clipboard);
3775 assert_eq!(c.network.hosts, [HostPattern::new("a.com").unwrap()]);
3776 assert_eq!(c.network.http.len(), 1);
3777 assert_eq!(c.network.http[0].host.as_str(), "c.com");
3778 assert_eq!(
3779 dropped,
3780 [
3781 "capabilities.bluetooth",
3782 "capabilities.network.http[0] (unknown key `ports`)"
3783 ]
3784 );
3785 let (c, dropped) =
3786 lenient(r#"{ "network": { "hosts": ["a.com"], "ipv6": false }, "webview": { "hosts": ["*"], "x": 1 } }"#)
3787 .unwrap();
3788 assert_eq!(c, Capabilities::default());
3789 assert_eq!(dropped.len(), 2);
3790 let (c, dropped) = lenient(
3794 r#"{ "statusBar": "yes", "clipboard": true,
3795 "network": { "hosts": ["exa mple.com"] }, "webview": { "hosts": ["a.com"] } }"#,
3796 )
3797 .unwrap();
3798 assert!(!c.status_bar);
3799 assert!(c.clipboard);
3800 assert!(c.network.hosts.is_empty());
3801 assert_eq!(c.webview, Some(vec![HostPattern::new("a.com").unwrap()]));
3802 assert_eq!(dropped.len(), 2, "{dropped:?}");
3803 assert!(
3804 dropped
3805 .iter()
3806 .any(|d| d.starts_with("capabilities.statusBar ("))
3807 );
3808 assert!(
3809 dropped
3810 .iter()
3811 .any(|d| d.starts_with("capabilities.network ("))
3812 );
3813 let (c, dropped) = lenient(
3815 r#"{ "network": { "hosts": ["a.com"], "http": [
3816 { "host": "b.com", "port": "any" }, { "host": "c.com" } ] } }"#,
3817 )
3818 .unwrap();
3819 assert_eq!(c.network.hosts.len(), 1);
3820 assert_eq!(c.network.http.len(), 1);
3821 assert_eq!(c.network.http[0].host.as_str(), "c.com");
3822 assert_eq!(dropped.len(), 1, "{dropped:?}");
3823 assert!(dropped[0].starts_with("capabilities.network.http[0] ("));
3824 let (c, dropped) = lenient(r#""everything""#).unwrap();
3826 assert_eq!(c, Capabilities::default());
3827 assert_eq!(dropped.len(), 1);
3828 assert!(Capabilities::from_json(&serde_json::json!({ "statusBar": "yes" })).is_err());
3830 let json = serde_json::json!({ "network": { "hosts": ["a.com"] }, "statusBar": true });
3832 let (c, dropped) = Capabilities::from_json_lenient(&json).unwrap();
3833 assert_eq!(c, Capabilities::from_json(&json).unwrap());
3834 assert!(dropped.is_empty());
3835 }
3836
3837 #[test]
3838 fn media_redirects_are_checked() {
3839 let a = Access {
3840 declared: Capabilities::from_json(
3841 &serde_json::json!({ "network": { "hosts": ["a.com"] } }),
3842 )
3843 .unwrap(),
3844 granted: None,
3845 };
3846 let from = "https://a.com/x/y.png";
3847 assert_eq!(
3848 a.media_redirect(from, "/z.png").unwrap(),
3849 "https://a.com/z.png"
3850 );
3851 assert_eq!(
3852 a.media_redirect(from, "z.png").unwrap(),
3853 "https://a.com/x/z.png"
3854 );
3855 assert!(a.media_redirect(from, "https://b.com/z.png").is_err());
3856 assert!(a.media_redirect(from, "//b.com/z.png").is_err());
3857 assert!(a.media_redirect(from, "file:///etc/passwd").is_err());
3858 assert!(
3859 Access::default()
3860 .media_redirect(from, "//b.com/z.png")
3861 .is_ok()
3862 );
3863 assert!(
3864 Access::default()
3865 .media_redirect(from, "ftp://b.com/z.png")
3866 .is_err()
3867 );
3868 }
3869
3870 #[test]
3874 fn http_paths_are_matched_as_whatwg_resolves_them() {
3875 let a = Access {
3876 declared: caps(
3877 r#"{ "network": { "http": [{ "host": "api.example.com", "pathPrefix": "/public" }] } }"#,
3878 ),
3879 granted: None,
3880 };
3881 for url in [
3882 "https://api.example.com/public/../private",
3883 "https://api.example.com/public/%2e%2e/private",
3884 "https://api.example.com/public/%2E%2E/private",
3885 "https://api.example.com/public/.%2e/private",
3886 "https://api.example.com/public/./../private",
3887 ] {
3888 assert!(!a.allows_http("GET", url), "{url}");
3889 assert!(!a.allows_media(url), "{url}");
3890 }
3891 for url in [
3892 "https://api.example.com/public/x",
3893 "https://api.example.com/private/../public/x",
3894 "https://api.example.com/public/./x",
3895 ] {
3896 assert!(a.allows_http("GET", url), "{url}");
3897 }
3898 }
3899
3900 #[test]
3903 fn redirects_resolve_dot_segments() {
3904 assert_eq!(
3905 resolve_reference("https://api.example.com/public/x", "../private"),
3906 "https://api.example.com/private"
3907 );
3908 assert_eq!(
3909 resolve_reference("https://api.example.com/public/x", "%2e%2e/private"),
3910 "https://api.example.com/private"
3911 );
3912 let a = Access {
3913 declared: caps(
3914 r#"{ "network": { "http": [{ "host": "api.example.com", "pathPrefix": "/public" }] } }"#,
3915 ),
3916 granted: None,
3917 };
3918 let from = "https://api.example.com/public/a.png";
3919 assert!(a.media_redirect(from, "b.png").is_ok());
3920 assert!(a.media_redirect(from, "../private.png").is_err());
3921 assert!(a.media_redirect(from, "/public/../private.png").is_err());
3922 }
3923
3924 #[test]
3928 fn media_sources_that_name_a_host_are_checked() {
3929 let a = Access {
3930 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
3931 granted: None,
3932 };
3933 for uri in [
3934 "//bank.example/x.png",
3935 "\\\\bank.example\\x.png",
3936 "/\\bank.example/x.png",
3937 "https:\\\\bank.example\\x.png",
3938 "https:/bank.example/x.png",
3939 "HTTPS://bank.example/x.png",
3940 ] {
3941 assert!(!a.allows_media(uri), "{uri}");
3942 }
3943 for uri in [
3945 "asset:/a.png",
3946 "data:image/png;base64,AAAA",
3947 "blob:https://app.example/1",
3948 "https://docs.example.com/x.png",
3949 ] {
3950 assert!(a.allows_media(uri), "{uri}");
3951 }
3952 assert!(!a.allows_media("img/a.png"));
3955 assert!(Access::default().allows_media("//bank.example/x.png"));
3957 }
3958
3959 #[test]
3963 fn media_sources_are_read_after_whatwg_strips_them() {
3964 let a = Access {
3965 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
3966 granted: None,
3967 };
3968 let page = Some("https://app.example/index.html");
3969 for uri in [
3970 "\t//bank.example/x.png",
3971 "\n//bank.example/x.png",
3972 "/\t/bank.example/x.png",
3973 " https://bank.example/x.png",
3974 "https://bank.example/x.png ",
3975 "ht\ttps://bank.example/x.png",
3976 "\u{1}https://bank.example/x.png",
3977 ] {
3978 assert_eq!(a.media_url(uri, page, None), None, "{uri:?} on the web");
3979 assert_eq!(
3980 a.media_url(uri, None, None),
3981 None,
3982 "{uri:?} in a native app"
3983 );
3984 }
3985 assert_eq!(
3987 a.media_url(" icons/a.png", page, None),
3988 Some(Cow::Borrowed(" icons/a.png"))
3989 );
3990 let local = Access {
3992 declared: caps(r#"{ "network": { "hosts": ["127.0.0.1"] } }"#),
3993 granted: None,
3994 };
3995 assert_eq!(
3996 local.media_url("http://0x7f.1/a.png", None, None),
3997 Some(Cow::Owned("http://127.0.0.1/a.png".into()))
3998 );
3999 assert_eq!(a.media_url("http://0x7f.1/a.png", None, None), None);
4000 for own in [
4002 "DATA:image/png;base64,AA",
4003 "Asset:/a.png",
4004 "BLOB:https://app.example/1",
4005 ] {
4006 assert_eq!(
4007 a.media_url(own, page, None),
4008 Some(Cow::Borrowed(own)),
4009 "{own}"
4010 );
4011 }
4012 }
4013
4014 #[test]
4020 fn whitespace_around_a_granted_url_loads_its_serialization() {
4021 let a = Access {
4022 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
4023 granted: None,
4024 };
4025 let page = Some("https://app.example/index.html");
4026 for (uri, base) in [
4027 ("https://docs.example.com/x.png ", None),
4028 (" https://docs.example.com/x.png", None),
4029 ("\u{1}https://docs.example.com/x.png", None),
4030 ("\t//docs.example.com/x.png", page),
4031 ] {
4032 assert_eq!(
4033 a.media_url(uri, base, None),
4034 Some(Cow::Owned("https://docs.example.com/x.png".into())),
4035 "{uri:?}"
4036 );
4037 }
4038 assert_eq!(a.media_url("https://bank.example/x.png ", None, None), None);
4041 for inside in [
4042 "https://docs.example.com/x\u{1}.png",
4043 "https://docs.ex\tample.com/x.png",
4044 "ht\ntps://docs.example.com/x.png",
4045 ] {
4046 assert_eq!(a.media_url(inside, None, None), None, "{inside:?}");
4047 }
4048 }
4049
4050 #[test]
4055 fn grant_paths_match_as_requests_send_them() {
4056 let a = Access {
4057 declared: caps(
4058 r#"{ "network": { "http": [
4059 { "host": "cdn.example.com", "pathPrefix": "/my photos" },
4060 { "host": "cdn.example.com", "paths": ["/über.png", "/{id}.png"] }
4061 ] } }"#,
4062 ),
4063 granted: None,
4064 };
4065 for url in [
4066 "https://cdn.example.com/my photos/a.png",
4067 "https://cdn.example.com/my%20photos/a.png",
4068 "https://cdn.example.com/über.png",
4069 "https://cdn.example.com/{id}.png",
4070 ] {
4071 assert!(a.allows_http("GET", url), "{url}");
4072 assert!(a.media_url(url, None, None).is_some(), "{url}");
4073 }
4074 assert!(!a.allows_http("GET", "https://cdn.example.com/my photosx/a.png"));
4075 for bad in [
4078 "/a/../b",
4079 "/./a",
4080 "/a/%2e%2e/b",
4081 "/a/.%2E",
4082 "/public\\..\\private",
4083 "/a/.\t./b",
4084 "/a/.\n/b",
4085 ] {
4086 let json = serde_json::json!({ "network": { "http": [{ "host": "h.example", "pathPrefix": bad }] } });
4087 assert!(Capabilities::from_json(&json).is_err(), "{bad}");
4088 }
4089 }
4090
4091 #[cfg(unix)]
4097 #[test]
4098 fn paths_outside_the_roots_are_refused_without_disk_work() {
4099 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
4100 let root = base.join(format!("media-text-{}", std::process::id()));
4101 let _ = std::fs::remove_dir_all(&root);
4102 std::fs::create_dir_all(root.join("allowed")).unwrap();
4103 std::fs::create_dir_all(root.join("elsewhere")).unwrap();
4104 std::fs::write(root.join("allowed/a.png"), b"png").unwrap();
4105 std::os::unix::fs::symlink(root.join("allowed"), root.join("elsewhere/in")).unwrap();
4107 let allowed = root.join("allowed");
4108 let access = Access {
4109 declared: Capabilities::from_json(
4110 &serde_json::json!({ "fs": { "read": [allowed.to_str().unwrap()] } }),
4111 )
4112 .unwrap(),
4113 granted: None,
4114 };
4115 let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
4116 let resolves = || RESOLVES.with(std::cell::Cell::get);
4117 let before = resolves();
4118 for outside in [
4119 root.join("elsewhere/x.png"),
4120 root.join("elsewhere/in/a.png"),
4121 PathBuf::from("/Volumes/hung/x.png"),
4122 ] {
4123 assert_eq!(files.readable(&outside), None, "{}", outside.display());
4124 }
4125 assert_eq!(
4126 resolves(),
4127 before,
4128 "outside the roots, nothing was resolved"
4129 );
4130 assert!(files.readable(&allowed.join("a.png")).is_some());
4132 assert!(
4133 files
4134 .readable(&canonicalize(&allowed).unwrap().join("a.png"))
4135 .is_some()
4136 );
4137 assert_eq!(resolves(), before + 2);
4138 let _ = std::fs::remove_dir_all(&root);
4139 }
4140
4141 #[cfg(unix)]
4145 #[test]
4146 fn a_granted_file_replaced_by_a_symlink_is_refused() {
4147 use std::os::unix::fs::symlink;
4148 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
4149 let root = base.join(format!("media-swap-{}", std::process::id()));
4150 let _ = std::fs::remove_dir_all(&root);
4151 std::fs::create_dir_all(root.join("allowed")).unwrap();
4152 let root = canonicalize(&root).unwrap();
4153 std::fs::write(root.join("allowed/image.png"), b"public").unwrap();
4154 std::fs::write(root.join("secret.png"), b"secret").unwrap();
4155 let allowed = root.join("allowed").to_str().unwrap().to_owned();
4156 let access = Access {
4157 declared: Capabilities::from_json(
4158 &serde_json::json!({ "fs": { "read": [allowed.clone()] } }),
4159 )
4160 .unwrap(),
4161 granted: None,
4162 };
4163 let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
4164 let src = format!("{allowed}/image.png");
4165 assert!(access.media_url(&src, None, Some(&files)).is_some());
4166 std::fs::remove_file(root.join("allowed/image.png")).unwrap();
4167 symlink(root.join("secret.png"), root.join("allowed/image.png")).unwrap();
4168 assert_eq!(access.media_url(&src, None, Some(&files)), None);
4169 let _ = std::fs::remove_dir_all(&root);
4170 }
4171
4172 #[test]
4177 fn bundled_files_stay_inside_the_app_files() {
4178 let a = Access {
4179 declared: caps(r#"{ "network": { "hosts": ["*"] } }"#),
4180 granted: None,
4181 };
4182 for escape in [
4183 "asset:/../outside.png",
4184 "asset:/sub/../../outside.png",
4185 "asset:/%2E%2e/outside.png",
4186 "asset:/..%2Foutside.png",
4187 "asset:/a%5c..%5c..%5coutside.png",
4188 "asset:/a.png?/../../outside.png",
4189 "asset:/a.png#/../../outside.png",
4190 "asset://Users/a/outside.png",
4191 "asset:/C:/outside.png",
4192 "asset:/./a.png",
4193 "asset:../outside.png",
4194 "ASSET:/../outside.png",
4195 ] {
4196 assert_eq!(a.media_url(escape, None, None), None, "{escape}");
4197 assert_eq!(
4198 a.media_url(escape, Some("https://app.example/"), None),
4199 None,
4200 "{escape} on the web"
4201 );
4202 assert_eq!(media_grant_advice(escape, None), ASSET_ADVICE, "{escape}");
4203 assert_eq!(media_capability(escape, None), "fs", "{escape}");
4204 }
4205 for inside in [
4206 "asset:/a.png",
4207 "asset:/@app/icons/a.png",
4208 "asset:/a.png?v=2",
4209 "asset:/a%20b.png",
4210 "asset:/sub/a..b.png",
4211 "ASSET:/a.png",
4212 ] {
4213 assert_eq!(
4214 a.media_url(inside, None, None),
4215 Some(Cow::Borrowed(inside)),
4216 "{inside}"
4217 );
4218 }
4219 assert_eq!(
4221 Access::default().media_url("asset:/../outside.png", None, None),
4222 Some(Cow::Borrowed("asset:/../outside.png"))
4223 );
4224 }
4225
4226 #[test]
4231 fn relative_paths_name_no_file_in_a_native_app() {
4232 let a = Access {
4233 declared: caps(r#"{ "network": { "hosts": ["*"] } }"#),
4234 granted: None,
4235 };
4236 for relative in [
4237 "clip.mp4",
4238 "./clip.mp4",
4239 "Users/a/secret.mp4",
4240 "../etc/x.png",
4241 " /etc/x.png",
4242 ] {
4243 assert_eq!(a.media_url(relative, None, None), None, "{relative}");
4244 assert_eq!(media_capability(relative, None), "fs", "{relative}");
4245 assert_eq!(
4246 media_grant_advice(relative, None),
4247 RELATIVE_ADVICE,
4248 "{relative}"
4249 );
4250 assert_eq!(
4251 a.media_url(relative, Some("https://app.example/"), None),
4252 Some(Cow::Borrowed(relative)),
4253 "{relative} on the web"
4254 );
4255 assert_eq!(
4256 Access::default().media_url(relative, None, None),
4257 Some(Cow::Borrowed(relative)),
4258 "{relative} without capabilities"
4259 );
4260 }
4261 for empty in ["", " "] {
4263 assert_eq!(a.media_url(empty, None, None), Some(Cow::Borrowed(empty)));
4264 }
4265 }
4266
4267 #[cfg(unix)]
4270 #[test]
4271 fn media_files_open_inside_their_root() {
4272 use std::io::Read;
4273 let base = std::env::temp_dir().join(format!("media-open-{}", std::process::id()));
4274 let _ = std::fs::remove_dir_all(&base);
4275 std::fs::create_dir_all(base.join("allowed")).unwrap();
4276 let base = canonicalize(&base).unwrap();
4277 std::fs::write(base.join("allowed/a.png"), b"public").unwrap();
4278 std::fs::write(base.join("secret.png"), b"secret").unwrap();
4279 let allowed = base.join("allowed");
4280 let access = Access {
4281 declared: Capabilities::from_json(
4282 &serde_json::json!({ "fs": { "read": [allowed.to_str().unwrap()] } }),
4283 )
4284 .unwrap(),
4285 granted: None,
4286 };
4287 let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
4288 let path = allowed.join("a.png");
4289 let read = |path: &Path| {
4290 let mut text = String::new();
4291 files.open(path)?.ok()?.read_to_string(&mut text).ok()?;
4292 Some(text)
4293 };
4294 assert_eq!(read(&path).as_deref(), Some("public"));
4295 std::fs::remove_file(&path).unwrap();
4297 std::os::unix::fs::symlink(base.join("secret.png"), &path).unwrap();
4298 assert!(matches!(files.open(&path), Some(Err(_))));
4299 assert!(matches!(files.open(&base.join("secret.png")), Some(Err(_))));
4300 assert!(MediaFiles::default().open(&path).is_none());
4302 std::fs::create_dir_all(base.join("allowed/sub")).unwrap();
4305 std::fs::write(base.join("allowed/sub/ok.png"), b"ok").unwrap();
4306 std::os::unix::fs::symlink(
4307 base.join("allowed/a.png"),
4308 base.join("allowed/sub/link.png"),
4309 )
4310 .unwrap();
4311 std::fs::remove_file(&path).unwrap();
4312 std::fs::write(&path, b"public").unwrap();
4313 let narrowed = Access {
4314 declared: access.declared.clone(),
4315 granted: Some(
4316 Capabilities::from_json(&serde_json::json!({
4317 "fs": { "read": [allowed.join("sub").to_str().unwrap()] }
4318 }))
4319 .unwrap(),
4320 ),
4321 };
4322 let files = MediaFiles::new(&narrowed, None, &TrustedPaths::default(), true);
4323 let mut text = String::new();
4324 files
4325 .open(&allowed.join("sub/ok.png"))
4326 .unwrap()
4327 .unwrap()
4328 .read_to_string(&mut text)
4329 .unwrap();
4330 assert_eq!(text, "ok");
4331 assert!(matches!(
4332 files.open(&allowed.join("sub/link.png")),
4333 Some(Err(_))
4334 ));
4335 assert!(matches!(files.open(&path), Some(Err(_))));
4336 let localhost = format!("file://localhost{}", allowed.join("sub/link.png").display());
4338 assert_eq!(narrowed.media_url(&localhost, None, Some(&files)), None);
4339 let ok = format!("file://localhost{}", allowed.join("sub/ok.png").display());
4340 assert!(narrowed.media_url(&ok, None, Some(&files)).is_some());
4341 let _ = std::fs::remove_dir_all(&base);
4342 }
4343
4344 #[cfg(unix)]
4348 #[test]
4349 fn a_dangling_symlink_in_a_granted_root_is_refused() {
4350 use std::os::unix::fs::symlink;
4351 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
4352 let root = base.join(format!("media-dangling-{}", std::process::id()));
4353 let _ = std::fs::remove_dir_all(&root);
4354 std::fs::create_dir_all(root.join("allowed")).unwrap();
4355 let root = canonicalize(&root).unwrap();
4356 symlink(root.join("secret.png"), root.join("allowed/link.png")).unwrap();
4357 let allowed = root.join("allowed").to_str().unwrap().to_owned();
4358 let access = Access {
4359 declared: Capabilities::from_json(
4360 &serde_json::json!({ "fs": { "read": [allowed.clone()] } }),
4361 )
4362 .unwrap(),
4363 granted: None,
4364 };
4365 let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
4366 assert_eq!(
4367 access.media_url(&format!("{allowed}/link.png"), None, Some(&files)),
4368 None
4369 );
4370 let missing = format!("{allowed}/later.png");
4372 assert_eq!(
4373 access.media_url(&missing, None, Some(&files)),
4374 Some(Cow::Borrowed(missing.as_str()))
4375 );
4376 let _ = std::fs::remove_dir_all(&root);
4377 }
4378
4379 #[cfg(unix)]
4384 #[test]
4385 fn local_media_files_need_an_fs_read_grant() {
4386 use std::os::unix::fs::symlink;
4387 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
4388 let root = base.join(format!("media-files-{}", std::process::id()));
4389 let _ = std::fs::remove_dir_all(&root);
4390 std::fs::create_dir_all(root.join("allowed")).unwrap();
4391 std::fs::create_dir_all(root.join("outside")).unwrap();
4392 std::fs::write(root.join("allowed/a.png"), b"png").unwrap();
4393 std::fs::write(root.join("outside/b.png"), b"png").unwrap();
4394 symlink(root.join("outside"), root.join("allowed/link")).unwrap();
4395 let root = canonicalize(&root).unwrap();
4397 let data = root.join("allowed");
4398 let access = Access {
4399 declared: caps(
4400 r#"{ "network": { "hosts": ["docs.example.com"] }, "fs": { "read": ["${dataDir}"] } }"#,
4401 ),
4402 granted: None,
4403 };
4404 let files = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), true);
4405 let real = canonicalize(&data).unwrap();
4406 let path = |p: &Path| p.to_str().unwrap().to_owned();
4407 let load = |uri: &str| {
4408 access
4409 .media_url(uri, None, Some(&files))
4410 .map(Cow::into_owned)
4411 };
4412
4413 let granted = path(&real.join("a.png"));
4414 assert_eq!(load(&path(&data.join("a.png"))), Some(granted.clone()));
4415 assert_eq!(
4416 load(&format!("file://{}", path(&data.join("a.png")))),
4417 Some(format!("file://{granted}"))
4418 );
4419 assert_eq!(
4420 load(&format!("FILE://{}", path(&data.join("a.png")))),
4421 Some(format!("file://{granted}"))
4422 );
4423 assert_eq!(load(&path(&data.join("../outside/b.png"))), None);
4425 assert_eq!(
4426 load(&format!("file://{}/%2e%2e/outside/b.png", path(&data))),
4427 None
4428 );
4429 assert_eq!(load(&path(&data.join("link/b.png"))), None);
4430 assert_eq!(load(&path(&root.join("outside/b.png"))), None);
4431 assert_eq!(
4433 access.media_url(&path(&data.join("a.png")), None, None),
4434 None
4435 );
4436 let mobile = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), false);
4437 assert_eq!(
4438 access.media_url(&path(&data.join("a.png")), None, Some(&mobile)),
4439 None
4440 );
4441 let network_only = Access {
4442 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
4443 granted: None,
4444 };
4445 let none = MediaFiles::new(&network_only, Some(&data), &TrustedPaths::default(), true);
4446 assert_eq!(
4447 network_only.media_url(&path(&data.join("a.png")), None, Some(&none)),
4448 None
4449 );
4450 let narrowed = Access {
4452 declared: caps(r#"{ "fs": { "read": ["${dataDir}"] } }"#),
4453 granted: Some(caps(r#"{ "fs": { "read": ["${dataDir}/sub"] } }"#)),
4454 };
4455 let files = MediaFiles::new(&narrowed, Some(&data), &TrustedPaths::default(), true);
4456 assert_eq!(
4457 narrowed.media_url(&path(&data.join("a.png")), None, Some(&files)),
4458 None
4459 );
4460 let page = Some("https://app.example/index.html");
4463 assert_eq!(
4464 access.media_url("/icons/a.png", page, None),
4465 Some(Cow::Borrowed("/icons/a.png"))
4466 );
4467 for local in [
4470 path(&root.join("outside/b.png")),
4471 format!("FILE://{}", path(&root.join("outside/b.png"))),
4472 "C:\\pictures\\x.png".to_owned(),
4473 "/x.png".to_owned(),
4474 ] {
4475 assert_eq!(
4476 Access::default().media_url(&local, None, None),
4477 Some(Cow::Borrowed(local.as_str())),
4478 "{local}"
4479 );
4480 }
4481 let files = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), true);
4483 for _ in 0..2 {
4484 let again = |uri: &str| {
4485 access
4486 .media_url(uri, None, Some(&files))
4487 .map(Cow::into_owned)
4488 };
4489 assert_eq!(again(&path(&data.join("a.png"))), Some(granted.clone()));
4490 assert_eq!(again(&path(&data.join("link/b.png"))), None);
4491 }
4492 let _ = std::fs::remove_dir_all(&root);
4493 }
4494
4495 #[test]
4498 fn every_native_os_has_the_files_the_capability_gates() {
4499 use crate::platform::Os;
4500 for os in [Os::MacOs, Os::Windows, Os::Linux, Os::Ios, Os::Android] {
4501 assert!(native_files(os), "{os:?}");
4502 }
4503 assert!(!native_files(Os::Web));
4504 }
4505
4506 #[cfg(not(target_arch = "wasm32"))]
4509 #[test]
4510 fn file_urls_name_their_decoded_path() {
4511 #[cfg(unix)]
4512 {
4513 assert_eq!(
4514 file_url_path("file:///tmp/a%20b.png"),
4515 Some(PathBuf::from("/tmp/a b.png"))
4516 );
4517 assert_eq!(
4518 file_url_path("file://localhost/tmp/a.png"),
4519 Some(PathBuf::from("/tmp/a.png"))
4520 );
4521 assert_eq!(file_url_path("file://host/tmp/a.png"), None);
4522 }
4523 #[cfg(windows)]
4524 {
4525 assert_eq!(
4530 file_url_path("file:///C:/a%20b.png"),
4531 Some(PathBuf::from("C:\\a b.png"))
4532 );
4533 assert_eq!(
4534 file_url_path("file://localhost/C:/a.png"),
4535 Some(PathBuf::from("C:\\a.png"))
4536 );
4537 assert_eq!(file_url_path("file:///tmp/a.png"), None);
4538 assert_eq!(file_url_path("file://localhost/tmp/a.png"), None);
4539 }
4540 assert_eq!(file_url_path("not a url"), None);
4541 assert_eq!(file_url_path("https://a/b"), None);
4542 }
4543
4544 #[test]
4547 fn refused_media_sources_advise_the_host_they_resolve_to() {
4548 let page = Some("http://localhost:8080/index.html");
4549 assert_eq!(
4551 media_grant_advice("//127.0.0.1:9000/a.png", page),
4552 "add `127.0.0.1` to capabilities.network in nsh.json"
4553 );
4554 assert_eq!(
4556 media_grant_advice("//127.0.0.1:9000/a.png", None),
4557 NO_SCHEME_ADVICE
4558 );
4559 assert_eq!(
4561 media_grant_advice("//127.0.0.1\\a.png", page),
4562 NO_HOST_ADVICE
4563 );
4564 assert_eq!(
4565 media_grant_advice("https://cdn.example.com/a.png", page),
4566 "add `cdn.example.com` to capabilities.network in nsh.json"
4567 );
4568 assert_eq!(
4571 media_grant_advice("/Users/a/x.png", None),
4572 LOCAL_FILE_ADVICE
4573 );
4574 assert_eq!(
4575 media_grant_advice("file:///Users/a/x.png", page),
4576 LOCAL_FILE_ADVICE
4577 );
4578 assert_eq!(media_capability("/Users/a/x.png", None), "fs");
4580 assert_eq!(media_capability("C:\\pictures\\x.png", None), "fs");
4581 assert_eq!(media_capability("FILE:///Users/a/x.png", page), "fs");
4582 assert_eq!(media_capability("/icons/a.png", page), "network");
4583 assert_eq!(
4584 media_capability("https://cdn.example.com/a.png", None),
4585 "network"
4586 );
4587 }
4588
4589 #[test]
4594 fn media_sources_load_the_url_the_check_granted() {
4595 let a = Access {
4596 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
4597 granted: None,
4598 };
4599 let https = Some("https://app.example/index.html");
4600 let http = Some("http://127.0.0.1:8080/");
4601 let loads = |uri, base| a.media_url(uri, base, None).map(|u| u.into_owned());
4602 assert_eq!(
4603 loads("https://DOCS.example.com/a/../x.png", None).as_deref(),
4604 Some("https://docs.example.com/x.png")
4605 );
4606 assert_eq!(
4607 loads("//docs.example.com/x.png", https).as_deref(),
4608 Some("https://docs.example.com/x.png")
4609 );
4610 assert_eq!(
4611 loads("//docs.example.com/x.png", http).as_deref(),
4612 Some("http://docs.example.com/x.png")
4613 );
4614 assert_eq!(loads("\\\\docs.example.com\\x.png", https), None);
4618 assert_eq!(loads("//docs.example.com/x.png", None), None);
4619 assert_eq!(loads("//bank.example/x.png", https), None);
4620 for own in ["asset:/a.png", "img/a.png", "data:image/png;base64,AAAA"] {
4621 assert!(
4622 matches!(a.media_url(own, https, None), Some(std::borrow::Cow::Borrowed(u)) if u == own),
4623 "{own}"
4624 );
4625 }
4626 assert!(matches!(
4628 Access::default().media_url("//bank.example/x.png", None, None),
4629 Some(std::borrow::Cow::Borrowed("//bank.example/x.png"))
4630 ));
4631 }
4632
4633 #[test]
4634 fn opening_urls_is_granted_by_scheme() {
4635 let caps = |json: serde_json::Value| Capabilities::from_json(&json).unwrap();
4636 let access =
4637 |declared: Capabilities, granted: Option<Capabilities>| Access { declared, granted };
4638 let any = access(caps(serde_json::json!({ "openUrl": true })), None);
4639 assert!(any.allows_open_url("https://a.com"));
4640 assert!(any.allows_open_url("tel:+15550100"));
4641 let some = access(
4642 caps(serde_json::json!({ "openUrl": { "schemes": ["HTTPS", "mailto"] } })),
4643 None,
4644 );
4645 assert!(some.allows_open_url("https://a.com"));
4646 assert!(some.allows_open_url("MAILTO:a@b.c"));
4647 assert!(!some.allows_open_url("tel:1"));
4648 let narrowed = access(
4650 caps(serde_json::json!({ "openUrl": true })),
4651 Some(caps(
4652 serde_json::json!({ "openUrl": { "schemes": ["https"] } }),
4653 )),
4654 );
4655 assert!(narrowed.allows_open_url("https://a.com"));
4656 assert!(!narrowed.allows_open_url("mailto:a@b.c"));
4657 let none = access(caps(serde_json::json!({ "openUrl": false })), None);
4658 assert!(!none.allows_open_url("https://a.com"));
4659 assert!(!access(caps(serde_json::json!({})), None).allows_open_url("https://a.com"));
4660 assert!(Access::default().allows_open_url("https://a.com"));
4661 for bad in [
4662 serde_json::json!({ "openUrl": "yes" }),
4663 serde_json::json!({ "openUrl": { "schemes": ["ht tp"] } }),
4664 serde_json::json!({ "openUrl": { "hosts": ["a.com"] } }),
4665 ] {
4666 assert!(Capabilities::from_json(&bad).is_err(), "{bad}");
4667 }
4668 for json in [
4670 serde_json::json!(true),
4671 serde_json::json!(false),
4672 serde_json::json!({ "schemes": ["https"] }),
4673 ] {
4674 let c = caps(serde_json::json!({ "openUrl": json }));
4675 assert_eq!(c.to_json()["openUrl"], json);
4676 }
4677 }
4678}