Skip to main content

common/
safedir.rs

1//! Safe, race-resistant directory traversal primitives.
2//!
3//! This module provides `O_NOFOLLOW`-based directory and file handle types that
4//! prevent TOCTOU races by using file-descriptor-relative syscalls (`openat`,
5//! `fstatat`) rather than path-based lookups. Every `open_dir`/`child` call
6//! refuses to follow symlinks, so an attacker who races a directory walk cannot
7//! redirect operations outside the intended tree.
8
9use std::ffi::{CStr, OsStr};
10use std::num::NonZeroUsize;
11use std::os::fd::{AsFd, BorrowedFd, IntoRawFd, OwnedFd};
12use std::os::unix::ffi::OsStrExt;
13use std::path::Path;
14use std::sync::Arc;
15
16use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
17
18use nix::fcntl::{AT_FDCWD, AtFlags, OFlag, openat, readlinkat};
19use nix::sys::stat::{FileStat, Mode, fchmod, fstat, fstatat, futimens, mkdirat};
20use nix::sys::time::TimeSpec;
21use nix::unistd::{Gid, Uid, UnlinkatFlags, fchown, fchownat, linkat, symlinkat, unlinkat};
22
23use crate::timing::metadata::{Phase as MetadataTimingPhase, scope as metadata_timing_scope};
24use crate::walk::EntryKind;
25
26#[cfg(test)]
27mod resource_tests;
28#[cfg(test)]
29mod timing_tests;
30
31// ── Destination creation modes ───────────────────────────────────────────────
32
33/// The mode a destination FILE is created with, before it has any contents.
34///
35/// Owner-only. The source mode is applied by [`set_file_metadata_owned`] once the last byte has been
36/// written, so the file is never visible to anyone but the copier while it is being filled in —
37/// the file counterpart of the directory split-chmod (see [`DST_DIR_CREATE_MODE`]).
38///
39/// Creating at the *final* mode instead would publish the destination before its contents exist,
40/// giving a half-written file the audience its finished form was meant to have — at the default
41/// `0o0777` mask, a world-readable source yields a world-readable destination from creation onward.
42/// The sharper case needs the special bits preserved: a root copier holds `CAP_FSETID`, so writing
43/// does not clear `S_ISUID`, and the destination carries `setuid` root while the source's owner is
44/// still authoring its contents. That is not an exec window while the copy *runs* — our own write
45/// descriptor is open, and `execve` refuses a file any process holds open for writing with
46/// `ETXTBSY`. If the copier dies, closing that descriptor drops the protection; creation at the
47/// final mode would leave a finished-looking setuid binary (see `docs/tocttou.md`). Withholding the
48/// owner execute bit is deliberate too — a half-written executable should not be executable.
49///
50/// This is a constant rather than a [`Dir::create_file`] parameter so that no call site, present or
51/// future, can create a destination file at a wide mode. Like any creation mode it is subject to
52/// the umask, which can only narrow it further.
53pub const DST_FILE_CREATE_MODE: u32 = 0o600;
54
55/// The mode a destination DIRECTORY is created with, before it has any children.
56///
57/// Owner-only, plus the execute bit the copier needs to populate it. The source mode is applied
58/// after every child has been written — by `CopyVisitor::dir_post` locally, and on directory
59/// completion remotely.
60pub const DST_DIR_CREATE_MODE: u32 = 0o700;
61
62// ── Strict operand resolution (--require-toctou-safe) ────────────────────────
63//
64// A process-global, one-way switch armed by the TOCTOU linter (see
65// `crate::toctou_check::run_linter`) when `--require-toctou-safe` proceeds. When
66// armed, the two multi-component path resolutions in this module —
67// `Dir::open_root_dir` and `Dir::open_parent_dir`, the only places an operand
68// path is resolved — use `openat2(2)` with `RESOLVE_NO_SYMLINKS` instead of a
69// plain `openat`, so a symlink in ANY component of an operand path fails closed
70// with `ELOOP` at the open itself (not in a racy pre-check). This is a global
71// rather than a threaded setting because it is per-process security policy that
72// must cover every operand open in every engine (copy/link/rm/chmod, local and
73// rcpd) without widening each Settings struct and the rcpd spawn contract; it is
74// armed once before the async runtime starts and never unset.
75
76static STRICT_OPERAND_RESOLUTION: std::sync::atomic::AtomicBool =
77    std::sync::atomic::AtomicBool::new(false);
78
79tokio::task_local! {
80    /// The weak admission reference inherited by fd-owning blocking metadata work in this task.
81    static FD_ADMISSION: throttle::FdAdmission;
82}
83
84/// Run `future` with a weak admission reference available to safedir blocking work.
85///
86/// Tokio cannot cancel a `spawn_blocking` closure after it starts. Without this scope, cancelling
87/// the async waiter drops its operation guard even though the detached closure may still own a
88/// duplicated directory or entry fd. [`run_metadata_probed_blocking`] upgrades the reference for
89/// each such closure, keeping the original admission slot occupied until that fd-owning owner
90/// finishes. The ambient reference is deliberately weak: dropping the concrete guard before
91/// directory recursion still releases capacity even while this scope remains on the stack.
92/// Tokio task locals are not inherited by `tokio::spawn`; every spawned entry worker must install
93/// its own scope after it receives admission.
94pub async fn with_fd_admission<F>(admission: throttle::FdAdmission, future: F) -> F::Output
95where
96    F: std::future::Future,
97{
98    FD_ADMISSION.scope(admission, future).await
99}
100
101/// Run `future` under `admission` when this traversal uses an fd-admission pool.
102pub(crate) async fn with_optional_fd_admission<F>(
103    admission: Option<throttle::FdAdmission>,
104    future: F,
105) -> F::Output
106where
107    F: std::future::Future,
108{
109    match admission {
110        Some(admission) => with_fd_admission(admission, future).await,
111        None => future.await,
112    }
113}
114
115/// Arm strict operand resolution for the rest of this process (one-way).
116///
117/// Called by the TOCTOU linter when `--require-toctou-safe` proceeds; not
118/// intended to be called from anywhere else.
119pub fn enable_strict_operand_resolution() {
120    STRICT_OPERAND_RESOLUTION.store(true, std::sync::atomic::Ordering::Release);
121}
122
123/// Whether strict operand resolution is armed for this process.
124#[must_use]
125pub fn strict_operand_resolution() -> bool {
126    STRICT_OPERAND_RESOLUTION.load(std::sync::atomic::Ordering::Acquire)
127}
128
129/// Open `path` with `openat2(2)`, refusing to resolve ANY symlink component
130/// (`RESOLVE_NO_SYMLINKS`, which also implies `RESOLVE_NO_MAGICLINKS`). A
131/// symlink anywhere in the path fails with `ELOOP`.
132#[cfg(target_os = "linux")]
133fn openat2_no_symlinks(path: &Path, flags: OFlag) -> nix::Result<OwnedFd> {
134    use nix::fcntl::{OpenHow, ResolveFlag, openat2};
135    let how = OpenHow::new()
136        .flags(flags)
137        .resolve(ResolveFlag::RESOLVE_NO_SYMLINKS);
138    // bounded retry: with resolve restrictions openat2 can return EAGAIN when the
139    // kernel detects a rename race during resolution (see openat2(2)); retrying a
140    // handful of times resolves transient races without risking an unbounded loop.
141    let mut attempts = 0;
142    loop {
143        match openat2(AT_FDCWD, path, how) {
144            Err(nix::errno::Errno::EAGAIN) if attempts < 4 => attempts += 1,
145            other => return other,
146        }
147    }
148}
149
150/// Whether this kernel supports `openat2(2)` (Linux 5.6+), probed once.
151///
152/// Strict operand resolution is impossible without it, so
153/// `--require-toctou-safe` refuses to run when this returns `false`.
154#[cfg(target_os = "linux")]
155#[must_use]
156pub fn openat2_available() -> bool {
157    static PROBE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
158    *PROBE.get_or_init(|| {
159        // "/" always exists and is a directory; ENOSYS is the only expected failure
160        !matches!(
161            openat2_no_symlinks(Path::new("/"), OFlag::O_PATH | OFlag::O_CLOEXEC),
162            Err(nix::errno::Errno::ENOSYS)
163        )
164    })
165}
166
167/// Non-Linux builds have no `openat2`; `--require-toctou-safe` already refuses
168/// to run there (the hardened walk is Linux-only), so this is only consulted to
169/// render an accurate `--toctou-check` note.
170#[cfg(not(target_os = "linux"))]
171#[must_use]
172pub fn openat2_available() -> bool {
173    false
174}
175
176// ── FileMeta ──────────────────────────────────────────────────────────────────
177
178/// A snapshot of filesystem metadata obtained via `fstat`/`fstatat`.
179///
180/// Implements [`crate::preserve::Metadata`] so callers can apply these fields
181/// to another entry with the existing `set_*_metadata` helpers.
182#[derive(Clone, Debug)]
183pub struct FileMeta {
184    uid: u32,
185    gid: u32,
186    atime: i64,
187    atime_nsec: i64,
188    mtime: i64,
189    mtime_nsec: i64,
190    ctime: i64,
191    ctime_nsec: i64,
192    mode: u32,
193    size: u64,
194    dev: u64,
195    ino: u64,
196}
197
198impl FileMeta {
199    fn from_stat(st: &FileStat) -> Self {
200        Self {
201            uid: st.st_uid,
202            gid: st.st_gid,
203            atime: st.st_atime,
204            atime_nsec: st.st_atime_nsec,
205            mtime: st.st_mtime,
206            mtime_nsec: st.st_mtime_nsec,
207            ctime: st.st_ctime,
208            ctime_nsec: st.st_ctime_nsec,
209            mode: st.st_mode,
210            size: st.st_size as u64,
211            dev: st.st_dev,
212            ino: st.st_ino,
213        }
214    }
215
216    /// The device number of the filesystem this entry lives on.
217    #[must_use]
218    pub fn dev(&self) -> u64 {
219        self.dev
220    }
221
222    /// The entry's inode number.
223    #[must_use]
224    pub fn ino(&self) -> u64 {
225        self.ino
226    }
227}
228
229impl crate::preserve::Metadata for FileMeta {
230    fn uid(&self) -> u32 {
231        self.uid
232    }
233    fn gid(&self) -> u32 {
234        self.gid
235    }
236    fn atime(&self) -> i64 {
237        self.atime
238    }
239    fn atime_nsec(&self) -> i64 {
240        self.atime_nsec
241    }
242    fn mtime(&self) -> i64 {
243        self.mtime
244    }
245    fn mtime_nsec(&self) -> i64 {
246        self.mtime_nsec
247    }
248    fn permissions(&self) -> std::fs::Permissions {
249        use std::os::unix::fs::PermissionsExt;
250        std::fs::Permissions::from_mode(self.mode)
251    }
252    fn ctime(&self) -> i64 {
253        self.ctime
254    }
255    fn ctime_nsec(&self) -> i64 {
256        self.ctime_nsec
257    }
258    fn size(&self) -> u64 {
259        self.size
260    }
261}
262
263// ── EntryKind classification ───────────────────────────────────────────────────
264
265fn kind_from_stat(st: &FileStat) -> EntryKind {
266    let mode = st.st_mode;
267    // use libc mode-classification macros via their bit patterns (POSIX S_IFMT)
268    // S_IFREG = 0o0100000, S_IFDIR = 0o0040000, S_IFLNK = 0o0120000
269    let ifmt = mode & libc::S_IFMT;
270    match ifmt {
271        libc::S_IFREG => EntryKind::File,
272        libc::S_IFDIR => EntryKind::Dir,
273        libc::S_IFLNK => EntryKind::Symlink,
274        _ => EntryKind::Special,
275    }
276}
277
278// ── Handle ────────────────────────────────────────────────────────────────────
279
280/// An open, classified handle to a filesystem entry obtained via `O_PATH|O_NOFOLLOW`.
281///
282/// The fd is opened with `O_PATH`, so it cannot be used for reading; it exists
283/// solely to identify the entry (for further `openat` calls relative to it) and
284/// to carry the stat snapshot. A symlink entry is never followed: it yields a
285/// `Handle` with `kind() == EntryKind::Symlink`.
286#[derive(Debug)]
287pub struct Handle {
288    fd: OwnedFd,
289    kind: EntryKind,
290    dev: u64,
291    ino: u64,
292    meta: FileMeta,
293}
294
295/// The classification and size needed to remove an occupied destination slot.
296///
297/// Unlike [`Handle`], this snapshot does not keep an inode pinned. Overwrite removal operates by
298/// name through a pinned parent directory, so retaining the entry fd cannot bind the later by-name
299/// removal to that inode. Converting to this snapshot closes the classification fd while preserving
300/// the accounting data the removal path needs.
301#[derive(Clone, Copy, Debug)]
302pub struct RemovalSnapshot {
303    kind: EntryKind,
304    size: u64,
305}
306
307impl RemovalSnapshot {
308    /// The entry classification captured during overwrite planning.
309    #[must_use]
310    pub fn kind(self) -> EntryKind {
311        self.kind
312    }
313
314    /// The entry size captured during overwrite planning.
315    #[must_use]
316    pub fn size(self) -> u64 {
317        self.size
318    }
319}
320
321impl Handle {
322    /// The entry's classification (File / Dir / Symlink / Special).
323    #[must_use]
324    pub fn kind(&self) -> EntryKind {
325        self.kind
326    }
327
328    /// The device number of the entry.
329    #[must_use]
330    pub fn dev(&self) -> u64 {
331        self.dev
332    }
333
334    /// The inode number of the entry.
335    #[must_use]
336    pub fn ino(&self) -> u64 {
337        self.ino
338    }
339
340    /// A snapshot of the entry's metadata at the time the handle was opened.
341    #[must_use]
342    pub fn meta(&self) -> &FileMeta {
343        &self.meta
344    }
345
346    /// Consume this handle and retain only the data needed for overwrite removal.
347    #[must_use]
348    pub fn into_removal_snapshot(self) -> RemovalSnapshot {
349        RemovalSnapshot {
350            kind: self.kind,
351            size: self.meta.size,
352        }
353    }
354
355    /// Borrow the underlying file descriptor.
356    #[must_use]
357    pub fn as_fd(&self) -> BorrowedFd<'_> {
358        self.fd.as_fd()
359    }
360
361    /// Duplicate this handle, sharing the same pinned inode via a `dup`'d
362    /// (`F_DUPFD_CLOEXEC`) `O_PATH` file descriptor and copying the cached
363    /// classification + stat snapshot.
364    ///
365    /// This is a pure fd dup — it opens nothing, follows nothing, and stats
366    /// nothing on the filesystem, so it preserves every TOCTOU property of the
367    /// original `O_PATH|O_NOFOLLOW` handle (the clone pins the exact same inode and
368    /// cannot be redirected by a concurrent rename/symlink swap). It lets a walk
369    /// that classifies an entry once hand an owned handle to a deferred (post-order)
370    /// step without a second `openat`/`fstatat` on the entry.
371    pub fn try_clone(&self) -> std::io::Result<Handle> {
372        Ok(Handle {
373            fd: self.fd.try_clone()?,
374            kind: self.kind,
375            dev: self.dev,
376            ino: self.ino,
377            meta: self.meta.clone(),
378        })
379    }
380
381    /// Read this symlink's target and metadata from the one pinned `O_PATH` fd: the target via the
382    /// empty-path `readlinkat` ([`read_link_handle`]) and the metadata from this handle's `fstat`
383    /// snapshot. Both describe the same pinned inode, so they are a faithful pair (the symlink
384    /// analogue of [`Dir::open_file_read`]'s `(File, FileMeta)`). Errors if the handle is not a
385    /// symlink (the empty-path read requires a symlink fd).
386    pub async fn read_symlink(
387        &self,
388        side: congestion::Side,
389    ) -> std::io::Result<(std::path::PathBuf, FileMeta)> {
390        let target = read_link_handle(self, side).await?;
391        Ok((target, self.meta.clone()))
392    }
393}
394
395// ── Dir ───────────────────────────────────────────────────────────────────────
396
397/// A directory file descriptor opened `O_RDONLY|O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC`.
398///
399/// All entry-level operations are relative to this fd, preventing TOCTOU races
400/// that path-based lookups are vulnerable to.
401///
402/// The fd is held behind an `Arc` so per-entry operations can move an owned
403/// reference into their `spawn_blocking` closure. Once a closure starts it is
404/// not cancellable: if the surrounding future is then dropped (timeout,
405/// `fail_early` abort, Ctrl-C) the closure keeps running detached. User work
406/// still queued at `run_fd_admitted_blocking`'s handoff is instead reclaimed
407/// synchronously with its captures; the Tokio wrapper does nothing if scheduled
408/// later. Cloning the `Arc` (a refcount bump, no syscall) keeps the open file
409/// description alive for a started closure's full duration even if the
410/// originating `Dir` is dropped mid-flight, preserving the `openat` TOCTOU
411/// guarantee. Later fd-relative methods (`open_file_read`, `create_file`,
412/// `make_dir`, `entries`, `read_entries`, …) must follow this same clone-Arc-into-closure
413/// shape.
414#[derive(Debug)]
415pub struct Dir {
416    fd: Arc<DirectoryDescriptor>,
417    /// Which filesystem side this directory lives on, for congestion gating.
418    side: congestion::Side,
419    /// Whether a file created in THIS directory may inherit an access ACL that rcp has not
420    /// sanitized — i.e. whether the directory may still carry a default ACL rcp took no
421    /// responsibility for.
422    ///
423    /// `true` for every directory rcp merely OPENED: the ambient parent above a named operand
424    /// (`open_parent_dir` / `open_root_dir`) and any reused directory before its lockdown. `false`
425    /// only once rcp has made inheritance impossible: a `make_dir` (which strips both ACLs at
426    /// creation under strict operand resolution) or a [`lockdown_reused_dir`] (which removes the
427    /// default ACL for the copy's duration) — the ONLY two sites that clear it, via
428    /// `Self::mark_children_cannot_inherit`.
429    ///
430    /// Consulted ONLY by the file-creation helpers, ONLY under `--require-toctou-safe`. The polarity is
431    /// deliberately fail-safe: a stale `true` on an already-sanitized parent costs one wasted
432    /// `fremovexattr` per created file; a wrong `false` would silently reopen the containment hole
433    /// (docs/acls.md, "containment"), so nothing but the two sanitizing sites may clear it — and
434    /// the ONE re-arming site may set it back: [`ReusedDirLock`]'s rollback restores the
435    /// directory's original default ACL, so it stores `true` (before the restore syscall) or a
436    /// file created after the rollback would inherit that ACL with the strip skipped. `Arc`d so
437    /// `create_file`'s blocking closure can consult it AFTER its `openat` (a pre-closure snapshot
438    /// races the rollback: the closure can run after the restore with a stale `false`).
439    children_may_inherit: Arc<std::sync::atomic::AtomicBool>,
440}
441
442/// Owns the directory fd before the shared credit that accounts for its lifetime.
443///
444/// Field order makes the descriptor close before its last admission reference is released.
445#[derive(Debug)]
446struct DirectoryDescriptor {
447    fd: OwnedFd,
448    credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
449}
450
451impl AsFd for DirectoryDescriptor {
452    fn as_fd(&self) -> BorrowedFd<'_> {
453        self.fd.as_fd()
454    }
455}
456
457impl AsRawFd for DirectoryDescriptor {
458    fn as_raw_fd(&self) -> RawFd {
459        self.fd.as_raw_fd()
460    }
461}
462
463/// A directory entry returned by a streaming cursor.
464///
465/// The type hint comes from `d_type` and must be checked before acting on the entry.
466#[derive(Debug)]
467pub struct DirectoryEntry {
468    pub name: std::ffi::OsString,
469    pub kind_hint: Option<EntryKind>,
470}
471
472#[cfg(test)]
473type CursorReadHook = Box<dyn FnMut(usize, RawFd) -> std::io::Result<()> + Send>;
474
475/// An independently opened directory stream whose offset survives batch boundaries.
476pub struct DirectoryCursor {
477    iterator: Option<OwnedDirectoryStream>,
478    #[cfg(test)]
479    read_hook: Option<CursorReadHook>,
480}
481
482impl DirectoryCursor {
483    /// Read access and default ACLs from this cursor's open directory.
484    ///
485    /// The stream moves through the gated reads without opening or duplicating a descriptor.
486    /// An error or cancellation ends this cursor; started work owns its stream and credit.
487    pub async fn read_acls(&mut self, side: congestion::Side) -> std::io::Result<Acls> {
488        let iterator = self
489            .iterator
490            .take()
491            .ok_or_else(|| std::io::Error::other("directory cursor was interrupted or failed"))?;
492        let (iterator, acls) = read_acls_owned(iterator, side, true).await?;
493        self.iterator = Some(iterator);
494        Ok(acls)
495    }
496
497    /// Open a directory cursor by path, following symlinks for explicit dereferencing callers.
498    pub async fn open_following_symlinks(
499        path: &Path,
500        side: congestion::Side,
501        credit: Arc<dyn std::fmt::Debug + Send + Sync>,
502    ) -> std::io::Result<Self> {
503        let path = path.to_owned();
504        let iterator = run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
505            if strict_operand_resolution() {
506                return Err(std::io::Error::new(
507                    std::io::ErrorKind::InvalidInput,
508                    "following directory symlinks is incompatible with strict operand resolution",
509                ));
510            }
511            let fd = openat(
512                AT_FDCWD,
513                &path,
514                OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC,
515                Mode::empty(),
516            )
517            .map_err(nix_to_io)?;
518            let iterator = OwnedDirectoryStream::from_fd(fd, Some(credit))?;
519            #[cfg(test)]
520            let _visit = resource_tests::gate_opened_descriptor(iterator.as_raw_fd())?;
521            Ok(iterator)
522        })
523        .await?;
524        Ok(Self {
525            iterator: Some(iterator),
526            #[cfg(test)]
527            read_hook: None,
528        })
529    }
530
531    /// Read at most `limit` entries, excluding `.` and `..`; an empty batch means EOF.
532    ///
533    /// An error or cancellation after admission ends this cursor. The blocking job then owns and
534    /// closes its iterator, so a later call cannot rewind or duplicate already yielded entries.
535    pub async fn next_batch(
536        &mut self,
537        limit: NonZeroUsize,
538    ) -> std::io::Result<Vec<DirectoryEntry>> {
539        throttle::get_ops_token().await;
540        let mut iterator = self
541            .iterator
542            .take()
543            .ok_or_else(|| std::io::Error::other("directory cursor was interrupted or failed"))?;
544        #[cfg(test)]
545        let mut read_hook = self.read_hook.take();
546        let (returned, entries) = run_fd_admitted_blocking(move || {
547            let mut entries = Vec::with_capacity(limit.get());
548            while entries.len() < limit.get() {
549                #[cfg(test)]
550                if let Some(read_hook) = read_hook.as_mut() {
551                    read_hook(entries.len(), iterator.as_raw_fd())?;
552                }
553                let Some(entry) = iterator.next_raw_entry()? else {
554                    break;
555                };
556                if entry.name == "." || entry.name == ".." {
557                    continue;
558                }
559                entries.push(entry);
560            }
561            Ok((iterator, entries))
562        })
563        .await?;
564        self.iterator = Some(returned);
565        Ok(entries)
566    }
567}
568
569/// Owns one `DIR*` and its fd for the entire lifetime of a movable cursor.
570#[derive(Debug)]
571struct OwnedDirectoryStream {
572    dir: std::ptr::NonNull<libc::DIR>,
573    // closedir runs in Drop before fields release this shared descriptor credit
574    _credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
575}
576
577// SAFETY: ownership is exclusive; the cursor moves into one blocking job at a time, and no
578// `readdir` call or entry reference can overlap a move to another thread.
579unsafe impl Send for OwnedDirectoryStream {}
580
581impl OwnedDirectoryStream {
582    fn from_fd(
583        fd: OwnedFd,
584        credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
585    ) -> std::io::Result<Self> {
586        let owner = DirectoryDescriptor { fd, credit };
587        // SAFETY: fd is valid and held exclusively. On failure fdopendir leaves it open, so
588        // the owner closes it before releasing credit; on success closedir takes over the fd.
589        let dir = std::ptr::NonNull::new(unsafe { libc::fdopendir(owner.as_raw_fd()) })
590            .ok_or_else(std::io::Error::last_os_error)?;
591        let _ = owner.fd.into_raw_fd();
592        Ok(Self {
593            dir,
594            _credit: owner.credit,
595        })
596    }
597
598    fn next_raw_entry(&mut self) -> std::io::Result<Option<DirectoryEntry>> {
599        nix::errno::Errno::clear();
600        // SAFETY: self exclusively owns the live stream, and the returned dirent is copied
601        // before another readdir call or the stream's Drop can invalidate it.
602        let raw = unsafe { libc::readdir(self.dir.as_ptr()) };
603        if raw.is_null() {
604            let errno = nix::errno::Errno::last_raw();
605            return if errno == 0 {
606                Ok(None)
607            } else {
608                Err(std::io::Error::from_raw_os_error(errno))
609            };
610        }
611        // SAFETY: readdir returned a valid dirent with a NUL-terminated d_name.
612        let entry = unsafe { &*raw };
613        let name = unsafe { CStr::from_ptr(entry.d_name.as_ptr()) };
614        let kind_hint = match entry.d_type {
615            libc::DT_UNKNOWN => None,
616            libc::DT_DIR => Some(EntryKind::Dir),
617            libc::DT_LNK => Some(EntryKind::Symlink),
618            libc::DT_REG => Some(EntryKind::File),
619            _ => Some(EntryKind::Special),
620        };
621        Ok(Some(DirectoryEntry {
622            name: OsStr::from_bytes(name.to_bytes()).to_owned(),
623            kind_hint,
624        }))
625    }
626}
627
628impl AsRawFd for OwnedDirectoryStream {
629    fn as_raw_fd(&self) -> RawFd {
630        // SAFETY: self owns the live DIR stream until Drop.
631        unsafe { libc::dirfd(self.dir.as_ptr()) }
632    }
633}
634
635impl Drop for OwnedDirectoryStream {
636    fn drop(&mut self) {
637        // SAFETY: fdopendir transferred this one stream to self on success.
638        unsafe { libc::closedir(self.dir.as_ptr()) };
639    }
640}
641
642impl Dir {
643    /// Wrap a directory fd rcp merely OPENED (as opposed to created): its inherited-ACL state is
644    /// unknown, so files created in it must assume the worst — see `children_may_inherit`.
645    fn opened(fd: OwnedFd, side: congestion::Side) -> Dir {
646        Self::opened_with_credit(fd, side, None)
647    }
648
649    fn opened_with_credit(
650        fd: OwnedFd,
651        side: congestion::Side,
652        credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
653    ) -> Dir {
654        Dir {
655            fd: Arc::new(DirectoryDescriptor { fd, credit }),
656            side,
657            children_may_inherit: Arc::new(std::sync::atomic::AtomicBool::new(true)),
658        }
659    }
660
661    /// Record that nothing created in this directory can inherit an ACL anymore — called by the
662    /// two sanitizing sites (`make_dir`'s creation strip and [`lockdown_reused_dir`]'s default-ACL
663    /// removal) and nothing else; see `children_may_inherit`.
664    fn mark_children_cannot_inherit(&self) {
665        self.children_may_inherit
666            .store(false, std::sync::atomic::Ordering::Relaxed);
667    }
668
669    /// Which filesystem side this directory lives on (for congestion gating).
670    #[must_use]
671    pub fn side(&self) -> congestion::Side {
672        self.side
673    }
674
675    /// Open `path` as a directory fd.
676    ///
677    /// The final component is always opened with `O_NOFOLLOW`. If `dereference`
678    /// is `false` and the final component is a symlink, the call fails with
679    /// `ELOOP`. If `dereference` is `true` and the final component is a symlink,
680    /// the call is retried without `O_NOFOLLOW` so the symlink is followed.
681    ///
682    /// The parent prefix is resolved normally (it is trusted) — unless strict
683    /// operand resolution is armed (`--require-toctou-safe`), in which case the
684    /// whole path is resolved `RESOLVE_NO_SYMLINKS` and a symlink in ANY
685    /// component fails closed with `ELOOP`.
686    pub async fn open_root_dir(
687        path: &Path,
688        dereference: bool,
689        side: congestion::Side,
690    ) -> std::io::Result<Dir> {
691        let path = path.to_owned();
692        // run the blocking openat inside spawn_blocking, gated by the congestion
693        // controller, matching the per-metadata-syscall pattern used across the crate.
694        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
695            let flags = OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;
696            let mode = Mode::empty();
697            #[cfg(target_os = "linux")]
698            {
699                if strict_operand_resolution() {
700                    // --require-toctou-safe: `-L` is refused by the linter before strict
701                    // mode can arm, so a dereference request here is an internal
702                    // inconsistency; fail closed rather than follow a symlink.
703                    if dereference {
704                        return Err(std::io::Error::new(
705                            std::io::ErrorKind::InvalidInput,
706                            "--dereference cannot be combined with strict operand resolution",
707                        ));
708                    }
709                    return openat2_no_symlinks(&path, flags)
710                        .map(|fd| Dir::opened(fd, side))
711                        .map_err(nix_to_io);
712                }
713            }
714            match openat(AT_FDCWD, &path, flags, mode) {
715                Ok(fd) => Ok(Dir::opened(fd, side)),
716                Err(nix::errno::Errno::ELOOP) if dereference => {
717                    // final component is a symlink; follow it only when dereference=true
718                    let follow_flags = OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC;
719                    openat(AT_FDCWD, &path, follow_flags, mode)
720                        .map(|fd| Dir::opened(fd, side))
721                        .map_err(nix_to_io)
722                }
723                Err(e) => Err(nix_to_io(e)),
724            }
725        })
726        .await
727    }
728
729    /// Open a TRUSTED command-line parent-prefix directory, resolving symlinks
730    /// normally (the final component IS followed if it is a symlink).
731    ///
732    /// The trusted-boundary model (docs/tocttou.md, "Trusted boundary") trusts the directory named on
733    /// the command line up to and including itself; only entries strictly BELOW
734    /// it are hardened with `O_NOFOLLOW`. The parent prefix that CONTAINS the
735    /// operand is therefore resolved like a normal path open — a symlinked parent
736    /// (e.g. `rcp file symlink_to_dir/out`, where `symlink_to_dir` is a symlink to
737    /// a real directory) must be followed into the real directory, not rejected
738    /// with `ELOOP`/`ENOTDIR`.
739    ///
740    /// This differs from [`Self::open_root_dir`], which `O_NOFOLLOW`s the final
741    /// component (the named operand itself) and only follows it when
742    /// `dereference` is set. Use `open_parent_dir` for the operand's CONTAINER
743    /// directory; use `open_root_dir` for the operand entry. Every descendant
744    /// `openat` during the walk still uses `O_NOFOLLOW`, so the hardening below
745    /// the named root is unaffected.
746    ///
747    /// Returns a [`TrustedDir`], the only retained/exposed symlink-following transition used by
748    /// ordinary callers. The private dry-run preview parent opener follows the trusted prefix
749    /// internally before beginning its nofollow descent. Crossing into the hardened tree below the
750    /// named root is the explicit [`TrustedDir::into_tree`] step.
751    ///
752    /// Under strict operand resolution (`--require-toctou-safe`) the prefix must
753    /// already be symlink-free: it is resolved `RESOLVE_NO_SYMLINKS`, and a
754    /// symlink in any component fails closed with `ELOOP` instead of being
755    /// followed. Pass fully-resolved operands (`realpath` output) in that mode.
756    pub async fn open_parent_dir(
757        path: &Path,
758        side: congestion::Side,
759    ) -> std::io::Result<TrustedDir> {
760        let path = path.to_owned();
761        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
762            let flags = OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC;
763            #[cfg(target_os = "linux")]
764            {
765                if strict_operand_resolution() {
766                    return openat2_no_symlinks(&path, flags)
767                        .map(|fd| TrustedDir(Dir::opened(fd, side)))
768                        .map_err(nix_to_io);
769                }
770            }
771            // a normal directory open: the kernel resolves the whole path following
772            // symlinks, including the final (trusted parent) component. No O_NOFOLLOW.
773            openat(AT_FDCWD, &path, flags, Mode::empty())
774                .map(|fd| TrustedDir(Dir::opened(fd, side)))
775                .map_err(nix_to_io)
776        })
777        .await
778    }
779
780    /// Open a child directory entry by name, refusing to follow symlinks.
781    ///
782    /// Fails with `ELOOP` if `name` refers to a symlink, or `ENOTDIR` if it
783    /// refers to a non-directory entry. The returned `Dir` carries the same
784    /// congestion side as `self`.
785    pub async fn open_dir(&self, name: &OsStr) -> std::io::Result<Dir> {
786        self.open_dir_with_credit(name, None).await
787    }
788
789    /// Open a child directory while retaining its caller's shared descriptor credit.
790    ///
791    /// The credit moves into blocking work before opening and remains owned by the returned
792    /// directory, its independent cursors, and any fd-owning jobs that outlive cancellation.
793    pub async fn open_dir_admitted(
794        &self,
795        name: &OsStr,
796        credit: Arc<dyn std::fmt::Debug + Send + Sync>,
797    ) -> std::io::Result<Dir> {
798        self.open_dir_with_credit(name, Some(credit)).await
799    }
800
801    async fn open_dir_with_credit(
802        &self,
803        name: &OsStr,
804        credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
805    ) -> std::io::Result<Dir> {
806        // `O_NOFOLLOW`/`O_PATH` only guard the final path component, so a `name`
807        // containing `/` could let openat traverse an intermediate symlink. Reject
808        // multi-component names at runtime (debug_assert is compiled out in release).
809        if !is_single_component(name) {
810            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
811        }
812        // clone the Arc (refcount bump, no syscall) and move it into the blocking
813        // closure so the open file description stays alive for the closure's full
814        // duration even if this Dir is dropped after the closure starts (started
815        // spawn_blocking work is not cancellable). see the Dir doc comment.
816        let dir = self.fd.clone();
817        let side = self.side;
818        let name = name.to_owned();
819        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
820            let flags = OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;
821            let fd =
822                openat(dir.as_fd(), name.as_bytes(), flags, Mode::empty()).map_err(nix_to_io)?;
823            let opened = Dir::opened_with_credit(fd, side, credit);
824            #[cfg(test)]
825            let _visit = resource_tests::gate_opened_descriptor(opened.fd.as_raw_fd())?;
826            Ok(opened)
827        })
828        .await
829    }
830
831    /// Open a child regular file for reading, refusing to follow symlinks and never
832    /// blocking on a FIFO. Returns the open file plus its metadata snapshot.
833    ///
834    /// `O_NONBLOCK` is included so that if an attacker races the directory entry to
835    /// a FIFO between `getdents` and this `open`, the open returns immediately
836    /// (`O_RDONLY|O_NONBLOCK` on a FIFO never blocks on Linux) rather than blocking
837    /// forever waiting for a writer. `O_NOFOLLOW` prevents symlink following but
838    /// does not catch FIFOs (they are not symlinks); the subsequent `fstat` +
839    /// `S_ISREG` check rejects any non-regular file (FIFO, device, directory) with
840    /// `EINVAL`. `O_NONBLOCK` persists on the returned `File`, which is harmless for
841    /// regular-file I/O on a local fs.
842    ///
843    /// Fails with `EINVAL` if `name` is not a single path component, `ELOOP` if
844    /// `name` is a symlink, or `EINVAL` (after open, via the `fstat`+`S_ISREG`
845    /// check) if the entry is any non-regular type such as a FIFO, device, or
846    /// directory.
847    ///
848    /// This is the canonical regular-file payload+metadata read: the returned `FileMeta` (not the
849    /// classify [`Handle`]'s metadata) is what callers must apply/send, so bytes and metadata come
850    /// from the same fd (read-side fidelity, see docs/tocttou.md).
851    pub async fn open_file_read(&self, name: &OsStr) -> std::io::Result<(std::fs::File, FileMeta)> {
852        if !is_single_component(name) {
853            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
854        }
855        let dir = self.fd.clone();
856        let side = self.side;
857        let name = name.to_owned();
858        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
859            let flags = OFlag::O_RDONLY | OFlag::O_NOFOLLOW | OFlag::O_NONBLOCK | OFlag::O_CLOEXEC;
860            let fd =
861                openat(dir.as_fd(), name.as_bytes(), flags, Mode::empty()).map_err(nix_to_io)?;
862            // fstat the open fd to confirm the entry is a regular file; this is the
863            // safety check — O_NOFOLLOW does not catch FIFOs or other special files.
864            let st = fstat(&fd).map_err(nix_to_io)?;
865            if kind_from_stat(&st) != EntryKind::File {
866                // fd is dropped here, closing it
867                return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
868            }
869            let meta = FileMeta::from_stat(&st);
870            let file = std::fs::File::from(fd);
871            Ok((file, meta))
872        })
873        .await
874    }
875
876    /// `fstat` this directory's own held fd, returning its metadata snapshot.
877    ///
878    /// Lets a caller apply/send a directory's metadata from the SAME fd whose `read_entries`
879    /// produced its contents (read-side fidelity, see docs/tocttou.md), rather than from a
880    /// separately-opened classify [`Handle`] that a concurrent swap could desync from the
881    /// enumerated contents. Gated as `Stat`.
882    pub async fn meta(&self) -> std::io::Result<FileMeta> {
883        let dir = self.fd.clone();
884        let side = self.side;
885        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
886            let st = fstat(dir.as_fd()).map_err(nix_to_io)?;
887            Ok(FileMeta::from_stat(&st))
888        })
889        .await
890    }
891
892    /// Read this directory's own access and default POSIX ACLs from its held fd.
893    ///
894    /// The directory counterpart of [`Self::meta`], and paired with it for the same reason: the
895    /// ACLs a caller applies to the destination come from the SAME fd whose `read_entries` produced
896    /// the contents being copied. Callers gate this on `d:acl` — see [`read_acls_fd`] for what the
897    /// probe costs.
898    pub async fn read_acls(&self) -> std::io::Result<Acls> {
899        read_acls_owned(self.fd.clone(), self.side, true)
900            .await
901            .map(|(_, acls)| acls)
902    }
903
904    /// Open a child entry by name, classifying it without following symlinks.
905    ///
906    /// Uses `O_PATH|O_NOFOLLOW`, which yields a valid fd even for symlinks. The
907    /// stat is then obtained via `fstatat` with `AT_EMPTY_PATH` on the resulting
908    /// fd so the classification is always consistent with the opened entry.
909    pub async fn child(&self, name: &OsStr) -> std::io::Result<Handle> {
910        // see open_dir: `O_NOFOLLOW`/`O_PATH` only guard the final component, so a
911        // `name` containing `/` could traverse an intermediate symlink. Reject
912        // multi-component names at runtime (debug_assert is compiled out in release).
913        if !is_single_component(name) {
914            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
915        }
916        // clone the Arc (refcount bump, no syscall) and move it into the blocking
917        // closure so the open file description stays alive for the closure's full
918        // duration even if this Dir is dropped after the closure starts (started
919        // spawn_blocking work is not cancellable). see the Dir doc comment.
920        let dir = self.fd.clone();
921        let side = self.side;
922        let name = name.to_owned();
923        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
924            let flags = OFlag::O_PATH | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;
925            let fd =
926                openat(dir.as_fd(), name.as_bytes(), flags, Mode::empty()).map_err(nix_to_io)?;
927            // stat the fd itself (empty path + AT_EMPTY_PATH): works for symlinks too
928            let st = fstatat(&fd, "", AtFlags::AT_EMPTY_PATH).map_err(nix_to_io)?;
929            let kind = kind_from_stat(&st);
930            let dev = st.st_dev;
931            let ino = st.st_ino;
932            let meta = FileMeta::from_stat(&st);
933            Ok(Handle {
934                fd,
935                kind,
936                dev,
937                ino,
938                meta,
939            })
940        })
941        .await
942    }
943
944    /// Confirm this directory's own held fd still refers to the same inode as
945    /// `handle` (same `dev` + `ino`), returning `ESTALE` on mismatch.
946    ///
947    /// This stats this [`Dir`]'s already-pinned fd (via [`Self::meta`]) against a classification
948    /// [`Handle`] taken for the same entry. It closes the classify-to-`open_dir` window in the
949    /// reused-destination-directory lockdown: `open_dir` re-resolves the name, so a concurrent
950    /// rename could substitute a different directory between classification and the open.
951    /// Comparing the opened fd's identity to the pinned classification handle catches that swap.
952    /// The handle keeps the classified inode number from being recycled during the comparison.
953    pub async fn verify_same_inode(&self, handle: &Handle) -> std::io::Result<()> {
954        let meta = self.meta().await?;
955        if meta.dev() == handle.dev() && meta.ino() == handle.ino() {
956            Ok(())
957        } else {
958            Err(std::io::Error::from_raw_os_error(libc::ESTALE))
959        }
960    }
961
962    /// Take uid ownership of this directory as the copier and restrict it to `mode`,
963    /// atomically and verified. Used by the reused-destination-directory lockdown under
964    /// [`strict_operand_resolution`]: taking ownership first means the directory's PRIOR
965    /// owner can no longer `chmod` it back open while children are written.
966    ///
967    /// The sequence — inside ONE `spawn_blocking` closure (which runs to completion once it
968    /// starts) — is ordered so that **every failure exit leaves the directory no wider than a
969    /// successful copy would**:
970    ///
971    /// 1. `fchown` the owner to the effective uid (lock the prior owner out). Failing here
972    ///    leaves the directory untouched — transparent, fail-safe.
973    /// 2. `fchmod` to a plain `0o700` IMMEDIATELY. From here on any failure leaves the
974    ///    directory owner-only, i.e. no wider than success. If this `fchmod` fails, roll the
975    ///    ownership back to `orig_uid` and CHECK the rollback: a clean rollback fully restores
976    ///    the pre-lockdown state (the failed `chmod` changed nothing); a rollback that ALSO
977    ///    fails is a genuinely stuck state (a read-only/failing backend) reported with both
978    ///    errnos — the caller fails closed, so no child is ever written there.
979    /// 3. Reset the gid to `orig_gid` **only if it differs** (a prior owner raced a `chgrp`
980    ///    between classification and step 1). This matters for a **setgid** directory:
981    ///    children inherit the directory's gid, and finalization cannot repair children
982    ///    already created. Writing only-when-different keeps the common case a no-op — never
983    ///    an EPERM for a non-root copier that owns the directory but is not in its group — and
984    ///    a difference implies a foreign-owned directory, so the copier took ownership in step
985    ///    1 as root and can set any gid.
986    /// 4. Re-add the setgid bit (`fchmod` to `mode`) when wanted, now that the gid is
987    ///    `orig_gid`. Doing this AFTER the gid reset stops a non-privileged copier's `chmod`
988    ///    from silently dropping `S_ISGID`.
989    /// 5. Final `fstat` verifies the directory is owned by the effective uid, carries gid
990    ///    `orig_gid`, and carries exactly `mode`. A filesystem that reports a successful
991    ///    `chown`/`chmod` without honoring it (e.g. CIFS without unix extensions), or a
992    ///    dropped `S_ISGID`, is caught here rather than descending into a still-exposed
993    ///    directory. A verify failure still leaves the directory at the restrictive interim
994    ///    mode from step 2/4.
995    ///
996    /// `orig_uid`/`orig_gid` are the owner/group captured at classification. Fails (typically
997    /// `EPERM`) when the copier neither owns the directory nor is privileged — caller fails closed.
998    pub async fn secure_as_copier(
999        &self,
1000        mode: u32,
1001        orig_uid: u32,
1002        orig_gid: u32,
1003    ) -> std::io::Result<()> {
1004        let fd = self.fd.clone();
1005        let euid = nix::unistd::geteuid().as_raw();
1006        run_metadata_probed_blocking(self.side, congestion::MetadataOp::Chmod, move || {
1007            let raw = fd.as_fd();
1008            // Take uid ownership — this locks the prior owner out of any further chown/chmod. If it
1009            // fails the directory is left untouched (transparent), which is fail-safe.
1010            fchown(raw, Some(Uid::from_raw(euid)), None).map_err(nix_to_io)?;
1011            // Restrict to owner-only IMMEDIATELY, so EVERY later failure leaves the directory no wider
1012            // than a successful copy would. Drop to a plain 0o700 first — there is no special bit to
1013            // lose yet; the setgid bit (if wanted) is re-added below, once the gid is correct. If the
1014            // chmod fails, roll the ownership back AND CHECK the rollback, so we never silently leave
1015            // the directory copier-owned at its original (possibly permissive) mode.
1016            if let Err(chmod_err) = fchmod(raw, Mode::from_bits_truncate(0o700)).map_err(nix_to_io)
1017            {
1018                // roll the ownership back AND VERIFY it landed with an fstat: a non-honoring backend
1019                // can report a false chown success, so we must never claim a restore that did not
1020                // happen.
1021                match fchown(raw, Some(Uid::from_raw(orig_uid)), None)
1022                    .map_err(nix_to_io)
1023                    .and_then(|()| fstat(raw).map_err(nix_to_io))
1024                {
1025                    // rollback landed: back to the prior owner at its original mode (the failed chmod
1026                    // changed nothing). Report the chmod cause.
1027                    Ok(st) if st.st_uid == orig_uid => return Err(chmod_err),
1028                    // rollback reported success but did not take effect (non-honoring backend).
1029                    Ok(st) => {
1030                        return Err(std::io::Error::new(
1031                            std::io::ErrorKind::PermissionDenied,
1032                            format!(
1033                                "reused-directory lockdown could not restrict the directory (chmod: \
1034                                 {chmod_err}); the ownership rollback did not take effect (directory \
1035                                 shows uid={}, expected {orig_uid}) — it is left copier-owned at its \
1036                                 original mode, refusing to descend (the filesystem may not honor \
1037                                 chown/chmod)",
1038                                st.st_uid,
1039                            ),
1040                        ));
1041                    }
1042                    Err(rb) => {
1043                        return Err(std::io::Error::new(
1044                            std::io::ErrorKind::PermissionDenied,
1045                            format!(
1046                                "reused-directory lockdown could not restrict the directory (chmod: \
1047                                 {chmod_err}) and could not roll ownership back (chown/stat: {rb}); \
1048                                 it is left owned by the copier at its original mode — refusing to \
1049                                 descend (the destination filesystem may be read-only or failing)"
1050                            ),
1051                        ));
1052                    }
1053                }
1054            }
1055            // VERIFY the takeover landed NOW — uid == copier and mode == exactly 0o700 — BEFORE the
1056            // fallible gid/setgid steps below run on a possibly-unverified directory. A backend that
1057            // reports a false chown/chmod success (e.g. CIFS without unix extensions) is thus caught
1058            // here rather than after more operations, and the directory is never descended into while
1059            // it might still be permissive.
1060            let st = fstat(raw).map_err(nix_to_io)?;
1061            if st.st_uid != euid || (st.st_mode & 0o7777) != 0o700 {
1062                return Err(std::io::Error::new(
1063                    std::io::ErrorKind::PermissionDenied,
1064                    format!(
1065                        "reused-directory lockdown could not be verified: after chown+chmod the \
1066                         directory shows uid={} mode={:#o} (expected uid={} mode={:#o}); the \
1067                         filesystem may not honor chown/chmod (e.g. CIFS without unix extensions) — \
1068                         refusing to descend",
1069                        st.st_uid,
1070                        st.st_mode & 0o7777,
1071                        euid,
1072                        0o700,
1073                    ),
1074                ));
1075            }
1076            // The directory is now VERIFIED copier-owned at 0o700 (restrictive); every exit below
1077            // leaves it at least that restrictive. Reset the gid if a prior owner raced a `chgrp`
1078            // before the take — only when it differs, so the unchanged common case issues no gid write
1079            // (never an EPERM for a non-root copier that owns the directory but is not in its group).
1080            // A setgid directory's children must inherit the captured gid, not the raced one.
1081            if st.st_gid != orig_gid {
1082                fchown(raw, None, Some(Gid::from_raw(orig_gid))).map_err(nix_to_io)?;
1083            }
1084            // Re-add the setgid bit now that the gid is orig_gid (skipped when the interim mode is a
1085            // plain 0o700). Doing this AFTER the gid reset means a non-privileged copier's chmod
1086            // cannot silently drop S_ISGID — the kernel keeps it because the directory's gid is now
1087            // one the copier is in (or the copier is root, with CAP_FSETID).
1088            if mode != 0o700 {
1089                fchmod(raw, Mode::from_bits_truncate(mode)).map_err(nix_to_io)?;
1090            }
1091            // verify the whole takeover actually landed (uid, gid, mode); fail closed otherwise.
1092            let st = fstat(raw).map_err(nix_to_io)?;
1093            if st.st_uid != euid || st.st_gid != orig_gid || (st.st_mode & 0o7777) != mode {
1094                return Err(std::io::Error::new(
1095                    std::io::ErrorKind::PermissionDenied,
1096                    format!(
1097                        "reused-directory lockdown could not be verified: after takeover the \
1098                         directory shows uid={} gid={} mode={:#o} (expected uid={} gid={} \
1099                         mode={:#o}); the filesystem may not honor chown/chmod (e.g. CIFS without \
1100                         unix extensions), or the copier is not in the directory's group and lacks \
1101                         CAP_FSETID to keep setgid — refusing to descend",
1102                        st.st_uid,
1103                        st.st_gid,
1104                        st.st_mode & 0o7777,
1105                        euid,
1106                        orig_gid,
1107                        mode,
1108                    ),
1109                ));
1110            }
1111            Ok(())
1112        })
1113        .await
1114    }
1115
1116    /// Create a child directory and return an open `Dir` handle to it (same side as self).
1117    ///
1118    /// Fails with `EINVAL` if `name` is not a single path component, or `EEXIST` if
1119    /// a directory (or any other entry) at `name` already exists.
1120    ///
1121    /// The `mkdirat`, the re-open, and (under strict operand resolution) the inherited-ACL strip
1122    /// all run inside ONE blocking closure, gated once as `MkDir`. That is a cancellation-safety
1123    /// requirement, not packaging: a queued job can be reclaimed before doing anything, while a
1124    /// closure that takes it runs every step to completion, so there is NO await point at which the
1125    /// directory exists but its sanitization has not happened. Splitting the steps across separate
1126    /// gated calls (as an earlier version did) leaves windows a `--fail-early` sibling abort can
1127    /// land in, abandoning an rcp-created directory that still carries the destination's inherited
1128    /// default ACL — inert at that moment (created owner-only, `ACL_MASK` empty), but poisoning the
1129    /// containment invariant for anything created under it later, including a rerun that cannot
1130    /// tell such an orphan from a user's own directory. For the same reason, a directory whose open
1131    /// or strip FAILS is removed (best-effort; it is empty and just created) inside the same closure
1132    /// rather than left behind unsanitized.
1133    ///
1134    /// # Inherited ACLs, and why the strip lives here
1135    ///
1136    /// A directory created under a parent that carries a DEFAULT ACL inherits both an access and a
1137    /// default ACL from it, and its own children then inherit in turn — so a destination tree's
1138    /// inheritance policy reaches straight through the directories rcp creates itself. Under
1139    /// [`strict_operand_resolution`] (`--require-toctou-safe`) that is contained by removing both
1140    /// ACLs from the new directory, which stops the chain for the directory's ENTIRE subtree:
1141    /// nothing created inside a stripped directory inherits anything. This is the containment half
1142    /// of the `--require-toctou-safe` invariant — *no destination entry that rcp CREATES carries an
1143    /// ACL entry that did not come from its source* — and stripping per DIRECTORY is what makes it
1144    /// 2 syscalls per directory and none per file created beneath one ([`Self::create_file`] pays
1145    /// its own single strip only in a parent rcp did NOT sanitize — the ambient parent of a direct
1146    /// file operand; see `children_may_inherit`).
1147    ///
1148    /// The strip belongs HERE rather than at each caller because this is the only `mkdirat` in the
1149    /// crate, and therefore the single creation site for both the local (`copy`/`link`) and remote
1150    /// (`rcpd`) destinations — a caller-side strip is one forgotten exit path away from leaving the
1151    /// hole open. The default path is untouched: it pays nothing, which is the whole point of making
1152    /// containment a strict-mode concern.
1153    ///
1154    /// `ENODATA` and `EOPNOTSUPP` are success for the strip (see `apply_one_acl`) — a directory
1155    /// with no inherited ACL, or on a filesystem that cannot hold one, already satisfies the
1156    /// post-condition. Any other errno fails the create (after the best-effort removal above), and
1157    /// the caller must fail closed rather than descend: an un-strippable default ACL is one every
1158    /// child written afterwards would inherit.
1159    ///
1160    /// **A consequence, deliberately taken.** Under `--require-toctou-safe` WITHOUT `d:acl` a fresh
1161    /// destination directory ends with NO ACL, even where the parent's default ACL would ordinarily
1162    /// have given it one. An administrator who set a default ACL on a destination tree expecting new
1163    /// subdirectories to inherit it does not get that under this flag. The flag's contract is that
1164    /// the destination reflects its source and nothing else, so containment beats inheritance;
1165    /// `d:acl` is the escape for a caller who wants the SOURCE's ACLs instead of none, and a caller
1166    /// who wants the destination tree's inheritance policy honored should not be using this flag on
1167    /// that tree.
1168    pub async fn make_dir(&self, name: &OsStr, mode: u32) -> std::io::Result<Dir> {
1169        self.make_dir_with_credit(name, mode, None).await
1170    }
1171
1172    /// Create a child while retaining its descriptor lifetime guard through blocking work.
1173    pub async fn make_dir_admitted(
1174        &self,
1175        name: &OsStr,
1176        mode: u32,
1177        credit: Arc<dyn std::fmt::Debug + Send + Sync>,
1178    ) -> std::io::Result<Dir> {
1179        self.make_dir_with_credit(name, mode, Some(credit)).await
1180    }
1181
1182    async fn make_dir_with_credit(
1183        &self,
1184        name: &OsStr,
1185        mode: u32,
1186        credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
1187    ) -> std::io::Result<Dir> {
1188        if !is_single_component(name) {
1189            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1190        }
1191        let dir = self.fd.clone();
1192        let side = self.side;
1193        let name_owned = name.to_owned();
1194        let strict = strict_operand_resolution();
1195        run_metadata_probed_blocking(side, congestion::MetadataOp::MkDir, move || {
1196            mkdirat(
1197                dir.as_fd(),
1198                name_owned.as_bytes(),
1199                Mode::from_bits_truncate(mode),
1200            )
1201            .map_err(nix_to_io)?;
1202            let open_flags =
1203                OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;
1204            let fd = match openat(
1205                dir.as_fd(),
1206                name_owned.as_bytes(),
1207                open_flags,
1208                Mode::empty(),
1209            )
1210            .map_err(nix_to_io)
1211            {
1212                Ok(fd) => fd,
1213                Err(err) => {
1214                    // could not open what was just created: remove it best-effort. No fd
1215                    // exists to anchor an inode recheck on, but the exposure is bounded —
1216                    // `RemoveDir` refuses anything but an empty directory, so a swapped-in
1217                    // file or symlink fails it and a swapped-in populated directory survives
1218                    let _ = unlinkat(dir.as_fd(), name_owned.as_bytes(), UnlinkatFlags::RemoveDir);
1219                    return Err(err);
1220                }
1221            };
1222            // construct the descriptor owner inside started work, before any fallible ACL
1223            // action or completed-task handoff can outlive the awaiting caller.
1224            let created = Dir {
1225                fd: Arc::new(DirectoryDescriptor { fd, credit }),
1226                side,
1227                children_may_inherit: Arc::new(std::sync::atomic::AtomicBool::new(!strict)),
1228            };
1229            #[cfg(test)]
1230            let _visit = resource_tests::gate_opened_descriptor(created.fd.as_raw_fd())?;
1231            if strict {
1232                // both ACLs, the default (inheritance-carrying) one first — see the doc
1233                // comment for why this must happen inside the creation closure
1234                if let Err(err) = apply_one_acl(created.fd.as_raw_fd(), ACL_DEFAULT_XATTR, None)
1235                    .and_then(|()| apply_one_acl(created.fd.as_raw_fd(), ACL_ACCESS_XATTR, None))
1236                {
1237                    // clean up the destination slot rather than leave inherited ACLs behind.
1238                    // rmdir can remove only an empty directory and never follows a symlink; a
1239                    // prior identity observation would not bind this by-name removal
1240                    let _ = unlinkat(dir.as_fd(), name_owned.as_bytes(), UnlinkatFlags::RemoveDir);
1241                    return Err(err);
1242                }
1243            }
1244            Ok(created)
1245        })
1246        .await
1247    }
1248
1249    /// Open an independent stream over this held directory.
1250    ///
1251    /// The `openat` of `.` creates a new open file description, so its offset is independent from
1252    /// both this `Dir` and every other cursor. It remains anchored to this already held directory.
1253    pub async fn entries(&self) -> std::io::Result<DirectoryCursor> {
1254        let dir = Arc::clone(&self.fd);
1255        let iterator = run_fd_admitted_blocking(move || {
1256            let fd = openat(
1257                dir.as_fd(),
1258                c".",
1259                OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC,
1260                Mode::empty(),
1261            )
1262            .map_err(nix_to_io)?;
1263            OwnedDirectoryStream::from_fd(fd, dir.credit.clone())
1264        })
1265        .await?;
1266        Ok(DirectoryCursor {
1267            iterator: Some(iterator),
1268            #[cfg(test)]
1269            read_hook: None,
1270        })
1271    }
1272
1273    /// Enumerate the directory's entries (excluding `.` and `..`).
1274    ///
1275    /// Returns each entry's name and its `getdents` `d_type` as a best-effort
1276    /// `EntryKind` hint (`None` when the filesystem reports `DT_UNKNOWN`). The
1277    /// hint is advisory only — callers MUST confirm type via `child`/`fstat`
1278    /// before acting (TOCTOU safety).
1279    ///
1280    /// This method acquires only the static ops rate gate (not the congestion
1281    /// probe). Directory enumeration is deliberately not probed because buffered
1282    /// `getdents` produces bimodal latency (cache hit vs. real kernel call) that
1283    /// would pollute the congestion controller's baseline — see
1284    /// `walk::next_entry_probed` for the full rationale.
1285    pub async fn read_entries(
1286        &self,
1287    ) -> std::io::Result<Vec<(std::ffi::OsString, Option<EntryKind>)>> {
1288        throttle::get_ops_token().await;
1289        let dir = self.fd.clone();
1290        run_fd_admitted_blocking(move || {
1291            // Dup the fd with FD_CLOEXEC so nix::dir::Dir can consume (and close)
1292            // it on drop without touching self's shared descriptor owner. A bare dup(2)
1293            // would clear FD_CLOEXEC; F_DUPFD_CLOEXEC atomically sets it.
1294            //
1295            // Re-entrancy: the dup shares the original's open file description,
1296            // and therefore its directory read offset. Reading to EOF advances
1297            // that shared offset, so a naive `fdopendir` loop would leave self's
1298            // fd at EOF and make a *second* read_entries() on the same Dir
1299            // return an empty listing. nix's borrowing `Iter` (from
1300            // `nix_dir.iter()`) rewinds the shared description in its `Drop`
1301            // (rewinddir(3) → offset 0), and that `Drop` runs on BOTH normal
1302            // completion AND the early `?`-return taken on a mid-iteration error
1303            // — so the dup is always rewound before it is closed, leaving self's
1304            // fd at offset 0 either way. This preserves repeatable full listings
1305            // for local callers. Streaming remote enumeration instead uses
1306            // `entries`, whose independent open description keeps its own offset.
1307            let dup_raw: RawFd =
1308                nix::fcntl::fcntl(dir.as_fd(), nix::fcntl::FcntlArg::F_DUPFD_CLOEXEC(0))
1309                    .map_err(nix_to_io)?;
1310            // SAFETY: dup_raw is a freshly-dup'd fd that we own exclusively; no
1311            // other reference to it exists.
1312            let dup_owned = unsafe { OwnedFd::from_raw_fd(dup_raw) };
1313            let mut nix_dir = nix::dir::Dir::from_fd(dup_owned).map_err(nix_to_io)?;
1314
1315            let mut entries = Vec::new();
1316            for entry_result in nix_dir.iter() {
1317                let entry = entry_result.map_err(nix_to_io)?;
1318                let name_cstr = entry.file_name();
1319                // skip "." and ".."
1320                if name_cstr == c"." || name_cstr == c".." {
1321                    continue;
1322                }
1323                let name = std::ffi::OsStr::from_bytes(name_cstr.to_bytes()).to_owned();
1324                let kind = entry.file_type().map(|t| match t {
1325                    nix::dir::Type::Directory => EntryKind::Dir,
1326                    nix::dir::Type::Symlink => EntryKind::Symlink,
1327                    nix::dir::Type::File => EntryKind::File,
1328                    _ => EntryKind::Special,
1329                });
1330                entries.push((name, kind));
1331            }
1332            // nix_dir drops here, closing the dup'd fd; self's fd is unaffected
1333            Ok(entries)
1334        })
1335        .await
1336    }
1337
1338    /// Enumerate at most `cap` entries (excluding `.` and `..`), or report the directory as
1339    /// over-cap. Returns `Ok(None)` as soon as a `cap + 1`-th entry is seen — the whole point:
1340    /// a caller that will DISCARD an over-cap listing (the overwrite-manifest build against its
1341    /// `--overwrite-manifest-max-entries` bound) must not pay for, or sit uncancellably in, a
1342    /// full enumeration of a directory arbitrarily larger than its bound. The early break leaves
1343    /// the shared read offset mid-directory; the borrowing iterator's `Drop` rewinds it exactly
1344    /// as on the full-read and error paths of [`Self::read_entries`], so re-enumeration on the
1345    /// same `Dir` stays sound.
1346    pub async fn read_entries_capped(
1347        &self,
1348        cap: usize,
1349    ) -> std::io::Result<Option<Vec<(std::ffi::OsString, Option<EntryKind>)>>> {
1350        throttle::get_ops_token().await;
1351        let dir = self.fd.clone();
1352        run_fd_admitted_blocking(move || {
1353            // dup + rewind contract: see read_entries
1354            let dup_raw: RawFd =
1355                nix::fcntl::fcntl(dir.as_fd(), nix::fcntl::FcntlArg::F_DUPFD_CLOEXEC(0))
1356                    .map_err(nix_to_io)?;
1357            // SAFETY: dup_raw is a freshly-dup'd fd that we own exclusively; no
1358            // other reference to it exists.
1359            let dup_owned = unsafe { OwnedFd::from_raw_fd(dup_raw) };
1360            let mut nix_dir = nix::dir::Dir::from_fd(dup_owned).map_err(nix_to_io)?;
1361            let mut entries = Vec::new();
1362            for entry_result in nix_dir.iter() {
1363                let entry = entry_result.map_err(nix_to_io)?;
1364                let name_cstr = entry.file_name();
1365                if name_cstr == c"." || name_cstr == c".." {
1366                    continue;
1367                }
1368                if entries.len() >= cap {
1369                    return Ok(None);
1370                }
1371                let name = std::ffi::OsStr::from_bytes(name_cstr.to_bytes()).to_owned();
1372                let kind = entry.file_type().map(|t| match t {
1373                    nix::dir::Type::Directory => EntryKind::Dir,
1374                    nix::dir::Type::Symlink => EntryKind::Symlink,
1375                    nix::dir::Type::File => EntryKind::File,
1376                    _ => EntryKind::Special,
1377                });
1378                entries.push((name, kind));
1379            }
1380            Ok(Some(entries))
1381        })
1382        .await
1383    }
1384
1385    /// Remove a child non-directory entry by name, gated on this directory's own congestion side.
1386    ///
1387    /// For a symlink, this unlinks the link itself — never its target.
1388    ///
1389    /// Fails with `EINVAL` if `name` is not a single path component, or `EISDIR`
1390    /// if `name` refers to a directory.
1391    pub async fn unlink_at(&self, name: &OsStr) -> std::io::Result<()> {
1392        self.unlink_at_on(name, self.side).await
1393    }
1394
1395    /// Like [`Self::unlink_at`], but gates the `unlinkat` on an explicitly chosen congestion
1396    /// `side` rather than the directory's own side.
1397    ///
1398    /// `rm` reads its tree on the `Source` side because its `Dir` handles are source-sided, but the
1399    /// destructive `unlinkat` is bucketed on `Destination` so it competes for the same metadata cwnd
1400    /// as other destructive work. The fd-relative TOCTOU guarantee is unaffected: the syscall is
1401    /// still resolved against this directory's pinned fd.
1402    pub(crate) async fn unlink_at_on(
1403        &self,
1404        name: &OsStr,
1405        side: congestion::Side,
1406    ) -> std::io::Result<()> {
1407        if !is_single_component(name) {
1408            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1409        }
1410        let dir = self.fd.clone();
1411        let name = name.to_owned();
1412        run_metadata_probed_blocking(side, congestion::MetadataOp::Unlink, move || {
1413            unlinkat(dir.as_fd(), name.as_bytes(), UnlinkatFlags::NoRemoveDir).map_err(nix_to_io)
1414        })
1415        .await
1416    }
1417
1418    /// Remove a child empty directory by name, gated on this directory's own congestion side.
1419    ///
1420    /// Fails with `EINVAL` if `name` is not a single path component, `ENOTEMPTY`
1421    /// if the directory is not empty, or `ENOTDIR` if `name` is not a directory.
1422    pub async fn rmdir_at(&self, name: &OsStr) -> std::io::Result<()> {
1423        self.rmdir_at_on(name, self.side).await
1424    }
1425
1426    /// Like [`Self::rmdir_at`], but gates the `rmdir` on an explicitly chosen congestion `side`
1427    /// rather than the directory's own side. See [`Self::unlink_at_on`] for why `rm` needs this
1428    /// (`Destination`-sided removal from a `Source`-sided read walk).
1429    pub(crate) async fn rmdir_at_on(
1430        &self,
1431        name: &OsStr,
1432        side: congestion::Side,
1433    ) -> std::io::Result<()> {
1434        if !is_single_component(name) {
1435            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1436        }
1437        let dir = self.fd.clone();
1438        let name = name.to_owned();
1439        run_metadata_probed_blocking(side, congestion::MetadataOp::RmDir, move || {
1440            unlinkat(dir.as_fd(), name.as_bytes(), UnlinkatFlags::RemoveDir).map_err(nix_to_io)
1441        })
1442        .await
1443    }
1444
1445    /// Create a symlink `name` → `target` in this directory, returning a
1446    /// fd-pinned `Handle` to the just-created link.
1447    ///
1448    /// The returned handle has `kind() == EntryKind::Symlink` and can be used to
1449    /// apply metadata to the link race-free. `target` is the link contents — it
1450    /// is an arbitrary path and is not restricted to a single component.
1451    ///
1452    /// Fails with `EINVAL` if `name` is not a single path component, or `EEXIST`
1453    /// if an entry at `name` already exists.
1454    pub async fn symlink_at(&self, name: &OsStr, target: &Path) -> std::io::Result<Handle> {
1455        if !is_single_component(name) {
1456            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1457        }
1458        let dir = self.fd.clone();
1459        let side = self.side;
1460        let name = name.to_owned();
1461        let target = target.to_owned();
1462        // clone `name` so we can call self.child() after the closure consumes it
1463        let name_for_child = name.clone();
1464        run_metadata_probed_blocking(side, congestion::MetadataOp::Symlink, move || {
1465            // symlinkat(target, dirfd, name): creates `name` → `target`
1466            symlinkat(target.as_os_str().as_bytes(), dir.as_fd(), name.as_bytes())
1467                .map_err(nix_to_io)
1468        })
1469        .await?;
1470        // open the just-created link with O_PATH|O_NOFOLLOW so we get a Handle
1471        // that is pinned to the symlink inode itself (not its target).
1472        let handle = self.child(&name_for_child).await?;
1473        if handle.kind() != EntryKind::Symlink {
1474            // should never happen — we just created a symlink; if it somehow
1475            // changed underneath us, report ENOENT to signal the caller.
1476            return Err(std::io::Error::from_raw_os_error(libc::ENOENT));
1477        }
1478        Ok(handle)
1479    }
1480
1481    /// Read the target of a child symlink.
1482    ///
1483    /// Fails with `EINVAL` if `name` is not a single path component, or `EINVAL`
1484    /// (from `readlinkat`) if `name` is not a symlink.
1485    pub async fn read_link_at(&self, name: &OsStr) -> std::io::Result<std::path::PathBuf> {
1486        if !is_single_component(name) {
1487            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1488        }
1489        let dir = self.fd.clone();
1490        let side = self.side;
1491        let name = name.to_owned();
1492        run_metadata_probed_blocking(side, congestion::MetadataOp::ReadLink, move || {
1493            readlinkat(dir.as_fd(), name.as_bytes())
1494                .map(std::path::PathBuf::from)
1495                .map_err(nix_to_io)
1496        })
1497        .await
1498    }
1499
1500    /// Create a hard link at `dst`/`dst_name` pointing to this directory's `name`.
1501    ///
1502    /// Uses `AtFlags::empty()` (flags=0, no `AT_SYMLINK_FOLLOW`), so if `name` is a
1503    /// symlink, the link target is the symlink inode itself — the target file
1504    /// gains no new hard link.
1505    ///
1506    /// Fails with `EINVAL` if either `name` or `dst_name` is not a single path
1507    /// component.
1508    pub async fn hard_link_at(
1509        &self,
1510        name: &OsStr,
1511        dst: &Dir,
1512        dst_name: &OsStr,
1513    ) -> std::io::Result<()> {
1514        if !is_single_component(name) {
1515            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1516        }
1517        if !is_single_component(dst_name) {
1518            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1519        }
1520        let src_dir = self.fd.clone();
1521        let dst_dir = dst.fd.clone();
1522        let side = dst.side;
1523        let name = name.to_owned();
1524        let dst_name = dst_name.to_owned();
1525        run_metadata_probed_blocking(side, congestion::MetadataOp::HardLink, move || {
1526            linkat(
1527                src_dir.as_fd(),
1528                name.as_bytes(),
1529                dst_dir.as_fd(),
1530                dst_name.as_bytes(),
1531                AtFlags::empty(),
1532            )
1533            .map_err(nix_to_io)
1534        })
1535        .await
1536    }
1537
1538    /// Create a hard link at `self`/`dst_name` pointing to the EXACT inode that
1539    /// `src_handle` pins — never re-resolving the source by name.
1540    ///
1541    /// `self` is the DESTINATION directory. The source is identified solely by
1542    /// `src_handle`'s `O_PATH` file descriptor: the link is made via
1543    /// `linkat(AT_FDCWD, "/proc/self/fd/N", dst_fd, dst_name, AT_SYMLINK_FOLLOW)`,
1544    /// where `N` is the handle's fd. `AT_SYMLINK_FOLLOW` makes `linkat` follow the
1545    /// `/proc` magic symlink to the handle's pinned inode, so the new hard link
1546    /// targets that exact inode regardless of any concurrent rename / symlink swap
1547    /// of the original directory entry.
1548    ///
1549    /// # Why /proc and not the source-name `linkat` or `AT_EMPTY_PATH`
1550    ///
1551    /// `Dir::hard_link_at` re-resolves the source by `name`, which is a TOCTOU
1552    /// window: an attacker who controls the source tree can replace `name` with a
1553    /// different inode (symlink, FIFO, another file) between classification and the
1554    /// `linkat`, so the link would target the replacement. Linking the pinned fd
1555    /// closes that window. `linkat(fd, "", .., AT_EMPTY_PATH)` would also be
1556    /// inode-exact but requires `CAP_DAC_READ_SEARCH`; the `/proc/self/fd` form does
1557    /// not, mirroring `chmod_via_proc_fd`.
1558    ///
1559    /// # Behavior
1560    ///
1561    /// - Inode-exact happy path: a stable regular-file handle links exactly as the
1562    ///   by-name path did (same inode, same content).
1563    /// - Fail-closed under attack: if the pinned inode's last directory entry was
1564    ///   removed (link count 0, e.g. the attacker renamed `name` away), the kernel
1565    ///   refuses to resurrect it and `linkat` fails with `ENOENT`. It never links a
1566    ///   swapped-in replacement.
1567    /// - Directories: `linkat` refuses to hard-link a directory (`EPERM`), exactly
1568    ///   as the by-name path did. Callers must only pass a regular-file handle.
1569    ///
1570    /// # Errors
1571    ///
1572    /// `EINVAL` if `dst_name` is not a single path component; `ENOENT` if the pinned
1573    /// inode has no remaining links (fail-closed); `EEXIST` if an entry at
1574    /// `dst_name` already exists; `EPERM` if the handle refers to a directory.
1575    /// Requires `/proc` mounted (same precondition as `chmod_via_proc_fd`).
1576    pub async fn hard_link_handle_at(
1577        &self,
1578        src_handle: &Handle,
1579        dst_name: &OsStr,
1580    ) -> std::io::Result<()> {
1581        if !is_single_component(dst_name) {
1582            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1583        }
1584        // clone the source O_PATH fd into an owned fd the blocking closure can hold,
1585        // keeping the pinned inode alive for the syscall's full duration even if the
1586        // originating Handle is dropped after the closure starts. started spawn_blocking work is
1587        // not cancellable.
1588        let src_owned = src_handle.as_fd().try_clone_to_owned()?;
1589        let dst_dir = self.fd.clone();
1590        let side = self.side;
1591        let dst_name = dst_name.to_owned();
1592        run_metadata_probed_blocking(side, congestion::MetadataOp::HardLink, move || {
1593            let proc_path = format!("/proc/self/fd/{}", src_owned.as_raw_fd());
1594            // AT_SYMLINK_FOLLOW: the /proc entry is a magic symlink that must be
1595            // dereferenced to reach the pinned inode (without the flag, linkat would
1596            // try to hard-link the magic symlink itself, which is not permitted).
1597            linkat(
1598                AT_FDCWD,
1599                proc_path.as_str(),
1600                dst_dir.as_fd(),
1601                dst_name.as_bytes(),
1602                AtFlags::AT_SYMLINK_FOLLOW,
1603            )
1604            .map_err(nix_to_io)
1605        })
1606        .await
1607    }
1608
1609    /// Create a new child file, failing if it already exists and never following a symlink.
1610    ///
1611    /// The file is ALWAYS created at [`DST_FILE_CREATE_MODE`] — there is deliberately no mode
1612    /// parameter, so a caller cannot publish a destination file at its final (possibly setuid)
1613    /// mode before its contents exist. [`set_file_metadata_owned`] widens it to the source mode after
1614    /// the last byte. Returns the open writable `File` on success; the returned fd is writable
1615    /// whatever the mode says, having been opened `O_WRONLY` at creation.
1616    ///
1617    /// `O_EXCL` is the primary guard: combined with `O_CREAT`, it fails with
1618    /// `EEXIST` on any pre-existing entry — including a symlink — without
1619    /// following it. `O_NOFOLLOW` is the fallback that would still refuse to
1620    /// follow a symlink (with `ELOOP`) should `O_EXCL` ever be bypassed.
1621    ///
1622    /// # The ambient-parent ACL strip
1623    ///
1624    /// Under [`strict_operand_resolution`] a file created in a parent rcp did NOT sanitize — the
1625    /// ambient parent of a direct file operand, the one directory kind rcp neither creates nor
1626    /// locks down (`children_may_inherit`) — has its inherited access ACL removed in the SAME
1627    /// blocking closure as the create. Without it, a parent's default ACL hands the fresh file
1628    /// named `user:`/`group:` entries; they are inert at [`DST_FILE_CREATE_MODE`] (the create mode
1629    /// leaves `ACL_MASK` empty), but the final `fchmod` to the source mode re-derives the mask
1630    /// from the group bits and ACTIVATES them — a strict copy of a plain `0640` file granting a
1631    /// named user read access its source never did. Files created beneath a sanitized directory
1632    /// pay nothing: the parent-side strip already broke the inheritance chain, which is the flag's
1633    /// whole point. A strip failure fails the create (after a best-effort unlink of the empty
1634    /// file), because the caller's later chmod would otherwise publish the inherited entries.
1635    ///
1636    /// Fails with `EINVAL` if `name` is not a single path component, or `EEXIST`
1637    /// if a file or symlink at `name` already exists.
1638    pub async fn create_file(&self, name: &OsStr) -> std::io::Result<std::fs::File> {
1639        let operation = self.file_create_operation(name, strict_operand_resolution())?;
1640        run_metadata_probed_blocking(self.side, congestion::MetadataOp::OpenCreate, operation).await
1641    }
1642
1643    /// Create a file and claim an unprobed continuation on the same blocking worker.
1644    ///
1645    /// Creation errors are passed to `continuation`, which can return any held source descriptor
1646    /// for conflict recovery. Invalid names invoke it inline without submitting blocking work.
1647    /// The outer error reports a blocking-worker failure. Cancelling before
1648    /// the continuation claim destroys its captures without running it; a claimed continuation
1649    /// retains the canonical blocking job's descriptor admission through completion and output drop.
1650    pub(crate) async fn create_file_and_then<C, T>(
1651        &self,
1652        name: &OsStr,
1653        continuation: C,
1654    ) -> std::io::Result<T>
1655    where
1656        C: FnOnce(std::io::Result<std::fs::File>) -> T + Send + 'static,
1657        T: Send + 'static,
1658    {
1659        let operation = match self.file_create_operation(name, strict_operand_resolution()) {
1660            Ok(operation) => operation,
1661            Err(error) => return Ok(continuation(Err(error))),
1662        };
1663        run_file_create_and_then(self.side, operation, continuation).await
1664    }
1665
1666    fn file_create_operation(
1667        &self,
1668        name: &OsStr,
1669        strict: bool,
1670    ) -> std::io::Result<impl FnOnce() -> std::io::Result<std::fs::File> + Send + 'static + use<>>
1671    {
1672        if !is_single_component(name) {
1673            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1674        }
1675        let dir = self.fd.clone();
1676        let name = name.to_owned();
1677        // the flag travels INTO the closure and is read AFTER the openat: a pre-submit snapshot
1678        // races the reused-dir rollback — a fail-early abort can restore the parent's default ACL
1679        // between this submit and the queued openat, and the file created then DOES inherit. The
1680        // rollback stores `true` before its restore syscall and this load runs after the openat;
1681        // syscalls order as full fences, so an openat that observed the restored ACL cannot then
1682        // load a stale `false`. A wasted strip on a not-yet-restored parent remains harmless.
1683        let may_inherit = Arc::clone(&self.children_may_inherit);
1684        Ok(move || {
1685            let flags = OFlag::O_CREAT
1686                | OFlag::O_EXCL
1687                | OFlag::O_WRONLY
1688                | OFlag::O_NOFOLLOW
1689                | OFlag::O_CLOEXEC;
1690            let file_mode = Mode::from_bits_truncate(DST_FILE_CREATE_MODE);
1691            let file = openat(dir.as_fd(), name.as_bytes(), flags, file_mode)
1692                .map(std::fs::File::from)
1693                .map_err(nix_to_io)?;
1694            #[cfg(test)]
1695            let _visit = tests::gate_file_create_stage(file.as_raw_fd(), "before-sanitation");
1696            if strict && may_inherit.load(std::sync::atomic::Ordering::SeqCst) {
1697                // same-closure for the same reason as `make_dir`: queued work creates nothing,
1698                // while work that starts runs to completion, so cancellation cannot abandon a
1699                // created-but-unsanitized file. cleanup is a single unlink relative to the ambient
1700                // operand parent; it never follows a symlink or removes a directory, and a prior
1701                // identity observation would not bind the by-name removal
1702                if let Err(err) = apply_one_acl(file.as_raw_fd(), ACL_ACCESS_XATTR, None) {
1703                    let _ = unlinkat(dir.as_fd(), name.as_bytes(), UnlinkatFlags::NoRemoveDir);
1704                    return Err(err);
1705                }
1706            }
1707            Ok(file)
1708        })
1709    }
1710}
1711
1712// ── TrustedDir ──────────────────────────────────────────────────────────────────
1713
1714/// A directory opened by FOLLOWING symlinks normally — the command-line-named
1715/// path's trusted parent prefix.
1716///
1717/// The trusted-boundary model (docs/tocttou.md, "Trusted boundary") trusts the path named on the
1718/// command line up to and including its container directory; only entries
1719/// strictly BELOW the named root are hardened with `O_NOFOLLOW`. A `TrustedDir`
1720/// is that trusted container, and it is the only retained/exposed follow-open transition used by
1721/// ordinary callers. The private dry-run preview parent opener follows the trusted prefix
1722/// internally before its nofollow descent. Every other ordinary directory open ([`Dir::open_dir`],
1723/// [`Dir::child`], [`Dir::open_file_read`], [`Dir::create_file`],
1724/// [`Dir::make_dir`], …) is `O_NOFOLLOW`.
1725///
1726/// Because the trusted/hardened distinction is a type rather than a convention,
1727/// the compiler enforces it: a parent-prefix slot typed `TrustedDir` can only be
1728/// filled by the follow-open, and a hardened `Dir` cannot be used where a trusted
1729/// parent is required. Crossing from the trusted prefix into the hardened tree is
1730/// the single explicit [`Self::into_tree`] step.
1731///
1732/// Under strict operand resolution (`--require-toctou-safe`) the "trusted"
1733/// prefix is additionally required to be symlink-free: the open resolves it
1734/// `RESOLVE_NO_SYMLINKS`, so a symlink component fails closed with `ELOOP`
1735/// rather than being followed (see [`enable_strict_operand_resolution`]).
1736#[derive(Debug)]
1737pub struct TrustedDir(Dir);
1738
1739impl TrustedDir {
1740    /// Cross from the trusted parent prefix into the hardened tree, consuming the `TrustedDir` and
1741    /// handing back the owned hardened `Dir` (e.g. to wrap it in an `Arc` for the walk). Every open
1742    /// below the returned `Dir` is `O_NOFOLLOW`, so nothing below the named root can be redirected
1743    /// by a symlink swap. This is the one explicit trusted→hardened transition.
1744    #[must_use]
1745    pub fn into_tree(self) -> Dir {
1746        self.0
1747    }
1748}
1749
1750// ── Operand probes and contained preview opens ───────────────────────────────
1751//
1752// dry-run preview scans resolve the trusted operand parent with the active default/strict policy,
1753// then open the named operand and every scan-relative component fd-relative without following
1754// symlinks. The strict existence/kind probes below similarly decompose an operand into parent +
1755// final component: strict mode resolves the parent through `openat2(RESOLVE_NO_SYMLINKS)` and
1756// touches only the final component fd-relative, while default-mode callers retain their existing
1757// path-based probes.
1758
1759/// Split a lexically-normal absolute operand into `(parent, final_component)` for
1760/// an fd-relative probe. Strict operands are already absolute + normal (the linter
1761/// enforced it), so a plain `parent()`/`file_name()` split is correct. Returns
1762/// `None` when the path has no distinct parent+name (e.g. `/`), where there is
1763/// nothing to probe fd-relative.
1764fn split_parent_and_name(path: &Path) -> Option<(&Path, &OsStr)> {
1765    let name = path.file_name()?;
1766    let parent = match path.parent() {
1767        Some(parent) if !parent.as_os_str().is_empty() => parent,
1768        // a single-component relative path means the current directory
1769        _ => Path::new("."),
1770    };
1771    Some((parent, name))
1772}
1773
1774/// Open the trusted parent of a destination operand for a contained preview scan.
1775///
1776/// `O_PATH` is load-bearing in default mode: a searchable-but-unreadable parent may contain an
1777/// operand that is itself readable, and preview containment must not add a parent read-permission
1778/// requirement. Strict mode applies the same flag through `openat2(RESOLVE_NO_SYMLINKS)`.
1779async fn open_preview_operand_parent(path: &Path, side: congestion::Side) -> std::io::Result<Dir> {
1780    let path = path.to_owned();
1781    run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
1782        let flags = OFlag::O_PATH | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC;
1783        #[cfg(target_os = "linux")]
1784        if strict_operand_resolution() {
1785            return openat2_no_symlinks(&path, flags)
1786                .map(|fd| Dir::opened(fd, side))
1787                .map_err(nix_to_io);
1788        }
1789        openat(AT_FDCWD, &path, flags, Mode::empty())
1790            .map(|fd| Dir::opened(fd, side))
1791            .map_err(nix_to_io)
1792    })
1793    .await
1794}
1795
1796fn preview_scan_absence(error: &std::io::Error) -> bool {
1797    error.kind() == std::io::ErrorKind::NotFound
1798        || error.kind() == std::io::ErrorKind::NotADirectory
1799        || matches!(
1800            error.raw_os_error(),
1801            Some(libc::ENOTDIR) | Some(libc::ELOOP)
1802        )
1803}
1804
1805/// Open one preview child through its held parent without following a final symlink.
1806/// Missing, non-directory, and symlink children have no directory to scan; other errors propagate.
1807pub(crate) async fn open_existing_preview_child(
1808    parent: &Dir,
1809    name: &OsStr,
1810) -> std::io::Result<Option<Dir>> {
1811    match parent.open_dir(name).await {
1812        Ok(dir) => Ok(Some(dir)),
1813        Err(error) if preview_scan_absence(&error) => Ok(None),
1814        Err(error) => Err(error),
1815    }
1816}
1817
1818fn preview_relative_components(relative: &Path) -> std::io::Result<Vec<std::ffi::OsString>> {
1819    if relative.as_os_str().is_empty() {
1820        return Ok(Vec::new());
1821    }
1822    relative
1823        .as_os_str()
1824        .as_bytes()
1825        .split(|byte| *byte == b'/')
1826        .map(|component| {
1827            let component = OsStr::from_bytes(component);
1828            is_single_component(component)
1829                .then(|| component.to_owned())
1830                .ok_or_else(|| std::io::Error::from_raw_os_error(libc::EINVAL))
1831        })
1832        .collect()
1833}
1834
1835/// Open an existing directory below the exact destination operand named by the user.
1836///
1837/// The operand's trusted parent is resolved with the normal strict/default policy, but the named
1838/// root itself and every `relative` component are opened one at a time with `O_NOFOLLOW`. This keeps
1839/// dry-run delete scans beneath the operand even when that final operand component is a symlink.
1840/// Missing, non-directory, and symlink components mean there is no real directory to preview and
1841/// return `None`; every other error remains observable to the caller.
1842pub(crate) async fn open_existing_dir_beneath_operand(
1843    named_root: &Path,
1844    relative: &Path,
1845    side: congestion::Side,
1846) -> std::io::Result<Option<Dir>> {
1847    let relative = preview_relative_components(relative)?;
1848    let Some((parent_path, root_name)) = split_parent_and_name(named_root) else {
1849        return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1850    };
1851    if !is_single_component(root_name) {
1852        return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1853    }
1854    let parent = match open_preview_operand_parent(parent_path, side).await {
1855        Ok(parent) => parent,
1856        Err(error) if preview_scan_absence(&error) => return Ok(None),
1857        Err(error) => return Err(error),
1858    };
1859    let mut current = match parent.open_dir(root_name).await {
1860        Ok(dir) => dir,
1861        Err(error) if preview_scan_absence(&error) => return Ok(None),
1862        Err(error) => return Err(error),
1863    };
1864    drop(parent);
1865    for component in relative {
1866        current = match current.open_dir(&component).await {
1867            Ok(dir) => dir,
1868            Err(error) if preview_scan_absence(&error) => return Ok(None),
1869            Err(error) => return Err(error),
1870        };
1871    }
1872    Ok(Some(current))
1873}
1874
1875/// Probe an operand's existence and kind fd-relative under strict operand
1876/// resolution: open its parent with `open_parent_dir` (`RESOLVE_NO_SYMLINKS`
1877/// while armed) and classify the final component via `child` (`O_NOFOLLOW`).
1878///
1879/// - `Ok(Some(kind))` — the entry exists (a final-component symlink counts as
1880///   existing, classified `Symlink`, and is never followed, matching
1881///   `symlink_metadata`).
1882/// - `Ok(None)` — the entry, or its parent, does not exist (`ENOENT`/`ENOTDIR`).
1883/// - `Err(ELOOP)` — a directory component of the operand path is a symlink; the
1884///   caller must fail closed.
1885pub async fn strict_probe_dst_kind(
1886    path: &Path,
1887    side: congestion::Side,
1888) -> std::io::Result<Option<EntryKind>> {
1889    let Some((parent, name)) = split_parent_and_name(path) else {
1890        return Ok(None);
1891    };
1892    match Dir::open_parent_dir(parent, side).await {
1893        Ok(parent) => match parent.into_tree().child(name).await {
1894            Ok(handle) => Ok(Some(handle.kind())),
1895            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
1896            Err(err) => Err(err),
1897        },
1898        Err(err)
1899            if err.kind() == std::io::ErrorKind::NotFound
1900                || err.raw_os_error() == Some(libc::ENOTDIR) =>
1901        {
1902            Ok(None)
1903        }
1904        Err(err) => Err(err),
1905    }
1906}
1907
1908/// What a strict-mode reused-directory lockdown changed and finalize must put back.
1909///
1910/// # This type is an RAII guard, and that is the point
1911///
1912/// The snapshotted default ACL is the ONLY copy of those bytes in existence — the lockdown removed
1913/// them from the filesystem. If this value were ever dropped without the restore running, the
1914/// destination directory would permanently lose an ACL it had before the copy: unrecoverable, and
1915/// invisible, since nothing else reports it.
1916///
1917/// There are many ways to drop it. A `--fail-early` copy returns `Err` from the walk driver without
1918/// ever reaching `dir_post`, and aborts its in-flight siblings by dropping their `JoinSet` — so one
1919/// failed leaf can end a dozen directories' lockdowns at once. A failed `read_entries` in
1920/// `link_dir_contents` also aborts under `--fail-early`; keep-going instead drains its workers and
1921/// reaches directory finalization. The remote destination can fail between locking a directory and
1922/// registering it, or shut down with directories still pending. Restoring at
1923/// each of those sites is the shape `CLAUDE.md` warns about — a missed exit path is the recurring
1924/// finding here, and there were six-plus of them.
1925///
1926/// So the restore lives in [`Drop`] instead, and holds on every exit path that drops the value: an
1927/// early return, a `?`, a `break`, and — the case the abort paths above actually need — a cancelled
1928/// task, since dropping a future drops its locals. [`set_reused_dir_metadata_fd`] disarms the guard
1929/// once the default ACL has been dealt with deliberately AND nothing after it can fail, which is
1930/// why the state is private: nothing outside this module can arm, disarm, or duplicate it. The
1931/// armed/disarmed distinction is an explicit enum (`DefaultAclGuard`) rather than the emptiness
1932/// of the snapshot, because a directory that HAD no default ACL still needs an armed rollback: a
1933/// partial finalize may have installed the source's, and only an armed guard removes it. `Clone`
1934/// is deliberately NOT derived — exactly one of these exists per lockdown, and a copy would
1935/// restore twice.
1936///
1937/// **The guard must exist before anything is destroyed, not after.** "Dropped on every exit path"
1938/// says nothing about the window in which the value does not exist. [`lockdown_reused_dir`] arms
1939/// the guard before removing the ACL synchronously, with no cancellation point in between.
1940///
1941/// # Exits it does NOT cover
1942///
1943/// A panic (the workspace builds `panic = "abort"`, so nothing unwinds and no destructor runs), a
1944/// signal, and `std::process::exit` — which, unlike the first two, is ordinary control flow in
1945/// shipped code. Every `process::exit` call site runs either before a copy starts (the TOCTOU
1946/// linter, config validation) or after `common::run` has dropped the tokio runtime, which drops every
1947/// task and therefore every guard; `rcpd`'s stdin watchdog follows the same lifetime rule. A call
1948/// that exits mid-copy would reintroduce the hole. Closing it for panic and signal would need the
1949/// snapshot on disk rather than in memory — out of proportion to the risk, but worth knowing rather
1950/// than assuming this is total.
1951///
1952/// # The `Drop` restore is best-effort recovery, not a guarantee
1953///
1954/// A destructor cannot await, so it issues a synchronous `fsetxattr` that bypasses the congestion
1955/// throttle every other metadata write here goes through, and it cannot return an error. A failure
1956/// is logged at `warn!` naming the directory — resolved from the held fd through `/proc/self/fd`,
1957/// one cheap syscall, because on a mass abort an operator otherwise gets N indistinguishable
1958/// warnings and no target — along with the ACL bytes to rebuild it from. A SUCCESSFUL restore is
1959/// logged at `debug!` so that "did the guard fire?" is observable rather than inferred. This is the
1960/// backstop for an aborted copy; the finalize path is where a successful one restores.
1961///
1962/// # What is deliberately NOT restored here
1963///
1964/// Only the default ACL. An aborted lockdown still leaves the directory owned by the copier at
1965/// `0o700` — that outcome is already documented in `docs/tocttou.md`, and unlike ACL loss it is
1966/// narrow, visible, and repairable: an operator sees the mode and fixes it. Nothing is destroyed.
1967/// The armed/disarmed state of a [`ReusedDirLock`]'s default-ACL rollback, shared (behind one
1968/// mutex) between the guard's `Drop` restore and every finalize write to the guarded attribute.
1969///
1970/// Two conflations this enum exists to prevent:
1971///
1972/// - **"Had no original ACL" is not "nothing to undo".** With `d:acl` on, finalize INSTALLS the
1973///   source's default ACL before later steps that can still fail; a directory that originally had
1974///   none must then get that installation REMOVED on rollback, or a failed copy leaves it carrying
1975///   an ACL the destination never had. A bare `Option<Vec<u8>>` cannot express that arm because its
1976///   `None` would have to mean both "no original ACL" and "disarmed".
1977/// - **A detached write must not undo the restore.** A finalize ACL write still queued when its
1978///   waiter is dropped is reclaimed before it starts, but one already taken by a blocking worker
1979///   cannot be cancelled and may land AFTER the guard's `Drop` has put the original back.
1980///   Serializing every guarded write and the restore through this one mutex, with a write that
1981///   observes [`Self::Disarmed`] SKIPPING, closes the race in both directions: a write mid-syscall
1982///   holds the mutex, so the restore waits and then lands over it (correct — the copy is
1983///   aborting); a write not yet started finds the guard disarmed and never lands.
1984#[derive(Debug)]
1985enum DefaultAclGuard {
1986    /// The lockdown is live. On abort, put the directory's default ACL back to `original`:
1987    /// `Some` bytes are restored; `None` means the directory had no default ACL, so whatever a
1988    /// partial finalize may have installed is REMOVED.
1989    Armed { original: Option<Vec<u8>> },
1990    /// Finalize resolved the default ACL deliberately (or the restore already ran). Nothing is
1991    /// left to undo, and any still-queued guarded write must NOT land.
1992    Disarmed,
1993}
1994
1995#[derive(Debug)]
1996pub struct ReusedDirLock {
1997    /// The directory's original `(uid, gid)`, taken from the classify handle before the takeover.
1998    pub restore_owner: (u32, u32),
1999    /// The rollback state plus the original default ACL, shared (`Arc`) with in-flight guarded
2000    /// writes so the `Drop` restore serializes against them — see `DefaultAclGuard`.
2001    state: Arc<std::sync::Mutex<DefaultAclGuard>>,
2002    /// The locked directory's fd, shared with the `Dir` it came from. An `Arc` rather than a `dup`:
2003    /// it costs no descriptor and no syscall, and it keeps the fd open for exactly as long as the
2004    /// guard can still need it, so `Drop` writes to the pinned inode rather than re-resolving a path
2005    /// an attacker may have swapped.
2006    fd: Arc<DirectoryDescriptor>,
2007    /// The locked `Dir`'s inherit flag, shared so the rollback can RE-ARM it (`store(true)` before
2008    /// the restore syscall): restoring the original default ACL makes inheritance possible again,
2009    /// and a file created in the window after the rollback must strip what it inherited — see
2010    /// `Dir::children_may_inherit` and `Dir::create_file`.
2011    children_may_inherit: Arc<std::sync::atomic::AtomicBool>,
2012}
2013
2014impl ReusedDirLock {
2015    /// The original default ACL the lockdown snapshotted (`None` when the directory had none).
2016    /// Peeks without disarming; a caller restores it via [`Self::write_default_acl_guarded`].
2017    fn original_default_acl(&self) -> Option<Vec<u8>> {
2018        match &*self.state.lock().unwrap() {
2019            DefaultAclGuard::Armed { original } => original.clone(),
2020            DefaultAclGuard::Disarmed => None,
2021        }
2022    }
2023
2024    /// Declare the default ACL deliberately resolved: the `Drop` restore becomes a no-op and any
2025    /// still-queued guarded write is refused. Only called once every finalize step that could
2026    /// still fail has succeeded.
2027    fn disarm(&self) {
2028        *self.state.lock().unwrap() = DefaultAclGuard::Disarmed;
2029    }
2030
2031    /// Install `blob` as the locked directory's DEFAULT ACL, serialized against the guard's
2032    /// rollback (see `DefaultAclGuard`): the state mutex is held across the syscall, and a write
2033    /// that finds the guard already disarmed is SKIPPED — landing it would silently undo a restore
2034    /// that already ran. Every finalize-path write to this attribute MUST go through here; an
2035    /// unguarded `set_or_remove_acl_fd` on the blocking pool is exactly the detached-write hazard
2036    /// the guard exists to close. Only ever needs to SET: after the lockdown the directory
2037    /// provably carries no default ACL, so "remove" cases have nothing to do.
2038    ///
2039    /// Gated as `MetadataOp::Chmod`, like every other single-inode permission write.
2040    async fn write_default_acl_guarded(
2041        &self,
2042        side: congestion::Side,
2043        blob: Vec<u8>,
2044    ) -> std::io::Result<()> {
2045        let state = Arc::clone(&self.state);
2046        let fd = Arc::clone(&self.fd);
2047        run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
2048            let guard = state.lock().unwrap();
2049            match &*guard {
2050                DefaultAclGuard::Armed { .. } => {
2051                    apply_one_acl(fd.as_raw_fd(), ACL_DEFAULT_XATTR, Some(&blob))
2052                }
2053                DefaultAclGuard::Disarmed => {
2054                    // this write's owner was cancelled and the dropped guard already restored;
2055                    // landing the write now would silently overwrite that restore
2056                    tracing::debug!(
2057                        "skipped a default-ACL write that lost its race against the lockdown \
2058                         guard's restore ({} bytes)",
2059                        blob.len(),
2060                    );
2061                    Ok(())
2062                }
2063            }
2064        })
2065        .await
2066    }
2067}
2068
2069impl Drop for ReusedDirLock {
2070    fn drop(&mut self) {
2071        // re-arm the inherit flag BEFORE the restore syscall (which may run detached below): once
2072        // the original default ACL is back, a file created in this directory inherits it and must
2073        // strip — `create_file` loads the flag after its openat, so this ordering (store, then
2074        // restore; openat, then load) leaves no interleaving where the openat sees the restored
2075        // ACL but the load sees `false`
2076        self.children_may_inherit
2077            .store(true, std::sync::atomic::Ordering::SeqCst);
2078        // Taking the mutex is what serializes this restore against an in-flight guarded write: a
2079        // write mid-syscall holds it, so the restore must wait and then deliberately land OVER
2080        // it. But WAITING here would block whatever thread runs this destructor — on the
2081        // cancellation paths that is an EXECUTOR thread (`--fail-early` dropping tracker state, a
2082        // watchdog dropping the operation), and the wait is bounded only by the write's
2083        // `fsetxattr`, which on dead network storage is unbounded. So: uncontended (the ordinary
2084        // case — no write in flight) restores inline; contended detaches the SAME serialized
2085        // wait-then-restore to its own thread. The `Arc`s keep the state and fd alive for it, and
2086        // process exit may abandon the thread exactly as it abandons the stalled write itself.
2087        let state = match self.state.try_lock() {
2088            Ok(guard) => guard,
2089            Err(std::sync::TryLockError::WouldBlock) => {
2090                let state = Arc::clone(&self.state);
2091                let fd = Arc::clone(&self.fd);
2092                let flag_note = "detached (a guarded write held the rollback mutex)";
2093                std::thread::spawn(move || {
2094                    // a poisoned mutex is unreachable under panic = "abort"; fail toward doing
2095                    // the restore anyway rather than silently dropping it
2096                    let guard = state
2097                        .lock()
2098                        .unwrap_or_else(|poisoned| poisoned.into_inner());
2099                    rollback_default_acl(guard, &fd, flag_note);
2100                });
2101                return;
2102            }
2103            // unreachable under panic = "abort"; restore anyway rather than skip
2104            Err(std::sync::TryLockError::Poisoned(poisoned)) => poisoned.into_inner(),
2105        };
2106        rollback_default_acl(state, &self.fd, "inline");
2107    }
2108}
2109
2110/// The rollback itself, run with the guard's mutex HELD (see `DefaultAclGuard`): flips the state
2111/// to `Disarmed` and puts the directory's original default ACL back (or removes what a partial
2112/// finalize installed, when there was none). Split from `ReusedDirLock::drop` so the contended
2113/// path can run it on a detached thread with the same serialization.
2114fn rollback_default_acl(
2115    mut state: std::sync::MutexGuard<'_, DefaultAclGuard>,
2116    fd: &DirectoryDescriptor,
2117    how: &str,
2118) {
2119    {
2120        let DefaultAclGuard::Armed { original } =
2121            std::mem::replace(&mut *state, DefaultAclGuard::Disarmed)
2122        else {
2123            return;
2124        };
2125        let raw = fd.as_raw_fd();
2126        let _ = how;
2127        // name the directory rather than the descriptor: a mass abort restores many at once, and
2128        // "fd 47" tells an operator nothing about which tree to repair. Best-effort — a fd whose
2129        // target is gone falls back to the raw number rather than failing the restore.
2130        let path = std::fs::read_link(format!("/proc/self/fd/{raw}"))
2131            .map_or_else(|_| format!("<fd {raw}>"), |p| p.display().to_string());
2132        let restore = apply_one_acl(raw, ACL_DEFAULT_XATTR, original.as_deref());
2133        match (restore, &original) {
2134            (Ok(()), Some(blob)) => tracing::debug!(
2135                "restored the default ACL of reused destination directory {} after an aborted \
2136                 copy ({} bytes)",
2137                path,
2138                blob.len(),
2139            ),
2140            (Ok(()), None) => tracing::debug!(
2141                "ensured reused destination directory {} carries no default ACL after an aborted \
2142                 copy (it had none before it)",
2143                path,
2144            ),
2145            (Err(error), Some(blob)) => tracing::warn!(
2146                "could not restore the default ACL of reused destination directory {} after an \
2147                 aborted copy: {:#}. It is left with NO default ACL; it had {} bytes ({:02x?}), \
2148                 which must be re-applied by hand to restore what entries created beneath it \
2149                 inherit.",
2150                path,
2151                &error,
2152                blob.len(),
2153                blob,
2154            ),
2155            (Err(error), None) => tracing::warn!(
2156                "could not remove a partially-applied default ACL from reused destination \
2157                 directory {} after an aborted copy: {:#}. The directory had NO default ACL \
2158                 before the copy; whatever the aborted finalize installed remains and must be \
2159                 removed by hand.",
2160                path,
2161                &error,
2162            ),
2163        }
2164    }
2165}
2166
2167/// Lock down a REUSED destination directory under strict operand resolution, returning what finalize
2168/// must restore — `Some` when locked, `None` (a pure no-op) when strict mode is off.
2169///
2170/// `dir` is the freshly `open_dir`'d handle to the reused directory; `handle` is the `O_PATH`
2171/// classify [`Handle`] taken for the same entry BEFORE the open (still held, pinning the classified
2172/// inode). While strict operand resolution is armed the lockdown:
2173///
2174/// 1. captures `handle`'s original `(uid, gid)` as the restore owner;
2175/// 2. [`Dir::verify_same_inode`] — confirms `dir` is still that exact inode, failing closed
2176///    (`ESTALE`) on a classify→open swap;
2177/// 3. [`Dir::secure_as_copier`] — takes ownership as the copier then restricts to `0o700`, so no
2178///    child is written while the directory is world-readable/writable and the prior owner cannot
2179///    re-widen it mid-copy;
2180/// 4. [`read_acls_fd`] — snapshots the DEFAULT ACL, and
2181/// 5. removes it, so nothing created during the copy inherits it.
2182///
2183/// Steps 4 and 5 both run AFTER the takeover, and both for the same reason: only an owner (or a
2184/// `CAP_FOWNER` copier) may write these attributes, so a strip issued before step 3 would leave the
2185/// prior owner free to put the default ACL straight back, and a snapshot read before it could be
2186/// raced by that same owner. `chmod` does not touch a default ACL (verified), so nothing about the
2187/// recorded value depends on reading it first.
2188///
2189/// # Why only the DEFAULT ACL
2190///
2191/// The *access* ACL is deliberately left alone, and this is a narrowing of what an earlier version
2192/// did. It buys no containment: step 3's `chmod` rewrites `ACL_MASK` from the new group bits, so at
2193/// `0o700` the mask is `---` and every named `user:`/`group:` entry — and the owning group — grants
2194/// nothing, while `OTHER` is `---` too. Only the copier, who now owns the directory, has any access
2195/// at all (verified). And it needs no restoring, because finalize resolves it either way: with
2196/// `d:acl` the source's ACL is set or cleared over it, and without `d:acl` the finalize `chmod`
2197/// re-derives its mask from the source's mode — which is exactly what an unhardened copy's single
2198/// `chmod` does to a pre-existing ACL, so the end state is identical either way.
2199///
2200/// Leaving it alone therefore costs nothing and means an aborted copy can destroy at most the
2201/// default ACL rather than both. (A freshly CREATED directory is the opposite case and still strips
2202/// both — see [`Dir::make_dir`]: what it inherited is not its own, and with `d:acl` off nothing at
2203/// finalize would remove an inherited access ACL, so the finalize `chmod` would make it effective.)
2204///
2205/// Distinct destination paths can alias the same directory inode and create overlapping lockdowns:
2206/// one guard can restore the ACL while another copy is still active. `--require-toctou-safe`
2207/// refuses byte-equal duplicate destinations up front and serializes strict multi-source copies;
2208/// filesystem-level aliasing (casefold, bind mount) is not detected. The remote tracker rejects
2209/// duplicate directory paths but does not coordinate distinct paths by inode identity.
2210///
2211/// Everything the lockdown changed is put back at finalize by [`set_reused_dir_metadata_fd`] (the
2212/// owner component-wise, so no transient window hands the directory back to a hostile prior owner)
2213/// along with the source mode, so a successful copy leaves the directory byte-identical to a copy
2214/// without this hardening. A recheck mismatch, an `fchown`/`fchmod` `EPERM` (non-owner,
2215/// non-privileged copier), or an ACL snapshot/strip that fails propagates as `Err`; callers fail
2216/// closed and skip descent, so no child is written into an unsecured directory. Failing closed on
2217/// the snapshot is why it is read before the strip: removing an ACL we could not record would
2218/// permanently destroy the destination directory's own. This is the single lockdown used by BOTH the
2219/// local (`copy`/`link`) and remote (`rcpd`) reuse sites.
2220pub async fn lockdown_reused_dir(
2221    dir: &Dir,
2222    handle: &Handle,
2223) -> std::io::Result<Option<ReusedDirLock>> {
2224    if !strict_operand_resolution() {
2225        return Ok(None);
2226    }
2227    use crate::preserve::Metadata as _;
2228    use std::os::unix::fs::PermissionsExt as _;
2229    let orig_meta = handle.meta();
2230    let restore_owner = (orig_meta.uid(), orig_meta.gid());
2231    dir.verify_same_inode(handle).await?;
2232    // Restrict to 0o700 (owner-only) for the copy's duration, PRESERVING the setgid bit if the reused
2233    // directory had it (0o700 already denies all group/other access, so keeping setgid costs nothing
2234    // security-wise). Unlike the source mode applied at finalize, this INTERIM setgid bit governs the
2235    // group that every child created during the copy inherits — and finalization cannot repair those
2236    // children's GIDs under `preserve_none`. So a setgid directory must be locked down with BOTH its
2237    // gid value and its S_ISGID bit intact: `secure_as_copier` (given the classified gid) resets the
2238    // gid if a prior owner raced a `chgrp`, and re-stats to fail closed if `chmod` cleared S_ISGID (a
2239    // non-privileged copier not in the directory's group, lacking `CAP_FSETID`) or if the filesystem
2240    // did not honor the takeover at all. Root has `CAP_FSETID`, keeps the bit, and never trips this.
2241    let want_setgid = orig_meta.permissions().mode() & 0o2000 != 0;
2242    let interim_mode = if want_setgid { 0o2700 } else { 0o700 };
2243    dir.secure_as_copier(interim_mode, orig_meta.uid(), orig_meta.gid())
2244        .await?;
2245    // snapshot the default ACL, now that the directory is ours and the prior owner can no longer
2246    // race the read (step 4). Mode-neutral. `read_acls_fd` also reads the access ACL when one is
2247    // present, which is one wasted `fgetxattr` on a reused directory that has one — not worth a
2248    // second read path for. Nothing is destroyed yet, so a cancellation here loses nothing.
2249    let original = read_acls_fd(dir.fd.as_fd(), dir.side, true).await?.default;
2250    let needs_strip = original.is_some();
2251    // ARM THE GUARD BEFORE DESTROYING ANYTHING (step 5). The snapshot is the only copy of these
2252    // bytes once the removal lands, so it must already be inside a value whose `Drop` puts it back
2253    // before the removal is issued — otherwise a task cancelled between the two loses it as a bare
2254    // `Option<Vec<u8>>` with no destructor. Armed even when the directory has no default ACL: the
2255    // rollback then means "keep it that way" — removing whatever a partial finalize installs.
2256    let lock = ReusedDirLock {
2257        restore_owner,
2258        state: Arc::new(std::sync::Mutex::new(DefaultAclGuard::Armed { original })),
2259        fd: Arc::clone(&dir.fd),
2260        children_may_inherit: Arc::clone(&dir.children_may_inherit),
2261    };
2262    if needs_strip {
2263        let raw = dir.fd.as_raw_fd();
2264        // The removal is issued SYNCHRONOUSLY, inside the gate rather than on the blocking pool,
2265        // and this is load-bearing rather than an optimization. the shared blocking boundary can
2266        // reclaim user work before a worker takes it, but a closure cannot be stopped after that
2267        // handoff, so an `.await` on it is a cancellation point at which the `fremovexattr` may
2268        // still run — the exact hazard the arming above closes. Running it in-line means there is
2269        // no cancellation point between arming and destroying at all: polling this future runs the
2270        // syscall to completion.
2271        //
2272        // Arming first while KEEPING `spawn_blocking` would be strictly worse than either: a pool
2273        // thread's `fremovexattr` could land after this task's `Drop` restore and silently undo it.
2274        //
2275        // The cost is one `fremovexattr` (microseconds) on an async worker, the same call `Drop`
2276        // already makes, and only for a reused directory that actually has a default ACL. The gate
2277        // still applies — `run_metadata_probed` takes the ops token and cwnd permit and feeds the
2278        // latency probe exactly as `set_or_remove_acl_fd` would.
2279        crate::walk::run_metadata_probed(dir.side, congestion::MetadataOp::Chmod, async {
2280            apply_one_acl(raw, ACL_DEFAULT_XATTR, None)
2281        })
2282        .await?;
2283        // NB: on `Err` the guard is still armed and `Drop` re-writes the snapshot. `fremovexattr`
2284        // is atomic, so the ACL is either gone (the restore puts it back) or never left (the
2285        // restore is a no-op) — never a partial state.
2286    }
2287    // the directory now provably has no default ACL (either it never had one, or the strip above
2288    // succeeded), so files created in it during the copy cannot inherit — `create_file` need not
2289    // pay the ambient-parent strip here
2290    dir.mark_children_cannot_inherit();
2291    Ok(Some(lock))
2292}
2293
2294// ── POSIX ACLs ──────────────────────────────────────────────────────────────────
2295//
2296// POSIX.1e ACLs live in two extended attributes and are read and written here as
2297// OPAQUE kernel blobs: `system.posix_acl_access` (on any inode) and
2298// `system.posix_acl_default` (directories only, governing what children inherit).
2299// Using the raw xattrs rather than libacl keeps this to plain fd syscalls with no
2300// new dependency, and the on-disk format is defined little-endian, so the bytes
2301// are portable verbatim. The blobs are never interpreted: rcp carries what the
2302// source kernel produced and lets the destination kernel validate it on
2303// `fsetxattr`.
2304
2305/// The access ACL: the entry's own permissions. Present on any inode kind.
2306const ACL_ACCESS_XATTR: &CStr = c"system.posix_acl_access";
2307
2308/// The default ACL: what a directory's freshly created CHILDREN inherit. Directories only, and
2309/// mode-neutral — setting or clearing it never moves the directory's own mode.
2310const ACL_DEFAULT_XATTR: &CStr = c"system.posix_acl_default";
2311
2312/// A source entry's POSIX.1e ACLs, as opaque kernel bytes.
2313///
2314/// `None` means the source has no such ACL — which a destination applier reproduces by REMOVING
2315/// the attribute, not by leaving it alone. A destination directory's default ACL is inherited by
2316/// every child created beneath it, so "do nothing when the source has no ACL" hands the copy
2317/// permissions the source never granted. See [`apply_acls_fd`].
2318#[derive(Clone, Debug, Default, PartialEq, Eq)]
2319pub struct Acls {
2320    /// `system.posix_acl_access`.
2321    pub access: Option<Vec<u8>>,
2322    /// `system.posix_acl_default`; only ever read or applied for a directory.
2323    pub default: Option<Vec<u8>>,
2324}
2325
2326/// Read an entry's POSIX ACLs through an fd it is already open on.
2327///
2328/// `want_default` is `true` for directories only — files have no default ACL, so asking for one
2329/// would spend a syscall that can only miss.
2330///
2331/// `flistxattr` runs FIRST and an `fgetxattr` is issued only for a name actually present. There is
2332/// no bit in `stat` saying an entry has an ACL, so this probe is what ACL preservation costs per
2333/// entry, and the shape is chosen to make the common case cheap: measured on ext4, a `getxattr`
2334/// that misses costs ~1057ns against ~591ns for the whole `listxattr`, and missing is the
2335/// overwhelming majority. Each syscall is gated through the module's `run_metadata_probed_blocking`
2336/// as `MetadataOp::Stat`, like every other metadata read here — an ACL probe that bypassed the
2337/// throttle would be the one metadata operation in rcp that does.
2338///
2339/// A filesystem that cannot hold ACLs (`EOPNOTSUPP`) and an entry that simply has none (`ENODATA`)
2340/// both yield `None`: neither has an ACL to preserve.
2341pub async fn read_acls_fd(
2342    fd: BorrowedFd<'_>,
2343    side: congestion::Side,
2344    want_default: bool,
2345) -> std::io::Result<Acls> {
2346    // dup once and move the owner through the (up to three) gated syscalls. Each blocking
2347    // closure owns its descriptor until its returned output is consumed or dropped.
2348    let owned = fd.try_clone_to_owned()?;
2349    read_acls_owned(owned, side, want_default)
2350        .await
2351        .map(|(_, acls)| acls)
2352}
2353
2354/// Read ACLs without duplicating the descriptor, returning the same owner on success.
2355///
2356/// Errors and cancellation drop the owner through the existing blocking-job lifetime rules.
2357pub(crate) async fn read_acls_owned<F: AsRawFd + Send + 'static>(
2358    owned: F,
2359    side: congestion::Side,
2360    want_default: bool,
2361) -> std::io::Result<(F, Acls)> {
2362    let (owned, names) =
2363        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
2364            #[cfg(test)]
2365            let _visit = resource_tests::gate_opened_descriptor(owned.as_raw_fd())?;
2366            let names = flistxattr_names(owned.as_raw_fd())?;
2367            Ok((owned, names))
2368        })
2369        .await?;
2370    let (owned, access) = if names_contain(&names, ACL_ACCESS_XATTR) {
2371        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
2372            let access = fgetxattr_blob(owned.as_raw_fd(), ACL_ACCESS_XATTR)?;
2373            Ok((owned, access))
2374        })
2375        .await?
2376    } else {
2377        (owned, None)
2378    };
2379    let (owned, default) = if want_default && names_contain(&names, ACL_DEFAULT_XATTR) {
2380        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
2381            let default = fgetxattr_blob(owned.as_raw_fd(), ACL_DEFAULT_XATTR)?;
2382            Ok((owned, default))
2383        })
2384        .await?
2385    } else {
2386        (owned, None)
2387    };
2388    Ok((owned, Acls { access, default }))
2389}
2390
2391/// Apply `acls` to a destination entry through an fd it is already open on, SETTING each attribute
2392/// the source had and REMOVING each one it did not.
2393///
2394/// Clearing is not an optimization to skip: a destination directory's default ACL is inherited by
2395/// every child created beneath it, including children rcp itself creates, so a source with no ACL
2396/// needs an explicit removal or the copy silently ends up more permissive than what it copied.
2397///
2398/// The access ACL is applied LAST because it is the step that WIDENS the destination — see
2399/// [`set_file_metadata_owned`]. The default ACL is mode-neutral, so it goes first and constrains
2400/// nothing.
2401///
2402/// Gated as `MetadataOp::Chmod`, the bucket for single-inode permission writes.
2403pub async fn apply_acls_fd(
2404    fd: BorrowedFd<'_>,
2405    side: congestion::Side,
2406    acls: &Acls,
2407    want_default: bool,
2408) -> std::io::Result<()> {
2409    if want_default {
2410        set_or_remove_acl_fd(fd, side, ACL_DEFAULT_XATTR, acls.default.clone()).await?;
2411    }
2412    set_or_remove_acl_fd(fd, side, ACL_ACCESS_XATTR, acls.access.clone()).await
2413}
2414
2415/// Install `blob` as `name` on `fd`, or REMOVE `name` when `blob` is `None`, through the module's
2416/// metadata gate.
2417///
2418/// The async half of `apply_one_acl`, at single-attribute granularity: [`apply_acls_fd`] (its
2419/// one caller) resolves the two ACLs one at a time through it. A LOCKED reused directory's
2420/// default ACL must NOT come through here — that write has to serialize against the lockdown
2421/// guard's rollback; `ReusedDirLock::write_default_acl_guarded` is the only correct writer.
2422///
2423/// Gated as `MetadataOp::Chmod`, the bucket for single-inode permission writes.
2424async fn set_or_remove_acl_fd(
2425    fd: BorrowedFd<'_>,
2426    side: congestion::Side,
2427    name: &'static CStr,
2428    blob: Option<Vec<u8>>,
2429) -> std::io::Result<()> {
2430    set_or_remove_acl_owned(fd.try_clone_to_owned()?, side, name, blob)
2431        .await
2432        .map(drop)
2433}
2434
2435async fn set_or_remove_acl_owned(
2436    owned: OwnedFd,
2437    side: congestion::Side,
2438    name: &'static CStr,
2439    blob: Option<Vec<u8>>,
2440) -> std::io::Result<OwnedFd> {
2441    run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
2442        apply_one_acl(owned.as_raw_fd(), name, blob.as_deref())?;
2443        Ok(owned)
2444    })
2445    .await
2446}
2447
2448/// Resolve the ACL payload an applier should install: `None` when ACL preservation is off for this
2449/// entry kind, `Some(acls)` when it is on and the caller carried the source's ACLs.
2450///
2451/// The third combination — preservation on, but the call site did not read the source's ACLs — is
2452/// an ERROR rather than either silent alternative. Treating it as "leave the destination alone"
2453/// keeps whatever the destination inherited, and treating it as an empty [`Acls`] CLEARS what the
2454/// source had; both produce a destination whose ACLs did not come from its source, which is exactly
2455/// the quiet lie ACL preservation exists to remove. Consolidated here so a reader verifies it once
2456/// rather than at each applier.
2457///
2458/// No caller reaches that arm today: the local copy reads the source's ACLs from the fd it is about
2459/// to copy, and the remote destination gets them from the wire header. It is kept as a fail-closed
2460/// backstop for a future applier that forgets to — which would otherwise be silent.
2461fn acls_to_apply(want: bool, acls: Option<&Acls>) -> std::io::Result<Option<&Acls>> {
2462    match (want, acls) {
2463        (false, _) => Ok(None),
2464        (true, Some(acls)) => Ok(Some(acls)),
2465        (true, None) => Err(std::io::Error::new(
2466            std::io::ErrorKind::Unsupported,
2467            "ACL preservation was requested but this copy path does not carry the source's ACLs",
2468        )),
2469    }
2470}
2471
2472/// The `listxattr` family's two-step protocol, shared by the fd and path forms: try a stack
2473/// buffer, and only on `ERANGE` ask the kernel for the current size and retry on the heap.
2474///
2475/// `call(buf, len)` issues one syscall; `call(null, 0)` asks for the size without writing.
2476///
2477/// An `EOPNOTSUPP` filesystem yields an empty list: it holds no xattrs, so it holds no ACL either.
2478fn listxattr_retry(
2479    mut call: impl FnMut(*mut libc::c_char, usize) -> isize,
2480) -> std::io::Result<Vec<u8>> {
2481    // a name list is well under 256 bytes even with `security.selinux` and a couple of user
2482    // attributes present; the ERANGE path below covers anything larger.
2483    let mut buf = [0u8; 256];
2484    let n = call(buf.as_mut_ptr().cast(), buf.len());
2485    if n >= 0 {
2486        return Ok(buf[..n as usize].to_vec());
2487    }
2488    let err = std::io::Error::last_os_error();
2489    match err.raw_os_error() {
2490        Some(libc::EOPNOTSUPP) => Ok(Vec::new()),
2491        Some(libc::ERANGE) => {
2492            let size = call(std::ptr::null_mut(), 0);
2493            if size < 0 {
2494                return Err(std::io::Error::last_os_error());
2495            }
2496            let mut heap = vec![0u8; size as usize];
2497            if heap.is_empty() {
2498                return Ok(heap);
2499            }
2500            let n = call(heap.as_mut_ptr().cast(), heap.len());
2501            if n < 0 {
2502                // a concurrent writer grew the list between the two calls; report it rather than
2503                // looping against a live competing writer.
2504                return Err(std::io::Error::last_os_error());
2505            }
2506            heap.truncate(n as usize);
2507            Ok(heap)
2508        }
2509        _ => Err(err),
2510    }
2511}
2512
2513/// `flistxattr`, returning the raw NUL-separated name list the kernel produced.
2514fn flistxattr_names(fd: RawFd) -> std::io::Result<Vec<u8>> {
2515    // SAFETY: `fd` is a valid open descriptor for the duration of the call and the kernel writes
2516    // at most `len` bytes into `buf` (or nothing at all when `buf` is null and `len` is 0).
2517    listxattr_retry(|buf, len| unsafe { libc::flistxattr(fd, buf, len) })
2518}
2519
2520/// `listxattr` on a PATH, following symlinks — used only for the `/proc/self/fd/N` magic symlink,
2521/// which must be dereferenced to reach the inode an `O_PATH` handle pins.
2522///
2523/// See [`has_acl_via_proc_fd`] for why the probe cannot go through the handle's fd directly.
2524fn listxattr_names_at_path(path: &CStr) -> std::io::Result<Vec<u8>> {
2525    // SAFETY: `path` is a NUL-terminated C string that outlives the call and the kernel writes at
2526    // most `len` bytes into `buf` (or nothing at all when `buf` is null and `len` is 0).
2527    // the only caller passes /proc/self/fd/N for an fd it already holds, so this resolves to that
2528    // PINNED inode: inode-exact, not a by-name lookup a swap could redirect.
2529    let probe = |buf, len| {
2530        unsafe { libc::listxattr(path.as_ptr(), buf, len) } // rcp-toctou-allow: /proc/self/fd magic symlink to a held fd
2531    };
2532    listxattr_retry(probe)
2533}
2534
2535/// Whether the NUL-separated `list` produced by [`flistxattr_names`] contains `name`.
2536fn names_contain(list: &[u8], name: &CStr) -> bool {
2537    list.split(|byte| *byte == 0).any(|n| n == name.to_bytes())
2538}
2539
2540/// `fgetxattr` one attribute, retrying on a larger buffer if the stack one did not fit.
2541///
2542/// `Ok(None)` for both "the entry has no such attribute" (`ENODATA`) and "this filesystem cannot
2543/// hold one" (`EOPNOTSUPP`) — neither has an ACL to preserve.
2544fn fgetxattr_blob(fd: RawFd, name: &CStr) -> std::io::Result<Option<Vec<u8>>> {
2545    // a POSIX.1e ACL blob is `4 + 8n` bytes, so 512 holds 63 entries — every realistic ACL in a
2546    // single syscall.
2547    let mut buf = [0u8; 512];
2548    // SAFETY: `fd` is a valid open descriptor for the duration of the call, `name` is a
2549    // NUL-terminated C string, and the kernel writes at most `buf.len()` bytes into `buf`.
2550    let n = unsafe { libc::fgetxattr(fd, name.as_ptr(), buf.as_mut_ptr().cast(), buf.len()) };
2551    if n >= 0 {
2552        return Ok(Some(buf[..n as usize].to_vec()));
2553    }
2554    let err = std::io::Error::last_os_error();
2555    match err.raw_os_error() {
2556        Some(libc::ENODATA | libc::EOPNOTSUPP) => Ok(None),
2557        Some(libc::ERANGE) => {
2558            // SAFETY: as above; a null buffer with size 0 asks the kernel for the current size
2559            // without writing anything.
2560            let size = unsafe { libc::fgetxattr(fd, name.as_ptr(), std::ptr::null_mut(), 0) };
2561            if size < 0 {
2562                return Err(std::io::Error::last_os_error());
2563            }
2564            let mut heap = vec![0u8; size as usize];
2565            if heap.is_empty() {
2566                return Ok(Some(heap));
2567            }
2568            // SAFETY: as above; `heap` has `len()` writable bytes.
2569            let n =
2570                unsafe { libc::fgetxattr(fd, name.as_ptr(), heap.as_mut_ptr().cast(), heap.len()) };
2571            if n < 0 {
2572                // a concurrent writer grew the attribute between the two calls; report it rather
2573                // than looping against a live competing writer.
2574                return Err(std::io::Error::last_os_error());
2575            }
2576            heap.truncate(n as usize);
2577            Ok(Some(heap))
2578        }
2579        _ => Err(err),
2580    }
2581}
2582
2583/// Install `blob` as `name`, or REMOVE `name` when `blob` is `None`.
2584///
2585/// The error handling is asymmetric, and the asymmetry is the point:
2586///
2587/// - A failing SET fails the entry, `EOPNOTSUPP` included. A destination that cannot hold the
2588///   source's ACL ends up MORE PERMISSIVE than its source — a named entry narrower than `other`
2589///   acts as a deny in effect, so dropping it grants exactly what the source withheld. Dropping it
2590///   quietly is the bug this feature exists to remove; a destination filesystem without ACL support
2591///   is a failure, not a shrug.
2592/// - A failing REMOVE with `ENODATA` or `EOPNOTSUPP` is SUCCESS. Both say there is no ACL on the
2593///   destination to clear, so nothing can have widened — the post-condition the caller asked for
2594///   already holds.
2595fn apply_one_acl(fd: RawFd, name: &CStr, blob: Option<&[u8]>) -> std::io::Result<()> {
2596    let Some(blob) = blob else {
2597        // SAFETY: `fd` is a valid open descriptor for the duration of the call and `name` is a
2598        // NUL-terminated C string.
2599        if unsafe { libc::fremovexattr(fd, name.as_ptr()) } == 0 {
2600            return Ok(());
2601        }
2602        let err = std::io::Error::last_os_error();
2603        return match err.raw_os_error() {
2604            Some(libc::ENODATA | libc::EOPNOTSUPP) => Ok(()),
2605            _ => Err(err),
2606        };
2607    };
2608    // SAFETY: as above; `blob` points at `blob.len()` readable bytes. Flags 0 means "create or
2609    // replace", which is what preserving a source's ACL onto a fresh destination needs.
2610    let rc = unsafe {
2611        libc::fsetxattr(
2612            fd,
2613            name.as_ptr(),
2614            blob.as_ptr().cast(),
2615            blob.len(),
2616            0, // neither XATTR_CREATE nor XATTR_REPLACE: set it whatever the destination holds
2617        )
2618    };
2619    if rc == 0 {
2620        Ok(())
2621    } else {
2622        Err(std::io::Error::last_os_error())
2623    }
2624}
2625
2626// ── The source-root ACL warning ─────────────────────────────────────────────────
2627//
2628// `all` does not preserve ACLs, and a user who asked for it and does not know
2629// that gets a silently wider destination. Telling them costs one `listxattr` on
2630// the SOURCE ROOT per run — a constant, not a per-entry probe, so it is
2631// affordable on the very path whose whole point is that it pays nothing per
2632// entry.
2633//
2634// armed by ASKING (`RootAclNotice`), not by an ACL merely existing: a run left at
2635// the shipped default already drops uid, gid, timestamps and the special mode bits
2636// without a word, so it is not the place to be loud about one more attribute it
2637// also does not carry — and it pays nothing to find that out.
2638//
2639// It is a HEURISTIC and must be read as one: a root without an ACL says nothing
2640// about its children. The alternative — probing enough entries to be sure — IS
2641// the per-entry cost that made `acl` opt-in in the first place.
2642
2643/// Guards the probe so it runs at most once per process, no matter how many source operands (or
2644/// `--dereference` recursions into `copy`) reach a call site.
2645static ROOT_ACL_PROBED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
2646
2647/// What a run's settings say about the source-root ACL notice: whether it is wanted at all, and
2648/// which kinds are already covered.
2649///
2650/// The single home of the rule, so the two entry points below, the cheap pre-check a caller uses to
2651/// skip work, and the remote source all decide the same way.
2652#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2653pub struct RootAclNotice {
2654    /// Whether this run asked for the kind of fidelity a dropped ACL would undermine, normally
2655    /// [`crate::preserve::Settings::requests_preservation`].
2656    ///
2657    /// `false` silences the notice outright — probe included, so a run that did not ask pays
2658    /// nothing at all. A copy left at the shipped default already drops uid, gid, timestamps and
2659    /// the setuid/setgid/sticky bits without a word; singling ACLs out there would be advice about
2660    /// permission completeness nobody claimed. It is also independent of
2661    /// [`strict_operand_resolution`], which arms the notice on its own: `--require-toctou-safe` is
2662    /// a request about permissions whatever the preserve settings say, and it gets its own wording.
2663    pub wanted: bool,
2664    /// Whether a FILE root's ACL is already safe — normally the `acl` preserve setting for files,
2665    /// but `true` also covers a kind whose ACL cannot be lost by construction (`rlink` passes it
2666    /// for files without `--update`, which share the source inode through the hard link).
2667    pub file_acl_preserved: bool,
2668    /// Whether a DIRECTORY root's ACLs (access and default) are already safe.
2669    pub dir_acl_preserved: bool,
2670}
2671
2672impl RootAclNotice {
2673    /// The notice a copy governed by `preserve` wants.
2674    #[must_use]
2675    pub fn for_preserve(preserve: &crate::preserve::Settings) -> Self {
2676        Self {
2677            wanted: preserve.requests_preservation(),
2678            file_acl_preserved: preserve.file.acl,
2679            dir_acl_preserved: preserve.dir.acl,
2680        }
2681    }
2682
2683    /// Whether a root of `kind` could produce a notice: the run wants one and that kind's ACLs are
2684    /// not already being carried across.
2685    ///
2686    /// Symlinks and special files answer `false` without consulting anything — the kernel has no
2687    /// symlink ACL (the settings parser rejects `l:acl`), and a special file is not copied as an
2688    /// object whose permissions rcp reproduces.
2689    ///
2690    /// Reads the process-global strict flag, so it must not be called before
2691    /// [`enable_strict_operand_resolution`] has run — every call site is well past the linter that
2692    /// sets it.
2693    fn could_warn_for(self, kind: EntryKind) -> bool {
2694        self.could_warn_for_strict(kind, strict_operand_resolution())
2695    }
2696
2697    /// [`could_warn_for`](Self::could_warn_for) with the strict flag passed in rather than read, so
2698    /// the rule itself can be pinned without a process-global to arrange.
2699    fn could_warn_for_strict(self, kind: EntryKind, strict: bool) -> bool {
2700        (self.wanted || strict)
2701            && match kind {
2702                EntryKind::File => !self.file_acl_preserved,
2703                EntryKind::Dir => !self.dir_acl_preserved,
2704                EntryKind::Symlink | EntryKind::Special => false,
2705            }
2706    }
2707
2708    /// Whether ANY root could produce a notice — [`could_warn_for`](Self::could_warn_for) with the
2709    /// root's kind not yet known, which is the only thing a caller holding just a path can ask.
2710    fn could_warn(self) -> bool {
2711        self.could_warn_for(EntryKind::File) || self.could_warn_for(EntryKind::Dir)
2712    }
2713}
2714
2715/// Whether the inode an `O_PATH` [`Handle`] pins carries either POSIX ACL, probed through its
2716/// `/proc/self/fd/N` magic symlink.
2717///
2718/// The `/proc` detour is not decoration: `flistxattr` on an `O_PATH` descriptor fails with `EBADF`,
2719/// so the classify handle — the one fd every engine already holds for its root, whatever the entry
2720/// kind — cannot answer the probe directly. Resolving the magic symlink reaches the pinned inode
2721/// while staying inode-exact, exactly as [`chmod_via_proc_fd`] and [`stat_meta_via_proc_fd`] do,
2722/// and it needs neither read permission on the entry nor a second `openat`. Requires `/proc`
2723/// mounted (same precondition as [`chmod_via_proc_fd`]); a caller treats failure as "don't know"
2724/// rather than as an error, since this only ever produces a warning.
2725///
2726/// Gated as `MetadataOp::Stat` like every other metadata read here.
2727async fn has_acl_via_proc_fd(handle: &Handle, side: congestion::Side) -> std::io::Result<bool> {
2728    // clone the O_PATH fd into an owned fd the blocking closure can hold, keeping the pinned inode
2729    // alive for the syscall's full duration even if the originating Handle is dropped.
2730    let owned = handle.as_fd().try_clone_to_owned()?;
2731    let names = run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
2732        let proc_path = std::ffi::CString::new(format!("/proc/self/fd/{}", owned.as_raw_fd()))
2733            .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err))?;
2734        listxattr_names_at_path(&proc_path)
2735    })
2736    .await?;
2737    Ok(names_contain(&names, ACL_ACCESS_XATTR) || names_contain(&names, ACL_DEFAULT_XATTR))
2738}
2739
2740/// Whether it is worth *reaching* for the probe: something could still be warned about, and the
2741/// one per-process run has not been taken yet.
2742///
2743/// Advisory only — it claims nothing, so the probe itself still goes through
2744/// [`warn_if_root_acl_unpreserved`] / [`warn_if_root_acl_unpreserved_at`], which claim internally.
2745/// Its job is to let a caller skip work it would otherwise do just to reach the probe: the two
2746/// entry points below use it to skip an `openat`, and `rcp`'s remote `-L` source uses it to skip
2747/// resolving and opening the root's parent, which it does not otherwise need.
2748#[must_use]
2749pub fn root_acl_probe_worth_reaching(notice: RootAclNotice) -> bool {
2750    if !notice.could_warn() {
2751        return false;
2752    }
2753    !ROOT_ACL_PROBED.load(std::sync::atomic::Ordering::Relaxed)
2754}
2755
2756/// Claim the single per-process probe run, returning `false` if someone already has it.
2757///
2758/// Called as LATE as possible — after the root's kind is known and after the per-kind settings
2759/// check — so that a root which cannot produce a warning does not consume the budget and silence
2760/// a later operand that could have. Two operands racing here can both pass
2761/// [`root_acl_probe_worth_reaching`] and both open their root; only one wins the swap, and the
2762/// loser has wasted one `openat`. Which one wins is therefore unspecified for concurrent operands;
2763/// see the note on [`warn_if_root_acl_unpreserved`].
2764fn claim_root_acl_probe() -> bool {
2765    !ROOT_ACL_PROBED.swap(true, std::sync::atomic::Ordering::Relaxed)
2766}
2767
2768/// Probe `handle` and warn if it carries an ACL this copy will not carry across. The shared body
2769/// of the two entry points below, so the message and the kind rule live in one place.
2770///
2771/// The root's kind is the LAST thing the rule needs, and the only one a caller cannot supply, so
2772/// this is where [`RootAclNotice::could_warn_for`] is asked authoritatively — a symlink or special
2773/// root, and a kind whose ACLs are already carried across, are turned away without a syscall.
2774/// Failure to probe is logged at `debug!` and nothing else: this produces advice, so a missing
2775/// `/proc` or an exotic filesystem must not turn into a copy error.
2776async fn warn_root_acl(handle: &Handle, src_root: &Path, notice: RootAclNotice) {
2777    if !notice.could_warn_for(handle.kind()) {
2778        return;
2779    }
2780    // claim LAST. A root that could not have warned returns above without spending the one
2781    // per-process run, so it cannot silence a later operand that had something to say.
2782    if !claim_root_acl_probe() {
2783        return;
2784    }
2785    // Both arms go to `crate::NOTICE_TARGET`, which the verbose filter renders at every verbosity
2786    // INCLUDING the default: a notice about `all` silently dropping ACLs is useless if only a user
2787    // who already passed `-v` — and therefore already suspects something — can see it.
2788    match has_acl_via_proc_fd(handle, congestion::Side::Source).await {
2789        Ok(false) => {}
2790        Ok(true) if strict_operand_resolution() => tracing::warn!(
2791            target: crate::NOTICE_TARGET,
2792            "Source root {src_root:?} carries a POSIX ACL that this copy will NOT preserve \
2793             (`--preserve-settings` does not request `acl`). --require-toctou-safe stops the \
2794             DESTINATION tree's ACLs from being inherited, but it does not carry the SOURCE's \
2795             across, so the copy can still end up more permissive than what it copied. Use \
2796             `--preserve-settings=all+acl`. Only the root was checked - entries beneath it may \
2797             carry ACLs this says nothing about."
2798        ),
2799        Ok(true) => tracing::warn!(
2800            target: crate::NOTICE_TARGET,
2801            "Source root {src_root:?} carries a POSIX ACL that this copy will NOT preserve \
2802             (`--preserve-settings` does not request `acl`), so the destination may end up more \
2803             permissive than its source. Use `--preserve-settings=all+acl`. Only the root was \
2804             checked - entries beneath it may carry ACLs this says nothing about."
2805        ),
2806        Err(err) => {
2807            tracing::debug!("cannot probe {src_root:?} for a POSIX ACL: {err:#}");
2808        }
2809    }
2810}
2811
2812/// Warn once per run when the source ROOT carries a POSIX ACL that this copy will not carry across.
2813///
2814/// `handle` is the root's `O_PATH` classify handle and `src_root` its path, for the message;
2815/// `notice` is what the run's settings say (see [`RootAclNotice`]). The probe consults whichever of
2816/// its per-kind flags matches the root's own kind, so `f:acl` does not silence a directory root.
2817///
2818/// "Once" is per PROCESS, which is what makes this affordable: a `--dereference` walk recurses into
2819/// `copy` per resolved symlink, and a multi-operand run has several roots. The first root that can
2820/// carry an ACL spends the probe; the rest are silent even if they would have warned. That is the
2821/// heuristic being cheap on purpose — the alternative is the per-entry cost that made `acl` opt-in.
2822pub async fn warn_if_root_acl_unpreserved(handle: &Handle, src_root: &Path, notice: RootAclNotice) {
2823    if !root_acl_probe_worth_reaching(notice) {
2824        return;
2825    }
2826    warn_root_acl(handle, src_root, notice).await;
2827}
2828
2829/// [`warn_if_root_acl_unpreserved`] for a caller that holds the root's PARENT rather than the root
2830/// itself — the shape of the local `rcp`/`rlink` entry points, which open the root only inside the
2831/// walk.
2832///
2833/// The `openat` is skipped when nothing could be warned about and when the per-process run is
2834/// already spent, so a copy that did not ask for the notice or already preserves ACLs — and every
2835/// call after the first — costs nothing at all. Two operands racing can both pass that check and
2836/// both open their root; the loser of the claim has then spent one `openat` and nothing more. A
2837/// root that cannot be opened is left to the walk to diagnose.
2838pub async fn warn_if_root_acl_unpreserved_at(
2839    parent: &Dir,
2840    name: &OsStr,
2841    src_root: &Path,
2842    notice: RootAclNotice,
2843) {
2844    if !root_acl_probe_worth_reaching(notice) {
2845        return;
2846    }
2847    match parent.child(name).await {
2848        Ok(handle) => warn_root_acl(&handle, src_root, notice).await,
2849        Err(err) => {
2850            tracing::debug!("cannot open source root {src_root:?} for a POSIX ACL probe: {err:#}");
2851        }
2852    }
2853}
2854
2855// ── fd-based metadata application ───────────────────────────────────────────────
2856//
2857// These primitives apply ownership / mode / timestamps to an entry through a
2858// file descriptor we already hold, rather than re-resolving a path. That closes
2859// the TOCTOU window a path-based applier would have between opening/creating the
2860// entry and re-touching it by name (which is why the fd-based appliers replaced
2861// the path-based ones entirely).
2862//
2863// Every applier does chown BEFORE chmod: an unprivileged `fchown` clears
2864// setuid/setgid on a regular file, so the chmod has to come after to restore
2865// them. `set_file_metadata_owned` additionally puts the widening step LAST, after
2866// utimens — it is what takes a destination file from the owner-only mode it was
2867// created at (`DST_FILE_CREATE_MODE`) to the source mode, so it must not land
2868// until every other fallible step has succeeded. Ordering the two is free:
2869// `fchmod` touches ctime only, never atime/mtime, so the timestamps `futimens`
2870// installs are the same either way. All syscalls are gated through
2871// `run_metadata_probed_blocking` with `MetadataOp::Chmod`, bucketing
2872// chown/chmod/utimens/ACL together.
2873
2874/// `fchown` on a real (readable/writable) file descriptor.
2875///
2876/// No-op is the caller's responsibility: this always issues the syscall. Pass
2877/// `None` for a component that must not change.
2878async fn fchown_fd(
2879    fd: BorrowedFd<'_>,
2880    side: congestion::Side,
2881    uid: Option<u32>,
2882    gid: Option<u32>,
2883) -> std::io::Result<()> {
2884    fchown_owned(fd.try_clone_to_owned()?, side, uid, gid)
2885        .await
2886        .map(drop)
2887}
2888
2889async fn fchown_owned(
2890    owned: OwnedFd,
2891    side: congestion::Side,
2892    uid: Option<u32>,
2893    gid: Option<u32>,
2894) -> std::io::Result<OwnedFd> {
2895    run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
2896        #[cfg(test)]
2897        let _visit = resource_tests::gate_opened_descriptor(owned.as_raw_fd())?;
2898        fchown(
2899            owned.as_fd(),
2900            uid.map(Uid::from_raw),
2901            gid.map(Gid::from_raw),
2902        )
2903        .map_err(nix_to_io)?;
2904        Ok(owned)
2905    })
2906    .await
2907}
2908
2909/// `fchmod` on a real file descriptor. `mode` is masked to the permission bits
2910/// (`0o7777`); file-type bits, if present, are dropped by `from_bits_truncate`.
2911///
2912/// `fd` must be a real (not `O_PATH`) descriptor — `fchmod` returns `EBADF` on an
2913/// `O_PATH` fd. This is used by the copy path, which holds the destination's own
2914/// writable file / directory fd. For an `O_PATH` [`Handle`] (e.g. rchm's classified
2915/// entry), use [`chmod_via_proc_fd`] instead.
2916async fn fchmod_fd(fd: BorrowedFd<'_>, side: congestion::Side, mode: u32) -> std::io::Result<()> {
2917    fchmod_owned(fd.try_clone_to_owned()?, side, mode)
2918        .await
2919        .map(drop)
2920}
2921
2922async fn fchmod_owned(
2923    owned: OwnedFd,
2924    side: congestion::Side,
2925    mode: u32,
2926) -> std::io::Result<OwnedFd> {
2927    run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
2928        fchmod(owned.as_fd(), Mode::from_bits_truncate(mode)).map_err(nix_to_io)?;
2929        Ok(owned)
2930    })
2931    .await
2932}
2933
2934/// `futimens` on a real file descriptor.
2935async fn futimens_fd(
2936    fd: BorrowedFd<'_>,
2937    side: congestion::Side,
2938    atime: i64,
2939    atime_nsec: i64,
2940    mtime: i64,
2941    mtime_nsec: i64,
2942) -> std::io::Result<()> {
2943    futimens_owned(
2944        fd.try_clone_to_owned()?,
2945        side,
2946        atime,
2947        atime_nsec,
2948        mtime,
2949        mtime_nsec,
2950    )
2951    .await
2952    .map(drop)
2953}
2954
2955async fn futimens_owned(
2956    owned: OwnedFd,
2957    side: congestion::Side,
2958    atime: i64,
2959    atime_nsec: i64,
2960    mtime: i64,
2961    mtime_nsec: i64,
2962) -> std::io::Result<OwnedFd> {
2963    run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
2964        let atime_spec = TimeSpec::new(atime, atime_nsec);
2965        let mtime_spec = TimeSpec::new(mtime, mtime_nsec);
2966        futimens(owned.as_fd(), &atime_spec, &mtime_spec).map_err(nix_to_io)?;
2967        Ok(owned)
2968    })
2969    .await
2970}
2971
2972/// Inode-exact `fchownat` on any [`Handle`]'s `O_PATH` fd, operating on the entry
2973/// the fd points at — file, directory, or symlink — never following a symlink.
2974///
2975/// Uses `AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW` so the empty pathname resolves to
2976/// the fd's own pinned inode: no path re-resolution by `name` happens, so a
2977/// concurrent rename/symlink-swap of the directory entry cannot redirect the
2978/// chown to a different target. `AT_SYMLINK_NOFOLLOW` makes a symlink `Handle`
2979/// chown the link itself rather than its target. Pass `None` for a component
2980/// that must not change (the caller decides when to issue the syscall at all).
2981pub(crate) async fn fchown_handle(
2982    handle: &Handle,
2983    side: congestion::Side,
2984    uid: Option<u32>,
2985    gid: Option<u32>,
2986) -> std::io::Result<()> {
2987    let owned = handle.as_fd().try_clone_to_owned()?;
2988    run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
2989        fchownat(
2990            owned.as_fd(),
2991            "",
2992            uid.map(Uid::from_raw),
2993            gid.map(Gid::from_raw),
2994            AtFlags::AT_EMPTY_PATH | AtFlags::AT_SYMLINK_NOFOLLOW,
2995        )
2996        .map_err(nix_to_io)
2997    })
2998    .await
2999}
3000
3001/// `chmod` any non-symlink entry (file, directory, or special) through an `O_PATH`
3002/// [`Handle`] by going via the `/proc/self/fd/N` magic symlink, changing the mode
3003/// of the EXACT inode the handle pins — never re-resolving the entry by name.
3004///
3005/// (Symlink mode bits are not settable on Linux, so callers never invoke this on a
3006/// symlink handle.)
3007///
3008/// # Why /proc and not `fchmod`/`fchmodat`
3009///
3010/// The `Handle` fd is `O_PATH`, which is the only way to pin an arbitrary entry's
3011/// inode without read/write/search rights on it. But `O_PATH` rules out the
3012/// obvious chmod paths:
3013///
3014/// - `fchmod(fd, mode)` returns `EBADF` on an `O_PATH` fd (it requires a real
3015///   open file description).
3016/// - `fchmodat(dirfd, name, mode, AT_SYMLINK_NOFOLLOW)` re-resolves `name`
3017///   relative to a directory fd — that re-resolution is exactly the TOCTOU window
3018///   we are closing, and the `AT_SYMLINK_NOFOLLOW` flag is only honored on Linux
3019///   6.6+ for `fchmodat` (older kernels reject it with `ENOTSUP`).
3020///
3021/// `chmod("/proc/self/fd/N", mode)` follows the kernel's per-fd magic symlink,
3022/// which resolves to the open file description's pinned inode regardless of what
3023/// the original `name` now refers to. Because the `O_PATH` handle keeps that
3024/// inode alive (the kernel cannot recycle an inode with an open reference), this
3025/// is inode-exact and immune to a concurrent rename/symlink swap. It also works
3026/// regardless of the file's own permission bits — e.g. a non-root owner's
3027/// `0000`-mode file — because the operation authorizes against the caller's
3028/// ownership, not the path's mode, and needs no traversal/read rights on the
3029/// target. (`fchmodat(.., FollowSymlink)` on the magic symlink is used because
3030/// the magic link must be dereferenced to reach the pinned inode.)
3031///
3032/// # Precondition
3033///
3034/// Requires `/proc` to be mounted (the standard Linux default). Without `/proc`
3035/// the call fails with `ENOENT`; this is a documented operational precondition of
3036/// the fd-based chmod path.
3037pub(crate) async fn chmod_via_proc_fd(
3038    handle: &Handle,
3039    side: congestion::Side,
3040    mode: u32,
3041) -> std::io::Result<()> {
3042    // clone the O_PATH fd into an owned fd the blocking closure can hold, keeping
3043    // the pinned inode alive for the syscall's full duration even if the
3044    // originating Handle is dropped after the closure starts. started spawn_blocking work is not
3045    // cancellable.
3046    let owned = handle.as_fd().try_clone_to_owned()?;
3047    run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
3048        let proc_path = format!("/proc/self/fd/{}", owned.as_raw_fd());
3049        // FollowSymlink: the /proc entry is a magic symlink that must be
3050        // dereferenced to reach the pinned inode (NoFollowSymlink would chmod the
3051        // magic link itself, a silent no-op).
3052        nix::sys::stat::fchmodat(
3053            AT_FDCWD,
3054            proc_path.as_str(),
3055            Mode::from_bits_truncate(mode),
3056            nix::sys::stat::FchmodatFlags::FollowSymlink,
3057        )
3058        .map_err(nix_to_io)
3059    })
3060    .await
3061}
3062
3063/// Read full [`std::fs::Metadata`] for the exact inode an `O_PATH` [`Handle`] pins,
3064/// via the `/proc/self/fd/N` magic symlink.
3065///
3066/// The fd-pinned [`FileMeta`] snapshot ([`Handle::meta`]) covers uid/gid/mode and
3067/// the a/m/ctime timestamps, but NOT the birth time (`btime`) — `fstat` does not
3068/// return it. Callers that need `Metadata::created()` (the `--created-before`
3069/// time filter) get it here while staying inode-exact: the open `O_PATH` handle
3070/// keeps the inode alive, so resolving `/proc/self/fd/N` lands on that same inode
3071/// regardless of a concurrent rename/symlink swap of the original name. Gated as
3072/// `Stat`. Requires `/proc` mounted (same precondition as [`chmod_via_proc_fd`]).
3073pub(crate) async fn stat_meta_via_proc_fd(
3074    handle: &Handle,
3075    side: congestion::Side,
3076) -> std::io::Result<std::fs::Metadata> {
3077    let owned = handle.as_fd().try_clone_to_owned()?;
3078    run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
3079        let proc_path = format!("/proc/self/fd/{}", owned.as_raw_fd());
3080        std::fs::metadata(proc_path)
3081    })
3082    .await
3083}
3084
3085/// Read the target of a symlink [`Handle`] inode-exact, via `readlinkat(fd, "")` on the pinned
3086/// `O_PATH | O_NOFOLLOW` fd.
3087///
3088/// The empty-pathname form of `readlinkat` (Linux 2.6.39+) operates on the symlink the fd itself
3089/// refers to, so the target comes from the *same* pinned inode as [`Handle::meta`] — there is no
3090/// path re-resolution by name that a concurrent same-name swap could redirect. This is the symlink
3091/// analogue of reading a regular file's bytes and metadata from one [`Dir::open_file_read`] fd: it
3092/// lets a caller send/apply a symlink's target and metadata as a faithful pair. Fails if the handle
3093/// does not refer to a symlink (the empty-path form requires a symlink fd); callers only invoke it
3094/// on a `Symlink`-classified handle. Gated as `ReadLink`.
3095///
3096/// Raw `libc::readlinkat` is required: nix's wrapper rejects the empty pathname that selects the
3097/// fd's own link (the same reason `symlink_utimes_fd` uses raw `utimensat`).
3098pub async fn read_link_handle(
3099    handle: &Handle,
3100    side: congestion::Side,
3101) -> std::io::Result<std::path::PathBuf> {
3102    use std::os::unix::ffi::OsStringExt;
3103    let owned = handle.as_fd().try_clone_to_owned()?;
3104    run_metadata_probed_blocking(side, congestion::MetadataOp::ReadLink, move || {
3105        // a symlink target is bounded by PATH_MAX, so a single buffer of that size never truncates.
3106        let mut buf = vec![0u8; libc::PATH_MAX as usize];
3107        // SAFETY: `owned` is a valid open fd for the duration of this call; the empty C string
3108        // selects the fd's own symlink (it was opened O_PATH|O_NOFOLLOW); `buf` has `len()` bytes.
3109        let n = unsafe {
3110            libc::readlinkat(
3111                owned.as_raw_fd(),
3112                c"".as_ptr(),
3113                buf.as_mut_ptr().cast::<libc::c_char>(),
3114                buf.len(),
3115            )
3116        };
3117        if n < 0 {
3118            return Err(std::io::Error::last_os_error());
3119        }
3120        buf.truncate(n as usize);
3121        Ok(std::path::PathBuf::from(std::ffi::OsString::from_vec(buf)))
3122    })
3123    .await
3124}
3125
3126/// Set timestamps on a symlink `Handle`'s `O_PATH` fd, operating on the link
3127/// itself, via a raw `utimensat(fd, "", times, AT_EMPTY_PATH)`.
3128///
3129/// Raw libc is required here: nix's `utimensat` wrapper cannot pass
3130/// `AT_EMPTY_PATH`, and `futimens` on an `O_PATH` fd returns `EBADF`. The
3131/// `/proc/self/fd` form silently no-ops under `NOFOLLOW`, so it must not be used.
3132async fn symlink_utimes_fd(
3133    handle: &Handle,
3134    side: congestion::Side,
3135    atime: i64,
3136    atime_nsec: i64,
3137    mtime: i64,
3138    mtime_nsec: i64,
3139) -> std::io::Result<()> {
3140    let owned = handle.as_fd().try_clone_to_owned()?;
3141    run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
3142        let times: [libc::timespec; 2] = [
3143            libc::timespec {
3144                tv_sec: atime,
3145                tv_nsec: atime_nsec,
3146            },
3147            libc::timespec {
3148                tv_sec: mtime,
3149                tv_nsec: mtime_nsec,
3150            },
3151        ];
3152        // SAFETY: `owned` is a valid open fd for the duration of this call; the
3153        // pathname is the empty C string and `times` points to a 2-element array.
3154        let res = unsafe {
3155            libc::utimensat(
3156                owned.as_raw_fd(),
3157                c"".as_ptr(),
3158                times.as_ptr(),
3159                libc::AT_EMPTY_PATH,
3160            )
3161        };
3162        if res == 0 {
3163            Ok(())
3164        } else {
3165            Err(std::io::Error::last_os_error())
3166        }
3167    })
3168    .await
3169}
3170
3171/// Apply file metadata (owner, timestamps, mode, ACL) while consuming the destination's
3172/// existing writable descriptor, in the chown → utimens → mode order.
3173///
3174/// `fd` must be the destination file's own fd (typically the write fd returned by
3175/// [`Dir::create_file`]). The same descriptor moves through individually gated metadata
3176/// operations, without duplication or reopening. Each blocking output owns it until consumed
3177/// or dropped, including cancellation. Callers must finish pending writes and check their errors
3178/// before transferring the descriptor so later writes cannot overwrite the applied timestamps.
3179/// Gating on `settings.file`: chown only when uid or gid is requested, chmod
3180/// always (the masked mode honors `mode_mask`), timestamps only when requested, ACLs only when
3181/// `settings.file.acl` is on — in which case `acls` must carry what was read from the source, or
3182/// the call fails rather than guessing (see `acls_to_apply`).
3183///
3184/// # The widening invariant
3185///
3186/// > EXACTLY ONE step widens the destination from its owner-only create mode, and it is the LAST
3187/// > fallible step here. Without a source access ACL that step is the `fchmod`; with one it is the
3188/// > `fsetxattr`, and the `fchmod` before it is narrowed to `(mode & 0o7000) | DST_FILE_CREATE_MODE`
3189/// > so that it cannot widen.
3190///
3191/// This is what makes [`DST_FILE_CREATE_MODE`] safe to use for every destination file: a failure
3192/// part-way through metadata application must not publish the final mode on a file the copy is
3193/// about to report as failed. The mode is also decided UNCONDITIONALLY here — this call is the
3194/// single place it happens, so no `--preserve` setting can leave a successfully copied file
3195/// owner-only.
3196///
3197/// An access ACL has to take that slot because applying one IS a mode-changing operation: the ACL's
3198/// `MASK` entry becomes the mode's group bits, so `fsetxattr` widens, and a `chmod` AFTER it would
3199/// re-derive `MASK` from the mode and destroy the ACL's fidelity. The two want the same slot, and
3200/// the resolution is verified kernel behavior: `fsetxattr` sets the rwx bits exactly (`USER_OBJ`,
3201/// `MASK`, `OTHER`) and PRESERVES setuid/setgid/sticky, so the preceding `fchmod` can carry the
3202/// special bits alone. Its result — special bits over an owner-only, non-executable mode — grants
3203/// nothing on its own, so a failing `fsetxattr` leaves a file no one else can reach.
3204///
3205/// Clearing an ACL, by contrast, is mode-neutral and can only narrow, so when the source has none
3206/// the removal is safe to run BEFORE the widening chmod (verified: a `0o600` file stays `0o600`
3207/// across `fremovexattr`).
3208///
3209/// A file whose copy fails anywhere before that widening step therefore stays owner-only —
3210/// deliberately. It is reported as an error, and its size/mtime then *normally* differ from the
3211/// source so a later run re-copies it. Two cases where they do not, leaving the file owner-only
3212/// until something else re-copies it: a failure at the widening step ITSELF, which comes after the
3213/// timestamps have been applied, so the destination matches its source on both size and mtime; and
3214/// the nanosecond concession in [`metadata_equal`], which skips that comparison when either side's
3215/// `mtime_nsec` is zero, so even a file that never reached `futimens` compares equal when its write
3216/// and the source's mtime land in the same whole second. See `docs/tocttou.md`.
3217///
3218/// [`metadata_equal`]: crate::filecmp::metadata_equal
3219pub async fn set_file_metadata_owned<Meta: crate::preserve::Metadata>(
3220    settings: &crate::preserve::Settings,
3221    meta: &Meta,
3222    acls: Option<&Acls>,
3223    fd: OwnedFd,
3224    side: congestion::Side,
3225) -> std::io::Result<()> {
3226    let ut = &settings.file.user_and_time;
3227    let fd = if ut.uid || ut.gid {
3228        let uid = if ut.uid { Some(meta.uid()) } else { None };
3229        let gid = if ut.gid { Some(meta.gid()) } else { None };
3230        fchown_owned(fd, side, uid, gid).await?
3231    } else {
3232        fd
3233    };
3234    let fd = if ut.time {
3235        futimens_owned(
3236            fd,
3237            side,
3238            meta.atime(),
3239            meta.atime_nsec(),
3240            meta.mtime(),
3241            meta.mtime_nsec(),
3242        )
3243        .await?
3244    } else {
3245        fd
3246    };
3247    let acls = acls_to_apply(settings.file.acl, acls)?;
3248    let mode = crate::preserve::masked_mode(settings.file.mode_mask, meta);
3249    if let Some(acls) = acls.filter(|acls| acls.access.is_some()) {
3250        // the ACL is the widening step; this chmod carries only the special bits
3251        let fd = fchmod_owned(fd, side, (mode & 0o7000) | DST_FILE_CREATE_MODE).await?;
3252        set_or_remove_acl_owned(fd, side, ACL_ACCESS_XATTR, acls.access.clone()).await?;
3253    } else {
3254        // clearing an inherited ACL can only narrow, so it is safe before the widening chmod
3255        let fd = if let Some(acls) = acls {
3256            set_or_remove_acl_owned(fd, side, ACL_ACCESS_XATTR, acls.access.clone()).await?
3257        } else {
3258            fd
3259        };
3260        fchmod_owned(fd, side, mode).await?;
3261    }
3262    Ok(())
3263}
3264
3265/// Apply directory metadata (owner, mode, ACLs, timestamps) to an open [`Dir`] fd,
3266/// following the chown → mode → utimens ordering. Gates on `settings.dir` and
3267/// uses the directory's own congestion side.
3268///
3269/// The mode step is the same two-branch shape as [`set_file_metadata_owned`] — see the widening
3270/// invariant there — with [`DST_DIR_CREATE_MODE`] as the create mode. It stays in the directory
3271/// applier's existing chmod slot rather than moving to the end: `futimens` is last for a directory
3272/// because a directory's mtime is bumped by every child created in it, and unlike a file's mode a
3273/// directory's is applied post-order, once its children exist. The DEFAULT ACL rides along with the
3274/// access one; being mode-neutral, it constrains nothing.
3275///
3276/// # One asymmetry a directory has and a file does not
3277///
3278/// A destination file is always freshly created, so the ACL branch's narrowed `fchmod` only ever
3279/// holds it at the mode it already had. A destination DIRECTORY may be REUSED — an existing `dst/`
3280/// that rcp is copying into — and there that same `fchmod` actively NARROWS it, to `0o700` plus its
3281/// special bits, for the moment between the chmod and the `fsetxattr`. If the `fsetxattr` then
3282/// fails, the copy is reported failed and a long-lived directory is left at `0o700`, which is not
3283/// the mode it started at.
3284///
3285/// That is fail-closed, and deliberately so: the alternative is publishing the source's mode on a
3286/// directory whose ACL never landed, which is the wider outcome. But it means an operator whose
3287/// destination directory comes back owner-only after a failed `d:acl` copy is looking at this step,
3288/// not at a bug. Branch 2 has no such window — it only ever chmods once, to the final mode.
3289pub async fn set_dir_metadata_fd<Meta: crate::preserve::Metadata>(
3290    settings: &crate::preserve::Settings,
3291    meta: &Meta,
3292    acls: Option<&Acls>,
3293    dir: &Dir,
3294) -> std::io::Result<()> {
3295    set_dir_metadata_fd_inner(settings, meta, acls, dir, true).await
3296}
3297
3298/// The body of [`set_dir_metadata_fd`], parameterized over whether the DEFAULT ACL is applied
3299/// here. `apply_default` is `false` for exactly one caller — [`set_reused_dir_metadata_fd`]'s
3300/// locked path, which owns the default ACL through the lockdown guard: that write must serialize
3301/// against the guard's rollback, and an unguarded write from here is precisely the detached-write
3302/// hazard the guard closes (see `DefaultAclGuard`). Everything else — including the access ACL's
3303/// claim on the widening slot — is identical in both modes.
3304async fn set_dir_metadata_fd_inner<Meta: crate::preserve::Metadata>(
3305    settings: &crate::preserve::Settings,
3306    meta: &Meta,
3307    acls: Option<&Acls>,
3308    dir: &Dir,
3309    apply_default: bool,
3310) -> std::io::Result<()> {
3311    let side = dir.side();
3312    let fd = dir.fd.as_fd();
3313    let ut = &settings.dir.user_and_time;
3314    if ut.uid || ut.gid {
3315        let uid = if ut.uid { Some(meta.uid()) } else { None };
3316        let gid = if ut.gid { Some(meta.gid()) } else { None };
3317        fchown_fd(fd, side, uid, gid).await?;
3318    }
3319    let acls = acls_to_apply(settings.dir.acl, acls)?;
3320    let mode = crate::preserve::masked_mode(settings.dir.mode_mask, meta);
3321    if let Some(acls) = acls.filter(|acls| acls.access.is_some()) {
3322        // the ACL is the widening step; this chmod carries only the special bits
3323        fchmod_fd(fd, side, (mode & 0o7000) | DST_DIR_CREATE_MODE).await?;
3324        apply_acls_fd(fd, side, acls, apply_default).await?;
3325    } else {
3326        // no source access ACL, so the chmod is the widening step and stays last. Both applies that
3327        // can run here are safe before it: clearing an inherited ACL can only narrow, and SETTING a
3328        // default ACL is mode-neutral — it governs what children inherit, never this directory's
3329        // own mode (a source can have a default ACL and no access one).
3330        if let Some(acls) = acls {
3331            apply_acls_fd(fd, side, acls, apply_default).await?;
3332        }
3333        fchmod_fd(fd, side, mode).await?;
3334    }
3335    if ut.time {
3336        futimens_fd(
3337            fd,
3338            side,
3339            meta.atime(),
3340            meta.atime_nsec(),
3341            meta.mtime(),
3342            meta.mtime_nsec(),
3343        )
3344        .await?;
3345    }
3346    Ok(())
3347}
3348
3349/// Apply directory metadata to a REUSED destination directory that may have been locked down under
3350/// [`strict_operand_resolution`], restoring the original owner correctly and WITHOUT a transient
3351/// window in which a hostile prior owner regains control.
3352///
3353/// `lock` is what [`lockdown_reused_dir`] recorded, or `None` for a freshly created directory
3354/// (nothing to restore). When present, this restores ONLY the owner components that are NOT being
3355/// preserved to the source — leaving each preserved component as the copier for
3356/// [`set_dir_metadata_fd`] to set to the source owner. So the directory's transient owner is always
3357/// the copier (for a preserved uid) or the final owner (a non-preserved uid equals the original) —
3358/// NEVER a prior owner who will not own the final directory. This closes the brief re-grant window
3359/// that a plain "chown to the original, then chown the preserved components to source" sequence
3360/// would open for a preserving copy, and removes the "left owned by the original if the second chown
3361/// fails" case. The non-preserved gid write, when issued, targets the directory's unchanged gid — a
3362/// kernel-permitted set-to-current no-op, safe even for a non-root copier not in that group.
3363///
3364/// # Resolving the two ACLs
3365///
3366/// The ACCESS ACL keeps its usual applier semantics (set or cleared by the inner applier when
3367/// `d:acl` is on, untouched otherwise). The DEFAULT ACL of a LOCKED directory is different: it is
3368/// resolved HERE, first, through the lockdown guard, and the inner applier is told to leave it
3369/// alone (`set_dir_metadata_fd_inner(…, apply_default: false)`):
3370///
3371/// 1. `settings.dir.acl` on → the SOURCE's default ACL is installed. When the source has none
3372///    there is nothing to write: the lockdown already left the directory without one, which is the
3373///    correct end state. The copy is preserving ACLs, so what the destination carried before is
3374///    not what it should end with.
3375/// 2. otherwise → the directory's ORIGINAL default ACL is restored (nothing to do when there was
3376///    none). rcp was not asked to change this directory's ACLs; the lockdown removed it only so
3377///    children created during the copy could not inherit it, and failing to put it back would
3378///    permanently destroy an ACL the destination had before the copy. That makes a failure here an
3379///    ERROR, unlike the lockdown strip, where `EOPNOTSUPP` is tolerated (a filesystem that cannot
3380///    hold an ACL cannot have had one).
3381///
3382/// Both writes go through `ReusedDirLock::write_default_acl_guarded`, which serializes them
3383/// against the guard's `Drop` rollback: this future can be cancelled with the write already
3384/// detached on the blocking pool, and an unserialized write could land AFTER the rollback and
3385/// silently undo it (see `DefaultAclGuard`). The guard stays armed through every remaining
3386/// fallible step — INCLUDING the final re-stat verification and every cancellation point up to
3387/// the successful return — and is disarmed only immediately before `Ok(())`, so a failure or a
3388/// cancellation anywhere in between rolls the directory back to ITS OWN original default ACL —
3389/// including the case where that original is "none" and the rollback must REMOVE a source ACL
3390/// that was just installed.
3391///
3392/// The guarded write runs FIRST, unwinding the lockdown in the reverse of the order it was applied
3393/// (ACL removed last, so resolved first; then the owner; then the mode, via the chmod inside the
3394/// inner applier). Two things make that placement deliberate:
3395///
3396/// - **It runs while the copier still owns the directory**, before the owner is handed back. Only
3397///   an owner or a `CAP_FOWNER` copier may write these attributes.
3398/// - **It fails toward *unchanged*.** If a later step fails, the armed guard leaves the directory
3399///   holding (or rolled back to) the default ACL it had before the copy. Deferring it past the
3400///   chmod would instead fail toward *damaged* — a directory permanently stripped of an ACL it
3401///   owned before rcp touched it, which is the one outcome this function is required to treat as
3402///   an error rather than produce.
3403///
3404/// The guarded write is mode-neutral, so unlike the SOURCE-ACL applies in the inner applier it
3405/// does not compete with the finalize chmod for the widening slot: only a DEFAULT ACL ever goes
3406/// through it, and a default ACL never moves its own directory's mode. That is a consequence of
3407/// the lockdown narrowing to the default ACL alone (see [`lockdown_reused_dir`]) and is worth
3408/// stating, because it was not always true: while the lockdown also stripped the ACCESS ACL, the
3409/// restore had to precede the chmod or it would install the DESTINATION's original rwx bits over
3410/// the source's mode — the snapshot's `USER_OBJ`/`MASK`/`OTHER` agree with the directory's
3411/// original mode, not the source's — and the re-stat verify below would then reject the copy.
3412/// Anything that reintroduces an access-ACL restore here inherits that constraint.
3413pub async fn set_reused_dir_metadata_fd<Meta: crate::preserve::Metadata>(
3414    settings: &crate::preserve::Settings,
3415    meta: &Meta,
3416    acls: Option<&Acls>,
3417    lock: Option<ReusedDirLock>,
3418    dir: &Dir,
3419) -> std::io::Result<()> {
3420    // A fresh / non-strict directory (lock == None) uses the shared best-effort applier UNVERIFIED —
3421    // verifying it would regress legitimate non-root `--preserve` copies (which the kernel silently
3422    // strips setgid from, best-effort). Only a strict-mode LOCKED reused directory (lock == Some)
3423    // gets the restore + final verify below.
3424    // NB: `ReusedDirLock` is an RAII guard, so it cannot be destructured by move — and must not be,
3425    // since dropping its parts separately is exactly the bug it exists to prevent. It stays whole
3426    // until it is deliberately disarmed below.
3427    let Some(lock) = lock else {
3428        return set_dir_metadata_fd(settings, meta, acls, dir).await;
3429    };
3430    let (orig_uid, orig_gid) = lock.restore_owner;
3431    // resolve the default ACL first, through the guard — see "Resolving the two ACLs" above for
3432    // the two cases, the serialization against the guard's rollback, and why a failure must leave
3433    // the guard armed (`Drop` then gets one synchronous rollback attempt rather than the bytes
3434    // dying with the error)
3435    let final_default = if settings.dir.acl {
3436        // fail closed exactly as the applier does when the call site carried no ACLs
3437        acls_to_apply(true, acls)?.and_then(|acls| acls.default.clone())
3438    } else {
3439        lock.original_default_acl()
3440    };
3441    if let Some(blob) = final_default {
3442        lock.write_default_acl_guarded(dir.side, blob).await?;
3443    }
3444    let ut = &settings.dir.user_and_time;
3445    {
3446        let uid = (!ut.uid).then_some(orig_uid);
3447        let gid = (!ut.gid).then_some(orig_gid);
3448        if uid.is_some() || gid.is_some() {
3449            fchown_fd(dir.fd.as_fd(), dir.side, uid, gid).await?;
3450        }
3451    }
3452    // the default ACL is excluded (`apply_default: false`): it was resolved through the guard
3453    // above, and only the guard's serialized writer may touch it while the lockdown is live
3454    set_dir_metadata_fd_inner(settings, meta, acls, dir, false).await?;
3455    // The guard stays ARMED through the verify below: a re-stat error, a verification failure, or
3456    // this future being cancelled at the `meta()` await all mean the copy of this directory FAILED,
3457    // and failure must leave the directory as it was — the armed guard's `Drop` rolls the default
3458    // ACL back to the destination's original (REMOVING a just-installed source ACL when the
3459    // original was "none") rather than leaving the directory half-converted to the source.
3460    // Disarming any earlier reopens exactly that window; see the disarm at the end.
3461    //
3462    // Re-stat and verify the finalize actually landed. A backend that reports chown/chmod success
3463    // without honoring it (e.g. CIFS without unix extensions) would otherwise leave a strict reused
3464    // directory silently owned by the copier or at the wrong mode. A lone dropped S_ISGID bit is a
3465    // WARNING, not a failure: it is narrower than the source, child safety was already ensured by the
3466    // INTERIM setgid held during the copy, and failing here would regress a legitimate non-root
3467    // `--preserve` of a setgid directory (the kernel strips setgid when the copier is not in the
3468    // group and lacks CAP_FSETID) — matching the best-effort behavior of a non-strict copy.
3469    //
3470    // `want_mode` stays `masked_mode` even when an access ACL was applied, because the two agree by
3471    // construction: the destination's rwx bits come from the source's ACL (`fsetxattr` sets them
3472    // from USER_OBJ/MASK/OTHER) and the source's own mode's rwx bits were derived from that same
3473    // ACL by the kernel. The special bits come from the chmod either way. So for a setgid source
3474    // directory with an ACL, `want_mode`'s S_ISGID is checked against the chmod's result and its
3475    // rwx against the ACL's, with no double-counting.
3476    use crate::preserve::Metadata as _;
3477    use std::os::unix::fs::PermissionsExt as _;
3478    let want_uid = if ut.uid { meta.uid() } else { orig_uid };
3479    let want_gid = if ut.gid { meta.gid() } else { orig_gid };
3480    let want_mode = crate::preserve::masked_mode(settings.dir.mode_mask, meta);
3481    let got = dir.meta().await?;
3482    let got_mode = got.permissions().mode() & 0o7777;
3483    if got.uid() != want_uid || got.gid() != want_gid {
3484        return Err(std::io::Error::new(
3485            std::io::ErrorKind::PermissionDenied,
3486            format!(
3487                "reused-directory finalize could not be verified: the directory shows uid={} gid={} \
3488                 (expected uid={} gid={}); the filesystem may not honor chown/chmod",
3489                got.uid(),
3490                got.gid(),
3491                want_uid,
3492                want_gid,
3493            ),
3494        ));
3495    }
3496    if got_mode != want_mode {
3497        if want_mode & 0o2000 != 0 && want_mode & !0o2000 == got_mode {
3498            // the ONLY difference is a dropped setgid bit — warn, do not fail.
3499            tracing::warn!(
3500                "setgid not applied to reused directory (final mode {:#o} vs source {:#o}): the \
3501                 copier is not in the directory's group and lacks CAP_FSETID",
3502                got_mode,
3503                want_mode,
3504            );
3505        } else {
3506            return Err(std::io::Error::new(
3507                std::io::ErrorKind::PermissionDenied,
3508                format!(
3509                    "reused-directory finalize could not be verified: the directory shows \
3510                     mode={:#o} (expected {:#o}); the filesystem may not honor chmod",
3511                    got_mode, want_mode,
3512                ),
3513            ));
3514        }
3515    }
3516    // Disarm only here, with the finalize verified and nothing fallible (or cancellable) left
3517    // before the successful return: every earlier exit — error or cancellation — leaves the guard
3518    // armed so its `Drop` restores the destination's original default ACL.
3519    lock.disarm();
3520    Ok(())
3521}
3522
3523/// Apply symlink metadata (owner and timestamps only — never mode) to a symlink
3524/// [`Handle`], operating on the link itself via `AT_EMPTY_PATH`.
3525///
3526/// Symlinks have no meaningful permission bits, so there is no chmod step;
3527/// ordering is chown → utimens. Gates on `settings.symlink`.
3528pub async fn set_symlink_metadata_fd<Meta: crate::preserve::Metadata>(
3529    settings: &crate::preserve::Settings,
3530    meta: &Meta,
3531    handle: &Handle,
3532    side: congestion::Side,
3533) -> std::io::Result<()> {
3534    let ut = &settings.symlink.user_and_time;
3535    if ut.uid || ut.gid {
3536        let uid = if ut.uid { Some(meta.uid()) } else { None };
3537        let gid = if ut.gid { Some(meta.gid()) } else { None };
3538        // chown the link itself: fchown_handle already operates inode-exact on the O_PATH handle
3539        // via AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW.
3540        fchown_handle(handle, side, uid, gid).await?;
3541    }
3542    if ut.time {
3543        symlink_utimes_fd(
3544            handle,
3545            side,
3546            meta.atime(),
3547            meta.atime_nsec(),
3548            meta.mtime(),
3549            meta.mtime_nsec(),
3550        )
3551        .await?;
3552    }
3553    Ok(())
3554}
3555
3556// ── helpers ───────────────────────────────────────────────────────────────────
3557
3558/// One blocking job whose queued resources have a defined destruction order.
3559///
3560/// Field order is load-bearing: queued user work may own fds, so it must be dropped before the
3561/// strong admission lease that accounts for them.
3562struct BlockingJob<F> {
3563    work: F,
3564    admission: Option<throttle::BlockingFdAdmissionLease>,
3565}
3566
3567type BlockingJobOutput<T> = (
3568    std::io::Result<T>,
3569    Option<throttle::BlockingFdAdmissionLease>,
3570);
3571
3572impl<F> BlockingJob<F> {
3573    fn run<T>(self) -> BlockingJobOutput<T>
3574    where
3575        F: FnOnce() -> std::io::Result<T>,
3576    {
3577        let Self { work, admission } = self;
3578        (work(), admission)
3579    }
3580}
3581
3582fn take_blocking_job<F>(
3583    shared_job: &std::sync::Mutex<Option<BlockingJob<F>>>,
3584) -> Option<BlockingJob<F>> {
3585    shared_job
3586        .lock()
3587        .unwrap_or_else(std::sync::PoisonError::into_inner)
3588        .take()
3589}
3590
3591/// Wait for a blocking job while retaining control of work that has not started.
3592struct BlockingJobWaiter<F, T> {
3593    shared_job: Arc<std::sync::Mutex<Option<BlockingJob<F>>>>,
3594    handle: tokio::task::JoinHandle<Option<BlockingJobOutput<T>>>,
3595}
3596
3597impl<F, T> std::future::Future for BlockingJobWaiter<F, T> {
3598    type Output = Result<Option<BlockingJobOutput<T>>, tokio::task::JoinError>;
3599
3600    fn poll(
3601        self: std::pin::Pin<&mut Self>,
3602        cx: &mut std::task::Context<'_>,
3603    ) -> std::task::Poll<Self::Output> {
3604        let this = self.get_mut();
3605        std::future::Future::poll(std::pin::Pin::new(&mut this.handle), cx)
3606    }
3607}
3608
3609impl<F, T> Drop for BlockingJobWaiter<F, T> {
3610    fn drop(&mut self) {
3611        let queued_job = take_blocking_job(&self.shared_job);
3612        drop(queued_job);
3613        self.handle.abort();
3614    }
3615}
3616
3617/// Internal entry point for work that inherits any live task-scoped admission.
3618pub(crate) async fn run_fd_admitted_blocking<F, T>(f: F) -> std::io::Result<T>
3619where
3620    F: FnOnce() -> std::io::Result<T> + Send + 'static,
3621    T: Send + 'static,
3622{
3623    // upgrade immediately before submission. if the ambient weak reference has expired (ordinary
3624    // directory recursion dropped its provisional guard), this remains an unadmitted directory
3625    // operation; an admitted outer leaf such as copy -> recursive rm stays represented.
3626    let blocking_admission = FD_ADMISSION
3627        .try_with(throttle::FdAdmission::blocking_lease)
3628        .ok();
3629    run_blocking_job(BlockingJob {
3630        work: f,
3631        admission: blocking_admission,
3632    })
3633    .await
3634}
3635
3636/// Run fd-owning blocking work with an explicitly borrowed OpenFile admission guard.
3637///
3638/// The borrow ensures the guard is live when its blocking lease is acquired. No ambient admission
3639/// scope is needed. Unlimited admission remains a no-op, matching the guard's configured policy.
3640/// The strong lease lives in the blocking task's output, after `result`, so an abandoned returned
3641/// descriptor owner is dropped before the admission slot is released. This boundary adds no rate
3642/// or congestion gating.
3643///
3644/// Until the worker takes the shared job, dropping the waiter synchronously destroys its user work
3645/// before its lease. Once the worker takes it, the job is considered started and runs detached if
3646/// the waiter is cancelled.
3647pub async fn run_fd_admitted_blocking_with<F, T>(
3648    admission: &throttle::OpenFileGuard,
3649    f: F,
3650) -> std::io::Result<T>
3651where
3652    F: FnOnce() -> std::io::Result<T> + Send + 'static,
3653    T: Send + 'static,
3654{
3655    run_blocking_job(BlockingJob {
3656        work: f,
3657        admission: Some(admission.admission().blocking_lease()),
3658    })
3659    .await
3660}
3661
3662async fn run_blocking_job<F, T>(job: BlockingJob<F>) -> std::io::Result<T>
3663where
3664    F: FnOnce() -> std::io::Result<T> + Send + 'static,
3665    T: Send + 'static,
3666{
3667    let shared_job = Arc::new(std::sync::Mutex::new(Some(job)));
3668    let worker_job = Arc::clone(&shared_job);
3669    #[cfg(test)]
3670    crate::testutils::record_blocking_submission();
3671    let handle =
3672        tokio::task::spawn_blocking(move || take_blocking_job(&worker_job).map(BlockingJob::run));
3673    let (result, _blocking_admission) = BlockingJobWaiter { shared_job, handle }
3674        .await
3675        .map_err(std::io::Error::other)?
3676        .expect("blocking job disappeared while its waiter was alive");
3677    result
3678}
3679
3680/// Owns one unclaimed continuation until the worker claims it or either owner cancels it.
3681struct PendingContinuation<C>(Option<Arc<std::sync::Mutex<Option<C>>>>);
3682
3683impl<C> PendingContinuation<C> {
3684    fn claim(&mut self) -> Option<C> {
3685        let shared = self
3686            .0
3687            .take()
3688            .expect("continuation already claimed or cancelled");
3689        shared
3690            .lock()
3691            .unwrap_or_else(std::sync::PoisonError::into_inner)
3692            .take()
3693    }
3694
3695    fn cancel(&mut self) {
3696        let Some(shared) = self.0.take() else {
3697            return;
3698        };
3699        let mut pending = shared
3700            .lock()
3701            .unwrap_or_else(std::sync::PoisonError::into_inner);
3702        // keep the lock until captured descriptors close. A worker that observes cancellation
3703        // can then return without releasing its admission lease ahead of those descriptors.
3704        drop(pending.take());
3705    }
3706
3707    fn disarm(&mut self) {
3708        self.0 = None;
3709    }
3710}
3711
3712impl<C> Drop for PendingContinuation<C> {
3713    fn drop(&mut self) {
3714        self.cancel();
3715    }
3716}
3717
3718pin_project_lite::pin_project! {
3719    /// Cancels pending captures before the canonical waiter's queued-job lease can be released.
3720    struct ContinuationWaiter<F, C> {
3721        continuation: PendingContinuation<C>,
3722        #[pin]
3723        future: F,
3724    }
3725
3726    impl<F, C> PinnedDrop for ContinuationWaiter<F, C> {
3727        fn drop(this: Pin<&mut Self>) {
3728            this.project().continuation.cancel();
3729        }
3730    }
3731}
3732
3733impl<F, C> std::future::Future for ContinuationWaiter<F, C>
3734where
3735    F: std::future::Future,
3736{
3737    type Output = F::Output;
3738
3739    fn poll(
3740        self: std::pin::Pin<&mut Self>,
3741        cx: &mut std::task::Context<'_>,
3742    ) -> std::task::Poll<Self::Output> {
3743        let this = self.project();
3744        let output = this.future.poll(cx);
3745        if output.is_ready() {
3746            // a completed worker has claimed or destroyed the continuation, including unwind
3747            this.continuation.disarm();
3748        }
3749        output
3750    }
3751}
3752
3753async fn run_file_create_and_then<F, C, T>(
3754    side: congestion::Side,
3755    operation: F,
3756    continuation: C,
3757) -> std::io::Result<T>
3758where
3759    F: FnOnce() -> std::io::Result<std::fs::File> + Send + 'static,
3760    C: FnOnce(std::io::Result<std::fs::File>) -> T + Send + 'static,
3761    T: Send + 'static,
3762{
3763    let operation =
3764        prepare_metadata_operation(side, congestion::MetadataOp::OpenCreate, operation).await;
3765    let pending = Arc::new(std::sync::Mutex::new(Some(continuation)));
3766    // the worker owns a second cancellation guard so a panic during creation destroys unclaimed
3767    // captures before the canonical job unwinds and releases its descriptor-admission lease.
3768    let mut worker_continuation = PendingContinuation(Some(Arc::clone(&pending)));
3769    let future = run_fd_admitted_blocking(move || {
3770        let created = operation();
3771        #[cfg(test)]
3772        let _visit = created.as_ref().ok().and_then(|file| {
3773            tests::gate_file_create_stage(file.as_raw_fd(), "before-continuation")
3774        });
3775        // the operation's probe, permit, and execution timing have all finished before this claim
3776        Ok(worker_continuation
3777            .claim()
3778            .map(|continuation| continuation(created)))
3779    });
3780    ContinuationWaiter {
3781        continuation: PendingContinuation(Some(pending)),
3782        future,
3783    }
3784    .await
3785    .map(|output| output.expect("continuation disappeared while its waiter was alive"))
3786}
3787
3788/// Run a blocking metadata syscall closure on the blocking pool, gated by the
3789/// congestion controller for the given side and operation kind.
3790///
3791/// Each per-entry `openat`/`fstatat` is rate-gated, counted against the cwnd permit, and feeds the
3792/// latency probe — the same per-metadata-syscall gating shape used throughout this crate. The cwnd
3793/// guard and probe move into the blocking closure because cancelling the async waiter cannot stop
3794/// a syscall that has started; releasing either in the waiter would undercount the actual in-flight
3795/// work and its latency.
3796pub async fn run_metadata_probed_blocking<F, T>(
3797    side: congestion::Side,
3798    op: congestion::MetadataOp,
3799    f: F,
3800) -> std::io::Result<T>
3801where
3802    F: FnOnce() -> std::io::Result<T> + Send + 'static,
3803    T: Send + 'static,
3804{
3805    let operation = prepare_metadata_operation(side, op, f).await;
3806    run_fd_admitted_blocking(operation).await
3807}
3808
3809async fn prepare_metadata_operation<F, T>(
3810    side: congestion::Side,
3811    op: congestion::MetadataOp,
3812    f: F,
3813) -> impl FnOnce() -> std::io::Result<T> + Send + 'static
3814where
3815    F: FnOnce() -> std::io::Result<T> + Send + 'static,
3816    T: Send + 'static,
3817{
3818    let rate = metadata_timing_scope(side, op, MetadataTimingPhase::Rate);
3819    throttle::get_ops_token().await;
3820    rate.finish();
3821    prepare_metadata_operation_no_rate(side, op, f).await
3822}
3823
3824/// Variant of [`run_metadata_probed_blocking`] for a caller that already consumed the static
3825/// operations-rate token before spawning its task.
3826pub async fn run_metadata_probed_blocking_no_rate<F, T>(
3827    side: congestion::Side,
3828    op: congestion::MetadataOp,
3829    f: F,
3830) -> std::io::Result<T>
3831where
3832    F: FnOnce() -> std::io::Result<T> + Send + 'static,
3833    T: Send + 'static,
3834{
3835    let operation = prepare_metadata_operation_no_rate(side, op, f).await;
3836    run_fd_admitted_blocking(operation).await
3837}
3838
3839async fn prepare_metadata_operation_no_rate<F, T>(
3840    side: congestion::Side,
3841    op: congestion::MetadataOp,
3842    f: F,
3843) -> impl FnOnce() -> std::io::Result<T> + Send + 'static
3844where
3845    F: FnOnce() -> std::io::Result<T> + Send + 'static,
3846    T: Send + 'static,
3847{
3848    let admission = metadata_timing_scope(side, op, MetadataTimingPhase::Admission);
3849    let ops_permit = throttle::ops_in_flight_permit(crate::walk::meta_resource(side, op)).await;
3850    admission.finish();
3851    let probe = congestion::Probe::start_metadata(side, op);
3852    // worker threads do not inherit a task-local subscriber. Retain it only for constructing the
3853    // execution scope; rooted metadata spans own their dispatcher without retaining contextual
3854    // parents whose release would otherwise depend on the worker's ambient subscriber.
3855    let timing_dispatch = tracing::enabled!(target: "rcp::timing", tracing::Level::TRACE)
3856        .then(|| tracing::dispatcher::get_default(Clone::clone));
3857    let queue = metadata_timing_scope(side, op, MetadataTimingPhase::Queue);
3858    move || {
3859        queue.finish();
3860        let execution = timing_dispatch.as_ref().map(|dispatch| {
3861            tracing::dispatcher::with_default(dispatch, || {
3862                metadata_timing_scope(side, op, MetadataTimingPhase::Execute)
3863            })
3864        });
3865        let result = f();
3866        match &result {
3867            Ok(_) => probe.complete_ok(0),
3868            Err(_) => probe.discard(),
3869        }
3870        // the cwnd models syscall concurrency, so release it when `f` finishes. The shared blocking
3871        // boundary keeps admission in the task output because `f` can return an fd that an
3872        // abandoned waiter never receives.
3873        drop(ops_permit);
3874        if let Some(execution) = execution {
3875            execution.finish();
3876        }
3877        result
3878    }
3879}
3880
3881/// Convert a `nix::errno::Errno` to `std::io::Error`.
3882fn nix_to_io(e: nix::errno::Errno) -> std::io::Error {
3883    std::io::Error::from_raw_os_error(e as i32)
3884}
3885
3886/// Return `true` when `name` is a single non-empty path component (no `/`,
3887/// not `.` or `..`).
3888fn is_single_component(name: &OsStr) -> bool {
3889    if name.is_empty() || name == "." || name == ".." {
3890        return false;
3891    }
3892    !name.as_bytes().contains(&b'/')
3893}
3894
3895// ── tests ─────────────────────────────────────────────────────────────────────
3896
3897#[cfg(test)]
3898mod tests {
3899    use super::*;
3900    use crate::preserve::Metadata;
3901    use crate::testutils;
3902    use std::io::Read;
3903    use std::num::NonZeroUsize;
3904
3905    #[test]
3906    fn failed_stream_construction_closes_the_owned_fd() -> anyhow::Result<()> {
3907        let root_path = tempfile::tempdir()?;
3908        let file_path = root_path.path().join("regular-file");
3909        std::fs::write(&file_path, b"x")?;
3910        let fd: OwnedFd = std::fs::File::open(file_path)?.into();
3911        let raw_fd = fd.as_raw_fd();
3912        let error = OwnedDirectoryStream::from_fd(fd, None).unwrap_err();
3913        assert_eq!(error.raw_os_error(), Some(libc::ENOTDIR));
3914        assert_eq!(unsafe { libc::fcntl(raw_fd, libc::F_GETFD) }, -1);
3915        assert_eq!(
3916            std::io::Error::last_os_error().raw_os_error(),
3917            Some(libc::EBADF)
3918        );
3919        Ok(())
3920    }
3921
3922    #[tokio::test]
3923    async fn cursor_visits_each_entry_once_across_batches() -> anyhow::Result<()> {
3924        let root_path = testutils::create_temp_dir().await?;
3925        for index in 0..150 {
3926            tokio::fs::write(root_path.join(format!("file-{index:03}")), b"x").await?;
3927        }
3928        let root = Dir::open_root_dir(&root_path, false, congestion::Side::Source).await?;
3929        let mut cursor = root.entries().await?;
3930        let mut names = Vec::new();
3931        let mut batch_sizes = Vec::new();
3932        loop {
3933            let batch = cursor.next_batch(NonZeroUsize::new(64).unwrap()).await?;
3934            if batch.is_empty() {
3935                break;
3936            }
3937            batch_sizes.push(batch.len());
3938            names.extend(batch.into_iter().map(|entry| entry.name));
3939        }
3940        names.sort();
3941        let expected: Vec<_> = (0..150)
3942            .map(|index| std::ffi::OsString::from(format!("file-{index:03}")))
3943            .collect();
3944        assert_eq!(batch_sizes, [64, 64, 22]);
3945        assert_eq!(names, expected);
3946        Ok(())
3947    }
3948
3949    #[tokio::test]
3950    async fn cursor_handles_empty_and_non_utf8_names() -> anyhow::Result<()> {
3951        use std::os::unix::ffi::OsStringExt;
3952
3953        let root_path = testutils::create_temp_dir().await?;
3954        let root = Dir::open_root_dir(&root_path, false, congestion::Side::Source).await?;
3955        let mut empty = root.entries().await?;
3956        assert!(
3957            empty
3958                .next_batch(NonZeroUsize::new(1).unwrap())
3959                .await?
3960                .is_empty()
3961        );
3962
3963        let name = std::ffi::OsString::from_vec(vec![b'n', 0xff]);
3964        tokio::fs::write(root_path.join(&name), b"x").await?;
3965        let mut cursor = root.entries().await?;
3966        let batch = cursor.next_batch(NonZeroUsize::new(1).unwrap()).await?;
3967        assert_eq!(batch.len(), 1);
3968        assert_eq!(batch[0].name, name);
3969        assert_eq!(batch[0].kind_hint, Some(EntryKind::File));
3970        assert!(
3971            cursor
3972                .next_batch(NonZeroUsize::new(1).unwrap())
3973                .await?
3974                .is_empty()
3975        );
3976        Ok(())
3977    }
3978
3979    #[tokio::test]
3980    async fn independent_cursors_do_not_share_directory_offsets() -> anyhow::Result<()> {
3981        let root_path = testutils::create_temp_dir().await?;
3982        for index in 0..80 {
3983            tokio::fs::write(root_path.join(format!("file-{index:02}")), b"x").await?;
3984        }
3985        let root = Dir::open_root_dir(&root_path, false, congestion::Side::Source).await?;
3986        let mut first = root.entries().await?;
3987        let mut second = root.entries().await?;
3988        let limit = NonZeroUsize::new(64).unwrap();
3989        let first_batch = first.next_batch(limit).await?;
3990        let second_batch = second.next_batch(limit).await?;
3991        let first_rest = first.next_batch(limit).await?;
3992        let second_rest = second.next_batch(limit).await?;
3993        let mut first_names: Vec<_> = first_batch
3994            .into_iter()
3995            .chain(first_rest)
3996            .map(|e| e.name)
3997            .collect();
3998        let mut second_names: Vec<_> = second_batch
3999            .into_iter()
4000            .chain(second_rest)
4001            .map(|e| e.name)
4002            .collect();
4003        first_names.sort();
4004        second_names.sort();
4005        let expected: Vec<_> = (0..80)
4006            .map(|index| std::ffi::OsString::from(format!("file-{index:02}")))
4007            .collect();
4008        assert_eq!(first_names, expected);
4009        assert_eq!(second_names, expected);
4010        Ok(())
4011    }
4012
4013    #[tokio::test]
4014    async fn cursor_failure_after_a_partial_read_does_not_restart() -> anyhow::Result<()> {
4015        let root_path = testutils::create_temp_dir().await?;
4016        for index in 0..3 {
4017            tokio::fs::write(root_path.join(format!("file-{index}")), b"x").await?;
4018        }
4019        let root = Dir::open_root_dir(&root_path, false, congestion::Side::Source).await?;
4020        let mut cursor = root.entries().await?;
4021        let fd = cursor.iterator.as_ref().unwrap().as_raw_fd();
4022        cursor.read_hook = Some(Box::new(|accepted, _| {
4023            if accepted == 1 {
4024                Err(std::io::Error::from_raw_os_error(libc::EIO))
4025            } else {
4026                Ok(())
4027            }
4028        }));
4029        let limit = NonZeroUsize::new(64).unwrap();
4030        assert_eq!(
4031            cursor.next_batch(limit).await.unwrap_err().raw_os_error(),
4032            Some(libc::EIO)
4033        );
4034        assert!(
4035            cursor.next_batch(limit).await.is_err(),
4036            "a failed cursor restarted"
4037        );
4038        assert_eq!(
4039            unsafe { libc::fcntl(fd, libc::F_GETFD) },
4040            -1,
4041            "failed cursor leaked its fd"
4042        );
4043
4044        let mut independent = root.entries().await?;
4045        assert_eq!(independent.next_batch(limit).await?.len(), 3);
4046        Ok(())
4047    }
4048
4049    #[tokio::test]
4050    async fn cancelled_admitted_batch_retains_its_fd_and_admission_until_exit() -> anyhow::Result<()>
4051    {
4052        use anyhow::Context;
4053        use std::time::Duration;
4054
4055        let root_path = testutils::create_temp_dir().await?;
4056        let root = Dir::open_root_dir(&root_path, false, congestion::Side::Source).await?;
4057        let mut inspect = root.entries().await?;
4058        let mut raw_names = [
4059            inspect
4060                .iterator
4061                .as_mut()
4062                .unwrap()
4063                .next_raw_entry()?
4064                .unwrap()
4065                .name,
4066            inspect
4067                .iterator
4068                .as_mut()
4069                .unwrap()
4070                .next_raw_entry()?
4071                .unwrap()
4072                .name,
4073        ];
4074        raw_names.sort();
4075        assert_eq!(
4076            raw_names,
4077            [
4078                std::ffi::OsString::from("."),
4079                std::ffi::OsString::from("..")
4080            ]
4081        );
4082        assert!(
4083            inspect
4084                .iterator
4085                .as_mut()
4086                .unwrap()
4087                .next_raw_entry()?
4088                .is_none()
4089        );
4090        let mut cursor = root.entries().await?;
4091        let admission = testutils::AdmissionLimit::new().await;
4092        admission.set_files_in_flight(1);
4093        let guard = throttle::open_file_permit().await;
4094        let fd_admission = guard.admission();
4095        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
4096        let (release_tx, release_rx) = std::sync::mpsc::channel();
4097        let mut started_tx = Some(started_tx);
4098        let raw_reads = Arc::new(std::sync::atomic::AtomicUsize::new(0));
4099        let observed_raw_reads = Arc::clone(&raw_reads);
4100        cursor.read_hook = Some(Box::new(move |_, fd| {
4101            observed_raw_reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
4102            if let Some(started_tx) = started_tx.take() {
4103                let _ = started_tx.send(fd);
4104                release_rx.recv().map_err(std::io::Error::other)?;
4105            }
4106            Ok(())
4107        }));
4108        let task = tokio::spawn(async move {
4109            with_fd_admission(fd_admission, async move {
4110                let _guard = guard;
4111                cursor.next_batch(NonZeroUsize::new(1).unwrap()).await
4112            })
4113            .await
4114        });
4115        let fd = started_rx.await.context("blocking batch did not start")?;
4116        task.abort();
4117        assert!(task.await.unwrap_err().is_cancelled());
4118        assert_ne!(
4119            unsafe { libc::fcntl(fd, libc::F_GETFD) },
4120            -1,
4121            "cancelled batch lost its owned fd"
4122        );
4123        let mut second = Box::pin(throttle::open_file_permit());
4124        assert!(
4125            futures::poll!(second.as_mut()).is_pending(),
4126            "admission released before read exited"
4127        );
4128        release_tx
4129            .send(())
4130            .context("blocking batch ended before release")?;
4131        let permit = admission
4132            .run_with_timeout(Duration::from_secs(20), second)
4133            .await
4134            .context("admission was not released after blocking batch exited")?;
4135        drop(permit);
4136        assert_eq!(
4137            unsafe { libc::fcntl(fd, libc::F_GETFD) },
4138            -1,
4139            "cancelled batch leaked its fd"
4140        );
4141        assert!(
4142            raw_reads.load(std::sync::atomic::Ordering::SeqCst) >= 3,
4143            "the blocking job stopped before reading past dot entries; raw reads: {}",
4144            raw_reads.load(std::sync::atomic::Ordering::SeqCst)
4145        );
4146        Ok(())
4147    }
4148
4149    const EVERY_KIND: [EntryKind; 4] = [
4150        EntryKind::File,
4151        EntryKind::Dir,
4152        EntryKind::Symlink,
4153        EntryKind::Special,
4154    ];
4155
4156    #[tokio::test]
4157    async fn preview_operand_descent_rejects_a_symlink_in_the_relative_prefix() -> anyhow::Result<()>
4158    {
4159        let fixture = testutils::create_temp_dir().await?;
4160        let named_root = fixture.join("named-root");
4161        let outside = fixture.join("outside");
4162        tokio::fs::create_dir_all(&named_root).await?;
4163        tokio::fs::create_dir_all(outside.join("level-two")).await?;
4164        tokio::fs::symlink(&outside, named_root.join("level-one")).await?;
4165
4166        let opened = open_existing_dir_beneath_operand(
4167            &named_root,
4168            Path::new("level-one/level-two"),
4169            congestion::Side::Destination,
4170        )
4171        .await?;
4172
4173        assert!(opened.is_none());
4174        Ok(())
4175    }
4176
4177    #[tokio::test]
4178    async fn preview_operand_relative_path_accepts_empty_and_rejects_non_normal_components()
4179    -> anyhow::Result<()> {
4180        let fixture = testutils::create_temp_dir().await?;
4181        let named_root = fixture.join("named-root");
4182        tokio::fs::create_dir(&named_root).await?;
4183
4184        assert!(
4185            open_existing_dir_beneath_operand(
4186                &named_root,
4187                Path::new(""),
4188                congestion::Side::Destination,
4189            )
4190            .await?
4191            .is_some(),
4192            "an empty relative path must open the named root"
4193        );
4194        for invalid in ["/absolute", ".", "..", "one/./two", "one/../two"] {
4195            let error = open_existing_dir_beneath_operand(
4196                &named_root,
4197                Path::new(invalid),
4198                congestion::Side::Destination,
4199            )
4200            .await
4201            .expect_err("a non-normal relative path must be rejected");
4202            assert_eq!(error.raw_os_error(), Some(libc::EINVAL), "{invalid:?}");
4203        }
4204        Ok(())
4205    }
4206
4207    pub(super) fn gate_file_create_stage(
4208        fd: RawFd,
4209        stage: &str,
4210    ) -> Option<testutils::BlockingPathGateVisit> {
4211        let path = std::fs::read_link(format!("/proc/self/fd/{fd}")).ok()?;
4212        testutils::wait_on_blocking_path_gate(&path.join(stage), fd)
4213    }
4214
4215    mod max_files_in_flight_tests {
4216        use super::*;
4217        use anyhow::Context as _;
4218        use futures::FutureExt as _;
4219
4220        struct BlockingDropFd {
4221            _file: std::fs::File,
4222            drop_started: Option<tokio::sync::oneshot::Sender<()>>,
4223            release_drop: std::sync::mpsc::Receiver<()>,
4224            _completion: crate::testutils::CompletionSignal,
4225        }
4226
4227        impl AsRawFd for BlockingDropFd {
4228            fn as_raw_fd(&self) -> RawFd {
4229                self._file.as_raw_fd()
4230            }
4231        }
4232
4233        impl Drop for BlockingDropFd {
4234            fn drop(&mut self) {
4235                if let Some(drop_started) = self.drop_started.take() {
4236                    let _ = drop_started.send(());
4237                }
4238                self.release_drop
4239                    .recv()
4240                    .expect("drop release sender must stay alive");
4241            }
4242        }
4243
4244        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
4245        struct QueuedFdDropObservation {
4246            fd_was_closed: bool,
4247            admission_was_retained: bool,
4248        }
4249
4250        struct QueuedFdCapture {
4251            file: Option<std::fs::File>,
4252            probe: crate::testutils::FdIdentityProbe,
4253            observation: Arc<std::sync::Mutex<Option<std::io::Result<QueuedFdDropObservation>>>>,
4254        }
4255
4256        impl AsRawFd for QueuedFdCapture {
4257            fn as_raw_fd(&self) -> RawFd {
4258                self.file
4259                    .as_ref()
4260                    .expect("captured file must be present")
4261                    .as_raw_fd()
4262            }
4263        }
4264
4265        impl Drop for QueuedFdCapture {
4266            fn drop(&mut self) {
4267                drop(self.file.take());
4268                let admission_was_retained = throttle::open_file_permit().now_or_never().is_none();
4269                *self
4270                    .observation
4271                    .lock()
4272                    .expect("queued fd drop observation lock poisoned") =
4273                    Some(self.probe.original_is_closed().map(|fd_was_closed| {
4274                        QueuedFdDropObservation {
4275                            fd_was_closed,
4276                            admission_was_retained,
4277                        }
4278                    }));
4279            }
4280        }
4281
4282        async fn assert_queued_owner_closes_before_admission<Fut>(
4283            operation: impl FnOnce(QueuedFdCapture) -> Fut,
4284        ) -> anyhow::Result<()>
4285        where
4286            Fut: std::future::Future,
4287        {
4288            let source = tempfile::tempfile()?;
4289            let probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
4290            let observation = Arc::new(std::sync::Mutex::new(None));
4291            let capture = QueuedFdCapture {
4292                file: Some(source),
4293                probe,
4294                observation: Arc::clone(&observation),
4295            };
4296            let limits = testutils::AdmissionLimit::new().await;
4297            limits.set_files_in_flight(1);
4298            let guard = throttle::open_file_permit().await;
4299            let (started_tx, started_rx) = tokio::sync::oneshot::channel();
4300            let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
4301            let blocker = tokio::task::spawn_blocking(move || {
4302                let _ = started_tx.send(());
4303                let _ = release_rx.recv();
4304            });
4305            started_rx.await?;
4306            let mut work = Box::pin(with_fd_admission(guard.admission(), operation(capture)));
4307            let queued = futures::poll!(work.as_mut()).is_pending();
4308            // leave the queued job as the only strong admission owner before dropping it
4309            drop(guard);
4310            drop(work);
4311            let closed_before_release = probe.original_is_closed();
4312            let drop_observation = observation.lock().unwrap().take().transpose();
4313            let mut next_file = Box::pin(throttle::open_file_permit());
4314            let returned = next_file.as_mut().now_or_never();
4315            let capacity_returned_before_release = returned.is_some();
4316            // collect failures only after releasing and joining the occupied worker
4317            drop(release_tx);
4318            blocker.await?;
4319            tokio::task::spawn_blocking(|| ()).await?;
4320            let permit = match returned {
4321                Some(permit) => permit,
4322                None => tokio::time::timeout(std::time::Duration::from_secs(5), next_file).await?,
4323            };
4324            drop(permit);
4325            assert!(
4326                queued,
4327                "the operation must queue behind the occupied worker"
4328            );
4329            assert!(
4330                closed_before_release?,
4331                "queued cancellation retained its fd"
4332            );
4333            assert!(capacity_returned_before_release);
4334            assert_eq!(
4335                drop_observation?,
4336                Some(QueuedFdDropObservation {
4337                    fd_was_closed: true,
4338                    admission_was_retained: true,
4339                }),
4340                "queued cancellation must close its fd before returning admission"
4341            );
4342            Ok(())
4343        }
4344
4345        #[test]
4346        fn cancelled_queued_owned_acl_read_closes_source_before_returning_admission()
4347        -> anyhow::Result<()> {
4348            tokio::runtime::Builder::new_current_thread()
4349                .max_blocking_threads(1)
4350                .enable_all()
4351                .build()?
4352                .block_on(assert_queued_owner_closes_before_admission(|owner| {
4353                    read_acls_owned(owner, congestion::Side::Source, false)
4354                }))
4355        }
4356
4357        async fn assert_abandoned_output_closes_before_admission<Fut, T>(
4358            operation: impl FnOnce(BlockingDropFd) -> Fut + Send + 'static,
4359        ) -> anyhow::Result<()>
4360        where
4361            Fut: std::future::Future<Output = T> + Send + 'static,
4362            T: Send + 'static,
4363        {
4364            let tmp = tempfile::tempdir()?;
4365            let path = tmp.path().join("returned-owner");
4366            std::fs::write(&path, b"payload")?;
4367            let file = std::fs::File::open(&path)?;
4368            let probe = testutils::FdIdentityProbe::capture(file.as_raw_fd())?;
4369            let mut gate = testutils::BlockingPathGate::install(&path);
4370            let limits = testutils::AdmissionLimit::new().await;
4371            limits.set_files_in_flight(1);
4372            let guard = throttle::open_file_permit().await;
4373            let (drop_started_tx, drop_started_rx) = tokio::sync::oneshot::channel();
4374            let (release_drop_tx, release_drop_rx) = std::sync::mpsc::channel();
4375            let (completion, completion_rx) = testutils::CompletionSignal::new();
4376            let owner = BlockingDropFd {
4377                _file: file,
4378                drop_started: Some(drop_started_tx),
4379                release_drop: release_drop_rx,
4380                _completion: completion,
4381            };
4382            let task = tokio::spawn(with_fd_admission(guard.admission(), async move {
4383                let _guard = guard;
4384                operation(owner).await
4385            }));
4386            let started = gate.wait_started().await;
4387            task.abort();
4388            let cancelled = matches!(task.await, Err(error) if error.is_cancelled());
4389            gate.release_all();
4390            let dropping = drop_started_rx.await;
4391            let admission_retained = throttle::open_file_permit().now_or_never().is_none();
4392            let fd_retained = probe.original_is_closed().map(|closed| !closed);
4393            let released = release_drop_tx.send(());
4394            let (completed, permit) = testutils::await_completion_and_capacity(
4395                completion_rx,
4396                throttle::open_file_permit(),
4397            )
4398            .await;
4399            drop(permit);
4400            started?;
4401            dropping?;
4402            released?;
4403            completed?;
4404            assert!(cancelled, "the async waiter must observe cancellation");
4405            assert!(
4406                admission_retained,
4407                "admission was released before the abandoned returned fd was dropped"
4408            );
4409            assert!(fd_retained?);
4410            assert!(probe.original_is_closed()?);
4411            Ok(())
4412        }
4413
4414        #[tokio::test]
4415        async fn abandoned_owned_acl_output_closes_source_before_returning_admission()
4416        -> anyhow::Result<()> {
4417            assert_abandoned_output_closes_before_admission(|owner| {
4418                read_acls_owned(owner, congestion::Side::Source, false)
4419            })
4420            .await
4421        }
4422
4423        #[test]
4424        fn cancelled_queued_file_creation_drops_payload_before_admission_without_creating()
4425        -> anyhow::Result<()> {
4426            let runtime = tokio::runtime::Builder::new_current_thread()
4427                .max_blocking_threads(1)
4428                .enable_all()
4429                .build()?;
4430            runtime.block_on(async {
4431                let tmp = tempfile::tempdir()?;
4432                let root =
4433                    Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
4434                let destination = tmp.path().join("destination");
4435                let called = Arc::new(std::sync::atomic::AtomicBool::new(false));
4436                let continuation_called = Arc::clone(&called);
4437                assert_queued_owner_closes_before_admission(|owner| async move {
4438                    root.create_file_and_then(OsStr::new("destination"), move |created| {
4439                        let _owner = owner;
4440                        continuation_called.store(true, std::sync::atomic::Ordering::SeqCst);
4441                        created
4442                    })
4443                    .await
4444                })
4445                .await?;
4446                assert!(!called.load(std::sync::atomic::Ordering::SeqCst));
4447                assert!(
4448                    !destination.exists(),
4449                    "cancelled queued work created a destination"
4450                );
4451                Ok(())
4452            })
4453        }
4454
4455        async fn cancelled_unclaimed_file_continuation_case(
4456            stage: &str,
4457            strict: bool,
4458        ) -> anyhow::Result<()> {
4459            use std::os::unix::fs::PermissionsExt as _;
4460            let tmp = tempfile::tempdir()?;
4461            if strict {
4462                set_xattr_at(tmp.path(), ACL_DEFAULT_XATTR, &permissive_acl());
4463            }
4464            let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
4465            let destination = tmp.path().join("destination");
4466            let source = tempfile::tempfile()?;
4467            let source_probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
4468            let observation = Arc::new(std::sync::Mutex::new(None));
4469            let capture = QueuedFdCapture {
4470                file: Some(source),
4471                probe: source_probe,
4472                observation: Arc::clone(&observation),
4473            };
4474            let called = Arc::new(std::sync::atomic::AtomicBool::new(false));
4475            let continuation_called = Arc::clone(&called);
4476            let gate = testutils::BlockingPathGate::install(destination.join(stage));
4477            let limits = testutils::AdmissionLimit::new().await;
4478            limits.set_files_in_flight(1);
4479            let resource = throttle::Resource::meta(
4480                throttle::Side::Destination,
4481                throttle::MetadataOp::OpenCreate,
4482            );
4483            limits.set_max_ops_in_flight(resource, 1);
4484            let samples = Arc::new(congestion::testing::CollectingSink::new());
4485            congestion::install_sample_sink(samples.clone());
4486            let guard = throttle::open_file_permit().await;
4487            let admission = guard.admission();
4488            let task = tokio::spawn(with_fd_admission(admission, async move {
4489                let _guard = guard;
4490                let continuation = move |created| {
4491                    let _capture = capture;
4492                    continuation_called.store(true, std::sync::atomic::Ordering::SeqCst);
4493                    created
4494                };
4495                if strict {
4496                    let operation = root.file_create_operation(OsStr::new("destination"), true)?;
4497                    run_file_create_and_then(congestion::Side::Destination, operation, continuation)
4498                        .await
4499                } else {
4500                    root.create_file_and_then(OsStr::new("destination"), continuation)
4501                        .await
4502                }
4503            }));
4504            let mut next_operation = Box::pin(throttle::ops_in_flight_permit(resource));
4505            let (
4506                cancelled,
4507                (
4508                    created_probe,
4509                    source_closed,
4510                    mode,
4511                    acquired_operation,
4512                    sample_count,
4513                    inherited_acl,
4514                ),
4515            ) = testutils::cancel_at_blocking_path(
4516                limits,
4517                gate,
4518                task,
4519                std::time::Duration::from_secs(20),
4520                |fd| {
4521                    (
4522                        testutils::FdIdentityProbe::capture(fd),
4523                        source_probe.original_is_closed(),
4524                        std::fs::metadata(&destination)
4525                            .map(|meta| meta.permissions().mode() & 0o7777),
4526                        next_operation.as_mut().now_or_never(),
4527                        samples.metadata_count(),
4528                        strict.then(|| get_xattr_at(&destination, ACL_ACCESS_XATTR).is_some()),
4529                    )
4530                },
4531            )
4532            .await?;
4533            let operation_was_finished = acquired_operation.is_some();
4534            let permit = match acquired_operation {
4535                Some(permit) => permit,
4536                None => {
4537                    tokio::time::timeout(std::time::Duration::from_secs(5), next_operation).await?
4538                }
4539            };
4540            drop(permit);
4541            assert!(cancelled.waiter_was_cancelled);
4542            assert!(cancelled.admission_was_retained_while_work_gated);
4543            assert!(cancelled.fd_was_open_while_work_gated);
4544            assert!(
4545                source_closed?,
4546                "unclaimed payload retained its captured source after cancellation"
4547            );
4548            assert_eq!(mode?, DST_FILE_CREATE_MODE);
4549            assert_eq!(operation_was_finished, stage == "before-continuation");
4550            assert_eq!(sample_count, usize::from(stage == "before-continuation"));
4551            assert_eq!(samples.metadata_count(), 1);
4552            assert!(created_probe?.original_is_closed()?);
4553            assert_eq!(
4554                observation.lock().unwrap().take().transpose()?,
4555                Some(QueuedFdDropObservation {
4556                    fd_was_closed: true,
4557                    admission_was_retained: true,
4558                })
4559            );
4560            assert!(!called.load(std::sync::atomic::Ordering::SeqCst));
4561            assert_eq!(cancelled.final_hit_count, 1);
4562            assert_eq!(
4563                std::fs::metadata(&destination)?.permissions().mode() & 0o7777,
4564                DST_FILE_CREATE_MODE
4565            );
4566            assert_eq!(std::fs::metadata(&destination)?.len(), 0);
4567            if strict {
4568                assert_eq!(inherited_acl, Some(stage == "before-sanitation"));
4569                assert_eq!(get_xattr_at(&destination, ACL_ACCESS_XATTR), None);
4570            }
4571            Ok(())
4572        }
4573
4574        #[tokio::test]
4575        async fn cancelled_created_file_never_starts_an_unclaimed_payload() -> anyhow::Result<()> {
4576            for stage in ["before-sanitation", "before-continuation"] {
4577                cancelled_unclaimed_file_continuation_case(stage, false).await?;
4578            }
4579            Ok(())
4580        }
4581
4582        #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
4583        #[tokio::test]
4584        async fn cancelled_file_creation_finishes_acl_sanitation_without_starting_payload()
4585        -> anyhow::Result<()> {
4586            for stage in ["before-sanitation", "before-continuation"] {
4587                cancelled_unclaimed_file_continuation_case(stage, true).await?;
4588            }
4589            Ok(())
4590        }
4591
4592        async fn cancelled_claimed_file_continuation_case(
4593            fail_payload: bool,
4594        ) -> anyhow::Result<()> {
4595            use std::io::{Seek as _, Write as _};
4596            use std::os::unix::fs::PermissionsExt as _;
4597            let tmp = tempfile::tempdir()?;
4598            let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
4599            let destination = tmp.path().join("destination");
4600            let mut source = tempfile::tempfile()?;
4601            source.write_all(b"complete payload")?;
4602            source.rewind()?;
4603            let source_probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
4604            let gate = testutils::BlockingPathGate::install(&destination);
4605            let limits = testutils::AdmissionLimit::new().await;
4606            limits.set_files_in_flight(1);
4607            let resource = throttle::Resource::meta(
4608                throttle::Side::Destination,
4609                throttle::MetadataOp::OpenCreate,
4610            );
4611            limits.set_max_ops_in_flight(resource, 1);
4612            let samples = Arc::new(congestion::testing::CollectingSink::new());
4613            congestion::install_sample_sink(samples.clone());
4614            let guard = throttle::open_file_permit().await;
4615            let admission = guard.admission();
4616            let data_path = destination.clone();
4617            let task = tokio::spawn(with_fd_admission(admission, async move {
4618                let _guard = guard;
4619                root.create_file_and_then(OsStr::new("destination"), move |created| {
4620                    let mut file = created?;
4621                    let visit = testutils::wait_on_blocking_path_gate(&data_path, file.as_raw_fd());
4622                    let copied = if fail_payload {
4623                        file.write_all(b"partial")
4624                            .and_then(|()| Err(std::io::Error::from_raw_os_error(libc::EIO)))
4625                    } else {
4626                        std::io::copy(&mut source, &mut file).map(|_| ())
4627                    };
4628                    std::io::Result::Ok((copied, source, file, visit))
4629                })
4630                .await
4631            }));
4632            let (cancelled, (source_open, mode, operation_available, sample_count)) =
4633                testutils::cancel_at_blocking_path(
4634                    limits,
4635                    gate,
4636                    task,
4637                    std::time::Duration::from_secs(20),
4638                    |_| {
4639                        (
4640                            source_probe.original_is_closed().map(|closed| !closed),
4641                            std::fs::metadata(&destination)
4642                                .map(|meta| meta.permissions().mode() & 0o7777),
4643                            throttle::ops_in_flight_permit(resource)
4644                                .now_or_never()
4645                                .is_some(),
4646                            samples.metadata_count(),
4647                        )
4648                    },
4649                )
4650                .await?;
4651            assert!(cancelled.waiter_was_cancelled);
4652            assert!(cancelled.admission_was_retained_while_work_gated);
4653            assert!(cancelled.fd_was_open_while_work_gated && source_open?);
4654            assert!(cancelled.fd_was_closed_at_output_drop_start);
4655            assert!(cancelled.admission_was_retained_at_output_drop_start);
4656            assert!(source_probe.original_is_closed()?);
4657            assert!(
4658                operation_available,
4659                "payload retained the OpenCreate operation permit"
4660            );
4661            assert_eq!(
4662                sample_count, 1,
4663                "payload started before its metadata probe finished"
4664            );
4665            assert_eq!(samples.metadata_count(), 1);
4666            assert_eq!(cancelled.final_hit_count, 1);
4667            assert_eq!(mode?, DST_FILE_CREATE_MODE);
4668            assert_eq!(
4669                std::fs::metadata(&destination)?.permissions().mode() & 0o7777,
4670                DST_FILE_CREATE_MODE
4671            );
4672            assert_eq!(
4673                std::fs::read(destination)?,
4674                if fail_payload {
4675                    b"partial".as_slice()
4676                } else {
4677                    b"complete payload".as_slice()
4678                }
4679            );
4680            Ok(())
4681        }
4682
4683        #[tokio::test]
4684        async fn cancelled_started_file_continuation_keeps_fds_until_abandoned_output_drops()
4685        -> anyhow::Result<()> {
4686            cancelled_claimed_file_continuation_case(false).await
4687        }
4688
4689        #[tokio::test]
4690        async fn cancelled_failed_file_continuation_keeps_fds_until_abandoned_output_drops()
4691        -> anyhow::Result<()> {
4692            cancelled_claimed_file_continuation_case(true).await
4693        }
4694
4695        #[tokio::test]
4696        async fn panicking_file_create_closes_unclaimed_payload_before_its_admission_lease()
4697        -> anyhow::Result<()> {
4698            let source = tempfile::tempfile()?;
4699            let probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
4700            let observation = Arc::new(std::sync::Mutex::new(None));
4701            let capture = QueuedFdCapture {
4702                file: Some(source),
4703                probe,
4704                observation: Arc::clone(&observation),
4705            };
4706            let called = Arc::new(std::sync::atomic::AtomicBool::new(false));
4707            let continuation_called = Arc::clone(&called);
4708            let limits = testutils::AdmissionLimit::new().await;
4709            limits.set_files_in_flight(1);
4710            let guard = throttle::open_file_permit().await;
4711            let (started_tx, started_rx) = tokio::sync::oneshot::channel();
4712            let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
4713            let mut work = Box::pin(with_fd_admission(guard.admission(), async move {
4714                run_file_create_and_then(
4715                    congestion::Side::Destination,
4716                    move || -> std::io::Result<std::fs::File> {
4717                        let _ = started_tx.send(());
4718                        let _ = release_rx.recv();
4719                        panic!("injected file-create panic");
4720                    },
4721                    move |_created| {
4722                        let _capture = capture;
4723                        continuation_called.store(true, std::sync::atomic::Ordering::SeqCst);
4724                    },
4725                )
4726                .await
4727            }));
4728            let pending = futures::poll!(work.as_mut()).is_pending();
4729            drop(guard);
4730            let started = tokio::time::timeout(std::time::Duration::from_secs(5), started_rx).await;
4731            drop(release_tx);
4732            let result = work.await;
4733            assert!(pending);
4734            started??;
4735            assert!(result.is_err(), "worker panic must fail the create waiter");
4736            assert!(probe.original_is_closed()?);
4737            assert_eq!(
4738                observation.lock().unwrap().take().transpose()?,
4739                Some(QueuedFdDropObservation {
4740                    fd_was_closed: true,
4741                    admission_was_retained: true,
4742                })
4743            );
4744            assert!(!called.load(std::sync::atomic::Ordering::SeqCst));
4745            let permit = tokio::time::timeout(
4746                std::time::Duration::from_secs(5),
4747                throttle::open_file_permit(),
4748            )
4749            .await?;
4750            drop(permit);
4751            Ok(())
4752        }
4753
4754        #[tokio::test]
4755        async fn cancelled_file_creation_waiting_for_opencreate_never_submits_or_runs_payload()
4756        -> anyhow::Result<()> {
4757            let tmp = tempfile::tempdir()?;
4758            let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
4759            let destination = tmp.path().join("destination");
4760            let source = tempfile::tempfile()?;
4761            let probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
4762            let observation = Arc::new(std::sync::Mutex::new(None));
4763            let capture = QueuedFdCapture {
4764                file: Some(source),
4765                probe,
4766                observation: Arc::clone(&observation),
4767            };
4768            let called = Arc::new(std::sync::atomic::AtomicBool::new(false));
4769            let continuation_called = Arc::clone(&called);
4770            let limits = testutils::AdmissionLimit::new().await;
4771            limits.set_files_in_flight(1);
4772            let resource = throttle::Resource::meta(
4773                throttle::Side::Destination,
4774                throttle::MetadataOp::OpenCreate,
4775            );
4776            limits.set_max_ops_in_flight(resource, 1);
4777            let occupied = throttle::ops_in_flight_permit(resource).await;
4778            let guard = throttle::open_file_permit().await;
4779            let submissions = testutils::BlockingSubmissions::start();
4780            let samples = Arc::new(congestion::testing::CollectingSink::new());
4781            congestion::install_sample_sink(samples.clone());
4782            let mut work = Box::pin(with_fd_admission(guard.admission(), async move {
4783                root.create_file_and_then(OsStr::new("destination"), move |created| {
4784                    let _capture = capture;
4785                    continuation_called.store(true, std::sync::atomic::Ordering::SeqCst);
4786                    created
4787                })
4788                .await
4789            }));
4790            let waiting = futures::poll!(work.as_mut()).is_pending();
4791            let source_was_open = probe.original_is_closed().map(|closed| !closed);
4792            drop(work);
4793            let source_closed_while_outer_admitted = probe.original_is_closed();
4794            let outer_admission_retained = throttle::open_file_permit().now_or_never().is_none();
4795            let drop_observation = observation.lock().unwrap().take().transpose();
4796            drop(occupied);
4797            drop(guard);
4798            let permit = tokio::time::timeout(
4799                std::time::Duration::from_secs(5),
4800                throttle::open_file_permit(),
4801            )
4802            .await?;
4803            drop(permit);
4804            assert!(waiting && source_was_open?);
4805            assert!(source_closed_while_outer_admitted?);
4806            assert!(outer_admission_retained);
4807            assert_eq!(
4808                drop_observation?,
4809                Some(QueuedFdDropObservation {
4810                    fd_was_closed: true,
4811                    admission_was_retained: true,
4812                })
4813            );
4814            assert_eq!(submissions.count(), 0);
4815            assert_eq!(samples.metadata_count(), 0);
4816            assert!(!called.load(std::sync::atomic::Ordering::SeqCst));
4817            assert!(!destination.exists());
4818            Ok(())
4819        }
4820
4821        #[tokio::test]
4822        async fn panicking_claimed_file_continuation_closes_both_fds_before_admission()
4823        -> anyhow::Result<()> {
4824            use std::os::unix::fs::PermissionsExt as _;
4825            let tmp = tempfile::tempdir()?;
4826            let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
4827            let destination = tmp.path().join("destination");
4828            let source = tempfile::tempfile()?;
4829            let source_probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
4830            let source_observation = Arc::new(std::sync::Mutex::new(None));
4831            let destination_observation = Arc::new(std::sync::Mutex::new(None));
4832            let payload_destination_observation = Arc::clone(&destination_observation);
4833            let source_capture = QueuedFdCapture {
4834                file: Some(source),
4835                probe: source_probe,
4836                observation: Arc::clone(&source_observation),
4837            };
4838            let limits = testutils::AdmissionLimit::new().await;
4839            limits.set_files_in_flight(1);
4840            let guard = throttle::open_file_permit().await;
4841            let (started_tx, started_rx) = tokio::sync::oneshot::channel();
4842            let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
4843            let mut work = Box::pin(with_fd_admission(guard.admission(), async move {
4844                root.create_file_and_then(
4845                    OsStr::new("destination"),
4846                    move |created| -> std::io::Result<()> {
4847                        let _source = source_capture;
4848                        let file = created?;
4849                        let probe = testutils::FdIdentityProbe::capture(file.as_raw_fd())?;
4850                        let _destination = QueuedFdCapture {
4851                            file: Some(file),
4852                            probe,
4853                            observation: payload_destination_observation,
4854                        };
4855                        let _ = started_tx.send(probe);
4856                        let _ = release_rx.recv();
4857                        panic!("injected claimed file-continuation panic");
4858                    },
4859                )
4860                .await
4861            }));
4862            let pending = futures::poll!(work.as_mut()).is_pending();
4863            drop(guard);
4864            let started = tokio::time::timeout(std::time::Duration::from_secs(5), started_rx).await;
4865            let source_was_open = source_probe.original_is_closed().map(|closed| !closed);
4866            let destination_was_open = match &started {
4867                Ok(Ok(probe)) => Some(probe.original_is_closed().map(|closed| !closed)),
4868                _ => None,
4869            };
4870            let admission_was_retained = throttle::open_file_permit().now_or_never().is_none();
4871            drop(release_tx);
4872            let result = work.await;
4873            let destination_probe = started??;
4874            assert!(pending);
4875            assert!(source_was_open? && destination_was_open.transpose()?.unwrap());
4876            assert!(admission_was_retained);
4877            assert!(
4878                result.is_err(),
4879                "claimed continuation panic must fail the waiter"
4880            );
4881            assert!(source_probe.original_is_closed()? && destination_probe.original_is_closed()?);
4882            for observation in [source_observation, destination_observation] {
4883                assert_eq!(
4884                    observation.lock().unwrap().take().transpose()?,
4885                    Some(QueuedFdDropObservation {
4886                        fd_was_closed: true,
4887                        admission_was_retained: true,
4888                    })
4889                );
4890            }
4891            assert_eq!(
4892                std::fs::metadata(destination)?.permissions().mode() & 0o7777,
4893                DST_FILE_CREATE_MODE
4894            );
4895            let permit = tokio::time::timeout(
4896                std::time::Duration::from_secs(5),
4897                throttle::open_file_permit(),
4898            )
4899            .await?;
4900            drop(permit);
4901            Ok(())
4902        }
4903
4904        /// Dropping a queued blocking waiter must synchronously close its captured fd and return
4905        /// admission before the occupied worker is released, without ever running user work.
4906        #[test]
4907        fn dropping_queued_blocking_work_closes_fd_before_returning_admission() -> anyhow::Result<()>
4908        {
4909            let runtime = tokio::runtime::Builder::new_multi_thread()
4910                .worker_threads(1)
4911                .max_blocking_threads(1)
4912                .enable_all()
4913                .build()?;
4914            runtime.block_on(async {
4915                let (started_tx, started_rx) = tokio::sync::oneshot::channel();
4916                assert_queued_owner_closes_before_admission(|owner| async move {
4917                    run_fd_admitted_blocking(move || {
4918                        let _owner = owner;
4919                        let _ = started_tx.send(());
4920                        Ok(())
4921                    })
4922                    .await
4923                })
4924                .await?;
4925                assert!(
4926                    matches!(
4927                        tokio::time::timeout(std::time::Duration::from_secs(5), started_rx).await,
4928                        Ok(Err(_))
4929                    ),
4930                    "the dropped queued blocking work started"
4931                );
4932                Ok(())
4933            })
4934        }
4935
4936        /// Cancelling an unprobed blocking waiter must retain any ambient fd admission until its
4937        /// detached closure releases the descriptor it owns. Directory enumeration uses this
4938        /// lower-level boundary because `getdents` is deliberately excluded from congestion
4939        /// probing.
4940        #[tokio::test]
4941        async fn cancelled_unprobed_waiter_keeps_admission_until_fd_owner_finishes()
4942        -> anyhow::Result<()> {
4943            let root = crate::testutils::create_temp_dir().await?;
4944            let file_path = root.join("held-unprobed");
4945            tokio::fs::write(&file_path, b"x").await?;
4946            let admission = crate::testutils::AdmissionLimit::new().await;
4947            admission.set_files_in_flight(1);
4948            let open_file_guard = throttle::open_file_permit().await;
4949            let (started_tx, started_rx) = tokio::sync::oneshot::channel();
4950            let (release_tx, release_rx) = std::sync::mpsc::channel();
4951            let (completion, completion_rx) = crate::testutils::CompletionSignal::new();
4952            let task = tokio::spawn(async move {
4953                let admission = open_file_guard.admission();
4954                with_fd_admission(admission, async move {
4955                    let _open_file_guard = open_file_guard;
4956                    run_fd_admitted_blocking(move || {
4957                        let _completion = completion;
4958                        let _file = std::fs::File::open(file_path)?;
4959                        let _ = started_tx.send(());
4960                        release_rx.recv().map_err(std::io::Error::other)?;
4961                        Ok(())
4962                    })
4963                    .await
4964                })
4965                .await
4966            });
4967            let started_result = started_rx.await;
4968            task.abort();
4969            let waiter_was_cancelled = matches!(task.await, Err(error) if error.is_cancelled());
4970
4971            let mut second_permit = Box::pin(throttle::open_file_permit());
4972            let admission_was_retained =
4973                started_result.is_ok() && futures::poll!(second_permit.as_mut()).is_pending();
4974            let release_result = release_tx.send(());
4975            let (completion_result, permit) = crate::testutils::await_completion_and_capacity(
4976                completion_rx,
4977                second_permit.as_mut(),
4978            )
4979            .await;
4980            started_result.context("detached unprobed work did not start")?;
4981            release_result.context("detached unprobed work ended before its release")?;
4982            completion_result.context("detached unprobed work did not report completion")?;
4983            drop(permit);
4984            assert!(waiter_was_cancelled);
4985            assert!(
4986                admission_was_retained,
4987                "cancelling the waiter released admission while detached work held an fd"
4988            );
4989            Ok(())
4990        }
4991
4992        /// Cancelling a metadata waiter must not release admission while its detached blocking
4993        /// closure still owns a file descriptor.
4994        #[tokio::test]
4995        async fn cancelled_metadata_waiter_keeps_admission_until_fd_owner_finishes()
4996        -> anyhow::Result<()> {
4997            let root = crate::testutils::create_temp_dir().await?;
4998            let file_path = root.join("held");
4999            tokio::fs::write(&file_path, b"x").await?;
5000            let admission = crate::testutils::AdmissionLimit::new().await;
5001            admission.set_files_in_flight(1);
5002            let stat_resource =
5003                throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
5004            admission.set_max_ops_in_flight(stat_resource, 1);
5005            let open_file_guard = throttle::open_file_permit().await;
5006            let (started_tx, started_rx) = tokio::sync::oneshot::channel();
5007            let (release_tx, release_rx) = std::sync::mpsc::channel();
5008            let (completion, completion_rx) = crate::testutils::CompletionSignal::new();
5009            let task = tokio::spawn(async move {
5010                let admission = open_file_guard.admission();
5011                with_fd_admission(admission, async move {
5012                    let _open_file_guard = open_file_guard;
5013                    run_metadata_probed_blocking(
5014                        congestion::Side::Source,
5015                        congestion::MetadataOp::Stat,
5016                        move || {
5017                            let _completion = completion;
5018                            let _file = std::fs::File::open(file_path)?;
5019                            let _ = started_tx.send(());
5020                            release_rx.recv().map_err(std::io::Error::other)?;
5021                            Ok(())
5022                        },
5023                    )
5024                    .await
5025                })
5026                .await
5027            });
5028            let started_result = started_rx.await;
5029            task.abort();
5030            let waiter_was_cancelled = matches!(task.await, Err(error) if error.is_cancelled());
5031
5032            let second_permit = throttle::open_file_permit();
5033            tokio::pin!(second_permit);
5034            let admission_was_retained =
5035                started_result.is_ok() && futures::poll!(second_permit.as_mut()).is_pending();
5036            let second_stat_permit = throttle::ops_in_flight_permit(stat_resource);
5037            tokio::pin!(second_stat_permit);
5038            let metadata_was_retained =
5039                started_result.is_ok() && futures::poll!(second_stat_permit.as_mut()).is_pending();
5040            let release_result = release_tx.send(());
5041            let (completion_result, (permit, stat_permit)) =
5042                crate::testutils::await_completion_and_capacity(
5043                    completion_rx,
5044                    futures::future::join(second_permit.as_mut(), second_stat_permit.as_mut()),
5045                )
5046                .await;
5047            started_result.context("detached metadata work did not start")?;
5048            release_result.context("detached metadata work ended before its release")?;
5049            completion_result.context("detached metadata work did not report completion")?;
5050            drop(permit);
5051            drop(stat_permit);
5052            assert!(waiter_was_cancelled);
5053            assert!(
5054                admission_was_retained,
5055                "cancelling the waiter released admission while detached work held an fd"
5056            );
5057            assert!(
5058                metadata_was_retained,
5059                "cancelling the waiter released metadata capacity while its syscall was live"
5060            );
5061            Ok(())
5062        }
5063
5064        /// A detached blocking task's returned fd must be dropped before its admission lease. The
5065        /// fd lives in the abandoned task output rather than inside the syscall closure itself.
5066        #[tokio::test]
5067        async fn abandoned_metadata_output_keeps_admission_until_returned_fd_drops()
5068        -> anyhow::Result<()> {
5069            assert_abandoned_output_closes_before_admission(|owner| async move {
5070                run_metadata_probed_blocking(
5071                    congestion::Side::Source,
5072                    congestion::MetadataOp::Stat,
5073                    move || {
5074                        let _visit = resource_tests::gate_opened_descriptor(owner.as_raw_fd())?;
5075                        Ok(owner)
5076                    },
5077                )
5078                .await
5079            })
5080            .await
5081        }
5082
5083        /// An abandoned unprobed blocking result must drop its fd owner before returning the
5084        /// strong admission lease. The data-copy path uses this lower-level runner directly.
5085        #[tokio::test]
5086        async fn abandoned_unprobed_output_keeps_admission_until_returned_fd_drops()
5087        -> anyhow::Result<()> {
5088            assert_abandoned_output_closes_before_admission(|owner| async move {
5089                run_fd_admitted_blocking(move || {
5090                    let _visit = resource_tests::gate_opened_descriptor(owner.as_raw_fd())?;
5091                    Ok(owner)
5092                })
5093                .await
5094            })
5095            .await
5096        }
5097    }
5098
5099    #[test]
5100    fn a_run_that_asked_for_nothing_wants_no_root_acl_notice() {
5101        // the gate this whole type exists for: a copy at the shipped default already drops uid,
5102        // gid, timestamps and the special mode bits silently, so an ACL notice there is advice
5103        // about a completeness nobody claimed — and it must cost nothing, kind unknown included.
5104        let notice = RootAclNotice::for_preserve(&crate::preserve::preserve_none());
5105        assert!(!notice.wanted);
5106        for kind in EVERY_KIND {
5107            assert!(
5108                !notice.could_warn_for_strict(kind, false),
5109                "a {kind:?} root warned under settings that asked for no preservation"
5110            );
5111        }
5112    }
5113
5114    #[test]
5115    fn strict_resolution_arms_the_notice_on_its_own() {
5116        // `--require-toctou-safe` is a request ABOUT permissions whatever `--preserve-settings`
5117        // says, and the two flags deliberately do not imply each other, so it must arm the notice
5118        // by itself — with its own wording, which `warn_root_acl` picks the same way.
5119        let notice = RootAclNotice::for_preserve(&crate::preserve::preserve_none());
5120        assert!(notice.could_warn_for_strict(EntryKind::Dir, true));
5121        assert!(notice.could_warn_for_strict(EntryKind::File, true));
5122    }
5123
5124    #[test]
5125    fn the_notice_consults_the_setting_for_the_roots_own_kind() {
5126        // `f:acl` and `d:acl` are independent. Getting this wrong is silent in both directions:
5127        // one way it warns about an ACL the copy is carrying across, the other it stays quiet
5128        // about one being dropped.
5129        let file_only = RootAclNotice {
5130            wanted: true,
5131            file_acl_preserved: true,
5132            dir_acl_preserved: false,
5133        };
5134        assert!(!file_only.could_warn_for_strict(EntryKind::File, false));
5135        assert!(file_only.could_warn_for_strict(EntryKind::Dir, false));
5136        assert!(
5137            file_only.could_warn(),
5138            "a directory root can still warn, so the kind-unknown pre-check must not skip the probe"
5139        );
5140    }
5141
5142    #[test]
5143    fn a_root_that_cannot_carry_an_acl_never_warns() {
5144        // the kernel has no symlink ACL, and a special file is not copied as an object whose
5145        // permissions rcp reproduces — so neither reaches the probe, armed or not
5146        let armed = RootAclNotice {
5147            wanted: true,
5148            file_acl_preserved: false,
5149            dir_acl_preserved: false,
5150        };
5151        for kind in [EntryKind::Symlink, EntryKind::Special] {
5152            assert!(!armed.could_warn_for_strict(kind, true));
5153        }
5154    }
5155
5156    #[test]
5157    fn preserving_both_kinds_acls_leaves_nothing_to_warn_about() {
5158        let notice = RootAclNotice::for_preserve(&crate::preserve::preserve_all_with_acls());
5159        assert!(notice.wanted, "`all+acl` did ask for preservation");
5160        assert!(
5161            !notice.could_warn(),
5162            "both kinds' ACLs are carried across, so even an armed run has nothing to say — and \
5163             must not pay the probe to find that out"
5164        );
5165    }
5166
5167    #[tokio::test]
5168    async fn child_classifies_file_dir_symlink_and_rejects_nofollow() -> anyhow::Result<()> {
5169        let tmp = testutils::setup_test_dir().await?;
5170        // setup_test_dir() returns the temp dir; the fixture lives at tmp/foo/
5171        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
5172        assert_eq!(
5173            root.child(OsStr::new("0.txt")).await?.kind(),
5174            EntryKind::File
5175        );
5176        assert_eq!(root.child(OsStr::new("bar")).await?.kind(), EntryKind::Dir);
5177        tokio::fs::symlink("0.txt", tmp.join("foo/lnk")).await?;
5178        assert_eq!(
5179            root.child(OsStr::new("lnk")).await?.kind(),
5180            EntryKind::Symlink
5181        );
5182        // open_dir on a symlinked "dir" must fail closed (ELOOP/ENOTDIR), never follow
5183        tokio::fs::symlink("/etc", tmp.join("foo/evil")).await?;
5184        assert!(root.open_dir(OsStr::new("evil")).await.is_err());
5185        Ok(())
5186    }
5187
5188    #[tokio::test]
5189    async fn open_dir_succeeds_on_real_directory() -> anyhow::Result<()> {
5190        let tmp = testutils::setup_test_dir().await?;
5191        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
5192        // bar is a real directory; open_dir must succeed and yield a usable Dir
5193        let bar = root.open_dir(OsStr::new("bar")).await?;
5194        // and the resulting Dir is functional: it can classify its own children
5195        assert_eq!(
5196            bar.child(OsStr::new("1.txt")).await?.kind(),
5197            EntryKind::File
5198        );
5199        Ok(())
5200    }
5201
5202    #[cfg_attr(
5203        rcp_nix_sandbox,
5204        ignore = "Nix sandbox cannot change ownership or set-id modes"
5205    )]
5206    #[tokio::test]
5207    async fn secure_as_copier_takes_ownership_restricts_mode_and_preserves_gid()
5208    -> anyhow::Result<()> {
5209        use std::os::unix::fs::PermissionsExt as _;
5210        let tmp = testutils::setup_test_dir().await?;
5211        let root =
5212            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
5213
5214        // a plain reused subdir locked down to 0o700: ownership becomes the copier, the mode is
5215        // exactly 0o700, and the gid is unchanged (no race means no gid write at all).
5216        let plain = root.make_dir(OsStr::new("reused_plain"), 0o755).await?;
5217        let before = plain.meta().await?;
5218        plain
5219            .secure_as_copier(0o700, before.uid(), before.gid())
5220            .await?;
5221        let after = plain.meta().await?;
5222        assert_eq!(
5223            after.permissions().mode() & 0o7777,
5224            0o700,
5225            "mode restricted"
5226        );
5227        assert_eq!(
5228            after.uid(),
5229            nix::unistd::geteuid().as_raw(),
5230            "owned by copier"
5231        );
5232        assert_eq!(after.gid(), before.gid(), "gid unchanged when it matches");
5233
5234        // a setgid reused subdir: BOTH the S_ISGID bit and the gid value must survive the
5235        // lockdown, since children created during the copy inherit the directory's group.
5236        let sg = root.make_dir(OsStr::new("reused_setgid"), 0o755).await?;
5237        std::fs::set_permissions(
5238            tmp.join("foo/reused_setgid"),
5239            std::fs::Permissions::from_mode(0o2755),
5240        )?;
5241        let sg_before = sg.meta().await?;
5242        assert_eq!(
5243            sg_before.permissions().mode() & 0o2000,
5244            0o2000,
5245            "test setup: S_ISGID is set before lockdown"
5246        );
5247        sg.secure_as_copier(0o2700, sg_before.uid(), sg_before.gid())
5248            .await?;
5249        let sg_after = sg.meta().await?;
5250        assert_eq!(
5251            sg_after.permissions().mode() & 0o7777,
5252            0o2700,
5253            "S_ISGID + 0o700 both preserved"
5254        );
5255        assert_eq!(
5256            sg_after.gid(),
5257            sg_before.gid(),
5258            "gid preserved under setgid"
5259        );
5260        Ok(())
5261    }
5262
5263    // FIX A (PR #247 review): `open_parent_dir` resolves a TRUSTED command-line parent prefix
5264    // following symlinks (the final component IS followed), while `open_root_dir` keeps the operand
5265    // entry `O_NOFOLLOW` and descendants stay hardened. This pins the parent-prefix-vs-operand
5266    // distinction and proves the hardening below the followed prefix is unchanged.
5267    #[tokio::test]
5268    async fn open_parent_dir_follows_symlinked_prefix_but_descendants_stay_hardened()
5269    -> anyhow::Result<()> {
5270        let tmp = testutils::setup_test_dir().await?;
5271        // a symlink-to-dir standing in for a trusted parent prefix component.
5272        tokio::fs::symlink("foo", tmp.join("foo_link")).await?;
5273        // open_parent_dir FOLLOWS the symlinked final component into the real `foo` directory,
5274        // yielding a TrustedDir; into_tree() crosses into the hardened tree below it.
5275        let parent = Dir::open_parent_dir(&tmp.join("foo_link"), congestion::Side::Source).await?;
5276        let tree = parent.into_tree();
5277        // the followed dir is functional: it sees `foo`'s real children.
5278        assert_eq!(
5279            tree.child(OsStr::new("0.txt")).await?.kind(),
5280            EntryKind::File
5281        );
5282        // open_root_dir on the SAME symlinked path (dereference=false) must instead fail closed —
5283        // it `O_NOFOLLOW`s the final component (the operand-entry contract), proving the two entry
5284        // points differ exactly at the final-component follow decision.
5285        assert!(
5286            Dir::open_root_dir(&tmp.join("foo_link"), false, congestion::Side::Source)
5287                .await
5288                .is_err()
5289        );
5290        // hardening below the followed prefix is UNCHANGED: a symlinked child reached via the
5291        // followed parent still fails closed (O_NOFOLLOW) rather than being followed.
5292        tokio::fs::symlink("/etc", tmp.join("foo/evil_below")).await?;
5293        assert!(tree.open_dir(OsStr::new("evil_below")).await.is_err());
5294        Ok(())
5295    }
5296
5297    #[tokio::test]
5298    async fn rejects_multi_component_names() -> anyhow::Result<()> {
5299        let tmp = testutils::setup_test_dir().await?;
5300        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
5301        // names with a path separator could traverse an intermediate symlink, so
5302        // they are rejected with EINVAL before any syscall (release-safe check)
5303        for bad in ["bar/1.txt", "..", ".", ""] {
5304            let child_err = root.child(OsStr::new(bad)).await.unwrap_err();
5305            assert_eq!(child_err.raw_os_error(), Some(libc::EINVAL));
5306            let dir_err = root.open_dir(OsStr::new(bad)).await.unwrap_err();
5307            assert_eq!(dir_err.raw_os_error(), Some(libc::EINVAL));
5308            let file_err = root.open_file_read(OsStr::new(bad)).await.unwrap_err();
5309            assert_eq!(file_err.raw_os_error(), Some(libc::EINVAL));
5310            let create_err = root.create_file(OsStr::new(bad)).await.unwrap_err();
5311            assert_eq!(create_err.raw_os_error(), Some(libc::EINVAL));
5312        }
5313        Ok(())
5314    }
5315
5316    // Regression for the spawn_blocking cancellation soundness bug: the Dir's fd
5317    // lives behind an Arc that each operation clones into its closure, so an op
5318    // stays sound even after the originating Dir is dropped. We model the
5319    // detached-closure case by cloning a Dir, dropping the original, and
5320    // confirming the clone still opens children correctly.
5321    #[tokio::test]
5322    async fn operations_remain_valid_after_original_dir_dropped() -> anyhow::Result<()> {
5323        let tmp = testutils::setup_test_dir().await?;
5324        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
5325        // clone the underlying Arc-held fd into a second Dir, then drop the original
5326        let shared = Dir {
5327            fd: root.fd.clone(),
5328            side: root.side,
5329            children_may_inherit: Arc::new(std::sync::atomic::AtomicBool::new(true)),
5330        };
5331        drop(root);
5332        // the shared handle's open file description is still alive; ops succeed
5333        assert_eq!(
5334            shared.child(OsStr::new("0.txt")).await?.kind(),
5335            EntryKind::File
5336        );
5337        let bar = shared.open_dir(OsStr::new("bar")).await?;
5338        assert_eq!(
5339            bar.child(OsStr::new("2.txt")).await?.kind(),
5340            EntryKind::File
5341        );
5342        Ok(())
5343    }
5344
5345    // open_file_read: verify that a regular file can be opened, metadata size is
5346    // correct, and the returned File is readable.
5347    #[tokio::test]
5348    async fn open_file_read_reads_regular_file() -> anyhow::Result<()> {
5349        let tmp = testutils::setup_test_dir().await?;
5350        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
5351        let (mut file, meta) = root.open_file_read(OsStr::new("0.txt")).await?;
5352        // "0.txt" contains the single byte "0"
5353        assert_eq!(meta.size(), 1);
5354        let mut buf = String::new();
5355        file.read_to_string(&mut buf)?;
5356        assert_eq!(buf, "0");
5357        Ok(())
5358    }
5359
5360    // open_file_read: a FIFO must not cause open to block (O_NONBLOCK) AND the
5361    // S_ISREG check must reject it, so the call returns Err without hanging.
5362    #[tokio::test]
5363    async fn open_file_read_rejects_fifo_without_blocking() -> anyhow::Result<()> {
5364        let tmp = testutils::setup_test_dir().await?;
5365        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
5366        let fifo_path = tmp.join("foo/test.fifo");
5367        nix::unistd::mkfifo(
5368            &fifo_path,
5369            nix::sys::stat::Mode::S_IRUSR | nix::sys::stat::Mode::S_IWUSR,
5370        )?;
5371        // the call must return (not block) within the timeout, and must be an Err
5372        let result = tokio::time::timeout(
5373            std::time::Duration::from_secs(5),
5374            root.open_file_read(OsStr::new("test.fifo")),
5375        )
5376        .await;
5377        assert!(result.is_ok(), "open_file_read blocked on FIFO (timed out)");
5378        assert!(
5379            result.unwrap().is_err(),
5380            "open_file_read must reject a FIFO"
5381        );
5382        Ok(())
5383    }
5384
5385    // open_file_read: a symlink must be rejected (ELOOP from O_NOFOLLOW).
5386    #[tokio::test]
5387    async fn open_file_read_rejects_symlink() -> anyhow::Result<()> {
5388        let tmp = testutils::setup_test_dir().await?;
5389        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
5390        // create a symlink pointing to a real file
5391        tokio::fs::symlink("0.txt", tmp.join("foo/link_to_0")).await?;
5392        let result = root.open_file_read(OsStr::new("link_to_0")).await;
5393        assert!(result.is_err(), "open_file_read must reject a symlink");
5394        Ok(())
5395    }
5396
5397    // create_file: successfully creates a new writable file.
5398    #[tokio::test]
5399    async fn create_file_creates_new_writable_file() -> anyhow::Result<()> {
5400        let tmp = testutils::setup_test_dir().await?;
5401        // use a dest-side dir for the write target
5402        let root =
5403            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
5404        let mut file = root.create_file(OsStr::new("new.txt")).await?;
5405        use std::io::Write;
5406        file.write_all(b"hello safedir")?;
5407        drop(file);
5408        // re-open via std and verify the content
5409        let content = std::fs::read(tmp.join("foo/new.txt"))?;
5410        assert_eq!(content, b"hello safedir");
5411        Ok(())
5412    }
5413
5414    // create_file: fails with EEXIST when the file already exists.
5415    #[tokio::test]
5416    async fn create_file_fails_if_exists() -> anyhow::Result<()> {
5417        let tmp = testutils::setup_test_dir().await?;
5418        let root =
5419            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
5420        // "0.txt" already exists in the fixture
5421        let err = root.create_file(OsStr::new("0.txt")).await.unwrap_err();
5422        assert_eq!(
5423            err.raw_os_error(),
5424            Some(libc::EEXIST),
5425            "expected EEXIST, got {err:#}"
5426        );
5427        Ok(())
5428    }
5429
5430    // make_dir: creates the directory and returns a usable Dir handle.
5431    #[tokio::test]
5432    async fn make_dir_creates_and_returns_usable_dir() -> anyhow::Result<()> {
5433        let tmp = testutils::setup_test_dir().await?;
5434        let root =
5435            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
5436        let sub = root.make_dir(OsStr::new("sub"), 0o755).await?;
5437        // the returned Dir must be usable: create a file inside it
5438        sub.create_file(OsStr::new("child.txt")).await?;
5439        // and read_entries on the sub dir must show that file
5440        let entries = sub.read_entries().await?;
5441        let names: Vec<_> = entries
5442            .iter()
5443            .map(|(n, _)| n.to_string_lossy().into_owned())
5444            .collect();
5445        assert!(
5446            names.contains(&"child.txt".to_string()),
5447            "child.txt not found in {names:?}"
5448        );
5449        Ok(())
5450    }
5451
5452    // make_dir: multi-component names must be rejected with EINVAL.
5453    #[tokio::test]
5454    async fn make_dir_rejects_multi_component_names() -> anyhow::Result<()> {
5455        let tmp = testutils::setup_test_dir().await?;
5456        let root =
5457            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
5458        for bad in ["a/b", "..", ".", ""] {
5459            let err = root.make_dir(OsStr::new(bad), 0o755).await.unwrap_err();
5460            assert_eq!(
5461                err.raw_os_error(),
5462                Some(libc::EINVAL),
5463                "expected EINVAL for {:?}, got {err:#}",
5464                bad
5465            );
5466        }
5467        Ok(())
5468    }
5469
5470    // read_entries: returns all entries with correct d_type hints.
5471    #[tokio::test]
5472    async fn read_entries_lists_children_with_dtype_hints() -> anyhow::Result<()> {
5473        use std::collections::HashMap;
5474        let tmp = testutils::setup_test_dir().await?;
5475        // baz contains: 4.txt (file), 5.txt (symlink), 6.txt (symlink)
5476        // use bar which has only files; instead build a custom fixture in foo
5477        let fixture = tmp.join("foo/fixture_dir");
5478        tokio::fs::create_dir(&fixture).await?;
5479        tokio::fs::write(fixture.join("afile.txt"), "x").await?;
5480        tokio::fs::create_dir(fixture.join("asubdir")).await?;
5481        tokio::fs::symlink("afile.txt", fixture.join("alink")).await?;
5482
5483        let root = Dir::open_root_dir(&fixture, false, congestion::Side::Source).await?;
5484        let entries = root.read_entries().await?;
5485        let map: HashMap<String, Option<EntryKind>> = entries
5486            .into_iter()
5487            .map(|(n, k)| (n.to_string_lossy().into_owned(), k))
5488            .collect();
5489
5490        assert_eq!(map.len(), 3, "expected 3 entries, got {map:?}");
5491        assert_eq!(
5492            map.get("afile.txt"),
5493            Some(&Some(EntryKind::File)),
5494            "afile.txt wrong"
5495        );
5496        assert_eq!(
5497            map.get("asubdir"),
5498            Some(&Some(EntryKind::Dir)),
5499            "asubdir wrong"
5500        );
5501        assert_eq!(
5502            map.get("alink"),
5503            Some(&Some(EntryKind::Symlink)),
5504            "alink wrong"
5505        );
5506        Ok(())
5507    }
5508
5509    // read_entries: calling it twice on the same Dir must succeed (fd not consumed).
5510    #[tokio::test]
5511    async fn read_entries_does_not_close_self_fd() -> anyhow::Result<()> {
5512        let tmp = testutils::setup_test_dir().await?;
5513        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
5514        // first call
5515        let first = root.read_entries().await?;
5516        assert!(!first.is_empty(), "first read_entries returned empty");
5517        // second call on the SAME Dir must yield the identical entry set, not
5518        // just an equal count. read_entries dups a fd that shares the directory
5519        // read offset, so absent nix's rewinddir-on-completion this second call
5520        // would see an empty (or partial) listing.
5521        let second = root.read_entries().await?;
5522        let mut first_names: Vec<_> = first.iter().map(|(name, _)| name.clone()).collect();
5523        let mut second_names: Vec<_> = second.iter().map(|(name, _)| name.clone()).collect();
5524        first_names.sort();
5525        second_names.sort();
5526        assert_eq!(
5527            first_names, second_names,
5528            "second read_entries differs from first"
5529        );
5530        // also prove child() still works on the same Dir
5531        root.child(OsStr::new("0.txt")).await?;
5532        Ok(())
5533    }
5534
5535    // create_file: refuses to follow or clobber an existing symlink.
5536    #[tokio::test]
5537    async fn create_file_refuses_existing_symlink() -> anyhow::Result<()> {
5538        let tmp = testutils::setup_test_dir().await?;
5539        let root =
5540            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
5541        // plant a symlink pointing at a non-existent target
5542        let link_path = tmp.join("foo/evil_link");
5543        let target_path = tmp.join("foo/should_not_be_created");
5544        tokio::fs::symlink(&target_path, &link_path).await?;
5545        // create_file must fail, not follow the symlink and create the target
5546        let err = root.create_file(OsStr::new("evil_link")).await.unwrap_err();
5547        // O_CREAT|O_EXCL returns EEXIST on an existing symlink without following it
5548        assert_eq!(
5549            err.raw_os_error(),
5550            Some(libc::EEXIST),
5551            "expected EEXIST, got {err:#}"
5552        );
5553        // the symlink target must NOT have been created
5554        assert!(
5555            !target_path.exists(),
5556            "symlink target was unexpectedly created"
5557        );
5558        Ok(())
5559    }
5560
5561    // unlink_at: removes a regular file and confirms it is gone.
5562    #[tokio::test]
5563    async fn unlink_at_removes_file() -> anyhow::Result<()> {
5564        let tmp = testutils::setup_test_dir().await?;
5565        let root =
5566            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
5567        // "0.txt" exists in the fixture
5568        root.unlink_at(OsStr::new("0.txt")).await?;
5569        // afterwards child() must fail with ENOENT
5570        let err = root.child(OsStr::new("0.txt")).await.unwrap_err();
5571        assert_eq!(
5572            err.raw_os_error(),
5573            Some(libc::ENOENT),
5574            "expected ENOENT after unlink, got {err:#}"
5575        );
5576        Ok(())
5577    }
5578
5579    // unlink_at: removes the symlink itself, not its target.
5580    #[tokio::test]
5581    async fn unlink_at_on_symlink_removes_link_not_target() -> anyhow::Result<()> {
5582        let tmp = testutils::setup_test_dir().await?;
5583        let root =
5584            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
5585        // create a sentinel file with content, then symlink to it
5586        tokio::fs::write(tmp.join("foo/sentinel.txt"), b"alive").await?;
5587        tokio::fs::symlink("sentinel.txt", tmp.join("foo/lnk")).await?;
5588        // unlink the link
5589        root.unlink_at(OsStr::new("lnk")).await?;
5590        // link is gone
5591        let err = root.child(OsStr::new("lnk")).await.unwrap_err();
5592        assert_eq!(
5593            err.raw_os_error(),
5594            Some(libc::ENOENT),
5595            "expected ENOENT for removed link, got {err:#}"
5596        );
5597        // sentinel target still exists with content
5598        let content = tokio::fs::read(tmp.join("foo/sentinel.txt")).await?;
5599        assert_eq!(content, b"alive", "sentinel.txt was unexpectedly removed");
5600        Ok(())
5601    }
5602
5603    // rmdir_at: removes an empty directory; rejects non-empty (ENOTEMPTY) and a
5604    // regular file (ENOTDIR).
5605    #[tokio::test]
5606    async fn rmdir_at_removes_empty_dir_and_rejects_nonempty() -> anyhow::Result<()> {
5607        let tmp = testutils::setup_test_dir().await?;
5608        let root =
5609            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
5610        // create an empty subdirectory and remove it
5611        tokio::fs::create_dir(tmp.join("foo/empty_sub")).await?;
5612        root.rmdir_at(OsStr::new("empty_sub")).await?;
5613        let err = root.child(OsStr::new("empty_sub")).await.unwrap_err();
5614        assert_eq!(
5615            err.raw_os_error(),
5616            Some(libc::ENOENT),
5617            "expected ENOENT after rmdir, got {err:#}"
5618        );
5619        // "bar" is non-empty in the fixture → ENOTEMPTY
5620        let err = root.rmdir_at(OsStr::new("bar")).await.unwrap_err();
5621        assert_eq!(
5622            err.raw_os_error(),
5623            Some(libc::ENOTEMPTY),
5624            "expected ENOTEMPTY for non-empty dir, got {err:#}"
5625        );
5626        // "0.txt" is a regular file → ENOTDIR
5627        let err = root.rmdir_at(OsStr::new("0.txt")).await.unwrap_err();
5628        assert_eq!(
5629            err.raw_os_error(),
5630            Some(libc::ENOTDIR),
5631            "expected ENOTDIR for regular file, got {err:#}"
5632        );
5633        Ok(())
5634    }
5635
5636    // symlink_at: creates a symlink and returns a Handle with kind Symlink;
5637    // read_link_at then returns the original target path.
5638    #[tokio::test]
5639    async fn symlink_at_creates_link_and_returns_pinned_handle() -> anyhow::Result<()> {
5640        let tmp = testutils::setup_test_dir().await?;
5641        let root =
5642            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
5643        let target = std::path::Path::new("some/arbitrary/target");
5644        let handle = root.symlink_at(OsStr::new("mylink"), target).await?;
5645        assert_eq!(
5646            handle.kind(),
5647            EntryKind::Symlink,
5648            "symlink_at must return a Symlink handle"
5649        );
5650        // read_link_at must return the same target
5651        let read_back = root.read_link_at(OsStr::new("mylink")).await?;
5652        assert_eq!(
5653            read_back, target,
5654            "read_link_at returned wrong target: {read_back:?}"
5655        );
5656        Ok(())
5657    }
5658
5659    // read_link_handle reads the target inode-exact from the pinned O_PATH symlink handle (the
5660    // empty-path readlinkat form), so the target pairs with `handle.meta()` from the SAME fd. A
5661    // non-symlink handle is rejected (EINVAL).
5662    #[tokio::test]
5663    async fn read_link_handle_reads_target_from_pinned_handle() -> anyhow::Result<()> {
5664        let tmp = testutils::setup_test_dir().await?;
5665        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
5666        let target = std::path::Path::new("some/arbitrary/target");
5667        tokio::fs::symlink(target, tmp.join("foo/mylink")).await?;
5668        // classify the link, then read its target through that same pinned handle.
5669        let handle = root.child(OsStr::new("mylink")).await?;
5670        assert_eq!(handle.kind(), EntryKind::Symlink);
5671        let read_back = read_link_handle(&handle, congestion::Side::Source).await?;
5672        assert_eq!(read_back, target, "wrong target: {read_back:?}");
5673        // a non-symlink handle (a regular file) is rejected (the empty-path readlinkat form requires
5674        // a symlink fd; the kernel returns an error rather than a target). Callers only ever invoke
5675        // this on a Symlink-classified handle, so this is the defensive path.
5676        let file_handle = root.child(OsStr::new("0.txt")).await?;
5677        assert!(
5678            read_link_handle(&file_handle, congestion::Side::Source)
5679                .await
5680                .is_err(),
5681            "read_link_handle on a non-symlink must fail"
5682        );
5683        Ok(())
5684    }
5685
5686    // Handle::read_symlink returns target AND metadata from the one pinned O_PATH fd, so they are a
5687    // faithful pair (the symlink analogue of open_file_read).
5688    #[tokio::test]
5689    async fn read_symlink_returns_target_and_meta_from_one_handle() -> anyhow::Result<()> {
5690        use crate::preserve::Metadata as _;
5691        let tmp = testutils::setup_test_dir().await?;
5692        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
5693        let target = std::path::Path::new("some/target");
5694        tokio::fs::symlink(target, tmp.join("foo/lnk")).await?;
5695        let handle = root.child(OsStr::new("lnk")).await?;
5696        let (read_target, meta) = handle.read_symlink(congestion::Side::Source).await?;
5697        assert_eq!(read_target, target);
5698        // metadata is the symlink's own, from the same handle.
5699        assert_eq!(meta.uid(), handle.meta().uid());
5700        assert_eq!(meta.mtime(), handle.meta().mtime());
5701        Ok(())
5702    }
5703
5704    // Dir::meta fstats the directory's own held fd (the fd whose contents we enumerate).
5705    #[tokio::test]
5706    async fn dir_meta_returns_opened_dir_fstat() -> anyhow::Result<()> {
5707        use crate::preserve::Metadata as _;
5708        let tmp = testutils::setup_test_dir().await?;
5709        let bar = Dir::open_root_dir(&tmp.join("foo/bar"), false, congestion::Side::Source).await?;
5710        let meta = bar.meta().await?;
5711        let std_meta = std::fs::metadata(tmp.join("foo/bar"))?;
5712        // `meta.uid()` resolves via preserve::Metadata (the only trait FileMeta implements);
5713        // fully-qualify the std::fs::Metadata side, which implements both that trait and MetadataExt.
5714        assert_eq!(meta.uid(), std::os::unix::fs::MetadataExt::uid(&std_meta));
5715        assert_eq!(meta.gid(), std::os::unix::fs::MetadataExt::gid(&std_meta));
5716        Ok(())
5717    }
5718
5719    // hard_link_at: creates a hard link sharing the same inode.
5720    #[tokio::test]
5721    async fn hard_link_at_creates_hardlink() -> anyhow::Result<()> {
5722        let tmp = testutils::setup_test_dir().await?;
5723        // use two subdirs as src and dst Dir handles
5724        tokio::fs::create_dir(tmp.join("foo/src_sub")).await?;
5725        tokio::fs::create_dir(tmp.join("foo/dst_sub")).await?;
5726        tokio::fs::write(tmp.join("foo/src_sub/orig.txt"), b"hardlink test").await?;
5727
5728        let src =
5729            Dir::open_root_dir(&tmp.join("foo/src_sub"), false, congestion::Side::Source).await?;
5730        let dst = Dir::open_root_dir(
5731            &tmp.join("foo/dst_sub"),
5732            false,
5733            congestion::Side::Destination,
5734        )
5735        .await?;
5736
5737        src.hard_link_at(OsStr::new("orig.txt"), &dst, OsStr::new("link.txt"))
5738            .await?;
5739
5740        // both handles must exist and share the same inode
5741        let orig_handle = src.child(OsStr::new("orig.txt")).await?;
5742        let link_handle = dst.child(OsStr::new("link.txt")).await?;
5743        assert_eq!(orig_handle.kind(), EntryKind::File, "orig must be a file");
5744        assert_eq!(link_handle.kind(), EntryKind::File, "link must be a file");
5745        assert_eq!(
5746            orig_handle.ino(),
5747            link_handle.ino(),
5748            "hard link must share the inode"
5749        );
5750        Ok(())
5751    }
5752
5753    // hard_link_at: when the source name is a symlink, linkat with flags=0 does
5754    // NOT follow it — it links the symlink inode itself, so the new entry is also
5755    // a symlink.
5756    #[tokio::test]
5757    async fn hard_link_at_does_not_follow_source_symlink() -> anyhow::Result<()> {
5758        let tmp = testutils::setup_test_dir().await?;
5759        tokio::fs::create_dir(tmp.join("foo/src_hl")).await?;
5760        tokio::fs::create_dir(tmp.join("foo/dst_hl")).await?;
5761        // create a real file and a symlink to it in src_hl
5762        tokio::fs::write(tmp.join("foo/src_hl/real.txt"), b"target").await?;
5763        tokio::fs::symlink("real.txt", tmp.join("foo/src_hl/sym.txt")).await?;
5764
5765        let src =
5766            Dir::open_root_dir(&tmp.join("foo/src_hl"), false, congestion::Side::Source).await?;
5767        let dst = Dir::open_root_dir(
5768            &tmp.join("foo/dst_hl"),
5769            false,
5770            congestion::Side::Destination,
5771        )
5772        .await?;
5773
5774        // Linux does not allow hard-linking a symlink without AT_EMPTY_PATH or
5775        // special capabilities; linkat with flags=0 on a symlink yields EPERM.
5776        // Verify that the call does NOT silently follow the symlink into real.txt.
5777        let result = src
5778            .hard_link_at(OsStr::new("sym.txt"), &dst, OsStr::new("new_link.txt"))
5779            .await;
5780        match result {
5781            Ok(()) => {
5782                // If it succeeded (some kernels/configs allow it), the new entry
5783                // must be a symlink — NOT a hard link to the underlying file.
5784                let new_handle = dst.child(OsStr::new("new_link.txt")).await?;
5785                assert_eq!(
5786                    new_handle.kind(),
5787                    EntryKind::Symlink,
5788                    "hard_link_at must link the symlink itself, not its target"
5789                );
5790                // and real.txt must still have link-count 1 (no new hard link)
5791                let real_meta = std::fs::metadata(tmp.join("foo/src_hl/real.txt"))?;
5792                use std::os::unix::fs::MetadataExt;
5793                assert_eq!(
5794                    real_meta.nlink(),
5795                    1,
5796                    "real.txt must not gain a new hard link"
5797                );
5798            }
5799            Err(ref e) if e.raw_os_error() == Some(libc::EPERM) => {
5800                // expected on most Linux configurations; the important thing is
5801                // that it did NOT follow the symlink and link real.txt.
5802                // real.txt must still have exactly 1 hard link.
5803                let real_meta = std::fs::metadata(tmp.join("foo/src_hl/real.txt"))?;
5804                use std::os::unix::fs::MetadataExt;
5805                assert_eq!(
5806                    real_meta.nlink(),
5807                    1,
5808                    "real.txt must not gain a new hard link"
5809                );
5810            }
5811            Err(e) => {
5812                return Err(anyhow::anyhow!(
5813                    "unexpected error from hard_link_at on symlink: {e:#}"
5814                ));
5815            }
5816        }
5817        Ok(())
5818    }
5819
5820    // hard_link_handle_at links the exact inode the classified Handle pins, immune to a concurrent
5821    // source-name swap. The deterministic swap occurs after classification but before the link.
5822    //
5823    // the decoy is a different regular file with different content placed at the same name. A
5824    // by-name link would re-resolve `name` and link the decoy; `hard_link_handle_at` links the pinned
5825    // original inode regardless.
5826    #[tokio::test]
5827    async fn hard_link_handle_at_links_pinned_inode_after_name_swap() -> anyhow::Result<()> {
5828        use std::os::unix::fs::MetadataExt;
5829        let tmp = testutils::create_temp_dir().await?;
5830        tokio::fs::create_dir(tmp.join("src")).await?;
5831        tokio::fs::create_dir(tmp.join("dst")).await?;
5832        tokio::fs::write(tmp.join("src/entry"), b"ORIGINAL").await?;
5833        let orig_ino = tokio::fs::metadata(tmp.join("src/entry")).await?.ino();
5834
5835        let src = Dir::open_root_dir(&tmp.join("src"), false, congestion::Side::Source).await?;
5836        let dst =
5837            Dir::open_root_dir(&tmp.join("dst"), false, congestion::Side::Destination).await?;
5838        // classify `entry` — pins the ORIGINAL regular-file inode via O_PATH.
5839        let handle = src.child(OsStr::new("entry")).await?;
5840        assert_eq!(handle.kind(), EntryKind::File);
5841
5842        // SWAP `entry` to a DIFFERENT regular file (the decoy) before linking. We keep
5843        // the original inode alive only through `handle` (its directory entry is gone),
5844        // mimicking an attacker renaming a decoy over the source name.
5845        tokio::fs::write(tmp.join("src/decoy"), b"DECOY_SECRET").await?;
5846        tokio::fs::rename(tmp.join("src/decoy"), tmp.join("src/entry")).await?;
5847        let decoy_ino = tokio::fs::metadata(tmp.join("src/entry")).await?.ino();
5848        assert_ne!(orig_ino, decoy_ino, "decoy must be a different inode");
5849
5850        // inode-exact link: either links the ORIGINAL pinned inode, or fails closed.
5851        match dst.hard_link_handle_at(&handle, OsStr::new("linked")).await {
5852            Ok(()) => {
5853                let lm = tokio::fs::symlink_metadata(tmp.join("dst/linked")).await?;
5854                assert!(
5855                    lm.file_type().is_file(),
5856                    "linked entry must be a regular file"
5857                );
5858                assert_eq!(
5859                    lm.ino(),
5860                    orig_ino,
5861                    "hard_link_handle_at must link the PINNED original inode, never the \
5862                     swapped-in decoy (the by-name link would have linked the decoy here)"
5863                );
5864                let content = tokio::fs::read_to_string(tmp.join("dst/linked")).await?;
5865                assert_eq!(
5866                    content, "ORIGINAL",
5867                    "must reflect the original inode's content"
5868                );
5869                assert_ne!(content, "DECOY_SECRET");
5870            }
5871            Err(e) => {
5872                // fail-closed is acceptable (e.g. the pinned inode's last link was
5873                // already gone). It must NEVER have linked the decoy.
5874                assert!(
5875                    !tmp.join("dst/linked").exists(),
5876                    "no destination entry may exist when the link failed closed (got {e:#})"
5877                );
5878            }
5879        }
5880        Ok(())
5881    }
5882
5883    // hard_link_handle_at must refuse to hard-link a DIRECTORY (linkat returns EPERM),
5884    // matching the by-name path — a hard link to a directory is never created.
5885    #[tokio::test]
5886    async fn hard_link_handle_at_refuses_directory() -> anyhow::Result<()> {
5887        let tmp = testutils::create_temp_dir().await?;
5888        tokio::fs::create_dir(tmp.join("src")).await?;
5889        tokio::fs::create_dir(tmp.join("dst")).await?;
5890        tokio::fs::create_dir(tmp.join("src/adir")).await?;
5891        let src = Dir::open_root_dir(&tmp.join("src"), false, congestion::Side::Source).await?;
5892        let dst =
5893            Dir::open_root_dir(&tmp.join("dst"), false, congestion::Side::Destination).await?;
5894        let dir_handle = src.child(OsStr::new("adir")).await?;
5895        assert_eq!(dir_handle.kind(), EntryKind::Dir);
5896        let result = dst
5897            .hard_link_handle_at(&dir_handle, OsStr::new("linked_dir"))
5898            .await;
5899        assert!(
5900            result.is_err(),
5901            "hard_link_handle_at must refuse to hard-link a directory"
5902        );
5903        assert!(
5904            !tmp.join("dst/linked_dir").exists(),
5905            "no destination entry may be created for a directory hard link"
5906        );
5907        Ok(())
5908    }
5909
5910    // classify a regular file, then swap the source name to a FIFO before linking. A by-name
5911    // `linkat(flags=0)` would re-resolve the name and hard-link the FIFO, surfacing a special at the
5912    // destination that rlink reports as a hard-linked file. The inode-exact link must instead link
5913    // the pinned regular file or fail closed, so the destination is never special.
5914    #[tokio::test]
5915    async fn hard_link_handle_at_never_links_swapped_in_fifo() -> anyhow::Result<()> {
5916        use std::os::unix::fs::FileTypeExt;
5917        let tmp = testutils::create_temp_dir().await?;
5918        tokio::fs::create_dir(tmp.join("src")).await?;
5919        tokio::fs::create_dir(tmp.join("dst")).await?;
5920        tokio::fs::write(tmp.join("src/entry"), b"REALFILE").await?;
5921        let src = Dir::open_root_dir(&tmp.join("src"), false, congestion::Side::Source).await?;
5922        let dst =
5923            Dir::open_root_dir(&tmp.join("dst"), false, congestion::Side::Destination).await?;
5924        // classify `entry` — pins the regular-file inode.
5925        let handle = src.child(OsStr::new("entry")).await?;
5926        assert_eq!(handle.kind(), EntryKind::File);
5927        // swap `entry` to a FIFO (keep the regular inode alive only via the handle).
5928        tokio::fs::remove_file(tmp.join("src/entry")).await?;
5929        nix::unistd::mkfifo(
5930            &tmp.join("src/entry"),
5931            nix::sys::stat::Mode::S_IRUSR | nix::sys::stat::Mode::S_IWUSR,
5932        )?;
5933        match dst.hard_link_handle_at(&handle, OsStr::new("linked")).await {
5934            Ok(()) => {
5935                let lm = tokio::fs::symlink_metadata(tmp.join("dst/linked")).await?;
5936                assert!(
5937                    lm.file_type().is_file(),
5938                    "linked entry must be the pinned regular file, never the swapped-in FIFO"
5939                );
5940                assert!(
5941                    !lm.file_type().is_fifo(),
5942                    "the destination must never be a special (the by-name link would link the FIFO)"
5943                );
5944                let content = tokio::fs::read_to_string(tmp.join("dst/linked")).await?;
5945                assert_eq!(content, "REALFILE");
5946            }
5947            Err(_) => {
5948                // fail-closed is acceptable; nothing may be left at the destination.
5949                assert!(
5950                    !tmp.join("dst/linked").exists(),
5951                    "no destination entry may exist when the link failed closed"
5952                );
5953            }
5954        }
5955        Ok(())
5956    }
5957
5958    // hard_link_handle_at on a STABLE regular file links exactly like the by-name path
5959    // did (same inode, same content) — the happy path is unchanged.
5960    #[tokio::test]
5961    async fn hard_link_handle_at_stable_file_happy_path() -> anyhow::Result<()> {
5962        let tmp = testutils::create_temp_dir().await?;
5963        tokio::fs::create_dir(tmp.join("src")).await?;
5964        tokio::fs::create_dir(tmp.join("dst")).await?;
5965        tokio::fs::write(tmp.join("src/f"), b"STABLE").await?;
5966        let src = Dir::open_root_dir(&tmp.join("src"), false, congestion::Side::Source).await?;
5967        let dst =
5968            Dir::open_root_dir(&tmp.join("dst"), false, congestion::Side::Destination).await?;
5969        let handle = src.child(OsStr::new("f")).await?;
5970        dst.hard_link_handle_at(&handle, OsStr::new("f_link"))
5971            .await?;
5972        let orig = src.child(OsStr::new("f")).await?;
5973        let linked = dst.child(OsStr::new("f_link")).await?;
5974        assert_eq!(linked.kind(), EntryKind::File);
5975        assert_eq!(orig.ino(), linked.ino(), "hard link must share the inode");
5976        let content = tokio::fs::read_to_string(tmp.join("dst/f_link")).await?;
5977        assert_eq!(content, "STABLE");
5978        Ok(())
5979    }
5980
5981    // ── fd-based metadata application ───────────────────────────────────────
5982
5983    #[tokio::test]
5984    async fn owned_file_metadata_follows_the_created_inode_after_name_replacement()
5985    -> anyhow::Result<()> {
5986        use std::io::Write as _;
5987        use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
5988        let tmp = tempfile::tempdir()?;
5989        let source = tmp.path().join("source");
5990        std::fs::write(&source, b"source")?;
5991        std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o751))?;
5992        filetime::set_file_times(
5993            &source,
5994            filetime::FileTime::from_unix_time(1_000_000_000, 123_456_789),
5995            filetime::FileTime::from_unix_time(1_000_000_500, 987_654_321),
5996        )?;
5997        let source_meta = std::fs::metadata(&source)?;
5998        let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
5999        let path = tmp.path().join("destination");
6000        let saved = tmp.path().join("saved-destination");
6001        let mut file = root.create_file(OsStr::new("destination")).await?;
6002        file.write_all(b"copied payload")?;
6003        let created = file.metadata()?;
6004        let identity = testutils::FdIdentityProbe::capture(file.as_raw_fd())?;
6005        std::fs::rename(&path, &saved)?;
6006        std::fs::write(&path, b"replacement")?;
6007        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640))?;
6008        let replacement_before = std::fs::metadata(&path)?;
6009        set_file_metadata_owned(
6010            &crate::preserve::preserve_all(),
6011            &source_meta,
6012            None,
6013            file.into(),
6014            congestion::Side::Destination,
6015        )
6016        .await?;
6017        assert!(
6018            identity.original_is_closed()?,
6019            "metadata retained its consumed descriptor"
6020        );
6021        let applied = std::fs::metadata(&saved)?;
6022        assert_eq!(
6023            (applied.dev(), applied.ino()),
6024            (created.dev(), created.ino())
6025        );
6026        assert_eq!(applied.permissions().mode() & 0o7777, 0o751);
6027        assert_eq!(
6028            std::os::unix::fs::MetadataExt::uid(&applied),
6029            std::os::unix::fs::MetadataExt::uid(&source_meta)
6030        );
6031        assert_eq!(
6032            std::os::unix::fs::MetadataExt::gid(&applied),
6033            std::os::unix::fs::MetadataExt::gid(&source_meta)
6034        );
6035        assert_eq!(
6036            std::os::unix::fs::MetadataExt::atime(&applied),
6037            1_000_000_000
6038        );
6039        assert_eq!(
6040            std::os::unix::fs::MetadataExt::atime_nsec(&applied),
6041            123_456_789
6042        );
6043        assert_eq!(
6044            std::os::unix::fs::MetadataExt::mtime(&applied),
6045            1_000_000_500
6046        );
6047        assert_eq!(
6048            std::os::unix::fs::MetadataExt::mtime_nsec(&applied),
6049            987_654_321
6050        );
6051        let replacement_after = std::fs::metadata(&path)?;
6052        assert_eq!(
6053            (replacement_after.dev(), replacement_after.ino()),
6054            (replacement_before.dev(), replacement_before.ino())
6055        );
6056        assert_eq!(
6057            replacement_after.permissions().mode(),
6058            replacement_before.permissions().mode()
6059        );
6060        assert_eq!(
6061            std::os::unix::fs::MetadataExt::mtime(&replacement_after),
6062            std::os::unix::fs::MetadataExt::mtime(&replacement_before)
6063        );
6064        assert_eq!(
6065            std::os::unix::fs::MetadataExt::mtime_nsec(&replacement_after),
6066            std::os::unix::fs::MetadataExt::mtime_nsec(&replacement_before)
6067        );
6068        assert_eq!(std::fs::read(&saved)?, b"copied payload");
6069        assert_eq!(std::fs::read(&path)?, b"replacement");
6070        Ok(())
6071    }
6072
6073    async fn assert_cancelled_owned_operation_keeps_resources<Fut, T, O>(
6074        file: std::fs::File,
6075        path: &Path,
6076        resource: throttle::Resource,
6077        operation: impl FnOnce(std::fs::File) -> Fut + Send + 'static,
6078        observe_while_gated: impl FnOnce() -> O,
6079    ) -> anyhow::Result<O>
6080    where
6081        Fut: std::future::Future<Output = T> + Send + 'static,
6082        T: Send + 'static,
6083    {
6084        use futures::FutureExt as _;
6085        let identity = testutils::FdIdentityProbe::capture(file.as_raw_fd())?;
6086        let gate = testutils::BlockingPathGate::install(path);
6087        let limits = testutils::AdmissionLimit::new().await;
6088        limits.set_files_in_flight(1);
6089        limits.set_max_ops_in_flight(resource, 1);
6090        let guard = throttle::open_file_permit().await;
6091        let task = tokio::spawn(with_fd_admission(guard.admission(), async move {
6092            let _guard = guard;
6093            operation(file).await
6094        }));
6095        let mut next_operation = Box::pin(throttle::ops_in_flight_permit(resource));
6096        let (observations, (acquired_operation, observed)) = testutils::cancel_at_blocking_path(
6097            limits,
6098            gate,
6099            task,
6100            std::time::Duration::from_secs(20),
6101            |_| {
6102                (
6103                    next_operation.as_mut().now_or_never(),
6104                    observe_while_gated(),
6105                )
6106            },
6107        )
6108        .await?;
6109        let operation_retained = acquired_operation.is_none();
6110        let permit = match acquired_operation {
6111            Some(permit) => permit,
6112            None => tokio::time::timeout(std::time::Duration::from_secs(5), next_operation).await?,
6113        };
6114        drop(permit);
6115        assert!(observations.waiter_was_cancelled);
6116        assert!(observations.admission_was_retained_while_work_gated);
6117        assert!(observations.fd_was_open_while_work_gated);
6118        assert!(
6119            operation_retained,
6120            "started work released its operation permit after cancellation"
6121        );
6122        assert_eq!(observations.final_hit_count, 1);
6123        assert!(
6124            identity.original_is_closed()?,
6125            "started work returned capacity before closing its owned descriptor"
6126        );
6127        Ok(observed)
6128    }
6129
6130    #[tokio::test]
6131    async fn cancelled_owned_acl_read_retains_source_and_permits_until_started_work_finishes()
6132    -> anyhow::Result<()> {
6133        let tmp = tempfile::tempdir()?;
6134        let path = tmp.path().join("source");
6135        std::fs::write(&path, b"payload")?;
6136        let file = std::fs::File::open(&path)?;
6137        assert_cancelled_owned_operation_keeps_resources(
6138            file,
6139            &path,
6140            throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat),
6141            |file| read_acls_owned(file, congestion::Side::Source, false),
6142            || (),
6143        )
6144        .await
6145    }
6146
6147    #[tokio::test]
6148    async fn cancelled_owned_metadata_waiting_for_admission_closes_the_file_without_widening()
6149    -> anyhow::Result<()> {
6150        use std::os::unix::fs::PermissionsExt as _;
6151        let tmp = tempfile::tempdir()?;
6152        let source = tmp.path().join("source");
6153        std::fs::write(&source, b"source")?;
6154        std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o755))?;
6155        let source_meta = std::fs::metadata(&source)?;
6156        let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
6157        let path = tmp.path().join("destination");
6158        let file = root.create_file(OsStr::new("destination")).await?;
6159        let identity = testutils::FdIdentityProbe::capture(file.as_raw_fd())?;
6160        let limits = testutils::AdmissionLimit::new().await;
6161        limits.set_files_in_flight(1);
6162        let resource =
6163            throttle::Resource::meta(throttle::Side::Destination, throttle::MetadataOp::Chmod);
6164        limits.set_max_ops_in_flight(resource, 1);
6165        let occupied = throttle::ops_in_flight_permit(resource).await;
6166        let guard = throttle::open_file_permit().await;
6167        let admission = guard.admission();
6168        let mut work = Box::pin(with_fd_admission(admission, async move {
6169            let _guard = guard;
6170            set_file_metadata_owned(
6171                &crate::preserve::preserve_all(),
6172                &source_meta,
6173                None,
6174                file.into(),
6175                congestion::Side::Destination,
6176            )
6177            .await
6178        }));
6179        let waiting = futures::poll!(work.as_mut()).is_pending();
6180        let fd_retained = !identity.original_is_closed()?;
6181        let mut next_file = Box::pin(throttle::open_file_permit());
6182        assert!(
6183            futures::poll!(next_file.as_mut()).is_pending(),
6184            "waiting metadata released file admission"
6185        );
6186        drop(work);
6187        let closed = identity.original_is_closed()?;
6188        let file_permit =
6189            tokio::time::timeout(std::time::Duration::from_secs(5), next_file).await?;
6190        drop(file_permit);
6191        drop(occupied);
6192        assert!(
6193            waiting,
6194            "metadata did not wait for its occupied operation permit"
6195        );
6196        assert!(fd_retained);
6197        assert!(
6198            closed,
6199            "cancelled metadata admission retained its owned descriptor"
6200        );
6201        assert_eq!(
6202            std::fs::metadata(path)?.permissions().mode() & 0o7777,
6203            DST_FILE_CREATE_MODE
6204        );
6205        Ok(())
6206    }
6207
6208    #[tokio::test]
6209    async fn cancelled_owned_metadata_retains_the_file_and_permits_until_started_work_finishes()
6210    -> anyhow::Result<()> {
6211        use std::os::unix::fs::PermissionsExt as _;
6212        let tmp = tempfile::tempdir()?;
6213        let source = tmp.path().join("source");
6214        std::fs::write(&source, b"source")?;
6215        std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o755))?;
6216        let source_meta = std::fs::metadata(&source)?;
6217        let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
6218        let path = tmp.path().join("destination");
6219        let file = root.create_file(OsStr::new("destination")).await?;
6220        let mode_while_gated = assert_cancelled_owned_operation_keeps_resources(
6221            file,
6222            &path,
6223            throttle::Resource::meta(throttle::Side::Destination, throttle::MetadataOp::Chmod),
6224            |file| async move {
6225                set_file_metadata_owned(
6226                    &crate::preserve::preserve_all(),
6227                    &source_meta,
6228                    None,
6229                    file.into(),
6230                    congestion::Side::Destination,
6231                )
6232                .await
6233            },
6234            || std::fs::metadata(&path).map(|meta| meta.permissions().mode() & 0o7777),
6235        )
6236        .await?;
6237        assert_eq!(mode_while_gated?, DST_FILE_CREATE_MODE);
6238        assert_eq!(
6239            std::fs::metadata(path)?.permissions().mode() & 0o7777,
6240            DST_FILE_CREATE_MODE
6241        );
6242        Ok(())
6243    }
6244
6245    // set_file_metadata_owned: applying owner/mode/time from a source FileMeta to an
6246    // already-open destination fd must reflect on the destination file: masked
6247    // mode, mtime, and (where testable) uid/gid all match the source.
6248    #[tokio::test]
6249    async fn set_file_metadata_owned_applies_owner_mode_time() -> anyhow::Result<()> {
6250        use std::io::Write;
6251        use std::os::unix::fs::PermissionsExt;
6252        let tmp = testutils::setup_test_dir().await?;
6253        // source file with a distinctive mode and a known, old mtime
6254        let src_path = tmp.join("foo/src_meta.txt");
6255        tokio::fs::write(&src_path, b"source").await?;
6256        std::fs::set_permissions(&src_path, std::fs::Permissions::from_mode(0o741))?;
6257        let src_mtime = filetime::FileTime::from_unix_time(1_000_000_000, 123_456_789);
6258        filetime::set_file_mtime(&src_path, src_mtime)?;
6259        filetime::set_file_atime(
6260            &src_path,
6261            filetime::FileTime::from_unix_time(1_000_000_500, 0),
6262        )?;
6263
6264        let root =
6265            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6266        // snapshot the source metadata via a Handle (the realistic source flow)
6267        let src_handle = root.child(OsStr::new("src_meta.txt")).await?;
6268        let src_meta = src_handle.meta().clone();
6269
6270        // create the destination file and write some content into it
6271        let mut dst_file = root.create_file(OsStr::new("dst_meta.txt")).await?;
6272        dst_file.write_all(b"destination")?;
6273        dst_file.flush()?;
6274
6275        // apply source metadata to the already-open dst fd; preserve everything
6276        let settings = crate::preserve::preserve_all();
6277        set_file_metadata_owned(
6278            &settings,
6279            &src_meta,
6280            None,
6281            dst_file.into(),
6282            congestion::Side::Destination,
6283        )
6284        .await?;
6285
6286        // re-stat the destination and assert mode (masked to 0o7777), mtime
6287        let dst_md = std::fs::metadata(tmp.join("foo/dst_meta.txt"))?;
6288        assert_eq!(
6289            dst_md.permissions().mode() & 0o7777,
6290            0o741,
6291            "destination mode mismatch"
6292        );
6293        // disambiguate: both preserve::Metadata and std MetadataExt are in scope
6294        use std::os::unix::fs::MetadataExt;
6295        assert_eq!(
6296            MetadataExt::mtime(&dst_md),
6297            1_000_000_000,
6298            "mtime seconds mismatch"
6299        );
6300        assert_eq!(
6301            MetadataExt::mtime_nsec(&dst_md),
6302            123_456_789,
6303            "mtime nanos mismatch"
6304        );
6305        // uid/gid: chown to source's uid/gid (same as current user here) must hold
6306        assert_eq!(MetadataExt::uid(&dst_md), src_meta.uid(), "uid mismatch");
6307        assert_eq!(MetadataExt::gid(&dst_md), src_meta.gid(), "gid mismatch");
6308        Ok(())
6309    }
6310
6311    // set_file_metadata_owned: chown before chmod must preserve a setuid bit.
6312    // An unprivileged fchown (even to the current uid) clears setuid/setgid; doing
6313    // chown FIRST and chmod AFTER restores it. This test proves that ordering.
6314    #[cfg_attr(
6315        rcp_nix_sandbox,
6316        ignore = "Nix sandbox cannot change ownership or set-id modes"
6317    )]
6318    #[tokio::test]
6319    async fn set_file_metadata_owned_ordering_preserves_setuid() -> anyhow::Result<()> {
6320        use std::io::Write;
6321        use std::os::unix::fs::PermissionsExt;
6322        let tmp = testutils::setup_test_dir().await?;
6323        // source file with the setuid bit set (0o4755)
6324        let src_path = tmp.join("foo/setuid_src");
6325        tokio::fs::write(&src_path, b"x").await?;
6326        std::fs::set_permissions(&src_path, std::fs::Permissions::from_mode(0o4755))?;
6327
6328        let root =
6329            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6330        let src_handle = root.child(OsStr::new("setuid_src")).await?;
6331        let src_meta = src_handle.meta().clone();
6332        assert_eq!(
6333            src_meta.permissions().mode() & 0o7777,
6334            0o4755,
6335            "source setuid bit was not set up correctly"
6336        );
6337
6338        // destination starts without the setuid bit
6339        let mut dst_file = root.create_file(OsStr::new("setuid_dst")).await?;
6340        dst_file.write_all(b"x")?;
6341        dst_file.flush()?;
6342
6343        // preserve_all keeps the full mode (mask 0o7777) AND preserves uid/gid, so
6344        // the chown runs before the chmod; the setuid bit must survive.
6345        let settings = crate::preserve::preserve_all();
6346        set_file_metadata_owned(
6347            &settings,
6348            &src_meta,
6349            None,
6350            dst_file.into(),
6351            congestion::Side::Destination,
6352        )
6353        .await?;
6354
6355        let dst_md = std::fs::metadata(tmp.join("foo/setuid_dst"))?;
6356        assert_eq!(
6357            dst_md.permissions().mode() & 0o7777,
6358            0o4755,
6359            "setuid bit was lost — chown must run before chmod"
6360        );
6361        Ok(())
6362    }
6363
6364    // set_file_metadata_owned: the widening chmod must be the LAST step. A destination file is created
6365    // owner-only and this call is the only thing that widens it to the source mode, so a fallible
6366    // step running AFTER the chmod would publish that final mode — here a setuid one — on a file the
6367    // copy is about to report as failed. `futimens` is that step. An out-of-range nanosecond field
6368    // makes it fail deterministically, with no privileged uid or hostile filesystem needed.
6369    #[tokio::test]
6370    async fn set_file_metadata_owned_keeps_the_file_owner_only_when_utimens_fails()
6371    -> anyhow::Result<()> {
6372        use std::os::unix::fs::PermissionsExt;
6373
6374        struct RejectedTimestamps;
6375        impl crate::preserve::Metadata for RejectedTimestamps {
6376            fn uid(&self) -> u32 {
6377                // SAFETY: `getuid` has no preconditions and cannot fail.
6378                unsafe { libc::getuid() }
6379            }
6380            fn gid(&self) -> u32 {
6381                // SAFETY: `getgid` has no preconditions and cannot fail.
6382                unsafe { libc::getgid() }
6383            }
6384            fn atime(&self) -> i64 {
6385                0
6386            }
6387            fn atime_nsec(&self) -> i64 {
6388                0
6389            }
6390            fn mtime(&self) -> i64 {
6391                0
6392            }
6393            // utimensat rejects a nanosecond field outside [0, 999999999] that is neither UTIME_NOW
6394            // nor UTIME_OMIT with EINVAL.
6395            fn mtime_nsec(&self) -> i64 {
6396                2_000_000_000
6397            }
6398            fn permissions(&self) -> std::fs::Permissions {
6399                std::fs::Permissions::from_mode(0o4755)
6400            }
6401        }
6402
6403        let tmp = testutils::setup_test_dir().await?;
6404        let root =
6405            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6406        let dst_file = root.create_file(OsStr::new("late_chmod")).await?;
6407        let dst_path = tmp.join("foo/late_chmod");
6408        assert_eq!(
6409            std::fs::metadata(&dst_path)?.permissions().mode() & 0o7777,
6410            DST_FILE_CREATE_MODE,
6411            "every destination file starts owner-only"
6412        );
6413
6414        // preserve_all: uid/gid so the chown runs first, time so the futimens is reached, and
6415        // mode_mask 0o7777 so the chmod that must NOT run would have set the setuid bit.
6416        let error = set_file_metadata_owned(
6417            &crate::preserve::preserve_all(),
6418            &RejectedTimestamps,
6419            None,
6420            dst_file.into(),
6421            congestion::Side::Destination,
6422        )
6423        .await
6424        .expect_err("an out-of-range nanosecond field must fail futimens");
6425        assert_eq!(error.raw_os_error(), Some(libc::EINVAL));
6426
6427        assert_eq!(
6428            std::fs::metadata(&dst_path)?.permissions().mode() & 0o7777,
6429            DST_FILE_CREATE_MODE,
6430            "a failure during metadata application must not leave the final mode behind"
6431        );
6432        Ok(())
6433    }
6434
6435    // set_dir_metadata_fd: applying mode/time to a freshly made directory via its
6436    // Dir fd must reflect on the directory.
6437    #[cfg_attr(
6438        rcp_nix_sandbox,
6439        ignore = "Nix sandbox cannot change ownership or set-id modes"
6440    )]
6441    #[tokio::test]
6442    async fn set_dir_metadata_fd_applies() -> anyhow::Result<()> {
6443        use std::os::unix::fs::{MetadataExt, PermissionsExt};
6444        let tmp = testutils::setup_test_dir().await?;
6445        // source directory with a distinctive mode and known mtime
6446        let src_dir_path = tmp.join("foo/src_dir");
6447        tokio::fs::create_dir(&src_dir_path).await?;
6448        std::fs::set_permissions(&src_dir_path, std::fs::Permissions::from_mode(0o2750))?;
6449        filetime::set_file_mtime(
6450            &src_dir_path,
6451            filetime::FileTime::from_unix_time(1_111_111_111, 222_000_000),
6452        )?;
6453
6454        let root =
6455            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6456        let src_handle = root.child(OsStr::new("src_dir")).await?;
6457        let src_meta = src_handle.meta().clone();
6458
6459        // create the destination directory and apply metadata via its Dir fd
6460        let dst_dir = root.make_dir(OsStr::new("dst_dir"), 0o700).await?;
6461        let settings = crate::preserve::preserve_all();
6462        set_dir_metadata_fd(&settings, &src_meta, None, &dst_dir).await?;
6463
6464        let dst_md = std::fs::metadata(tmp.join("foo/dst_dir"))?;
6465        assert_eq!(
6466            dst_md.permissions().mode() & 0o7777,
6467            0o2750,
6468            "destination dir mode mismatch"
6469        );
6470        assert_eq!(
6471            MetadataExt::mtime(&dst_md),
6472            1_111_111_111,
6473            "dir mtime seconds mismatch"
6474        );
6475        assert_eq!(
6476            MetadataExt::mtime_nsec(&dst_md),
6477            222_000_000,
6478            "dir mtime nanos mismatch"
6479        );
6480        Ok(())
6481    }
6482
6483    // set_symlink_metadata_fd: applying time (and owner) to a symlink via its
6484    // O_PATH Handle must change the LINK's own atime/mtime — NOT the target's
6485    // mtime. This is the key proof that utimensat(AT_EMPTY_PATH) hit the link.
6486    #[tokio::test]
6487    async fn set_symlink_metadata_fd_changes_link_not_target() -> anyhow::Result<()> {
6488        use std::os::unix::fs::MetadataExt;
6489        let tmp = testutils::setup_test_dir().await?;
6490        let root =
6491            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6492
6493        // sentinel target file with a known mtime we must NOT disturb
6494        let target_path = tmp.join("foo/sentinel_target.txt");
6495        tokio::fs::write(&target_path, b"keep my mtime").await?;
6496        let target_mtime = filetime::FileTime::from_unix_time(1_500_000_000, 0);
6497        filetime::set_file_mtime(&target_path, target_mtime)?;
6498        let target_before = std::fs::metadata(&target_path)?;
6499
6500        // the link to apply metadata to
6501        let link = root
6502            .symlink_at(
6503                OsStr::new("the_link"),
6504                std::path::Path::new("sentinel_target.txt"),
6505            )
6506            .await?;
6507
6508        // desired link timestamps come from a source FileMeta; build one by
6509        // stating a second symlink we set up with a distinctive mtime.
6510        let src_link_path = tmp.join("foo/src_link");
6511        tokio::fs::symlink("sentinel_target.txt", &src_link_path).await?;
6512        let src_link_mtime = filetime::FileTime::from_unix_time(1_234_567_890, 0);
6513        // set the LINK's own mtime (symlink=true) — not the target's
6514        filetime::set_symlink_file_times(
6515            &src_link_path,
6516            filetime::FileTime::from_unix_time(1_234_500_000, 0),
6517            src_link_mtime,
6518        )?;
6519        let src_meta = root.child(OsStr::new("src_link")).await?.meta().clone();
6520
6521        let settings = crate::preserve::preserve_all();
6522        set_symlink_metadata_fd(&settings, &src_meta, &link, congestion::Side::Destination).await?;
6523
6524        // the LINK's own mtime must now equal the source link's mtime
6525        let link_md = std::fs::symlink_metadata(tmp.join("foo/the_link"))?;
6526        assert_eq!(
6527            MetadataExt::mtime(&link_md),
6528            1_234_567_890,
6529            "link's own mtime was not applied"
6530        );
6531        // the TARGET file's mtime must be UNCHANGED
6532        let target_after = std::fs::metadata(&target_path)?;
6533        assert_eq!(
6534            MetadataExt::mtime(&target_after),
6535            MetadataExt::mtime(&target_before),
6536            "target mtime changed — utimensat followed the symlink!"
6537        );
6538        assert_eq!(
6539            MetadataExt::mtime_nsec(&target_after),
6540            MetadataExt::mtime_nsec(&target_before),
6541            "target mtime_nsec changed — utimensat followed the symlink!"
6542        );
6543        Ok(())
6544    }
6545
6546    // rejects_multi_component_names: cover every by-name helper added with fd-relative mutation.
6547    #[tokio::test]
6548    async fn new_methods_reject_multi_component_names() -> anyhow::Result<()> {
6549        let tmp = testutils::setup_test_dir().await?;
6550        let root =
6551            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6552        // a second Dir for hard_link_at's dst parameter
6553        let dst =
6554            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6555        for bad in ["a/b", "..", ".", ""] {
6556            let bad_os = OsStr::new(bad);
6557
6558            let err = root.unlink_at(bad_os).await.unwrap_err();
6559            assert_eq!(
6560                err.raw_os_error(),
6561                Some(libc::EINVAL),
6562                "unlink_at: expected EINVAL for {bad:?}, got {err:#}"
6563            );
6564
6565            let err = root.rmdir_at(bad_os).await.unwrap_err();
6566            assert_eq!(
6567                err.raw_os_error(),
6568                Some(libc::EINVAL),
6569                "rmdir_at: expected EINVAL for {bad:?}, got {err:#}"
6570            );
6571
6572            // symlink_at: only `name` is guarded; target is arbitrary
6573            let err = root
6574                .symlink_at(bad_os, std::path::Path::new("irrelevant"))
6575                .await
6576                .unwrap_err();
6577            assert_eq!(
6578                err.raw_os_error(),
6579                Some(libc::EINVAL),
6580                "symlink_at(name): expected EINVAL for {bad:?}, got {err:#}"
6581            );
6582
6583            let err = root.read_link_at(bad_os).await.unwrap_err();
6584            assert_eq!(
6585                err.raw_os_error(),
6586                Some(libc::EINVAL),
6587                "read_link_at: expected EINVAL for {bad:?}, got {err:#}"
6588            );
6589
6590            // hard_link_at: both `name` and `dst_name` are guarded
6591            let err = root
6592                .hard_link_at(bad_os, &dst, OsStr::new("good"))
6593                .await
6594                .unwrap_err();
6595            assert_eq!(
6596                err.raw_os_error(),
6597                Some(libc::EINVAL),
6598                "hard_link_at(name): expected EINVAL for {bad:?}, got {err:#}"
6599            );
6600
6601            let err = root
6602                .hard_link_at(OsStr::new("good"), &dst, bad_os)
6603                .await
6604                .unwrap_err();
6605            assert_eq!(
6606                err.raw_os_error(),
6607                Some(libc::EINVAL),
6608                "hard_link_at(dst_name): expected EINVAL for {bad:?}, got {err:#}"
6609            );
6610        }
6611        Ok(())
6612    }
6613
6614    // chmod_via_proc_fd: changing the mode of a 0000-mode file through its O_PATH
6615    // handle must succeed (the /proc magic-symlink path does not need any rights on
6616    // the target itself) and the new mode must be observable on disk. This is the
6617    // case `fchmod` (EBADF on O_PATH) and a bare path chmod under restrictive modes
6618    // would struggle with; the pinned inode makes it inode-exact and permission-free.
6619    #[tokio::test]
6620    async fn chmod_via_proc_fd_changes_mode_of_zero_mode_file() -> anyhow::Result<()> {
6621        use std::os::unix::fs::PermissionsExt;
6622        let tmp = testutils::setup_test_dir().await?;
6623        let root =
6624            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6625        // a file with no permission bits at all (0000).
6626        let path = tmp.join("foo/locked.txt");
6627        tokio::fs::write(&path, b"locked").await?;
6628        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000))?;
6629        // O_PATH handle pins the inode even though the file is 0000.
6630        let handle = root.child(OsStr::new("locked.txt")).await?;
6631        assert_eq!(handle.kind(), EntryKind::File, "fixture must be a file");
6632        // chmod it to 0o640 via the /proc magic symlink.
6633        chmod_via_proc_fd(&handle, congestion::Side::Destination, 0o640).await?;
6634        // the mode change must be visible on disk.
6635        let md = std::fs::symlink_metadata(&path)?;
6636        assert_eq!(
6637            md.permissions().mode() & 0o7777,
6638            0o640,
6639            "chmod_via_proc_fd must change the mode of a 0000-mode file"
6640        );
6641        Ok(())
6642    }
6643
6644    // stat_meta_via_proc_fd: on a symlink Handle (opened O_PATH|O_NOFOLLOW), resolving
6645    // /proc/self/fd/N must land on the LINK's own inode — never the target's. This is
6646    // load-bearing for symlink time-filtering (rm/rrm reads a symlink's own mtime/btime to
6647    // decide removal). We give the link and its target DISTINCT mtimes and assert the metadata
6648    // returned is the link's (is_symlink + the link's mtime), proving the magic-symlink resolve
6649    // is pinned to the O_PATH inode and does not follow the link to the target.
6650    #[tokio::test]
6651    async fn stat_meta_via_proc_fd_on_symlink_resolves_link_not_target() -> anyhow::Result<()> {
6652        use std::os::unix::fs::MetadataExt;
6653        let tmp = testutils::setup_test_dir().await?;
6654        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6655
6656        // target file with one mtime ...
6657        let target_path = tmp.join("foo/stat_target.txt");
6658        tokio::fs::write(&target_path, b"target body").await?;
6659        filetime::set_file_mtime(
6660            &target_path,
6661            filetime::FileTime::from_unix_time(1_700_000_000, 0),
6662        )?;
6663
6664        // ... and a symlink to it with a DISTINCT mtime set on the LINK itself (not the target).
6665        let link_path = tmp.join("foo/stat_link");
6666        tokio::fs::symlink("stat_target.txt", &link_path).await?;
6667        filetime::set_symlink_file_times(
6668            &link_path,
6669            filetime::FileTime::from_unix_time(1_600_000_000, 0),
6670            filetime::FileTime::from_unix_time(1_600_000_123, 0),
6671        )?;
6672
6673        // open the symlink via child() — an O_PATH|O_NOFOLLOW handle pinned to the link inode.
6674        let handle = root.child(OsStr::new("stat_link")).await?;
6675        assert_eq!(
6676            handle.kind(),
6677            EntryKind::Symlink,
6678            "fixture must classify as a symlink"
6679        );
6680
6681        let md = stat_meta_via_proc_fd(&handle, congestion::Side::Source).await?;
6682        // the returned metadata must be the LINK's, not the dereferenced target's.
6683        assert!(
6684            md.file_type().is_symlink(),
6685            "stat_meta_via_proc_fd followed the symlink to its target (got a non-symlink)"
6686        );
6687        assert_eq!(
6688            MetadataExt::mtime(&md),
6689            1_600_000_123,
6690            "expected the LINK's own mtime; a target-following stat would return 1_700_000_000"
6691        );
6692        Ok(())
6693    }
6694
6695    // NOTE: the test that ARMS strict operand resolution and exercises the strict
6696    // (openat2) open path lives in tests/strict_resolution.rs — its own integration
6697    // binary and therefore its own process. The switch is one-way, and under the
6698    // plain `cargo test` harness (used by the nix checkPhase) a lib's unit tests
6699    // share one process, so arming here would leak into the symlink-following
6700    // default-behavior tests above.
6701
6702    #[test]
6703    fn openat2_probe_is_stable() {
6704        // the probe is memoized; both calls must agree. On kernels without openat2 a
6705        // `false` result is the correct answer (the linter then refuses strict mode),
6706        // so no hard assertion on availability itself.
6707        let first = openat2_available();
6708        assert_eq!(first, openat2_available(), "probe must be stable");
6709        if !first {
6710            eprintln!("this kernel lacks openat2(2); strict-mode tests skip themselves");
6711        }
6712    }
6713
6714    // ── POSIX ACLs ──────────────────────────────────────────────────────────
6715
6716    use crate::testutils::acl::*;
6717
6718    fn mode_of(path: &std::path::Path) -> u32 {
6719        use std::os::unix::fs::PermissionsExt as _;
6720        std::fs::metadata(path).unwrap().permissions().mode() & 0o7777
6721    }
6722
6723    #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
6724    #[tokio::test]
6725    async fn read_acls_owned_returns_the_same_source_descriptor_after_name_replacement()
6726    -> anyhow::Result<()> {
6727        use std::io::Read as _;
6728        let tmp = tempfile::tempdir()?;
6729        let path = tmp.path().join("source");
6730        std::fs::write(&path, b"original")?;
6731        let blob = restrictive_access_acl();
6732        set_xattr_at(&path, ACL_ACCESS_XATTR, &blob);
6733        let file = std::fs::File::open(&path)?;
6734        let raw_fd = file.as_raw_fd();
6735        std::fs::rename(&path, tmp.path().join("original"))?;
6736        std::fs::write(&path, b"replacement")?;
6737        set_xattr_at(&path, ACL_ACCESS_XATTR, &permissive_acl());
6738        let (mut file, acls) = read_acls_owned(file, congestion::Side::Source, false).await?;
6739        assert_eq!(file.as_raw_fd(), raw_fd);
6740        assert_eq!(acls.access.as_deref(), Some(blob.as_slice()));
6741        assert_eq!(acls.default, None);
6742        let mut bytes = Vec::new();
6743        file.read_to_end(&mut bytes)?;
6744        assert_eq!(bytes, b"original");
6745        Ok(())
6746    }
6747
6748    #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
6749    #[tokio::test]
6750    async fn read_acls_fd_round_trips_an_access_acl() -> anyhow::Result<()> {
6751        let tmp = testutils::setup_test_dir().await?;
6752        let src_path = tmp.join("foo/acl_src");
6753        tokio::fs::write(&src_path, b"x").await?;
6754        let blob = restrictive_access_acl();
6755        set_xattr_at(&src_path, ACL_ACCESS_XATTR, &blob);
6756        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6757        let (file, _) = root.open_file_read(OsStr::new("acl_src")).await?;
6758        let acls = read_acls_fd(file.as_fd(), congestion::Side::Source, false).await?;
6759        // byte-identical: the blob is carried opaquely, never re-encoded
6760        assert_eq!(acls.access.as_deref(), Some(blob.as_slice()));
6761        assert_eq!(acls.default, None, "a file has no default ACL to read");
6762        Ok(())
6763    }
6764
6765    // An ACL far larger than the stack buffers, so BOTH `ERANGE` fallbacks run: the name list is
6766    // padded past 256 bytes with `user.*` attributes, and the blob past 512 by entry count (a blob
6767    // is `4 + 8n` bytes, so 64 entries fill the buffer exactly and 80 overflow it). Without the
6768    // retry paths this fails rather than silently truncating — `fgetxattr` refuses a short buffer.
6769    // tmpfs gained user.* xattr support in Linux 6.6, so older sandbox kernels cannot construct the
6770    // padded name list even apart from the POSIX ACL restriction
6771    #[cfg_attr(
6772        rcp_nix_sandbox,
6773        ignore = "Nix sandbox cannot provide both POSIX ACL and user xattrs this test requires"
6774    )]
6775    #[tokio::test]
6776    async fn read_acls_fd_reads_an_acl_larger_than_the_stack_buffers() -> anyhow::Result<()> {
6777        let tmp = testutils::setup_test_dir().await?;
6778        let src_path = tmp.join("foo/big_acl");
6779        tokio::fs::write(&src_path, b"x").await?;
6780        // canonical POSIX.1e order — USER_OBJ, named users by ascending uid, GROUP_OBJ, MASK,
6781        // OTHER. The kernel validates it and rejects anything else with EINVAL.
6782        let mut entries = vec![(ACL_USER_OBJ, 7, ACL_UNDEFINED_ID)];
6783        entries.extend((0..80).map(|i| (ACL_USER, 5, 100_000 + i)));
6784        entries.extend([
6785            (ACL_GROUP_OBJ, 0, ACL_UNDEFINED_ID),
6786            (ACL_MASK, 5, ACL_UNDEFINED_ID),
6787            (ACL_OTHER, 0, ACL_UNDEFINED_ID),
6788        ]);
6789        let blob = encode_acl(&entries);
6790        assert!(blob.len() > 512, "fixture must overflow the read buffer");
6791        set_xattr_at(&src_path, ACL_ACCESS_XATTR, &blob);
6792        // push the NAME list past its own 256-byte buffer too
6793        for i in 0..30 {
6794            let name = std::ffi::CString::new(format!("user.padding_attribute_number_{i:03}"))?;
6795            set_xattr_at(&src_path, &name, b"v");
6796        }
6797        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6798        let (file, _) = root.open_file_read(OsStr::new("big_acl")).await?;
6799        let acls = read_acls_fd(file.as_fd(), congestion::Side::Source, false).await?;
6800        assert_eq!(acls.access.as_deref(), Some(blob.as_slice()));
6801        Ok(())
6802    }
6803
6804    #[tokio::test]
6805    async fn read_acls_fd_reports_no_acl_when_there_is_none() -> anyhow::Result<()> {
6806        let tmp = testutils::setup_test_dir().await?;
6807        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6808        let (file, _) = root.open_file_read(OsStr::new("0.txt")).await?;
6809        let acls = read_acls_fd(file.as_fd(), congestion::Side::Source, false).await?;
6810        assert_eq!(acls, Acls::default(), "an entry with no xattrs has no ACL");
6811        Ok(())
6812    }
6813
6814    #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
6815    #[tokio::test]
6816    async fn read_acls_fd_reads_a_directorys_default_acl_only_when_asked() -> anyhow::Result<()> {
6817        let tmp = testutils::setup_test_dir().await?;
6818        let dir_path = tmp.join("foo/acl_dir");
6819        tokio::fs::create_dir(&dir_path).await?;
6820        let access = restrictive_access_acl();
6821        let default = permissive_acl();
6822        set_xattr_at(&dir_path, ACL_ACCESS_XATTR, &access);
6823        set_xattr_at(&dir_path, ACL_DEFAULT_XATTR, &default);
6824        let dir = Dir::open_root_dir(&dir_path, false, congestion::Side::Source).await?;
6825        let both = dir.read_acls().await?;
6826        assert_eq!(both.access.as_deref(), Some(access.as_slice()));
6827        assert_eq!(both.default.as_deref(), Some(default.as_slice()));
6828        // `want_default: false` is what the file path passes; it must not spend the extra syscall
6829        let access_only = read_acls_fd(dir.fd.as_fd(), congestion::Side::Source, false).await?;
6830        assert_eq!(access_only.access.as_deref(), Some(access.as_slice()));
6831        assert_eq!(access_only.default, None);
6832        Ok(())
6833    }
6834
6835    #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
6836    #[tokio::test]
6837    async fn apply_acls_fd_installs_the_source_acl_and_clears_what_the_source_lacked()
6838    -> anyhow::Result<()> {
6839        let tmp = testutils::setup_test_dir().await?;
6840        let dst_path = tmp.join("foo/applied");
6841        tokio::fs::write(&dst_path, b"x").await?;
6842        let root =
6843            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6844        let (file, _) = root.open_file_read(OsStr::new("applied")).await?;
6845        let blob = restrictive_access_acl();
6846        apply_acls_fd(
6847            file.as_fd(),
6848            congestion::Side::Destination,
6849            &Acls {
6850                access: Some(blob.clone()),
6851                default: None,
6852            },
6853            false,
6854        )
6855        .await?;
6856        assert_eq!(
6857            get_xattr_at(&dst_path, ACL_ACCESS_XATTR).as_deref(),
6858            Some(blob.as_slice())
6859        );
6860        // an all-`None` payload is a request to CLEAR, not to do nothing
6861        apply_acls_fd(
6862            file.as_fd(),
6863            congestion::Side::Destination,
6864            &Acls::default(),
6865            false,
6866        )
6867        .await?;
6868        assert_eq!(get_xattr_at(&dst_path, ACL_ACCESS_XATTR), None);
6869        // and clearing again, with nothing there, still succeeds (ENODATA is not a failure)
6870        apply_acls_fd(
6871            file.as_fd(),
6872            congestion::Side::Destination,
6873            &Acls::default(),
6874            false,
6875        )
6876        .await?;
6877        Ok(())
6878    }
6879
6880    #[tokio::test]
6881    async fn apply_acls_fd_fails_a_set_the_filesystem_cannot_hold_but_not_a_remove()
6882    -> anyhow::Result<()> {
6883        // `/proc` holds no xattrs at all, so both operations get EOPNOTSUPP — the asymmetry under
6884        // test is entirely in how each is interpreted.
6885        let probe = std::fs::File::open("/proc/self/environ")?;
6886        let error = apply_acls_fd(
6887            probe.as_fd(),
6888            congestion::Side::Destination,
6889            &Acls {
6890                access: Some(restrictive_access_acl()),
6891                default: None,
6892            },
6893            false,
6894        )
6895        .await
6896        .expect_err("a destination that cannot hold the source's ACL must fail the entry");
6897        assert_eq!(error.raw_os_error(), Some(libc::EOPNOTSUPP));
6898        // the same errno on a REMOVE says there is nothing to clear and nothing can have widened
6899        apply_acls_fd(
6900            probe.as_fd(),
6901            congestion::Side::Destination,
6902            &Acls::default(),
6903            false,
6904        )
6905        .await
6906        .expect("clearing an ACL a filesystem cannot hold is already satisfied");
6907        Ok(())
6908    }
6909
6910    // ORDERING, branch 1 (the source HAS an access ACL): the narrowed chmod carries the special
6911    // bits, the `fsetxattr` lands the rwx bits, and both survive together.
6912    #[cfg_attr(
6913        rcp_nix_sandbox,
6914        ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
6915    )]
6916    #[tokio::test]
6917    async fn set_file_metadata_owned_applies_a_setuid_source_mode_and_its_acl() -> anyhow::Result<()>
6918    {
6919        use std::io::Write;
6920        use std::os::unix::fs::PermissionsExt;
6921        let tmp = testutils::setup_test_dir().await?;
6922        let src_path = tmp.join("foo/acl_setuid_src");
6923        tokio::fs::write(&src_path, b"x").await?;
6924        std::fs::set_permissions(&src_path, std::fs::Permissions::from_mode(0o4700))?;
6925        let blob = restrictive_access_acl();
6926        set_xattr_at(&src_path, ACL_ACCESS_XATTR, &blob);
6927        // writing the ACL moved the source's own rwx bits to match it (USER_OBJ / MASK / OTHER);
6928        // that equality is exactly what the destination has to reproduce.
6929        assert_eq!(mode_of(&src_path), 0o4755, "fixture source mode");
6930        let root =
6931            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6932        let src_handle = root.child(OsStr::new("acl_setuid_src")).await?;
6933        let src_meta = src_handle.meta().clone();
6934        let mut dst_file = root.create_file(OsStr::new("acl_setuid_dst")).await?;
6935        dst_file.write_all(b"x")?;
6936        dst_file.flush()?;
6937        set_file_metadata_owned(
6938            &crate::preserve::preserve_all_with_acls(),
6939            &src_meta,
6940            Some(&Acls {
6941                access: Some(blob.clone()),
6942                default: None,
6943            }),
6944            dst_file.into(),
6945            congestion::Side::Destination,
6946        )
6947        .await?;
6948        let dst_path = tmp.join("foo/acl_setuid_dst");
6949        assert_eq!(
6950            mode_of(&dst_path),
6951            mode_of(&src_path),
6952            "the special bits come from the chmod and the rwx bits from the ACL; both must land"
6953        );
6954        assert_eq!(mode_of(&dst_path), 0o4755);
6955        assert_eq!(
6956            get_xattr_at(&dst_path, ACL_ACCESS_XATTR).as_deref(),
6957            Some(blob.as_slice()),
6958            "the destination must not be more permissive than its source"
6959        );
6960        Ok(())
6961    }
6962
6963    // ORDERING, branch 1 under failure: the `fsetxattr` IS the widening step, so when it fails the
6964    // file must be left unreachable by anyone but the copier. This is what pins the preceding chmod
6965    // to `(mode & 0o7000) | DST_FILE_CREATE_MODE`: widening there and failing here would publish a
6966    // setuid-root file whose copy is about to be reported as failed (PR #287's regression).
6967    #[cfg_attr(
6968        rcp_nix_sandbox,
6969        ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
6970    )]
6971    #[tokio::test]
6972    async fn set_file_metadata_owned_keeps_the_file_owner_only_when_the_acl_fails()
6973    -> anyhow::Result<()> {
6974        use std::os::unix::fs::PermissionsExt;
6975        let tmp = testutils::setup_test_dir().await?;
6976        let src_path = tmp.join("foo/acl_fail_src");
6977        tokio::fs::write(&src_path, b"x").await?;
6978        std::fs::set_permissions(&src_path, std::fs::Permissions::from_mode(0o4755))?;
6979        let root =
6980            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6981        let src_meta = root.child(OsStr::new("acl_fail_src")).await?.meta().clone();
6982        let dst_file = root.create_file(OsStr::new("acl_fail_dst")).await?;
6983        let dst_path = tmp.join("foo/acl_fail_dst");
6984        let error = set_file_metadata_owned(
6985            &crate::preserve::preserve_all_with_acls(),
6986            &src_meta,
6987            Some(&Acls {
6988                access: Some(rejected_access_acl()),
6989                default: None,
6990            }),
6991            dst_file.into(),
6992            congestion::Side::Destination,
6993        )
6994        .await
6995        .expect_err("an ACL the kernel rejects must fail the entry");
6996        assert_eq!(error.raw_os_error(), Some(libc::EINVAL));
6997        assert_eq!(
6998            mode_of(&dst_path),
6999            0o4000 | DST_FILE_CREATE_MODE,
7000            "the chmod preceding a source ACL must carry the special bits ALONE — a failed ACL \
7001             application left the file at a mode it had not earned"
7002        );
7003        Ok(())
7004    }
7005
7006    // ORDERING, branch 2 (the source has NO access ACL): the chmod is the widening step and stays
7007    // last, and the clear that precedes it is mode-neutral. Inverting the branch condition sends
7008    // this case down the narrowed-chmod path and leaves the file at 0o4600.
7009    #[cfg_attr(
7010        rcp_nix_sandbox,
7011        ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
7012    )]
7013    #[tokio::test]
7014    async fn set_file_metadata_owned_clears_an_inherited_acl_and_still_applies_the_full_mode()
7015    -> anyhow::Result<()> {
7016        use std::io::Write;
7017        use std::os::unix::fs::PermissionsExt;
7018        let tmp = testutils::setup_test_dir().await?;
7019        let src_path = tmp.join("foo/plain_setuid_src");
7020        tokio::fs::write(&src_path, b"x").await?;
7021        std::fs::set_permissions(&src_path, std::fs::Permissions::from_mode(0o4755))?;
7022        let root =
7023            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7024        let src_meta = root
7025            .child(OsStr::new("plain_setuid_src"))
7026            .await?
7027            .meta()
7028            .clone();
7029        let mut dst_file = root.create_file(OsStr::new("plain_setuid_dst")).await?;
7030        dst_file.write_all(b"x")?;
7031        dst_file.flush()?;
7032        let dst_path = tmp.join("foo/plain_setuid_dst");
7033        // stand in for what a permissive destination directory's default ACL would have left here
7034        set_xattr_at(&dst_path, ACL_ACCESS_XATTR, &permissive_acl());
7035        set_file_metadata_owned(
7036            &crate::preserve::preserve_all_with_acls(),
7037            &src_meta,
7038            Some(&Acls::default()),
7039            dst_file.into(),
7040            congestion::Side::Destination,
7041        )
7042        .await?;
7043        assert_eq!(
7044            get_xattr_at(&dst_path, ACL_ACCESS_XATTR),
7045            None,
7046            "a source with no ACL must leave the destination with no ACL"
7047        );
7048        assert_eq!(
7049            mode_of(&dst_path),
7050            0o4755,
7051            "without a source ACL the chmod is the widening step and applies the FULL mode"
7052        );
7053        Ok(())
7054    }
7055
7056    #[cfg_attr(
7057        rcp_nix_sandbox,
7058        ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
7059    )]
7060    #[tokio::test]
7061    async fn set_dir_metadata_fd_installs_access_and_default_acls() -> anyhow::Result<()> {
7062        let tmp = testutils::setup_test_dir().await?;
7063        let root =
7064            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7065        let src_dir_path = tmp.join("foo/acl_src_dir");
7066        tokio::fs::create_dir(&src_dir_path).await?;
7067        let access = restrictive_access_acl();
7068        let default = permissive_acl();
7069        set_xattr_at(&src_dir_path, ACL_ACCESS_XATTR, &access);
7070        set_xattr_at(&src_dir_path, ACL_DEFAULT_XATTR, &default);
7071        let src_meta = root.child(OsStr::new("acl_src_dir")).await?.meta().clone();
7072        let dst_dir = root.make_dir(OsStr::new("acl_dst_dir"), 0o700).await?;
7073        let dst_path = tmp.join("foo/acl_dst_dir");
7074        set_dir_metadata_fd(
7075            &crate::preserve::preserve_all_with_acls(),
7076            &src_meta,
7077            Some(&Acls {
7078                access: Some(access.clone()),
7079                default: Some(default.clone()),
7080            }),
7081            &dst_dir,
7082        )
7083        .await?;
7084        assert_eq!(
7085            get_xattr_at(&dst_path, ACL_ACCESS_XATTR).as_deref(),
7086            Some(access.as_slice())
7087        );
7088        assert_eq!(
7089            get_xattr_at(&dst_path, ACL_DEFAULT_XATTR).as_deref(),
7090            Some(default.as_slice()),
7091            "the default ACL decides what CHILDREN inherit; dropping it changes the destination \
7092             tree's inheritance policy"
7093        );
7094        assert_eq!(mode_of(&dst_path), mode_of(&src_dir_path));
7095        assert_eq!(mode_of(&dst_path), 0o755);
7096        Ok(())
7097    }
7098
7099    // The access ACL is applied LAST inside `apply_acls_fd` for the same reason it is applied last
7100    // in the file applier: it is the step that WIDENS. A default ACL the kernel rejects must
7101    // therefore fail while the directory is still at its owner-only create mode.
7102    #[cfg_attr(
7103        rcp_nix_sandbox,
7104        ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
7105    )]
7106    #[tokio::test]
7107    async fn set_dir_metadata_fd_keeps_the_dir_owner_only_when_the_default_acl_fails()
7108    -> anyhow::Result<()> {
7109        use std::os::unix::fs::PermissionsExt;
7110        let tmp = testutils::setup_test_dir().await?;
7111        let root =
7112            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7113        let src_dir_path = tmp.join("foo/acl_dfail_src");
7114        tokio::fs::create_dir(&src_dir_path).await?;
7115        std::fs::set_permissions(&src_dir_path, std::fs::Permissions::from_mode(0o755))?;
7116        let src_meta = root
7117            .child(OsStr::new("acl_dfail_src"))
7118            .await?
7119            .meta()
7120            .clone();
7121        let dst_dir = root.make_dir(OsStr::new("acl_dfail_dst"), 0o700).await?;
7122        let error = set_dir_metadata_fd(
7123            &crate::preserve::preserve_all_with_acls(),
7124            &src_meta,
7125            Some(&Acls {
7126                access: Some(permissive_acl()),
7127                default: Some(rejected_access_acl()),
7128            }),
7129            &dst_dir,
7130        )
7131        .await
7132        .expect_err("a default ACL the kernel rejects must fail the entry");
7133        assert_eq!(error.raw_os_error(), Some(libc::EINVAL));
7134        assert_eq!(
7135            mode_of(&tmp.join("foo/acl_dfail_dst")),
7136            DST_DIR_CREATE_MODE,
7137            "the access ACL must be applied LAST: a failing default apply left the directory wider"
7138        );
7139        Ok(())
7140    }
7141
7142    // The reused-directory finalize re-stats and verifies the mode it applied. Its `want_mode` is
7143    // still `masked_mode`, which stays correct with an ACL in play only because the source's own
7144    // rwx bits and its ACL are the same fact — worth a test rather than a comment, and worth doing
7145    // it on a SETGID directory, where the special bit comes from the chmod and the rwx bits from
7146    // the ACL.
7147    #[cfg_attr(
7148        rcp_nix_sandbox,
7149        ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
7150    )]
7151    #[tokio::test]
7152    async fn set_reused_dir_metadata_fd_verifies_a_setgid_source_with_an_acl() -> anyhow::Result<()>
7153    {
7154        use std::os::unix::fs::PermissionsExt;
7155        let tmp = testutils::setup_test_dir().await?;
7156        let root =
7157            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7158        let src_dir_path = tmp.join("foo/setgid_acl_src");
7159        tokio::fs::create_dir(&src_dir_path).await?;
7160        std::fs::set_permissions(&src_dir_path, std::fs::Permissions::from_mode(0o2700))?;
7161        let access = restrictive_access_acl();
7162        set_xattr_at(&src_dir_path, ACL_ACCESS_XATTR, &access);
7163        let src_meta = root
7164            .child(OsStr::new("setgid_acl_src"))
7165            .await?
7166            .meta()
7167            .clone();
7168        assert_eq!(
7169            mode_of(&src_dir_path),
7170            0o2755,
7171            "fixture must keep setgid alongside the ACL (whose MASK set the group bits)"
7172        );
7173        let dst_dir = root.make_dir(OsStr::new("setgid_acl_dst"), 0o700).await?;
7174        let (uid, gid) = {
7175            let meta = dst_dir.meta().await?;
7176            use crate::preserve::Metadata as _;
7177            (meta.uid(), meta.gid())
7178        };
7179        // `Some(lock)` is the strict-mode locked path — the one that verifies. The snapshot is
7180        // empty and irrelevant here: `d:acl` is on, so the SOURCE's ACL wins and the snapshot is
7181        // discarded.
7182        set_reused_dir_metadata_fd(
7183            &crate::preserve::preserve_all_with_acls(),
7184            &src_meta,
7185            Some(&Acls {
7186                access: Some(access.clone()),
7187                default: None,
7188            }),
7189            Some(ReusedDirLock {
7190                restore_owner: (uid, gid),
7191                state: Arc::new(std::sync::Mutex::new(DefaultAclGuard::Armed {
7192                    original: None,
7193                })),
7194                fd: Arc::clone(&dst_dir.fd),
7195                children_may_inherit: Arc::new(std::sync::atomic::AtomicBool::new(false)),
7196            }),
7197            &dst_dir,
7198        )
7199        .await?;
7200        let dst_path = tmp.join("foo/setgid_acl_dst");
7201        assert_eq!(
7202            mode_of(&dst_path),
7203            0o2755,
7204            "setgid from the chmod, rwx from the ACL"
7205        );
7206        assert_eq!(
7207            get_xattr_at(&dst_path, ACL_ACCESS_XATTR).as_deref(),
7208            Some(access.as_slice())
7209        );
7210        Ok(())
7211    }
7212
7213    #[tokio::test]
7214    async fn appliers_refuse_a_call_site_that_did_not_carry_acls() -> anyhow::Result<()> {
7215        let tmp = testutils::setup_test_dir().await?;
7216        let root =
7217            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7218        let src_meta = root.child(OsStr::new("0.txt")).await?.meta().clone();
7219        let dst_file = root.create_file(OsStr::new("no_acls_carried")).await?;
7220        // `acl` on but no payload: neither "leave it alone" nor "clear it" reproduces the source,
7221        // so the applier must refuse rather than silently pick one.
7222        let error = set_file_metadata_owned(
7223            &crate::preserve::preserve_all_with_acls(),
7224            &src_meta,
7225            None,
7226            dst_file.into(),
7227            congestion::Side::Destination,
7228        )
7229        .await
7230        .expect_err("requesting ACL preservation on a path that carries no ACLs must fail");
7231        assert_eq!(error.kind(), std::io::ErrorKind::Unsupported);
7232        // with `acl` off the same call site is correct and must stay silent
7233        let dst_file = root.create_file(OsStr::new("acls_not_requested")).await?;
7234        set_file_metadata_owned(
7235            &crate::preserve::preserve_all(),
7236            &src_meta,
7237            None,
7238            dst_file.into(),
7239            congestion::Side::Destination,
7240        )
7241        .await?;
7242        Ok(())
7243    }
7244
7245    #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
7246    #[tokio::test]
7247    async fn guarded_default_acl_write_is_skipped_once_disarmed() -> anyhow::Result<()> {
7248        let tmp = testutils::setup_test_dir().await?;
7249        let root =
7250            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7251        let dir = root.make_dir(OsStr::new("locked"), 0o700).await?;
7252        // a guard whose restore has already run (the owning future was cancelled and the guard
7253        // dropped): a finalize write that already started on the blocking pool must observe that
7254        // and SKIP — landing it would silently overwrite the restore
7255        let lock = ReusedDirLock {
7256            restore_owner: (0, 0),
7257            state: Arc::new(std::sync::Mutex::new(DefaultAclGuard::Disarmed)),
7258            fd: Arc::clone(&dir.fd),
7259            children_may_inherit: Arc::new(std::sync::atomic::AtomicBool::new(false)),
7260        };
7261        lock.write_default_acl_guarded(congestion::Side::Destination, restrictive_access_acl())
7262            .await?;
7263        assert_eq!(
7264            get_xattr_at(&tmp.join("foo/locked"), ACL_DEFAULT_XATTR),
7265            None,
7266            "a disarmed guard must refuse the write — landing it would undo the restore"
7267        );
7268        Ok(())
7269    }
7270}