1use std::{
68 borrow::Cow,
69 path::{Component, Path, PathBuf},
70};
71
72use serde_json::{Map, Value};
73
74#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct HostPattern(String);
78
79impl HostPattern {
80 pub fn new(pattern: &str) -> Result<Self, String> {
82 let p = pattern.trim().to_ascii_lowercase();
83 let host = p.strip_prefix("*.").unwrap_or(&p);
84 let valid = p == "*"
85 || (!host.is_empty()
86 && host.chars().all(|c| {
87 c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | ':' | '[' | ']')
88 }));
89 if valid {
90 Ok(Self(p))
91 } else {
92 Err(format!("invalid host pattern `{pattern}`"))
93 }
94 }
95
96 pub fn matches(&self, host: &str) -> bool {
98 match self.0.strip_prefix("*.") {
99 _ if self.0 == "*" => true,
100 Some(suffix) => {
101 host.len() > suffix.len() + 1 && host.ends_with(suffix) && {
102 let dot = host.len() - suffix.len() - 1;
103 host.as_bytes()[dot] == b'.'
104 }
105 }
106 None => self.0 == host,
107 }
108 }
109
110 pub fn as_str(&self) -> &str {
112 &self.0
113 }
114
115 fn is_any(&self) -> bool {
117 self.0 == "*"
118 }
119}
120
121#[derive(Debug, Clone, PartialEq, Eq)]
124#[non_exhaustive]
125pub struct HttpGrant {
126 pub host: HostPattern,
128 pub methods: Vec<String>,
130 pub schemes: Vec<String>,
132 pub port: Option<u16>,
134 pub paths: Vec<String>,
138 pub path_prefixes: Vec<String>,
142}
143
144impl Default for HttpGrant {
145 fn default() -> Self {
146 Self {
147 host: HostPattern(String::new()),
148 methods: Vec::new(),
149 schemes: Vec::new(),
150 port: None,
151 paths: Vec::new(),
152 path_prefixes: Vec::new(),
153 }
154 }
155}
156
157impl HttpGrant {
158 fn allows(&self, method: &str, url: &UrlParts<'_>) -> bool {
159 let default_port = match url.scheme.as_str() {
160 "https" | "wss" => 443,
161 _ => 80,
162 };
163 let path = url.path.split(['?', '#']).next().unwrap_or("/");
164 let path = if path.is_empty() { "/" } else { path };
165 self.host.matches(&url.host)
166 && (self.methods.is_empty()
167 || self.methods.iter().any(|m| m.eq_ignore_ascii_case(method)))
168 && (self.schemes.is_empty() || self.schemes.contains(&url.scheme))
169 && self
170 .port
171 .is_none_or(|p| url.port.unwrap_or(default_port) == p)
172 && ((self.paths.is_empty() && self.path_prefixes.is_empty())
173 || self.paths.iter().any(|allowed| allowed == path)
174 || self.path_prefixes.iter().any(|prefix| {
175 path.strip_prefix(prefix.as_str()).is_some_and(|tail| {
176 tail.is_empty() || prefix.ends_with('/') || tail.starts_with('/')
177 })
178 }))
179 }
180
181 fn allows_anywhere(&self, method: &str, scheme: &str) -> bool {
184 self.host.is_any()
185 && (self.methods.is_empty()
186 || self.methods.iter().any(|m| m.eq_ignore_ascii_case(method)))
187 && (self.schemes.is_empty() || self.schemes.iter().any(|s| s == scheme))
188 && self.port.is_none()
189 && self.paths.is_empty()
190 && self.path_prefixes.is_empty()
191 }
192}
193
194#[derive(Debug, Clone, PartialEq, Eq, Default)]
196#[non_exhaustive]
197pub struct NetworkGrants {
198 pub hosts: Vec<HostPattern>,
200 pub http: Vec<HttpGrant>,
202 pub sockets: Vec<SocketGrant>,
204}
205
206#[derive(Debug, Clone, PartialEq, Eq)]
210pub struct SocketGrant {
211 host: String,
212 port: u16,
213}
214
215impl SocketGrant {
216 pub fn new(grant: &str) -> Result<Self, String> {
218 let invalid = || {
219 format!(
220 "invalid socket grant `{grant}`: expected an exact `host:port` (`[::1]:port` for IPv6), without wildcards"
221 )
222 };
223 let (host, port) = grant.trim().rsplit_once(':').ok_or_else(invalid)?;
224 let port = port
225 .parse::<u16>()
226 .ok()
227 .filter(|p| *p != 0)
228 .ok_or_else(invalid)?;
229 let host = host.to_ascii_lowercase();
230 let host = match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
231 Some(v6)
232 if !v6.is_empty()
233 && v6
234 .chars()
235 .all(|c| c.is_ascii_hexdigit() || matches!(c, ':' | '.')) =>
236 {
237 v6.to_owned()
238 }
239 Some(_) => return Err(invalid()),
240 None if !host.is_empty()
241 && host
242 .chars()
243 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')) =>
244 {
245 host.trim_end_matches('.').to_owned()
246 }
247 None => return Err(invalid()),
248 };
249 Ok(Self { host, port })
250 }
251
252 pub fn host(&self) -> &str {
254 &self.host
255 }
256
257 pub fn port(&self) -> u16 {
259 self.port
260 }
261
262 pub fn to_string_form(&self) -> String {
264 if self.host.contains(':') {
265 format!("[{}]:{}", self.host, self.port)
266 } else {
267 format!("{}:{}", self.host, self.port)
268 }
269 }
270}
271
272#[derive(Debug, Clone, PartialEq, Eq, Default)]
274#[non_exhaustive]
275pub struct ProcessGrants {
276 pub execute: Vec<String>,
278 pub exit: bool,
280 pub env: Vec<String>,
282}
283
284#[derive(Debug, Clone, PartialEq, Eq, Default)]
287#[non_exhaustive]
288pub struct FileGrants {
289 pub read: Vec<String>,
291 pub write: Vec<String>,
293}
294
295#[derive(Debug, Clone, PartialEq, Eq, Default)]
297#[non_exhaustive]
298pub struct TrustedPaths {
299 pub plugin_dir: Option<PathBuf>,
301 pub home_dir: Option<PathBuf>,
303}
304impl TrustedPaths {
305 pub fn resolve_root(&self, root: &str, data_dir: &Path) -> Result<PathBuf, String> {
308 validate_path_pattern(root)?;
309 for (placeholder, anchor) in [
310 ("${dataDir}", Some(data_dir)),
311 ("${pluginDir}", self.plugin_dir.as_deref()),
312 ("${homeDir}", self.home_dir.as_deref()),
313 ] {
314 if let Some(tail) = root.strip_prefix(placeholder) {
315 let anchor = anchor
316 .filter(|p| absolute(p))
317 .ok_or_else(|| format!("host anchor {placeholder} unavailable"))?;
318 let tail: PathBuf = tail.split('/').filter(|part| !part.is_empty()).collect();
321 return within(anchor, &tail, root);
322 }
323 }
324 let path = PathBuf::from(root);
325 if absolute(&path) {
326 Ok(path)
327 } else {
328 let anchor = self
329 .plugin_dir
330 .as_deref()
331 .filter(|p| absolute(p))
332 .ok_or_else(|| {
333 "host application directory unavailable for relative filesystem root".to_owned()
334 })?;
335 within(anchor, &path, root)
336 }
337 }
338}
339
340pub(crate) fn lexical(path: &Path) -> PathBuf {
342 use std::path::Component;
343 let mut out = PathBuf::new();
344 for part in path.components() {
345 match part {
346 Component::ParentDir => {
347 out.pop();
348 }
349 Component::CurDir => (),
350 other => out.push(other.as_os_str()),
351 }
352 }
353 out
354}
355
356#[cfg(not(target_arch = "wasm32"))]
359pub(crate) fn resolved(path: &Path) -> Result<PathBuf, String> {
360 let mut current = path.to_path_buf();
361 let mut tail = Vec::new();
362 loop {
363 if let Ok(mut real) = canonicalize(¤t) {
364 real.extend(tail.into_iter().rev());
365 return Ok(real);
366 }
367 let name = current
368 .file_name()
369 .ok_or("invalid filesystem path")?
370 .to_owned();
371 if !current.pop() {
372 return Err("invalid filesystem path".into());
373 }
374 tail.push(name);
375 }
376}
377
378pub(crate) fn inside(path: &Path, root: &Path) -> Option<PathBuf> {
381 let mut rest = path.components();
382 for part in root.components() {
383 let next = rest.next()?;
384 let same = if cfg!(windows) {
385 next.as_os_str()
386 .to_string_lossy()
387 .eq_ignore_ascii_case(&part.as_os_str().to_string_lossy())
388 } else {
389 next == part
390 };
391 if !same {
392 return None;
393 }
394 }
395 Some(rest.collect())
396}
397
398#[cfg(not(target_arch = "wasm32"))]
401pub(crate) fn in_root(path: &Path, (expanded, canonical): &(PathBuf, PathBuf)) -> Option<PathBuf> {
402 inside(path, canonical).or_else(|| inside(path, expanded))
403}
404
405pub fn native_files(os: crate::platform::Os) -> bool {
409 cfg!(any(
410 target_os = "linux",
411 target_os = "macos",
412 target_os = "windows"
413 )) && os.is_desktop()
414}
415
416#[derive(Debug, Clone, Default)]
422#[non_exhaustive]
423#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
424pub struct MediaFiles {
425 declared: Vec<(PathBuf, PathBuf)>,
428 granted: Option<Vec<(PathBuf, PathBuf)>>,
430}
431
432impl MediaFiles {
433 pub fn new(
437 access: &Access,
438 data_dir: Option<&Path>,
439 paths: &TrustedPaths,
440 available: bool,
441 ) -> Self {
442 #[cfg(target_arch = "wasm32")]
443 {
444 let _ = (access, data_dir, paths, available);
445 Self::default()
446 }
447 #[cfg(not(target_arch = "wasm32"))]
448 {
449 if !available {
450 return Self::default();
451 }
452 let data = data_dir.map(Path::to_path_buf).unwrap_or_default();
453 let roots = |grants: &Capabilities| {
454 grants
455 .fs
456 .read
457 .iter()
458 .filter_map(|root| {
459 let expanded = lexical(&paths.resolve_root(root, &data).ok()?);
460 let canonical = resolved(&expanded).ok()?;
461 Some((expanded, canonical))
462 })
463 .collect()
464 };
465 Self {
466 declared: roots(&access.declared),
467 granted: access.granted.as_ref().map(roots),
468 }
469 }
470 }
471
472 #[cfg(not(target_arch = "wasm32"))]
478 pub(crate) fn open(&self, path: &Path) -> Option<std::io::Result<std::fs::File>> {
479 if self.declared.is_empty() {
480 return None;
481 }
482 let refused = || std::io::Error::new(std::io::ErrorKind::PermissionDenied, "not granted");
483 let path = lexical(path);
484 if !self
485 .declared
486 .iter()
487 .any(|root| in_root(&path, root).is_some())
488 {
489 return Some(Err(refused()));
490 }
491 let granted: Vec<&(PathBuf, PathBuf)> = match &self.granted {
495 Some(roots) => roots
496 .iter()
497 .filter(|(_, canonical)| {
498 self.declared
499 .iter()
500 .any(|(_, declared)| inside(canonical, declared).is_some())
501 })
502 .collect(),
503 None => self.declared.iter().collect(),
504 };
505 let Some(((_, canonical), relative)) = granted
508 .into_iter()
509 .filter_map(|root| Some((root, in_root(&path, root)?)))
510 .max_by_key(|((_, canonical), _)| canonical.components().count())
511 else {
512 return Some(Err(refused()));
513 };
514 Some((|| {
515 let dir = crate::runtime::fs::confined::open_root(canonical)?;
516 let file = crate::runtime::fs::confined::open_file(&dir, &relative, false)?;
517 Ok(file.into_std())
518 })())
519 }
520
521 fn readable(&self, path: &Path) -> Option<PathBuf> {
526 #[cfg(target_arch = "wasm32")]
527 {
528 let _ = path;
529 None
530 }
531 #[cfg(not(target_arch = "wasm32"))]
532 {
533 if !absolute(path) || self.declared.is_empty() {
534 return None;
535 }
536 let path = lexical(path);
539 let within = |roots: &[(PathBuf, PathBuf)]| {
540 roots.iter().any(|root| in_root(&path, root).is_some())
541 };
542 if !within(&self.declared) || !self.granted.as_deref().is_none_or(within) {
543 return None;
544 }
545 #[cfg(test)]
550 RESOLVES.with(|n| n.set(n.get() + 1));
551 let real = resolved_path(&path).ok()?;
552 let holds = |roots: &[(PathBuf, PathBuf)]| {
553 roots
554 .iter()
555 .any(|(_, canonical)| inside(&real, canonical).is_some())
556 };
557 (holds(&self.declared) && self.granted.as_deref().is_none_or(holds)).then_some(real)
558 }
559 }
560}
561
562#[cfg(test)]
563thread_local! {
564 static RESOLVES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
567}
568
569pub(crate) fn absolute(path: &Path) -> bool {
572 if cfg!(target_arch = "wasm32") {
573 path.has_root()
574 } else {
575 path.is_absolute()
576 }
577}
578
579fn within(anchor: &Path, tail: &Path, root: &str) -> Result<PathBuf, String> {
583 use std::path::Component;
584 let names = tail
585 .components()
586 .all(|c| matches!(c, Component::Normal(_) | Component::CurDir));
587 let mut path = anchor.to_path_buf();
588 path.extend(tail.components().filter(|c| *c != Component::CurDir));
589 if names && path.starts_with(anchor) {
590 Ok(path)
591 } else {
592 Err(format!("filesystem root `{root}` leaves its anchor"))
593 }
594}
595
596pub(crate) fn env_names_match(a: &str, b: &str) -> bool {
600 if cfg!(windows) {
601 a.eq_ignore_ascii_case(b)
602 } else {
603 a == b
604 }
605}
606
607#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
609pub enum WebMedia {
610 Microphone,
612 Camera,
614}
615
616impl WebMedia {
617 pub fn as_str(self) -> &'static str {
619 match self {
620 Self::Microphone => "microphone",
621 Self::Camera => "camera",
622 }
623 }
624}
625
626#[derive(Debug, Clone, PartialEq, Eq, Default)]
630#[non_exhaustive]
631pub struct Capabilities {
632 pub process: ProcessGrants,
634 pub fs: FileGrants,
636 pub network: NetworkGrants,
638 pub webview: Option<Vec<HostPattern>>,
640 pub webview_input: bool,
643 pub webview_media: Vec<WebMedia>,
646 pub status_bar: bool,
648 pub clipboard: bool,
650 pub picker: bool,
653 pub share: bool,
657 pub speech: bool,
661 pub notifications: bool,
664 pub audio: bool,
666 pub application: bool,
670 pub home_dir: bool,
672 pub host: Vec<String>,
676 pub open_url: Option<OpenUrlGrant>,
679 pub windows: Option<WindowsGrant>,
682}
683
684#[derive(Debug, Clone, PartialEq, Eq, Default)]
688#[non_exhaustive]
689pub struct WindowsGrant {
690 pub kinds: Vec<crate::desktop::WindowKind>,
693 pub levels: Vec<crate::desktop::WindowLevel>,
695 pub max: Option<u32>,
698 pub overlay: bool,
700}
701
702impl WindowsGrant {
703 fn allows_kind(&self, kind: crate::desktop::WindowKind) -> bool {
704 use crate::desktop::WindowKind;
705 if kind == WindowKind::Overlay && !self.overlay {
706 return false;
707 }
708 self.kinds.is_empty() || self.kinds.contains(&kind)
709 }
710
711 fn allows_level(&self, level: crate::desktop::WindowLevel) -> bool {
712 self.levels.is_empty() || self.levels.contains(&level)
713 }
714}
715
716#[derive(Debug, Clone, PartialEq, Eq, Default)]
718#[non_exhaustive]
719pub struct OpenUrlGrant {
720 pub schemes: Vec<String>,
723}
724
725impl OpenUrlGrant {
726 pub fn allows(&self, scheme: &str) -> bool {
728 self.schemes.is_empty() || self.schemes.iter().any(|s| s == scheme)
729 }
730}
731
732#[derive(Debug, Clone, PartialEq, Eq)]
734pub struct UrlParts<'a> {
735 pub scheme: String,
737 pub host: String,
739 pub path: &'a str,
741 pub port: Option<u16>,
743}
744
745pub fn parse_url(url: &str) -> Option<UrlParts<'_>> {
750 read_url(url).ok()
751}
752
753pub(crate) fn grant_advice(url: &str, capability: &str) -> String {
757 match parse_url(url) {
758 Some(parts) => format!(
759 "add `{}` to capabilities.{capability} in nsh.json",
760 parts.host
761 ),
762 None => NO_HOST_ADVICE.to_owned(),
763 }
764}
765
766pub(crate) fn media_grant_advice(uri: &str, base: Option<&str>) -> String {
771 if native_relative(uri, base) {
772 return RELATIVE_ADVICE.to_owned();
773 }
774 if starts_with_ignoring_case(uri, "asset:") && !is_inside_assets(uri) {
775 return ASSET_ADVICE.to_owned();
776 }
777 if media_capability(uri, base) == "fs" {
778 return LOCAL_FILE_ADVICE.to_owned();
779 }
780 let unambiguous = !uri.contains('\\') && !uri.bytes().any(|b| b.is_ascii_control());
781 if scheme_of(uri).is_none() && uri.starts_with("//") && unambiguous {
782 let resolved = base
783 .and_then(|base| url::Url::parse(base).ok())
784 .and_then(|base| base.join(uri).ok());
785 return match resolved {
786 Some(url) => grant_advice(url.as_str(), "network"),
787 None => NO_SCHEME_ADVICE.to_owned(),
788 };
789 }
790 grant_advice(uri, "network")
791}
792
793pub(crate) fn media_capability(uri: &str, base: Option<&str>) -> &'static str {
797 if starts_with_ignoring_case(uri, "asset:") || native_relative(uri, base) {
798 return "fs";
799 }
800 let local =
801 (base.is_none() || starts_with_ignoring_case(uri, "file:")) && local_file(uri).is_some();
802 if local { "fs" } else { "network" }
803}
804
805const RELATIVE_ADVICE: &str = "a relative path names no file in a native app: name a bundled file as `asset:/…`, or import it";
807
808const ASSET_ADVICE: &str = "bundled files are named by a path inside the app's files";
811
812const LOCAL_FILE_ADVICE: &str = "a local file is read under capabilities.fs.read in nsh.json: add a root that holds it (desktop apps)";
814
815const NO_SCHEME_ADVICE: &str =
817 "it names no scheme and has no page to take one from: write it as an http(s) URL";
818
819const 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";
821
822fn is_own_media(uri: &str) -> bool {
826 ["asset:", "data:", "blob:"]
827 .iter()
828 .any(|prefix| starts_with_ignoring_case(uri, prefix))
829}
830
831pub fn is_inside_assets(url: &str) -> bool {
841 let Some(path) = url.get(6..).and_then(|rest| rest.strip_prefix('/')) else {
842 return false;
843 };
844 path.split('/').all(|segment| {
845 let bytes = segment.as_bytes();
846 let encoded = |code: &[u8; 3]| bytes.windows(3).any(|w| w.eq_ignore_ascii_case(code));
847 !only_dots(bytes)
848 && !bytes.iter().any(|b| matches!(b, b'\\' | b'\0' | b':'))
849 && ![b"%2f", b"%5c", b"%00", b"%3a"]
850 .iter()
851 .any(|code| encoded(code))
852 })
853}
854
855fn only_dots(segment: &[u8]) -> bool {
858 let (mut dots, mut at) = (0, 0);
859 while at < segment.len() {
860 if segment[at] == b'.' {
861 at += 1;
862 } else if segment[at..].len() >= 3
863 && segment[at] == b'%'
864 && segment[at + 1] == b'2'
865 && segment[at + 2].eq_ignore_ascii_case(&b'e')
866 {
867 at += 3;
868 } else {
869 return false;
870 }
871 dots += 1;
872 if dots > 2 {
873 return false;
874 }
875 }
876 true
877}
878
879fn names_host(uri: &str) -> bool {
882 let stripped = whatwg_stripped(uri);
883 scheme_of(&stripped).is_some()
884 || stripped.starts_with("//")
885 || stripped.starts_with('\\')
886 || stripped.starts_with("/\\")
887}
888
889fn native_relative(uri: &str, base: Option<&str>) -> bool {
892 base.is_none()
893 && !uri.trim().is_empty()
894 && !is_own_media(uri)
895 && local_file(uri).is_none()
896 && !names_host(uri)
897}
898
899fn path_as_sent(path: &str) -> Option<String> {
904 let path: String = path
906 .chars()
907 .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
908 .map(|c| if c == '\\' { '/' } else { c })
909 .collect();
910 let dots = path.split('/').any(|segment| {
911 let segment = segment.to_ascii_lowercase().replace("%2e", ".");
912 segment == "." || segment == ".."
913 });
914 if dots {
915 return None;
916 }
917 let url = url::Url::parse(&format!("http://h{path}")).ok()?;
918 Some(url.path().to_owned())
919}
920
921fn starts_with_ignoring_case(text: &str, prefix: &str) -> bool {
923 text.get(..prefix.len())
924 .is_some_and(|head| head.eq_ignore_ascii_case(prefix))
925}
926
927fn local_file(uri: &str) -> Option<Option<PathBuf>> {
932 if starts_with_ignoring_case(uri, "file:") {
933 return Some(file_url_path(uri));
934 }
935 let drive = matches!(uri.as_bytes(), [d, b':', b'\\' | b'/', ..] if d.is_ascii_alphabetic());
936 let rooted = uri.starts_with('/') && !uri.starts_with("//") && !uri.starts_with("/\\");
937 (drive || rooted).then(|| Some(PathBuf::from(uri)))
938}
939
940fn file_url_path(uri: &str) -> Option<PathBuf> {
942 #[cfg(target_arch = "wasm32")]
943 {
944 let _ = uri;
945 None
946 }
947 #[cfg(not(target_arch = "wasm32"))]
948 {
949 url::Url::parse(uri).ok()?.to_file_path().ok()
950 }
951}
952
953fn file_url_of(path: &Path) -> Option<String> {
955 #[cfg(target_arch = "wasm32")]
956 {
957 let _ = path;
958 None
959 }
960 #[cfg(not(target_arch = "wasm32"))]
961 {
962 url::Url::from_file_path(path).ok().map(String::from)
963 }
964}
965
966fn whatwg_stripped(uri: &str) -> Cow<'_, str> {
969 let trimmed = uri.trim_matches(|c: char| c <= ' ');
970 if trimmed.contains(['\t', '\n', '\r']) {
971 Cow::Owned(trimmed.replace(['\t', '\n', '\r'], ""))
972 } else {
973 Cow::Borrowed(trimmed)
974 }
975}
976
977fn scheme_of(uri: &str) -> Option<&str> {
979 let (scheme, _) = uri.split_once(':')?;
980 let mut chars = scheme.chars();
981 (chars.next()?.is_ascii_alphabetic()
982 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')))
983 .then_some(scheme)
984}
985
986fn media_as_written(uri: &str, allows_http: impl Fn(&str) -> bool) -> bool {
990 !uri.contains("://") || is_own_media(uri) || local_file(uri).is_some() || allows_http(uri)
991}
992
993fn written_or(written: &str, serialized: String) -> Cow<'_, str> {
995 if serialized == written {
996 Cow::Borrowed(written)
997 } else {
998 Cow::Owned(serialized)
999 }
1000}
1001
1002enum Unread {
1004 NotUrl,
1006 Ambiguous(String),
1009}
1010
1011fn read_url(url: &str) -> Result<UrlParts<'_>, Unread> {
1013 let (scheme, rest) = url.split_once("://").ok_or(Unread::NotUrl)?;
1014 if scheme.is_empty()
1015 || !scheme
1016 .chars()
1017 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
1018 {
1019 return Err(Unread::NotUrl);
1020 }
1021 let scheme = scheme.to_ascii_lowercase();
1022 let head = url.split(['?', '#']).next().unwrap_or(url);
1028 if head.contains('\\') || url.bytes().any(|b| b.is_ascii_control()) {
1029 return Err(Unread::Ambiguous(scheme));
1030 }
1031 let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
1032 let (authority, path) = rest.split_at(end);
1033 let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
1035 let host = if let Some(v6) = host_port.strip_prefix('[') {
1036 format!("[{}]", v6.split_once(']').ok_or(Unread::NotUrl)?.0)
1037 } else {
1038 host_port.split(':').next().unwrap_or_default().to_owned()
1039 };
1040 if host.is_empty() {
1041 return Err(Unread::NotUrl);
1042 }
1043 if host.contains(['%', ' ', '<', '>', '^', '|'])
1046 || (!host_port.starts_with('[') && host.contains(['[', ']']))
1047 {
1048 return Err(Unread::Ambiguous(scheme));
1049 }
1050 let port = if host_port.starts_with('[') {
1051 host_port
1052 .split_once(']')
1053 .and_then(|(_, rest)| rest.strip_prefix(':'))
1054 .map(str::parse::<u16>)
1055 .transpose()
1056 } else {
1057 host_port
1058 .split_once(':')
1059 .map(|(_, port)| port.parse::<u16>())
1060 .transpose()
1061 }
1062 .map_err(|_| Unread::NotUrl)?;
1063 Ok(UrlParts {
1064 scheme,
1065 host: host.to_ascii_lowercase().trim_end_matches('.').to_owned(),
1066 path: if path.is_empty() { "/" } else { path },
1067 port,
1068 })
1069}
1070
1071fn blob_origin(url: &str) -> Option<&str> {
1076 url.get(..5)
1077 .is_some_and(|scheme| scheme.eq_ignore_ascii_case("blob:"))
1078 .then(|| &url[5..])
1079 .filter(|origin| !origin.is_empty())
1080}
1081
1082impl Capabilities {
1083 pub fn all() -> Self {
1087 let any = vec![HostPattern("*".into())];
1088 Self {
1089 network: NetworkGrants {
1090 hosts: any.clone(),
1091 http: Vec::new(),
1092 sockets: Vec::new(),
1093 },
1094 webview: Some(any),
1095 status_bar: true,
1096 clipboard: true,
1097 picker: true,
1098 share: true,
1099 speech: true,
1100 notifications: true,
1101 audio: true,
1102 application: true,
1103 home_dir: true,
1104 open_url: Some(OpenUrlGrant::default()),
1105 windows: Some(WindowsGrant::default()),
1107 ..Self::default()
1109 }
1110 }
1111
1112 pub fn from_json(value: &Value) -> Result<Self, String> {
1117 Self::parse(value, None)
1118 }
1119
1120 pub fn from_json_lenient(value: &Value) -> Result<(Self, Vec<String>), String> {
1131 let mut dropped = Vec::new();
1132 let Value::Object(obj) = value else {
1133 dropped.push(format!(
1134 "capabilities ({value} is not an object): all of them"
1135 ));
1136 return Ok((Self::default(), dropped));
1137 };
1138 let mut readable = Map::new();
1140 for (key, v) in obj {
1141 let one = Value::Object(Map::from_iter([(key.clone(), v.clone())]));
1142 let mut its_dropped = Vec::new();
1143 match Self::parse(&one, Some(&mut its_dropped)) {
1144 Ok(_) => {
1145 dropped.append(&mut its_dropped);
1146 readable.insert(key.clone(), v.clone());
1147 }
1148 Err(e) => dropped.push(format!("capabilities.{key} ({e})")),
1149 }
1150 }
1151 let caps = Self::parse(&Value::Object(readable), Some(&mut Vec::new()))?;
1152 Ok((caps, dropped))
1153 }
1154
1155 fn parse(value: &Value, mut dropped: Option<&mut Vec<String>>) -> Result<Self, String> {
1158 const KNOWN: [&str; 16] = [
1159 "windows",
1160 "network",
1161 "webview",
1162 "statusBar",
1163 "clipboard",
1164 "picker",
1165 "share",
1166 "speech",
1167 "notifications",
1168 "audio",
1169 "application",
1170 "homeDir",
1171 "openUrl",
1172 "process",
1173 "fs",
1174 "host",
1175 ];
1176 let obj = object(value, "capabilities")?;
1177 for key in obj.keys().filter(|k| !KNOWN.contains(&k.as_str())) {
1178 match dropped.as_deref_mut() {
1179 Some(dropped) => dropped.push(format!("capabilities.{key}")),
1181 None => return Err(unknown_key("capabilities", key, &KNOWN)),
1182 }
1183 }
1184 let lenient = dropped.is_some();
1185 let mut http_dropped = Vec::new();
1188 let mut check = |obj: &Map<String, Value>,
1191 what: &str,
1192 keys: &[&str],
1193 name: &str|
1194 -> Result<bool, String> {
1195 let Some(key) = obj.keys().find(|k| !keys.contains(&k.as_str())) else {
1196 return Ok(true);
1197 };
1198 match dropped.as_deref_mut() {
1199 Some(dropped) => {
1200 dropped.push(format!("{name} (unknown key `{key}`)"));
1201 Ok(false)
1202 }
1203 None => Err(unknown_key(what, key, keys)),
1204 }
1205 };
1206 let mut caps = Capabilities::default();
1207 if let Some(network) = obj.get("network") {
1208 let network = object(network, "capabilities.network")?;
1209 if check(
1210 network,
1211 "capabilities.network",
1212 &["hosts", "http", "sockets"],
1213 "capabilities.network",
1214 )? {
1215 if let Some(hosts) = network.get("hosts") {
1216 caps.network.hosts = patterns(hosts, "capabilities.network.hosts")?;
1217 }
1218 if let Some(sockets) = network.get("sockets") {
1219 caps.network.sockets = strings(sockets, "capabilities.network.sockets")?
1220 .iter()
1221 .map(|s| SocketGrant::new(s))
1222 .collect::<Result<_, _>>()?;
1223 }
1224 if let Some(http) = network.get("http") {
1225 let list = http
1226 .as_array()
1227 .ok_or("capabilities.network.http must be an array")?;
1228 for (i, grant) in list.iter().enumerate() {
1229 let name = format!("capabilities.network.http[{i}]");
1230 let parsed = object(grant, "capabilities.network.http[]").and_then(|g| {
1231 let keys = [
1232 "host",
1233 "methods",
1234 "scheme",
1235 "schemes",
1236 "port",
1237 "paths",
1238 "pathPrefix",
1239 "pathPrefixes",
1240 "path_prefixes",
1241 ];
1242 Ok(
1243 match check(g, "capabilities.network.http[]", &keys, &name)? {
1244 true => Some(http_grant(g)?),
1245 false => None,
1246 },
1247 )
1248 });
1249 match parsed {
1250 Ok(Some(grant)) => caps.network.http.push(grant),
1251 Ok(None) => {}
1252 Err(e) if lenient => http_dropped.push(format!("{name} ({e})")),
1255 Err(e) => return Err(e),
1256 }
1257 }
1258 }
1259 }
1260 }
1261 if let Some(webview) = obj.get("webview") {
1262 let webview = object(webview, "capabilities.webview")?;
1263 if check(
1264 webview,
1265 "capabilities.webview",
1266 &["hosts", "input", "media"],
1267 "capabilities.webview",
1268 )? {
1269 caps.webview = Some(match webview.get("hosts") {
1270 Some(hosts) => patterns(hosts, "capabilities.webview.hosts")?,
1271 None => Vec::new(),
1272 });
1273 if let Some(input) = webview.get("input") {
1274 caps.webview_input = input
1275 .as_bool()
1276 .ok_or("capabilities.webview.input must be a boolean")?;
1277 }
1278 if let Some(media) = webview.get("media") {
1279 caps.webview_media = strings(media, "capabilities.webview.media")?
1280 .iter()
1281 .map(|kind| match kind.as_str() {
1282 "microphone" => Ok(WebMedia::Microphone),
1283 "camera" => Ok(WebMedia::Camera),
1284 _ => Err(format!(
1285 "capabilities.webview.media takes `microphone` and `camera`, not `{kind}`"
1286 )),
1287 })
1288 .collect::<Result<_, _>>()?;
1289 }
1290 }
1291 }
1292 if let Some(status_bar) = obj.get("statusBar") {
1293 caps.status_bar = status_bar
1294 .as_bool()
1295 .ok_or("capabilities.statusBar must be a boolean")?;
1296 }
1297 if let Some(clipboard) = obj.get("clipboard") {
1298 caps.clipboard = clipboard
1299 .as_bool()
1300 .ok_or("capabilities.clipboard must be a boolean")?;
1301 }
1302 if let Some(picker) = obj.get("picker") {
1303 caps.picker = picker
1304 .as_bool()
1305 .ok_or("capabilities.picker must be a boolean")?;
1306 }
1307 if let Some(share) = obj.get("share") {
1308 caps.share = share
1309 .as_bool()
1310 .ok_or("capabilities.share must be a boolean")?;
1311 }
1312 if let Some(speech) = obj.get("speech") {
1313 caps.speech = speech
1314 .as_bool()
1315 .ok_or("capabilities.speech must be a boolean")?;
1316 }
1317 if let Some(notifications) = obj.get("notifications") {
1318 caps.notifications = notifications
1319 .as_bool()
1320 .ok_or("capabilities.notifications must be a boolean")?;
1321 }
1322 if let Some(audio) = obj.get("audio") {
1323 caps.audio = audio
1324 .as_bool()
1325 .ok_or("capabilities.audio must be a boolean")?;
1326 }
1327 if let Some(application) = obj.get("application") {
1328 caps.application = application
1329 .as_bool()
1330 .ok_or("capabilities.application must be a boolean")?;
1331 }
1332 if let Some(home_dir) = obj.get("homeDir") {
1333 caps.home_dir = home_dir
1334 .as_bool()
1335 .ok_or("capabilities.homeDir must be a boolean")?;
1336 }
1337 if let Some(open_url) = obj.get("openUrl") {
1338 match open_url {
1339 Value::Bool(granted) => {
1340 caps.open_url = granted.then(OpenUrlGrant::default);
1341 }
1342 Value::Object(grant) => {
1343 if check(
1344 grant,
1345 "capabilities.openUrl",
1346 &["schemes"],
1347 "capabilities.openUrl",
1348 )? {
1349 let schemes = match grant.get("schemes") {
1350 Some(schemes) => strings(schemes, "capabilities.openUrl.schemes")?,
1351 None => Vec::new(),
1352 };
1353 if schemes.iter().any(|s| {
1354 s.is_empty()
1355 || !s.starts_with(|c: char| c.is_ascii_alphabetic())
1356 || !s
1357 .chars()
1358 .all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c))
1359 }) {
1360 return Err(
1361 "capabilities.openUrl.schemes needs URL schemes (`https`, `mailto`)"
1362 .into(),
1363 );
1364 }
1365 caps.open_url = Some(OpenUrlGrant {
1366 schemes: schemes.iter().map(|s| s.to_ascii_lowercase()).collect(),
1367 });
1368 }
1369 }
1370 _ => {
1371 return Err(
1372 "capabilities.openUrl must be a boolean or an object of `schemes`".into(),
1373 );
1374 }
1375 }
1376 }
1377 if let Some(process) = obj.get("process") {
1378 let process = object(process, "capabilities.process")?;
1379 if check(
1380 process,
1381 "capabilities.process",
1382 &["execute", "exit", "env"],
1383 "capabilities.process",
1384 )? {
1385 if let Some(execute) = process.get("execute") {
1386 caps.process.execute = strings(execute, "capabilities.process.execute")?;
1387 if caps.process.execute.iter().any(|s| !valid_command(s)) {
1388 return Err("capabilities.process.execute needs exact executable names or absolute paths".into());
1389 }
1390 }
1391 if let Some(exit) = process.get("exit") {
1392 caps.process.exit = exit
1393 .as_bool()
1394 .ok_or("capabilities.process.exit must be a boolean")?;
1395 }
1396 if let Some(env) = process.get("env") {
1397 caps.process.env = strings(env, "capabilities.process.env")?;
1398 if caps
1399 .process
1400 .env
1401 .iter()
1402 .any(|name| name.is_empty() || name.contains(['=', '\0']))
1403 {
1404 return Err(
1405 "capabilities.process.env needs nonempty environment variable names"
1406 .into(),
1407 );
1408 }
1409 }
1410 }
1411 }
1412 if let Some(fs) = obj.get("fs") {
1413 let fs = object(fs, "capabilities.fs")?;
1414 if check(fs, "capabilities.fs", &["read", "write"], "capabilities.fs")? {
1415 for (key, target) in [("read", &mut caps.fs.read), ("write", &mut caps.fs.write)] {
1416 if let Some(value) = fs.get(key) {
1417 *target = strings(value, &format!("capabilities.fs.{key}"))?;
1418 for root in target.iter() {
1419 validate_path_pattern(root)?;
1420 }
1421 }
1422 }
1423 }
1424 }
1425 if let Some(windows) = obj.get("windows") {
1426 match windows {
1427 Value::Bool(granted) => caps.windows = granted.then(WindowsGrant::default),
1428 Value::Object(grant) => {
1429 if check(
1430 grant,
1431 "capabilities.windows",
1432 &["kinds", "levels", "max", "overlay"],
1433 "capabilities.windows",
1434 )? {
1435 caps.windows = Some(windows_grant(grant)?);
1436 }
1437 }
1438 _ => {
1439 return Err(
1440 "capabilities.windows must be a boolean or an object of `kinds`, `levels`, `max` and `overlay`"
1441 .into(),
1442 );
1443 }
1444 }
1445 }
1446 if let Some(host) = obj.get("host") {
1447 caps.host = match host {
1448 Value::Bool(all) => {
1449 if *all {
1450 vec!["*".into()]
1451 } else {
1452 Vec::new()
1453 }
1454 }
1455 _ => {
1456 let names = strings(host, "capabilities.host")
1457 .map_err(|e| format!("{e} (or a boolean)"))?;
1458 if let Some(bad) = names.iter().find(|n| match n.strip_suffix('*') {
1459 Some(prefix) => !prefix.is_empty() && !valid_host_name(prefix),
1460 None => !valid_host_name(n),
1461 }) {
1462 return Err(format!(
1463 "capabilities.host: invalid function `{bad}` (a name of {HOST_NAME_CHARS}, or a prefix of them ending in `*`)"
1464 ));
1465 }
1466 names
1467 }
1468 };
1469 }
1470 if let Some(dropped) = dropped {
1471 dropped.append(&mut http_dropped);
1472 }
1473 Ok(caps)
1474 }
1475
1476 pub fn to_json(&self) -> Value {
1478 let mut obj = self.to_json_without_windows();
1479 if let (Value::Object(obj), Some(w)) = (&mut obj, &self.windows) {
1481 let mut o = Map::new();
1482 if !w.kinds.is_empty() {
1483 o.insert(
1484 "kinds".into(),
1485 w.kinds
1486 .iter()
1487 .map(|k| window_kind_name(*k))
1488 .collect::<Vec<_>>()
1489 .into(),
1490 );
1491 }
1492 if !w.levels.is_empty() {
1493 o.insert(
1494 "levels".into(),
1495 w.levels
1496 .iter()
1497 .map(|l| window_level_name(*l))
1498 .collect::<Vec<_>>()
1499 .into(),
1500 );
1501 }
1502 if let Some(max) = w.max {
1503 o.insert("max".into(), max.into());
1504 }
1505 if w.overlay {
1506 o.insert("overlay".into(), true.into());
1507 }
1508 obj.insert("windows".into(), Value::Object(o));
1509 }
1510 obj
1511 }
1512
1513 fn to_json_without_windows(&self) -> Value {
1514 let list =
1515 |l: &[HostPattern]| Value::from(l.iter().map(|p| p.0.clone()).collect::<Vec<_>>());
1516 let mut network = Map::new();
1517 network.insert("hosts".into(), list(&self.network.hosts));
1518 let http: Vec<Value> = self
1519 .network
1520 .http
1521 .iter()
1522 .map(|g| {
1523 let mut o = Map::new();
1524 o.insert("host".into(), g.host.0.clone().into());
1525 if !g.methods.is_empty() {
1526 o.insert("methods".into(), g.methods.clone().into());
1527 }
1528 if !g.schemes.is_empty() {
1529 o.insert("schemes".into(), g.schemes.clone().into());
1530 }
1531 if let Some(port) = g.port {
1532 o.insert("port".into(), port.into());
1533 }
1534 if !g.paths.is_empty() {
1535 o.insert("paths".into(), g.paths.clone().into());
1536 }
1537 if !g.path_prefixes.is_empty() {
1538 o.insert("pathPrefixes".into(), g.path_prefixes.clone().into());
1539 }
1540 Value::Object(o)
1541 })
1542 .collect();
1543 network.insert("http".into(), http.into());
1544 if !self.network.sockets.is_empty() {
1545 let sockets: Vec<String> = self
1546 .network
1547 .sockets
1548 .iter()
1549 .map(SocketGrant::to_string_form)
1550 .collect();
1551 network.insert("sockets".into(), sockets.into());
1552 }
1553 let mut obj = Map::new();
1554 obj.insert("network".into(), Value::Object(network));
1555 obj.insert(
1556 "process".into(),
1557 serde_json::json!({"execute": self.process.execute, "exit": self.process.exit, "env": self.process.env}),
1558 );
1559 obj.insert(
1560 "fs".into(),
1561 serde_json::json!({"read": self.fs.read, "write": self.fs.write}),
1562 );
1563 if let Some(hosts) = &self.webview {
1564 let mut w = Map::new();
1565 w.insert("hosts".into(), list(hosts));
1566 if self.webview_input {
1568 w.insert("input".into(), true.into());
1569 }
1570 if !self.webview_media.is_empty() {
1571 let media = self.webview_media.iter().map(|m| m.as_str().into());
1572 w.insert("media".into(), Value::Array(media.collect()));
1573 }
1574 obj.insert("webview".into(), Value::Object(w));
1575 }
1576 obj.insert("statusBar".into(), self.status_bar.into());
1577 obj.insert("clipboard".into(), self.clipboard.into());
1578 obj.insert("picker".into(), self.picker.into());
1579 if self.share {
1581 obj.insert("share".into(), true.into());
1582 }
1583 if self.speech {
1584 obj.insert("speech".into(), true.into());
1585 }
1586 if self.notifications {
1587 obj.insert("notifications".into(), true.into());
1588 }
1589 if self.audio {
1590 obj.insert("audio".into(), true.into());
1591 }
1592 if self.application {
1593 obj.insert("application".into(), true.into());
1594 }
1595 if self.home_dir {
1596 obj.insert("homeDir".into(), true.into());
1597 }
1598 if !self.host.is_empty() {
1599 obj.insert("host".into(), self.host.clone().into());
1600 }
1601 obj.insert(
1602 "openUrl".into(),
1603 match &self.open_url {
1604 None => false.into(),
1605 Some(grant) if grant.schemes.is_empty() => true.into(),
1606 Some(grant) => serde_json::json!({ "schemes": grant.schemes }),
1607 },
1608 );
1609 Value::Object(obj)
1610 }
1611
1612 fn allows_http(&self, method: &str, url: &UrlParts<'_>) -> bool {
1613 if !matches!(url.scheme.as_str(), "http" | "https" | "ws" | "wss") {
1614 return false;
1615 }
1616 self.network.hosts.iter().any(|h| h.matches(&url.host))
1617 || self.network.http.iter().any(|g| g.allows(method, url))
1618 }
1619
1620 fn allows_http_anywhere(&self, method: &str, scheme: &str) -> bool {
1622 matches!(scheme, "http" | "https" | "ws" | "wss")
1623 && (self.network.hosts.iter().any(HostPattern::is_any)
1624 || self
1625 .network
1626 .http
1627 .iter()
1628 .any(|g| g.allows_anywhere(method, scheme)))
1629 }
1630
1631 fn allows_host(&self, name: &str) -> bool {
1632 self.host.iter().any(|g| match g.strip_suffix('*') {
1633 Some(prefix) => name.starts_with(prefix),
1634 None => g == name,
1635 })
1636 }
1637
1638 fn allows_webview(&self, url: &UrlParts<'_>) -> bool {
1639 matches!(url.scheme.as_str(), "http" | "https")
1640 && self
1641 .webview
1642 .as_ref()
1643 .is_some_and(|hosts| hosts.iter().any(|h| h.matches(&url.host)))
1644 }
1645
1646 fn allows_webview_anywhere(&self, scheme: &str) -> bool {
1648 matches!(scheme, "http" | "https")
1649 && self
1650 .webview
1651 .as_ref()
1652 .is_some_and(|hosts| hosts.iter().any(HostPattern::is_any))
1653 }
1654}
1655
1656pub const HOST_NAME_CHARS: &str = "1 to 128 of A-Z a-z 0-9 _ . : -, without `..`";
1658
1659pub fn valid_host_name(name: &str) -> bool {
1663 (1..=128).contains(&name.len())
1664 && name
1665 .bytes()
1666 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b':' | b'-'))
1667 && !name.contains("..")
1668}
1669
1670fn valid_command(command: &str) -> bool {
1671 !command.is_empty()
1672 && !command.contains(['\0', '*'])
1673 && (absolute(Path::new(command))
1677 || (!command.contains(['/', '\\', ':']) && command != "." && command != ".."))
1680}
1681
1682fn validate_path_pattern(path: &str) -> Result<(), String> {
1683 if [
1684 "$HOME",
1685 "${HOME}",
1686 "$USERPROFILE",
1687 "${USERPROFILE}",
1688 "%USERPROFILE%",
1689 "~",
1690 ]
1691 .into_iter()
1692 .any(|prefix| {
1693 path.strip_prefix(prefix)
1694 .is_some_and(|tail| tail.is_empty() || tail.starts_with(['/', '\\']))
1695 }) {
1696 return Err("use ${homeDir} for the native home directory".into());
1697 }
1698 let placeholder = ["${dataDir}", "${pluginDir}", "${homeDir}"]
1699 .into_iter()
1700 .find(|prefix| path.starts_with(prefix));
1701 let tail = placeholder.and_then(|prefix| path.strip_prefix(prefix));
1702 if path.is_empty()
1703 || path.contains(['\0', '*'])
1704 || tail.is_some_and(|s| !s.is_empty() && !s.starts_with('/'))
1705 || (placeholder.is_none() && path.contains("${"))
1706 || tail.is_some_and(|s| s.contains("${"))
1707 || Path::new(path)
1708 .components()
1709 .any(|p| matches!(p, Component::ParentDir))
1710 {
1711 return Err(
1712 "filesystem roots must use valid host placeholders and contain no traversal".into(),
1713 );
1714 }
1715 Ok(())
1716}
1717
1718pub fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
1724 let path = std::fs::canonicalize(path)?;
1725 #[cfg(windows)]
1726 if let Some(plain) = path.to_str().and_then(without_verbatim_prefix) {
1727 return Ok(PathBuf::from(plain));
1728 }
1729 Ok(path)
1730}
1731
1732#[cfg_attr(not(windows), allow(dead_code))]
1740fn without_verbatim_prefix(path: &str) -> Option<String> {
1741 let rest = path.strip_prefix(r"\\?\")?;
1742 let (plain, tail) = if let Some(unc) = rest.strip_prefix(r"UNC\") {
1743 (format!(r"\\{unc}"), unc)
1744 } else {
1745 let bytes = rest.as_bytes();
1746 if bytes.len() < 3 || !bytes[0].is_ascii_alphabetic() || &bytes[1..3] != b":\\" {
1747 return None;
1748 }
1749 (rest.to_owned(), &rest[3..])
1750 };
1751 if plain.len() >= 260 {
1752 return None;
1753 }
1754 let tail = tail.strip_suffix('\\').unwrap_or(tail);
1756 let device = |name: &str| {
1757 let stem = name.split('.').next().unwrap_or(name).trim_end();
1758 ["CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"]
1759 .iter()
1760 .any(|d| stem.eq_ignore_ascii_case(d))
1761 || (stem.len() == 4
1762 && ["COM", "LPT"]
1763 .iter()
1764 .any(|d| stem[..3].eq_ignore_ascii_case(d))
1765 && matches!(stem.as_bytes()[3], b'1'..=b'9'))
1766 };
1767 let plain_component = |c: &str| {
1768 !c.is_empty()
1769 && c != "."
1770 && c != ".."
1771 && !c.contains('/')
1772 && !c.ends_with(['.', ' '])
1773 && !device(c)
1774 };
1775 (tail.is_empty() || tail.split('\\').all(plain_component)).then_some(plain)
1776}
1777
1778#[derive(Debug, Clone, PartialEq, Eq)]
1782#[non_exhaustive]
1783pub enum FileRefusal {
1784 Invalid(String),
1787 NotGranted(String),
1789}
1790
1791impl std::fmt::Display for FileRefusal {
1792 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1793 match self {
1794 FileRefusal::Invalid(why) | FileRefusal::NotGranted(why) => f.write_str(why),
1795 }
1796 }
1797}
1798
1799fn resolved_path(path: &Path) -> Result<PathBuf, String> {
1800 if !absolute(path) || path.components().any(|p| matches!(p, Component::ParentDir)) {
1801 return Err("filesystem paths must be absolute and contain no parent traversal".into());
1802 }
1803 let mut cursor = path;
1804 let mut tail = Vec::new();
1805 loop {
1806 match std::fs::symlink_metadata(cursor) {
1807 Ok(_) => {
1808 let mut resolved = canonicalize(cursor).map_err(|e| e.to_string())?;
1809 for part in tail.into_iter().rev() {
1810 resolved.push(part);
1811 }
1812 return Ok(resolved);
1813 }
1814 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1815 tail.push(
1816 cursor
1817 .file_name()
1818 .ok_or("invalid filesystem path")?
1819 .to_owned(),
1820 );
1821 cursor = cursor.parent().ok_or("invalid filesystem path")?;
1822 }
1823 Err(e) => return Err(e.to_string()),
1824 }
1825 }
1826}
1827
1828fn object<'a>(value: &'a Value, what: &str) -> Result<&'a Map<String, Value>, String> {
1829 value
1830 .as_object()
1831 .ok_or_else(|| format!("{what} must be an object"))
1832}
1833
1834const WINDOW_KINDS: [(&str, crate::desktop::WindowKind); 5] = [
1835 ("normal", crate::desktop::WindowKind::Normal),
1836 ("dialog", crate::desktop::WindowKind::Dialog),
1837 ("panel", crate::desktop::WindowKind::Panel),
1838 ("popup", crate::desktop::WindowKind::Popup),
1839 ("overlay", crate::desktop::WindowKind::Overlay),
1840];
1841
1842const WINDOW_LEVELS: [(&str, crate::desktop::WindowLevel); 4] = [
1843 ("normal", crate::desktop::WindowLevel::Normal),
1844 ("floating", crate::desktop::WindowLevel::Floating),
1845 ("aboveDock", crate::desktop::WindowLevel::AboveDock),
1846 ("desktopIcon", crate::desktop::WindowLevel::DesktopIcon),
1847];
1848
1849fn window_kind_name(kind: crate::desktop::WindowKind) -> &'static str {
1850 WINDOW_KINDS
1851 .iter()
1852 .find(|(_, k)| *k == kind)
1853 .map_or("normal", |(n, _)| n)
1854}
1855
1856fn window_level_name(level: crate::desktop::WindowLevel) -> &'static str {
1857 WINDOW_LEVELS
1858 .iter()
1859 .find(|(_, l)| *l == level)
1860 .map_or("normal", |(n, _)| n)
1861}
1862
1863fn windows_grant(grant: &Map<String, Value>) -> Result<WindowsGrant, String> {
1865 let mut out = WindowsGrant::default();
1866 if let Some(kinds) = grant.get("kinds") {
1867 for name in strings(kinds, "capabilities.windows.kinds")? {
1868 let Some((_, kind)) = WINDOW_KINDS.iter().find(|(n, _)| *n == name) else {
1869 return Err(format!(
1870 "capabilities.windows.kinds: unknown kind `{name}` (normal, dialog, panel, popup or overlay)"
1871 ));
1872 };
1873 out.kinds.push(*kind);
1874 }
1875 }
1876 if let Some(levels) = grant.get("levels") {
1877 for name in strings(levels, "capabilities.windows.levels")? {
1878 let Some((_, level)) = WINDOW_LEVELS.iter().find(|(n, _)| *n == name) else {
1879 return Err(format!(
1880 "capabilities.windows.levels: unknown level `{name}` (normal, floating, aboveDock or desktopIcon)"
1881 ));
1882 };
1883 out.levels.push(*level);
1884 }
1885 }
1886 if let Some(max) = grant.get("max") {
1887 out.max = Some(
1888 max.as_u64()
1889 .and_then(|m| u32::try_from(m).ok())
1890 .ok_or("capabilities.windows.max must be a whole number")?,
1891 );
1892 }
1893 if let Some(v) = grant.get("overlay") {
1894 out.overlay = v
1895 .as_bool()
1896 .ok_or("capabilities.windows.overlay must be a boolean")?;
1897 }
1898 Ok(out)
1899}
1900
1901fn unknown_key(what: &str, key: &str, known: &[&str]) -> String {
1902 format!("{what}: unknown key `{key}` (known: {})", known.join(", "))
1903}
1904
1905fn strings(value: &Value, what: &str) -> Result<Vec<String>, String> {
1906 value
1907 .as_array()
1908 .and_then(|a| a.iter().map(|v| v.as_str().map(str::to_owned)).collect())
1909 .ok_or_else(|| format!("{what} must be an array of strings"))
1910}
1911
1912fn http_grant(g: &Map<String, Value>) -> Result<HttpGrant, String> {
1916 let what = "capabilities.network.http[]";
1917 let host = g
1918 .get("host")
1919 .and_then(Value::as_str)
1920 .ok_or_else(|| format!("{what} needs a `host`"))?;
1921 let list = |key: &str| -> Result<Vec<String>, String> {
1923 match g.get(key) {
1924 None => Ok(Vec::new()),
1925 Some(Value::String(s)) => Ok(vec![s.clone()]),
1926 Some(v) => strings(v, &format!("{what}.{key}")),
1927 }
1928 };
1929 let methods = list("methods")?
1930 .into_iter()
1931 .map(|m| {
1932 if !m.is_empty() && m.bytes().all(|b| b.is_ascii_alphabetic() || b == b'-') {
1933 Ok(m.to_ascii_uppercase())
1934 } else {
1935 Err(format!("{what}.methods: `{m}` is not an HTTP method"))
1936 }
1937 })
1938 .collect::<Result<Vec<_>, _>>()?;
1939 let mut schemes = Vec::new();
1940 for scheme in list("scheme")?.into_iter().chain(list("schemes")?) {
1941 let scheme = scheme.to_ascii_lowercase();
1942 if !matches!(scheme.as_str(), "http" | "https" | "ws" | "wss") {
1943 return Err(format!(
1944 "{what}.schemes: `{scheme}` is not http, https, ws or wss"
1945 ));
1946 }
1947 if !schemes.contains(&scheme) {
1948 schemes.push(scheme);
1949 }
1950 }
1951 let port = match g.get("port") {
1952 None => None,
1953 Some(v) => Some(
1954 v.as_u64()
1955 .and_then(|p| u16::try_from(p).ok())
1956 .filter(|&p| p != 0)
1957 .ok_or_else(|| format!("{what}.port must be a port from 1 to 65535"))?,
1958 ),
1959 };
1960 let paths = list("paths")?;
1961 let mut path_prefixes = Vec::new();
1962 for prefix in list("pathPrefix")?
1963 .into_iter()
1964 .chain(list("pathPrefixes")?)
1965 .chain(list("path_prefixes")?)
1966 {
1967 if !path_prefixes.contains(&prefix) {
1968 path_prefixes.push(prefix);
1969 }
1970 }
1971 if let Some(bad) = paths
1973 .iter()
1974 .chain(&path_prefixes)
1975 .find(|p| !p.starts_with('/') || p.contains(['*', '?', '#']))
1976 {
1977 return Err(format!(
1978 "{what}: path `{bad}` must start with / and has no `*`, `?` or `#` (paths match as written)"
1979 ));
1980 }
1981 let as_sent = |list: Vec<String>| -> Result<Vec<String>, String> {
1984 let mut sent = Vec::new();
1985 for path in list {
1986 let path = path_as_sent(&path).ok_or_else(|| {
1987 format!("{what}: path `{path}` has a `.` or `..` segment, which no request sends")
1988 })?;
1989 if !sent.contains(&path) {
1990 sent.push(path);
1991 }
1992 }
1993 Ok(sent)
1994 };
1995 let paths = as_sent(paths)?;
1996 let path_prefixes = as_sent(path_prefixes)?;
1997 Ok(HttpGrant {
1998 host: HostPattern::new(host)?,
1999 methods,
2000 schemes,
2001 port,
2002 paths,
2003 path_prefixes,
2004 })
2005}
2006
2007fn patterns(value: &Value, what: &str) -> Result<Vec<HostPattern>, String> {
2008 strings(value, what)?
2009 .iter()
2010 .map(|p| HostPattern::new(p))
2011 .collect()
2012}
2013
2014#[derive(Debug, Clone, PartialEq, Eq)]
2017pub struct Access {
2018 pub declared: Capabilities,
2020 pub granted: Option<Capabilities>,
2022}
2023
2024impl Default for Access {
2025 fn default() -> Self {
2026 Self::all()
2027 }
2028}
2029
2030impl Access {
2031 pub fn all() -> Self {
2033 Self {
2034 declared: Capabilities::all(),
2035 granted: None,
2036 }
2037 }
2038
2039 fn each(&self, f: impl Fn(&Capabilities) -> bool) -> bool {
2040 f(&self.declared) && self.granted.as_ref().is_none_or(f)
2041 }
2042
2043 pub fn is_unrestricted(&self) -> bool {
2046 let all = Capabilities::all();
2047 self.declared == all && self.granted.as_ref().is_none_or(|g| *g == all)
2048 }
2049
2050 pub fn allows_process(&self, command: &str) -> bool {
2053 valid_command(command) && self.each(|c| c.process.execute.iter().any(|p| p == command))
2054 }
2055
2056 pub fn allows_exit(&self) -> bool {
2059 self.each(|caps| caps.process.exit)
2060 }
2061
2062 pub fn allows_env(&self, name: &str) -> bool {
2065 let defaults = include_str!("default-env").lines().filter_map(|line| {
2066 let name = line.split('#').next().unwrap_or_default().trim();
2067 (!name.is_empty()).then_some(name)
2068 });
2069 defaults
2070 .into_iter()
2071 .any(|allowed| env_names_match(allowed, name))
2072 || self.each(|caps| {
2073 caps.process
2074 .env
2075 .iter()
2076 .any(|allowed| env_names_match(allowed, name))
2077 })
2078 }
2079
2080 pub fn authorize_file(
2083 &self,
2084 path: &Path,
2085 data_dir: &Path,
2086 write: bool,
2087 ) -> Result<PathBuf, FileRefusal> {
2088 self.authorize_file_with_paths(path, data_dir, &TrustedPaths::default(), write)
2089 }
2090
2091 pub fn authorize_file_with_paths(
2093 &self,
2094 path: &Path,
2095 data_dir: &Path,
2096 paths: &TrustedPaths,
2097 write: bool,
2098 ) -> Result<PathBuf, FileRefusal> {
2099 let requested = if let Some(text) = path.to_str().filter(|s| s.starts_with("${")) {
2100 paths
2101 .resolve_root(text, data_dir)
2102 .map_err(FileRefusal::Invalid)?
2103 } else {
2104 path.to_owned()
2105 };
2106 let resolved = resolved_path(&requested).map_err(FileRefusal::Invalid)?;
2107 let allowed = self.each(|c| {
2108 let roots = if write { &c.fs.write } else { &c.fs.read };
2109 roots.iter().any(|root| {
2110 paths
2111 .resolve_root(root, data_dir)
2112 .and_then(|r| resolved_path(&r))
2113 .is_ok_and(|root| resolved.starts_with(root))
2114 })
2115 });
2116 if allowed {
2117 Ok(resolved)
2118 } else {
2119 Err(FileRefusal::NotGranted(format!(
2120 "filesystem {} is not granted by capabilities.fs",
2121 if write { "write" } else { "read" }
2122 )))
2123 }
2124 }
2125
2126 pub fn allows_socket(&self, host: &str, port: u16) -> bool {
2130 if host.is_empty() || host.contains(['/', '@', '?', '#', '\0']) {
2131 return false;
2132 }
2133 let host = host.to_ascii_lowercase();
2134 let host = host
2135 .strip_prefix('[')
2136 .and_then(|h| h.strip_suffix(']'))
2137 .unwrap_or(&host)
2138 .trim_end_matches('.');
2139 self.each(|c| {
2140 c.network
2141 .sockets
2142 .iter()
2143 .any(|grant| grant.port == port && grant.host == host)
2144 })
2145 }
2146
2147 pub fn allows_websocket(&self, url: &str) -> bool {
2151 let http = if let Some(rest) = url.strip_prefix("wss:") {
2152 format!("https:{rest}")
2153 } else if let Some(rest) = url.strip_prefix("ws:") {
2154 format!("http:{rest}")
2155 } else {
2156 return false;
2157 };
2158 self.allows_http("GET", &http) || self.allows_http("GET", url)
2159 }
2160
2161 pub fn allows_http(&self, method: &str, url: &str) -> bool {
2164 if url.starts_with("asset:") {
2165 return true;
2166 }
2167 match read_url(url) {
2168 Ok(parts) => {
2170 url::Url::parse(url).is_ok_and(|whatwg| self.allows_parts(method, parts, &whatwg))
2171 }
2172 Err(Unread::Ambiguous(scheme)) => {
2174 self.each(|c| c.allows_http_anywhere(method, &scheme))
2175 }
2176 Err(Unread::NotUrl) => false,
2177 }
2178 }
2179
2180 fn allows_parsed(&self, method: &str, url: &str, whatwg: &url::Url) -> bool {
2185 match read_url(url) {
2186 Ok(parts) => self.allows_parts(method, parts, whatwg),
2187 Err(Unread::Ambiguous(scheme)) => {
2188 self.each(|c| c.allows_http_anywhere(method, &scheme))
2189 }
2190 Err(Unread::NotUrl) => false,
2191 }
2192 }
2193
2194 fn allows_parts(&self, method: &str, parts: UrlParts<'_>, whatwg: &url::Url) -> bool {
2197 let parts = UrlParts {
2198 path: whatwg.path(),
2199 ..parts
2200 };
2201 self.each(|c| c.allows_http(method, &parts))
2202 }
2203
2204 pub fn http_url<'a>(&self, method: &str, url: &'a str) -> Option<Cow<'a, str>> {
2208 if url.starts_with("asset:") {
2209 return Some(Cow::Borrowed(url));
2210 }
2211 let whatwg = url::Url::parse(url).ok()?;
2212 self.allows_parsed(method, whatwg.as_str(), &whatwg)
2213 .then(|| written_or(url, whatwg.into()))
2214 }
2215
2216 pub fn allows_media(&self, uri: &str) -> bool {
2220 self.media_url(uri, None, None).is_some()
2221 }
2222
2223 pub fn media_url<'a>(
2243 &self,
2244 uri: &'a str,
2245 base: Option<&str>,
2246 files: Option<&MediaFiles>,
2247 ) -> Option<Cow<'a, str>> {
2248 if is_own_media(uri) {
2249 let inside = !starts_with_ignoring_case(uri, "asset:") || is_inside_assets(uri);
2252 return (inside || self.is_unrestricted()).then_some(Cow::Borrowed(uri));
2253 }
2254 if self.is_unrestricted() {
2255 return media_as_written(uri, |url| self.allows_http("GET", url))
2256 .then_some(Cow::Borrowed(uri));
2257 }
2258 let file_url = starts_with_ignoring_case(uri, "file:");
2259 if (base.is_none() || file_url)
2260 && let Some(path) = local_file(uri)
2261 {
2262 let real = files?.readable(&path?)?;
2263 let loads = if file_url {
2264 file_url_of(&real)?
2265 } else {
2266 real.into_os_string().into_string().ok()?
2267 };
2268 return Some(written_or(uri, loads));
2269 }
2270 let stripped = whatwg_stripped(uri);
2273 let scheme = scheme_of(&stripped);
2274 let names_host = scheme.is_some()
2275 || stripped.starts_with("//")
2276 || stripped.starts_with(['\\'])
2277 || stripped.starts_with("/\\");
2278 if !names_host {
2279 return (base.is_some() || uri.trim().is_empty()).then_some(Cow::Borrowed(uri));
2283 }
2284 let base = || base.and_then(|b| url::Url::parse(b).ok());
2286 let trimmed = uri.trim_matches(|c: char| c <= ' ');
2292 let head = trimmed.split(['?', '#']).next().unwrap_or(trimmed);
2293 if head.contains('\\')
2294 || trimmed.bytes().any(|b| b.is_ascii_control())
2295 || matches!(read_url(trimmed), Err(Unread::Ambiguous(_)))
2296 {
2297 let scheme = match scheme {
2298 Some(scheme) => scheme.to_ascii_lowercase(),
2299 None => base()?.scheme().to_owned(),
2300 };
2301 return self
2302 .each(|c| c.allows_http_anywhere("GET", &scheme))
2303 .then_some(Cow::Borrowed(uri));
2304 }
2305 let parsed = match scheme {
2306 Some(_) => url::Url::parse(trimmed),
2307 None => base()?.join(trimmed),
2308 }
2309 .ok()?;
2310 self.allows_parsed("GET", parsed.as_str(), &parsed)
2311 .then(|| written_or(uri, parsed.into()))
2312 }
2313
2314 pub fn media_redirect(&self, base: &str, location: &str) -> Result<String, String> {
2320 let url = resolve_reference(base, location);
2321 if !(url.starts_with("http://") || url.starts_with("https://")) {
2322 return Err(format!("redirect to `{url}` is not an http(s) URL"));
2323 }
2324 if !self.is_unrestricted() && !self.allows_media(&url) {
2325 return Err(format!(
2326 "redirect to `{url}` is not granted by capabilities.network"
2327 ));
2328 }
2329 Ok(url)
2330 }
2331
2332 pub fn allows_webviews(&self) -> bool {
2334 self.each(|c| c.webview.is_some())
2335 }
2336
2337 pub fn allows_webview(&self, url: &str) -> bool {
2344 if url == "about:blank" {
2345 return self.allows_webviews();
2346 }
2347 let url = blob_origin(url).unwrap_or(url);
2348 match read_url(url) {
2349 Ok(parts) => self.each(|c| c.allows_webview(&parts)),
2350 Err(Unread::Ambiguous(scheme)) => self.each(|c| c.allows_webview_anywhere(&scheme)),
2351 Err(Unread::NotUrl) => false,
2352 }
2353 }
2354
2355 pub fn allows_web_input(&self) -> bool {
2358 self.each(|c| c.webview.is_some() && c.webview_input)
2359 }
2360
2361 pub fn allows_web_media(&self, media: WebMedia) -> bool {
2365 self.each(|c| c.webview.is_some() && c.webview_media.contains(&media))
2366 }
2367
2368 pub fn check_window(
2373 &self,
2374 kind: crate::desktop::WindowKind,
2375 attributes: &crate::desktop::WindowAttributes,
2376 open: usize,
2377 ) -> Result<(), String> {
2378 if !self.each(|c| c.windows.is_some()) {
2379 return Err("windows of the app's own are not granted by capabilities.windows".into());
2380 }
2381 if !self.each(|c| c.windows.as_ref().is_some_and(|w| w.allows_kind(kind))) {
2382 return Err(format!(
2383 "a window of kind `{}` is not granted by capabilities.windows{}",
2384 window_kind_name(kind),
2385 if kind == crate::desktop::WindowKind::Overlay {
2386 " (overlays need `overlay: true`)"
2387 } else {
2388 ""
2389 }
2390 ));
2391 }
2392 if !self.each(|c| {
2393 c.windows
2394 .as_ref()
2395 .is_some_and(|w| w.max.is_none_or(|max| open < max as usize))
2396 }) {
2397 return Err("capabilities.windows.max windows are open already".into());
2398 }
2399 let mut own = attributes.clone();
2400 let level = own.level.take();
2402 let denied = self.deny_window_attributes(&mut own);
2403 if let Some(name) = denied.first() {
2404 return Err(format!(
2405 "the window attribute `{name}` is not granted by capabilities.windows"
2406 ));
2407 }
2408 if let Some(level) = level
2409 && !self.each(|c| c.windows.as_ref().is_some_and(|w| w.allows_level(level)))
2410 {
2411 return Err(format!(
2412 "the window level `{}` is not granted by capabilities.windows.levels",
2413 window_level_name(level)
2414 ));
2415 }
2416 Ok(())
2417 }
2418
2419 pub fn deny_window_attributes(
2425 &self,
2426 attributes: &mut crate::desktop::WindowAttributes,
2427 ) -> Vec<&'static str> {
2428 let mut denied = Vec::new();
2429 let grant = |f: &dyn Fn(&WindowsGrant) -> bool| {
2430 self.each(|c| match &c.windows {
2431 Some(w) => f(w),
2432 None => false,
2434 })
2435 };
2436 if let Some(level) = attributes.level
2437 && level != crate::desktop::WindowLevel::Normal
2438 && !grant(&|w| w.allows_level(level))
2439 {
2440 attributes.level = None;
2441 denied.push("level");
2442 }
2443 if attributes.passes_pointer() && !grant(&|w| w.overlay) {
2444 attributes.pointer_events = None;
2445 denied.push("pointerEvents");
2446 }
2447 denied
2448 }
2449
2450 pub fn allows_status_bar(&self) -> bool {
2452 self.each(|c| c.status_bar)
2453 }
2454
2455 pub fn allows_share(&self) -> bool {
2458 self.each(|c| c.share)
2459 }
2460
2461 pub fn allows_clipboard(&self) -> bool {
2463 self.each(|c| c.clipboard)
2464 }
2465
2466 pub fn allows_picker(&self) -> bool {
2468 self.each(|c| c.picker)
2469 }
2470
2471 pub fn allows_speech(&self) -> bool {
2473 self.each(|c| c.speech)
2474 }
2475
2476 pub fn allows_notifications(&self) -> bool {
2479 self.each(|c| c.notifications)
2480 }
2481
2482 pub fn allows_audio(&self) -> bool {
2484 self.each(|c| c.audio)
2485 }
2486
2487 pub fn allows_application(&self) -> bool {
2491 self.each(|c| c.application)
2492 }
2493
2494 pub fn allows_home_dir(&self) -> bool {
2496 self.each(|c| c.home_dir)
2497 }
2498
2499 pub fn allows_host(&self, name: &str) -> bool {
2501 self.each(|c| c.allows_host(name))
2502 }
2503
2504 pub fn allows_open_url(&self, url: &str) -> bool {
2507 let Some(scheme) = url
2508 .split_once(':')
2509 .map(|(scheme, _)| scheme.to_ascii_lowercase())
2510 else {
2511 return false;
2512 };
2513 self.each(|c| c.open_url.as_ref().is_some_and(|g| g.allows(&scheme)))
2514 }
2515}
2516
2517pub fn resolve_reference(base: &str, location: &str) -> String {
2523 match url::Url::parse(base).and_then(|base| base.join(location)) {
2524 Ok(url) => url.into(),
2525 Err(_) => location.to_owned(),
2526 }
2527}
2528
2529#[cfg(test)]
2530mod tests {
2531 #[test]
2532 fn verbatim_windows_paths_compare_in_their_plain_form() {
2533 use super::without_verbatim_prefix as plain;
2534 assert_eq!(plain(r"\\?\C:\Users\a").as_deref(), Some(r"C:\Users\a"));
2535 assert_eq!(plain(r"\\?\d:\").as_deref(), Some(r"d:\"));
2536 assert_eq!(plain(r"\\?\C:\app\").as_deref(), Some(r"C:\app\"));
2537 assert_eq!(
2538 plain(r"\\?\UNC\server\share\a").as_deref(),
2539 Some(r"\\server\share\a")
2540 );
2541 for path in [
2543 r"C:\a",
2544 r"\\server\share",
2545 "/home/a",
2546 r"\\?\Volume{x}\a",
2547 r"\\.\C:\a",
2548 ] {
2549 assert_eq!(plain(path), None, "{path}");
2550 }
2551 for path in [
2553 r"\\?\C:\a\NUL",
2554 r"\\?\C:\a\com1.txt",
2555 r"\\?\C:\a\Lpt9",
2556 r"\\?\C:\a\b.",
2557 r"\\?\C:\a\b ",
2558 r"\\?\C:\a\..\b",
2559 r"\\?\C:\a\.\b",
2560 r"\\?\C:\a\\b",
2561 r"\\?\C:\a/b",
2562 ] {
2563 assert_eq!(plain(path), None, "{path}");
2564 }
2565 assert_eq!(
2566 plain(r"\\?\C:\a\com10\console").as_deref(),
2567 Some(r"C:\a\com10\console")
2568 );
2569 let long = format!(r"\\?\C:\{}", "a".repeat(260));
2570 assert_eq!(plain(&long), None);
2571 }
2572
2573 #[test]
2574 fn anchored_roots_join_their_tail_component_by_component() {
2575 let app = PathBuf::from(if cfg!(windows) { r"C:\app" } else { "/app" });
2576 let paths = super::TrustedPaths {
2577 plugin_dir: Some(app.clone()),
2578 home_dir: None,
2579 };
2580 let root = paths.resolve_root("${pluginDir}/a//b/", &app).unwrap();
2581 assert_eq!(root, app.join("a").join("b"));
2582 let names = root.components().rev().take(2).collect::<Vec<_>>();
2583 assert_eq!(
2584 names,
2585 [
2586 Component::Normal("b".as_ref()),
2587 Component::Normal("a".as_ref())
2588 ]
2589 );
2590 }
2591 use std::cell::Cell;
2592
2593 use super::*;
2594
2595 fn caps(json: &str) -> Capabilities {
2596 Capabilities::from_json(&serde_json::from_str(json).unwrap()).unwrap()
2597 }
2598
2599 #[test]
2600 fn windows_are_granted_by_kind_level_and_count() {
2601 use crate::desktop::{WindowAttributes, WindowKind, WindowLevel, WindowPointerEvents};
2602 let none = WindowAttributes::default();
2603 let all = Access::all();
2606 assert!(all.check_window(WindowKind::Panel, &none, 10).is_ok());
2607 assert!(all.check_window(WindowKind::Overlay, &none, 0).is_err());
2608 let click_through = WindowAttributes {
2609 pointer_events: Some(WindowPointerEvents::None),
2610 ..Default::default()
2611 };
2612 assert!(
2613 all.check_window(WindowKind::Normal, &click_through, 0)
2614 .is_err()
2615 );
2616 let declared = |json: &str| Access {
2618 declared: caps(json),
2619 granted: None,
2620 };
2621 assert!(
2622 declared(r#"{"process":{"exit":true}}"#)
2623 .check_window(WindowKind::Normal, &none, 0)
2624 .is_err()
2625 );
2626 let limited = declared(
2627 r#"{"windows":{"kinds":["normal","dialog"],"levels":["normal","floating"],"max":2}}"#,
2628 );
2629 assert!(limited.check_window(WindowKind::Dialog, &none, 1).is_ok());
2630 assert!(limited.check_window(WindowKind::Popup, &none, 0).is_err());
2631 assert!(limited.check_window(WindowKind::Normal, &none, 2).is_err());
2632 let above = WindowAttributes {
2633 level: Some(WindowLevel::AboveDock),
2634 ..Default::default()
2635 };
2636 assert!(limited.check_window(WindowKind::Normal, &above, 0).is_err());
2637 let overlay = declared(r#"{"windows":{"overlay":true}}"#);
2638 assert!(
2639 overlay
2640 .check_window(WindowKind::Overlay, &click_through, 0)
2641 .is_ok()
2642 );
2643 let mut asked = WindowAttributes {
2645 title: Some("Notes".into()),
2646 level: Some(WindowLevel::AboveDock),
2647 ..Default::default()
2648 };
2649 assert_eq!(limited.deny_window_attributes(&mut asked), ["level"]);
2650 assert_eq!(asked.title.as_deref(), Some("Notes"));
2651 assert_eq!(asked.level, None);
2652 }
2653
2654 #[test]
2655 fn environment_names_match_exactly_except_on_windows() {
2656 let access = Access {
2657 declared: caps(r#"{"process":{"env":["MY_TOKEN"]}}"#),
2658 granted: None,
2659 };
2660 assert!(access.allows_env("MY_TOKEN"));
2661 assert_eq!(access.allows_env("my_token"), cfg!(windows));
2662 assert_eq!(super::env_names_match("Path", "PATH"), cfg!(windows));
2663 }
2664
2665 #[test]
2666 fn roots_stay_within_their_anchor_and_bare_commands_have_no_drive() {
2667 let anchor = Path::new(if cfg!(windows) { "C:\\app" } else { "/app" });
2668 assert!(super::within(anchor, Path::new("data/x"), "r").is_ok());
2669 assert!(super::within(anchor, Path::new("/etc"), "r").is_err());
2670 #[cfg(windows)]
2671 for tail in ["C:/Windows", "\\\\srv\\share", "\\Users", "D:x"] {
2672 assert!(
2673 super::within(anchor, Path::new(tail), "r").is_err(),
2674 "{tail}"
2675 );
2676 }
2677 assert!(!super::valid_command("C:git"));
2678 assert!(super::valid_command("git"));
2679 }
2680
2681 #[test]
2682 fn a_manifest_with_absolute_commands_and_roots_parses() {
2683 let declared = caps(
2686 r#"{"process":{"execute":["/bin/sh","/usr/bin/open","git"]},"fs":{"read":["/Applications"]}}"#,
2687 );
2688 assert_eq!(
2689 declared.process.execute,
2690 ["/bin/sh", "/usr/bin/open", "git"]
2691 );
2692 if !cfg!(windows) {
2693 assert!(super::valid_command("/bin/sh"));
2694 assert!(super::absolute(Path::new("/Applications")));
2695 }
2696 }
2697
2698 #[test]
2699 fn system_capabilities_are_explicit_and_intersected() {
2700 let declared = caps(
2701 r#"{"process":{"execute":["claude","codex"]},"fs":{"read":["${dataDir}"],"write":["${dataDir}"]}}"#,
2702 );
2703 assert_eq!(
2704 Capabilities::from_json(&declared.to_json()).unwrap(),
2705 declared
2706 );
2707 let access = Access {
2708 declared,
2709 granted: Some(caps(
2710 r#"{"process":{"execute":["codex"]},"fs":{"read":["${dataDir}/conversations"]}}"#,
2711 )),
2712 };
2713 assert!(access.allows_process("codex"));
2714 assert!(!access.allows_process("claude"));
2715 assert!(!access.allows_process("/usr/bin/codex"));
2716 assert!(!Access::all().allows_process("codex"));
2717 let root = std::env::current_dir().unwrap();
2718 assert!(
2719 access
2720 .authorize_file(&root.join("conversations/new.json"), &root, false)
2721 .is_ok()
2722 );
2723 assert!(
2724 access
2725 .authorize_file(&root.join("other.json"), &root, false)
2726 .is_err()
2727 );
2728 assert!(
2729 access
2730 .authorize_file(&root.join("conversations/new.json"), &root, true)
2731 .is_err()
2732 );
2733 assert!(Access::all().authorize_file(&root, &root, false).is_err());
2734 assert!(
2735 access
2736 .authorize_file(&root.join("../secret"), &root, false)
2737 .is_err()
2738 );
2739 for bad in [
2740 r#"{"process":{"execut":[]}}"#,
2741 r#"{"fs":{"reads":[]}}"#,
2742 r#"{"fs":{"read":["${dataDir}/../outside"]}}"#,
2743 r#"{"process":{"execute":["*"]}}"#,
2744 ] {
2745 assert!(Capabilities::from_json(&serde_json::from_str(bad).unwrap()).is_err());
2746 }
2747 }
2748
2749 #[test]
2750 fn trusted_host_anchors_expand_without_implicit_grants() {
2751 let root = std::env::current_dir().unwrap();
2752 let anchors = TrustedPaths {
2753 plugin_dir: Some(root.clone()),
2754 home_dir: Some(root.join("native-home")),
2755 };
2756 let access = Access {
2757 declared: caps(
2758 r#"{"fs":{"read":["assets","${homeDir}/settings","${pluginDir}/content"]}}"#,
2759 ),
2760 granted: None,
2761 };
2762 for path in ["assets/file", "native-home/settings/file", "content/file"] {
2763 assert!(
2764 access
2765 .authorize_file_with_paths(&root.join(path), &root, &anchors, false)
2766 .is_ok()
2767 );
2768 }
2769 assert!(
2770 access
2771 .authorize_file(&root.join("content/file"), &root, false)
2772 .is_err()
2773 );
2774 assert!(
2775 access
2776 .authorize_file_with_paths(&root.join("other/file"), &root, &anchors, false)
2777 .is_err()
2778 );
2779 assert!(
2780 TrustedPaths::default()
2781 .resolve_root("${homeDir}/settings", &root)
2782 .is_err()
2783 );
2784 assert!(
2785 TrustedPaths::default()
2786 .resolve_root("assets", &root)
2787 .is_err()
2788 );
2789 }
2790
2791 #[test]
2792 fn http_rules_are_one_form_whose_keys_all_narrow() {
2793 let allows = |rule: serde_json::Value, method: &str, url: &str| {
2794 Access {
2795 declared: Capabilities::from_json(&serde_json::json!({"network":{"http":[rule]}}))
2796 .unwrap(),
2797 granted: None,
2798 }
2799 .allows_http(method, url)
2800 };
2801 let plain = serde_json::json!({"host": "api.example.com", "methods": ["GET"]});
2803 assert!(allows(plain.clone(), "GET", "https://api.example.com/"));
2804 assert!(allows(
2805 plain.clone(),
2806 "GET",
2807 "http://api.example.com:8080/any/path"
2808 ));
2809 assert!(!allows(plain.clone(), "POST", "https://api.example.com/"));
2810 assert!(allows(
2811 serde_json::json!({"host": "api.example.com"}),
2812 "PUT",
2813 "https://api.example.com/x"
2814 ));
2815 let scoped = serde_json::json!({
2817 "host": "api.example.com", "methods": ["GET"], "scheme": "https", "port": 443,
2818 "paths": ["/exact"], "pathPrefixes": ["/v1"]
2819 });
2820 assert!(allows(
2821 scoped.clone(),
2822 "GET",
2823 "https://api.example.com/exact?q=1"
2824 ));
2825 assert!(allows(scoped.clone(), "GET", "https://api.example.com/v1"));
2826 assert!(allows(
2827 scoped.clone(),
2828 "GET",
2829 "https://api.example.com/v1/child"
2830 ));
2831 assert!(!allows(
2832 scoped.clone(),
2833 "GET",
2834 "https://api.example.com/v10"
2835 ));
2836 assert!(!allows(
2837 scoped.clone(),
2838 "GET",
2839 "https://api.example.com/exact/more"
2840 ));
2841 assert!(!allows(
2842 scoped.clone(),
2843 "GET",
2844 "http://api.example.com/exact"
2845 ));
2846 assert!(!allows(
2847 scoped.clone(),
2848 "GET",
2849 "https://api.example.com:444/exact"
2850 ));
2851 assert!(allows(scoped, "GET", "https://api.example.com:443/exact"));
2852 let legacy = serde_json::json!({"host": "*.example.com", "schemes": ["https", "wss"], "pathPrefix": "/v1/"});
2854 assert!(allows(
2855 legacy.clone(),
2856 "GET",
2857 "https://quotes.example.com/v1/quote"
2858 ));
2859 assert!(!allows(legacy, "GET", "https://quotes.example.com/v2/"));
2860 let mixed = caps(
2862 r#"{"network":{"http":[{"host":"a.example.com","methods":["get"],"scheme":"https","schemes":["wss","https"],"pathPrefix":"/a","path_prefixes":["/b"],"pathPrefixes":["/a","/c"]}]}}"#,
2863 );
2864 let grant = &mixed.network.http[0];
2865 assert_eq!(grant.methods, ["GET"]);
2866 assert_eq!(grant.schemes, ["https", "wss"]);
2867 assert_eq!(grant.path_prefixes, ["/a", "/c", "/b"]);
2868 assert_eq!(
2869 mixed.to_json()["network"]["http"][0],
2870 serde_json::json!({"host":"a.example.com","methods":["GET"],"schemes":["https","wss"],"pathPrefixes":["/a","/c","/b"]})
2871 );
2872 assert_eq!(Capabilities::from_json(&mixed.to_json()).unwrap(), mixed);
2873 for bad in [
2875 serde_json::json!({"host": "a.example.com", "schemes": ["ftp"]}),
2876 serde_json::json!({"host": "a.example.com", "port": 0}),
2877 serde_json::json!({"host": "a.example.com", "port": 70000}),
2878 serde_json::json!({"host": "a.example.com", "paths": ["relative"]}),
2879 serde_json::json!({"host": "a.example.com", "pathPrefixes": ["/v1/*"]}),
2880 serde_json::json!({"host": "a.example.com", "methods": ["*"]}),
2881 serde_json::json!({"host": "a.example.com", "paths": "/x", "query": true}),
2882 serde_json::json!({"methods": ["GET"]}),
2883 ] {
2884 assert!(
2885 Capabilities::from_json(&serde_json::json!({"network":{"http":[bad.clone()]}}))
2886 .is_err(),
2887 "{bad}"
2888 );
2889 }
2890 }
2891
2892 #[test]
2893 fn exit_and_environment_permissions_intersect() {
2894 let declared = caps(r#"{"process":{"env":["NSH_SECRET","OTHER"],"exit":true}}"#);
2895 assert_eq!(
2896 Capabilities::from_json(&declared.to_json()).unwrap(),
2897 declared
2898 );
2899 let access = Access {
2900 declared,
2901 granted: Some(caps(r#"{"process":{"env":["NSH_SECRET"]}}"#)),
2902 };
2903 assert!(access.allows_env("NSH_SECRET"));
2904 assert!(!access.allows_env("OTHER"));
2905 assert!(!access.allows_exit());
2906 assert!(!Access::all().allows_exit());
2907 assert!(!Access::all().allows_env("NSH_SECRET"));
2908 assert!(Access::all().allows_env("LANG"));
2909 assert_eq!(Access::all().allows_env("lang"), cfg!(windows));
2910 assert!(Access::all().allows_env("TZ"));
2911 for name in [
2913 "HOME",
2914 "USER",
2915 "USERNAME",
2916 "HOSTNAME",
2917 "COMPUTERNAME",
2918 "PATH",
2919 "TMPDIR",
2920 "XDG_RUNTIME_DIR",
2921 "APPDATA",
2922 "http_proxy",
2923 "HTTPS_PROXY",
2924 "ALL_PROXY",
2925 "NO_PROXY",
2926 "DISPLAY",
2927 ] {
2928 assert!(!Access::all().allows_env(name), "{name}");
2929 }
2930 assert!(!Access::all().allows_env("SSH_AUTH_SOCK"));
2931 assert!(!Access::all().allows_env("DBUS_SESSION_BUS_ADDRESS"));
2932 assert!(Capabilities::from_json(&serde_json::json!({"process":{"exit":"true"}})).is_err());
2933 assert!(
2934 Capabilities::from_json(&serde_json::json!({"process":{"env":["BAD=NAME"]}})).is_err()
2935 );
2936 }
2937
2938 #[test]
2939 fn default_environment_entries_are_upper_case_names() {
2940 for line in include_str!("default-env").lines() {
2941 let name = line.split('#').next().unwrap_or_default().trim();
2942 assert!(
2943 name.is_empty()
2944 || name
2945 .chars()
2946 .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'),
2947 "{line}"
2948 );
2949 }
2950 }
2951
2952 #[test]
2953 fn sockets_need_exact_host_and_port_grants() {
2954 let declared = caps(
2955 r#"{"network":{"hosts":["*"],"sockets":["MQTT.example.com:8883","[::1]:9000","127.0.0.1:22"]}}"#,
2956 );
2957 assert_eq!(
2958 Capabilities::from_json(&declared.to_json()).unwrap(),
2959 declared
2960 );
2961 let access = Access {
2962 declared,
2963 granted: None,
2964 };
2965 assert!(access.allows_socket("mqtt.example.com", 8883));
2966 assert!(access.allows_socket("MQTT.example.com.", 8883));
2967 assert!(!access.allows_socket("mqtt.example.com", 1883));
2968 assert!(!access.allows_socket("example.com", 8883));
2969 assert!(!access.allows_socket("a.mqtt.example.com", 8883));
2970 assert!(access.allows_socket("::1", 9000));
2971 assert!(access.allows_socket("[::1]", 9000));
2972 assert!(access.allows_socket("127.0.0.1", 22));
2973 assert!(!access.allows_socket("127.0.0.1", 0));
2974 assert!(!access.allows_socket("localhost", 22));
2976 assert!(!Access::all().allows_socket("127.0.0.1", 22));
2977 assert!(!Access::all().allows_socket("example.com", 443));
2978 let narrowed = Access {
2979 granted: Some(caps(r#"{"network":{"sockets":["127.0.0.1:22"]}}"#)),
2980 ..access
2981 };
2982 assert!(narrowed.allows_socket("127.0.0.1", 22));
2983 assert!(!narrowed.allows_socket("mqtt.example.com", 8883));
2984 for bad in [
2985 "*.example.com:443",
2986 "*:443",
2987 "example.com",
2988 "example.com:0",
2989 "example.com:65536",
2990 "example.com:*",
2991 ":443",
2992 "::1:443",
2993 "[]:443",
2994 "exa mple.com:1",
2995 ] {
2996 assert!(
2997 Capabilities::from_json(&serde_json::json!({"network":{"sockets":[bad]}}))
2998 .unwrap_err()
2999 .contains("invalid socket grant"),
3000 "{bad}"
3001 );
3002 }
3003 }
3004
3005 #[test]
3006 fn websockets_follow_http_grants() {
3007 let access = Access {
3008 declared: caps(
3009 r#"{"network":{"hosts":["ws.example.com"],"http":[
3010 {"host":"chat.example.com","methods":["GET"],"scheme":"https","paths":["/socket"]},
3011 {"host":"legacy.example.com","schemes":["wss"]}
3012 ]}}"#,
3013 ),
3014 granted: None,
3015 };
3016 assert!(access.allows_websocket("ws://ws.example.com:8080/x"));
3017 assert!(access.allows_websocket("wss://chat.example.com/socket"));
3018 assert!(!access.allows_websocket("ws://chat.example.com/socket"));
3019 assert!(!access.allows_websocket("wss://chat.example.com/other"));
3020 assert!(access.allows_websocket("wss://legacy.example.com/"));
3021 assert!(!access.allows_websocket("ws://legacy.example.com/"));
3022 assert!(!access.allows_websocket("https://ws.example.com/"));
3023 assert!(!access.allows_socket("ws.example.com", 8080));
3024 }
3025
3026 #[cfg(unix)]
3027 #[test]
3028 fn filesystem_symlinks_cannot_escape_granted_roots() {
3029 use std::os::unix::fs::symlink;
3030 let base = std::env::var_os("TMPDIR")
3031 .map(PathBuf::from)
3032 .unwrap_or_else(|| {
3033 PathBuf::from(std::env::var_os("HOME").unwrap()).join(".cache/nsh-benchs-test-tmp")
3034 });
3035 let root = base.join(format!("access-policy-{}", std::process::id()));
3036 std::fs::create_dir_all(root.join("allowed")).unwrap();
3037 std::fs::create_dir_all(root.join("outside")).unwrap();
3038 symlink(root.join("outside"), root.join("allowed/link")).unwrap();
3039 let access = Access {
3040 declared: caps(r#"{"fs":{"read":["${dataDir}"],"write":["${dataDir}"]}}"#),
3041 granted: None,
3042 };
3043 for write in [false, true] {
3044 assert!(
3045 access
3046 .authorize_file(
3047 &root.join("allowed/link/missing/file"),
3048 &root.join("allowed"),
3049 write
3050 )
3051 .is_err()
3052 );
3053 assert!(
3054 access
3055 .authorize_file(&root.join("allowed/new/file"), &root.join("allowed"), write)
3056 .is_ok()
3057 );
3058 }
3059 std::fs::remove_dir_all(root).unwrap();
3060 }
3061
3062 #[test]
3063 fn the_share_sheet_is_granted_by_both_sides() {
3064 let declared = caps(r#"{ "share": true }"#);
3065 assert!(declared.share);
3066 assert_eq!(declared.to_json()["share"], serde_json::json!(true));
3067 assert!(
3068 Access {
3069 declared: declared.clone(),
3070 granted: None,
3071 }
3072 .allows_share()
3073 );
3074 assert!(
3076 !Access {
3077 declared,
3078 granted: Some(caps("{}")),
3079 }
3080 .allows_share()
3081 );
3082 assert!(Access::all().allows_share());
3084 assert!(Capabilities::from_json(&serde_json::json!({ "share": "yes" })).is_err());
3085 }
3086
3087 #[test]
3088 fn denies_unless_listed() {
3089 let access = Access {
3090 declared: caps("{}"),
3091 granted: None,
3092 };
3093 assert!(!access.allows_http("GET", "https://example.com/"));
3094 assert!(!access.allows_media("https://example.com/a.png"));
3095 assert!(access.allows_media("asset:/logo.png"));
3096 assert!(!access.allows_media("logo.png"));
3098 assert!(!access.allows_media("/home/a/logo.png"));
3101 assert!(!access.allows_media("file:///home/a/logo.png"));
3102 assert!(access.allows_media("data:image/png;base64,iVBORw0KGgo="));
3103 assert!(!access.allows_webview("https://example.com/"));
3104 assert!(!access.allows_status_bar());
3105 assert!(!access.allows_clipboard());
3106 assert!(!access.allows_picker());
3107 assert!(!access.allows_share());
3108 assert!(!access.allows_speech());
3109 assert!(!access.allows_audio());
3110 assert!(!access.allows_application());
3111 assert!(!access.allows_home_dir());
3112 assert!(!access.allows_host("getUserInfo"));
3113 assert!(Access::all().is_unrestricted());
3114 }
3115
3116 #[test]
3117 fn the_application_and_the_home_directory_are_capabilities() {
3118 let all = Access::all();
3120 assert!(all.allows_application() && all.allows_home_dir());
3121 let access = |declared: &str, granted: Option<&str>| Access {
3123 declared: caps(declared),
3124 granted: granted.map(caps),
3125 };
3126 let listed = access(r#"{ "application": true, "homeDir": true }"#, None);
3127 assert!(listed.allows_application() && listed.allows_home_dir());
3128 let application = access(r#"{ "application": true }"#, None);
3129 assert!(application.allows_application() && !application.allows_home_dir());
3130 let narrowed = access(
3131 r#"{ "application": true, "homeDir": true }"#,
3132 Some(r#"{ "homeDir": true }"#),
3133 );
3134 assert!(!narrowed.allows_application() && narrowed.allows_home_dir());
3135 assert!(!access(r#"{ "application": false }"#, None).allows_application());
3136 assert!(Capabilities::from_json(&serde_json::json!({ "application": "yes" })).is_err());
3137 assert!(Capabilities::from_json(&serde_json::json!({ "homeDir": 1 })).is_err());
3138 let both = caps(r#"{ "application": true, "homeDir": true }"#);
3140 assert_eq!(Capabilities::from_json(&both.to_json()).unwrap(), both);
3141 let none = Capabilities::default().to_json();
3142 assert!(none.get("application").is_none() && none.get("homeDir").is_none());
3143 }
3144
3145 #[test]
3146 fn host_functions_need_an_explicit_grant() {
3147 let all = Access::all();
3150 assert!(all.allows_clipboard());
3151 assert!(!all.allows_host("getUserInfo"));
3152 let access = |json: &str| Access {
3153 declared: caps(json),
3154 granted: None,
3155 };
3156 let every = access(r#"{ "host": true }"#);
3157 assert!(every.allows_host("getUserInfo") && every.allows_host("bridge.call"));
3158 assert!(!access(r#"{ "host": false }"#).allows_host("getUserInfo"));
3159 let listed = access(r#"{ "host": ["getUserInfo", "bridge.*"] }"#);
3160 assert!(listed.allows_host("getUserInfo"));
3161 assert!(listed.allows_host("bridge.share"));
3162 assert!(!listed.allows_host("getUserInfoX"));
3163 assert!(!listed.allows_host("bridge"));
3164 assert!(Capabilities::from_json(&serde_json::json!({ "host": ["a*b"] })).is_err());
3165 assert!(Capabilities::from_json(&serde_json::json!({ "host": [""] })).is_err());
3166 let narrowed = Access {
3168 declared: caps(r#"{ "host": true }"#),
3169 granted: Some(caps(r#"{ "host": ["bridge.*"] }"#)),
3170 };
3171 assert!(narrowed.allows_host("bridge.call") && !narrowed.allows_host("getUserInfo"));
3172 }
3173
3174 #[test]
3175 fn trusted_web_input_needs_an_explicit_grant() {
3176 let all = Access::all();
3178 assert!(all.allows_webviews() && !all.allows_web_input());
3179 let access = |json: &str| Access {
3180 declared: caps(json),
3181 granted: None,
3182 };
3183 let input = r#"{ "webview": { "hosts": ["example.com"], "input": true } }"#;
3184 assert!(access(input).allows_web_input());
3185 assert!(!access(r#"{ "webview": { "hosts": ["example.com"] } }"#).allows_web_input());
3186 assert!(!access(r#"{ "webview": { "input": false } }"#).allows_web_input());
3187 assert!(
3188 Capabilities::from_json(&serde_json::json!({ "webview": { "input": "yes" } })).is_err()
3189 );
3190 assert_eq!(
3192 Capabilities::from_json(&caps(input).to_json()),
3193 Ok(caps(input))
3194 );
3195 let narrowed = Access {
3196 declared: caps(input),
3197 granted: Some(caps(r#"{ "webview": { "hosts": ["*"] } }"#)),
3198 };
3199 assert!(!narrowed.allows_web_input());
3200 }
3201
3202 #[test]
3203 fn web_media_needs_an_explicit_grant() {
3204 let all = Access::all();
3205 assert!(!all.allows_web_media(WebMedia::Microphone));
3206 let access = |json: &str| Access {
3207 declared: caps(json),
3208 granted: None,
3209 };
3210 let mic = r#"{ "webview": { "hosts": ["example.com"], "media": ["microphone"] } }"#;
3211 assert!(access(mic).allows_web_media(WebMedia::Microphone));
3212 assert!(!access(mic).allows_web_media(WebMedia::Camera));
3213 assert!(
3214 Capabilities::from_json(&serde_json::json!({ "webview": { "media": ["screen"] } }))
3215 .is_err()
3216 );
3217 assert_eq!(Capabilities::from_json(&caps(mic).to_json()), Ok(caps(mic)));
3218 let narrowed = Access {
3219 declared: caps(mic),
3220 granted: Some(caps(r#"{ "webview": { "hosts": ["*"] } }"#)),
3221 };
3222 assert!(!narrowed.allows_web_media(WebMedia::Microphone));
3223 }
3224
3225 #[test]
3230 fn page_owned_blob_urls_follow_the_origin_they_embed() {
3231 let a = Access {
3232 declared: caps(
3233 r#"{ "webview": { "hosts": ["app.example.com", "*.app.example.com"] } }"#,
3234 ),
3235 granted: None,
3236 };
3237 for url in [
3238 "blob:https://app.example.com/uuid",
3239 "blob:http://app.example.com:6711/uuid",
3240 "blob:https://docs.app.example.com/uuid",
3241 "BLOB:HTTPS://APP.EXAMPLE.COM/uuid",
3242 ] {
3243 assert!(a.allows_webview(url), "{url}");
3244 }
3245 for url in [
3246 "blob:https://bank.example/uuid",
3247 "blob:https://app.example.com.evil.example/uuid",
3248 "blob:https://app.example.com@bank.example/uuid",
3249 "blob:null/uuid",
3250 "blob:data:text/html,hi",
3251 "blob:file:///etc/passwd",
3252 "blob:",
3253 "blob:https://",
3254 ] {
3255 assert!(!a.allows_webview(url), "{url}");
3256 }
3257 let denied = Access {
3259 declared: caps("{}"),
3260 granted: None,
3261 };
3262 assert!(!denied.allows_webview("blob:https://app.example.com/uuid"));
3263 let narrowed = Access {
3265 granted: Some(caps(r#"{ "webview": { "hosts": ["app.example.com"] } }"#)),
3266 ..a.clone()
3267 };
3268 assert!(narrowed.allows_webview("blob:https://app.example.com/uuid"));
3269 assert!(!narrowed.allows_webview("blob:https://docs.app.example.com/uuid"));
3270 let local = Access {
3272 declared: caps(r#"{ "webview": { "hosts": ["127.0.0.1"] } }"#),
3273 granted: None,
3274 };
3275 assert!(
3276 local.allows_webview("blob:http://127.0.0.1:6711/6f3c2f0e-8a1d-4c5e-9b7a-0d2e4f6a8b1c")
3277 );
3278 assert!(a.allows_webview("https://app.example.com/page"));
3281 assert!(!a.allows_webview("https://bank.example/page"));
3282 let ambiguous = "blob:https://app.example.com\\@bank.example/uuid";
3285 assert!(!a.allows_webview(ambiguous));
3286 let any = Access {
3287 declared: caps(r#"{ "webview": { "hosts": ["*"] } }"#),
3288 granted: None,
3289 };
3290 assert!(any.allows_webview(ambiguous));
3291 }
3292
3293 #[test]
3294 fn host_function_names_and_grants_keep_to_their_charset() {
3295 for good in ["getUserInfo", "user.info", "a-b_c:d.E9", &"a".repeat(128)] {
3296 assert!(valid_host_name(good), "{good}");
3297 }
3298 for bad in [
3299 "",
3300 "user.x/../../admin",
3301 "a..b",
3302 "user x",
3303 "a\\b",
3304 "caf\u{e9}",
3305 "ok\u{0}",
3306 "a*",
3307 &"a".repeat(129),
3308 ] {
3309 assert!(!valid_host_name(bad), "{bad:?}");
3310 }
3311 let parses =
3312 |grant: &str| Capabilities::from_json(&serde_json::json!({ "host": [grant] })).is_ok();
3313 assert!(parses("*") && parses("user.*") && parses("user.info"));
3314 for bad in ["user/*", "a..*", "../*", "a b", "**"] {
3315 assert!(!parses(bad), "{bad}");
3316 }
3317 }
3318
3319 #[test]
3320 fn hosts_and_finer_grants() {
3321 let c = caps(
3322 r#"{ "network": {
3323 "hosts": ["*.example.org"],
3324 "http": [{ "host": "api.example.com", "methods": ["get"], "pathPrefix": "/v1/" }]
3325 } }"#,
3326 );
3327 let a = Access {
3328 declared: c,
3329 granted: None,
3330 };
3331 assert!(a.allows_http("POST", "https://api.example.org/x"));
3332 assert!(!a.allows_http("GET", "https://example.org/"));
3333 assert!(!a.allows_http("GET", "https://example.org.evil.io/"));
3334 assert!(!a.allows_http("GET", "https://evilexample.org/"));
3335 assert!(a.allows_http("GET", "https://API.example.com/v1/quote"));
3336 assert!(!a.allows_http("POST", "https://api.example.com/v1/quote"));
3337 assert!(!a.allows_http("GET", "https://api.example.com/v2/"));
3338 assert!(!a.allows_http("GET", "file://api.example.com/v1/"));
3339 assert!(!a.allows_http("GET", "https://api.example.org@evil.io/"));
3341 assert!(a.allows_http("GET", "https://user:pw@api.example.org:8443/"));
3342 }
3343
3344 #[test]
3351 fn urls_that_parsers_read_as_different_hosts_are_refused() {
3352 let hosts = r#"["docs.example.com", "*.docs.example.com"]"#;
3353 let a = Access {
3354 declared: caps(&format!(
3355 r#"{{ "network": {{ "hosts": {hosts} }}, "webview": {{ "hosts": {hosts} }} }}"#
3356 )),
3357 granted: None,
3358 };
3359 for url in [
3360 "https://bank.example\\@docs.example.com/",
3362 "https://bank.example:443\\@docs.example.com/",
3363 "https://[::1]\\@docs.example.com/",
3364 "https://bank.example\\.docs.example.com/",
3366 "https://docs.example.com\\@bank.example/",
3368 "https://docs.example.com/a\\..\\b",
3370 "https://bank.example\0.docs.example.com/",
3372 "https://bank.example\t.docs.example.com/",
3373 "https://bank.example\n.docs.example.com/",
3374 "https://bank.example .docs.example.com/",
3375 "https://bank.example[.docs.example.com/",
3376 "https://x]y.docs.example.com/",
3377 "https://bank%2Eexample.docs.example.com/",
3379 ] {
3380 assert!(!a.allows_webview(url), "{url:?}");
3381 assert!(!a.allows_http("GET", url), "{url:?}");
3382 assert!(!a.allows_media(url), "{url:?}");
3383 }
3384 assert!(!a.allows_websocket("wss://bank.example\\@docs.example.com/"));
3385 for url in [
3388 "https://docs.example.com/a%5Cb",
3389 "https://x.docs.example.com/?q=C:\\x#a\\b",
3390 "https://user:pw@docs.example.com/a b",
3391 ] {
3392 assert!(a.allows_webview(url), "{url:?}");
3393 assert!(a.allows_http("GET", url), "{url:?}");
3394 }
3395 let all = Access {
3397 declared: Capabilities::all(),
3398 granted: None,
3399 };
3400 let query = url::Url::parse("wss://x.example/?q=a\\b").unwrap();
3401 assert!(all.allows_websocket(query.as_str()), "{query}");
3402 assert!(all.allows_media("https://x.example/i.png?p=a\\b"));
3403 }
3404
3405 #[test]
3410 fn only_grants_of_every_host_cover_ambiguous_urls() {
3411 let url = "https://x.example/a\\b.png";
3412 let all = Access {
3413 declared: Capabilities::all(),
3414 granted: None,
3415 };
3416 let any = Access {
3417 declared: caps(r#"{ "network": { "hosts": ["*"] }, "webview": { "hosts": ["*"] } }"#),
3418 granted: None,
3419 };
3420 for a in [&all, &any] {
3421 assert!(a.allows_http("GET", url));
3422 assert!(a.allows_media(url));
3423 assert!(a.allows_webview(url));
3424 assert!(!a.allows_http("GET", "ftp://x.example/a\\b"));
3425 assert!(!a.allows_webview("file://x.example/a\\b"));
3426 assert!(!a.allows_webview("not a url"));
3427 assert!(!a.allows_http("GET", "https://"));
3428 }
3429 let rule = |rule: &str| Access {
3430 declared: caps(&format!(r#"{{ "network": {{ "http": [{rule}] }} }}"#)),
3431 granted: None,
3432 };
3433 let methods = rule(r#"{ "host": "*", "methods": ["get"], "schemes": ["https"] }"#);
3434 assert!(methods.allows_http("GET", url));
3435 assert!(!methods.allows_http("POST", url));
3436 assert!(!methods.allows_http("GET", "http://x.example/a\\b.png"));
3437 for narrowed in [
3438 r#"{ "host": "*", "port": 443 }"#,
3439 r#"{ "host": "*", "pathPrefix": "/a" }"#,
3440 r#"{ "host": "*", "paths": ["/a/b.png"] }"#,
3441 r#"{ "host": "x.example" }"#,
3442 ] {
3443 assert!(!rule(narrowed).allows_http("GET", url), "{narrowed}");
3444 }
3445 }
3446
3447 #[test]
3450 fn granted_urls_are_granted_hosts_for_whatwg() {
3451 let pattern = |p: &str| HostPattern::new(p).unwrap();
3452 let granted = [pattern("docs.example.com"), pattern("*.docs.example.com")];
3453 let a = Access {
3454 declared: caps(
3455 r#"{ "webview": { "hosts": ["docs.example.com", "*.docs.example.com"] } }"#,
3456 ),
3457 granted: None,
3458 };
3459 for url in [
3460 "https://docs.example.com/a",
3461 "https://DOCS.Example.COM/",
3462 "https://docs.example.com./",
3463 "https://x.docs.example.com:8443/",
3464 "https://user:pw@docs.example.com/",
3465 "https://docs.example.com#@bank.example/",
3466 "https://docs.example.com?@bank.example/",
3467 "https://docs.example.com:pass@bank.example/",
3468 "https://docs.example.com%2F@bank.example/",
3469 "https://bank.example\\@docs.example.com/",
3470 "https://bank.example:443\\@docs.example.com/",
3471 "https://[::1]\\@docs.example.com/",
3472 "https://bank.example\\.docs.example.com/",
3473 "https://docs.example.com\\@bank.example/",
3474 "https://bank.example\0.docs.example.com/",
3475 "https://bank.example\t.docs.example.com/",
3476 "https://docs.example.com\n.bank.example/",
3477 "https://bank%2Eexample.docs.example.com/",
3478 "https://docs\u{FF0E}example\u{FF0E}com/",
3479 "https://d\u{043E}cs.example.com/",
3480 "https:\\\\docs.example.com\\",
3481 " https://docs.example.com/",
3482 "https://docs.example.com /",
3483 "https://bank.example .docs.example.com/",
3484 "https://bank.example^.docs.example.com/",
3485 "https://bank.example[.docs.example.com/",
3486 "https://x]y.docs.example.com/",
3487 "https://a@bank.example@docs.example.com/",
3488 "https://..docs.example.com/",
3489 "HTTPS://DOCS.EXAMPLE.COM/",
3490 "https://x.docs.example.com/?q=C:\\x",
3491 ] {
3492 if a.allows_webview(url) {
3493 let whatwg = url::Url::parse(url).unwrap_or_else(|e| panic!("{url:?}: {e}"));
3494 let host = whatwg.host_str().unwrap_or_default().trim_end_matches('.');
3495 assert!(granted.iter().any(|p| p.matches(host)), "{url:?}: {host}");
3496 }
3497 }
3498 }
3499
3500 #[test]
3501 fn the_embedder_grants_at_most() {
3502 let a = Access {
3503 declared: caps(
3504 r#"{ "network": { "hosts": ["a.com", "b.com"] }, "statusBar": true, "clipboard": true, "picker": true, "speech": true, "audio": true }"#,
3505 ),
3506 granted: Some(caps(
3507 r#"{ "network": { "hosts": ["b.com"] }, "clipboard": true }"#,
3508 )),
3509 };
3510 assert!(a.allows_clipboard());
3511 assert!(!a.allows_http("GET", "https://a.com/"));
3512 assert!(!a.allows_picker());
3513 assert!(!a.allows_speech());
3514 assert!(!a.allows_audio());
3515 assert!(a.allows_http("GET", "https://b.com/"));
3516 assert!(!a.allows_status_bar());
3517 }
3518
3519 #[test]
3520 fn typos_are_errors() {
3521 let bad =
3522 |json: &str| Capabilities::from_json(&serde_json::from_str(json).unwrap()).unwrap_err();
3523 assert!(bad(r#"{ "netwrok": {} }"#).contains("unknown key `netwrok`"));
3524 assert!(bad(r#"{ "network": { "host": [] } }"#).contains("unknown key `host`"));
3525 assert!(bad(r#"{ "network": { "hosts": ["exa mple.com"] } }"#).contains("invalid host"));
3526 let c = caps(
3527 r#"{ "network": { "hosts": ["a.com"], "http": [{ "host": "b.com", "methods": ["GET"] }] }, "webview": { "hosts": ["*"] } }"#,
3528 );
3529 assert_eq!(Capabilities::from_json(&c.to_json()).unwrap(), c);
3530 }
3531
3532 #[test]
3535 fn unknown_keys_in_packages_grant_nothing() {
3536 let lenient =
3537 |json: &str| Capabilities::from_json_lenient(&serde_json::from_str(json).unwrap());
3538 let (c, dropped) = lenient(
3539 r#"{ "bluetooth": true, "clipboard": true,
3540 "network": { "hosts": ["a.com"], "http": [
3541 { "host": "b.com", "ports": [443] },
3542 { "host": "c.com", "methods": ["GET"] }
3543 ] } }"#,
3544 )
3545 .unwrap();
3546 assert!(c.clipboard);
3547 assert_eq!(c.network.hosts, [HostPattern::new("a.com").unwrap()]);
3548 assert_eq!(c.network.http.len(), 1);
3549 assert_eq!(c.network.http[0].host.as_str(), "c.com");
3550 assert_eq!(
3551 dropped,
3552 [
3553 "capabilities.bluetooth",
3554 "capabilities.network.http[0] (unknown key `ports`)"
3555 ]
3556 );
3557 let (c, dropped) =
3558 lenient(r#"{ "network": { "hosts": ["a.com"], "ipv6": false }, "webview": { "hosts": ["*"], "x": 1 } }"#)
3559 .unwrap();
3560 assert_eq!(c, Capabilities::default());
3561 assert_eq!(dropped.len(), 2);
3562 let (c, dropped) = lenient(
3566 r#"{ "statusBar": "yes", "clipboard": true,
3567 "network": { "hosts": ["exa mple.com"] }, "webview": { "hosts": ["a.com"] } }"#,
3568 )
3569 .unwrap();
3570 assert!(!c.status_bar);
3571 assert!(c.clipboard);
3572 assert!(c.network.hosts.is_empty());
3573 assert_eq!(c.webview, Some(vec![HostPattern::new("a.com").unwrap()]));
3574 assert_eq!(dropped.len(), 2, "{dropped:?}");
3575 assert!(
3576 dropped
3577 .iter()
3578 .any(|d| d.starts_with("capabilities.statusBar ("))
3579 );
3580 assert!(
3581 dropped
3582 .iter()
3583 .any(|d| d.starts_with("capabilities.network ("))
3584 );
3585 let (c, dropped) = lenient(
3587 r#"{ "network": { "hosts": ["a.com"], "http": [
3588 { "host": "b.com", "port": "any" }, { "host": "c.com" } ] } }"#,
3589 )
3590 .unwrap();
3591 assert_eq!(c.network.hosts.len(), 1);
3592 assert_eq!(c.network.http.len(), 1);
3593 assert_eq!(c.network.http[0].host.as_str(), "c.com");
3594 assert_eq!(dropped.len(), 1, "{dropped:?}");
3595 assert!(dropped[0].starts_with("capabilities.network.http[0] ("));
3596 let (c, dropped) = lenient(r#""everything""#).unwrap();
3598 assert_eq!(c, Capabilities::default());
3599 assert_eq!(dropped.len(), 1);
3600 assert!(Capabilities::from_json(&serde_json::json!({ "statusBar": "yes" })).is_err());
3602 let json = serde_json::json!({ "network": { "hosts": ["a.com"] }, "statusBar": true });
3604 let (c, dropped) = Capabilities::from_json_lenient(&json).unwrap();
3605 assert_eq!(c, Capabilities::from_json(&json).unwrap());
3606 assert!(dropped.is_empty());
3607 }
3608
3609 #[test]
3610 fn media_redirects_are_checked() {
3611 let a = Access {
3612 declared: Capabilities::from_json(
3613 &serde_json::json!({ "network": { "hosts": ["a.com"] } }),
3614 )
3615 .unwrap(),
3616 granted: None,
3617 };
3618 let from = "https://a.com/x/y.png";
3619 assert_eq!(
3620 a.media_redirect(from, "/z.png").unwrap(),
3621 "https://a.com/z.png"
3622 );
3623 assert_eq!(
3624 a.media_redirect(from, "z.png").unwrap(),
3625 "https://a.com/x/z.png"
3626 );
3627 assert!(a.media_redirect(from, "https://b.com/z.png").is_err());
3628 assert!(a.media_redirect(from, "//b.com/z.png").is_err());
3629 assert!(a.media_redirect(from, "file:///etc/passwd").is_err());
3630 assert!(
3631 Access::default()
3632 .media_redirect(from, "//b.com/z.png")
3633 .is_ok()
3634 );
3635 assert!(
3636 Access::default()
3637 .media_redirect(from, "ftp://b.com/z.png")
3638 .is_err()
3639 );
3640 }
3641
3642 #[test]
3646 fn http_paths_are_matched_as_whatwg_resolves_them() {
3647 let a = Access {
3648 declared: caps(
3649 r#"{ "network": { "http": [{ "host": "api.example.com", "pathPrefix": "/public" }] } }"#,
3650 ),
3651 granted: None,
3652 };
3653 for url in [
3654 "https://api.example.com/public/../private",
3655 "https://api.example.com/public/%2e%2e/private",
3656 "https://api.example.com/public/%2E%2E/private",
3657 "https://api.example.com/public/.%2e/private",
3658 "https://api.example.com/public/./../private",
3659 ] {
3660 assert!(!a.allows_http("GET", url), "{url}");
3661 assert!(!a.allows_media(url), "{url}");
3662 }
3663 for url in [
3664 "https://api.example.com/public/x",
3665 "https://api.example.com/private/../public/x",
3666 "https://api.example.com/public/./x",
3667 ] {
3668 assert!(a.allows_http("GET", url), "{url}");
3669 }
3670 }
3671
3672 #[test]
3675 fn redirects_resolve_dot_segments() {
3676 assert_eq!(
3677 resolve_reference("https://api.example.com/public/x", "../private"),
3678 "https://api.example.com/private"
3679 );
3680 assert_eq!(
3681 resolve_reference("https://api.example.com/public/x", "%2e%2e/private"),
3682 "https://api.example.com/private"
3683 );
3684 let a = Access {
3685 declared: caps(
3686 r#"{ "network": { "http": [{ "host": "api.example.com", "pathPrefix": "/public" }] } }"#,
3687 ),
3688 granted: None,
3689 };
3690 let from = "https://api.example.com/public/a.png";
3691 assert!(a.media_redirect(from, "b.png").is_ok());
3692 assert!(a.media_redirect(from, "../private.png").is_err());
3693 assert!(a.media_redirect(from, "/public/../private.png").is_err());
3694 }
3695
3696 #[test]
3700 fn media_sources_that_name_a_host_are_checked() {
3701 let a = Access {
3702 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
3703 granted: None,
3704 };
3705 for uri in [
3706 "//bank.example/x.png",
3707 "\\\\bank.example\\x.png",
3708 "/\\bank.example/x.png",
3709 "https:\\\\bank.example\\x.png",
3710 "https:/bank.example/x.png",
3711 "HTTPS://bank.example/x.png",
3712 ] {
3713 assert!(!a.allows_media(uri), "{uri}");
3714 }
3715 for uri in [
3717 "asset:/a.png",
3718 "data:image/png;base64,AAAA",
3719 "blob:https://app.example/1",
3720 "https://docs.example.com/x.png",
3721 ] {
3722 assert!(a.allows_media(uri), "{uri}");
3723 }
3724 assert!(!a.allows_media("img/a.png"));
3727 assert!(Access::default().allows_media("//bank.example/x.png"));
3729 }
3730
3731 #[test]
3735 fn media_sources_are_read_after_whatwg_strips_them() {
3736 let a = Access {
3737 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
3738 granted: None,
3739 };
3740 let page = Some("https://app.example/index.html");
3741 for uri in [
3742 "\t//bank.example/x.png",
3743 "\n//bank.example/x.png",
3744 "/\t/bank.example/x.png",
3745 " https://bank.example/x.png",
3746 "https://bank.example/x.png ",
3747 "ht\ttps://bank.example/x.png",
3748 "\u{1}https://bank.example/x.png",
3749 ] {
3750 assert_eq!(a.media_url(uri, page, None), None, "{uri:?} on the web");
3751 assert_eq!(
3752 a.media_url(uri, None, None),
3753 None,
3754 "{uri:?} in a native app"
3755 );
3756 }
3757 assert_eq!(
3759 a.media_url(" icons/a.png", page, None),
3760 Some(Cow::Borrowed(" icons/a.png"))
3761 );
3762 let local = Access {
3764 declared: caps(r#"{ "network": { "hosts": ["127.0.0.1"] } }"#),
3765 granted: None,
3766 };
3767 assert_eq!(
3768 local.media_url("http://0x7f.1/a.png", None, None),
3769 Some(Cow::Owned("http://127.0.0.1/a.png".into()))
3770 );
3771 assert_eq!(a.media_url("http://0x7f.1/a.png", None, None), None);
3772 for own in [
3774 "DATA:image/png;base64,AA",
3775 "Asset:/a.png",
3776 "BLOB:https://app.example/1",
3777 ] {
3778 assert_eq!(
3779 a.media_url(own, page, None),
3780 Some(Cow::Borrowed(own)),
3781 "{own}"
3782 );
3783 }
3784 }
3785
3786 #[test]
3792 fn whitespace_around_a_granted_url_loads_its_serialization() {
3793 let a = Access {
3794 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
3795 granted: None,
3796 };
3797 let page = Some("https://app.example/index.html");
3798 for (uri, base) in [
3799 ("https://docs.example.com/x.png ", None),
3800 (" https://docs.example.com/x.png", None),
3801 ("\u{1}https://docs.example.com/x.png", None),
3802 ("\t//docs.example.com/x.png", page),
3803 ] {
3804 assert_eq!(
3805 a.media_url(uri, base, None),
3806 Some(Cow::Owned("https://docs.example.com/x.png".into())),
3807 "{uri:?}"
3808 );
3809 }
3810 assert_eq!(a.media_url("https://bank.example/x.png ", None, None), None);
3813 for inside in [
3814 "https://docs.example.com/x\u{1}.png",
3815 "https://docs.ex\tample.com/x.png",
3816 "ht\ntps://docs.example.com/x.png",
3817 ] {
3818 assert_eq!(a.media_url(inside, None, None), None, "{inside:?}");
3819 }
3820 }
3821
3822 #[test]
3827 fn grant_paths_match_as_requests_send_them() {
3828 let a = Access {
3829 declared: caps(
3830 r#"{ "network": { "http": [
3831 { "host": "cdn.example.com", "pathPrefix": "/my photos" },
3832 { "host": "cdn.example.com", "paths": ["/über.png", "/{id}.png"] }
3833 ] } }"#,
3834 ),
3835 granted: None,
3836 };
3837 for url in [
3838 "https://cdn.example.com/my photos/a.png",
3839 "https://cdn.example.com/my%20photos/a.png",
3840 "https://cdn.example.com/über.png",
3841 "https://cdn.example.com/{id}.png",
3842 ] {
3843 assert!(a.allows_http("GET", url), "{url}");
3844 assert!(a.media_url(url, None, None).is_some(), "{url}");
3845 }
3846 assert!(!a.allows_http("GET", "https://cdn.example.com/my photosx/a.png"));
3847 for bad in [
3850 "/a/../b",
3851 "/./a",
3852 "/a/%2e%2e/b",
3853 "/a/.%2E",
3854 "/public\\..\\private",
3855 "/a/.\t./b",
3856 "/a/.\n/b",
3857 ] {
3858 let json = serde_json::json!({ "network": { "http": [{ "host": "h.example", "pathPrefix": bad }] } });
3859 assert!(Capabilities::from_json(&json).is_err(), "{bad}");
3860 }
3861 }
3862
3863 #[cfg(unix)]
3869 #[test]
3870 fn paths_outside_the_roots_are_refused_without_disk_work() {
3871 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
3872 let root = base.join(format!("media-text-{}", std::process::id()));
3873 let _ = std::fs::remove_dir_all(&root);
3874 std::fs::create_dir_all(root.join("allowed")).unwrap();
3875 std::fs::create_dir_all(root.join("elsewhere")).unwrap();
3876 std::fs::write(root.join("allowed/a.png"), b"png").unwrap();
3877 std::os::unix::fs::symlink(root.join("allowed"), root.join("elsewhere/in")).unwrap();
3879 let allowed = root.join("allowed");
3880 let access = Access {
3881 declared: Capabilities::from_json(
3882 &serde_json::json!({ "fs": { "read": [allowed.to_str().unwrap()] } }),
3883 )
3884 .unwrap(),
3885 granted: None,
3886 };
3887 let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
3888 let resolves = || RESOLVES.with(Cell::get);
3889 let before = resolves();
3890 for outside in [
3891 root.join("elsewhere/x.png"),
3892 root.join("elsewhere/in/a.png"),
3893 PathBuf::from("/Volumes/hung/x.png"),
3894 ] {
3895 assert_eq!(files.readable(&outside), None, "{}", outside.display());
3896 }
3897 assert_eq!(
3898 resolves(),
3899 before,
3900 "outside the roots, nothing was resolved"
3901 );
3902 assert!(files.readable(&allowed.join("a.png")).is_some());
3904 assert!(
3905 files
3906 .readable(&canonicalize(&allowed).unwrap().join("a.png"))
3907 .is_some()
3908 );
3909 assert_eq!(resolves(), before + 2);
3910 let _ = std::fs::remove_dir_all(&root);
3911 }
3912
3913 #[cfg(unix)]
3917 #[test]
3918 fn a_granted_file_replaced_by_a_symlink_is_refused() {
3919 use std::os::unix::fs::symlink;
3920 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
3921 let root = base.join(format!("media-swap-{}", std::process::id()));
3922 let _ = std::fs::remove_dir_all(&root);
3923 std::fs::create_dir_all(root.join("allowed")).unwrap();
3924 let root = canonicalize(&root).unwrap();
3925 std::fs::write(root.join("allowed/image.png"), b"public").unwrap();
3926 std::fs::write(root.join("secret.png"), b"secret").unwrap();
3927 let allowed = root.join("allowed").to_str().unwrap().to_owned();
3928 let access = Access {
3929 declared: Capabilities::from_json(
3930 &serde_json::json!({ "fs": { "read": [allowed.clone()] } }),
3931 )
3932 .unwrap(),
3933 granted: None,
3934 };
3935 let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
3936 let src = format!("{allowed}/image.png");
3937 assert!(access.media_url(&src, None, Some(&files)).is_some());
3938 std::fs::remove_file(root.join("allowed/image.png")).unwrap();
3939 symlink(root.join("secret.png"), root.join("allowed/image.png")).unwrap();
3940 assert_eq!(access.media_url(&src, None, Some(&files)), None);
3941 let _ = std::fs::remove_dir_all(&root);
3942 }
3943
3944 #[test]
3949 fn bundled_files_stay_inside_the_app_files() {
3950 let a = Access {
3951 declared: caps(r#"{ "network": { "hosts": ["*"] } }"#),
3952 granted: None,
3953 };
3954 for escape in [
3955 "asset:/../outside.png",
3956 "asset:/sub/../../outside.png",
3957 "asset:/%2E%2e/outside.png",
3958 "asset:/..%2Foutside.png",
3959 "asset:/a%5c..%5c..%5coutside.png",
3960 "asset:/a.png?/../../outside.png",
3961 "asset:/a.png#/../../outside.png",
3962 "asset://Users/a/outside.png",
3963 "asset:/C:/outside.png",
3964 "asset:/./a.png",
3965 "asset:../outside.png",
3966 "ASSET:/../outside.png",
3967 ] {
3968 assert_eq!(a.media_url(escape, None, None), None, "{escape}");
3969 assert_eq!(
3970 a.media_url(escape, Some("https://app.example/"), None),
3971 None,
3972 "{escape} on the web"
3973 );
3974 assert_eq!(media_grant_advice(escape, None), ASSET_ADVICE, "{escape}");
3975 assert_eq!(media_capability(escape, None), "fs", "{escape}");
3976 }
3977 for inside in [
3978 "asset:/a.png",
3979 "asset:/@app/icons/a.png",
3980 "asset:/a.png?v=2",
3981 "asset:/a%20b.png",
3982 "asset:/sub/a..b.png",
3983 "ASSET:/a.png",
3984 ] {
3985 assert_eq!(
3986 a.media_url(inside, None, None),
3987 Some(Cow::Borrowed(inside)),
3988 "{inside}"
3989 );
3990 }
3991 assert_eq!(
3993 Access::default().media_url("asset:/../outside.png", None, None),
3994 Some(Cow::Borrowed("asset:/../outside.png"))
3995 );
3996 }
3997
3998 #[test]
4003 fn relative_paths_name_no_file_in_a_native_app() {
4004 let a = Access {
4005 declared: caps(r#"{ "network": { "hosts": ["*"] } }"#),
4006 granted: None,
4007 };
4008 for relative in [
4009 "clip.mp4",
4010 "./clip.mp4",
4011 "Users/a/secret.mp4",
4012 "../etc/x.png",
4013 " /etc/x.png",
4014 ] {
4015 assert_eq!(a.media_url(relative, None, None), None, "{relative}");
4016 assert_eq!(media_capability(relative, None), "fs", "{relative}");
4017 assert_eq!(
4018 media_grant_advice(relative, None),
4019 RELATIVE_ADVICE,
4020 "{relative}"
4021 );
4022 assert_eq!(
4023 a.media_url(relative, Some("https://app.example/"), None),
4024 Some(Cow::Borrowed(relative)),
4025 "{relative} on the web"
4026 );
4027 assert_eq!(
4028 Access::default().media_url(relative, None, None),
4029 Some(Cow::Borrowed(relative)),
4030 "{relative} without capabilities"
4031 );
4032 }
4033 for empty in ["", " "] {
4035 assert_eq!(a.media_url(empty, None, None), Some(Cow::Borrowed(empty)));
4036 }
4037 }
4038
4039 #[cfg(unix)]
4042 #[test]
4043 fn media_files_open_inside_their_root() {
4044 use std::io::Read;
4045 let base = std::env::temp_dir().join(format!("media-open-{}", std::process::id()));
4046 let _ = std::fs::remove_dir_all(&base);
4047 std::fs::create_dir_all(base.join("allowed")).unwrap();
4048 let base = canonicalize(&base).unwrap();
4049 std::fs::write(base.join("allowed/a.png"), b"public").unwrap();
4050 std::fs::write(base.join("secret.png"), b"secret").unwrap();
4051 let allowed = base.join("allowed");
4052 let access = Access {
4053 declared: Capabilities::from_json(
4054 &serde_json::json!({ "fs": { "read": [allowed.to_str().unwrap()] } }),
4055 )
4056 .unwrap(),
4057 granted: None,
4058 };
4059 let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
4060 let path = allowed.join("a.png");
4061 let read = |path: &Path| {
4062 let mut text = String::new();
4063 files.open(path)?.ok()?.read_to_string(&mut text).ok()?;
4064 Some(text)
4065 };
4066 assert_eq!(read(&path).as_deref(), Some("public"));
4067 std::fs::remove_file(&path).unwrap();
4069 std::os::unix::fs::symlink(base.join("secret.png"), &path).unwrap();
4070 assert!(matches!(files.open(&path), Some(Err(_))));
4071 assert!(matches!(files.open(&base.join("secret.png")), Some(Err(_))));
4072 assert!(MediaFiles::default().open(&path).is_none());
4074 std::fs::create_dir_all(base.join("allowed/sub")).unwrap();
4077 std::fs::write(base.join("allowed/sub/ok.png"), b"ok").unwrap();
4078 std::os::unix::fs::symlink(
4079 base.join("allowed/a.png"),
4080 base.join("allowed/sub/link.png"),
4081 )
4082 .unwrap();
4083 std::fs::remove_file(&path).unwrap();
4084 std::fs::write(&path, b"public").unwrap();
4085 let narrowed = Access {
4086 declared: access.declared.clone(),
4087 granted: Some(
4088 Capabilities::from_json(&serde_json::json!({
4089 "fs": { "read": [allowed.join("sub").to_str().unwrap()] }
4090 }))
4091 .unwrap(),
4092 ),
4093 };
4094 let files = MediaFiles::new(&narrowed, None, &TrustedPaths::default(), true);
4095 let mut text = String::new();
4096 files
4097 .open(&allowed.join("sub/ok.png"))
4098 .unwrap()
4099 .unwrap()
4100 .read_to_string(&mut text)
4101 .unwrap();
4102 assert_eq!(text, "ok");
4103 assert!(matches!(
4104 files.open(&allowed.join("sub/link.png")),
4105 Some(Err(_))
4106 ));
4107 assert!(matches!(files.open(&path), Some(Err(_))));
4108 let localhost = format!("file://localhost{}", allowed.join("sub/link.png").display());
4110 assert_eq!(narrowed.media_url(&localhost, None, Some(&files)), None);
4111 let ok = format!("file://localhost{}", allowed.join("sub/ok.png").display());
4112 assert!(narrowed.media_url(&ok, None, Some(&files)).is_some());
4113 let _ = std::fs::remove_dir_all(&base);
4114 }
4115
4116 #[cfg(unix)]
4120 #[test]
4121 fn a_dangling_symlink_in_a_granted_root_is_refused() {
4122 use std::os::unix::fs::symlink;
4123 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
4124 let root = base.join(format!("media-dangling-{}", std::process::id()));
4125 let _ = std::fs::remove_dir_all(&root);
4126 std::fs::create_dir_all(root.join("allowed")).unwrap();
4127 let root = canonicalize(&root).unwrap();
4128 symlink(root.join("secret.png"), root.join("allowed/link.png")).unwrap();
4129 let allowed = root.join("allowed").to_str().unwrap().to_owned();
4130 let access = Access {
4131 declared: Capabilities::from_json(
4132 &serde_json::json!({ "fs": { "read": [allowed.clone()] } }),
4133 )
4134 .unwrap(),
4135 granted: None,
4136 };
4137 let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
4138 assert_eq!(
4139 access.media_url(&format!("{allowed}/link.png"), None, Some(&files)),
4140 None
4141 );
4142 let missing = format!("{allowed}/later.png");
4144 assert_eq!(
4145 access.media_url(&missing, None, Some(&files)),
4146 Some(Cow::Borrowed(missing.as_str()))
4147 );
4148 let _ = std::fs::remove_dir_all(&root);
4149 }
4150
4151 #[cfg(unix)]
4156 #[test]
4157 fn local_media_files_need_an_fs_read_grant() {
4158 use std::os::unix::fs::symlink;
4159 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
4160 let root = base.join(format!("media-files-{}", std::process::id()));
4161 let _ = std::fs::remove_dir_all(&root);
4162 std::fs::create_dir_all(root.join("allowed")).unwrap();
4163 std::fs::create_dir_all(root.join("outside")).unwrap();
4164 std::fs::write(root.join("allowed/a.png"), b"png").unwrap();
4165 std::fs::write(root.join("outside/b.png"), b"png").unwrap();
4166 symlink(root.join("outside"), root.join("allowed/link")).unwrap();
4167 let root = canonicalize(&root).unwrap();
4169 let data = root.join("allowed");
4170 let access = Access {
4171 declared: caps(
4172 r#"{ "network": { "hosts": ["docs.example.com"] }, "fs": { "read": ["${dataDir}"] } }"#,
4173 ),
4174 granted: None,
4175 };
4176 let files = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), true);
4177 let real = canonicalize(&data).unwrap();
4178 let path = |p: &Path| p.to_str().unwrap().to_owned();
4179 let load = |uri: &str| {
4180 access
4181 .media_url(uri, None, Some(&files))
4182 .map(Cow::into_owned)
4183 };
4184
4185 let granted = path(&real.join("a.png"));
4186 assert_eq!(load(&path(&data.join("a.png"))), Some(granted.clone()));
4187 assert_eq!(
4188 load(&format!("file://{}", path(&data.join("a.png")))),
4189 Some(format!("file://{granted}"))
4190 );
4191 assert_eq!(
4192 load(&format!("FILE://{}", path(&data.join("a.png")))),
4193 Some(format!("file://{granted}"))
4194 );
4195 assert_eq!(load(&path(&data.join("../outside/b.png"))), None);
4197 assert_eq!(
4198 load(&format!("file://{}/%2e%2e/outside/b.png", path(&data))),
4199 None
4200 );
4201 assert_eq!(load(&path(&data.join("link/b.png"))), None);
4202 assert_eq!(load(&path(&root.join("outside/b.png"))), None);
4203 assert_eq!(
4205 access.media_url(&path(&data.join("a.png")), None, None),
4206 None
4207 );
4208 let mobile = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), false);
4209 assert_eq!(
4210 access.media_url(&path(&data.join("a.png")), None, Some(&mobile)),
4211 None
4212 );
4213 let network_only = Access {
4214 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
4215 granted: None,
4216 };
4217 let none = MediaFiles::new(&network_only, Some(&data), &TrustedPaths::default(), true);
4218 assert_eq!(
4219 network_only.media_url(&path(&data.join("a.png")), None, Some(&none)),
4220 None
4221 );
4222 let narrowed = Access {
4224 declared: caps(r#"{ "fs": { "read": ["${dataDir}"] } }"#),
4225 granted: Some(caps(r#"{ "fs": { "read": ["${dataDir}/sub"] } }"#)),
4226 };
4227 let files = MediaFiles::new(&narrowed, Some(&data), &TrustedPaths::default(), true);
4228 assert_eq!(
4229 narrowed.media_url(&path(&data.join("a.png")), None, Some(&files)),
4230 None
4231 );
4232 let page = Some("https://app.example/index.html");
4235 assert_eq!(
4236 access.media_url("/icons/a.png", page, None),
4237 Some(Cow::Borrowed("/icons/a.png"))
4238 );
4239 for local in [
4242 path(&root.join("outside/b.png")),
4243 format!("FILE://{}", path(&root.join("outside/b.png"))),
4244 "C:\\pictures\\x.png".to_owned(),
4245 "/x.png".to_owned(),
4246 ] {
4247 assert_eq!(
4248 Access::default().media_url(&local, None, None),
4249 Some(Cow::Borrowed(local.as_str())),
4250 "{local}"
4251 );
4252 }
4253 let files = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), true);
4255 for _ in 0..2 {
4256 let again = |uri: &str| {
4257 access
4258 .media_url(uri, None, Some(&files))
4259 .map(Cow::into_owned)
4260 };
4261 assert_eq!(again(&path(&data.join("a.png"))), Some(granted.clone()));
4262 assert_eq!(again(&path(&data.join("link/b.png"))), None);
4263 }
4264 let _ = std::fs::remove_dir_all(&root);
4265 }
4266
4267 #[test]
4270 fn refused_media_sources_advise_the_host_they_resolve_to() {
4271 let page = Some("http://localhost:8080/index.html");
4272 assert_eq!(
4274 media_grant_advice("//127.0.0.1:9000/a.png", page),
4275 "add `127.0.0.1` to capabilities.network in nsh.json"
4276 );
4277 assert_eq!(
4279 media_grant_advice("//127.0.0.1:9000/a.png", None),
4280 NO_SCHEME_ADVICE
4281 );
4282 assert_eq!(
4284 media_grant_advice("//127.0.0.1\\a.png", page),
4285 NO_HOST_ADVICE
4286 );
4287 assert_eq!(
4288 media_grant_advice("https://cdn.example.com/a.png", page),
4289 "add `cdn.example.com` to capabilities.network in nsh.json"
4290 );
4291 assert_eq!(
4294 media_grant_advice("/Users/a/x.png", None),
4295 LOCAL_FILE_ADVICE
4296 );
4297 assert_eq!(
4298 media_grant_advice("file:///Users/a/x.png", page),
4299 LOCAL_FILE_ADVICE
4300 );
4301 assert_eq!(media_capability("/Users/a/x.png", None), "fs");
4303 assert_eq!(media_capability("C:\\pictures\\x.png", None), "fs");
4304 assert_eq!(media_capability("FILE:///Users/a/x.png", page), "fs");
4305 assert_eq!(media_capability("/icons/a.png", page), "network");
4306 assert_eq!(
4307 media_capability("https://cdn.example.com/a.png", None),
4308 "network"
4309 );
4310 }
4311
4312 #[test]
4317 fn media_sources_load_the_url_the_check_granted() {
4318 let a = Access {
4319 declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
4320 granted: None,
4321 };
4322 let https = Some("https://app.example/index.html");
4323 let http = Some("http://127.0.0.1:8080/");
4324 let loads = |uri, base| a.media_url(uri, base, None).map(|u| u.into_owned());
4325 assert_eq!(
4326 loads("https://DOCS.example.com/a/../x.png", None).as_deref(),
4327 Some("https://docs.example.com/x.png")
4328 );
4329 assert_eq!(
4330 loads("//docs.example.com/x.png", https).as_deref(),
4331 Some("https://docs.example.com/x.png")
4332 );
4333 assert_eq!(
4334 loads("//docs.example.com/x.png", http).as_deref(),
4335 Some("http://docs.example.com/x.png")
4336 );
4337 assert_eq!(loads("\\\\docs.example.com\\x.png", https), None);
4341 assert_eq!(loads("//docs.example.com/x.png", None), None);
4342 assert_eq!(loads("//bank.example/x.png", https), None);
4343 for own in ["asset:/a.png", "img/a.png", "data:image/png;base64,AAAA"] {
4344 assert!(
4345 matches!(a.media_url(own, https, None), Some(std::borrow::Cow::Borrowed(u)) if u == own),
4346 "{own}"
4347 );
4348 }
4349 assert!(matches!(
4351 Access::default().media_url("//bank.example/x.png", None, None),
4352 Some(std::borrow::Cow::Borrowed("//bank.example/x.png"))
4353 ));
4354 }
4355
4356 #[test]
4357 fn opening_urls_is_granted_by_scheme() {
4358 let caps = |json: serde_json::Value| Capabilities::from_json(&json).unwrap();
4359 let access =
4360 |declared: Capabilities, granted: Option<Capabilities>| Access { declared, granted };
4361 let any = access(caps(serde_json::json!({ "openUrl": true })), None);
4362 assert!(any.allows_open_url("https://a.com"));
4363 assert!(any.allows_open_url("tel:+15550100"));
4364 let some = access(
4365 caps(serde_json::json!({ "openUrl": { "schemes": ["HTTPS", "mailto"] } })),
4366 None,
4367 );
4368 assert!(some.allows_open_url("https://a.com"));
4369 assert!(some.allows_open_url("MAILTO:a@b.c"));
4370 assert!(!some.allows_open_url("tel:1"));
4371 let narrowed = access(
4373 caps(serde_json::json!({ "openUrl": true })),
4374 Some(caps(
4375 serde_json::json!({ "openUrl": { "schemes": ["https"] } }),
4376 )),
4377 );
4378 assert!(narrowed.allows_open_url("https://a.com"));
4379 assert!(!narrowed.allows_open_url("mailto:a@b.c"));
4380 let none = access(caps(serde_json::json!({ "openUrl": false })), None);
4381 assert!(!none.allows_open_url("https://a.com"));
4382 assert!(!access(caps(serde_json::json!({})), None).allows_open_url("https://a.com"));
4383 assert!(Access::default().allows_open_url("https://a.com"));
4384 for bad in [
4385 serde_json::json!({ "openUrl": "yes" }),
4386 serde_json::json!({ "openUrl": { "schemes": ["ht tp"] } }),
4387 serde_json::json!({ "openUrl": { "hosts": ["a.com"] } }),
4388 ] {
4389 assert!(Capabilities::from_json(&bad).is_err(), "{bad}");
4390 }
4391 for json in [
4393 serde_json::json!(true),
4394 serde_json::json!(false),
4395 serde_json::json!({ "schemes": ["https"] }),
4396 ] {
4397 let c = caps(serde_json::json!({ "openUrl": json }));
4398 assert_eq!(c.to_json()["openUrl"], json);
4399 }
4400 }
4401}