Skip to main content

hyprstream_containedfs/
pathrs_root.rs

1//! Linux pathrs-based containment (kernel-enforced via openat2).
2//!
3//! On Linux 5.6+, pathrs uses `openat2` with `RESOLVE_IN_ROOT` which atomically
4//! resolves paths within the root. On older kernels, it falls back to O_PATH
5//! walk with `/proc/self/fd` verification.
6
7use crate::error::FsError;
8use crate::path::validate_relative_path;
9use crate::types::{DirEntry, FsHandle, OpenMode, Stat};
10use crate::ContainedFs;
11use pathrs::flags::{OpenFlags, RenameFlags};
12use std::fs::{self, File};
13use std::os::unix::io::AsRawFd;
14use std::path::{Path, PathBuf};
15use std::sync::Arc;
16
17/// Kernel-enforced path containment using pathrs + openat2(RESOLVE_IN_ROOT).
18pub struct PathrsRoot {
19    root: pathrs::Root,
20    /// Cached root path for operations that need it.
21    root_path: PathBuf,
22}
23
24impl PathrsRoot {
25    /// Create a new PathrsRoot for the given root path.
26    #[allow(clippy::new_ret_no_self)]
27    pub fn new(path: &Path) -> Result<Arc<dyn ContainedFs>, FsError> {
28        let root_path = fs::canonicalize(path).map_err(FsError::Io)?;
29        let root = pathrs::Root::open(path).map_err(pathrs_to_fs_error)?;
30        Ok(Arc::new(Self { root, root_path }))
31    }
32}
33
34fn pathrs_to_fs_error(e: pathrs::error::Error) -> FsError {
35    let msg = e.to_string();
36    if msg.contains("SafetyViolation") || msg.contains("safety violation") {
37        FsError::PathEscape(msg)
38    } else if msg.contains("ENOENT")
39        || msg.contains("No such file")
40        || msg.contains("subpath failed")
41    {
42        FsError::NotFound(msg)
43    } else if msg.contains("EACCES") || msg.contains("EPERM") || msg.contains("Permission denied") {
44        FsError::PermissionDenied(msg)
45    } else if msg.contains("EEXIST") || msg.contains("File exists") {
46        FsError::AlreadyExists(msg)
47    } else {
48        FsError::Io(std::io::Error::other(msg))
49    }
50}
51
52impl ContainedFs for PathrsRoot {
53    fn walk(&self, path: &str) -> Result<FsHandle, FsError> {
54        let handle = self.root.resolve(path).map_err(pathrs_to_fs_error)?;
55        // Derive rel_path from the kernel-resolved fd, not the user-supplied string.
56        // This prevents poisoned rel_path strings (e.g. "a/../../b" resolving to "b"
57        // but storing the traversal path) from leaking to git operations.
58        let rel_path = {
59            let probe: File = handle
60                .reopen(OpenFlags::O_PATH | OpenFlags::O_CLOEXEC)
61                .map_err(pathrs_to_fs_error)?;
62            let real = fs::read_link(format!("/proc/self/fd/{}", probe.as_raw_fd()))
63                .map_err(FsError::Io)?;
64            real.strip_prefix(&self.root_path)
65                .map(|p| {
66                    let s = p.to_string_lossy().to_string();
67                    if s.is_empty() {
68                        ".".to_owned()
69                    } else {
70                        s
71                    }
72                })
73                .unwrap_or_else(|_| path.to_owned())
74        };
75        Ok(FsHandle::from_pathrs(handle, rel_path))
76    }
77
78    fn open(&self, path: &str, mode: OpenMode) -> Result<File, FsError> {
79        let mut flags = OpenFlags::O_CLOEXEC;
80        if mode.is_write() {
81            flags |= OpenFlags::O_RDWR;
82        } else {
83            flags |= OpenFlags::O_RDONLY;
84        }
85        if mode.is_truncate() {
86            flags |= OpenFlags::O_TRUNC;
87        }
88        if mode.is_append() {
89            flags |= OpenFlags::O_APPEND;
90        }
91
92        self.root
93            .open_subpath(path, flags)
94            .map_err(pathrs_to_fs_error)
95    }
96
97    fn create(&self, path: &str, mode: OpenMode) -> Result<File, FsError> {
98        use std::os::unix::fs::PermissionsExt;
99        let perms = std::fs::Permissions::from_mode(0o644);
100
101        let mut flags = OpenFlags::O_CLOEXEC;
102        if mode.is_write() {
103            flags |= OpenFlags::O_RDWR;
104        } else {
105            flags |= OpenFlags::O_RDONLY;
106        }
107        if mode.is_truncate() {
108            flags |= OpenFlags::O_TRUNC;
109        }
110        if mode.is_append() {
111            flags |= OpenFlags::O_APPEND;
112        }
113        if mode.is_exclusive() {
114            flags |= OpenFlags::O_EXCL;
115        }
116
117        self.root
118            .create_file(path, flags, &perms)
119            .map_err(pathrs_to_fs_error)
120    }
121
122    fn mkdir(&self, path: &str) -> Result<(), FsError> {
123        use std::os::unix::fs::PermissionsExt;
124        let perms = fs::Permissions::from_mode(0o755);
125        // pathrs only has mkdir_all; for single-level, use it anyway
126        self.root
127            .mkdir_all(path, &perms)
128            .map_err(pathrs_to_fs_error)?;
129        Ok(())
130    }
131
132    fn mkdir_all(&self, path: &str) -> Result<(), FsError> {
133        use std::os::unix::fs::PermissionsExt;
134        let perms = fs::Permissions::from_mode(0o755);
135        self.root
136            .mkdir_all(path, &perms)
137            .map_err(pathrs_to_fs_error)?;
138        Ok(())
139    }
140
141    fn stat(&self, path: &str) -> Result<Stat, FsError> {
142        let handle = self.root.resolve(path).map_err(pathrs_to_fs_error)?;
143        let file: File = handle
144            .reopen(OpenFlags::O_RDONLY | OpenFlags::O_CLOEXEC)
145            .map_err(pathrs_to_fs_error)?;
146        let meta = file.metadata().map_err(FsError::Io)?;
147        let name = Path::new(path)
148            .file_name()
149            .map(|n| n.to_string_lossy().to_string())
150            .unwrap_or_default();
151        Ok(Stat::from_metadata(&meta, name))
152    }
153
154    fn rename(&self, src: &str, dst: &str) -> Result<(), FsError> {
155        self.root
156            .rename(src, dst, RenameFlags::empty())
157            .map_err(pathrs_to_fs_error)
158    }
159
160    fn remove(&self, path: &str) -> Result<(), FsError> {
161        // Try file removal first, then directory
162        match self.root.remove_file(path) {
163            Ok(()) => Ok(()),
164            Err(_) => self.root.remove_dir(path).map_err(pathrs_to_fs_error),
165        }
166    }
167
168    fn readdir(&self, path: &str) -> Result<Vec<DirEntry>, FsError> {
169        let handle = self.root.resolve(path).map_err(pathrs_to_fs_error)?;
170        let dir_file: File = handle
171            .reopen(OpenFlags::O_RDONLY | OpenFlags::O_DIRECTORY | OpenFlags::O_CLOEXEC)
172            .map_err(pathrs_to_fs_error)?;
173
174        // Use /proc/self/fd to get the real path for read_dir
175        let fd = dir_file.as_raw_fd();
176        let real_path = fs::read_link(format!("/proc/self/fd/{}", fd)).map_err(FsError::Io)?;
177
178        let mut entries = Vec::new();
179        for entry in fs::read_dir(real_path).map_err(FsError::Io)? {
180            let entry = entry.map_err(FsError::Io)?;
181            let name = entry.file_name().to_string_lossy().to_string();
182            if name == "." || name == ".." {
183                continue;
184            }
185            let meta = entry.metadata().map_err(FsError::Io)?;
186            entries.push(DirEntry {
187                name,
188                is_dir: meta.is_dir(),
189                size: meta.len(),
190            });
191        }
192        Ok(entries)
193    }
194
195    fn copy(&self, src: &str, dst: &str) -> Result<(), FsError> {
196        // FIX S3: Resolve BOTH src AND dst within root using pathrs
197        let src_handle = self.root.resolve(src).map_err(pathrs_to_fs_error)?;
198        let src_file: File = src_handle
199            .reopen(OpenFlags::O_PATH | OpenFlags::O_CLOEXEC)
200            .map_err(pathrs_to_fs_error)?;
201        let src_fd = src_file.as_raw_fd();
202        let src_path = fs::read_link(format!("/proc/self/fd/{}", src_fd)).map_err(FsError::Io)?;
203
204        // Resolve dst parent within root, then construct full dst path
205        let dst_validated = validate_relative_path(dst)?;
206        let dst_parent = dst_validated
207            .parent()
208            .map(|p| p.to_string_lossy().to_string());
209
210        let dst_full = if let Some(parent_str) = dst_parent {
211            if !parent_str.is_empty() {
212                // Resolve parent directory within root
213                let parent_handle = self.root.resolve(&parent_str).map_err(pathrs_to_fs_error)?;
214                let parent_file: File = parent_handle
215                    .reopen(OpenFlags::O_PATH | OpenFlags::O_CLOEXEC)
216                    .map_err(pathrs_to_fs_error)?;
217                let parent_fd = parent_file.as_raw_fd();
218                let parent_path =
219                    fs::read_link(format!("/proc/self/fd/{}", parent_fd)).map_err(FsError::Io)?;
220                parent_path.join(dst_validated.file_name().unwrap_or_default())
221            } else {
222                self.root_path.join(&dst_validated)
223            }
224        } else {
225            self.root_path.join(&dst_validated)
226        };
227
228        reflink_copy::reflink_or_copy(&src_path, &dst_full)
229            .map(|_| ())
230            .map_err(|e| FsError::Io(std::io::Error::other(e)))
231    }
232}