返回 CodeWhale
files.rs
根目录 / crates / util / src / files.rs
1 //! Workspace-confined file operations shared by Fleet artifacts and its ledger.
2
3 use std::fs::File;
4 use std::io;
5 use std::path::{Component, Path};
6
7 pub struct ConfinedDirEntry {
8 pub name: String,
9 pub is_dir: bool,
10 }
11
12 pub struct ConfinedDirListing {
13 pub entries: Vec<ConfinedDirEntry>,
14 pub total_entries: usize,
15 }
16
17 pub fn path_is_confined(path: &Path) -> bool {
18 !path.as_os_str().is_empty()
19 && path.components().all(|component| match component {
20 Component::Normal(name) => !cfg!(windows) || !name.as_encoded_bytes().contains(&b':'),
21 _ => false,
22 })
23 }
24
25 /// Whether `workspace` is the user's own home directory.
26 ///
27 /// A session rooted at home is not a repository: everything below it is the
28 /// user's own global content, which the user may keep behind a link (for
29 /// example a junction onto another volume). Workspace confinement exists to
30 /// keep repository content from reaching outside itself, so a home workspace is
31 /// exempt from it.
32 pub fn workspace_is_user_home(workspace: &Path) -> bool {
33 codewhale_paths::user_home().is_some_and(|home| same_directory(&home, workspace))
34 }
35
36 fn same_directory(left: &Path, right: &Path) -> bool {
37 if left == right {
38 return true;
39 }
40 match (left.canonicalize(), right.canonicalize()) {
41 (Ok(left), Ok(right)) => left == right,
42 _ => false,
43 }
44 }
45
46 /// The `.codewhale` state directory that owns `workspace`'s application state.
47 ///
48 /// A home workspace is resolved: `~/.codewhale` may be a junction the user made
49 /// to keep state on another volume. Any other workspace returns its literal
50 /// `.codewhale`, which is still repository content. When a home state directory
51 /// exists but cannot be resolved, the literal path comes back and the caller
52 /// treats it as workspace content again — that fails closed instead of creating
53 /// a second state tree beside the one that cannot be reached.
54 #[must_use]
55 pub fn workspace_state_dir(workspace: &Path) -> std::path::PathBuf {
56 let state = workspace.join(codewhale_paths::CODEWHALE_APP_DIR);
57 resolved_home_state(workspace).unwrap_or(state)
58 }
59
60 /// `workspace`'s state directory as its real path, for a home workspace whose
61 /// `~/.codewhale` resolves. `None` is every other case: another workspace, a
62 /// missing directory (first run), or a link that cannot be reached right now.
63 fn resolved_home_state(workspace: &Path) -> Option<std::path::PathBuf> {
64 if !workspace_is_user_home(workspace) {
65 return None;
66 }
67 workspace
68 .join(codewhale_paths::CODEWHALE_APP_DIR)
69 .canonicalize()
70 .ok()
71 }
72
73 /// Confinement root and state path for `relative` beneath the workspace's
74 /// Codewhale state directory. The tuple is `(root, path)`.
75 ///
76 /// The root is the boundary a link walk starts from, and
77 /// [`reject_linked_path`] never examines the root itself — only what is below
78 /// it. So the root decides whether `.codewhale` is inspected:
79 ///
80 /// - A home workspace resolves `~/.codewhale` once and uses its target as the
81 /// root: the user's own junction is the place they chose for state, and a
82 /// path below it is still walked.
83 /// - Every other workspace keeps itself as the root with `.codewhale` still
84 /// inside the path, so a repository-supplied link is refused exactly as it
85 /// was before this helper existed.
86 ///
87 /// `relative` is joined as given and must be a relative path of literal
88 /// components. Every caller passes components it wrote itself; anything else
89 /// could step outside the state directory this root exists to bound, so the
90 /// contract is enforced in release builds too rather than only in debug ones.
91 #[must_use]
92 pub fn workspace_state_path(
93 workspace: &Path,
94 relative: &Path,
95 ) -> (std::path::PathBuf, std::path::PathBuf) {
96 assert!(
97 path_is_confined(relative),
98 "workspace state path must be a relative path of literal components: {}",
99 relative.display()
100 );
101 match resolved_home_state(workspace) {
102 Some(resolved) => {
103 let path = resolved.join(relative);
104 (resolved, path)
105 }
106 // A missing directory is the first run, created inside the home
107 // workspace itself. A directory that exists but cannot be resolved fails
108 // closed against the strict root rather than writing a second state
109 // tree beside the one that cannot be reached.
110 None => (
111 workspace.to_path_buf(),
112 workspace
113 .join(codewhale_paths::CODEWHALE_APP_DIR)
114 .join(relative),
115 ),
116 }
117 }
118
119 /// Refuse `path` when any existing component below `root` is a link. The
120 /// walk stops at the first component that does not exist yet, so a path that
121 /// is about to be created through a real directory chain passes. This is a
122 /// lexical check made before the use; prefer [`WorkspaceFile`] where the
123 /// caller can open through it, and use this for paths a library call (a
124 /// directory listing, a removal) takes by name.
125 pub fn reject_linked_path(root: &Path, path: &Path) -> io::Result<()> {
126 let relative = path.strip_prefix(root).map_err(|_| {
127 io::Error::new(
128 io::ErrorKind::InvalidInput,
129 format!("{} must stay within {}", path.display(), root.display()),
130 )
131 })?;
132 let mut current = root.to_path_buf();
133 for component in relative.components() {
134 current.push(component);
135 match std::fs::symlink_metadata(&current) {
136 Ok(metadata) if crate::path_identity::metadata_is_link_or_reparse(&metadata) => {
137 return Err(io::Error::new(
138 io::ErrorKind::InvalidInput,
139 format!("Refusing symlinked path {}", current.display()),
140 ));
141 }
142 Ok(_) => {}
143 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
144 Err(error) => return Err(error),
145 }
146 }
147 Ok(())
148 }
149
150 fn invalid_path() -> io::Error {
151 io::Error::new(
152 io::ErrorKind::InvalidInput,
153 "Fleet artifact path must stay within the workspace",
154 )
155 }
156
157 #[cfg(unix)]
158 fn open_confined_dir_fd(
159 workspace: &Path,
160 relative: Option<&Path>,
161 create: bool,
162 shared: bool,
163 resolve_root: bool,
164 expected_root: Option<&File>,
165 ) -> io::Result<File> {
166 use std::os::fd::{AsRawFd, FromRawFd};
167 use std::os::unix::ffi::OsStrExt;
168 if let Some(rel) = relative
169 && !path_is_confined(rel)
170 {
171 return Err(invalid_path());
172 }
173 let workspace = if resolve_root {
174 workspace.canonicalize()?
175 } else {
176 if !workspace.is_absolute() {
177 return Err(invalid_path());
178 }
179 workspace.to_path_buf()
180 };
181 #[cfg(any(target_os = "linux", target_os = "android"))]
182 let fd = unsafe {
183 libc::open(
184 c"/".as_ptr(),
185 libc::O_PATH | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
186 )
187 };
188 #[cfg(not(any(target_os = "linux", target_os = "android")))]
189 let fd = unsafe {
190 libc::open(
191 c"/".as_ptr(),
192 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
193 )
194 };
195 if fd < 0 {
196 return Err(io::Error::last_os_error());
197 }
198 let mut directory = unsafe { File::from_raw_fd(fd) };
199 let empty = Path::new("");
200 for (path, may_create, check_root) in [
201 (workspace.as_path(), false, expected_root),
202 (relative.unwrap_or(empty), create, None),
203 ] {
204 for component in path.components() {
205 let Component::Normal(name) = component else {
206 if component == Component::RootDir {
207 continue;
208 }
209 return Err(invalid_path());
210 };
211 let name = std::ffi::CString::new(name.as_bytes())?;
212 #[cfg(any(target_os = "linux", target_os = "android"))]
213 let flags = libc::O_PATH | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC;
214 #[cfg(not(any(target_os = "linux", target_os = "android")))]
215 let flags = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC;
216 let mut fd = unsafe { libc::openat(directory.as_raw_fd(), name.as_ptr(), flags) };
217 if fd < 0 && may_create && io::Error::last_os_error().kind() == io::ErrorKind::NotFound
218 {
219 let mode = if shared { 0o777 } else { 0o700 };
220 if unsafe { libc::mkdirat(directory.as_raw_fd(), name.as_ptr(), mode) } != 0
221 && io::Error::last_os_error().kind() != io::ErrorKind::AlreadyExists
222 {
223 return Err(io::Error::last_os_error());
224 }
225 fd = unsafe { libc::openat(directory.as_raw_fd(), name.as_ptr(), flags) };
226 }
227 if fd < 0 {
228 let err = io::Error::last_os_error();
229 if matches!(err.raw_os_error(), Some(libc::ENOTDIR) | Some(libc::ELOOP)) {
230 let mut st: libc::stat = unsafe { std::mem::zeroed() };
231 if unsafe {
232 libc::fstatat(
233 directory.as_raw_fd(),
234 name.as_ptr(),
235 &mut st,
236 libc::AT_SYMLINK_NOFOLLOW,
237 )
238 } == 0
239 && (st.st_mode & libc::S_IFMT) == libc::S_IFLNK
240 {
241 return Err(io::Error::from_raw_os_error(libc::ELOOP));
242 }
243 }
244 return Err(err);
245 }
246 directory = unsafe { File::from_raw_fd(fd) };
247 }
248 if let Some(expected) = check_root
249 && !same_file(&directory, expected)?
250 {
251 return Err(invalid_path());
252 }
253 }
254 let real_fd = unsafe {
255 libc::openat(
256 directory.as_raw_fd(),
257 c".".as_ptr(),
258 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
259 )
260 };
261 if real_fd < 0 {
262 return Err(io::Error::last_os_error());
263 }
264 Ok(unsafe { File::from_raw_fd(real_fd) })
265 }
266
267 #[cfg(unix)]
268 struct DirStream(*mut libc::DIR);
269
270 #[cfg(unix)]
271 impl Drop for DirStream {
272 fn drop(&mut self) {
273 if !self.0.is_null() {
274 unsafe {
275 libc::closedir(self.0);
276 }
277 }
278 }
279 }
280
281 #[cfg(unix)]
282 pub fn read_dir_from_fd(
283 dir_file: &File,
284 max_entries: usize,
285 mut cancelled: impl FnMut() -> bool,
286 ) -> io::Result<ConfinedDirListing> {
287 use std::os::fd::AsRawFd;
288 let iter_fd = unsafe { libc::dup(dir_file.as_raw_fd()) };
289 if iter_fd < 0 {
290 return Err(io::Error::last_os_error());
291 }
292 let raw_dir = unsafe { libc::fdopendir(iter_fd) };
293 if raw_dir.is_null() {
294 let error = io::Error::last_os_error();
295 unsafe { libc::close(iter_fd) };
296 return Err(error);
297 }
298 let stream = DirStream(raw_dir);
299 let mut entries = Vec::new();
300 let mut total_entries = 0usize;
301 loop {
302 if cancelled() {
303 return Err(io::Error::new(
304 io::ErrorKind::Interrupted,
305 "directory listing cancelled",
306 ));
307 }
308 let entry = unsafe { libc::readdir(stream.0) };
309 if entry.is_null() {
310 break;
311 }
312 let name_cstr = unsafe { std::ffi::CStr::from_ptr((*entry).d_name.as_ptr()) };
313 let name_bytes = name_cstr.to_bytes();
314 if name_bytes == b"." || name_bytes == b".." {
315 continue;
316 }
317 total_entries += 1;
318 if entries.len() >= max_entries {
319 continue;
320 }
321 let mut stat = std::mem::MaybeUninit::<libc::stat>::zeroed();
322 let st_ok = unsafe {
323 libc::fstatat(
324 dir_file.as_raw_fd(),
325 name_cstr.as_ptr(),
326 stat.as_mut_ptr(),
327 libc::AT_SYMLINK_NOFOLLOW,
328 )
329 } == 0;
330 let is_dir = if st_ok {
331 let stat = unsafe { stat.assume_init() };
332 (stat.st_mode & libc::S_IFMT) == libc::S_IFDIR
333 } else {
334 false
335 };
336 entries.push(ConfinedDirEntry {
337 name: String::from_utf8_lossy(name_bytes).into_owned(),
338 is_dir,
339 });
340 }
341 Ok(ConfinedDirListing {
342 entries,
343 total_entries,
344 })
345 }
346
347 #[cfg(unix)]
348 pub fn read_confined_dir(
349 workspace: &Path,
350 relative: Option<&Path>,
351 max_entries: usize,
352 ) -> io::Result<ConfinedDirListing> {
353 let normalized = relative.filter(|p| !p.as_os_str().is_empty() && *p != Path::new("."));
354 let dir_file = open_confined_dir_fd(workspace, normalized, false, true, true, None)?;
355 read_dir_from_fd(&dir_file, max_entries, || false)
356 }
357
358 #[cfg(unix)]
359 #[derive(Debug)]
360 pub struct WorkspaceFile {
361 directory: File,
362 filename: std::ffi::CString,
363 /// A user's own workspace file rather than a private store entry: new
364 /// entries take the process umask and replacement keeps the existing
365 /// permission bits instead of narrowing them to owner-only.
366 shared: bool,
367 }
368
369 #[cfg(unix)]
370 impl WorkspaceFile {
371 /// Private store entry: created files are 0600, created parents 0700, and
372 /// every replacement is owner-only again.
373 pub fn open(workspace: &Path, relative: &Path, create: bool) -> io::Result<Self> {
374 Self::open_confined(workspace, relative, create, false, true, None)
375 }
376
377 /// A user's workspace file, edited in place: created entries follow the
378 /// umask and replacement preserves the file's permission bits (an
379 /// executable script stays executable). Confinement is unchanged.
380 pub fn open_shared(workspace: &Path, relative: &Path, create: bool) -> io::Result<Self> {
381 Self::open_confined(workspace, relative, create, true, true, None)
382 }
383
384 pub fn open_shared_in(
385 workspace: &Path,
386 expected_root: &File,
387 relative: &Path,
388 create: bool,
389 ) -> io::Result<Self> {
390 Self::open_confined(
391 workspace,
392 relative,
393 create,
394 true,
395 false,
396 Some(expected_root),
397 )
398 }
399
400 /// An already captured absolute root: reject later root/ancestor links.
401 pub fn open_delivery(workspace: &Path, relative: &Path) -> io::Result<Self> {
402 Self::open_confined(workspace, relative, false, false, false, None)
403 }
404
405 /// Open under a root that may itself be reached through user-owned links:
406 /// the application's own state directory, which a user may have relocated
407 /// behind a symlink. The Unix opener already resolves the root and still
408 /// refuses every link below it, so this is the same call under a name that
409 /// says why a caller wants it. Not for a caller-supplied workspace root.
410 pub fn open_resolved_root(workspace: &Path, relative: &Path, create: bool) -> io::Result<Self> {
411 Self::open(workspace, relative, create)
412 }
413
414 fn open_confined(
415 workspace: &Path,
416 relative: &Path,
417 create: bool,
418 shared: bool,
419 resolve_root: bool,
420 expected_root: Option<&File>,
421 ) -> io::Result<Self> {
422 use std::os::unix::ffi::OsStrExt;
423 if !path_is_confined(relative) {
424 return Err(invalid_path());
425 }
426 let parents = relative.parent().ok_or_else(invalid_path)?;
427 let directory = open_confined_dir_fd(
428 workspace,
429 (!parents.as_os_str().is_empty()).then_some(parents),
430 create,
431 shared,
432 resolve_root,
433 expected_root,
434 )?;
435 Ok(Self {
436 directory,
437 filename: std::ffi::CString::new(
438 relative.file_name().ok_or_else(invalid_path)?.as_bytes(),
439 )?,
440 shared,
441 })
442 }
443
444 fn create_mode(&self) -> libc::c_uint {
445 if self.shared { 0o666 } else { 0o600 }
446 }
447
448 pub fn sibling(&self, name: &str) -> io::Result<Self> {
449 if !path_is_confined(Path::new(name)) || Path::new(name).components().count() != 1 {
450 return Err(invalid_path());
451 }
452 Ok(Self {
453 directory: self.directory.try_clone()?,
454 filename: std::ffi::CString::new(name)?,
455 shared: self.shared,
456 })
457 }
458
459 pub fn open_update(&self, create: bool, append: bool) -> io::Result<File> {
460 self.open_with_flags(
461 libc::O_RDWR
462 | if create { libc::O_CREAT } else { 0 }
463 | if append { libc::O_APPEND } else { 0 },
464 )
465 }
466
467 pub fn open_file(&self) -> io::Result<File> {
468 self.open_with_flags(libc::O_RDONLY)
469 }
470
471 /// Reads a file another process may hold open for writing. Unix opens do
472 /// not exclude writers, so this is [`Self::open_file`].
473 pub fn open_file_shared(&self) -> io::Result<File> {
474 self.open_file()
475 }
476
477 pub fn open_write(&self, append: bool) -> io::Result<File> {
478 self.open_with_flags(
479 libc::O_WRONLY | libc::O_CREAT | if append { libc::O_APPEND } else { 0 },
480 )
481 }
482
483 fn open_with_flags(&self, flags: libc::c_int) -> io::Result<File> {
484 self.open_with_flags_and_max_links(flags, 1)
485 }
486
487 fn open_with_flags_and_max_links(
488 &self,
489 flags: libc::c_int,
490 max_links: u64,
491 ) -> io::Result<File> {
492 use std::os::fd::{AsRawFd, FromRawFd};
493 use std::os::unix::fs::MetadataExt;
494 // macOS can fail an `openat(O_CREAT)` with ENOENT while another thread
495 // is creating the same name through the same pinned directory, even
496 // though the parent exists. The loser of that race only has to ask
497 // again: the file is there by then. The retry is bounded and applies
498 // only when creating, so a vanished parent still fails.
499 let mut attempts = 0;
500 let fd = loop {
501 // SAFETY: a pinned parent and validated basename; never follows links.
502 let fd = unsafe {
503 libc::openat(
504 self.directory.as_raw_fd(),
505 self.filename.as_ptr(),
506 flags | libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK,
507 self.create_mode(),
508 )
509 };
510 if fd >= 0 {
511 break fd;
512 }
513 let error = io::Error::last_os_error();
514 attempts += 1;
515 if flags & libc::O_CREAT != 0 && error.kind() == io::ErrorKind::NotFound && attempts < 4
516 {
517 std::thread::yield_now();
518 continue;
519 }
520 return Err(error);
521 };
522 // SAFETY: fd is freshly owned.
523 let file = unsafe { File::from_raw_fd(fd) };
524 let metadata = file.metadata()?;
525 if !metadata.is_file() || !(1..=max_links).contains(&metadata.nlink()) {
526 return Err(io::Error::new(
527 io::ErrorKind::InvalidData,
528 "Fleet file must be a regular, non-hard-linked file",
529 ));
530 }
531 Ok(file)
532 }
533
534 pub fn publish(&self, bytes: &[u8]) -> io::Result<()> {
535 self.atomic_write(bytes, false)
536 }
537
538 pub fn publish_from_reader(&self, reader: &mut impl io::Read) -> io::Result<()> {
539 self.atomic_write_retained(reader, false, None, true)
540 .map(drop)
541 }
542
543 pub fn replace(&self, bytes: &[u8]) -> io::Result<()> {
544 self.atomic_write(bytes, true)
545 }
546
547 pub fn replace_siblings(&self, files: &[(String, Vec<u8>)]) -> io::Result<()> {
548 for (name, bytes) in files {
549 self.sibling(name)?.atomic_write_retained(
550 &mut io::Cursor::new(bytes),
551 true,
552 None,
553 false,
554 )?;
555 }
556 self.sync_parent()
557 }
558
559 fn atomic_write(&self, bytes: &[u8], replace: bool) -> io::Result<()> {
560 self.atomic_write_retained(&mut io::Cursor::new(bytes), replace, None, true)
561 .map(drop)
562 }
563
564 pub fn publish_retained(&self, bytes: &[u8], executable: bool) -> io::Result<File> {
565 self.atomic_write_retained(
566 &mut io::Cursor::new(bytes),
567 false,
568 Some(if executable { 0o755 } else { 0o644 }),
569 true,
570 )
571 }
572
573 fn atomic_write_retained(
574 &self,
575 reader: &mut impl io::Read,
576 replace: bool,
577 mode: Option<u32>,
578 sync_parent: bool,
579 ) -> io::Result<File> {
580 use std::os::fd::{AsRawFd, FromRawFd};
581 let temporary =
582 std::ffi::CString::new(format!(".fleet-write-{}.tmp", uuid::Uuid::new_v4()))
583 .expect("generated basename");
584 // SAFETY: parent is pinned; exclusive creation cannot follow a link.
585 let fd = unsafe {
586 libc::openat(
587 self.directory.as_raw_fd(),
588 temporary.as_ptr(),
589 libc::O_RDWR | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC,
590 self.create_mode(),
591 )
592 };
593 if fd < 0 {
594 return Err(io::Error::last_os_error());
595 }
596 // SAFETY: fd is freshly owned.
597 let mut file = unsafe { File::from_raw_fd(fd) };
598 let result = (|| {
599 if self.shared && replace {
600 self.copy_permissions_to(&file)?;
601 }
602 if let Some(mode) = mode {
603 use std::os::unix::fs::PermissionsExt;
604 // The file was just created with the caller's access bits, so
605 // this only matters on a mount that applied its own. There it
606 // answers EPERM for every `chmod`, and the delivery still has
607 // to land: the handle, the single link and the publication
608 // below are what this writer guarantees.
609 if let Err(error) = file.set_permissions(std::fs::Permissions::from_mode(mode))
610 && !mount_cannot_extend_guard(&self.directory)
611 {
612 return Err(error);
613 }
614 }
615 io::copy(reader, &mut file)?;
616 file.sync_all()?;
617 if !replace
618 && rename_exclusive(
619 self.directory.as_raw_fd(),
620 &temporary,
621 self.directory.as_raw_fd(),
622 &self.filename,
623 )?
624 {
625 return Ok(true);
626 }
627 // SAFETY: both basenames are anchored to the same open parent.
628 // Replacement changes the directory entry, never a symlink target.
629 let published = unsafe {
630 if replace {
631 libc::renameat(
632 self.directory.as_raw_fd(),
633 temporary.as_ptr(),
634 self.directory.as_raw_fd(),
635 self.filename.as_ptr(),
636 )
637 } else {
638 libc::linkat(
639 self.directory.as_raw_fd(),
640 temporary.as_ptr(),
641 self.directory.as_raw_fd(),
642 self.filename.as_ptr(),
643 0,
644 )
645 }
646 };
647 if published != 0 {
648 return Err(io::Error::last_os_error());
649 }
650 Ok(replace)
651 })();
652 // Successful rename already consumed this temporary entry. Never
653 // unlink the vacant old name, which another writer could now reuse.
654 if !matches!(result, Ok(true)) {
655 // SAFETY: unlink this call's exclusive temporary basename.
656 if unsafe { libc::unlinkat(self.directory.as_raw_fd(), temporary.as_ptr(), 0) } != 0 {
657 return Err(io::Error::last_os_error());
658 }
659 }
660 result?;
661 if sync_parent {
662 self.sync_parent()?;
663 }
664 Ok(file)
665 }
666
667 pub fn open_retained(&self) -> io::Result<File> {
668 self.open_retained_with_max_links(1)
669 }
670
671 /// Open a delivery file while bounding its permitted Unix hard-link count.
672 pub fn open_retained_with_max_links(&self, max_links: u64) -> io::Result<File> {
673 self.open_with_flags_and_max_links(libc::O_RDONLY, max_links)
674 }
675
676 pub fn identity_probe(&self) -> io::Result<File> {
677 self.identity_probe_with_max_links(1)
678 }
679
680 /// Probe a delivery path while bounding its permitted Unix hard-link count.
681 pub fn identity_probe_with_max_links(&self, max_links: u64) -> io::Result<File> {
682 self.open_with_flags_and_max_links(libc::O_RDONLY, max_links)
683 }
684
685 pub fn move_opened_to_sibling(&self, file: &File, destination: &Self) -> io::Result<()> {
686 if !same_file(&self.directory, &destination.directory)? {
687 return Err(invalid_path());
688 }
689 // Retirement must be one no-clobber rename. The link/unlink fallback
690 // used by immutable publication is not a conditional move of an old entry.
691 self.move_opened_to_directory(file, destination)
692 }
693
694 pub fn verify_delivery_owner(&self, file: &File) -> io::Result<()> {
695 self.verify_delivery_owner_with_max_links(file, 1)
696 }
697
698 /// Verify parent and file ownership/permissions while bounding permitted links.
699 pub fn verify_delivery_owner_with_max_links(
700 &self,
701 file: &File,
702 max_links: u64,
703 ) -> io::Result<()> {
704 use std::os::unix::fs::MetadataExt;
705 let owner = codewhale_config::private_directory::PrivateDirectory::current_user_id();
706 let parent = self.directory.metadata()?;
707 let entry = file.metadata()?;
708 let public = parent.uid() != owner
709 || parent.mode() & 0o022 != 0
710 || entry.uid() != owner
711 || entry.mode() & 0o022 != 0;
712 // A mount that reports an owner and mode of its own (HarmonyOS hmdfs
713 // reports the logged-in user's uid and a group-writable mode for every
714 // object) cannot satisfy any of those fields. Only a disagreement asks
715 // the mount, so a filesystem that stores them never pays for the probe
716 // and a delivery that already looks private is never delayed.
717 if public && !mount_cannot_extend_guard(&self.directory) {
718 return Err(io::Error::new(
719 io::ErrorKind::PermissionDenied,
720 "delivery file and retained parent must be owned by the current user and not writable by group or others",
721 ));
722 }
723 if !same_file(file, &self.identity_probe_with_max_links(max_links)?)? {
724 return Err(invalid_path());
725 }
726 Ok(())
727 }
728
729 pub fn move_opened_to_directory(&self, file: &File, destination: &Self) -> io::Result<()> {
730 self.move_opened_to_directory_with_max_links(file, destination, 1)
731 }
732
733 /// Move an opened delivery entry into a destination directory while bounding permitted links.
734 pub fn move_opened_to_directory_with_max_links(
735 &self,
736 file: &File,
737 destination: &Self,
738 max_links: u64,
739 ) -> io::Result<()> {
740 use std::os::fd::AsRawFd;
741 if !same_file(file, &self.identity_probe_with_max_links(max_links)?)? {
742 return Err(invalid_path());
743 }
744 if !rename_exclusive(
745 self.directory.as_raw_fd(),
746 &self.filename,
747 destination.directory.as_raw_fd(),
748 &destination.filename,
749 )? {
750 return Err(io::Error::new(
751 io::ErrorKind::Unsupported,
752 "exclusive retirement is unavailable",
753 ));
754 }
755 Ok(())
756 }
757
758 pub fn unlink_opened(&self, file: &File) -> io::Result<()> {
759 self.unlink_opened_with_max_links(file, 1)
760 }
761
762 /// Unlink an opened delivery entry after verifying its private parent and bounded links.
763 pub fn unlink_opened_with_max_links(&self, file: &File, max_links: u64) -> io::Result<()> {
764 use std::os::fd::AsRawFd;
765 use std::os::unix::fs::MetadataExt;
766 let parent = self.directory.metadata()?;
767 let public = parent.mode() & 0o077 != 0 || parent.uid() != unsafe { libc::geteuid() };
768 let unverified = public && !mount_cannot_extend_guard(&self.directory);
769 if unverified || !same_file(file, &self.identity_probe_with_max_links(max_links)?)? {
770 return Err(invalid_path());
771 }
772 if unsafe { libc::unlinkat(self.directory.as_raw_fd(), self.filename.as_ptr(), 0) } != 0 {
773 return Err(io::Error::last_os_error());
774 }
775 Ok(())
776 }
777
778 pub fn sync_parent(&self) -> io::Result<()> {
779 self.directory.sync_all()
780 }
781 }
782
783 #[cfg(unix)]
784 impl WorkspaceFile {
785 /// Give the replacement the permission bits of the regular file it
786 /// replaces. Set-id bits are never carried over; an absent target keeps
787 /// the umask-derived creation mode.
788 fn copy_permissions_to(&self, replacement: &File) -> io::Result<()> {
789 use std::os::fd::AsRawFd;
790 // SAFETY: zeroed plain-data struct, filled by fstatat on success.
791 let mut stat: libc::stat = unsafe { std::mem::zeroed() };
792 // SAFETY: pinned parent, validated basename, and no link following.
793 let found = unsafe {
794 libc::fstatat(
795 self.directory.as_raw_fd(),
796 self.filename.as_ptr(),
797 &mut stat,
798 libc::AT_SYMLINK_NOFOLLOW,
799 )
800 };
801 if found != 0 {
802 let error = io::Error::last_os_error();
803 return if error.kind() == io::ErrorKind::NotFound {
804 Ok(())
805 } else {
806 Err(error)
807 };
808 }
809 if (stat.st_mode & libc::S_IFMT) != libc::S_IFREG {
810 return Ok(());
811 }
812 // SAFETY: an owned, open descriptor; fchmod never follows a path.
813 if unsafe { libc::fchmod(replacement.as_raw_fd(), stat.st_mode & 0o777) } != 0 {
814 return Err(io::Error::last_os_error());
815 }
816 Ok(())
817 }
818 }
819
820 /// Publish `from` as `to` without replacing an existing entry, as the Windows
821 /// rename below does. `linkat` then `unlinkat` leaves the published file with
822 /// two links for a moment, and `open_with_flags` rejects a link count other
823 /// than 1, so a concurrent reader failed with InvalidData. `Ok(false)` sends
824 /// the caller back to `linkat`, which keeps that window: other Unixes, and any
825 /// kernel, filesystem or sandbox that refuses the exclusive rename.
826 #[cfg(any(target_os = "linux", target_os = "android"))]
827 fn rename_exclusive(
828 directory: libc::c_int,
829 from: &std::ffi::CStr,
830 destination: libc::c_int,
831 to: &std::ffi::CStr,
832 ) -> io::Result<bool> {
833 // SAFETY: both basenames are anchored to their retained open parents.
834 let renamed = unsafe {
835 libc::syscall(
836 libc::SYS_renameat2,
837 directory,
838 from.as_ptr(),
839 destination,
840 to.as_ptr(),
841 libc::RENAME_NOREPLACE,
842 )
843 };
844 exclusive_rename_outcome(renamed == 0)
845 }
846
847 #[cfg(target_vendor = "apple")]
848 fn rename_exclusive(
849 directory: libc::c_int,
850 from: &std::ffi::CStr,
851 destination: libc::c_int,
852 to: &std::ffi::CStr,
853 ) -> io::Result<bool> {
854 // SAFETY: both basenames are anchored to their retained open parents.
855 let renamed = unsafe {
856 libc::renameatx_np(
857 directory,
858 from.as_ptr(),
859 destination,
860 to.as_ptr(),
861 libc::RENAME_EXCL,
862 )
863 };
864 exclusive_rename_outcome(renamed == 0)
865 }
866
867 #[cfg(all(
868 unix,
869 not(any(target_os = "linux", target_os = "android", target_vendor = "apple"))
870 ))]
871 fn rename_exclusive(
872 _: libc::c_int,
873 _: &std::ffi::CStr,
874 _: libc::c_int,
875 _: &std::ffi::CStr,
876 ) -> io::Result<bool> {
877 Ok(false)
878 }
879
880 /// Only an existing target is final. Any other refusal falls back to `linkat`,
881 /// so publication is never worse off than before the exclusive rename.
882 #[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
883 fn exclusive_rename_outcome(renamed: bool) -> io::Result<bool> {
884 if renamed {
885 return Ok(true);
886 }
887 let error = io::Error::last_os_error();
888 if error.kind() == io::ErrorKind::AlreadyExists {
889 return Err(error);
890 }
891 Ok(false)
892 }
893
894 #[cfg(windows)]
895 pub fn read_confined_dir(
896 workspace: &Path,
897 relative: Option<&Path>,
898 max_entries: usize,
899 ) -> io::Result<ConfinedDirListing> {
900 let normalized = relative.filter(|p| !p.as_os_str().is_empty() && *p != Path::new("."));
901 if let Some(rel) = normalized
902 && !path_is_confined(rel)
903 {
904 return Err(invalid_path());
905 }
906 let resolved = workspace.canonicalize()?;
907 let root = WindowsDirectory::open(&resolved)?;
908 let pinned = match normalized {
909 Some(rel) => WindowsDirectory::open_inner(&resolved.join(rel), false, false)?,
910 None => WindowsDirectory::open(&resolved)?,
911 };
912 let mut entries = Vec::new();
913 let mut total_entries = 0usize;
914 for entry in std::fs::read_dir(&pinned.directory)? {
915 let entry = entry?;
916 total_entries += 1;
917 if entries.len() >= max_entries {
918 continue;
919 }
920 let file_type = entry.file_type()?;
921 let is_reparse = file_type.is_symlink()
922 || std::fs::symlink_metadata(entry.path())
923 .ok()
924 .is_some_and(|meta| crate::path_identity::metadata_is_link_or_reparse(&meta));
925 entries.push(ConfinedDirEntry {
926 name: entry.file_name().to_string_lossy().to_string(),
927 is_dir: file_type.is_dir() && !is_reparse,
928 });
929 }
930 let _keep_root_pinned = root;
931 Ok(ConfinedDirListing {
932 entries,
933 total_entries,
934 })
935 }
936
937 /// Windows path fence shared by Fleet publication and Native sandbox ACL
938 /// admission. Every original absolute ancestor is opened without delete/write
939 /// sharing and without following reparse points before path-based calls.
940 #[cfg(windows)]
941 #[derive(Clone, Debug)]
942 pub struct WindowsDirectory {
943 ancestors: Vec<std::sync::Arc<File>>,
944 directory: std::path::PathBuf,
945 }
946
947 #[cfg(windows)]
948 impl WindowsDirectory {
949 pub fn open(path: &Path) -> io::Result<Self> {
950 Self::open_inner(path, false, false)
951 }
952
953 fn open_inner(path: &Path, create: bool, acl_target: bool) -> io::Result<Self> {
954 if !path.is_absolute() {
955 return Err(invalid_path());
956 }
957 let mut directory = std::path::PathBuf::new();
958 let mut ancestors = Vec::new();
959 let count = path.components().count();
960 for (index, component) in path.components().enumerate() {
961 if matches!(component, Component::ParentDir | Component::CurDir) {
962 return Err(invalid_path());
963 }
964 directory.push(component.as_os_str());
965 if matches!(component, Component::Prefix(_)) {
966 continue;
967 }
968 let open = || Self::open_component(&directory, acl_target && index + 1 == count);
969 let file = match open() {
970 Err(error) if create && error.kind() == io::ErrorKind::NotFound => {
971 match std::fs::create_dir(&directory) {
972 Ok(()) => {}
973 Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
974 Err(error) => return Err(error),
975 }
976 open()?
977 }
978 result => result?,
979 };
980 ancestors.push(file);
981 }
982 Ok(Self {
983 ancestors,
984 directory,
985 })
986 }
987
988 fn open_component(path: &Path, acl_target: bool) -> io::Result<std::sync::Arc<File>> {
989 use std::os::windows::fs::OpenOptionsExt;
990 let mut options = std::fs::OpenOptions::new();
991 options.read(true).share_mode(1).custom_flags(0x0220_0000);
992 if acl_target {
993 // The Native ACL writer uses SetKernelObjectSecurity, which never
994 // propagates to descendants; each child is fenced and granted
995 // explicitly. So the target needs only READ_CONTROL|WRITE_DAC plus a
996 // read right that records share access: read-only sharing still
997 // blocks rename, delete and data writes while it is edited. Unlike
998 // MAXIMUM_ALLOWED, which includes DELETE, it does not collide with a
999 // live host whose current directory is this directory.
1000 use windows_sys::Win32::Storage::FileSystem::{
1001 FILE_LIST_DIRECTORY, FILE_READ_ATTRIBUTES, READ_CONTROL, WRITE_DAC,
1002 };
1003 options
1004 .access_mode(READ_CONTROL | WRITE_DAC | FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES);
1005 }
1006 let file = retry_windows_io(false, || options.open(path))?;
1007 let metadata = file.metadata()?;
1008 if crate::path_identity::metadata_is_link_or_reparse(&metadata) {
1009 return Err(invalid_path());
1010 }
1011 if !metadata.is_dir() {
1012 return Err(io::Error::new(
1013 io::ErrorKind::NotADirectory,
1014 "target must be a directory",
1015 ));
1016 }
1017 Ok(std::sync::Arc::new(file))
1018 }
1019
1020 pub fn child_path(&self, name: &std::ffi::OsStr) -> io::Result<std::path::PathBuf> {
1021 let name = Path::new(name);
1022 if !path_is_confined(name) || name.components().count() != 1 {
1023 return Err(invalid_path());
1024 }
1025 Ok(self.directory.join(name))
1026 }
1027
1028 /// Extend the actual held direct-parent chain instead of reopening pinned
1029 /// ancestors by path.
1030 pub fn open_acl_child(&self, name: &std::ffi::OsStr) -> io::Result<Self> {
1031 let directory = self.child_path(name)?;
1032 let file = Self::open_component(&directory, true)?;
1033 let mut ancestors = self.ancestors.clone();
1034 ancestors.push(file);
1035 Ok(Self {
1036 ancestors,
1037 directory,
1038 })
1039 }
1040
1041 pub fn open_acl(path: &Path) -> io::Result<Self> {
1042 Self::open_inner(path, false, true)
1043 }
1044
1045 pub fn acl_handle(&self) -> io::Result<&File> {
1046 self.ancestors
1047 .last()
1048 .map(std::sync::Arc::as_ref)
1049 .ok_or_else(invalid_path)
1050 }
1051 }
1052
1053 #[cfg(windows)]
1054 #[derive(Debug)]
1055 pub struct WorkspaceFile {
1056 // Retaining every ancestor without delete/write sharing prevents a path
1057 // swap or junction replacement while path-based Windows calls are running.
1058 _ancestors: Vec<std::sync::Arc<File>>,
1059 directory: std::path::PathBuf,
1060 filename: std::ffi::OsString,
1061 }
1062
1063 #[cfg(windows)]
1064 impl WorkspaceFile {
1065 pub fn open(workspace: &Path, relative: &Path, create: bool) -> io::Result<Self> {
1066 Self::open_confined(workspace, relative, create, None)
1067 }
1068
1069 pub fn open_shared_in(
1070 workspace: &Path,
1071 expected_root: &File,
1072 relative: &Path,
1073 create: bool,
1074 ) -> io::Result<Self> {
1075 Self::open_confined(workspace, relative, create, Some(expected_root))
1076 }
1077
1078 fn open_confined(
1079 workspace: &Path,
1080 relative: &Path,
1081 create: bool,
1082 expected_root: Option<&File>,
1083 ) -> io::Result<Self> {
1084 if !path_is_confined(relative) {
1085 return Err(invalid_path());
1086 }
1087 // Preserve the original spelling until links/reparse points have been
1088 // refused. Canonicalization must not turn a linked root into authority.
1089 let workspace = if workspace.is_absolute() {
1090 workspace.to_path_buf()
1091 } else {
1092 std::env::current_dir()?.join(workspace)
1093 };
1094 let root = WindowsDirectory::open(&workspace)?;
1095 if let Some(expected) = expected_root
1096 && !same_file(root.acl_handle()?, expected)?
1097 {
1098 return Err(invalid_path());
1099 }
1100 let target = workspace.join(relative.parent().ok_or_else(invalid_path)?);
1101 let mut pinned = WindowsDirectory::open_inner(&target, create, false)?;
1102 pinned.ancestors.extend(root.ancestors);
1103 let ancestors = pinned.ancestors;
1104 let directory = pinned.directory;
1105 Ok(Self {
1106 _ancestors: ancestors,
1107 directory,
1108 filename: relative.file_name().ok_or_else(invalid_path)?.to_owned(),
1109 })
1110 }
1111
1112 /// Open under a root that may itself be reached through user-owned links:
1113 /// the application's own state directory, which a user may have relocated
1114 /// behind a junction. The root is resolved once to its real directory and
1115 /// the same link-refusing walk then runs, so links below the root are still
1116 /// refused. The caller must have created the root already. Not for a
1117 /// caller-supplied workspace root.
1118 pub fn open_resolved_root(workspace: &Path, relative: &Path, create: bool) -> io::Result<Self> {
1119 let resolved = workspace.canonicalize()?;
1120 Self::open(&resolved, relative, create)
1121 }
1122
1123 pub fn open_delivery(workspace: &Path, relative: &Path) -> io::Result<Self> {
1124 Self::open(workspace, relative, false)
1125 }
1126
1127 /// Windows has no Unix permission bits to preserve; see the Unix opener.
1128 pub fn open_shared(workspace: &Path, relative: &Path, create: bool) -> io::Result<Self> {
1129 Self::open(workspace, relative, create)
1130 }
1131
1132 pub fn sibling(&self, name: &str) -> io::Result<Self> {
1133 if !path_is_confined(Path::new(name)) || Path::new(name).components().count() != 1 {
1134 return Err(invalid_path());
1135 }
1136 Ok(Self {
1137 _ancestors: self._ancestors.clone(),
1138 directory: self.directory.clone(),
1139 filename: name.into(),
1140 })
1141 }
1142
1143 pub fn open_update(&self, create: bool, append: bool) -> io::Result<File> {
1144 self.open_with_access(create, append, true, true)
1145 }
1146
1147 pub fn open_write(&self, append: bool) -> io::Result<File> {
1148 self.open_with_access(true, append, false, true)
1149 }
1150
1151 /// Reads a file another process may hold open for writing (a running
1152 /// worker's log). [`Self::open_file`] denies concurrent writers, so it
1153 /// fails with a sharing violation while the writer is alive; this opens
1154 /// read-only with full sharing and applies the same regular, unlinked
1155 /// checks to the handle.
1156 pub fn open_file_shared(&self) -> io::Result<File> {
1157 self.open_with_access(false, false, true, false)
1158 }
1159
1160 fn open_with_access(
1161 &self,
1162 create: bool,
1163 append: bool,
1164 read: bool,
1165 write: bool,
1166 ) -> io::Result<File> {
1167 use std::os::windows::fs::OpenOptionsExt;
1168 let file = std::fs::OpenOptions::new()
1169 .read(read)
1170 .write(write)
1171 .append(append)
1172 .create(create)
1173 .truncate(false)
1174 .share_mode(0x0000_0007)
1175 .custom_flags(0x0020_0000)
1176 .open(self.directory.join(&self.filename))?;
1177 let metadata = file.metadata()?;
1178 if !metadata.is_file()
1179 || crate::path_identity::metadata_is_link_or_reparse(&metadata)
1180 || crate::path_identity::windows_file_identity(&file)?.links != 1
1181 {
1182 return Err(io::Error::new(
1183 io::ErrorKind::InvalidData,
1184 "Fleet file must be regular and not linked",
1185 ));
1186 }
1187 Ok(file)
1188 }
1189
1190 pub fn open_file(&self) -> io::Result<File> {
1191 // Existing protected reader rejects reparse points, hard links and
1192 // non-regular files, and denies concurrent writes/replacement.
1193 crate::bundle_file::open_bundle_file(&self.directory.join(&self.filename))
1194 }
1195
1196 pub fn publish(&self, bytes: &[u8]) -> io::Result<()> {
1197 self.atomic_write(bytes, false)
1198 }
1199
1200 pub fn publish_from_reader(&self, reader: &mut impl io::Read) -> io::Result<()> {
1201 self.atomic_write_retained(reader, false).map(drop)
1202 }
1203
1204 pub fn replace(&self, bytes: &[u8]) -> io::Result<()> {
1205 self.atomic_write(bytes, true)
1206 }
1207
1208 fn atomic_write(&self, bytes: &[u8], replace: bool) -> io::Result<()> {
1209 self.atomic_write_retained(&mut io::Cursor::new(bytes), replace)
1210 .map(drop)
1211 }
1212
1213 pub fn replace_siblings(&self, files: &[(String, Vec<u8>)]) -> io::Result<()> {
1214 for (name, bytes) in files {
1215 self.sibling(name)?.replace(bytes)?;
1216 }
1217 Ok(())
1218 }
1219
1220 pub fn publish_retained(&self, bytes: &[u8], _executable: bool) -> io::Result<File> {
1221 self.atomic_write_retained(&mut io::Cursor::new(bytes), false)
1222 }
1223
1224 pub fn open_retained(&self) -> io::Result<File> {
1225 crate::bundle_file::open_bundle_file_for_retirement(&self.directory.join(&self.filename))
1226 }
1227
1228 /// Windows delivery files remain strictly single-link.
1229 pub fn open_retained_with_max_links(&self, _max_links: u64) -> io::Result<File> {
1230 self.open_retained()
1231 }
1232
1233 pub fn identity_probe(&self) -> io::Result<File> {
1234 crate::bundle_file::open_bundle_identity_probe(&self.directory.join(&self.filename), false)
1235 }
1236
1237 /// Windows delivery identity probes remain strictly single-link.
1238 pub fn identity_probe_with_max_links(&self, _max_links: u64) -> io::Result<File> {
1239 self.identity_probe()
1240 }
1241
1242 pub fn move_opened_to_sibling(&self, file: &File, destination: &Self) -> io::Result<()> {
1243 if self.directory != destination.directory {
1244 return Err(invalid_path());
1245 }
1246 rename_windows_opened(file, &destination.filename, false)
1247 }
1248
1249 pub fn sync_parent(&self) -> io::Result<()> {
1250 Ok(())
1251 }
1252
1253 fn atomic_write_retained(&self, reader: &mut impl io::Read, replace: bool) -> io::Result<File> {
1254 use std::os::windows::fs::OpenOptionsExt;
1255 use windows_sys::Win32::Storage::FileSystem::{
1256 DELETE, FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_SHARE_READ,
1257 };
1258
1259 let mut temporary = retry_windows_io(false, || {
1260 tempfile::Builder::new()
1261 .prefix(".fleet-write-")
1262 .make_in(&self.directory, |path| {
1263 std::fs::OpenOptions::new()
1264 .write(true)
1265 .create_new(true)
1266 .access_mode(FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE)
1267 .share_mode(FILE_SHARE_READ)
1268 .open(path)
1269 })
1270 })?;
1271 let result = (|| {
1272 io::copy(reader, &mut temporary)?;
1273 temporary.as_file().sync_all()?;
1274
1275 rename_windows_opened(temporary.as_file(), &self.filename, replace)
1276 })();
1277 match result {
1278 Ok(()) => {
1279 // The old name is vacant after the rename; do not unlink an
1280 // entry another process might create there afterwards.
1281 temporary.disable_cleanup(true);
1282 Ok(temporary.into_file())
1283 }
1284 Err(error) => {
1285 // Close the source's delete-denying handle before cleanup.
1286 temporary.into_temp_path().close()?;
1287 Err(error)
1288 }
1289 }
1290 }
1291 }
1292
1293 #[cfg(windows)]
1294 fn retry_windows_io<T>(
1295 include_permission_denied: bool,
1296 mut op: impl FnMut() -> io::Result<T>,
1297 ) -> io::Result<T> {
1298 let mut attempt = 0;
1299 loop {
1300 match op() {
1301 Ok(value) => return Ok(value),
1302 Err(error)
1303 if matches!(error.raw_os_error(), Some(32 | 33))
1304 || (include_permission_denied
1305 && (error.kind() == io::ErrorKind::PermissionDenied
1306 || error.raw_os_error() == Some(5))) =>
1307 {
1308 let Some(backoff) = crate::utils::windows_publish_retry_delay(&error, attempt)
1309 else {
1310 return Err(error);
1311 };
1312 std::thread::sleep(backoff);
1313 attempt += 1;
1314 }
1315 Err(error) => return Err(error),
1316 }
1317 }
1318 }
1319
1320 #[cfg(windows)]
1321 pub fn rename_windows_opened(
1322 file: &File,
1323 filename: &std::ffi::OsStr,
1324 replace: bool,
1325 ) -> io::Result<()> {
1326 use std::mem::{offset_of, size_of};
1327 use std::os::windows::ffi::OsStrExt;
1328 use std::os::windows::io::AsRawHandle;
1329 use windows_sys::Wdk::Storage::FileSystem::{
1330 FILE_RENAME_INFORMATION, FileRenameInformation, NtSetInformationFile,
1331 };
1332 use windows_sys::Win32::Foundation::RtlNtStatusToDosError;
1333 use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;
1334 // MoveFileExW (including tempfile::persist) reopens the destination
1335 // directory with FILE_ADD_FILE, conflicting with our ancestor pins.
1336 // A native rename with no root handle and a single basename uses
1337 // the source file's existing parent instead. Keep all ancestor and
1338 // source handles pinned; never relax their write/delete guards.
1339 // https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_rename_information
1340 let name = filename.encode_wide().collect::<Vec<_>>();
1341 let name_bytes = name.len() * size_of::<u16>();
1342 let buffer_size = (offset_of!(FILE_RENAME_INFORMATION, FileName) + name_bytes)
1343 .max(size_of::<FILE_RENAME_INFORMATION>());
1344 let mut buffer = vec![0_usize; buffer_size.div_ceil(size_of::<usize>())];
1345 let rename = buffer.as_mut_ptr().cast::<FILE_RENAME_INFORMATION>();
1346 // SAFETY: the zeroed buffer is aligned and covers the struct plus
1347 // the complete UTF-16 basename; no root means the source's parent.
1348 unsafe {
1349 (*rename).Anonymous.ReplaceIfExists = replace;
1350 (*rename).FileNameLength = name_bytes as u32;
1351 std::ptr::copy_nonoverlapping(name.as_ptr(), (*rename).FileName.as_mut_ptr(), name.len());
1352 }
1353 retry_windows_io(true, || {
1354 let mut status = IO_STATUS_BLOCK::default();
1355 // SAFETY: this synchronously opened file has DELETE access;
1356 // every handle and buffer remains live throughout the call.
1357 let result = unsafe {
1358 NtSetInformationFile(
1359 file.as_raw_handle(),
1360 &mut status,
1361 rename.cast(),
1362 buffer_size as u32,
1363 FileRenameInformation,
1364 )
1365 };
1366 if result >= 0 {
1367 Ok(())
1368 } else {
1369 // SAFETY: converts the returned NTSTATUS without dereferencing.
1370 Err(io::Error::from_raw_os_error(unsafe {
1371 RtlNtStatusToDosError(result) as i32
1372 }))
1373 }
1374 })
1375 }
1376
1377 /// Whether `directory`'s filesystem reports an owner and mode of its own for
1378 /// objects created in it, so neither can serve as evidence about this file.
1379 ///
1380 /// The question is the one [`codewhale_config::private_directory::private_footing`]
1381 /// answers, asked through the directory handle the caller already holds: no
1382 /// path is involved, so nothing outside this directory can be reached, and the
1383 /// answer is cached per directory so a write path pays for it at most once.
1384 /// Only a directory this process cannot write to answers `false`, which keeps
1385 /// the strict error above — that is a real problem, and not this one.
1386 #[cfg(unix)]
1387 fn mount_cannot_extend_guard(directory: &std::fs::File) -> bool {
1388 matches!(
1389 codewhale_config::private_directory::mount_footing_of(directory),
1390 codewhale_config::private_directory::PrivateFooting::Synthesised { .. }
1391 )
1392 }
1393
1394 #[cfg(all(test, unix))]
1395 mod unix_publication_tests {
1396 use super::*;
1397 use std::io::Read;
1398
1399 /// Several threads creating one new name through their own pinned handles
1400 /// must all succeed. macOS can fail the losers of that race with ENOENT
1401 /// unless the open asks again.
1402 #[test]
1403 fn racing_creates_of_one_name_all_succeed() {
1404 let workspace = tempfile::tempdir().unwrap();
1405 for round in 0..40 {
1406 let relative = std::path::PathBuf::from(format!("locks-{round}/manager.lock"));
1407 std::thread::scope(|scope| {
1408 let workers: Vec<_> = (0..4)
1409 .map(|_| {
1410 scope.spawn(|| {
1411 WorkspaceFile::open(workspace.path(), &relative, true)
1412 .and_then(|file| file.open_update(true, false))
1413 })
1414 })
1415 .collect();
1416 for worker in workers {
1417 worker
1418 .join()
1419 .unwrap()
1420 .expect("every racing create succeeds");
1421 }
1422 });
1423 }
1424 }
1425
1426 #[test]
1427 fn a_racing_reader_never_sees_a_publication_half_done() {
1428 // Identical replays publish the same handle concurrently and the loser
1429 // reads the winner's file back. A reader that lands between linkat and
1430 // the temporary's unlink sees two links, which open_file rejects.
1431 let workspace = tempfile::tempdir().unwrap();
1432 for round in 0..50 {
1433 let relative = std::path::PathBuf::from(format!("receipt-{round}.json"));
1434 let writer = WorkspaceFile::open(workspace.path(), &relative, true).unwrap();
1435 let reader = WorkspaceFile::open(workspace.path(), &relative, false).unwrap();
1436 std::thread::scope(|scope| {
1437 let read = scope.spawn(|| {
1438 loop {
1439 match reader.open_file() {
1440 Ok(mut file) => {
1441 let mut bytes = Vec::new();
1442 file.read_to_end(&mut bytes).unwrap();
1443 break bytes;
1444 }
1445 Err(error) if error.kind() == io::ErrorKind::NotFound => {
1446 std::hint::spin_loop();
1447 }
1448 Err(error) => panic!("round {round}: {error}"),
1449 }
1450 }
1451 });
1452 writer.publish(b"receipt").unwrap();
1453 assert_eq!(read.join().unwrap(), b"receipt");
1454 });
1455 }
1456 assert_eq!(std::fs::read_dir(workspace.path()).unwrap().count(), 50);
1457 }
1458
1459 fn mode(path: &Path) -> u32 {
1460 use std::os::unix::fs::PermissionsExt;
1461 std::fs::symlink_metadata(path)
1462 .unwrap()
1463 .permissions()
1464 .mode()
1465 & 0o7777
1466 }
1467
1468 #[test]
1469 fn shared_replacement_keeps_the_existing_permission_bits() {
1470 use std::os::unix::fs::PermissionsExt;
1471 let workspace = tempfile::tempdir().unwrap();
1472 let script = workspace.path().join("deploy.sh");
1473 std::fs::write(&script, b"#!/bin/sh\n").unwrap();
1474 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
1475
1476 WorkspaceFile::open_shared(workspace.path(), Path::new("deploy.sh"), false)
1477 .unwrap()
1478 .replace(b"#!/bin/sh\necho edited\n")
1479 .unwrap();
1480
1481 assert_eq!(std::fs::read(&script).unwrap(), b"#!/bin/sh\necho edited\n");
1482 assert_eq!(
1483 mode(&script),
1484 0o755,
1485 "an edit must not drop the executable bit"
1486 );
1487 }
1488
1489 #[test]
1490 fn shared_replacement_drops_set_id_bits_and_keeps_owner_only_files_private() {
1491 use std::os::unix::fs::PermissionsExt;
1492 let workspace = tempfile::tempdir().unwrap();
1493 // Set-group-id on a file of one's own group is allowed unprivileged;
1494 // the sticky bit on a regular file is not (EFTYPE on macOS).
1495 for (name, before, after) in [("tool", 0o6750, 0o750), ("key.pem", 0o600, 0o600)] {
1496 let path = workspace.path().join(name);
1497 std::fs::write(&path, b"old").unwrap();
1498 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(before)).unwrap();
1499 WorkspaceFile::open_shared(workspace.path(), Path::new(name), false)
1500 .unwrap()
1501 .replace(b"new")
1502 .unwrap();
1503 assert_eq!(std::fs::read(&path).unwrap(), b"new");
1504 assert_eq!(mode(&path), after, "{name}");
1505 }
1506 }
1507
1508 #[test]
1509 fn shared_creation_follows_the_umask_for_the_file_and_its_parents() {
1510 let workspace = tempfile::tempdir().unwrap();
1511 // std creates files as 0o666 and directories as 0o777 under the
1512 // process umask; read that back instead of changing the umask.
1513 let probe_file = workspace.path().join("probe-file");
1514 std::fs::write(&probe_file, b"").unwrap();
1515 let probe_dir = workspace.path().join("probe-dir");
1516 std::fs::create_dir(&probe_dir).unwrap();
1517
1518 WorkspaceFile::open_shared(workspace.path(), Path::new("new/nested/notes.md"), true)
1519 .unwrap()
1520 .replace(b"notes")
1521 .unwrap();
1522
1523 let created = workspace.path().join("new/nested/notes.md");
1524 assert_eq!(std::fs::read(&created).unwrap(), b"notes");
1525 assert_eq!(mode(&created), mode(&probe_file));
1526 assert_eq!(mode(&workspace.path().join("new")), mode(&probe_dir));
1527 assert_eq!(mode(&workspace.path().join("new/nested")), mode(&probe_dir));
1528 }
1529
1530 #[test]
1531 fn private_replacement_and_creation_stay_owner_only() {
1532 use std::os::unix::fs::PermissionsExt;
1533 let workspace = tempfile::tempdir().unwrap();
1534 let ledger = workspace.path().join("fleet.jsonl");
1535 std::fs::write(&ledger, b"old").unwrap();
1536 std::fs::set_permissions(&ledger, std::fs::Permissions::from_mode(0o644)).unwrap();
1537
1538 WorkspaceFile::open(workspace.path(), Path::new("fleet.jsonl"), false)
1539 .unwrap()
1540 .replace(b"compacted")
1541 .unwrap();
1542 assert_eq!(mode(&ledger), 0o600);
1543
1544 WorkspaceFile::open(workspace.path(), Path::new("private/receipt.json"), true)
1545 .unwrap()
1546 .publish(b"receipt")
1547 .unwrap();
1548 assert_eq!(mode(&workspace.path().join("private")), 0o700);
1549 assert_eq!(mode(&workspace.path().join("private/receipt.json")), 0o600);
1550 }
1551
1552 #[test]
1553 fn read_confined_dir_lists_entries_and_refuses_symlinks() {
1554 let workspace = tempfile::tempdir().unwrap();
1555 let outside = tempfile::tempdir().unwrap();
1556 std::fs::create_dir(workspace.path().join("sub")).unwrap();
1557 std::fs::write(workspace.path().join("sub/file.txt"), "hi").unwrap();
1558 std::os::unix::fs::symlink(outside.path(), workspace.path().join("out")).unwrap();
1559 std::os::unix::fs::symlink(workspace.path().join("sub"), workspace.path().join("alias"))
1560 .unwrap();
1561
1562 let root_listing = read_confined_dir(workspace.path(), None, 100).unwrap();
1563 assert_eq!(root_listing.total_entries, 3);
1564 let sub_entry = root_listing
1565 .entries
1566 .iter()
1567 .find(|e| e.name == "sub")
1568 .unwrap();
1569 assert!(sub_entry.is_dir);
1570 let link_entry = root_listing
1571 .entries
1572 .iter()
1573 .find(|e| e.name == "out")
1574 .unwrap();
1575 assert!(!link_entry.is_dir);
1576
1577 let sub_listing = read_confined_dir(workspace.path(), Some(Path::new("sub")), 100).unwrap();
1578 assert_eq!(sub_listing.entries.len(), 1);
1579 assert_eq!(sub_listing.entries[0].name, "file.txt");
1580
1581 assert!(read_confined_dir(workspace.path(), Some(Path::new("out")), 100).is_err());
1582 assert!(read_confined_dir(workspace.path(), Some(Path::new("alias")), 100).is_err());
1583 assert!(read_confined_dir(workspace.path(), Some(Path::new("../escape")), 100).is_err());
1584 }
1585 }
1586
1587 #[cfg(all(test, windows))]
1588 mod windows_publication_tests {
1589 use super::*;
1590 use std::os::windows::fs::OpenOptionsExt;
1591
1592 #[test]
1593 fn publication_and_replacement_keep_ancestor_write_and_delete_guards() {
1594 let workspace = tempfile::tempdir().unwrap();
1595 let parent = workspace.path().join("private");
1596 let ledger =
1597 WorkspaceFile::open(workspace.path(), Path::new("private/fleet.jsonl"), true).unwrap();
1598 let forbidden = std::fs::OpenOptions::new()
1599 .write(true)
1600 .custom_flags(0x0220_0000)
1601 .open(&parent)
1602 .unwrap_err();
1603 assert_eq!(forbidden.raw_os_error(), Some(32));
1604 assert!(std::fs::rename(&parent, workspace.path().join("swapped")).is_err());
1605
1606 // Both fail with MoveFileExW while the destination parent is pinned.
1607 ledger.publish(b"first").unwrap();
1608 ledger.replace(b"compacted").unwrap();
1609 assert_eq!(
1610 std::fs::read(parent.join("fleet.jsonl")).unwrap(),
1611 b"compacted"
1612 );
1613 assert_eq!(std::fs::read_dir(&parent).unwrap().count(), 1);
1614 }
1615
1616 #[test]
1617 fn replacement_survives_a_short_lived_reader_without_delete_sharing() {
1618 let workspace = tempfile::tempdir().unwrap();
1619 let relative = Path::new("fleet.jsonl");
1620 let ledger = WorkspaceFile::open(workspace.path(), relative, true).unwrap();
1621 ledger.publish(b"first").unwrap();
1622 let held = std::fs::OpenOptions::new()
1623 .read(true)
1624 .share_mode(0x1 | 0x2)
1625 .open(workspace.path().join(relative))
1626 .unwrap();
1627 let release = std::thread::spawn(move || {
1628 std::thread::sleep(std::time::Duration::from_millis(50));
1629 drop(held);
1630 });
1631 ledger.replace(b"compacted").unwrap();
1632 release.join().unwrap();
1633 assert_eq!(
1634 std::fs::read(workspace.path().join(relative)).unwrap(),
1635 b"compacted"
1636 );
1637 }
1638
1639 #[test]
1640 fn immutable_publication_preserves_existing_bytes_and_removes_its_temporary() {
1641 let workspace = tempfile::tempdir().unwrap();
1642 let artifact =
1643 WorkspaceFile::open(workspace.path(), Path::new("receipt.json"), true).unwrap();
1644 artifact.publish(b"receipt").unwrap();
1645 assert_eq!(
1646 artifact.publish(b"replacement").unwrap_err().kind(),
1647 io::ErrorKind::AlreadyExists
1648 );
1649 assert_eq!(
1650 std::fs::read(workspace.path().join("receipt.json")).unwrap(),
1651 b"receipt"
1652 );
1653 assert_eq!(std::fs::read_dir(workspace.path()).unwrap().count(), 1);
1654 }
1655
1656 #[test]
1657 fn artifact_paths_cannot_name_windows_alternate_data_streams() {
1658 for path in ["receipt.json:private", "dir/receipt:private", ":stream"] {
1659 assert!(
1660 !path_is_confined(Path::new(path)),
1661 "accepted stream path {path}"
1662 );
1663 }
1664 }
1665 }
1666
1667 #[cfg(all(test, windows))]
1668 mod windows_root_link_tests {
1669 use super::*;
1670
1671 fn make_junction(link: &Path, target: &Path) {
1672 let output = std::process::Command::new("cmd")
1673 .args(["/C", "mklink", "/J"])
1674 .arg(link)
1675 .arg(target)
1676 .output()
1677 .expect("invoke Windows junction creation");
1678 assert!(
1679 output.status.success(),
1680 "failed to create junction: {}",
1681 String::from_utf8_lossy(&output.stderr)
1682 );
1683 }
1684
1685 /// A state root relocated behind a junction: the strict opener refuses the
1686 /// root link, `open_resolved_root` resolves it once and writes through,
1687 /// and a link below the root stays refused either way.
1688 #[test]
1689 fn linked_state_root_resolves_once_and_keeps_the_inner_rule() {
1690 let temp = tempfile::tempdir().unwrap();
1691 let real = temp.path().join("real");
1692 std::fs::create_dir(&real).unwrap();
1693 let link = temp.path().join("link");
1694 make_junction(&link, &real);
1695
1696 let relative = Path::new("state/entry.txt");
1697 assert!(
1698 WorkspaceFile::open(&link, relative, true).is_err(),
1699 "the strict opener must refuse a linked root"
1700 );
1701
1702 WorkspaceFile::open_resolved_root(&link, relative, true)
1703 .unwrap()
1704 .publish(b"payload")
1705 .unwrap();
1706 assert_eq!(
1707 std::fs::read(real.join("state").join("entry.txt")).unwrap(),
1708 b"payload"
1709 );
1710
1711 let elsewhere = temp.path().join("elsewhere");
1712 std::fs::create_dir(&elsewhere).unwrap();
1713 make_junction(&real.join("linked-child"), &elsewhere);
1714 assert!(
1715 WorkspaceFile::open_resolved_root(&link, Path::new("linked-child/x.txt"), true)
1716 .is_err(),
1717 "a link below the resolved root must stay refused"
1718 );
1719 }
1720 }
1721
1722 #[cfg(all(not(unix), not(windows)))]
1723 pub fn read_confined_dir(_: &Path, _: Option<&Path>, _: usize) -> io::Result<ConfinedDirListing> {
1724 Err(io::Error::new(
1725 io::ErrorKind::Unsupported,
1726 "Confined Fleet artifact I/O is unavailable on this platform",
1727 ))
1728 }
1729
1730 #[cfg(all(not(unix), not(windows)))]
1731 #[derive(Debug)]
1732 pub struct WorkspaceFile;
1733 #[cfg(all(not(unix), not(windows)))]
1734 impl WorkspaceFile {
1735 pub fn open(_: &Path, _: &Path, _: bool) -> io::Result<Self> {
1736 Err(io::Error::new(
1737 io::ErrorKind::Unsupported,
1738 "Confined Fleet artifact I/O is unavailable on this platform",
1739 ))
1740 }
1741 pub fn open_shared(workspace: &Path, relative: &Path, create: bool) -> io::Result<Self> {
1742 Self::open(workspace, relative, create)
1743 }
1744 pub fn open_shared_in(
1745 workspace: &Path,
1746 _: &File,
1747 relative: &Path,
1748 create: bool,
1749 ) -> io::Result<Self> {
1750 Self::open(workspace, relative, create)
1751 }
1752 pub fn open_resolved_root(workspace: &Path, relative: &Path, create: bool) -> io::Result<Self> {
1753 Self::open(workspace, relative, create)
1754 }
1755 pub fn sibling(&self, _: &str) -> io::Result<Self> {
1756 unreachable!()
1757 }
1758 pub fn open_update(&self, _: bool, _: bool) -> io::Result<File> {
1759 unreachable!()
1760 }
1761 pub fn open_write(&self, _: bool) -> io::Result<File> {
1762 unreachable!()
1763 }
1764 pub fn replace(&self, _: &[u8]) -> io::Result<()> {
1765 unreachable!()
1766 }
1767 pub fn replace_siblings(&self, _: &[(String, Vec<u8>)]) -> io::Result<()> {
1768 Err(io::ErrorKind::Unsupported.into())
1769 }
1770 pub fn open_file(&self) -> io::Result<File> {
1771 unreachable!()
1772 }
1773 pub fn open_file_shared(&self) -> io::Result<File> {
1774 unreachable!()
1775 }
1776 pub fn publish(&self, _: &[u8]) -> io::Result<()> {
1777 unreachable!()
1778 }
1779 pub fn publish_from_reader(&self, _: &mut impl io::Read) -> io::Result<()> {
1780 Err(io::ErrorKind::Unsupported.into())
1781 }
1782 pub fn open_delivery(workspace: &Path, relative: &Path) -> io::Result<Self> {
1783 Self::open(workspace, relative, false)
1784 }
1785 pub fn open_retained(&self) -> io::Result<File> {
1786 self.open_file()
1787 }
1788 pub fn open_retained_with_max_links(&self, _max_links: u64) -> io::Result<File> {
1789 self.open_retained()
1790 }
1791 pub fn identity_probe(&self) -> io::Result<File> {
1792 self.open_file()
1793 }
1794 pub fn identity_probe_with_max_links(&self, _max_links: u64) -> io::Result<File> {
1795 self.identity_probe()
1796 }
1797 pub fn publish_retained(&self, _: &[u8], _: bool) -> io::Result<File> {
1798 Err(io::ErrorKind::Unsupported.into())
1799 }
1800 pub fn move_opened_to_sibling(&self, _: &File, _: &Self) -> io::Result<()> {
1801 Err(io::ErrorKind::Unsupported.into())
1802 }
1803 pub fn sync_parent(&self) -> io::Result<()> {
1804 Err(io::ErrorKind::Unsupported.into())
1805 }
1806 }
1807
1808 pub fn same_handle(left: &File, right: &File) -> io::Result<bool> {
1809 same_file(left, right)
1810 }
1811
1812 /// Compare already opened lock handles; a replaced lock must never create two
1813 /// independent critical sections for the same live ledger.
1814 pub fn same_file(left: &File, right: &File) -> io::Result<bool> {
1815 #[cfg(unix)]
1816 {
1817 use std::os::unix::fs::MetadataExt;
1818 let a = left.metadata()?;
1819 let b = right.metadata()?;
1820 Ok(a.dev() == b.dev() && a.ino() == b.ino())
1821 }
1822 #[cfg(windows)]
1823 {
1824 let a = crate::path_identity::windows_file_identity(left)?;
1825 let b = crate::path_identity::windows_file_identity(right)?;
1826 Ok(a.volume == b.volume && a.index == b.index)
1827 }
1828 #[cfg(all(not(unix), not(windows)))]
1829 {
1830 let _ = (left, right);
1831 unreachable!()
1832 }
1833 }
1834
1835 #[cfg(all(test, any(unix, windows)))]
1836 mod workspace_root_tests {
1837 use super::*;
1838
1839 #[test]
1840 fn workspace_file_traversal_requires_the_admitted_root() {
1841 let admitted = tempfile::tempdir().expect("admitted workspace");
1842 let other = tempfile::tempdir().expect("other workspace");
1843 let (root, anchor) = crate::workspace_dir::open_workspace_directory(admitted.path())
1844 .expect("open admitted directory");
1845 let other_root = other
1846 .path()
1847 .canonicalize()
1848 .expect("resolve other workspace");
1849 let relative = Path::new("subdirectory/note.txt");
1850
1851 assert!(WorkspaceFile::open_shared_in(&other_root, &anchor, relative, true).is_err());
1852 assert!(!other_root.join("subdirectory").exists());
1853
1854 let file = WorkspaceFile::open_shared_in(&root, &anchor, relative, true)
1855 .expect("open inside admitted root");
1856 file.publish(b"inside")
1857 .expect("publish inside admitted root");
1858 assert_eq!(
1859 std::fs::read(root.join(relative)).expect("read published file"),
1860 b"inside"
1861 );
1862 }
1863 }
1864
1864 lines RUST