Skip to main content

lean_ctx_cloud/tasks/
gate_run.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Where and how the gate's rerun runs: the gate's directories
3//! ([`GateDirs`]), the run's environment and command, and the locked
4//! files of the run tree (read-only during the run, compared with
5//! `spec_commit` after every command).
6//!
7//! - **Directories.** Private copies, the gate's `CARGO_HOME`, the run's
8//!   `CARGO_TARGET_DIR` and `TMPDIR` live under the Instance's data dir
9//!   (`work`, 0700). The run tree, where cargo runs, lives **outside
10//!   `$HOME`**, because cargo reads `.cargo/config.toml` in the working
11//!   directory and every parent, and `~/.cargo/config.toml` is common. A
12//!   run under any parent cargo config is refused. Each run gets its own
13//!   directory created **directly** in `runs`: `/run/user/<getuid()>`
14//!   (which the user cannot rename: its parent is root's; never the
15//!   caller's `XDG_RUNTIME_DIR`, N7), else `/tmp` (sticky, root's). No shared directory of the
16//!   user's sits between that per-run directory and `/`.
17//! - **Locked files.** Before the run they are made read-only (files 0444,
18//!   their directories 0555) and then pinned: content, device, inode, mode
19//!   and change time of every file and of every directory on its way; the
20//!   tree root's device and inode; the per-run directory that holds only
21//!   the tree, made 0555 too (device, inode, mode, change time); and every
22//!   directory above it up to `/` (device and inode, and a watch for a
23//!   rename of any of them, [`MoveWatch`]: inotify on Linux, kqueue on
24//!   macOS; elsewhere the change time of each one this user could rename).
25//!   After every
26//!   command each is compared, added files included. Any write, chmod or
27//!   rename during the run moves the change time or the inode, which a
28//!   process of the same user cannot set back, so a locked test rewritten
29//!   and restored within one command, or the tree, its per-run directory
30//!   or any directory above them swapped for a copy and back, still makes
31//!   the run a `locked_paths_changed` fail (R4-1, R5-1). Where no watch
32//!   exists, a `runs` given by hand inside a directory other processes
33//!   write to makes runs fail closed, never pass.
34//! - **Toolchain.** `HOME`, `~/.cargo/bin` and `~/.rustup` come from the
35//!   user's passwd entry, never from the caller's environment (the CLI
36//!   submit runs in the agent's process): a `CARGO_HOME` or `RUSTUP_HOME`
37//!   set to anything else refuses the run (R5-4).
38//! - **Windows.** The same run with the platform's own facts, never the
39//!   caller's environment either: the home is the profile known folder
40//!   (not `USERPROFILE`), the system directories come from
41//!   `GetSystemWindowsDirectoryW` and the Program Files and ProgramData
42//!   known folders (not `SystemRoot`/`PATH`), and the commands run in Git for Windows' `sh`
43//!   from there, so the POSIX command lines of a repository mean the same.
44//!   Windows has no change time a process cannot set back and no
45//!   [`MoveWatch`]: locked files are made read-only (attribute) and pinned
46//!   by content, attributes and write time, which a process of the same
47//!   user can restore. The rename-and-restore protection of the tree and
48//!   of the directories above it (R4-1, R5-1) is Unix-only, and the
49//!   default `runs` is the user's local temp directory (the known folder),
50//!   so a `~/.cargo/config.toml` refuses the run there.
51//!
52//! **Known gap:** the code of the judged commit (its library, proc-macros,
53//! path and registry dependencies with their build scripts) runs at build
54//! time as the same Unix user, and the code under test runs inside the test
55//! binary and can end it with exit 0. The harness report in
56//! `gate_report.rs` is evidence only against accidental and simple exits
57//! (a binary that ends before its summary, a locked test that never ran);
58//! it is no evidence against code under test that prints a complete,
59//! consistent forged report to the real stdout and exits 0 (N6). Build
60//! scripts and test-target keys changed against `spec_commit` are refused
61//! before the run, but code that runs anyway can act on the run in ways no
62//! file check sees. Only a sandboxed run with a read-only bind mount of
63//! the locked paths and no write access outside the run (on pounce, under
64//! the gate, ยง5) closes that. The same holds for a proc-macro of unlocked
65//! code that shadows the plain `#[test]` of a locked file by a route the
66//! parser does not see (a glob import or a prelude of unlocked code, N7):
67//! `#[macro_use] extern crate` on the mount chain and `use .. as test` are
68//! refused, other shadowing is not proven absent.
69
70use std::collections::BTreeMap;
71use std::io::Write as _;
72use std::path::{Path, PathBuf};
73use std::process::{Command, Stdio};
74use std::time::{Duration, Instant};
75
76use lean_ctx_protocol::cloud::gate::{LockedChange, under_locked};
77use sha2::{Digest as _, Sha256};
78
79use super::GateError;
80
81/// Cargo config files cargo reads from a directory and every parent.
82pub(super) const CARGO_CONFIGS: [&str; 2] = [".cargo/config", ".cargo/config.toml"];
83
84/// `name` as an executable file name of this platform (`cargo.exe` on
85/// Windows).
86#[cfg(test)]
87pub(super) fn exe(name: &str) -> String {
88    format!("{name}{}", std::env::consts::EXE_SUFFIX)
89}
90
91/// The system directories git and the gate's helpers run with, nothing of
92/// the caller's `PATH`: on Unix `/usr/local/bin`, `/opt/homebrew/bin`,
93/// `/usr/bin`, `/bin`.
94#[cfg(not(windows))]
95pub(super) fn system_dirs() -> Vec<PathBuf> {
96    ["/usr/local/bin", "/opt/homebrew/bin", "/usr/bin", "/bin"]
97        .iter()
98        .map(PathBuf::from)
99        .collect()
100}
101
102/// Windows: the Windows directory's `System32`, itself, `Wbem` and
103/// PowerShell, and Git for Windows' `cmd` (its `git.exe`) under Program
104/// Files, from the system's own answers ([`win::windows_dir`],
105/// [`win::program_files`]), never from `SystemRoot` or `PATH`.
106#[cfg(windows)]
107pub(super) fn system_dirs() -> Vec<PathBuf> {
108    let mut dirs = Vec::new();
109    if let Some(windows) = win::windows_dir() {
110        let system32 = windows.join("System32");
111        dirs.extend([
112            system32.clone(),
113            windows,
114            system32.join("Wbem"),
115            system32.join("WindowsPowerShell").join("v1.0"),
116        ]);
117    }
118    if let Some(pf) = win::program_files() {
119        dirs.push(pf.join("Git").join("cmd"));
120    }
121    dirs
122}
123
124/// [`system_dirs`] as a `PATH` value.
125pub(super) fn system_path() -> std::ffi::OsString {
126    std::env::join_paths(system_dirs()).unwrap_or_default()
127}
128
129/// The shell the gate's commands run in: `/bin/sh` on Unix, Git for
130/// Windows' `sh.exe` under Program Files on Windows.
131pub(super) fn shell() -> Result<PathBuf, GateError> {
132    #[cfg(windows)]
133    {
134        let sh = win::program_files()
135            .map(|pf| pf.join("Git").join("bin").join("sh.exe"))
136            .filter(|sh| sh.is_file())
137            .ok_or_else(|| {
138                GateError::Check(
139                    "the gate runs its commands in Git for Windows' sh (Program Files\\Git\\bin\\sh.exe), which is missing".into(),
140                )
141            })?;
142        Ok(sh)
143    }
144    #[cfg(not(windows))]
145    {
146        Ok(PathBuf::from("/bin/sh"))
147    }
148}
149
150/// The platform calls behind the Windows run: the system's own directories
151/// and a job object that holds the run's whole process tree.
152#[cfg(windows)]
153mod win {
154    use std::ffi::{OsString, c_void};
155    use std::os::windows::ffi::OsStringExt as _;
156    use std::path::PathBuf;
157
158    #[repr(C)]
159    struct Guid {
160        data1: u32,
161        data2: u16,
162        data3: u16,
163        data4: [u8; 8],
164    }
165
166    /// `FOLDERID_ProgramFiles` {905E63B6-C1BF-494E-B29C-65B732D3D21A}.
167    const FOLDERID_PROGRAM_FILES: Guid = Guid {
168        data1: 0x905E_63B6,
169        data2: 0xC1BF,
170        data3: 0x494E,
171        data4: [0xB2, 0x9C, 0x65, 0xB7, 0x32, 0xD3, 0xD2, 0x1A],
172    };
173
174    /// `FOLDERID_ProgramData` {62AB5D82-FDC1-4DC3-A9DD-070D1D495D97}.
175    const FOLDERID_PROGRAM_DATA: Guid = Guid {
176        data1: 0x62AB_5D82,
177        data2: 0xFDC1,
178        data3: 0x4DC3,
179        data4: [0xA9, 0xDD, 0x07, 0x0D, 0x1D, 0x49, 0x5D, 0x97],
180    };
181
182    #[repr(C)]
183    #[derive(Default)]
184    struct BasicLimits {
185        per_process_user_time_limit: i64,
186        per_job_user_time_limit: i64,
187        limit_flags: u32,
188        minimum_working_set_size: usize,
189        maximum_working_set_size: usize,
190        active_process_limit: u32,
191        affinity: usize,
192        priority_class: u32,
193        scheduling_class: u32,
194    }
195
196    #[repr(C)]
197    #[derive(Default)]
198    struct IoCounters {
199        counts: [u64; 6],
200    }
201
202    /// `JOBOBJECT_EXTENDED_LIMIT_INFORMATION`.
203    #[repr(C)]
204    #[derive(Default)]
205    struct ExtendedLimits {
206        basic: BasicLimits,
207        io: IoCounters,
208        process_memory_limit: usize,
209        job_memory_limit: usize,
210        peak_process_memory_used: usize,
211        peak_job_memory_used: usize,
212    }
213
214    const JOB_OBJECT_EXTENDED_LIMIT_INFORMATION: u32 = 9;
215    const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: u32 = 0x2000;
216
217    #[link(name = "kernel32")]
218    unsafe extern "system" {
219        fn GetSystemWindowsDirectoryW(buffer: *mut u16, size: u32) -> u32;
220        fn CreateJobObjectW(attributes: *mut c_void, name: *const u16) -> *mut c_void;
221        fn SetInformationJobObject(
222            job: *mut c_void,
223            class: u32,
224            info: *const c_void,
225            length: u32,
226        ) -> i32;
227        fn AssignProcessToJobObject(job: *mut c_void, process: *mut c_void) -> i32;
228        fn TerminateJobObject(job: *mut c_void, exit_code: u32) -> i32;
229        fn CloseHandle(handle: *mut c_void) -> i32;
230    }
231
232    #[link(name = "ntdll")]
233    unsafe extern "system" {
234        fn NtResumeProcess(process: *mut c_void) -> i32;
235    }
236
237    /// `CREATE_SUSPENDED`: the child's first thread waits until it is
238    /// resumed, so it starts nothing before it sits in the job.
239    pub(super) const CREATE_SUSPENDED: u32 = 0x0000_0004;
240
241    #[link(name = "shell32")]
242    unsafe extern "system" {
243        fn SHGetKnownFolderPath(
244            id: *const Guid,
245            flags: u32,
246            token: *mut c_void,
247            path: *mut *mut u16,
248        ) -> i32;
249    }
250
251    #[link(name = "ole32")]
252    unsafe extern "system" {
253        fn CoTaskMemFree(memory: *mut c_void);
254    }
255
256    /// The system's Windows directory (`C:\Windows`).
257    pub(super) fn windows_dir() -> Option<PathBuf> {
258        let mut buf = vec![0u16; 1024];
259        let len = u32::try_from(buf.len()).ok()?;
260        // SAFETY: writes at most `len` UTF-16 units into `buf`.
261        let n = unsafe { GetSystemWindowsDirectoryW(buf.as_mut_ptr(), len) };
262        let n = usize::try_from(n).ok()?;
263        (n > 0 && n < buf.len()).then(|| PathBuf::from(OsString::from_wide(&buf[..n])))
264    }
265
266    /// The Program Files known folder (`C:\Program Files`).
267    pub(super) fn program_files() -> Option<PathBuf> {
268        known_folder(&FOLDERID_PROGRAM_FILES)
269    }
270
271    /// The ProgramData known folder (`C:\ProgramData`), where the Visual
272    /// Studio setup lookup rustc uses to find the MSVC linker keeps its
273    /// instances.
274    pub(super) fn program_data() -> Option<PathBuf> {
275        known_folder(&FOLDERID_PROGRAM_DATA)
276    }
277
278    fn known_folder(id: &Guid) -> Option<PathBuf> {
279        let mut raw: *mut u16 = std::ptr::null_mut();
280        // SAFETY: the GUID lives across the call; on success `raw` is a
281        // NUL-terminated string the caller frees with CoTaskMemFree.
282        let hr = unsafe {
283            SHGetKnownFolderPath(
284                std::ptr::from_ref(id),
285                0,
286                std::ptr::null_mut(),
287                &raw mut raw,
288            )
289        };
290        let path = (hr == 0 && !raw.is_null()).then(|| {
291            let mut len = 0usize;
292            // SAFETY: `raw` is NUL-terminated (above); read up to the NUL.
293            unsafe {
294                while *raw.add(len) != 0 {
295                    len += 1;
296                }
297                PathBuf::from(OsString::from_wide(std::slice::from_raw_parts(raw, len)))
298            }
299        });
300        // SAFETY: frees what SHGetKnownFolderPath allocated (null is fine).
301        unsafe { CoTaskMemFree(raw.cast()) };
302        path
303    }
304
305    /// A job object that kills every process in it when it is closed or
306    /// terminated: the run's process tree (Git's `sh` launcher, the shell,
307    /// cargo and the test binaries), as the process group on Unix.
308    pub(super) struct Job(*mut c_void);
309
310    impl Job {
311        pub(super) fn new() -> Option<Self> {
312            // SAFETY: an anonymous job object, owned by the returned value.
313            let handle = unsafe { CreateJobObjectW(std::ptr::null_mut(), std::ptr::null()) };
314            if handle.is_null() {
315                return None;
316            }
317            let job = Self(handle);
318            let mut limits = ExtendedLimits::default();
319            limits.basic.limit_flags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
320            let size = u32::try_from(std::mem::size_of::<ExtendedLimits>()).ok()?;
321            // SAFETY: `limits` is the structure the class names, `size` its size.
322            let ok = unsafe {
323                SetInformationJobObject(
324                    job.0,
325                    JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
326                    (&raw const limits).cast(),
327                    size,
328                )
329            };
330            (ok != 0).then_some(job)
331        }
332
333        /// Put the suspended `child` (and so everything it will start) in the
334        /// job, then let it run. False when either step failed; the caller
335        /// then kills the child, which has not run a single instruction.
336        pub(super) fn assign_and_resume(&self, child: &std::process::Child) -> bool {
337            use std::os::windows::io::AsRawHandle as _;
338            let process = child.as_raw_handle().cast();
339            // SAFETY: both handles are valid while `self` and `child` live.
340            if unsafe { AssignProcessToJobObject(self.0, process) } == 0 {
341                return false;
342            }
343            // SAFETY: the child's process handle (full access), valid while
344            // `child` lives; NTSTATUS 0 is success.
345            unsafe { NtResumeProcess(process) == 0 }
346        }
347
348        /// Kill every process in the job.
349        pub(super) fn terminate(&self) {
350            // SAFETY: the job handle is valid while `self` lives.
351            unsafe {
352                TerminateJobObject(self.0, 1);
353            }
354        }
355    }
356
357    impl Drop for Job {
358        fn drop(&mut self) {
359            // SAFETY: closes the handle this value owns; KILL_ON_JOB_CLOSE
360            // ends whatever of the run is still alive.
361            unsafe {
362                CloseHandle(self.0);
363            }
364        }
365    }
366}
367
368/// The gate's directories: `work` under the Instance's data dir (private
369/// copies, the gate's `CARGO_HOME`, targets), `runs` outside `$HOME`, the
370/// directory each run's own directory is created in directly.
371#[derive(Debug, Clone, PartialEq, Eq)]
372pub struct GateDirs {
373    pub work: PathBuf,
374    pub runs: PathBuf,
375}
376
377impl GateDirs {
378    /// The directories of the Instance whose data dir is `data_dir`.
379    #[must_use]
380    pub fn for_instance(data_dir: &Path) -> Self {
381        let work = data_dir.join("g6");
382        Self {
383            work,
384            runs: default_runs(),
385        }
386    }
387}
388
389/// `/run/user/<getuid()>` when it is this user's directory (Linux: 0700,
390/// its parent root's), else `/tmp` as the system resolves it. Never the
391/// caller's `XDG_RUNTIME_DIR` (N7: it could name a mount of the user's own
392/// that raises no inotify event), and not the per-user temp dir on macOS:
393/// its parent is the user's, and other processes write to it all the time.
394/// On macOS `/tmp` is root's symlink to `/private/tmp`, and the gate refuses
395/// to run in a symlink, so the resolved directory is the base.
396fn default_runs() -> PathBuf {
397    #[cfg(unix)]
398    {
399        use std::os::unix::fs::MetadataExt as _;
400        // SAFETY: getuid takes no arguments and cannot fail.
401        let uid = unsafe { libc::getuid() };
402        let run = PathBuf::from(format!("/run/user/{uid}"));
403        if std::fs::symlink_metadata(&run).is_ok_and(|m| m.is_dir() && m.uid() == uid) {
404            return run;
405        }
406    }
407    #[cfg(windows)]
408    {
409        // No root-owned shared directory: the user's local temp directory
410        // from the known folder (never `TMP`/`TEMP`), see the module docs.
411        dirs::data_local_dir().map_or_else(std::env::temp_dir, |local| local.join("Temp"))
412    }
413    #[cfg(not(windows))]
414    {
415        std::fs::canonicalize("/tmp").unwrap_or_else(|_| PathBuf::from("/tmp"))
416    }
417}
418
419/// `path` resolved, without the Windows `\\?\` prefix: the form cargo,
420/// rustc's dep-info, git and Git's `sh` use, so paths compare as written.
421pub(super) fn resolved(path: &Path) -> std::io::Result<PathBuf> {
422    std::fs::canonicalize(path).map(lean_ctx::core::pathutil::strip_verbatim)
423}
424
425#[cfg(unix)]
426fn private_mode(dir: &Path) -> Result<(), GateError> {
427    use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
428    let meta = std::fs::symlink_metadata(dir)
429        .map_err(|e| GateError::Check(format!("{}: {e}", dir.display())))?;
430    // SAFETY: getuid takes no arguments and cannot fail.
431    let uid = unsafe { libc::getuid() };
432    if meta.file_type().is_symlink() || !meta.is_dir() || meta.uid() != uid {
433        return Err(GateError::Check(format!(
434            "{} is no directory of this user; the gate refuses to work in it",
435            dir.display()
436        )));
437    }
438    std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
439        .map_err(|e| GateError::Check(format!("{}: {e}", dir.display())))
440}
441
442#[cfg(not(unix))]
443fn private_mode(_dir: &Path) -> Result<(), GateError> {
444    Ok(())
445}
446
447/// `dir` created if needed, this user's, mode 0700.
448pub(super) fn make_private_dir(dir: &Path) -> Result<(), GateError> {
449    std::fs::create_dir_all(dir)
450        .map_err(|e| GateError::Check(format!("the gate's directory {}: {e}", dir.display())))?;
451    private_mode(dir)
452}
453
454/// A fresh private directory under `work` (private copies, the recheck,
455/// targets). Nothing runs cargo here, so parent configs do not matter.
456pub(super) fn private_dir(work: &Path) -> Result<tempfile::TempDir, GateError> {
457    make_private_dir(work)?;
458    // Resolved, so the run's variables name the long form (a Windows temp
459    // folder can be an 8.3 short name such as `RUNNER~1`).
460    let work = resolved(work).map_err(|e| GateError::Check(format!("the gate's work dir: {e}")))?;
461    tempfile::Builder::new()
462        .prefix("g6-")
463        .tempdir_in(&work)
464        .map_err(|e| GateError::Check(format!("a fresh directory: {e}")))
465}
466
467/// A fresh private directory for the run tree, created directly in `runs`
468/// (which is created private when missing, and left as it is otherwise:
469/// `/tmp` is root's), refused when `runs` or any parent holds a cargo
470/// config (cargo would read it in the run).
471pub(super) fn cargo_run_dir(runs: &Path) -> Result<tempfile::TempDir, GateError> {
472    match std::fs::symlink_metadata(runs) {
473        Ok(meta) if meta.is_dir() => {}
474        Ok(_) => {
475            return Err(GateError::Check(format!(
476                "{} is no directory; the gate refuses to run in it",
477                runs.display()
478            )));
479        }
480        Err(_) => make_private_dir(runs)?,
481    }
482    let canonical =
483        resolved(runs).map_err(|e| GateError::Check(format!("the gate's run directory: {e}")))?;
484    for dir in canonical.ancestors() {
485        for name in CARGO_CONFIGS {
486            let file = dir.join(Path::new(name).components().collect::<PathBuf>());
487            if std::fs::symlink_metadata(&file).is_ok() {
488                return Err(GateError::Check(format!(
489                    "{} lies above the gate's run directory, and cargo would read it in the rerun; the gate refuses to run under it",
490                    file.display()
491                )));
492            }
493        }
494    }
495    // tempfile creates it 0700.
496    tempfile::Builder::new()
497        .prefix("lean-ctx-g6-run-")
498        .tempdir_in(&canonical)
499        .map_err(|e| GateError::Check(format!("a fresh directory: {e}")))
500}
501
502/// This user's home from the passwd entry, never `$HOME` (R5-4).
503#[cfg(unix)]
504pub(super) fn user_home() -> Result<PathBuf, GateError> {
505    use std::ffi::{CStr, OsStr};
506    use std::os::unix::ffi::OsStrExt as _;
507    let mut buf = vec![0 as libc::c_char; 16 * 1024];
508    // SAFETY: a zeroed passwd is a valid out-parameter for getpwuid_r.
509    let mut pwd: libc::passwd = unsafe { std::mem::zeroed() };
510    let mut found: *mut libc::passwd = std::ptr::null_mut();
511    // SAFETY: getuid cannot fail; getpwuid_r writes only into `pwd` and
512    // `buf` (whose length it is given) and sets `found`.
513    let rc = unsafe {
514        libc::getpwuid_r(
515            libc::getuid(),
516            &raw mut pwd,
517            buf.as_mut_ptr(),
518            buf.len(),
519            &raw mut found,
520        )
521    };
522    if rc != 0 || found.is_null() || pwd.pw_dir.is_null() {
523        return Err(GateError::Check(
524            "this user has no passwd entry, so the gate cannot tell its home".into(),
525        ));
526    }
527    // SAFETY: pw_dir points into `buf`, NUL-terminated, while `buf` lives.
528    let dir = unsafe { CStr::from_ptr(pwd.pw_dir) };
529    let home = PathBuf::from(OsStr::from_bytes(dir.to_bytes()));
530    if !home.is_absolute() {
531        return Err(GateError::Check(
532            "this user's passwd home is not absolute".into(),
533        ));
534    }
535    Ok(home)
536}
537
538/// Windows: this user's profile from the known folder (`dirs` asks
539/// `SHGetKnownFolderPath(FOLDERID_Profile)`), never `USERPROFILE`/`HOME`.
540#[cfg(not(unix))]
541pub(super) fn user_home() -> Result<PathBuf, GateError> {
542    dirs::home_dir()
543        .filter(|home| home.is_absolute())
544        .ok_or_else(|| GateError::Check("this user has no profile directory".into()))
545}
546
547/// rustup's directories of `home`: `~/.cargo` (whose `bin` holds cargo) and
548/// `~/.rustup`. Refused when the caller's `CARGO_HOME` or `RUSTUP_HOME`
549/// names anything else: the CLI submit runs in the agent's process, so
550/// those would let the agent pick the cargo that judges it (R5-4).
551pub(super) fn toolchain_dirs(
552    home: &Path,
553    cargo_home: Option<&std::ffi::OsStr>,
554    rustup_home: Option<&std::ffi::OsStr>,
555) -> Result<(PathBuf, PathBuf), GateError> {
556    let fixed = (home.join(".cargo"), home.join(".rustup"));
557    let same = |given: &Path, fixed: &Path| {
558        given == fixed
559            || std::fs::canonicalize(given)
560                .is_ok_and(|g| std::fs::canonicalize(fixed).ok().as_ref() == Some(&g))
561    };
562    for (name, given, fixed) in [
563        ("CARGO_HOME", cargo_home, &fixed.0),
564        ("RUSTUP_HOME", rustup_home, &fixed.1),
565    ] {
566        if let Some(given) = given.filter(|g| !g.is_empty())
567            && !same(Path::new(given), fixed)
568        {
569            return Err(GateError::Check(format!(
570                "{name} is {}, not {}; the gate runs only rustup's toolchain of this user's home, so it refuses the run",
571                Path::new(given).display(),
572                fixed.display()
573            )));
574        }
575    }
576    Ok(fixed)
577}
578
579/// rustup's directories the run uses: [`toolchain_dirs`] of the passwd
580/// home, checked against the caller's `CARGO_HOME`/`RUSTUP_HOME`.
581#[cfg(not(test))]
582fn run_toolchain(home: &Path) -> Result<(PathBuf, PathBuf), GateError> {
583    toolchain_dirs(
584        home,
585        std::env::var_os("CARGO_HOME").as_deref(),
586        std::env::var_os("RUSTUP_HOME").as_deref(),
587    )
588}
589
590/// Unit tests only (never compiled into a binary): as in production when
591/// the passwd home has rustup's cargo. A home without it (CI's disposable
592/// test user, whose toolchain is the image's, with a job-local
593/// `CARGO_HOME`) runs the cargo fixtures with the toolchain of the test
594/// process instead: the first `cargo` on its `PATH` and its `RUSTUP_HOME`.
595/// The refusal itself is covered by `toolchain_dirs_refuse_a_differing_env`.
596#[cfg(test)]
597fn run_toolchain(home: &Path) -> Result<(PathBuf, PathBuf), GateError> {
598    if home.join(".cargo").join("bin").join(exe("cargo")).is_file() {
599        return toolchain_dirs(
600            home,
601            std::env::var_os("CARGO_HOME").as_deref(),
602            std::env::var_os("RUSTUP_HOME").as_deref(),
603        );
604    }
605    let path = std::env::var_os("PATH").unwrap_or_default();
606    let cargo_dir = std::env::split_paths(&path)
607        .find(|dir| dir.is_absolute() && dir.join(exe("cargo")).is_file())
608        .and_then(|bin| bin.parent().map(Path::to_path_buf))
609        .ok_or_else(|| GateError::Check("no cargo for the gate's test runs".into()))?;
610    let rustup = std::env::var_os("RUSTUP_HOME")
611        .filter(|v| !v.is_empty())
612        .map_or_else(|| home.join(".rustup"), PathBuf::from);
613    Ok((cargo_dir, rustup))
614}
615
616/// The environment of the gate's run: nothing inherited. A fixed `PATH`
617/// (the host's cargo gate in `~/.local/bin`, rustup's `~/.cargo/bin`, the
618/// system), `HOME` and rustup's home from the passwd entry
619/// ([`toolchain_dirs`]), the gate's own `CARGO_HOME` under `work`, and
620/// `CARGO_TARGET_DIR` and `TMPDIR` in `scratch`.
621///
622/// `~/.local/bin` and `~/.cargo/bin` are writable by the same Unix user
623/// (the known gap); they go once the run moves to pounce's gate.
624pub(super) fn run_env(
625    scratch: &Path,
626    work: &Path,
627) -> Result<Vec<(String, std::ffi::OsString)>, GateError> {
628    let home = user_home()?;
629    let (rustup_cargo, rustup) = run_toolchain(&home)?;
630    make_private_dir(work)?;
631    let work = resolved(work).map_err(|e| GateError::Check(format!("the gate's work dir: {e}")))?;
632    let cargo_home = work.join("cargo-home");
633    make_private_dir(&cargo_home)?;
634    for name in ["config", "config.toml", "credentials", "credentials.toml"] {
635        let file = cargo_home.join(name);
636        if std::fs::symlink_metadata(&file).is_ok() {
637            return Err(GateError::Check(format!(
638                "{} is in the gate's CARGO_HOME, which the gate never writes; refused",
639                file.display()
640            )));
641        }
642    }
643    let tmp = scratch.join("tmp");
644    make_private_dir(&tmp)?;
645    let mut dirs = vec![home.join(".local").join("bin"), rustup_cargo.join("bin")];
646    dirs.extend(system_dirs());
647    let path = std::env::join_paths(&dirs)
648        .map_err(|e| GateError::Check(format!("the run's PATH: {e}")))?;
649    let mut env: Vec<(String, std::ffi::OsString)> = vec![
650        ("PATH".into(), path),
651        ("HOME".into(), home.clone().into()),
652        ("LANG".into(), "C.UTF-8".into()),
653        ("CARGO_HOME".into(), cargo_home.into()),
654        ("CARGO_TARGET_DIR".into(), scratch.join("target").into()),
655        ("CARGO_TERM_COLOR".into(), "never".into()),
656        ("TMPDIR".into(), tmp.clone().into()),
657    ];
658    // Windows programs read their own names for the same places: the
659    // profile (rustup's and cargo's home lookup), the temp directory, and
660    // the Windows directory (process start-up, COM for the MSVC linker's
661    // lookup) and ProgramData (where that lookup finds the Visual Studio
662    // instances; without it rustc falls back to the `link.exe` on `PATH`,
663    // which in Git's `sh` is coreutils' `link`), all from the gate's facts
664    // above, known folders rather than the caller's variables.
665    #[cfg(windows)]
666    {
667        env.push(("USERPROFILE".into(), home.clone().into()));
668        env.push(("TEMP".into(), tmp.clone().into()));
669        env.push(("TMP".into(), tmp.into()));
670        if let Some(windows) = win::windows_dir() {
671            env.push(("SystemRoot".into(), windows.into()));
672        }
673        if let Some(data) = win::program_data() {
674            env.push(("ProgramData".into(), data.into()));
675        }
676    }
677    if rustup.is_dir() {
678        env.push(("RUSTUP_HOME".into(), rustup.into()));
679    }
680    Ok(env)
681}
682
683/// Run `command` in `dir` until `deadline`, its output appended to `log`;
684/// the exit code (`-1` when it was killed or ended by a signal). The
685/// command leads its own process group, which is killed on the deadline.
686pub(super) fn run_command(
687    dir: &Path,
688    command: &str,
689    env: &[(String, std::ffi::OsString)],
690    log: &mut std::fs::File,
691    deadline: Instant,
692) -> Result<i32, GateError> {
693    let out = log
694        .try_clone()
695        .map_err(|e| GateError::Check(format!("the run log: {e}")))?;
696    let err = log
697        .try_clone()
698        .map_err(|e| GateError::Check(format!("the run log: {e}")))?;
699    let mut cmd = Command::new(shell()?);
700    // Windows: the command goes to `sh` as a script file in the run's temp
701    // directory, so no Windows command-line quoting stands between the
702    // command and the shell.
703    #[cfg(windows)]
704    let _script = {
705        let tmp = env
706            .iter()
707            .find(|(k, _)| k == "TMPDIR")
708            .map(|(_, v)| PathBuf::from(v))
709            .ok_or_else(|| GateError::Check("the run has no temp directory".into()))?;
710        let mut file = tempfile::Builder::new()
711            .prefix("g6-command-")
712            .suffix(".sh")
713            .tempfile_in(&tmp)
714            .map_err(|e| GateError::Check(format!("the command file: {e}")))?;
715        file.write_all(command.as_bytes())
716            .map_err(|e| GateError::Check(format!("the command file: {e}")))?;
717        let path = file.into_temp_path();
718        cmd.arg(&*path);
719        path
720    };
721    #[cfg(not(windows))]
722    cmd.arg("-c").arg(command);
723    cmd.env_clear()
724        .envs(env.iter().map(|(k, v)| (k, v)))
725        .current_dir(dir)
726        .stdin(Stdio::null())
727        .stdout(out)
728        .stderr(err);
729    #[cfg(unix)]
730    {
731        use std::os::unix::process::CommandExt as _;
732        cmd.process_group(0);
733    }
734    // Windows: the job holds what the shell starts, as the process group on
735    // Unix. The child starts suspended and runs only once it is in the job,
736    // so nothing it starts can escape; without a job there is no run.
737    // Dropping the job at the end kills whatever of the run is left.
738    #[cfg(windows)]
739    let job = {
740        use std::os::windows::process::CommandExt as _;
741        cmd.creation_flags(win::CREATE_SUSPENDED);
742        win::Job::new().ok_or_else(|| GateError::Check("no job object for the run".into()))?
743    };
744    let mut child = cmd
745        .spawn()
746        .map_err(|e| GateError::Check(format!("the command did not start: {e}")))?;
747    #[cfg(windows)]
748    if !job.assign_and_resume(&child) {
749        let _ = child.kill();
750        let _ = child.wait();
751        return Err(GateError::Check(
752            "the run could not be held in its job object".into(),
753        ));
754    }
755    loop {
756        match child.try_wait() {
757            Ok(Some(status)) => return Ok(status.code().unwrap_or(-1)),
758            Ok(None) if Instant::now() >= deadline => {
759                #[cfg(unix)]
760                if let Ok(group) = i32::try_from(child.id()) {
761                    // SAFETY: signals the process group the child leads.
762                    unsafe {
763                        libc::kill(-group, libc::SIGKILL);
764                    }
765                }
766                #[cfg(windows)]
767                job.terminate();
768                let _ = child.kill();
769                let _ = child.wait();
770                let _ = writeln!(log, "\n[G6: the run passed its time limit and was stopped]");
771                return Ok(-1);
772            }
773            Ok(None) => std::thread::sleep(Duration::from_millis(50)),
774            Err(e) => return Err(GateError::Check(format!("waiting for the command: {e}"))),
775        }
776    }
777}
778
779/// The inode facts of an entry that a process of the same user cannot put
780/// back: device and inode (a rename over it gives another inode), mode, and
781/// the change time (any write, chmod, link or rename sets it to now, and no
782/// call sets it back).
783#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
784struct Stamp {
785    dev: u64,
786    ino: u64,
787    mode: u32,
788    ctime: i64,
789    ctime_ns: i64,
790}
791
792impl Stamp {
793    #[cfg(unix)]
794    fn of(meta: &std::fs::Metadata) -> Self {
795        use std::os::unix::fs::MetadataExt as _;
796        Self {
797            dev: meta.dev(),
798            ino: meta.ino(),
799            mode: meta.mode(),
800            ctime: meta.ctime(),
801            ctime_ns: meta.ctime_nsec(),
802        }
803    }
804
805    /// Windows has no change time a process cannot set back and no inode
806    /// in stable std: the attributes (read-only among them) and the last
807    /// write time, which a process of the same user can restore (module
808    /// docs).
809    #[cfg(windows)]
810    fn of(meta: &std::fs::Metadata) -> Self {
811        use std::os::windows::fs::MetadataExt as _;
812        let written = meta.last_write_time();
813        Self {
814            mode: meta.file_attributes(),
815            ctime: i64::try_from(written / 10_000_000).unwrap_or(i64::MAX),
816            ctime_ns: i64::try_from(written % 10_000_000).unwrap_or_default() * 100,
817            ..Self::default()
818        }
819    }
820
821    #[cfg(not(any(unix, windows)))]
822    fn of(_meta: &std::fs::Metadata) -> Self {
823        Self::default()
824    }
825}
826
827/// What a locked entry of the run tree is: a file or a symlink, by the
828/// sha256 of its content or link text, with its [`Stamp`].
829#[derive(Debug, Clone, PartialEq, Eq)]
830enum Held {
831    File(String, Stamp),
832    Link(String, Stamp),
833}
834
835/// Every file and symlink under a locked path in the run tree, keyed by its
836/// repository path, and every directory on the way to one (below the tree's
837/// root) with its [`Stamp`]. `root` is the tree root (compared by device and
838/// inode only, since cargo writing `Cargo.lock` moves its change time);
839/// `chain` is the private per-run directory that holds only the tree
840/// (compared whole, so renaming the tree in or out of it is seen) and every
841/// directory above it up to `/` ([`chain`]).
842#[derive(Debug, Clone, Default, PartialEq, Eq)]
843pub(super) struct LockedFiles {
844    held: BTreeMap<String, Held>,
845    dirs: BTreeMap<String, Option<Stamp>>,
846    root: Option<(u64, u64)>,
847    chain: Vec<(PathBuf, Option<Stamp>)>,
848}
849
850/// Whether this user could rename `dir`: its parent is this user's (who
851/// can chmod it writable) or writable by them now (`/tmp` is, sticky or
852/// not: they may rename their own entries there).
853#[cfg(unix)]
854fn movable(dir: &Path) -> bool {
855    use std::os::unix::ffi::OsStrExt as _;
856    use std::os::unix::fs::MetadataExt as _;
857    let Some(parent) = dir.parent() else {
858        return false;
859    };
860    // SAFETY: getuid takes no arguments and cannot fail.
861    let uid = unsafe { libc::getuid() };
862    if std::fs::metadata(parent).is_ok_and(|m| m.uid() == uid) {
863        return true;
864    }
865    let Ok(c) = std::ffi::CString::new(parent.as_os_str().as_bytes()) else {
866        return true;
867    };
868    // SAFETY: `c` is a NUL-terminated path that lives across the call.
869    unsafe { libc::access(c.as_ptr(), libc::W_OK) == 0 }
870}
871
872#[cfg(not(unix))]
873fn movable(_dir: &Path) -> bool {
874    true
875}
876
877/// The per-run directory `cradle` and every directory above it, each with
878/// its [`Stamp`]: whole for the per-run directory; device and inode for
879/// the rest, whose renames the [`MoveWatch`] sees (Linux, macOS). Where no
880/// watch sees them, also whole for every directory this user could rename
881/// ([`movable`]): swapping one for a copy and back renames it, which moves
882/// its change time (R5-1); entries other processes make there move it too,
883/// so such a `runs` fails closed. Root's
884/// directories (`/tmp`, `/`) keep device and inode only. On Windows only
885/// the per-run directory is compared (its attributes and write time; the
886/// directories above have no stamp a rename moves, module docs).
887fn chain(cradle: &Path) -> Vec<(PathBuf, Option<Stamp>)> {
888    cradle
889        .ancestors()
890        .enumerate()
891        .map(|(i, dir)| {
892            let stamp = std::fs::symlink_metadata(dir)
893                .ok()
894                .filter(std::fs::Metadata::is_dir)
895                .map(|m| {
896                    let s = Stamp::of(&m);
897                    if i == 0 || (cfg!(unix) && !MoveWatch::SEES_RENAMES && movable(dir)) {
898                        s
899                    } else {
900                        Stamp {
901                            dev: s.dev,
902                            ino: s.ino,
903                            ..Stamp::default()
904                        }
905                    }
906                });
907            (dir.to_path_buf(), stamp)
908        })
909        .collect()
910}
911
912/// Linux: an inotify watch for `IN_MOVE_SELF`/`IN_DELETE_SELF` on the
913/// per-run directory and every directory above it, set before the run. A
914/// rename of any of them during the run, even one put back, is an event
915/// (R5-1); entries other processes make there are not.
916#[cfg(target_os = "linux")]
917pub(super) struct MoveWatch(std::os::fd::OwnedFd);
918
919#[cfg(target_os = "linux")]
920impl MoveWatch {
921    pub(super) fn new(cradle: &Path) -> Result<Self, GateError> {
922        use std::os::fd::{AsRawFd as _, FromRawFd as _};
923        use std::os::unix::ffi::OsStrExt as _;
924        // SAFETY: plain syscall; the fd is owned right below.
925        let raw = unsafe { libc::inotify_init1(libc::IN_NONBLOCK | libc::IN_CLOEXEC) };
926        if raw < 0 {
927            return Err(GateError::Check(format!(
928                "watching the run directory: {}",
929                std::io::Error::last_os_error()
930            )));
931        }
932        // SAFETY: `raw` is a fresh fd nothing else owns.
933        let fd = unsafe { std::os::fd::OwnedFd::from_raw_fd(raw) };
934        for dir in cradle.ancestors() {
935            let c = std::ffi::CString::new(dir.as_os_str().as_bytes())
936                .map_err(|_| GateError::Check("a run path with a NUL byte".into()))?;
937            // SAFETY: `c` is NUL-terminated and lives across the call.
938            let wd = unsafe {
939                libc::inotify_add_watch(
940                    fd.as_raw_fd(),
941                    c.as_ptr(),
942                    libc::IN_MOVE_SELF | libc::IN_DELETE_SELF | libc::IN_ONLYDIR,
943                )
944            };
945            if wd < 0 {
946                return Err(GateError::Check(format!(
947                    "watching {}: {}",
948                    dir.display(),
949                    std::io::Error::last_os_error()
950                )));
951            }
952        }
953        Ok(Self(fd))
954    }
955
956    /// Whether any watched directory was renamed or removed (or the queue
957    /// overflowed, or reading failed: fail closed).
958    pub(super) fn moved(&self) -> bool {
959        use std::os::fd::AsRawFd as _;
960        let mut buf = [0u8; 4096];
961        // SAFETY: reads at most `buf.len()` bytes into `buf`.
962        let n = unsafe { libc::read(self.0.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len()) };
963        !(n < 0 && std::io::Error::last_os_error().kind() == std::io::ErrorKind::WouldBlock)
964    }
965}
966
967#[cfg(target_os = "linux")]
968impl MoveWatch {
969    /// [`chain`] compares the directories above the per-run one by device
970    /// and inode only: this watch sees their renames.
971    const SEES_RENAMES: bool = true;
972}
973
974/// macOS: a kqueue `EVFILT_VNODE` filter for `NOTE_RENAME`/`NOTE_DELETE`/
975/// `NOTE_REVOKE` on the per-run directory and every directory above it,
976/// each held open (`O_EVTONLY`) from before the run. A rename of any of
977/// them during the run, even one put back, is an event (R5-1); entries
978/// other processes make there are not (their `NOTE_WRITE` is not asked for).
979#[cfg(target_vendor = "apple")]
980pub(super) struct MoveWatch {
981    queue: std::os::fd::OwnedFd,
982    _dirs: Vec<std::os::fd::OwnedFd>,
983}
984
985#[cfg(target_vendor = "apple")]
986impl MoveWatch {
987    const SEES_RENAMES: bool = true;
988
989    pub(super) fn new(cradle: &Path) -> Result<Self, GateError> {
990        use std::os::fd::{AsRawFd as _, FromRawFd as _, OwnedFd};
991        use std::os::unix::ffi::OsStrExt as _;
992        let fail = |what: &Path| {
993            GateError::Check(format!(
994                "watching {}: {}",
995                what.display(),
996                std::io::Error::last_os_error()
997            ))
998        };
999        // SAFETY: plain syscall; the fd is owned right below.
1000        let raw = unsafe { libc::kqueue() };
1001        if raw < 0 {
1002            return Err(fail(cradle));
1003        }
1004        // SAFETY: `raw` is a fresh fd nothing else owns.
1005        let queue = unsafe { OwnedFd::from_raw_fd(raw) };
1006        let mut dirs = Vec::new();
1007        for dir in cradle.ancestors() {
1008            let c = std::ffi::CString::new(dir.as_os_str().as_bytes())
1009                .map_err(|_| GateError::Check("a run path with a NUL byte".into()))?;
1010            // SAFETY: `c` is NUL-terminated and lives across the call.
1011            let fd = unsafe {
1012                libc::open(
1013                    c.as_ptr(),
1014                    libc::O_EVTONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
1015                )
1016            };
1017            if fd < 0 {
1018                return Err(fail(dir));
1019            }
1020            // SAFETY: `fd` is a fresh fd nothing else owns.
1021            let fd = unsafe { OwnedFd::from_raw_fd(fd) };
1022            let ident = usize::try_from(fd.as_raw_fd()).map_err(|_| fail(dir))?;
1023            let change = libc::kevent {
1024                ident,
1025                filter: libc::EVFILT_VNODE,
1026                flags: libc::EV_ADD | libc::EV_CLEAR,
1027                fflags: libc::NOTE_RENAME | libc::NOTE_DELETE | libc::NOTE_REVOKE,
1028                data: 0,
1029                udata: std::ptr::null_mut(),
1030            };
1031            // SAFETY: one change from a live local, no event buffer.
1032            let added = unsafe {
1033                libc::kevent(
1034                    queue.as_raw_fd(),
1035                    &raw const change,
1036                    1,
1037                    std::ptr::null_mut(),
1038                    0,
1039                    std::ptr::null(),
1040                )
1041            };
1042            if added < 0 {
1043                return Err(fail(dir));
1044            }
1045            dirs.push(fd);
1046        }
1047        Ok(Self { queue, _dirs: dirs })
1048    }
1049
1050    /// Whether any watched directory was renamed or removed (or polling
1051    /// failed: fail closed).
1052    pub(super) fn moved(&self) -> bool {
1053        use std::os::fd::AsRawFd as _;
1054        // SAFETY: kevent is plain old data; all zeroes is a valid value.
1055        let mut event: libc::kevent = unsafe { std::mem::zeroed() };
1056        let now = libc::timespec {
1057            tv_sec: 0,
1058            tv_nsec: 0,
1059        };
1060        // SAFETY: no changes; room for one event in a live local; zero wait.
1061        let n = unsafe {
1062            libc::kevent(
1063                self.queue.as_raw_fd(),
1064                std::ptr::null(),
1065                0,
1066                &raw mut event,
1067                1,
1068                &raw const now,
1069            )
1070        };
1071        n != 0
1072    }
1073}
1074
1075/// Elsewhere the change times of [`chain`] do this job.
1076#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
1077pub(super) struct MoveWatch;
1078
1079#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
1080impl MoveWatch {
1081    const SEES_RENAMES: bool = false;
1082
1083    #[allow(clippy::unnecessary_wraps)]
1084    pub(super) fn new(_cradle: &Path) -> Result<Self, GateError> {
1085        Ok(Self)
1086    }
1087
1088    pub(super) fn moved(&self) -> bool {
1089        false
1090    }
1091}
1092
1093impl LockedFiles {
1094    /// Read the locked entries of `tree` (symlinks are not followed).
1095    pub(super) fn read(tree: &Path, locked: &[String]) -> Result<Self, GateError> {
1096        let mut held = BTreeMap::new();
1097        if !locked.is_empty() {
1098            walk(tree, tree, &mut |rel, path, meta| {
1099                if !locked.iter().any(|c| under_locked(rel, c)) {
1100                    return Ok(());
1101                }
1102                let fail = |e: std::io::Error| GateError::Check(format!("reading {rel}: {e}"));
1103                let stamp = Stamp::of(meta);
1104                let entry = if meta.file_type().is_symlink() {
1105                    let target = std::fs::read_link(path).map_err(fail)?;
1106                    Held::Link(
1107                        hex::encode(Sha256::digest(target.to_string_lossy().as_bytes())),
1108                        stamp,
1109                    )
1110                } else {
1111                    Held::File(
1112                        hex::encode(Sha256::digest(std::fs::read(path).map_err(fail)?)),
1113                        stamp,
1114                    )
1115                };
1116                held.insert(rel.to_owned(), entry);
1117                Ok(())
1118            })?;
1119        }
1120        let mut dirs = BTreeMap::new();
1121        for rel in held.keys() {
1122            for dir in parents(rel) {
1123                dirs.entry(dir.clone()).or_insert_with(|| {
1124                    std::fs::symlink_metadata(tree.join(&dir))
1125                        .ok()
1126                        .filter(std::fs::Metadata::is_dir)
1127                        .map(|m| Stamp::of(&m))
1128                });
1129            }
1130        }
1131        // The tree root and the directories above it: a swap of the whole
1132        // tree, or of a directory above it, touches no entry inside, only
1133        // these (R4-1, R5-1).
1134        let root = std::fs::symlink_metadata(tree)
1135            .ok()
1136            .filter(std::fs::Metadata::is_dir)
1137            .map(|m| {
1138                let s = Stamp::of(&m);
1139                (s.dev, s.ino)
1140            });
1141        let chain = tree.parent().map(chain).unwrap_or_default();
1142        Ok(Self {
1143            held,
1144            dirs,
1145            root,
1146            chain,
1147        })
1148    }
1149
1150    /// How the tree's locked entries now differ from `self`, the tree as
1151    /// `spec_commit` holds it once locked. A file whose content, mode, inode
1152    /// or change time differs is `modified`, whatever it holds now; a
1153    /// directory on its way that changed does the same to every file below.
1154    /// Re-reads only the pinned directories, so an entry added elsewhere
1155    /// under a locked path comes from the walk.
1156    /// `moved`: the [`MoveWatch`] saw a directory above the tree renamed.
1157    pub(super) fn changes(
1158        &self,
1159        tree: &Path,
1160        now: &Self,
1161        moved: bool,
1162    ) -> BTreeMap<String, LockedChange> {
1163        let mut changed = BTreeMap::new();
1164        for (path, was) in &self.held {
1165            match now.held.get(path) {
1166                None => {
1167                    changed.insert(path.clone(), LockedChange::Deleted);
1168                }
1169                Some(is) if std::mem::discriminant(is) != std::mem::discriminant(was) => {
1170                    changed.insert(path.clone(), LockedChange::TypeChanged);
1171                }
1172                Some(is) if is != was => {
1173                    changed.insert(path.clone(), LockedChange::Modified);
1174                }
1175                Some(_) => {}
1176            }
1177        }
1178        for (dir, was) in &self.dirs {
1179            let is = std::fs::symlink_metadata(tree.join(dir))
1180                .ok()
1181                .filter(std::fs::Metadata::is_dir)
1182                .map(|m| Stamp::of(&m));
1183            if is != *was {
1184                for path in self
1185                    .held
1186                    .keys()
1187                    .filter(|p| p.starts_with(&format!("{dir}/")))
1188                {
1189                    changed
1190                        .entry(path.clone())
1191                        .or_insert(LockedChange::Modified);
1192                }
1193            }
1194        }
1195        for path in now.held.keys() {
1196            if !self.held.contains_key(path) {
1197                changed.insert(path.clone(), LockedChange::Added);
1198            }
1199        }
1200        // The tree root swapped, or the per-run directory or one above it
1201        // touched: every locked file is suspect, whatever its own stamp
1202        // says now.
1203        let root_moved = self.root.is_some() && self.root != now.root;
1204        let chain_moved = moved || self.chain != now.chain;
1205        if (root_moved || chain_moved) && !self.held.is_empty() {
1206            for path in self.held.keys() {
1207                changed
1208                    .entry(path.clone())
1209                    .or_insert(LockedChange::Modified);
1210            }
1211        }
1212        changed
1213    }
1214
1215    /// Make every locked file read-only (0444) and every directory on its
1216    /// way below the tree's root 0555, so a plain write of the run fails.
1217    /// Read the entries again afterwards: the chmod moves their change time.
1218    #[cfg(unix)]
1219    pub(super) fn lock(&self, tree: &Path) -> Result<(), GateError> {
1220        use std::os::unix::fs::PermissionsExt as _;
1221        let set = |path: &Path, mode: u32| {
1222            std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))
1223                .map_err(|e| GateError::Check(format!("{}: {e}", path.display())))
1224        };
1225        for (rel, held) in &self.held {
1226            if matches!(held, Held::File(..)) {
1227                set(&tree.join(rel), 0o444)?;
1228            }
1229        }
1230        for dir in self.dirs.keys() {
1231            set(&tree.join(dir), 0o555)?;
1232        }
1233        // The per-run directory holds only the tree: read-only, so moving
1234        // the tree out or back must first change its mode and change time
1235        // (R4-1). [`Unlock`] on that directory opens it again.
1236        if let Some(cradle) = tree.parent() {
1237            set(cradle, 0o555)?;
1238        }
1239        Ok(())
1240    }
1241
1242    /// Windows: every locked file gets the read-only attribute (directories
1243    /// have none that stops a write).
1244    #[cfg(not(unix))]
1245    pub(super) fn lock(&self, tree: &Path) -> Result<(), GateError> {
1246        for (rel, held) in &self.held {
1247            if matches!(held, Held::File(..)) {
1248                let path = tree.join(rel);
1249                let mut perms = std::fs::symlink_metadata(&path)
1250                    .map_err(|e| GateError::Check(format!("{}: {e}", path.display())))?
1251                    .permissions();
1252                perms.set_readonly(true);
1253                std::fs::set_permissions(&path, perms)
1254                    .map_err(|e| GateError::Check(format!("{}: {e}", path.display())))?;
1255            }
1256        }
1257        Ok(())
1258    }
1259}
1260
1261/// The directories on the way to the repository path `rel`, below the root.
1262fn parents(rel: &str) -> Vec<String> {
1263    let mut out = Vec::new();
1264    let mut parent = Path::new(rel).parent();
1265    while let Some(dir) = parent.filter(|d| !d.as_os_str().is_empty()) {
1266        out.push(dir.to_string_lossy().replace('\\', "/"));
1267        parent = dir.parent();
1268    }
1269    out
1270}
1271
1272/// Visit every entry below `dir` (symlinks not followed) with its path
1273/// relative to `root`; directories are descended into, not visited.
1274fn walk(
1275    root: &Path,
1276    dir: &Path,
1277    visit: &mut dyn FnMut(&str, &Path, &std::fs::Metadata) -> Result<(), GateError>,
1278) -> Result<(), GateError> {
1279    let entries = std::fs::read_dir(dir)
1280        .map_err(|e| GateError::Check(format!("reading {}: {e}", dir.display())))?;
1281    for entry in entries {
1282        let entry = entry.map_err(|e| GateError::Check(format!("reading the tree: {e}")))?;
1283        let path = entry.path();
1284        let meta = std::fs::symlink_metadata(&path)
1285            .map_err(|e| GateError::Check(format!("{}: {e}", path.display())))?;
1286        if meta.is_dir() {
1287            walk(root, &path, visit)?;
1288            continue;
1289        }
1290        let rel = path
1291            .strip_prefix(root)
1292            .map_err(|_| GateError::Check("a path outside the run tree".into()))?
1293            .to_string_lossy()
1294            .replace('\\', "/");
1295        visit(&rel, &path, &meta)?;
1296    }
1297    Ok(())
1298}
1299
1300/// Makes every directory of the run tree writable again when dropped (on
1301/// Windows every read-only file), so the tree can be removed whatever the
1302/// run left read-only.
1303pub(super) struct Unlock(pub(super) PathBuf);
1304
1305impl Drop for Unlock {
1306    fn drop(&mut self) {
1307        fn open_up(dir: &Path) {
1308            #[cfg(unix)]
1309            {
1310                use std::os::unix::fs::PermissionsExt as _;
1311                let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
1312            }
1313            if let Ok(entries) = std::fs::read_dir(dir) {
1314                for entry in entries.flatten() {
1315                    let path = entry.path();
1316                    match std::fs::symlink_metadata(&path) {
1317                        Ok(m) if m.is_dir() => open_up(&path),
1318                        #[cfg(not(unix))]
1319                        Ok(m) if m.is_file() && m.permissions().readonly() => {
1320                            let mut perms = m.permissions();
1321                            #[expect(
1322                                clippy::permissions_set_readonly_false,
1323                                reason = "Windows: clears the read-only attribute, no mode bits"
1324                            )]
1325                            perms.set_readonly(false);
1326                            let _ = std::fs::set_permissions(&path, perms);
1327                        }
1328                        _ => {}
1329                    }
1330                }
1331            }
1332        }
1333        open_up(&self.0);
1334    }
1335}