Skip to main content

aidaemon_tools/
workspace.rs

1use std::io;
2use std::path::{Path, PathBuf};
3
4/// Why a path argument was refused.
5#[derive(Debug, thiserror::Error)]
6pub enum PathError {
7    #[error("path must not be empty")]
8    Empty,
9    #[error(
10        "`{path}` is outside the workspace ({root}); use a path relative to the workspace root"
11    )]
12    Escapes { path: String, root: String },
13    #[error("cannot resolve `{path}`: {source}")]
14    Io {
15        path: String,
16        #[source]
17        source: io::Error,
18    },
19}
20
21/// A root directory that confines every path argument a tool receives.
22///
23/// Paths are resolved relative to the root (absolute paths are accepted only
24/// if they land inside it) by the same resolver as the scope guard
25/// ([`aidaemon_policies::resolve_path`]): one component at a time, every
26/// symlink followed (a broken one to its target) and `..` applied to the
27/// directory really reached, before the containment check. A path that does
28/// not exist yet is allowed when it resolves inside the root, so tools can
29/// create new files and directories.
30///
31/// A path check is not a boundary against a hostile filesystem: a hard link
32/// inside the root to a file outside resolves inside, and a concurrent
33/// process that swaps a directory for a symlink between the check and the
34/// I/O is not seen. Use a [`crate::Sandbox`] when the workspace itself is
35/// shared with untrusted processes.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct Workspace {
38    root: PathBuf,
39}
40
41impl Workspace {
42    /// Open an existing directory as a workspace. The root is canonicalized.
43    pub fn new(root: impl AsRef<Path>) -> io::Result<Self> {
44        let root = dunce::canonicalize(root.as_ref())?;
45        if !root.is_dir() {
46            return Err(io::Error::new(
47                io::ErrorKind::InvalidInput,
48                format!("workspace root {} is not a directory", root.display()),
49            ));
50        }
51        Ok(Self { root })
52    }
53
54    /// The canonical root directory.
55    pub fn root(&self) -> &Path {
56        &self.root
57    }
58
59    /// Resolve a path argument to a canonical absolute path inside the root.
60    /// The path need not exist, but it must resolve inside the root (after
61    /// following every symlink, including a broken last one).
62    pub fn resolve(&self, path: &str) -> Result<PathBuf, PathError> {
63        if path.trim().is_empty() {
64            return Err(PathError::Empty);
65        }
66        let given = Path::new(path);
67        let joined = if given.is_absolute() {
68            given.to_path_buf()
69        } else {
70            self.root.join(given)
71        };
72        let resolved =
73            aidaemon_policies::resolve_path(&joined).map_err(|source| PathError::Io {
74                path: path.to_string(),
75                source,
76            })?;
77        if !resolved.starts_with(&self.root) {
78            return Err(PathError::Escapes {
79                path: path.to_string(),
80                root: self.root.display().to_string(),
81            });
82        }
83        Ok(resolved)
84    }
85
86    /// Like [`Workspace::resolve`] but falls back to the lexical join, for
87    /// declaring access manifests before the call is validated.
88    pub fn declare(&self, path: &str) -> String {
89        match self.resolve(path) {
90            Ok(p) => p.display().to_string(),
91            Err(_) => {
92                let given = Path::new(path);
93                if given.is_absolute() {
94                    path.to_string()
95                } else {
96                    self.root.join(given).display().to_string()
97                }
98            }
99        }
100    }
101
102    /// A path for display: relative to the root when inside it.
103    pub fn display(&self, path: &Path) -> String {
104        match path.strip_prefix(&self.root) {
105            Ok(rel) if rel.as_os_str().is_empty() => ".".to_string(),
106            Ok(rel) => rel.display().to_string(),
107            Err(_) => path.display().to_string(),
108        }
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115
116    fn ws() -> (tempfile::TempDir, Workspace) {
117        let dir = tempfile::tempdir().unwrap();
118        let ws = Workspace::new(dir.path()).unwrap();
119        (dir, ws)
120    }
121
122    #[test]
123    fn resolves_relative_and_new_paths() {
124        let (_d, ws) = ws();
125        std::fs::create_dir(ws.root().join("src")).unwrap();
126        assert_eq!(ws.resolve("src").unwrap(), ws.root().join("src"));
127        assert_eq!(
128            ws.resolve("src/new/deep.txt").unwrap(),
129            ws.root().join("src/new/deep.txt")
130        );
131        assert_eq!(
132            ws.resolve("./src/../src/a").unwrap(),
133            ws.root().join("src/a")
134        );
135        let abs = ws.root().join("src").display().to_string();
136        assert_eq!(ws.resolve(&abs).unwrap(), ws.root().join("src"));
137    }
138
139    #[test]
140    fn rejects_parent_escape() {
141        let (_d, ws) = ws();
142        let err = ws.resolve("../outside.txt").unwrap_err();
143        assert!(matches!(err, PathError::Escapes { .. }), "{err}");
144        assert!(ws.resolve("a/../../x").is_err());
145        assert!(ws.resolve("").is_err());
146    }
147
148    #[test]
149    fn rejects_absolute_outside() {
150        let (_d, ws) = ws();
151        let other = tempfile::tempdir().unwrap();
152        let p = other.path().join("secret.txt");
153        std::fs::write(&p, "synthetic").unwrap();
154        assert!(ws.resolve(&p.display().to_string()).is_err());
155        assert!(ws.resolve("/").is_err());
156    }
157
158    #[cfg(unix)]
159    #[test]
160    fn rejects_symlink_pointing_outside() {
161        let (_d, ws) = ws();
162        let other = tempfile::tempdir().unwrap();
163        std::fs::write(other.path().join("secret.txt"), "synthetic").unwrap();
164        std::os::unix::fs::symlink(other.path(), ws.root().join("link")).unwrap();
165        let err = ws.resolve("link/secret.txt").unwrap_err();
166        assert!(matches!(err, PathError::Escapes { .. }), "{err}");
167        // New files through the outside symlink are refused as well.
168        assert!(ws.resolve("link/new.txt").is_err());
169        // A symlink that stays inside is fine.
170        std::fs::create_dir(ws.root().join("real")).unwrap();
171        std::os::unix::fs::symlink(ws.root().join("real"), ws.root().join("inner")).unwrap();
172        assert_eq!(
173            ws.resolve("inner/x").unwrap(),
174            ws.root().join("real").join("x")
175        );
176    }
177
178    #[cfg(unix)]
179    #[test]
180    fn follows_links_before_dot_dot_and_broken_links_to_their_target() {
181        let (_d, ws) = ws();
182        let other = tempfile::tempdir().unwrap();
183        let other = dunce::canonicalize(other.path()).unwrap();
184        std::fs::create_dir(other.join("sub")).unwrap();
185        std::os::unix::fs::symlink(other.join("sub"), ws.root().join("link")).unwrap();
186        assert!(ws.resolve("link/../escape.txt").is_err());
187        std::os::unix::fs::symlink(other.join("new.txt"), ws.root().join("dangling")).unwrap();
188        assert!(ws.resolve("dangling").is_err());
189        assert!(!other.join("new.txt").exists());
190        std::os::unix::fs::symlink(ws.root().join("made.txt"), ws.root().join("inner")).unwrap();
191        assert_eq!(ws.resolve("inner").unwrap(), ws.root().join("made.txt"));
192    }
193}