返回 CodeWhale
fs_confined.rs
根目录 / crates / util / src / fs_confined.rs
1 //! Shared regular-file I/O, replacing project_context's private no-follow open.
2 //! Parent containment uses the existing Fleet `WorkspaceFile` primitive.
3 //!
4 //! The caller chooses the root; links below it are refused. The root itself
5 //! may resolve through a user-selected link. Writes are not transactions:
6 //! callers needing atomic replacement must use `WorkspaceFile::replace`.
7
8 use std::fs::{self, File};
9 use std::io::{self, Read, Write};
10 use std::path::Path;
11
12 use crate::files::WorkspaceFile;
13
14 fn target(root: &Path, path: &Path, create: bool) -> io::Result<WorkspaceFile> {
15 let relative = path.strip_prefix(root).map_err(|_| {
16 io::Error::new(
17 io::ErrorKind::InvalidInput,
18 "File must stay within its root",
19 )
20 })?;
21 WorkspaceFile::open(root, relative, create)
22 }
23
24 pub fn open_read(root: &Path, path: &Path) -> io::Result<File> {
25 open_regular(root, path, false)
26 }
27
28 /// [`open_read`] for a file another process may hold open for writing, such as
29 /// a running worker's log. Windows denies those writers to [`open_read`] (it
30 /// is the protected reader), so this takes the sharing reader; the links and
31 /// regular-file policy is the same.
32 pub fn open_read_shared(root: &Path, path: &Path) -> io::Result<File> {
33 open_regular(root, path, true)
34 }
35
36 fn open_regular(root: &Path, path: &Path, shared: bool) -> io::Result<File> {
37 let target = target(root, path, false)?;
38 let metadata = fs::symlink_metadata(path)?;
39 if metadata.file_type().is_symlink() {
40 return Err(io::Error::new(
41 io::ErrorKind::InvalidInput,
42 "Refusing symlinked file",
43 ));
44 }
45 if !metadata.is_file() {
46 return Err(io::Error::new(
47 io::ErrorKind::InvalidInput,
48 "Path is not a regular file",
49 ));
50 }
51 // The pinned parent and no-follow open enforce the same policy even if
52 // the path changes after the metadata check. The handle is checked too.
53 if shared {
54 target.open_file_shared()
55 } else {
56 target.open_file()
57 }
58 }
59
60 /// [`open_read`] for a workspace file that may be a link to another file in the
61 /// same root, such as a shared `AGENTS.md`. Every link is resolved first and
62 /// the final target must stay below the resolved root; the resolved path is
63 /// then opened with the same no-follow policy, so a component swapped for a
64 /// link after resolution is refused.
65 pub fn open_read_linked_within(root: &Path, path: &Path) -> io::Result<File> {
66 let root = fs::canonicalize(root)?;
67 let resolved = fs::canonicalize(path)?;
68 if !resolved.starts_with(&root) {
69 return Err(io::Error::new(
70 io::ErrorKind::InvalidInput,
71 "Refusing symlinked file that resolves outside the workspace",
72 ));
73 }
74 open_regular(&root, &resolved, false)
75 }
76
77 pub fn read_to_string(root: &Path, path: &Path) -> io::Result<String> {
78 let mut contents = String::new();
79 open_read(root, path)?.read_to_string(&mut contents)?;
80 Ok(contents)
81 }
82
83 /// Operator-owned global instructions may intentionally share a linked file.
84 /// This is not a workspace reader: it resolves links without a containment root.
85 pub fn open_user_read(path: &Path) -> io::Result<File> {
86 let resolved = fs::canonicalize(path)?;
87 let mut options = fs::OpenOptions::new();
88 options.read(true);
89 #[cfg(unix)]
90 {
91 use std::os::unix::fs::OpenOptionsExt;
92 options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
93 }
94 #[cfg(windows)]
95 {
96 use std::os::windows::fs::OpenOptionsExt;
97 options.custom_flags(0x0020_0000); // FILE_FLAG_OPEN_REPARSE_POINT
98 }
99 let file = options.open(resolved)?;
100 let metadata = file.metadata()?;
101 if !metadata.is_file() || crate::path_identity::metadata_is_link_or_reparse(&metadata) {
102 return Err(io::Error::new(
103 io::ErrorKind::InvalidInput,
104 "Path is not a regular file",
105 ));
106 }
107 Ok(file)
108 }
109
110 pub fn open_append(root: &Path, path: &Path) -> io::Result<File> {
111 target(root, path, true)?.open_write(true)
112 }
113
114 /// Append `contents` to a confined regular file and fsync its data. When the
115 /// file or any ancestor directory inside `root` did not exist yet, also issue
116 /// best-effort parent directory syncs so the new entries survive a crash
117 /// without failing on network/FUSE mounts.
118 pub fn append_durable(root: &Path, path: &Path, contents: &[u8]) -> io::Result<()> {
119 let existed = path.exists();
120 let mut missing_parents = Vec::new();
121 if !existed {
122 let mut cursor = path.parent();
123 while let Some(dir) = cursor {
124 if dir.exists() || !dir.starts_with(root) {
125 break;
126 }
127 missing_parents.push(dir.to_path_buf());
128 if dir == root {
129 break;
130 }
131 cursor = dir.parent();
132 }
133 }
134 let target = target(root, path, true)?;
135 let mut file = target.open_write(true)?;
136 file.write_all(contents)?;
137 file.sync_all()?;
138 if !existed {
139 crate::utils::report_directory_sync(path.parent().unwrap_or(root), target.sync_parent());
140 for created_dir in &missing_parents {
141 if let Some(ancestor) = created_dir.parent()
142 && ancestor.starts_with(root)
143 {
144 crate::utils::sync_directory(ancestor);
145 }
146 }
147 }
148 Ok(())
149 }
150
151 pub fn write(root: &Path, path: &Path, contents: &[u8]) -> io::Result<()> {
152 let mut file = target(root, path, true)?.open_write(false)?;
153 // Validate the opened file before truncating it.
154 file.set_len(0)?;
155 file.write_all(contents)
156 }
157
158 #[cfg(test)]
159 mod tests {
160 use super::*;
161
162 #[test]
163 fn confined_files_support_read_append_and_truncate() {
164 let root = tempfile::tempdir().unwrap();
165 let path = root.path().join("notes/file.md");
166 open_append(root.path(), &path)
167 .unwrap()
168 .write_all(b"first")
169 .unwrap();
170 open_append(root.path(), &path)
171 .unwrap()
172 .write_all(b" second")
173 .unwrap();
174 assert_eq!(read_to_string(root.path(), &path).unwrap(), "first second");
175 write(root.path(), &path, b"next").unwrap();
176 assert_eq!(read_to_string(root.path(), &path).unwrap(), "next");
177 }
178
179 /// A running worker holds its log open for writing while the host reads
180 /// it (Windows denied that to the protected reader).
181 #[test]
182 fn a_shared_read_sees_a_file_a_writer_still_holds_open() {
183 let root = tempfile::tempdir().unwrap();
184 let path = root.path().join("logs/worker.log");
185 let mut writer = open_append(root.path(), &path).unwrap();
186 writer.write_all(b"started").unwrap();
187 writer.flush().unwrap();
188 let mut text = String::new();
189 open_read_shared(root.path(), &path)
190 .unwrap()
191 .read_to_string(&mut text)
192 .unwrap();
193 assert_eq!(text, "started");
194 writer.write_all(b" and running").unwrap();
195 drop(writer);
196 assert_eq!(
197 read_to_string(root.path(), &path).unwrap(),
198 "started and running"
199 );
200 assert!(open_read_shared(root.path(), root.path()).is_err());
201 assert!(open_read_shared(root.path(), &root.path().join("../worker.log")).is_err());
202 }
203
204 #[test]
205 fn confined_files_refuse_paths_outside_the_root() {
206 let root = tempfile::tempdir().unwrap();
207 let outside = tempfile::tempdir().unwrap();
208 for path in [
209 outside.path().join("file.md"),
210 root.path().join("../file.md"),
211 ] {
212 assert!(open_read(root.path(), &path).is_err());
213 assert!(open_append(root.path(), &path).is_err());
214 assert!(write(root.path(), &path, b"next").is_err());
215 }
216 }
217
218 #[cfg(unix)]
219 #[test]
220 fn confined_files_validate_handles_before_truncation() {
221 let root = tempfile::tempdir().unwrap();
222 let outside = tempfile::tempdir().unwrap();
223 let original = outside.path().join("original.md");
224 fs::write(&original, "original").unwrap();
225 let path = root.path().join("linked.md");
226 fs::hard_link(&original, &path).unwrap();
227 assert!(write(root.path(), &path, b"next").is_err());
228 assert_eq!(fs::read_to_string(original).unwrap(), "original");
229 assert!(open_read(root.path(), root.path()).is_err());
230 }
231
232 #[cfg(unix)]
233 #[test]
234 fn confined_files_refuse_links_even_within_the_root() {
235 use std::os::unix::fs::symlink;
236 let root = tempfile::tempdir().unwrap();
237 let directory = root.path().join("real");
238 fs::create_dir(&directory).unwrap();
239 let original = directory.join("file.md");
240 fs::write(&original, "original").unwrap();
241 symlink(&directory, root.path().join("linked-dir")).unwrap();
242 symlink(&original, root.path().join("linked.md")).unwrap();
243 for path in [
244 root.path().join("linked-dir/file.md"),
245 root.path().join("linked.md"),
246 ] {
247 assert!(open_read(root.path(), &path).is_err());
248 assert!(open_read_shared(root.path(), &path).is_err());
249 assert!(open_append(root.path(), &path).is_err());
250 assert!(write(root.path(), &path, b"next").is_err());
251 assert_eq!(fs::read_to_string(&original).unwrap(), "original");
252 }
253 }
254
255 #[cfg(unix)]
256 #[test]
257 fn linked_reads_follow_links_that_stay_within_the_root() {
258 use std::os::unix::fs::symlink;
259 let root = tempfile::tempdir().unwrap();
260 let outside = tempfile::tempdir().unwrap();
261 let shared = root.path().join("ops/operator/AGENTS.md");
262 fs::create_dir_all(shared.parent().unwrap()).unwrap();
263 fs::write(&shared, "shared").unwrap();
264 fs::write(outside.path().join("AGENTS.md"), "outside").unwrap();
265 symlink("ops/operator/AGENTS.md", root.path().join("AGENTS.md")).unwrap();
266 symlink(&shared, root.path().join("absolute.md")).unwrap();
267 symlink("AGENTS.md", root.path().join("chain.md")).unwrap();
268 symlink(root.path().join("ops"), root.path().join("linked-dir")).unwrap();
269 for name in [
270 "AGENTS.md",
271 "absolute.md",
272 "chain.md",
273 "linked-dir/operator/AGENTS.md",
274 ] {
275 let mut text = String::new();
276 open_read_linked_within(root.path(), &root.path().join(name))
277 .unwrap()
278 .read_to_string(&mut text)
279 .unwrap();
280 assert_eq!(text, "shared", "{name}");
281 }
282 let outside_agents = outside.path().join("AGENTS.md");
283 let relative_escape = Path::new("..")
284 .join(outside.path().file_name().unwrap())
285 .join("AGENTS.md");
286 symlink(&outside_agents, root.path().join("escape.md")).unwrap();
287 symlink(&relative_escape, root.path().join("dotdot.md")).unwrap();
288 symlink(&outside_agents, root.path().join("ops/out.md")).unwrap();
289 symlink("ops/out.md", root.path().join("chain-out.md")).unwrap();
290 symlink(outside.path(), root.path().join("outside-dir")).unwrap();
291 symlink(root.path().join("ops/operator"), root.path().join("dir.md")).unwrap();
292 for name in [
293 "escape.md",
294 "dotdot.md",
295 "chain-out.md",
296 "outside-dir/AGENTS.md",
297 "dir.md",
298 ] {
299 let error = open_read_linked_within(root.path(), &root.path().join(name)).unwrap_err();
300 assert_eq!(error.kind(), io::ErrorKind::InvalidInput, "{name}: {error}");
301 }
302 assert!(
303 open_read_linked_within(root.path(), &root.path().join("escape.md"))
304 .unwrap_err()
305 .to_string()
306 .contains("outside")
307 );
308 }
309
310 #[cfg(windows)]
311 #[test]
312 fn linked_reads_follow_junctions_within_the_root_and_refuse_escapes() {
313 fn junction(link: &Path, target: &Path) {
314 let output = std::process::Command::new("cmd")
315 .args(["/C", "mklink", "/J"])
316 .arg(link)
317 .arg(target)
318 .output()
319 .unwrap();
320 assert!(output.status.success(), "{output:?}");
321 }
322 let root = tempfile::tempdir().unwrap();
323 let outside = tempfile::tempdir().unwrap();
324 fs::create_dir_all(root.path().join("ops")).unwrap();
325 fs::write(root.path().join("ops/AGENTS.md"), "shared").unwrap();
326 fs::write(outside.path().join("AGENTS.md"), "outside").unwrap();
327 junction(&root.path().join("inside"), &root.path().join("ops"));
328 junction(&root.path().join("escape"), outside.path());
329 let mut text = String::new();
330 open_read_linked_within(root.path(), &root.path().join("inside/AGENTS.md"))
331 .unwrap()
332 .read_to_string(&mut text)
333 .unwrap();
334 assert_eq!(text, "shared");
335 assert!(
336 open_read_linked_within(root.path(), &root.path().join("escape/AGENTS.md")).is_err()
337 );
338 assert!(open_read(root.path(), &root.path().join("inside/AGENTS.md")).is_err());
339 }
340
341 #[cfg(unix)]
342 #[test]
343 fn confined_writes_do_not_require_read_permission() {
344 use std::os::unix::fs::PermissionsExt;
345 let root = tempfile::tempdir().unwrap();
346 let path = root.path().join("notes.md");
347 fs::write(&path, "first").unwrap();
348 fs::set_permissions(&path, fs::Permissions::from_mode(0o200)).unwrap();
349 let mut file = open_append(root.path(), &path).unwrap();
350 assert!(file.read(&mut [0]).is_err());
351 file.write_all(b" second").unwrap();
352 drop(file);
353 fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
354 assert_eq!(fs::read_to_string(&path).unwrap(), "first second");
355 fs::set_permissions(&path, fs::Permissions::from_mode(0o200)).unwrap();
356 write(root.path(), &path, b"next").unwrap();
357 fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
358 assert_eq!(fs::read_to_string(&path).unwrap(), "next");
359 }
360
361 #[test]
362 fn append_durable_creates_nested_file_and_appends_records() {
363 let root = tempfile::tempdir().unwrap();
364 let path = root.path().join("state/nested/journal.jsonl");
365 append_durable(root.path(), &path, b"{\"seq\":1}\n").unwrap();
366 append_durable(root.path(), &path, b"{\"seq\":2}\n").unwrap();
367 assert_eq!(
368 read_to_string(root.path(), &path).unwrap(),
369 "{\"seq\":1}\n{\"seq\":2}\n"
370 );
371 assert!(append_durable(root.path(), &root.path().join("../escape.jsonl"), b"x").is_err());
372 }
373 }
374
374 lines RUST