mq_lang/io/sandboxed/
path_access.rs1use std::path::{Component, Path, PathBuf};
2
3#[derive(Debug, Clone, Default, PartialEq, Eq)]
12pub enum PathAccess {
13 #[default]
15 Denied,
16 Allowed,
18 AllowedPaths(Vec<PathBuf>),
21}
22
23impl From<bool> for PathAccess {
24 fn from(allow: bool) -> Self {
25 if allow { PathAccess::Allowed } else { PathAccess::Denied }
26 }
27}
28
29impl From<Vec<PathBuf>> for PathAccess {
30 fn from(paths: Vec<PathBuf>) -> Self {
31 if paths.is_empty() {
32 PathAccess::Allowed
33 } else {
34 PathAccess::AllowedPaths(paths)
35 }
36 }
37}
38
39impl From<Option<Vec<PathBuf>>> for PathAccess {
40 fn from(paths: Option<Vec<PathBuf>>) -> Self {
41 match paths {
42 None => PathAccess::Denied,
43 Some(paths) => paths.into(),
44 }
45 }
46}
47
48impl PathAccess {
49 pub(super) fn permits(&self, path: &Path) -> bool {
50 match self {
51 PathAccess::Denied => false,
52 PathAccess::Allowed => true,
53 PathAccess::AllowedPaths(allowed) => {
54 let target = normalize(path);
55 allowed.iter().any(|root| target.starts_with(normalize(root)))
56 }
57 }
58 }
59
60 pub(super) fn is_denied(&self) -> bool {
61 matches!(self, PathAccess::Denied)
62 }
63}
64
65fn normalize(path: &Path) -> PathBuf {
66 let absolute = if path.is_absolute() {
67 path.to_path_buf()
68 } else {
69 std::env::current_dir().unwrap_or_default().join(path)
70 };
71
72 let mut result = PathBuf::new();
73 for component in absolute.components() {
74 match component {
75 Component::ParentDir => {
76 result.pop();
77 }
78 Component::CurDir => {}
79 other => result.push(other.as_os_str()),
80 }
81 }
82 result
83}