Skip to main content

agentmux_srv_core/backend/
confined_read.rs

1//! Reading a file only if it really is inside a folder, decided on the open file rather than its name.
2//!
3//! A container agent can change its mounted workspace while srv reads it. Checking a path (resolving it)
4//! and then opening the same path leaves a gap: a folder or file swapped for a symlink in between sends the
5//! read outside the workspace. So the file is opened first, and the check is on what the open handle is: its
6//! real path, as the system resolved it when it opened. The handle keeps pointing at that file, so nothing
7//! swapped afterwards changes what is read.
8
9use std::fs::File;
10use std::io::Read;
11use std::path::{Path, PathBuf};
12
13/// The most a confined read returns: startup files are text a person wrote.
14const MAX_BYTES: u64 = 1024 * 1024;
15
16/// The text of the file at `path`. With a `confine` folder (canonical), only if the file that was opened is a
17/// regular file inside it; without one, a plain read.
18pub(crate) fn read_to_string_within(path: &Path, confine: Option<&Path>) -> Option<String> {
19    let Some(root) = confine else { return std::fs::read_to_string(path).ok() };
20    let file = open_nonblocking(path).ok()?;
21    if !file.metadata().ok()?.is_file() {
22        return None;
23    }
24    if !real_path_of(&file)?.starts_with(root) {
25        return None;
26    }
27    let mut text = String::new();
28    file.take(MAX_BYTES).read_to_string(&mut text).ok()?;
29    Some(text)
30}
31
32/// Opened without waiting on a pipe or device, so a planted one can't hold srv.
33fn open_nonblocking(path: &Path) -> std::io::Result<File> {
34    #[cfg(unix)]
35    {
36        use std::os::unix::fs::OpenOptionsExt;
37        std::fs::OpenOptions::new().read(true).custom_flags(libc::O_NONBLOCK).open(path)
38    }
39    #[cfg(not(unix))]
40    {
41        File::open(path)
42    }
43}
44
45/// Where the open file is, from the system, not from the name it was opened by.
46fn real_path_of(file: &File) -> Option<PathBuf> {
47    #[cfg(target_os = "linux")]
48    {
49        use std::os::fd::AsRawFd;
50        std::fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd())).ok()
51    }
52    #[cfg(target_os = "macos")]
53    {
54        use std::os::fd::AsRawFd;
55        use std::os::unix::ffi::OsStringExt;
56        let mut buf = vec![0u8; libc::PATH_MAX as usize];
57        // SAFETY: F_GETPATH writes a NUL-terminated path of at most PATH_MAX bytes into `buf`.
58        if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETPATH, buf.as_mut_ptr()) } == -1 {
59            return None;
60        }
61        buf.truncate(buf.iter().position(|b| *b == 0)?);
62        Some(PathBuf::from(std::ffi::OsString::from_vec(buf)))
63    }
64    #[cfg(windows)]
65    {
66        use std::os::windows::ffi::OsStringExt;
67        use std::os::windows::io::AsRawHandle;
68        use windows_sys::Win32::Storage::FileSystem::{GetFinalPathNameByHandleW, FILE_NAME_NORMALIZED, VOLUME_NAME_DOS};
69        let handle = file.as_raw_handle();
70        let mut buf = vec![0u16; 32768];
71        // SAFETY: `handle` is open for the call, and `buf` is writable for the length passed.
72        let len = unsafe { GetFinalPathNameByHandleW(handle as _, buf.as_mut_ptr(), buf.len() as u32, FILE_NAME_NORMALIZED | VOLUME_NAME_DOS) };
73        if len == 0 || len as usize > buf.len() {
74            return None;
75        }
76        Some(PathBuf::from(std::ffi::OsString::from_wide(&buf[..len as usize])))
77    }
78    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
79    {
80        let _ = file;
81        None
82    }
83}
84
85#[cfg(test)]
86mod tests {
87    use super::*;
88
89    #[test]
90    fn a_file_inside_the_folder_is_read_and_one_outside_is_not() {
91        let dir = tempfile::tempdir().unwrap();
92        let root = std::fs::canonicalize(dir.path()).unwrap();
93        std::fs::write(root.join("a.md"), "inside").unwrap();
94        let other = tempfile::tempdir().unwrap();
95        std::fs::write(other.path().join("b.md"), "outside").unwrap();
96
97        assert_eq!(read_to_string_within(&root.join("a.md"), Some(&root)).as_deref(), Some("inside"));
98        assert_eq!(read_to_string_within(&other.path().join("b.md"), Some(&root)), None);
99        assert_eq!(read_to_string_within(&other.path().join("b.md"), None).as_deref(), Some("outside"));
100    }
101
102    #[test]
103    fn a_folder_or_a_missing_file_is_not_read() {
104        let dir = tempfile::tempdir().unwrap();
105        let root = std::fs::canonicalize(dir.path()).unwrap();
106        std::fs::create_dir(root.join("sub")).unwrap();
107        assert_eq!(read_to_string_within(&root.join("sub"), Some(&root)), None);
108        assert_eq!(read_to_string_within(&root.join("none.md"), Some(&root)), None);
109    }
110
111    #[test]
112    fn a_file_is_cut_at_the_limit() {
113        let dir = tempfile::tempdir().unwrap();
114        let root = std::fs::canonicalize(dir.path()).unwrap();
115        std::fs::write(root.join("big.md"), "x".repeat(MAX_BYTES as usize + 10)).unwrap();
116        assert_eq!(read_to_string_within(&root.join("big.md"), Some(&root)).map(|t| t.len()), Some(MAX_BYTES as usize));
117    }
118
119    #[cfg(unix)]
120    #[test]
121    fn a_link_to_a_file_outside_is_not_read() {
122        let dir = tempfile::tempdir().unwrap();
123        let root = std::fs::canonicalize(dir.path()).unwrap();
124        let other = tempfile::tempdir().unwrap();
125        std::fs::write(other.path().join("b.md"), "outside").unwrap();
126        std::os::unix::fs::symlink(other.path().join("b.md"), root.join("link.md")).unwrap();
127        assert_eq!(read_to_string_within(&root.join("link.md"), Some(&root)), None);
128    }
129
130    #[cfg(unix)]
131    #[test]
132    fn a_fifo_does_not_hold_the_read() {
133        let dir = tempfile::tempdir().unwrap();
134        let root = std::fs::canonicalize(dir.path()).unwrap();
135        let fifo = std::ffi::CString::new(root.join("pipe.md").to_str().unwrap()).unwrap();
136        // SAFETY: a valid NUL-terminated path.
137        assert_eq!(unsafe { libc::mkfifo(fifo.as_ptr(), 0o600) }, 0);
138        assert_eq!(read_to_string_within(&root.join("pipe.md"), Some(&root)), None);
139    }
140}