agentmux_srv_core/backend/
confined_read.rs1use std::fs::File;
10use std::io::Read;
11use std::path::{Path, PathBuf};
12
13const MAX_BYTES: u64 = 1024 * 1024;
15
16pub(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
32fn 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
45fn 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 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 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 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}