Skip to main content

hyprstream_containedfs/
lib.rs

1//! Path-contained filesystem operations with 9P-aligned naming.
2//!
3//! Provides a [`ContainedFs`] trait that abstracts path-safe filesystem operations.
4//! All operations are contained within a root directory — paths cannot escape via
5//! symlinks, `..` traversal, or other techniques.
6//!
7//! - **Linux**: Uses `pathrs` with `openat2(RESOLVE_IN_ROOT)` for kernel-enforced
8//!   containment. This is atomic and TOCTOU-proof.
9//! - **Unix non-Linux** (macOS, FreeBSD): Uses `safe-path` with per-component symlink
10//!   resolution constrained within root. Better than canonicalize but not kernel-enforced.
11//! - **Non-Unix** (Windows): Uses `canonicalize` + prefix check. Best-effort
12//!   (TOCTOU-vulnerable), acceptable for development.
13//!
14//! # Path utilities
15//!
16//! - [`contained_join`]: Clamps `..` traversal (for path construction).
17//! - [`validate_relative_path`]: Rejects `..` traversal (for I/O validation).
18//! - [`validate_ref_name`]: Git ref name validation (matches `git check-ref-format`).
19
20pub mod canonical_root;
21pub mod error;
22pub mod path;
23#[cfg(target_os = "linux")]
24pub mod pathrs_root;
25#[cfg(all(unix, not(target_os = "linux")))]
26pub mod scoped_root;
27pub mod types;
28
29// Re-exports
30pub use canonical_root::CanonicalRoot;
31pub use error::FsError;
32pub use path::{contained_join, validate_ref_name, validate_relative_path};
33#[cfg(target_os = "linux")]
34pub use pathrs_root::PathrsRoot;
35#[cfg(all(unix, not(target_os = "linux")))]
36pub use scoped_root::ScopedRoot;
37pub use types::{DirEntry, FsHandle, OpenMode, Stat, QTDIR, QTFILE};
38
39use std::path::Path;
40use std::sync::Arc;
41
42/// Trait abstracting path-contained filesystem operations.
43///
44/// All paths passed to methods are relative to the contained root
45/// (forward-slash-separated `&str`, 9P convention).
46/// Implementations ensure no path can escape the root directory.
47pub trait ContainedFs: Send + Sync {
48    /// Resolve a relative path and return an FsHandle for 9P walk state.
49    fn walk(&self, path: &str) -> Result<FsHandle, FsError>;
50
51    /// Open an existing file relative to the root.
52    fn open(&self, path: &str, mode: OpenMode) -> Result<std::fs::File, FsError>;
53
54    /// Create a file relative to the root (implies open).
55    fn create(&self, path: &str, mode: OpenMode) -> Result<std::fs::File, FsError>;
56
57    /// Create a single directory.
58    fn mkdir(&self, path: &str) -> Result<(), FsError>;
59
60    /// Create directories recursively.
61    fn mkdir_all(&self, path: &str) -> Result<(), FsError>;
62
63    /// Get file/directory metadata.
64    fn stat(&self, path: &str) -> Result<Stat, FsError>;
65
66    /// Rename a file or directory within the root.
67    fn rename(&self, src: &str, dst: &str) -> Result<(), FsError>;
68
69    /// Remove a file or empty directory.
70    fn remove(&self, path: &str) -> Result<(), FsError>;
71
72    /// List directory entries.
73    fn readdir(&self, path: &str) -> Result<Vec<DirEntry>, FsError>;
74
75    /// Copy a file (uses reflink/COW when available).
76    fn copy(&self, src: &str, dst: &str) -> Result<(), FsError>;
77}
78
79/// Open best available ContainedFs for root path.
80///
81/// - **Linux**: `PathrsRoot` — kernel-enforced via `openat2(RESOLVE_IN_ROOT)`.
82/// - **Unix non-Linux**: `ScopedRoot` — `safe-path` per-component symlink resolution.
83/// - **Non-Unix**: `CanonicalRoot` — `canonicalize` + prefix check (best-effort).
84pub fn open(root: &Path) -> Result<Arc<dyn ContainedFs>, FsError> {
85    #[cfg(target_os = "linux")]
86    {
87        PathrsRoot::new(root)
88    }
89    #[cfg(all(unix, not(target_os = "linux")))]
90    {
91        ScopedRoot::new(root)
92    }
93    #[cfg(not(unix))]
94    {
95        CanonicalRoot::new(root)
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102    use tempfile::TempDir;
103
104    #[test]
105    fn test_open_creates_contained_fs() {
106        let temp = TempDir::new().unwrap_or_else(|e| panic!("tempdir: {e}"));
107        let fs = open(temp.path()).unwrap_or_else(|e| panic!("open: {e}"));
108
109        // Should be able to mkdir and stat
110        fs.mkdir_all("test/subdir")
111            .unwrap_or_else(|e| panic!("mkdir_all: {e}"));
112        let stat = fs
113            .stat("test/subdir")
114            .unwrap_or_else(|e| panic!("stat: {e}"));
115        assert_eq!(stat.qtype, QTDIR);
116    }
117
118    #[test]
119    fn test_create_and_read() {
120        let temp = TempDir::new().unwrap_or_else(|e| panic!("tempdir: {e}"));
121        let fs = open(temp.path()).unwrap_or_else(|e| panic!("open: {e}"));
122
123        // Create a file
124        {
125            use std::io::Write;
126            let mut file = fs
127                .create("test.txt", OpenMode::OWRITE)
128                .unwrap_or_else(|e| panic!("create: {e}"));
129            file.write_all(b"hello")
130                .unwrap_or_else(|e| panic!("write: {e}"));
131        }
132
133        // Read it back
134        {
135            use std::io::Read;
136            let mut file = fs
137                .open("test.txt", OpenMode::OREAD)
138                .unwrap_or_else(|e| panic!("open: {e}"));
139            let mut buf = String::new();
140            file.read_to_string(&mut buf)
141                .unwrap_or_else(|e| panic!("read: {e}"));
142            assert_eq!(buf, "hello");
143        }
144    }
145
146    #[test]
147    fn test_walk_and_metadata() {
148        let temp = TempDir::new().unwrap_or_else(|e| panic!("tempdir: {e}"));
149        let fs = open(temp.path()).unwrap_or_else(|e| panic!("open: {e}"));
150
151        fs.mkdir("testdir").unwrap_or_else(|e| panic!("mkdir: {e}"));
152        let handle = fs.walk("testdir").unwrap_or_else(|e| panic!("walk: {e}"));
153        assert_eq!(handle.rel_path(), "testdir");
154
155        let meta = handle
156            .metadata()
157            .unwrap_or_else(|e| panic!("metadata: {e}"));
158        assert!(meta.is_dir());
159    }
160
161    #[test]
162    fn test_readdir() {
163        let temp = TempDir::new().unwrap_or_else(|e| panic!("tempdir: {e}"));
164        let fs = open(temp.path()).unwrap_or_else(|e| panic!("open: {e}"));
165
166        fs.mkdir("dir").unwrap_or_else(|e| panic!("mkdir: {e}"));
167        {
168            use std::io::Write;
169            let mut f = fs
170                .create("dir/a.txt", OpenMode::OWRITE)
171                .unwrap_or_else(|e| panic!("create: {e}"));
172            f.write_all(b"a").unwrap_or_else(|e| panic!("write: {e}"));
173        }
174        {
175            use std::io::Write;
176            let mut f = fs
177                .create("dir/b.txt", OpenMode::OWRITE)
178                .unwrap_or_else(|e| panic!("create: {e}"));
179            f.write_all(b"b").unwrap_or_else(|e| panic!("write: {e}"));
180        }
181
182        let entries = fs.readdir("dir").unwrap_or_else(|e| panic!("readdir: {e}"));
183        let mut names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
184        names.sort();
185        assert_eq!(names, vec!["a.txt", "b.txt"]);
186    }
187
188    #[test]
189    fn test_rename() {
190        let temp = TempDir::new().unwrap_or_else(|e| panic!("tempdir: {e}"));
191        let fs = open(temp.path()).unwrap_or_else(|e| panic!("open: {e}"));
192
193        {
194            use std::io::Write;
195            let mut f = fs
196                .create("old.txt", OpenMode::OWRITE)
197                .unwrap_or_else(|e| panic!("create: {e}"));
198            f.write_all(b"data")
199                .unwrap_or_else(|e| panic!("write: {e}"));
200        }
201
202        fs.rename("old.txt", "new.txt")
203            .unwrap_or_else(|e| panic!("rename: {e}"));
204
205        assert!(fs.stat("old.txt").is_err());
206        assert!(fs.stat("new.txt").is_ok());
207    }
208
209    #[test]
210    fn test_remove() {
211        let temp = TempDir::new().unwrap_or_else(|e| panic!("tempdir: {e}"));
212        let fs = open(temp.path()).unwrap_or_else(|e| panic!("open: {e}"));
213
214        {
215            use std::io::Write;
216            let mut f = fs
217                .create("to_remove.txt", OpenMode::OWRITE)
218                .unwrap_or_else(|e| panic!("create: {e}"));
219            f.write_all(b"data")
220                .unwrap_or_else(|e| panic!("write: {e}"));
221        }
222
223        fs.remove("to_remove.txt")
224            .unwrap_or_else(|e| panic!("remove: {e}"));
225        assert!(fs.stat("to_remove.txt").is_err());
226    }
227
228    #[test]
229    fn test_copy() {
230        let temp = TempDir::new().unwrap_or_else(|e| panic!("tempdir: {e}"));
231        let fs = open(temp.path()).unwrap_or_else(|e| panic!("open: {e}"));
232
233        {
234            use std::io::Write;
235            let mut f = fs
236                .create("src.txt", OpenMode::OWRITE)
237                .unwrap_or_else(|e| panic!("create: {e}"));
238            f.write_all(b"copy me")
239                .unwrap_or_else(|e| panic!("write: {e}"));
240        }
241
242        fs.copy("src.txt", "dst.txt")
243            .unwrap_or_else(|e| panic!("copy: {e}"));
244
245        {
246            use std::io::Read;
247            let mut f = fs
248                .open("dst.txt", OpenMode::OREAD)
249                .unwrap_or_else(|e| panic!("open: {e}"));
250            let mut buf = String::new();
251            f.read_to_string(&mut buf)
252                .unwrap_or_else(|e| panic!("read: {e}"));
253            assert_eq!(buf, "copy me");
254        }
255    }
256
257    #[test]
258    fn test_child_rel_path() {
259        let temp = TempDir::new().unwrap_or_else(|e| panic!("tempdir: {e}"));
260        let fs = open(temp.path()).unwrap_or_else(|e| panic!("open: {e}"));
261
262        fs.mkdir("parent").unwrap_or_else(|e| panic!("mkdir: {e}"));
263        let handle = fs.walk("parent").unwrap_or_else(|e| panic!("walk: {e}"));
264        assert_eq!(handle.child_rel_path("child"), "parent/child");
265
266        // Root-level handle
267        let root_handle = fs.walk(".").unwrap_or_else(|e| panic!("walk root: {e}"));
268        assert_eq!(root_handle.child_rel_path("child"), "child");
269    }
270}