Skip to main content

mq_lang/io/sandboxed/
path_access.rs

1use std::path::{Component, Path, PathBuf};
2
3/// Filesystem access granted for one capability (read or write) of
4/// [`SandboxedIo`](super::SandboxedIo).
5///
6/// Built via `impl Into<PathAccess>` so existing call sites keep working
7/// unchanged: `bool` maps to fully denied/allowed, and `Option<Vec<PathBuf>>`
8/// maps directly to a CLI flag parsed as "absent = denied, present with no
9/// paths = fully allowed, present with paths = restricted to those paths"
10/// (e.g. `mq-run`'s `--allow-read`/`--allow-write`).
11#[derive(Debug, Clone, Default, PartialEq, Eq)]
12pub enum PathAccess {
13    /// No filesystem access at all (fail-safe default).
14    #[default]
15    Denied,
16    /// Unrestricted access, matching a bare `--allow-read`/`--allow-write`.
17    Allowed,
18    /// Access restricted to the given files/directories (and their
19    /// descendants).
20    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}