Skip to main content

runner_manager_platform/
process.rs

1// owner: d1-platform-core
2
3//! Spawning, observing and terminating a child process; a process identity
4//! that survives a restart; and the restrictive handoff that gets a JIT
5//! configuration to a runner without it ever appearing in a process listing.
6//!
7//! # A PID is not an identity
8//!
9//! The agent records the runner processes it started in a durable journal and
10//! reads that journal back after a restart (`03-control-flows.md`, flow 3.2).
11//! If the record were a bare PID, then after a reboot — or after enough process
12//! churn — the PID in the journal may belong to somebody else's process. Acting
13//! on that record means either adopting a stranger as a runner or, worse,
14//! terminating it. `e3`'s restart-recovery Definition of Done ("a journal
15//! containing a live process adopts it without starting a duplicate") rests
16//! entirely on telling those cases apart.
17//!
18//! So [`ProcessIdentity`] is a PID **plus a start token**: an opaque,
19//! platform-defined string that changes when the process at that PID changes.
20//! [`ProcessIdentity::recheck`] re-resolves the token and answers
21//! [`Adoption::Live`], [`Adoption::Gone`], or [`Adoption::PidRecycled`] — three
22//! answers, because collapsing the last two into "not live" is exactly the bug
23//! this type exists to prevent.
24//!
25//! | | Start token | Resolution | Distinct across a reboot |
26//! |---|---|---|---|
27//! | Windows | `GetProcessTimes` creation `FILETIME` | 100 ns | yes, it is an absolute time |
28//! | macOS | `proc_pidinfo(PROC_PIDTBSDINFO)` start `timeval` | 1 µs | yes, it is an absolute time |
29//! | Linux | boot id + `/proc/<pid>/stat` field 22 | one clock tick, typically 10 ms | yes, the boot id changes every boot |
30//!
31//! The Linux token pairs the boot identifier with the raw tick count rather
32//! than converting ticks to a wall-clock time. Field 22 counts ticks *since
33//! boot*, so on its own it repeats after every reboot; and dividing by
34//! `sysconf(_SC_CLK_TCK)` and adding `btime` would produce an absolute time
35//! whose precision is bounded by `btime`'s whole seconds — coarser than the
36//! ticks it was derived from, and coarser than a PID-recycling discriminator
37//! wants. Prefixing the tick count with `/proc/sys/kernel/random/boot_id`
38//! keeps the full tick resolution *and* makes the token unrepeatable across a
39//! reboot. See [`Adoption`] for what that buys.
40//!
41//! # The JIT configuration never becomes an argument
42//!
43//! `07-security.md`'s threat table: *"A process listing reveals a JIT config"*,
44//! controlled by *"Do not pass JIT data as a command-line argument; use
45//! restrictive file/pipe handoff"*. [`RestrictiveHandoff`] is that file, and
46//! [`SpawnSpec::spawn_with_handoff`] refuses to spawn when the payload appears
47//! in any argument or environment value, so an obvious mistake fails the launch
48//! instead of failing a review. [`SpawnSpec::spawn_runner_with_handoff`] is the
49//! one narrow exception: GitHub Runner's supported JIT intake is the secret
50//! `ACTIONS_RUNNER_INPUT_JITCONFIG` environment input. The value is injected
51//! only while creating the child, is never retained in the public spawn spec,
52//! and Runner masks and removes it as its command parser starts.
53//!
54//! **It is a tripwire, not a proof.** A caller that passes it has not been
55//! shown to be safe. The check looks for the payload as a verbatim substring of
56//! each argument's and each environment *value's* `to_string_lossy()`, and that
57//! is all it looks for. It does not inspect the program path, the working
58//! directory, or environment variable *names*; and anything that re-encodes the
59//! payload — base64 of the base64, URL-escaping, a different Unicode
60//! normalisation — or splits it across two arguments walks straight past it.
61//! The control that actually holds is either *"pass the handoff file's path"*
62//! to a program that supports one or use the dedicated Runner intake above;
63//! `e3` must not read a passing generic check as evidence that a configuration
64//! cannot reach a process listing.
65
66use std::ffi::{OsStr, OsString};
67use std::fmt;
68use std::path::{Path, PathBuf};
69use std::process::{Child, Command, ExitStatus, Stdio};
70use std::time::{Duration, Instant};
71
72use secrecy::{ExposeSecret, SecretString};
73use serde::{Deserialize, Serialize};
74
75/// GitHub Runner's supported process-safe JIT configuration input.
76///
77/// `actions/runner` v2.336.0 reads every `ACTIONS_RUNNER_INPUT_*` variable in
78/// `CommandSettings`, registers secret inputs with its masker, and removes the
79/// variable from its environment before `Runner.ExecuteCommand` decodes it.
80const RUNNER_JIT_CONFIG_ENV: &str = "ACTIONS_RUNNER_INPUT_JITCONFIG";
81
82// ---------------------------------------------------------------------------
83// Errors
84// ---------------------------------------------------------------------------
85
86/// Something went wrong spawning, observing, or identifying a process.
87#[derive(Debug, thiserror::Error)]
88pub enum ProcessError {
89    /// The program could not be launched.
90    #[error("cannot start {}: {source}", program.display())]
91    Spawn {
92        /// The program that could not be launched.
93        program: PathBuf,
94        /// The underlying error.
95        #[source]
96        source: std::io::Error,
97    },
98
99    /// The operating system would not say when a process started.
100    #[error("cannot read the start time of process {pid}: {source}")]
101    Identity {
102        /// The process that could not be identified.
103        pid: u32,
104        /// The underlying error.
105        #[source]
106        source: std::io::Error,
107    },
108
109    /// No live process holds this PID, so it has no identity to record.
110    #[error("no live process holds PID {pid}")]
111    NoSuchProcess {
112        /// The PID that resolved to nothing.
113        pid: u32,
114    },
115
116    /// Waiting on, signalling, or killing a process failed.
117    #[error("cannot control process {pid}: {source}")]
118    Control {
119        /// The process that could not be controlled.
120        pid: u32,
121        /// The underlying error.
122        #[source]
123        source: std::io::Error,
124    },
125
126    /// The handoff payload was about to be visible in a process listing.
127    ///
128    /// Returned by [`SpawnSpec::spawn_with_handoff`] rather than logged,
129    /// because the whole point is that the launch must not happen.
130    #[error(
131        "refusing to start {}: the handoff payload appears in {location}, which would put \
132         it in this machine's process listing. Pass the handoff file's path instead \
133         (`07-security.md`, threat table).",
134        program.display()
135    )]
136    SecretInCommandLine {
137        /// The program that would have been launched.
138        program: PathBuf,
139        /// Where the payload was found — an argument index or an environment
140        /// variable name.
141        location: String,
142    },
143}
144
145// ---------------------------------------------------------------------------
146// Process identity
147// ---------------------------------------------------------------------------
148
149/// A PID paired with a token that changes when the process at that PID does.
150///
151/// Serializable because its whole reason to exist is being written to the
152/// attempt journal and read back after a restart. The token is opaque: its
153/// shape is documented at the module level for diagnostics, but nothing should
154/// parse it. Comparison — not interpretation — is the operation it supports.
155#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
156pub struct ProcessIdentity {
157    pid: u32,
158    start_token: String,
159}
160
161/// The start token of a child that was gone before its identity could be read.
162///
163/// Deliberately not a value any platform produces: every real token is
164/// `<platform>:<instant>`, so this can never compare equal to a live process
165/// and never claims a start instant that was not observed. See
166/// [`ProcessIdentity::of_child`].
167const EXITED_BEFORE_IDENTIFIED: &str = "exited-before-identified";
168
169/// What a recorded [`ProcessIdentity`] turns out to refer to now.
170///
171/// # One journal entry can answer differently on different platforms
172///
173/// For a PID now held by **another account's** process, Linux answers
174/// [`Adoption::PidRecycled`] while macOS and Windows answer
175/// [`ProcessError::Identity`]: `/proc/<pid>/stat` is world-readable, whereas
176/// `proc_pidinfo` and `OpenProcess` refuse an inspection this account is not
177/// entitled to. So the same journal entry, read back after the agent's service
178/// account has been changed, is a recycled PID on one platform and an error on
179/// the other two. `e3` branches on this, and should treat the error as the same
180/// *decision* as `PidRecycled` — do not adopt, do not terminate — rather than
181/// as a platform bug.
182#[derive(Debug, Clone, PartialEq, Eq)]
183pub enum Adoption {
184    /// The same process is still running. Adopt it; do not start a replacement.
185    Live,
186
187    /// Nothing holds the PID. The process is gone and its attempt is terminal.
188    Gone,
189
190    /// Something holds the PID, but it is not the recorded process.
191    ///
192    /// Distinct from [`Adoption::Gone`] on purpose. The recorded process is
193    /// equally gone in both cases, but here there is a stranger at that PID,
194    /// and treating this as `Gone` is one refactor away from treating it as
195    /// `Live` — which is how an agent terminates somebody else's process.
196    PidRecycled {
197        /// Whoever holds the PID now.
198        current: ProcessIdentity,
199    },
200}
201
202impl Adoption {
203    /// Whether the recorded process is still running.
204    #[must_use]
205    pub const fn is_live(&self) -> bool {
206        matches!(self, Self::Live)
207    }
208}
209
210/// The outcome of asking a recorded process to stop.
211#[derive(Debug, Clone, PartialEq, Eq)]
212pub enum Termination {
213    /// The process was signalled and is no longer running.
214    Terminated,
215    /// It had already exited; nothing to do.
216    AlreadyGone,
217    /// The PID belongs to a different process now, so nothing was signalled.
218    ///
219    /// The refusal is the feature. See [`Adoption::PidRecycled`].
220    RefusedPidRecycled {
221        /// Whoever holds the PID now.
222        current: ProcessIdentity,
223    },
224}
225
226impl ProcessIdentity {
227    /// Reads the identity of a live process.
228    ///
229    /// # Errors
230    ///
231    /// [`ProcessError::NoSuchProcess`] when nothing holds the PID, and
232    /// [`ProcessError::Identity`] when the operating system refuses to answer —
233    /// a process owned by another account, for instance. The two are separate
234    /// because "gone" is a normal lifecycle answer and "refused" is a
235    /// misconfiguration.
236    pub fn resolve(pid: u32) -> Result<Self, ProcessError> {
237        Self::read(pid, LivenessFilter::LiveOnly)
238    }
239
240    /// Reads the identity of a process this program has just spawned and still
241    /// holds the handle to.
242    ///
243    /// Separate from [`ProcessIdentity::resolve`] because of a race that would
244    /// otherwise make short-lived children unlaunchable: a program that exits
245    /// before its parent gets round to identifying it is *already* not live by
246    /// the time the identity is read, and `resolve` would answer
247    /// [`ProcessError::NoSuchProcess`]. Reading an exited child's start time is
248    /// safe in a way that reading an arbitrary exited PID's is not — the parent
249    /// holds the child handle, so the PID cannot have been reused underneath
250    /// it.
251    fn of_child(pid: u32) -> Result<Self, ProcessError> {
252        match Self::read(pid, LivenessFilter::IncludeExited) {
253            Ok(identity) => Ok(identity),
254            // ------------------------------------------------------------
255            // THE RACE THIS FUNCTION EXISTS FOR, ON THE ONE PLATFORM WHERE
256            // `IncludeExited` IS NOT ENOUGH TO SURVIVE IT.
257            // ------------------------------------------------------------
258            // The filter above covers a *zombie*: exited, unreaped, still
259            // holding its PID. macOS has a narrower window than that.
260            // `proc_pidinfo(PROC_PIDTBSDINFO)` answers `ESRCH` for a child
261            // that has only just gone, and the filter never gets a say --
262            // so a program that exits fast enough could not be launched at
263            // all, which is the exact failure the documentation above says
264            // this function prevents. It cost two CI runs before it was
265            // recognised as that rather than as noise.
266            //
267            // A start token is a claim about *when a process started*, used
268            // to notice a PID that has since been reused. There is no such
269            // instant to read here, and inventing one would be a lie a later
270            // comparison could believe. This sentinel is the honest value:
271            // it matches nothing, so [`ProcessIdentity::classify`] answers
272            // `Gone` for a PID nobody holds and `PidRecycled` for one
273            // somebody else has taken -- and `PidRecycled` is refused rather
274            // than signalled, which is the safe half of the pair.
275            //
276            // Only the parent reaches this: it holds the child handle, so the
277            // PID cannot already belong to somebody else at this moment.
278            Err(ProcessError::NoSuchProcess { .. }) => Ok(Self {
279                pid,
280                start_token: EXITED_BEFORE_IDENTIFIED.to_string(),
281            }),
282            Err(other) => Err(other),
283        }
284    }
285
286    fn read(pid: u32, filter: LivenessFilter) -> Result<Self, ProcessError> {
287        match sys::start_token(pid, filter) {
288            Ok(Some(start_token)) => Ok(Self { pid, start_token }),
289            Ok(None) => Err(ProcessError::NoSuchProcess { pid }),
290            Err(source) => Err(ProcessError::Identity { pid, source }),
291        }
292    }
293
294    /// The identity of the calling process.
295    ///
296    /// # Errors
297    ///
298    /// As [`ProcessIdentity::resolve`], though a process can always see itself
299    /// in practice.
300    pub fn of_current_process() -> Result<Self, ProcessError> {
301        Self::resolve(std::process::id())
302    }
303
304    /// The PID. Recorded in `RunnerAttempt::process_id` and shown in the UI;
305    /// never used on its own to decide whether a process is ours.
306    #[must_use]
307    pub const fn pid(&self) -> u32 {
308        self.pid
309    }
310
311    /// The opaque start token. Exposed for diagnostics only.
312    #[must_use]
313    pub fn start_token(&self) -> &str {
314        &self.start_token
315    }
316
317    /// Re-resolves this identity against the machine as it is now.
318    ///
319    /// # Errors
320    ///
321    /// [`ProcessError::Identity`] when the operating system refuses to answer.
322    /// A PID that resolves to nothing is [`Adoption::Gone`], not an error.
323    pub fn recheck(&self) -> Result<Adoption, ProcessError> {
324        match sys::start_token(self.pid, LivenessFilter::LiveOnly) {
325            Ok(observed) => Ok(self.classify(observed)),
326            Err(source) => Err(ProcessError::Identity {
327                pid: self.pid,
328                source,
329            }),
330        }
331    }
332
333    /// The adoption decision itself, with the operating system already
334    /// consulted.
335    ///
336    /// Split out of [`ProcessIdentity::recheck`] so that all three answers can
337    /// be exercised without spawning anything. One of them cannot be reached
338    /// through a spawn on demand: two processes carrying an *identical* start
339    /// token. On Windows (100 ns) and macOS (1 µs) that is unreachable, and on
340    /// Linux it happens only by landing inside the same 10 ms clock tick, which
341    /// is a race a test cannot ask for. Comparing tokens here rather than
342    /// inline means the discriminator can be shown to behave correctly on that
343    /// input from every leg of the CI matrix.
344    fn classify(&self, observed: Option<String>) -> Adoption {
345        match observed {
346            None => Adoption::Gone,
347            Some(token) if token == self.start_token => Adoption::Live,
348            Some(token) => Adoption::PidRecycled {
349                current: Self {
350                    pid: self.pid,
351                    start_token: token,
352                },
353            },
354        }
355    }
356
357    /// Stops the process this identity names, and nothing else.
358    ///
359    /// Re-checks the identity immediately before signalling. That check is the
360    /// difference between "terminate the runner recorded in the journal" and
361    /// "terminate whatever now holds PID 4312", and it is why the recycled case
362    /// returns [`Termination::RefusedPidRecycled`] rather than proceeding.
363    ///
364    /// `grace` applies only where the platform has a polite stop to offer: on
365    /// Unix the process is sent `SIGTERM`, given `grace` to exit, and then
366    /// `SIGKILL`ed. Windows has no console-independent equivalent, so the
367    /// process is terminated immediately and `grace` is ignored — stated here
368    /// rather than emulated, because a fake grace period that never actually
369    /// asks politely is worse than no grace period.
370    ///
371    /// # Errors
372    ///
373    /// [`ProcessError::Control`] when signalling fails for a reason other than
374    /// the process having already exited.
375    pub fn terminate(&self, grace: Duration) -> Result<Termination, ProcessError> {
376        match self.recheck()? {
377            Adoption::Gone => return Ok(Termination::AlreadyGone),
378            Adoption::PidRecycled { current } => {
379                return Ok(Termination::RefusedPidRecycled { current });
380            }
381            Adoption::Live => {}
382        }
383
384        let requested = sys::request_stop(self.pid).map_err(|source| ProcessError::Control {
385            pid: self.pid,
386            source,
387        })?;
388
389        if requested {
390            let deadline = Instant::now() + grace;
391            while Instant::now() < deadline {
392                if matches!(
393                    self.recheck()?,
394                    Adoption::Gone | Adoption::PidRecycled { .. }
395                ) {
396                    return Ok(Termination::Terminated);
397                }
398                std::thread::sleep(POLL_INTERVAL);
399            }
400        }
401
402        // Either the platform has no polite stop, or the grace period expired.
403        // Re-check once more so a process that exited during the wait is not
404        // reported as force-killed, and so a PID recycled during the wait is
405        // not force-killed at all.
406        match self.recheck()? {
407            Adoption::Gone => Ok(Termination::AlreadyGone),
408            Adoption::PidRecycled { current } => Ok(Termination::RefusedPidRecycled { current }),
409            Adoption::Live => {
410                sys::force_stop(self.pid).map_err(|source| ProcessError::Control {
411                    pid: self.pid,
412                    source,
413                })?;
414                Ok(Termination::Terminated)
415            }
416        }
417    }
418}
419
420/// When this machine booted, as Linux reports it in `/proc/stat`. `None`
421/// elsewhere, and where it cannot be read.
422#[must_use]
423pub fn boot_time() -> Option<chrono::DateTime<chrono::Utc>> {
424    #[cfg(target_os = "linux")]
425    {
426        sys::btime()
427            .ok()
428            .and_then(|seconds| seconds.parse().ok())
429            .and_then(|seconds| chrono::DateTime::from_timestamp(seconds, 0))
430    }
431    #[cfg(not(target_os = "linux"))]
432    {
433        None
434    }
435}
436
437impl fmt::Display for ProcessIdentity {
438    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
439        write!(f, "pid {} started {}", self.pid, self.start_token)
440    }
441}
442
443/// How often a wait loop re-checks. Short enough that a terminating runner is
444/// noticed promptly, long enough that a grace period is not a spin.
445const POLL_INTERVAL: Duration = Duration::from_millis(20);
446
447/// Whether a start-time lookup should answer for a process that has already
448/// exited but whose PID is not yet free.
449///
450/// Both states exist on both families: a Unix child that has exited and not
451/// been reaped is a zombie holding its PID, and a Windows process whose handle
452/// is still open leaves a process object behind with a non-zero exit time.
453#[derive(Debug, Clone, Copy, PartialEq, Eq)]
454enum LivenessFilter {
455    /// Answer only for a process that is still running. What recovery and
456    /// adoption need: an exited process is not something to adopt.
457    LiveOnly,
458    /// Answer for an exited process too. Only ever used by the parent of that
459    /// process, which holds its handle and therefore knows the PID is not
460    /// somebody else's.
461    IncludeExited,
462}
463
464// ---------------------------------------------------------------------------
465// Spawning
466// ---------------------------------------------------------------------------
467
468/// What to do with a child's standard output and standard error.
469#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
470pub enum OutputMode {
471    /// Send both to the null device. The default: a runner writes its own
472    /// diagnostics into its workspace, and inheriting its output would splice
473    /// unredacted text into this process's stream.
474    #[default]
475    Discard,
476    /// Inherit this process's handles.
477    Inherit,
478    /// Capture both, readable through [`ChildProcess::take_stdout`].
479    Capture,
480}
481
482/// A child process about to be launched.
483///
484/// A builder rather than a bare [`Command`] so that the arguments and the
485/// environment can be inspected before the launch — which is what
486/// [`SpawnSpec::spawn_with_handoff`] does.
487#[derive(Debug, Clone)]
488pub struct SpawnSpec {
489    program: PathBuf,
490    args: Vec<OsString>,
491    envs: Vec<(OsString, OsString)>,
492    removed_envs: Vec<OsString>,
493    working_dir: Option<PathBuf>,
494    output: OutputMode,
495    normal_scheduling: bool,
496}
497
498impl SpawnSpec {
499    /// Starts a specification for `program`.
500    pub fn new(program: impl Into<PathBuf>) -> Self {
501        Self {
502            program: program.into(),
503            args: Vec::new(),
504            envs: Vec::new(),
505            removed_envs: Vec::new(),
506            working_dir: None,
507            output: OutputMode::Discard,
508            normal_scheduling: false,
509        }
510    }
511
512    /// Appends one argument.
513    #[must_use]
514    pub fn arg(mut self, arg: impl AsRef<OsStr>) -> Self {
515        self.args.push(arg.as_ref().to_os_string());
516        self
517    }
518
519    /// Appends several arguments.
520    #[must_use]
521    pub fn args<I, S>(mut self, args: I) -> Self
522    where
523        I: IntoIterator<Item = S>,
524        S: AsRef<OsStr>,
525    {
526        self.args
527            .extend(args.into_iter().map(|a| a.as_ref().to_os_string()));
528        self
529    }
530
531    /// Sets one environment variable for the child, on top of the inherited
532    /// environment.
533    #[must_use]
534    pub fn env(mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> Self {
535        self.envs
536            .push((key.as_ref().to_os_string(), value.as_ref().to_os_string()));
537        self
538    }
539
540    /// Prevents an inherited variable from changing a subprocess's operation.
541    #[must_use]
542    pub fn without_env(mut self, key: impl AsRef<OsStr>) -> Self {
543        self.removed_envs.push(key.as_ref().to_owned());
544        self
545    }
546
547    /// Sets the child's working directory.
548    #[must_use]
549    pub fn working_dir(mut self, dir: impl Into<PathBuf>) -> Self {
550        self.working_dir = Some(dir.into());
551        self
552    }
553
554    /// Chooses what happens to the child's output.
555    #[must_use]
556    pub fn output(mut self, output: OutputMode) -> Self {
557        self.output = output;
558        self
559    }
560
561    /// Declares that the child must run at normal scheduling priority, and
562    /// has the launch say so when it does not.
563    ///
564    /// On macOS the parent reads the child's base priority back after the
565    /// spawn and logs a warning when it is at the background ceiling. A
566    /// throttled runner still runs its job correctly, only 4 to 20 times
567    /// slower, so this reports rather than refuses.
568    ///
569    /// Nothing here changes the child's priority. Under launchd the priority
570    /// comes from the job's `ProcessType`, which every descendant inherits and
571    /// none can leave (`crate::service::LAUNCHD_PROCESS_TYPE` has the
572    /// measurements), so the fix belongs in the plist. 0.4.31 cleared
573    /// `PRIO_DARWIN_PROCESS` between `fork` and `exec` instead; the call
574    /// succeeded and the runner stayed at 4, and this warning is what showed
575    /// it.
576    ///
577    /// No effect on other platforms.
578    #[must_use]
579    pub fn expect_normal_scheduling(mut self) -> Self {
580        self.normal_scheduling = true;
581        self
582    }
583
584    /// The arguments as configured. Exposed so a security test can assert what
585    /// a process listing would show.
586    #[must_use]
587    pub fn arguments(&self) -> &[OsString] {
588        &self.args
589    }
590
591    /// The variable the child gets for `name`, as configured on top of the
592    /// inherited environment: the last [`Self::env`] for it wins, as it does in
593    /// the child. Names compare without case on Windows, as Windows does.
594    #[must_use]
595    pub fn configured_env(&self, name: &str) -> Option<&OsStr> {
596        self.envs
597            .iter()
598            .rev()
599            .find(|(key, _)| {
600                key.to_str()
601                    .is_some_and(|key| crate::runner_env::same_name(key, name))
602            })
603            .map(|(_, value)| value.as_os_str())
604    }
605
606    /// Whether [`Self::expect_normal_scheduling`] was asked for.
607    #[doc(hidden)]
608    #[must_use]
609    pub const fn expects_normal_scheduling(&self) -> bool {
610        self.normal_scheduling
611    }
612
613    /// Launches the child.
614    ///
615    /// # Errors
616    ///
617    /// [`ProcessError::Spawn`] when the program cannot be launched, and
618    /// [`ProcessError::Identity`] when it launches but its start time cannot be
619    /// read — which would leave an unrecordable process running, so the child
620    /// is killed rather than leaked.
621    pub fn spawn(&self) -> Result<ChildProcess, ProcessError> {
622        self.spawn_with_extra_env(None)
623    }
624
625    fn spawn_with_extra_env(
626        &self,
627        extra_env: Option<(&OsStr, &OsStr)>,
628    ) -> Result<ChildProcess, ProcessError> {
629        let mut command = Command::new(&self.program);
630        #[cfg(unix)]
631        std::os::unix::process::CommandExt::process_group(&mut command, 0);
632
633        command.args(&self.args);
634        for key in &self.removed_envs {
635            command.env_remove(key);
636        }
637        for (key, value) in &self.envs {
638            command.env(key, value);
639        }
640        if let Some((key, value)) = extra_env {
641            command.env(key, value);
642        }
643        if let Some(dir) = &self.working_dir {
644            command.current_dir(dir);
645        }
646        // Never inherited: a runner that reads this process's stdin would block
647        // the agent, and nothing in this design feeds a child interactively.
648        command.stdin(Stdio::null());
649        let (stdout, stderr) = match self.output {
650            OutputMode::Discard => (Stdio::null(), Stdio::null()),
651            OutputMode::Inherit => (Stdio::inherit(), Stdio::inherit()),
652            OutputMode::Capture => (Stdio::piped(), Stdio::piped()),
653        };
654        command.stdout(stdout).stderr(stderr);
655
656        let child = command.spawn().map_err(|source| ProcessError::Spawn {
657            program: self.program.clone(),
658            source,
659        })?;
660
661        let pid = child.id();
662        #[cfg(target_os = "macos")]
663        if self.normal_scheduling && sys::runs_throttled(pid) {
664            tracing::warn!(
665                pid,
666                reason = "runner_started_at_background_priority",
667                "the runner process still runs at background priority, so its jobs will be slow"
668            );
669        }
670        match ProcessIdentity::of_child(pid) {
671            Ok(identity) => Ok(ChildProcess {
672                child,
673                identity,
674                program: self.program.clone(),
675            }),
676            Err(error) => {
677                // An unidentifiable child cannot be journalled, so it cannot be
678                // recovered after a restart. Leaving it running would create
679                // exactly the orphan the journal exists to prevent.
680                let mut child = child;
681                let _ = child.kill();
682                let _ = child.wait();
683                Err(error)
684            }
685        }
686    }
687
688    /// Launches the child after proving the handoff payload is not in the
689    /// command line or the environment.
690    ///
691    /// This is the enforcement point for `07-security.md`'s control on *"A
692    /// process listing reveals a JIT config"*. `e3` should reach for this and
693    /// not for [`SpawnSpec::spawn`], because a rule that is checked is a rule,
694    /// and a rule that is written down is a hope.
695    ///
696    /// # Errors
697    ///
698    /// [`ProcessError::SecretInCommandLine`] when the payload appears in an
699    /// argument or an environment value, plus everything
700    /// [`SpawnSpec::spawn`] returns.
701    pub fn spawn_with_handoff(
702        &self,
703        handoff: &RestrictiveHandoff,
704    ) -> Result<ChildProcess, ProcessError> {
705        self.reject_exposed_handoff(handoff)?;
706        self.spawn()
707    }
708
709    /// Launches GitHub Runner using its supported process-safe JIT input.
710    ///
711    /// The encoded configuration is deliberately absent from [`SpawnSpec`]:
712    /// callers cannot render it as an argument or accidentally retain it in a
713    /// reusable specification. It is copied from the restrictive handoff into
714    /// the child's initial environment at the final `Command::spawn` boundary.
715    /// GitHub Runner's `CommandSettings` treats `jitconfig` as a secret and
716    /// removes `ACTIONS_RUNNER_INPUT_JITCONFIG` from the process environment
717    /// before executing the `run` command.
718    ///
719    /// The caller still owns deleting `handoff` immediately after this method
720    /// returns. A failed launch leaves deletion to [`RestrictiveHandoff`]'s
721    /// fail-closed `Drop` implementation.
722    ///
723    /// # Errors
724    ///
725    /// [`ProcessError::SecretInCommandLine`] when the payload was also placed
726    /// in an argument or explicitly configured environment value, plus every
727    /// error returned by [`SpawnSpec::spawn`].
728    pub fn spawn_runner_with_handoff(
729        &self,
730        handoff: &RestrictiveHandoff,
731    ) -> Result<ChildProcess, ProcessError> {
732        self.reject_exposed_handoff(handoff)?;
733        self.spawn_with_extra_env(Some((
734            OsStr::new(RUNNER_JIT_CONFIG_ENV),
735            OsStr::new(handoff.payload.expose_secret()),
736        )))
737    }
738
739    fn reject_exposed_handoff(&self, handoff: &RestrictiveHandoff) -> Result<(), ProcessError> {
740        let payload = handoff.payload.expose_secret();
741        // An empty payload cannot meaningfully be searched for — every string
742        // contains it — and it is not a secret worth protecting either.
743        if !payload.is_empty() {
744            for (index, arg) in self.args.iter().enumerate() {
745                if os_str_contains(arg, payload) {
746                    return Err(ProcessError::SecretInCommandLine {
747                        program: self.program.clone(),
748                        location: format!("argument {index}"),
749                    });
750                }
751            }
752            for (key, value) in &self.envs {
753                if os_str_contains(value, payload) {
754                    return Err(ProcessError::SecretInCommandLine {
755                        program: self.program.clone(),
756                        location: format!("environment variable {}", key.to_string_lossy()),
757                    });
758                }
759            }
760        }
761
762        Ok(())
763    }
764}
765
766/// Whether `haystack` contains `needle`, for an [`OsStr`] that may not be valid
767/// Unicode.
768///
769/// `to_string_lossy` is enough here: the payload is a base64 JIT configuration,
770/// so it is ASCII, and lossy conversion replaces only the bytes that could not
771/// have matched it anyway.
772fn os_str_contains(haystack: &OsStr, needle: &str) -> bool {
773    haystack.to_string_lossy().contains(needle)
774}
775
776/// A child process this agent started.
777///
778/// `04-subsystem-contracts.md`: *"local process state is authoritative only for
779/// a child process owned by this agent"*. That is this type. For a process
780/// recovered from the journal after a restart there is no [`Child`] and no
781/// parent relationship, so [`ProcessIdentity`] is the authority instead.
782#[derive(Debug)]
783pub struct ChildProcess {
784    child: Child,
785    identity: ProcessIdentity,
786    program: PathBuf,
787}
788
789impl ChildProcess {
790    /// The identity to record in the journal.
791    #[must_use]
792    pub const fn identity(&self) -> &ProcessIdentity {
793        &self.identity
794    }
795
796    /// The child's PID.
797    #[must_use]
798    pub const fn pid(&self) -> u32 {
799        self.identity.pid
800    }
801
802    /// Whether the child is still running.
803    ///
804    /// # Errors
805    ///
806    /// [`ProcessError::Control`] when the wait fails.
807    pub fn is_running(&mut self) -> Result<bool, ProcessError> {
808        Ok(self.try_exit_status()?.is_none())
809    }
810
811    /// The child's exit status if it has already exited, reaping it if so.
812    ///
813    /// # Errors
814    ///
815    /// [`ProcessError::Control`] when the wait fails.
816    pub fn try_exit_status(&mut self) -> Result<Option<ExitStatus>, ProcessError> {
817        self.child
818            .try_wait()
819            .map_err(|source| ProcessError::Control {
820                pid: self.identity.pid,
821                source,
822            })
823    }
824
825    /// Blocks until the child exits.
826    ///
827    /// # Errors
828    ///
829    /// [`ProcessError::Control`] when the wait fails.
830    pub fn wait(&mut self) -> Result<ExitStatus, ProcessError> {
831        self.child.wait().map_err(|source| ProcessError::Control {
832            pid: self.identity.pid,
833            source,
834        })
835    }
836
837    /// Waits up to `timeout` for the child to exit; `None` means it is still
838    /// running when the timeout expires.
839    ///
840    /// # Errors
841    ///
842    /// [`ProcessError::Control`] when the wait fails.
843    pub fn wait_for(&mut self, timeout: Duration) -> Result<Option<ExitStatus>, ProcessError> {
844        let deadline = Instant::now() + timeout;
845        loop {
846            if let Some(status) = self.try_exit_status()? {
847                return Ok(Some(status));
848            }
849            if Instant::now() >= deadline {
850                return Ok(None);
851            }
852            std::thread::sleep(POLL_INTERVAL);
853        }
854    }
855
856    /// Asks the child to stop, forcefully if `grace` expires first.
857    ///
858    /// See [`ProcessIdentity::terminate`] for what `grace` means on each
859    /// platform. Unlike that method this one has the parent relationship, so it
860    /// reaps the child and returns its exit status.
861    ///
862    /// # Errors
863    ///
864    /// [`ProcessError::Control`] when signalling or waiting fails.
865    pub fn stop(&mut self, grace: Duration) -> Result<ExitStatus, ProcessError> {
866        if let Some(status) = self.try_exit_status()? {
867            return Ok(status);
868        }
869
870        let pid = self.identity.pid;
871        // Safe to signal by PID: this process holds the child handle, so the
872        // PID cannot have been recycled behind our back.
873        let requested =
874            sys::request_stop(pid).map_err(|source| ProcessError::Control { pid, source })?;
875
876        if requested && let Some(status) = self.wait_for(grace)? {
877            return Ok(status);
878        }
879
880        self.child
881            .kill()
882            .map_err(|source| ProcessError::Control { pid, source })?;
883        self.wait()
884    }
885
886    /// Takes the captured standard output, if [`OutputMode::Capture`] was set.
887    pub fn take_stdout(&mut self) -> Option<std::process::ChildStdout> {
888        self.child.stdout.take()
889    }
890
891    /// Takes the captured standard error, if [`OutputMode::Capture`] was set.
892    pub fn take_stderr(&mut self) -> Option<std::process::ChildStderr> {
893        self.child.stderr.take()
894    }
895
896    /// The program that was launched.
897    #[must_use]
898    pub fn program(&self) -> &Path {
899        &self.program
900    }
901}
902
903// ---------------------------------------------------------------------------
904// Restrictive handoff
905// ---------------------------------------------------------------------------
906
907/// Something went wrong creating, inspecting, or removing a handoff file.
908#[derive(Debug, thiserror::Error)]
909pub enum HandoffError {
910    /// The file could not be created with restrictive permissions.
911    #[error("cannot create a restrictive handoff file in {}: {source}", directory.display())]
912    Create {
913        /// The directory the file was to be created in.
914        directory: PathBuf,
915        /// The underlying error.
916        #[source]
917        source: std::io::Error,
918    },
919
920    /// The payload could not be written.
921    #[error("cannot write the handoff payload to {}: {source}", path.display())]
922    Write {
923        /// The file that could not be written.
924        path: PathBuf,
925        /// The underlying error.
926        #[source]
927        source: std::io::Error,
928    },
929
930    /// The file's permissions could not be read back.
931    #[error("cannot read the permissions of {}: {source}", path.display())]
932    Inspect {
933        /// The file that could not be inspected.
934        path: PathBuf,
935        /// The underlying error.
936        #[source]
937        source: std::io::Error,
938    },
939
940    /// The file could not be removed.
941    ///
942    /// Worth an error rather than a shrug: a JIT configuration left on disk is
943    /// the exact thing `05-infrastructure.md` says must be deleted immediately.
944    #[error("cannot delete the handoff file {}: {source}", path.display())]
945    Delete {
946        /// The file that could not be removed.
947        path: PathBuf,
948        /// The underlying error.
949        #[source]
950        source: std::io::Error,
951    },
952}
953
954/// What a file's permissions amount to, in terms this product cares about.
955#[derive(Debug, Clone, PartialEq, Eq)]
956pub struct PermissionsSummary {
957    /// Platform-native description — a Unix mode, or a Windows DACL in SDDL
958    /// form. For diagnostics and for test failure messages.
959    pub description: String,
960    /// Whether an ordinary local user other than the file's owner could read
961    /// it.
962    ///
963    /// A local administrator or `root` is deliberately outside this question:
964    /// `07-security.md` records that such an account is already assumed able to
965    /// read the runner's credentials and job workspaces, so pretending a file
966    /// mode could exclude it would be theatre.
967    pub readable_by_other_local_users: bool,
968}
969
970/// Reads back what a file's permissions actually grant.
971///
972/// # Errors
973///
974/// [`HandoffError::Inspect`] when the permissions cannot be read.
975/// This account's SID, in the string form an SDDL trustee takes.
976///
977/// Windows only, because a SID is. The secret store names the account that
978/// wrote a value explicitly rather than describing it as `OW`: OWNER RIGHTS is
979/// deleted by the system whenever an object's owner changes, so a DACL that
980/// leans on it loses the grant the moment anybody runs `takeown`.
981///
982/// # Errors
983/// Whatever reading this process's own token reported.
984#[cfg(windows)]
985pub(crate) fn current_user_sid() -> std::io::Result<String> {
986    sys::current_user_sid()
987}
988
989/// Whether this process runs at the background priority ceiling, by the same
990/// reading the post-spawn runner check uses.
991#[cfg(target_os = "macos")]
992#[must_use]
993pub fn runs_at_background_priority() -> bool {
994    sys::runs_throttled(std::process::id())
995}
996
997pub fn permissions_summary(path: &Path) -> Result<PermissionsSummary, HandoffError> {
998    sys::describe_permissions(path)
999        .map(
1000            |(description, readable_by_other_local_users)| PermissionsSummary {
1001                description,
1002                readable_by_other_local_users,
1003            },
1004        )
1005        .map_err(|source| HandoffError::Inspect {
1006            path: path.to_path_buf(),
1007            source,
1008        })
1009}
1010
1011/// A short-lived file holding a secret, readable only by this account, deleted
1012/// on every path out.
1013///
1014/// `05-infrastructure.md` puts the encoded JIT configuration in a *"restrictive
1015/// temporary file or process-safe handoff"* and requires *"Delete immediately
1016/// after runner start or failed start"*. Both halves of that sentence are
1017/// implemented here: [`RestrictiveHandoff::create`] makes the file
1018/// unreadable by other local users at the moment of creation, and [`Drop`]
1019/// deletes it whether the launch succeeded, failed, or panicked.
1020///
1021/// # Why creation, not creation-then-chmod
1022///
1023/// On Windows the file is created through `CreateFileW` with an explicit
1024/// `SECURITY_ATTRIBUTES`, and on Unix through `open(2)` with mode `0600`. In
1025/// both cases the restriction is applied *by the call that creates the file*.
1026/// Creating a file and then tightening it leaves a window — however short — in
1027/// which the JIT configuration exists on disk under whatever the parent
1028/// directory happened to grant, and a window is all a local attacker needs.
1029///
1030/// # What is not claimed
1031///
1032/// The file is deleted, not securely erased. No modern filesystem lets a
1033/// userspace program guarantee that the bytes are unrecoverable — a journal, a
1034/// copy-on-write snapshot, or an SSD's wear levelling can each keep a copy that
1035/// an overwrite never reaches. Claiming otherwise would be worse than saying
1036/// so plainly, so the control this design relies on is the file's short life
1037/// and its access control, not erasure.
1038#[derive(Debug)]
1039pub struct RestrictiveHandoff {
1040    path: PathBuf,
1041    payload: SecretString,
1042    deleted: bool,
1043}
1044
1045impl RestrictiveHandoff {
1046    /// What every handoff file's name begins with.
1047    ///
1048    /// Published because the name is otherwise a UUID nobody can predict, and
1049    /// `c3`'s persistent cleanup has to answer "did an encoded configuration
1050    /// survive into this slot?" *after* the process that owned it is gone
1051    /// (`04-security-recovery.md`: JIT values are "never retained in slot").
1052    /// A second `"jit-"` spelled out over there would be a second source of
1053    /// truth for the one fact that decides whether a secret is still on disk.
1054    pub const NAME_PREFIX: &'static str = "jit-";
1055
1056    /// Writes `payload` to a new uniquely named file in `directory`.
1057    ///
1058    /// The name is a UUID rather than a predictable one, so that another local
1059    /// account cannot pre-create the path and win the race for it; creation is
1060    /// exclusive, so if it did, this fails rather than writing into the
1061    /// squatter's file.
1062    ///
1063    /// # Errors
1064    ///
1065    /// [`HandoffError::Create`] and [`HandoffError::Write`].
1066    pub fn create(directory: &Path, payload: SecretString) -> Result<Self, HandoffError> {
1067        use std::io::Write as _;
1068
1069        let path = directory.join(format!("{}{}.tmp", Self::NAME_PREFIX, uuid::Uuid::new_v4()));
1070
1071        let mut file =
1072            sys::create_restrictive_file(&path).map_err(|source| HandoffError::Create {
1073                directory: directory.to_path_buf(),
1074                source,
1075            })?;
1076
1077        let handoff = Self {
1078            path,
1079            payload,
1080            deleted: false,
1081        };
1082
1083        // From here on the file exists, so every failure path must delete it.
1084        // `handoff` is already constructed, so `?` unwinds through its `Drop`.
1085        let write = file
1086            .write_all(handoff.payload.expose_secret().as_bytes())
1087            .and_then(|()| file.flush())
1088            .and_then(|()| file.sync_all());
1089        write.map_err(|source| HandoffError::Write {
1090            path: handoff.path.clone(),
1091            source,
1092        })?;
1093        drop(file);
1094
1095        Ok(handoff)
1096    }
1097
1098    /// The path to hand to the child process.
1099    ///
1100    /// This is the only thing that may reach a command line. The payload is not
1101    /// exposed at all: it is held as a [`SecretString`], which has no `Display`
1102    /// and a redacting `Debug`, so it cannot be formatted into an argument by
1103    /// accident.
1104    #[must_use]
1105    pub fn path(&self) -> &Path {
1106        &self.path
1107    }
1108
1109    /// What the file's permissions actually grant.
1110    ///
1111    /// # Errors
1112    ///
1113    /// [`HandoffError::Inspect`].
1114    pub fn permissions(&self) -> Result<PermissionsSummary, HandoffError> {
1115        permissions_summary(&self.path)
1116    }
1117
1118    /// Deletes the file now, reporting failure.
1119    ///
1120    /// The success path should call this rather than relying on [`Drop`], for
1121    /// one reason: `Drop` cannot report an error, and a JIT configuration that
1122    /// could not be deleted is something an operator must be told about.
1123    ///
1124    /// # Errors
1125    ///
1126    /// [`HandoffError::Delete`].
1127    pub fn delete(mut self) -> Result<(), HandoffError> {
1128        self.delete_in_place()
1129    }
1130
1131    fn delete_in_place(&mut self) -> Result<(), HandoffError> {
1132        if self.deleted {
1133            return Ok(());
1134        }
1135        match std::fs::remove_file(&self.path) {
1136            Ok(()) => {
1137                self.deleted = true;
1138                Ok(())
1139            }
1140            // Already gone is the desired end state, not a failure.
1141            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
1142                self.deleted = true;
1143                Ok(())
1144            }
1145            Err(source) => Err(HandoffError::Delete {
1146                path: self.path.clone(),
1147                source,
1148            }),
1149        }
1150    }
1151}
1152
1153impl Drop for RestrictiveHandoff {
1154    fn drop(&mut self) {
1155        if let Err(error) = self.delete_in_place() {
1156            // The path is logged at `error` because an undeleted JIT
1157            // configuration is an operator-actionable condition, and the path
1158            // is the only actionable part. It is redacted by the log sink like
1159            // every other path (`crate::logging`).
1160            tracing::error!(
1161                event = "handoff_delete_failed",
1162                path = %self.path.display(),
1163                error = %error,
1164                "a JIT handoff file could not be deleted and is still on disk"
1165            );
1166        }
1167    }
1168}
1169
1170// ---------------------------------------------------------------------------
1171// The Linux `/proc/<pid>/stat` parser
1172// ---------------------------------------------------------------------------
1173
1174/// The two fields of `/proc/<pid>/stat` this crate reads.
1175#[cfg_attr(
1176    not(target_os = "linux"),
1177    allow(dead_code, reason = "parsed on Linux; unit tested on every platform")
1178)]
1179#[derive(Debug, Clone, PartialEq, Eq)]
1180struct ProcStat<'a> {
1181    /// Field 3: a single character, `R`, `S`, `D`, `Z`, `T`, and so on.
1182    state: &'a str,
1183    /// Field 22: the process's start time, in clock ticks since boot.
1184    start_ticks: &'a str,
1185}
1186
1187/// Parses the fields after the `comm` field of a `/proc/<pid>/stat` line.
1188///
1189/// Lives here, outside the `#[cfg(unix)]` module, for one reason: it is the
1190/// riskiest few lines in this crate and the only ones whose correctness is
1191/// pure string handling. Keeping it platform-independent means it is unit
1192/// tested on the Windows and macOS legs of CI as well as the Linux one, and by
1193/// a developer on any machine — rather than being exercised for the first time
1194/// on the leg where a mistake is a wrong process identity.
1195///
1196/// The hazard it exists to handle: **field 2 is the executable name, in
1197/// parentheses, and it may itself contain spaces and parentheses.** A process
1198/// really can be called `my prog (v2)`, and `procfs(5)` says so. Splitting the
1199/// whole line on whitespace therefore mis-indexes every later field, and does
1200/// so only for the one process whose name happens to be adversarial — which is
1201/// to say, only when someone is being adversarial. The *last* `)` on the line
1202/// is the reliable anchor, because every field after `comm` is numeric.
1203#[cfg_attr(
1204    not(target_os = "linux"),
1205    allow(dead_code, reason = "parsed on Linux; unit tested on every platform")
1206)]
1207fn parse_proc_stat(stat: &str) -> Option<ProcStat<'_>> {
1208    // Everything after the last `)` is field 3 onwards, all of it numeric and
1209    // whitespace separated.
1210    let after_comm = &stat[stat.rfind(')')? + 1..];
1211    let mut fields = after_comm.split_whitespace();
1212
1213    // `next()` yields field 3; the iterator then stands at field 4, so
1214    // `nth(k)` yields field `4 + k`.
1215    let state = fields.next()?;
1216    let start_ticks = fields.nth(22 - 4)?;
1217
1218    Some(ProcStat { state, start_ticks })
1219}
1220
1221/// Whether a failed start-time probe means the process is *gone*, as opposed to
1222/// unreadable for some other reason.
1223///
1224/// `no_such_process` is the platform's `ESRCH`, passed in rather than read from
1225/// `libc` here for the same reason [`parse_proc_stat`] lives outside the
1226/// `#[cfg(unix)]` module: this is a security-relevant decision that is
1227/// otherwise only compiled on two of the three CI legs and testable on neither
1228/// a Windows developer's machine nor the Windows leg. As a plain function over
1229/// an `Option<i32>` it is exercised everywhere.
1230///
1231/// **Only `ESRCH` is "gone".** Every other answer — `EPERM` for a process this
1232/// account may not inspect, or a zero `errno` from a call that failed without
1233/// setting one — is an error. This is the same rule the Windows leg applies to
1234/// `ERROR_ACCESS_DENIED`, and for the same reason: an unexplained failure is
1235/// not evidence of absence, and reporting [`Adoption::Gone`] for one is how an
1236/// agent decides to start a duplicate runner.
1237///
1238/// # Compiled where it is used, rather than allowed where it is not
1239///
1240/// This carried `#[cfg_attr(not(target_os = "macos"), allow(dead_code, …))]`,
1241/// and now carries a `cfg` that names macOS plus `test`. The difference is not
1242/// tidiness. An allowance leaves the lint's premise true and silences the
1243/// report; the condition it carries is a claim about every platform it does
1244/// *not* name, and getting that claim wrong is invisible until the one CI leg
1245/// that disagrees runs. That is precisely how N1 reached the Linux leg. A
1246/// `cfg` makes the premise false instead: on a platform that does not call
1247/// this, the item is not there to be dead, and there is nothing left to allow.
1248///
1249/// `test` is in the condition because the unit tests below are the reason this
1250/// function is a plain function over `Option<i32>` at all -- they are what
1251/// exercise it on the Windows and Linux legs, where the macOS caller does not
1252/// exist.
1253#[cfg(any(target_os = "macos", test))]
1254const fn probe_failure_means_gone(errno: Option<i32>, no_such_process: i32) -> bool {
1255    matches!(errno, Some(code) if code == no_such_process)
1256}
1257
1258// ---------------------------------------------------------------------------
1259// Platform implementations
1260// ---------------------------------------------------------------------------
1261//
1262// Each `sys` module offers the same five functions, and the shared code above
1263// is the only caller:
1264//
1265//   start_token(pid, filter)    -> Ok(None) when nothing matching holds the PID
1266//   request_stop(pid)           -> Ok(false) when the platform has no polite stop
1267//   force_stop(pid)             -> terminate immediately
1268//   create_restrictive_file(p)  -> a new file only this account can read
1269//   describe_permissions(p)     -> (native description, readable by others?)
1270
1271#[cfg(windows)]
1272mod sys {
1273    use std::fs::File;
1274    use std::io;
1275    use std::os::windows::ffi::OsStrExt;
1276    use std::os::windows::io::FromRawHandle;
1277    use std::path::Path;
1278
1279    use windows::Win32::Foundation::{
1280        CloseHandle, ERROR_ACCESS_DENIED, ERROR_INVALID_PARAMETER, ERROR_SUCCESS, FILETIME, HANDLE,
1281        HLOCAL, LocalFree,
1282    };
1283    use windows::Win32::Security::Authorization::{
1284        ConvertSecurityDescriptorToStringSecurityDescriptorW, ConvertSidToStringSidW,
1285        ConvertStringSecurityDescriptorToSecurityDescriptorW, GetNamedSecurityInfoW,
1286        SDDL_REVISION_1, SE_FILE_OBJECT,
1287    };
1288    use windows::Win32::Security::{
1289        DACL_SECURITY_INFORMATION, GetTokenInformation, PSECURITY_DESCRIPTOR, SECURITY_ATTRIBUTES,
1290        TOKEN_QUERY, TOKEN_USER, TokenUser,
1291    };
1292    use windows::Win32::Storage::FileSystem::{
1293        CREATE_NEW, CreateFileW, FILE_ATTRIBUTE_NORMAL, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
1294        FILE_SHARE_NONE,
1295    };
1296    use windows::Win32::System::Threading::{
1297        GetCurrentProcess, GetProcessTimes, OpenProcess, OpenProcessToken,
1298        PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE, TerminateProcess,
1299    };
1300    use windows::core::{PCWSTR, PWSTR};
1301
1302    /// `HRESULT_FROM_WIN32`, which windows-rs does not re-export as a function.
1303    const fn hresult_from_win32(code: u32) -> i32 {
1304        if code == 0 {
1305            0
1306        } else {
1307            ((code & 0x0000_ffff) | 0x8007_0000) as i32
1308        }
1309    }
1310
1311    fn to_wide(path: &Path) -> Vec<u16> {
1312        path.as_os_str()
1313            .encode_wide()
1314            .chain(std::iter::once(0))
1315            .collect()
1316    }
1317
1318    fn filetime_to_u64(time: FILETIME) -> u64 {
1319        (u64::from(time.dwHighDateTime) << 32) | u64::from(time.dwLowDateTime)
1320    }
1321
1322    fn io_error(error: &windows::core::Error) -> io::Error {
1323        io::Error::from_raw_os_error(error.code().0)
1324    }
1325
1326    pub(super) fn start_token(
1327        pid: u32,
1328        filter: super::LivenessFilter,
1329    ) -> io::Result<Option<String>> {
1330        let handle = match unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) } {
1331            Ok(handle) => handle,
1332            Err(error) => {
1333                // `OpenProcess` answers a PID nobody holds with
1334                // ERROR_INVALID_PARAMETER, not with a "no such process" code.
1335                // Access denied stays an error: a process this agent may not
1336                // query is not the same as one that is gone, and treating it as
1337                // gone is how an agent decides to start a duplicate.
1338                let code = error.code().0;
1339                if code == hresult_from_win32(ERROR_INVALID_PARAMETER.0) {
1340                    return Ok(None);
1341                }
1342                if code == hresult_from_win32(ERROR_ACCESS_DENIED.0) {
1343                    return Err(io::Error::new(
1344                        io::ErrorKind::PermissionDenied,
1345                        format!("PID {pid} belongs to a process this account may not query"),
1346                    ));
1347                }
1348                return Err(io_error(&error));
1349            }
1350        };
1351
1352        let mut creation = FILETIME::default();
1353        let mut exit = FILETIME::default();
1354        let mut kernel = FILETIME::default();
1355        let mut user = FILETIME::default();
1356        let times =
1357            unsafe { GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user) };
1358        unsafe {
1359            let _ = CloseHandle(handle);
1360        }
1361        times.map_err(|error| io_error(&error))?;
1362
1363        // A non-zero exit time means the process object outlives the process
1364        // itself because somebody still holds a handle to it — which this
1365        // process does, for every child it spawned. Without this check a killed
1366        // child would keep reporting `Live` until it was reaped.
1367        if filetime_to_u64(exit) != 0 && filter == super::LivenessFilter::LiveOnly {
1368            return Ok(None);
1369        }
1370
1371        Ok(Some(format!("windows:{}", filetime_to_u64(creation))))
1372    }
1373
1374    pub(super) fn request_stop(_pid: u32) -> io::Result<bool> {
1375        // Windows has no signal a non-console process can be asked to handle
1376        // from outside. `GenerateConsoleCtrlEvent` needs a shared console, and
1377        // a service-hosted agent has none. Reporting `false` tells the caller
1378        // to go straight to `force_stop` rather than sit through a grace period
1379        // during which nothing was ever asked.
1380        Ok(false)
1381    }
1382
1383    pub(super) fn force_stop(pid: u32) -> io::Result<()> {
1384        let _ = std::process::Command::new("taskkill")
1385            .args(["/F", "/T", "/PID", &pid.to_string()])
1386            .stdout(std::process::Stdio::null())
1387            .stderr(std::process::Stdio::null())
1388            .status();
1389
1390        match unsafe { OpenProcess(PROCESS_TERMINATE, false, pid) } {
1391            Ok(handle) => {
1392                let result = unsafe { TerminateProcess(handle, 1) };
1393                unsafe {
1394                    let _ = CloseHandle(handle);
1395                }
1396                if let Err(error) = result {
1397                    let code = error.code().0 as u32;
1398                    if code != 0x80070005 && code != 0x80070057 {
1399                        return Err(io_error(&error));
1400                    }
1401                }
1402                Ok(())
1403            }
1404            Err(error) => {
1405                let code = error.code().0 as u32;
1406                if code == 0x80070005 || code == 0x80070057 {
1407                    Ok(())
1408                } else {
1409                    Err(io_error(&error))
1410                }
1411            }
1412        }
1413    }
1414
1415    /// The current account's SID in string form, for the DACL below.
1416    ///
1417    /// `pub(crate)` because the secret store needs the same answer for the same
1418    /// reason: a DACL that names the account explicitly, rather than one that
1419    /// describes it and hopes the description still fits later.
1420    pub(crate) fn current_user_sid() -> io::Result<String> {
1421        let mut token = HANDLE(std::ptr::null_mut());
1422        unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) }
1423            .map_err(|error| io_error(&error))?;
1424
1425        let mut needed = 0u32;
1426        // The first call is expected to fail with ERROR_INSUFFICIENT_BUFFER; it
1427        // is how the required size is learned.
1428        let _ = unsafe { GetTokenInformation(token, TokenUser, None, 0, &mut needed) };
1429
1430        // `TOKEN_USER` contains a pointer, so the buffer must be
1431        // pointer-aligned; a `Vec<u8>` is aligned to 1 and casting it would be
1432        // undefined behaviour.
1433        let words = (needed as usize).div_ceil(size_of::<usize>()).max(1);
1434        let mut buffer = vec![0usize; words];
1435
1436        let information = unsafe {
1437            GetTokenInformation(
1438                token,
1439                TokenUser,
1440                Some(buffer.as_mut_ptr().cast()),
1441                needed,
1442                &mut needed,
1443            )
1444        };
1445        if let Err(error) = information {
1446            unsafe {
1447                let _ = CloseHandle(token);
1448            }
1449            return Err(io_error(&error));
1450        }
1451
1452        let token_user = unsafe { &*buffer.as_ptr().cast::<TOKEN_USER>() };
1453        let mut sid_string = PWSTR::null();
1454        let converted = unsafe { ConvertSidToStringSidW(token_user.User.Sid, &mut sid_string) };
1455        unsafe {
1456            let _ = CloseHandle(token);
1457        }
1458        converted.map_err(|error| io_error(&error))?;
1459
1460        let text = unsafe { sid_string.to_string() }
1461            .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error));
1462        unsafe {
1463            let _ = LocalFree(Some(HLOCAL(sid_string.0.cast())));
1464        }
1465        text
1466    }
1467
1468    pub(super) fn create_restrictive_file(path: &Path) -> io::Result<File> {
1469        // A protected DACL — the `P` — so that nothing is inherited from the
1470        // parent directory, granting full access to exactly two trustees: this
1471        // account, and the local Administrators group.
1472        //
1473        // `BA` is not a weakening: `07-security.md` places a local
1474        // administrator outside this threat model, because such an account can
1475        // already read the runner's workspace and its credentials. It is kept
1476        // so that an operator can clean up a handoff file left behind by an
1477        // agent running under a service account they are not logged in as.
1478        //
1479        // There is deliberately no `(A;;FA;;;SY)` ACE. An earlier version
1480        // carried one "so that a service running as LocalSystem still works",
1481        // and that justification was simply wrong: if this agent *is*
1482        // LocalSystem then `current_user_sid()` returns S-1-5-18 and the third
1483        // ACE already covers it. So the ACE added nothing in the one case it
1484        // was written for, and in every other case it widened access to a file
1485        // whose entire purpose is to be narrow.
1486        let sddl = format!("D:P(A;;FA;;;BA)(A;;FA;;;{})", current_user_sid()?);
1487        let sddl_wide: Vec<u16> = sddl.encode_utf16().chain(std::iter::once(0)).collect();
1488
1489        let mut descriptor = PSECURITY_DESCRIPTOR(std::ptr::null_mut());
1490        unsafe {
1491            ConvertStringSecurityDescriptorToSecurityDescriptorW(
1492                PCWSTR(sddl_wide.as_ptr()),
1493                SDDL_REVISION_1,
1494                &mut descriptor,
1495                None,
1496            )
1497        }
1498        .map_err(|error| io_error(&error))?;
1499
1500        let attributes = SECURITY_ATTRIBUTES {
1501            nLength: u32::try_from(size_of::<SECURITY_ATTRIBUTES>()).unwrap_or(u32::MAX),
1502            lpSecurityDescriptor: descriptor.0,
1503            // False: a handle to the JIT configuration must not be inherited by
1504            // the runner or by anything else this agent spawns.
1505            bInheritHandle: windows::core::BOOL(0),
1506        };
1507
1508        let wide = to_wide(path);
1509        let handle = unsafe {
1510            CreateFileW(
1511                PCWSTR(wide.as_ptr()),
1512                FILE_GENERIC_READ.0 | FILE_GENERIC_WRITE.0,
1513                FILE_SHARE_NONE,
1514                Some(&raw const attributes),
1515                CREATE_NEW,
1516                FILE_ATTRIBUTE_NORMAL,
1517                None,
1518            )
1519        };
1520
1521        unsafe {
1522            let _ = LocalFree(Some(HLOCAL(descriptor.0)));
1523        }
1524
1525        let handle = handle.map_err(|error| io_error(&error))?;
1526        Ok(unsafe { File::from_raw_handle(handle.0) })
1527    }
1528
1529    pub(super) fn describe_permissions(path: &Path) -> io::Result<(String, bool)> {
1530        let wide = to_wide(path);
1531        let mut descriptor = PSECURITY_DESCRIPTOR(std::ptr::null_mut());
1532        let status = unsafe {
1533            GetNamedSecurityInfoW(
1534                PCWSTR(wide.as_ptr()),
1535                SE_FILE_OBJECT,
1536                DACL_SECURITY_INFORMATION,
1537                None,
1538                None,
1539                None,
1540                None,
1541                &mut descriptor,
1542            )
1543        };
1544        if status != ERROR_SUCCESS {
1545            return Err(io::Error::from_raw_os_error(
1546                i32::try_from(status.0).unwrap_or(i32::MAX),
1547            ));
1548        }
1549
1550        let mut sddl = PWSTR::null();
1551        let converted = unsafe {
1552            ConvertSecurityDescriptorToStringSecurityDescriptorW(
1553                descriptor,
1554                SDDL_REVISION_1,
1555                DACL_SECURITY_INFORMATION,
1556                &mut sddl,
1557                None,
1558            )
1559        };
1560        let text = match converted {
1561            Ok(()) => {
1562                let text = unsafe { sddl.to_string() }
1563                    .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error));
1564                unsafe {
1565                    let _ = LocalFree(Some(HLOCAL(sddl.0.cast())));
1566                }
1567                text
1568            }
1569            Err(error) => Err(io_error(&error)),
1570        };
1571        unsafe {
1572            let _ = LocalFree(Some(HLOCAL(descriptor.0)));
1573        }
1574        let text = text?;
1575
1576        let readable = dacl_grants_broad_access(&text);
1577        Ok((text, readable))
1578    }
1579
1580    /// Whether a DACL in SDDL form lets an ordinary local user other than the
1581    /// owner read the object.
1582    ///
1583    /// Two conditions, and both matter. An unprotected DACL inherits whatever
1584    /// the parent directory grants, which is not this program's to vouch for.
1585    /// And an allow ACE naming one of the broad well-known trustees grants
1586    /// access to every interactive account on the machine.
1587    fn dacl_grants_broad_access(sddl: &str) -> bool {
1588        /// The trustees that mean "more or less anybody logged in here", in
1589        /// both the two-letter SDDL alias form and the raw SID form the
1590        /// converter may emit instead.
1591        const BROAD: &[&str] = &[
1592            "WD",           // Everyone
1593            "S-1-1-0",      // Everyone
1594            "AU",           // Authenticated Users
1595            "S-1-5-11",     // Authenticated Users
1596            "BU",           // Builtin Users
1597            "S-1-5-32-545", // Builtin Users
1598            "IU",           // Interactive
1599            "S-1-5-4",      // Interactive
1600            "AN",           // Anonymous
1601            "S-1-5-7",      // Anonymous
1602            "WR",           // Write Restricted
1603            "LU",           // Performance Log Users
1604        ];
1605
1606        let Some(dacl) = sddl.split("D:").nth(1) else {
1607            // No DACL at all means "everyone, full control" in Windows'
1608            // security model. Never the answer this function should be
1609            // optimistic about.
1610            return true;
1611        };
1612
1613        let flags: String = dacl.chars().take_while(|c| *c != '(').collect();
1614        if !flags.contains('P') {
1615            return true;
1616        }
1617
1618        for ace in dacl.split('(').skip(1) {
1619            let ace = ace.split(')').next().unwrap_or_default();
1620            let fields: Vec<&str> = ace.split(';').collect();
1621            // (type;flags;rights;object_guid;inherit_object_guid;trustee)
1622            let (Some(kind), Some(trustee)) = (fields.first(), fields.get(5)) else {
1623                continue;
1624            };
1625            // Only allow ACEs grant anything; a deny ACE naming Everyone is a
1626            // tightening, not a leak.
1627            if !kind.starts_with('A') {
1628                continue;
1629            }
1630            if BROAD
1631                .iter()
1632                .any(|broad| trustee.eq_ignore_ascii_case(broad))
1633            {
1634                return true;
1635            }
1636        }
1637
1638        false
1639    }
1640
1641    #[cfg(test)]
1642    mod tests {
1643        use super::dacl_grants_broad_access;
1644
1645        #[test]
1646        fn a_protected_owner_only_dacl_is_not_broadly_readable() {
1647            // The shape `create_restrictive_file` actually writes: protected,
1648            // Administrators, and this account. No LocalSystem ACE — see the
1649            // comment there for why one would add nothing.
1650            assert!(!dacl_grants_broad_access(
1651                "D:P(A;;FA;;;BA)(A;;FA;;;S-1-5-21-1-2-3-1001)"
1652            ));
1653            // A LocalSystem agent's own SID is S-1-5-18, which is what makes
1654            // the separate `SY` ACE redundant rather than load-bearing.
1655            assert!(!dacl_grants_broad_access(
1656                "D:P(A;;FA;;;BA)(A;;FA;;;S-1-5-18)"
1657            ));
1658            // Still tolerated when it arrives from somewhere else: this
1659            // heuristic inspects files, and not every file it sees was written
1660            // by this module.
1661            assert!(!dacl_grants_broad_access(
1662                "D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FA;;;S-1-5-21-1-2-3-1001)"
1663            ));
1664        }
1665
1666        #[test]
1667        fn an_everyone_ace_is_broadly_readable_in_either_notation() {
1668            assert!(dacl_grants_broad_access("D:P(A;;FA;;;SY)(A;;FR;;;WD)"));
1669            assert!(dacl_grants_broad_access("D:P(A;;FA;;;SY)(A;;FR;;;S-1-1-0)"));
1670            assert!(dacl_grants_broad_access("D:P(A;;FR;;;BU)"));
1671        }
1672
1673        #[test]
1674        fn an_unprotected_dacl_is_broadly_readable_because_it_inherits() {
1675            assert!(dacl_grants_broad_access("D:AI(A;ID;FA;;;SY)"));
1676        }
1677
1678        #[test]
1679        fn a_deny_ace_for_everyone_is_not_a_grant() {
1680            assert!(!dacl_grants_broad_access("D:P(D;;FA;;;WD)(A;;FA;;;SY)"));
1681        }
1682
1683        #[test]
1684        fn a_missing_dacl_is_treated_as_wide_open() {
1685            assert!(dacl_grants_broad_access("O:BAG:BA"));
1686        }
1687    }
1688}
1689
1690#[cfg(unix)]
1691mod sys {
1692    use std::fs::File;
1693    use std::io;
1694    use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
1695    use std::path::Path;
1696
1697    pub(super) fn request_stop(pid: u32) -> io::Result<bool> {
1698        // SAFETY: `kill` takes a PID and a signal number and touches no memory
1699        // this program owns. The PID is checked for liveness by the caller
1700        // immediately beforehand, and every caller either holds the child
1701        // handle or has just re-verified the process identity.
1702        // We use `-pid` to send the signal to the entire process group.
1703        let result = unsafe { libc::kill(-(pid as libc::pid_t), libc::SIGTERM) };
1704        if result == 0 {
1705            return Ok(true);
1706        }
1707        let error = io::Error::last_os_error();
1708        // The process exited between the liveness check and the signal. That is
1709        // a normal race, not a failure to stop it.
1710        if error.raw_os_error() == Some(libc::ESRCH) {
1711            return Ok(true);
1712        }
1713        Err(error)
1714    }
1715
1716    pub(super) fn force_stop(pid: u32) -> io::Result<()> {
1717        // SAFETY: as `request_stop`.
1718        let result = unsafe { libc::kill(-(pid as libc::pid_t), libc::SIGKILL) };
1719        if result == 0 {
1720            return Ok(());
1721        }
1722        let error = io::Error::last_os_error();
1723        if error.raw_os_error() == Some(libc::ESRCH) {
1724            return Ok(());
1725        }
1726        Err(error)
1727    }
1728
1729    pub(super) fn create_restrictive_file(path: &Path) -> io::Result<File> {
1730        // `mode` is applied by `open(2)` itself, so the file never exists with
1731        // any other permissions. `create_new` makes it exclusive, so a
1732        // pre-created path belonging to somebody else is an error rather than a
1733        // file this process writes a JIT configuration into.
1734        std::fs::OpenOptions::new()
1735            .read(true)
1736            .write(true)
1737            .create_new(true)
1738            .mode(0o600)
1739            .open(path)
1740    }
1741
1742    pub(super) fn describe_permissions(path: &Path) -> io::Result<(String, bool)> {
1743        let mode = std::fs::metadata(path)?.permissions().mode() & 0o777;
1744        // Any group or other bit at all, not just the read bit: an executable
1745        // or writable bit for another account is not something this file should
1746        // ever carry either.
1747        Ok((format!("mode {mode:04o}"), mode & 0o077 != 0))
1748    }
1749
1750    #[cfg(target_os = "linux")]
1751    pub(super) fn start_token(
1752        pid: u32,
1753        filter: super::LivenessFilter,
1754    ) -> io::Result<Option<String>> {
1755        let stat = match std::fs::read_to_string(format!("/proc/{pid}/stat")) {
1756            Ok(stat) => stat,
1757            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
1758            Err(error) => return Err(error),
1759        };
1760
1761        let parsed = super::parse_proc_stat(&stat).ok_or_else(|| {
1762            io::Error::new(
1763                io::ErrorKind::InvalidData,
1764                format!("/proc/{pid}/stat is not in the documented format"),
1765            )
1766        })?;
1767
1768        // `Z` is a process that has exited and is waiting to be reaped. Its PID
1769        // is still taken, but it is not a process that can be adopted or asked
1770        // to do anything.
1771        if parsed.state == "Z" && filter == super::LivenessFilter::LiveOnly {
1772            return Ok(None);
1773        }
1774
1775        Ok(Some(format!("linux:{}:{}", boot_id()?, parsed.start_ticks)))
1776    }
1777
1778    /// An identifier that changes on every boot.
1779    ///
1780    /// Needed because `starttime` counts from boot, so without it a process
1781    /// started 500 ticks after this boot and one started 500 ticks after the
1782    /// previous boot are indistinguishable — which is exactly the confusion a
1783    /// journal read back after a reboot invites.
1784    #[cfg(target_os = "linux")]
1785    fn boot_id() -> io::Result<String> {
1786        // Every kernel since 2.6.19 offers this, and it is world-readable.
1787        if let Ok(id) = std::fs::read_to_string("/proc/sys/kernel/random/boot_id") {
1788            let id = id.trim();
1789            if !id.is_empty() {
1790                return Ok(id.to_string());
1791            }
1792        }
1793
1794        // A container or a hardened kernel may hide it. `btime` in
1795        // `/proc/stat` is the boot wall-clock time in whole seconds and serves
1796        // the same purpose here: it distinguishes boots. It is only ever the
1797        // fallback because two boots within the same second would collide, and
1798        // `boot_id` cannot.
1799        btime()
1800            .map(|value| format!("btime-{value}"))
1801            .map_err(|error| {
1802                if error.kind() == io::ErrorKind::NotFound {
1803                    io::Error::new(
1804                        io::ErrorKind::NotFound,
1805                        "neither /proc/sys/kernel/random/boot_id nor /proc/stat btime is \
1806                         readable, so a process identity that survives a reboot cannot be formed",
1807                    )
1808                } else {
1809                    error
1810                }
1811            })
1812    }
1813
1814    /// `btime` from `/proc/stat`: the boot wall-clock time, in whole seconds.
1815    #[cfg(target_os = "linux")]
1816    pub(super) fn btime() -> io::Result<String> {
1817        let stat = std::fs::read_to_string("/proc/stat")?;
1818        stat.lines()
1819            .find_map(|line| line.strip_prefix("btime "))
1820            .map(|value| value.trim().to_string())
1821            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "/proc/stat has no btime"))
1822    }
1823
1824    #[cfg(target_os = "macos")]
1825    pub(super) fn start_token(
1826        pid: u32,
1827        filter: super::LivenessFilter,
1828    ) -> io::Result<Option<String>> {
1829        // `proc_pidinfo(PROC_PIDTBSDINFO)` rather than `sysctl(KERN_PROC)`:
1830        // libc 0.2 defines `proc_bsdinfo` for Apple targets but not
1831        // `kinfo_proc`, so the sysctl route would mean declaring the struct
1832        // layout by hand — a layout this crate would then own and have to keep
1833        // correct across macOS releases. `proc_pidinfo` gives the same
1834        // microsecond start time through a declared type.
1835        //
1836        // SAFETY: `info` is a correctly sized, zero-initialised `proc_bsdinfo`
1837        // and the size passed matches it, so the kernel writes only within it.
1838        // `proc_pidinfo` reads no memory this program owns other than that
1839        // buffer.
1840        let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
1841        let size = i32::try_from(size_of::<libc::proc_bsdinfo>()).unwrap_or(i32::MAX);
1842        let written = unsafe {
1843            libc::proc_pidinfo(
1844                pid as libc::c_int,
1845                libc::PROC_PIDTBSDINFO,
1846                0,
1847                std::ptr::from_mut(&mut info).cast(),
1848                size,
1849            )
1850        };
1851
1852        if written <= 0 {
1853            let error = io::Error::last_os_error();
1854            // See `super::probe_failure_means_gone`, which is where this rule
1855            // lives so that it can be tested on a leg that has no `libc`.
1856            // Only ESRCH is "gone"; EPERM and a zero `errno` are errors.
1857            return if super::probe_failure_means_gone(error.raw_os_error(), libc::ESRCH) {
1858                Ok(None)
1859            } else {
1860                Err(error)
1861            };
1862        }
1863        if written != size {
1864            return Err(io::Error::new(
1865                io::ErrorKind::InvalidData,
1866                format!("proc_pidinfo returned {written} bytes for PID {pid}, expected {size}"),
1867            ));
1868        }
1869
1870        // A zombie still holds its PID but is not a process anything can adopt.
1871        if info.pbi_status == libc::SZOMB && filter == super::LivenessFilter::LiveOnly {
1872            return Ok(None);
1873        }
1874
1875        Ok(Some(format!(
1876            "macos:{}.{:06}",
1877            info.pbi_start_tvsec, info.pbi_start_tvusec
1878        )))
1879    }
1880
1881    /// The highest base priority XNU gives a "darwinbg" task
1882    /// (`MAXPRI_THROTTLE`). A normal user task runs at 31.
1883    #[cfg(target_os = "macos")]
1884    pub(super) const BACKGROUND_PRIORITY_CEILING: i32 = 4;
1885
1886    /// The highest base scheduling priority among the process's threads: the
1887    /// number `ps -o pri` shows.
1888    ///
1889    /// The threads, because that is where the throttle is. Under a launchd
1890    /// `Background` job a child's task priority (`proc_taskinfo::pti_priority`)
1891    /// reads 31 while every one of its threads has base priority 4, and `ps`
1892    /// shows 4 (measured on macOS 27); only the job itself reads 4 there. A
1893    /// check of the task priority therefore passes for exactly the runners it
1894    /// exists to catch. `getpriority(PRIO_DARWIN_PROCESS, pid)` is no better:
1895    /// for a `Background` agent at priority 4 it answers 0, "not background".
1896    #[cfg(target_os = "macos")]
1897    pub(super) fn base_priority(pid: u32) -> io::Result<i32> {
1898        /// `PROC_PIDLISTTHREADS` from `<sys/proc_info.h>`, which `libc` lacks.
1899        const PROC_PIDLISTTHREADS: libc::c_int = 6;
1900        /// Far more than a freshly started runner has; a process with more
1901        /// threads is still judged by the first this many.
1902        const MAX_THREADS: usize = 256;
1903
1904        let mut threads = [0u64; MAX_THREADS];
1905        let capacity = i32::try_from(size_of_val(&threads)).unwrap_or(i32::MAX);
1906        // SAFETY: the buffer and its exact size in bytes, so the kernel writes
1907        // only within it.
1908        let written = unsafe {
1909            libc::proc_pidinfo(
1910                pid as libc::c_int,
1911                PROC_PIDLISTTHREADS,
1912                0,
1913                threads.as_mut_ptr().cast(),
1914                capacity,
1915            )
1916        };
1917        if written <= 0 {
1918            return Err(io::Error::last_os_error());
1919        }
1920        let count = usize::try_from(written).unwrap_or(0) / size_of::<u64>();
1921        let size = i32::try_from(size_of::<libc::proc_threadinfo>()).unwrap_or(i32::MAX);
1922        let mut highest = None;
1923        for &thread in &threads[..count.min(MAX_THREADS)] {
1924            // SAFETY: as above, a zeroed, correctly sized `proc_threadinfo`.
1925            let mut info: libc::proc_threadinfo = unsafe { std::mem::zeroed() };
1926            let written = unsafe {
1927                libc::proc_pidinfo(
1928                    pid as libc::c_int,
1929                    libc::PROC_PIDTHREADINFO,
1930                    thread,
1931                    std::ptr::from_mut(&mut info).cast(),
1932                    size,
1933                )
1934            };
1935            // A thread can exit between the listing and this read.
1936            if written == size {
1937                highest = highest.max(Some(info.pth_priority));
1938            }
1939        }
1940        highest.ok_or_else(io::Error::last_os_error)
1941    }
1942
1943    /// Whether `pid` runs at or under the background priority ceiling. A
1944    /// process that can no longer be read is not reported as throttled.
1945    #[cfg(target_os = "macos")]
1946    pub(super) fn runs_throttled(pid: u32) -> bool {
1947        base_priority(pid).is_ok_and(|priority| priority <= BACKGROUND_PRIORITY_CEILING)
1948    }
1949}
1950
1951// ---------------------------------------------------------------------------
1952// Tests
1953// ---------------------------------------------------------------------------
1954
1955#[cfg(test)]
1956pub(crate) mod tests {
1957    use super::*;
1958
1959    /// Every Rust program, this test binary and the daemon alike, starts with
1960    /// SIGPIPE ignored, and an ignored disposition survives `exec`. A runner
1961    /// started with it would hand it to every job step, where `yes | head`
1962    /// exits 1 instead of 141 and `tr … </dev/urandom | head` never ends. The
1963    /// child must start with the default disposition, so a shell that sends
1964    /// itself SIGPIPE dies of it.
1965    ///
1966    /// Job steps on a runner this product starts do still see SIGPIPE ignored,
1967    /// on every host and under a classic runner too: .NET ignores it in
1968    /// `Runner.Listener` and `Runner.Worker`, and its process start keeps an
1969    /// ignored disposition for the shells it runs (actions/runner#2684). That is
1970    /// below this spawn, and this test pins only what this spawn hands over.
1971    #[cfg(unix)]
1972    #[test]
1973    fn a_spawned_child_starts_with_the_default_sigpipe_disposition() {
1974        use std::os::unix::process::ExitStatusExt as _;
1975        let mut child = SpawnSpec::new("/bin/sh")
1976            .args(["-c", "kill -s PIPE $$; exit 3"])
1977            .output(OutputMode::Discard)
1978            .spawn()
1979            .expect("/bin/sh starts");
1980        let status = child.wait().expect("the shell is reaped");
1981        assert_eq!(
1982            status.signal(),
1983            Some(libc::SIGPIPE),
1984            "the child inherited an ignored SIGPIPE: {status:?}"
1985        );
1986    }
1987
1988    /// A child can be gone before its parent reads its identity, and launching
1989    /// it must still succeed. macOS is where this bites: `proc_pidinfo` answers
1990    /// `ESRCH` for a child that has only just exited, so `IncludeExited` -- which
1991    /// covers a zombie -- never gets a say, and the spawn failed outright.
1992    #[test]
1993    fn a_child_that_is_already_gone_is_still_given_an_identity() {
1994        let identity = ProcessIdentity::of_child(u32::MAX).expect(
1995            "a parent holding the handle must always end up with an identity, even for a              child that has already exited",
1996        );
1997
1998        // The sentinel is a claim about nothing, deliberately: there is no
1999        // start instant to read, and inventing one would be a lie that a later
2000        // comparison could believe.
2001        assert_eq!(
2002            identity.classify(None),
2003            Adoption::Gone,
2004            "a PID nobody holds is gone"
2005        );
2006        assert!(
2007            matches!(
2008                identity.classify(Some("macos:1.000000".to_string())),
2009                Adoption::PidRecycled { .. }
2010            ),
2011            "and a PID somebody else has taken is recycled -- which is refused, never signalled"
2012        );
2013    }
2014
2015    /// A program that exits immediately, on every supported platform.
2016    pub(crate) fn quick_exit() -> SpawnSpec {
2017        if cfg!(windows) {
2018            SpawnSpec::new("cmd").args(["/C", "exit", "0"])
2019        } else {
2020            SpawnSpec::new("true")
2021        }
2022    }
2023
2024    /// A program that stays alive until it is stopped.
2025    ///
2026    /// Deliberately a single process on both families rather than a shell
2027    /// wrapping one. Terminating a shell does not terminate the child it
2028    /// spawned, so a `cmd /C …` or `sh -c …` wrapper would leave a stray
2029    /// process behind after every test that stops it — and would make
2030    /// `Adoption::Gone` assertions read as passes for the wrong reason.
2031    ///
2032    /// `ping -n 600 127.0.0.1` sends one loopback echo a second for ten
2033    /// minutes: it needs no console, writes to the null device this spec
2034    /// already sets, and burns no CPU while waiting.
2035    pub(crate) fn long_running() -> SpawnSpec {
2036        if cfg!(windows) {
2037            SpawnSpec::new("ping").args(["-n", "600", "127.0.0.1"])
2038        } else {
2039            SpawnSpec::new("sleep").args(["600"])
2040        }
2041    }
2042
2043    /// The coarsest start-token resolution any supported platform has.
2044    ///
2045    /// Linux's token carries `/proc/<pid>/stat` field 22, which counts
2046    /// `USER_HZ` ticks. `USER_HZ` is 100 on every supported distribution, so
2047    /// one tick is **10 ms** and two processes started inside the same tick get
2048    /// byte-identical start tokens. Windows resolves creation time to 100 ns
2049    /// and macOS to 1 µs, so neither can collide this way.
2050    const COARSEST_START_TOKEN_TICK: Duration = Duration::from_millis(10);
2051
2052    /// Puts a start-token boundary between two spawns.
2053    ///
2054    /// Every "recycled PID" fixture below works by pairing one process's PID
2055    /// with another process's start token. That only *is* a recycled record if
2056    /// the two tokens differ. Spawning back to back is well inside one Linux
2057    /// tick — a `posix_spawn` and two small `/proc` reads — so without this the
2058    /// synthesised record would be the survivor's genuine identity, `recheck`
2059    /// would correctly answer `Live`, and the fixture would fail while the
2060    /// primitive it is testing was working exactly as designed.
2061    ///
2062    /// This is a defect in the fixture and not in the discriminator: recycling
2063    /// a PID for real takes far longer than 10 ms, and `boot_id` changes across
2064    /// a reboot, so no production record can collide this way.
2065    fn separate_start_tokens() {
2066        // Comfortably more than one tick, so a slow or virtualised Linux CI
2067        // runner does not land on the boundary itself.
2068        std::thread::sleep(COARSEST_START_TOKEN_TICK * 5 / 2);
2069    }
2070
2071    /// Fails with a message naming its own cause if two spawns still collided.
2072    ///
2073    /// Without this the collision surfaces as `assert!(!…is_live())` or as a
2074    /// dead survivor, both of which read as "the start token has stopped
2075    /// discriminating" — the opposite of what actually happened.
2076    fn assert_distinguishable(first: &ProcessIdentity, second: &ProcessIdentity) {
2077        assert_ne!(
2078            first.start_token(),
2079            second.start_token(),
2080            "the two children share a start token, so the record synthesised below would be \
2081             the second child's real identity rather than a recycled one. This is the fixture \
2082             colliding inside one start-token tick, not the discriminator failing; lengthen \
2083             `separate_start_tokens` for this platform."
2084        );
2085    }
2086
2087    // -----------------------------------------------------------------------
2088    // The Linux `/proc/<pid>/stat` parser
2089    //
2090    // Deliberately not `#[cfg(target_os = "linux")]`. This is the only Linux
2091    // path in the crate whose correctness is decidable without a Linux kernel,
2092    // and running it on all three legs means a Windows or macOS developer
2093    // breaking it finds out immediately rather than in the Linux leg of CI.
2094    // -----------------------------------------------------------------------
2095
2096    /// A real `/proc/<pid>/stat` line, from a 6.x kernel, truncated after the
2097    /// fields this crate reads. Fields 1 and 2 are the PID and `comm`; field 3
2098    /// is the state; field 22 is `starttime`.
2099    const REAL_STAT: &str = "1234 (bash) S 1200 1234 1234 34816 1234 4194304 3300 5100 0 0 6 5 8 4 20 0 1 0 987654 12345678 900 18446744073709551615";
2100
2101    #[test]
2102    fn the_proc_stat_parser_reads_the_state_and_the_start_time() {
2103        let parsed = parse_proc_stat(REAL_STAT).expect("a well-formed line parses");
2104        assert_eq!(parsed.state, "S");
2105        assert_eq!(
2106            parsed.start_ticks, "987654",
2107            "field 22 is `starttime`; an off-by-one here silently produces a process identity \
2108             that is stable but wrong, which is worse than one that fails"
2109        );
2110    }
2111
2112    #[test]
2113    fn the_proc_stat_parser_survives_a_command_name_containing_spaces_and_parentheses() {
2114        // `procfs(5)` permits this, and a whitespace split of the whole line
2115        // mis-indexes every field after it. The failure would show up only for
2116        // a process whose name was chosen to cause it — that is, only when
2117        // somebody meant to.
2118        let hostile = REAL_STAT.replace("(bash)", "(my prog (v2) :) )");
2119        let parsed = parse_proc_stat(&hostile).expect("a hostile comm still parses");
2120        assert_eq!(parsed.state, "S");
2121        assert_eq!(parsed.start_ticks, "987654");
2122    }
2123
2124    #[test]
2125    fn a_naive_whitespace_split_gets_the_hostile_case_wrong() {
2126        // Shows the previous test is not decorative: the obvious
2127        // implementation, run on the same input, returns a different field.
2128        let hostile = REAL_STAT.replace("(bash)", "(my prog (v2) :) )");
2129        let naive: Vec<&str> = hostile.split_whitespace().collect();
2130        // Field 22 counting from the start of the line, as the naive reading
2131        // would.
2132        let naive_start = naive.get(21).copied();
2133
2134        assert_ne!(
2135            naive_start,
2136            Some(parse_proc_stat(&hostile).expect("parses").start_ticks),
2137            "if these agree, the hostile fixture no longer exercises the hazard and the test \
2138             above proves nothing"
2139        );
2140    }
2141
2142    #[test]
2143    fn the_proc_stat_parser_reports_a_zombie() {
2144        let zombie = REAL_STAT.replacen(") S ", ") Z ", 1);
2145        let parsed = parse_proc_stat(&zombie).expect("parses");
2146        assert_eq!(
2147            parsed.state, "Z",
2148            "a zombie holds its PID but is not adoptable; the caller depends on seeing this"
2149        );
2150    }
2151
2152    #[test]
2153    fn the_proc_stat_parser_rejects_a_truncated_line() {
2154        assert_eq!(parse_proc_stat(""), None);
2155        assert_eq!(parse_proc_stat("1234 (bash)"), None);
2156        assert_eq!(parse_proc_stat("1234 (bash) S 1200"), None);
2157        assert_eq!(
2158            parse_proc_stat("no parenthesis here at all"),
2159            None,
2160            "a line with no comm field must be rejected, not indexed into"
2161        );
2162    }
2163
2164    #[test]
2165    fn the_current_process_has_a_stable_identity() {
2166        let first = ProcessIdentity::of_current_process().expect("this process can see itself");
2167        let second = ProcessIdentity::of_current_process().expect("twice");
2168
2169        assert_eq!(
2170            first, second,
2171            "an identity that changes between two reads of the same live process would make \
2172             every journal record unmatchable"
2173        );
2174        assert_eq!(first.pid(), std::process::id());
2175        assert!(
2176            !first.start_token().is_empty(),
2177            "an empty start token would make the identity a bare PID again"
2178        );
2179        assert_eq!(first.recheck().expect("resolvable"), Adoption::Live);
2180    }
2181
2182    #[test]
2183    fn the_start_token_varies_between_processes() {
2184        // Guards against the degenerate implementation that satisfies every
2185        // other test in this module: a token that is the same constant for
2186        // everything. Such a token would make a recycled PID indistinguishable
2187        // from the original process.
2188        //
2189        // Under cargo-nextest, this test process and its child start so close
2190        // together that they can share the same clock tick on Linux (10ms resolution).
2191        // Sleep for a tick to ensure they have distinct start times.
2192        std::thread::sleep(Duration::from_millis(20));
2193
2194        let mut child = long_running().spawn().expect("the child starts");
2195        let mine = ProcessIdentity::of_current_process().expect("this process can see itself");
2196
2197        assert_ne!(
2198            child.identity().start_token(),
2199            mine.start_token(),
2200            "two different processes must not share a start token"
2201        );
2202
2203        child.stop(Duration::from_secs(5)).expect("the child stops");
2204    }
2205
2206    #[test]
2207    fn a_spawned_child_is_observable_and_terminable() {
2208        let mut child = long_running().spawn().expect("the child starts");
2209
2210        assert!(child.is_running().expect("observable"), "just spawned");
2211        assert_eq!(child.identity().pid(), child.pid());
2212        assert_eq!(
2213            child.identity().recheck().expect("resolvable"),
2214            Adoption::Live,
2215            "a running child must re-resolve to itself"
2216        );
2217        assert_eq!(
2218            child.wait_for(Duration::from_millis(50)).expect("waitable"),
2219            None,
2220            "a long-running child must not be reported as exited"
2221        );
2222
2223        child
2224            .stop(Duration::from_secs(10))
2225            .expect("the child stops");
2226
2227        assert!(!child.is_running().expect("observable"), "after stop");
2228        assert_eq!(
2229            child.identity().recheck().expect("resolvable"),
2230            Adoption::Gone,
2231            "a stopped child's identity must not still resolve as live"
2232        );
2233    }
2234
2235    #[test]
2236    fn a_child_that_exits_on_its_own_is_reported_as_exited() {
2237        let mut child = quick_exit().spawn().expect("the child starts");
2238
2239        let status = child
2240            .wait_for(Duration::from_secs(30))
2241            .expect("waitable")
2242            .expect("a program that exits immediately must be seen to exit");
2243        assert!(status.success(), "{status:?}");
2244        assert!(!child.is_running().expect("observable"));
2245    }
2246
2247    /// The Definition of Done clause this whole module exists for: *"its
2248    /// recorded identity is re-resolvable after a simulated restart and does
2249    /// **not** match a recycled PID belonging to a different process"*.
2250    ///
2251    /// The restart is simulated by round-tripping the identity through JSON —
2252    /// the journal's representation — and dropping every in-memory handle, so
2253    /// the re-resolution has nothing but the serialised record to work from.
2254    /// The recycling is simulated by pairing a *live* process's PID with a
2255    /// *different* process's start token, which is precisely the state a real
2256    /// PID reuse produces.
2257    #[test]
2258    fn a_recorded_identity_survives_a_restart_and_rejects_a_recycled_pid() {
2259        let mut victim = long_running().spawn().expect("the first child starts");
2260        let recorded = victim.identity().clone();
2261
2262        // The journal round trip.
2263        let journalled = serde_json::to_string(&recorded).expect("serialisable");
2264        let recovered: ProcessIdentity = serde_json::from_str(&journalled).expect("readable back");
2265        assert_eq!(recovered, recorded);
2266        assert_eq!(
2267            recovered.recheck().expect("resolvable"),
2268            Adoption::Live,
2269            "a journalled identity whose process is still running must be adoptable; e3's \
2270             restart recovery depends on exactly this"
2271        );
2272
2273        // A second, unrelated process. Its PID is the one the record will be
2274        // made to point at.
2275        separate_start_tokens();
2276        let mut survivor = long_running().spawn().expect("the second child starts");
2277        let survivor_identity = survivor.identity().clone();
2278        assert_ne!(survivor_identity.pid(), recorded.pid());
2279        assert_distinguishable(&recorded, &survivor_identity);
2280
2281        victim
2282            .stop(Duration::from_secs(10))
2283            .expect("the first child stops");
2284
2285        // The record as it would look after PID reuse: the journalled start
2286        // token, now pointing at a PID a different process holds.
2287        let recycled = ProcessIdentity {
2288            pid: survivor_identity.pid(),
2289            start_token: recorded.start_token().to_string(),
2290        };
2291
2292        match recycled.recheck().expect("resolvable") {
2293            Adoption::PidRecycled { current } => {
2294                assert_eq!(
2295                    current, survivor_identity,
2296                    "the recycled answer must name whoever actually holds the PID"
2297                );
2298            }
2299            other => panic!(
2300                "a recycled PID must not be adopted, and must be distinguishable from a PID \
2301                 nobody holds; got {other:?}"
2302            ),
2303        }
2304
2305        survivor
2306            .stop(Duration::from_secs(10))
2307            .expect("the second child stops");
2308    }
2309
2310    /// Only `ESRCH` means the process is gone.
2311    ///
2312    /// Runs on every leg, including the one with no `libc`, because the rule is
2313    /// a function over an `Option<i32>` rather than a `match` buried in a
2314    /// `#[cfg(target_os = "macos")]` body. `ESRCH` is 3 on both Unix platforms,
2315    /// but it is passed in rather than assumed, so this stays true of a
2316    /// platform where it is not.
2317    #[test]
2318    fn only_no_such_process_means_gone() {
2319        const ESRCH: i32 = 3;
2320        const EPERM: i32 = 1;
2321
2322        assert!(probe_failure_means_gone(Some(ESRCH), ESRCH));
2323
2324        // The finding this guards. A zero `errno` was once folded in with
2325        // `ESRCH`, which contradicted the Windows policy on
2326        // `ERROR_ACCESS_DENIED`: an unexplained failure is not evidence that
2327        // the process is gone, and answering `Gone` for one is how an agent
2328        // decides to start a second runner for an attempt that already has one.
2329        assert!(
2330            !probe_failure_means_gone(Some(0), ESRCH),
2331            "a zero errno is an unexplained failure, not an absent process"
2332        );
2333
2334        // A process owned by another account. Reporting this as `Gone` would
2335        // silently un-adopt every runner after a service-account change.
2336        assert!(!probe_failure_means_gone(Some(EPERM), ESRCH));
2337
2338        // No errno at all is not evidence of anything either.
2339        assert!(!probe_failure_means_gone(None, ESRCH));
2340    }
2341
2342    /// The attribute this scan walks, and the lint it looks for inside it.
2343    ///
2344    /// Assembled rather than written out, so that this file contains no
2345    /// literal spelling of the attribute outside the attributes themselves.
2346    /// A text scan reads its own machinery as readily as it reads code: the
2347    /// first version of this test found the attribute quoted in its own
2348    /// documentation and failed, which was a fair demonstration that it
2349    /// detects the shape and a reminder that the needle must not be in the
2350    /// haystack.
2351    const CFG_ATTR: &str = concat!("#[cfg_", "attr(");
2352
2353    /// The lint's own name, which has to appear verbatim in any allowance.
2354    const DEAD_CODE: &str = concat!("dead_", "code");
2355
2356    /// The condition of every `dead_code` allowance in `source` that names a
2357    /// platform rather than the complement of one.
2358    ///
2359    /// Split out from the test below so that it can also be run against a
2360    /// fixture. A scan that finds nothing in this file is worth exactly what
2361    /// its ability to find something is worth, and the only way to establish
2362    /// that is to hand it something it must object to -- the same device
2363    /// `logging.rs` uses to prove its secret-injection scan is capable of
2364    /// failing.
2365    fn positive_dead_code_conditions(source: &str) -> Vec<String> {
2366        // Comment lines go first, for the reason `CFG_ATTR` documents.
2367        let code: String = source
2368            .lines()
2369            .filter(|line| !line.trim_start().starts_with("//"))
2370            .collect::<Vec<_>>()
2371            .join("\n");
2372
2373        let mut offenders = Vec::new();
2374
2375        for block in code.split(CFG_ATTR).skip(1) {
2376            // Walk to the `)` closing the attribute, and remember the first
2377            // comma at depth zero: that is what separates the condition from
2378            // the attributes it applies.
2379            let mut depth = 0usize;
2380            let mut body_end = None;
2381            let mut split_at = None;
2382            for (index, character) in block.char_indices() {
2383                match character {
2384                    '(' => depth += 1,
2385                    ')' => {
2386                        if depth == 0 {
2387                            body_end = Some(index);
2388                            break;
2389                        }
2390                        depth -= 1;
2391                    }
2392                    ',' if depth == 0 && split_at.is_none() => split_at = Some(index),
2393                    _ => {}
2394                }
2395            }
2396
2397            let (Some(body_end), Some(split_at)) = (body_end, split_at) else {
2398                continue;
2399            };
2400            if !block[split_at..body_end].contains(DEAD_CODE) {
2401                continue;
2402            }
2403
2404            let condition = block[..split_at].trim();
2405            if !condition.starts_with("not(") {
2406                offenders.push(condition.to_string());
2407            }
2408        }
2409
2410        offenders
2411    }
2412
2413    /// Every `dead_code` allowance in this file must name a *complement*.
2414    ///
2415    /// A lint on the lint, and it exists because the alternative did not work.
2416    /// `probe_failure_means_gone` carried a `dead_code` allowance conditioned
2417    /// on `windows` while its only non-test caller was macOS-only. On Linux the
2418    /// allowance was inactive *and* the caller absent, so the lint fired on
2419    /// the lib target and `cargo clippy --all-targets -- -D warnings` failed --
2420    /// on the one CI leg no Windows developer runs, and invisibly to every
2421    /// local gate.
2422    ///
2423    /// A `dead_code` allowance is a claim about everywhere the caller is *not*,
2424    /// so its condition is naturally a complement: `not(target_os = "…")`. A
2425    /// bare positive names a single platform and says nothing whatsoever about
2426    /// the rest, which is precisely how the wrong one went unnoticed. Requiring
2427    /// the complement form does not prove the condition names the *right*
2428    /// platform, but it does refuse the shape that hid the bug.
2429    ///
2430    /// # No lower bound, and why the vacuity check is a fixture instead
2431    ///
2432    /// This used to end with `checked >= 3`: a lower bound on the number of
2433    /// allowances found. A lower bound cannot tell "the parser stopped
2434    /// matching" from "somebody removed an allowance properly", so it punished
2435    /// the correct remediation. Replacing one of these with a plain
2436    /// `cfg(any(…, test))` -- no allowance at all, which is strictly stronger,
2437    /// because it makes the lint's premise false rather than silencing the
2438    /// report -- left `cargo clippy --all-targets -- -D warnings` clean and
2439    /// this test failing. A tripwire that fires on the better fix teaches
2440    /// people to make the worse one.
2441    ///
2442    /// Counting parsed attributes against occurrences in the text does not fix
2443    /// it either, and that was tried: both counts come from the same needle, so
2444    /// breaking the needle takes both to zero and the check passes. Measured,
2445    /// not reasoned -- the probe that was meant to fail did not.
2446    ///
2447    /// So the vacuity check is
2448    /// [`the_allowance_scan_catches_a_positive_condition`], which runs the same
2449    /// walk over a fixture that must be objected to. It cannot go vacuous,
2450    /// because its input does not depend on what this file happens to contain,
2451    /// and it costs nothing when an allowance is properly removed.
2452    ///
2453    /// # Scope
2454    ///
2455    /// Scoped to this file because it is the only one in the crate that carries
2456    /// a `dead_code` allowance. It is *not* the only one with
2457    /// target-conditional compilation, which is what this used to claim and
2458    /// which was untrue: `paths.rs` and `logging.rs` both carry `#[cfg(unix)]`,
2459    /// and `lock.rs` carries a Windows arm and a Unix arm. Those are a
2460    /// different shape and not the one guarded here -- a `cfg` that selects an
2461    /// implementation is load-bearing, while an `allow(dead_code)` conditioned
2462    /// on one platform is an unexamined claim about all the others. If an
2463    /// allowance ever appears in another file this scan will not see it, and
2464    /// widening it is then the fix.
2465    #[test]
2466    fn every_dead_code_allowance_names_a_complement() {
2467        let offenders = positive_dead_code_conditions(include_str!("process.rs"));
2468        assert!(
2469            offenders.is_empty(),
2470            "a dead_code allowance must name the complement of its caller's \
2471             cfg rather than one platform, or it says nothing about the legs \
2472             it does not name: {offenders:?}"
2473        );
2474    }
2475
2476    /// Proves the scan above is capable of finding something.
2477    ///
2478    /// Without this, "no offending allowance in the file" and "the walk no
2479    /// longer recognises an attribute" are the same passing test. The fixtures
2480    /// are assembled with `concat!` for the reason [`CFG_ATTR`] documents: a
2481    /// literal here would be found by the file scan itself and reported as a
2482    /// defect in the file.
2483    #[test]
2484    fn the_allowance_scan_catches_a_positive_condition() {
2485        let offending = concat!(
2486            "#[cfg_",
2487            "attr(windows, allow(dead_",
2488            "code, reason = \"a reason\"))]\nfn f() {}"
2489        );
2490        assert_eq!(
2491            positive_dead_code_conditions(offending),
2492            vec!["windows".to_string()],
2493            "the walk no longer recognises an allowance, so the scan over this \
2494             file is checking nothing"
2495        );
2496
2497        // The shape this file actually uses is not objected to.
2498        let complement = concat!(
2499            "#[cfg_",
2500            "attr(not(target_os = \"linux\"), allow(dead_",
2501            "code, reason = \"a reason\"))]\nfn f() {}"
2502        );
2503        assert!(positive_dead_code_conditions(complement).is_empty());
2504
2505        // Nor is a `cfg_attr` that allows something other than this lint, at
2506        // any condition: the rule is about claims made on this lint's behalf.
2507        let unrelated = concat!(
2508            "#[cfg_",
2509            "attr(windows, allow(clippy::needless_return))]\nfn f() {}"
2510        );
2511        assert!(positive_dead_code_conditions(unrelated).is_empty());
2512
2513        // A comment is not code. The rule this enforces is quoted in prose
2514        // above, and reading prose as code is how the first version of this
2515        // scan failed.
2516        let commented = concat!(
2517            "// #[cfg_",
2518            "attr(windows, allow(dead_",
2519            "code))]\nfn f() {}"
2520        );
2521        assert!(positive_dead_code_conditions(commented).is_empty());
2522    }
2523
2524    /// The three-way answer, on synthesised tokens, on every platform.
2525    ///
2526    /// The spawn-based tests above cannot cover the case where two identities
2527    /// carry the *same* start token: on Windows and macOS the resolution makes
2528    /// it unreachable, and on Linux it is a 10 ms race rather than something a
2529    /// test can request. That case is exactly what the tick boundary in
2530    /// `separate_start_tokens` is there to avoid, so it is worth pinning down
2531    /// what the discriminator does with it — and pinning it down on the Windows
2532    /// leg, which cannot exhibit the collision any other way.
2533    #[test]
2534    fn identical_start_tokens_are_the_same_process_and_differing_ones_are_not() {
2535        let recorded = ProcessIdentity {
2536            pid: 4312,
2537            start_token: "platform:token-a".to_string(),
2538        };
2539
2540        // The collision. This is the answer that makes a colliding fixture fail
2541        // for the wrong reason: `Live` is *correct* here, because on the
2542        // evidence available the two are the same process.
2543        assert_eq!(
2544            recorded.classify(Some("platform:token-a".to_string())),
2545            Adoption::Live,
2546            "an identical token is the same process; a fixture that spawns twice inside one \
2547             tick is therefore asserting against a correct answer"
2548        );
2549
2550        // A different token at the same PID is the recycled case, and it must
2551        // carry whoever holds the PID now.
2552        assert_eq!(
2553            recorded.classify(Some("platform:token-b".to_string())),
2554            Adoption::PidRecycled {
2555                current: ProcessIdentity {
2556                    pid: 4312,
2557                    start_token: "platform:token-b".to_string(),
2558                },
2559            }
2560        );
2561
2562        assert_eq!(recorded.classify(None), Adoption::Gone);
2563        assert!(
2564            recorded
2565                .classify(Some("platform:token-a".to_string()))
2566                .is_live()
2567        );
2568        assert!(
2569            !recorded
2570                .classify(Some("platform:token-b".to_string()))
2571                .is_live()
2572        );
2573        assert!(!recorded.classify(None).is_live());
2574    }
2575
2576    /// The Linux token shape is the one that can collide, so assert the
2577    /// collision is a tick-granularity property rather than a boot-id one.
2578    ///
2579    /// Runs everywhere: these are strings, not `/proc` reads.
2580    #[test]
2581    fn two_linux_tokens_collide_only_within_one_tick_of_one_boot() {
2582        let boot = "f81d4fae-7dec-11d0-a765-00a0c91e6bf6";
2583        let at = |ticks: u64| ProcessIdentity {
2584            pid: 4312,
2585            start_token: format!("linux:{boot}:{ticks}"),
2586        };
2587
2588        // Same boot, same tick: indistinguishable. This is the H1 collision,
2589        // reproduced without a Linux kernel.
2590        assert_eq!(
2591            at(884_213).classify(Some(at(884_213).start_token)),
2592            Adoption::Live
2593        );
2594
2595        // One tick apart — 10 ms — is enough to tell them apart, which is why
2596        // `separate_start_tokens` sleeps for longer than one tick.
2597        assert!(
2598            !at(884_213)
2599                .classify(Some(at(884_214).start_token))
2600                .is_live()
2601        );
2602
2603        // The same tick count across a reboot is a different token, which is
2604        // the whole reason the boot id is in there.
2605        let other_boot = ProcessIdentity {
2606            pid: 4312,
2607            start_token: "linux:6ba7b810-9dad-11d1-80b4-00c04fd430c8:884213".to_string(),
2608        };
2609        assert!(!at(884_213).classify(Some(other_boot.start_token)).is_live());
2610    }
2611
2612    /// Shows the previous test is not vacuous.
2613    ///
2614    /// A bare-PID identity — the implementation the task specification calls
2615    /// insufficient — is built here and run through the same comparison. It
2616    /// reports the recycled record as a match, which is the failure the start
2617    /// token exists to prevent. If this test ever stops finding a difference,
2618    /// the start token has stopped discriminating and the test above has become
2619    /// decoration.
2620    #[test]
2621    fn a_bare_pid_would_have_accepted_the_recycled_record() {
2622        let mut victim = long_running().spawn().expect("the first child starts");
2623        let recorded = victim.identity().clone();
2624        separate_start_tokens();
2625        let mut survivor = long_running().spawn().expect("the second child starts");
2626        let survivor_identity = survivor.identity().clone();
2627        assert_distinguishable(&recorded, &survivor_identity);
2628
2629        victim
2630            .stop(Duration::from_secs(10))
2631            .expect("the first child stops");
2632
2633        let recycled = ProcessIdentity {
2634            pid: survivor_identity.pid(),
2635            start_token: recorded.start_token().to_string(),
2636        };
2637
2638        // What a PID-only comparison would conclude.
2639        let bare_pid_says_live = recycled.pid() == survivor_identity.pid();
2640        assert!(
2641            bare_pid_says_live,
2642            "the recycled record must genuinely point at a live process, or the test above is \
2643             not testing recycling at all"
2644        );
2645
2646        // What this module concludes.
2647        assert!(
2648            !recycled.recheck().expect("resolvable").is_live(),
2649            "the start token must reject what a bare PID accepts"
2650        );
2651
2652        survivor
2653            .stop(Duration::from_secs(10))
2654            .expect("the second child stops");
2655    }
2656
2657    #[test]
2658    fn terminating_a_recycled_record_refuses_rather_than_killing_a_stranger() {
2659        let mut victim = long_running().spawn().expect("the first child starts");
2660        let recorded = victim.identity().clone();
2661        separate_start_tokens();
2662        let mut survivor = long_running().spawn().expect("the second child starts");
2663        let survivor_identity = survivor.identity().clone();
2664        // Without this guard a token collision would make the test SIGTERM and
2665        // then SIGKILL the very process it exists to prove is protected, and
2666        // then fail on `survivor.is_running()` — a failure that names the wrong
2667        // cause and has already destroyed its own evidence.
2668        assert_distinguishable(&recorded, &survivor_identity);
2669
2670        victim
2671            .stop(Duration::from_secs(10))
2672            .expect("the first child stops");
2673
2674        let recycled = ProcessIdentity {
2675            pid: survivor_identity.pid(),
2676            start_token: recorded.start_token().to_string(),
2677        };
2678
2679        let outcome = recycled
2680            .terminate(Duration::from_secs(1))
2681            .expect("terminable");
2682        assert_eq!(
2683            outcome,
2684            Termination::RefusedPidRecycled {
2685                current: survivor_identity,
2686            },
2687            "terminating a recycled record must refuse; killing a stranger's process is the \
2688             worst outcome this primitive can produce"
2689        );
2690
2691        assert!(
2692            survivor.is_running().expect("observable"),
2693            "the innocent process must still be running"
2694        );
2695        survivor.stop(Duration::from_secs(10)).expect("cleanup");
2696    }
2697
2698    #[test]
2699    fn terminating_by_identity_stops_a_process_this_agent_did_not_spawn_as_a_child() {
2700        // The post-restart shape: an identity from the journal, no `Child`.
2701        let mut child = long_running().spawn().expect("the child starts");
2702        let identity = child.identity().clone();
2703
2704        assert_eq!(
2705            identity
2706                .terminate(Duration::from_secs(10))
2707                .expect("terminable"),
2708            Termination::Terminated
2709        );
2710
2711        // Reap it so the PID is released; on Unix an unreaped child stays a
2712        // zombie and keeps its PID.
2713        let status = child.wait_for(Duration::from_secs(30)).expect("waitable");
2714        assert!(status.is_some(), "the process must actually have stopped");
2715
2716        assert_eq!(
2717            identity
2718                .terminate(Duration::from_secs(1))
2719                .expect("terminable"),
2720            Termination::AlreadyGone,
2721            "terminating an already-dead identity must be a no-op, not an error: recovery runs \
2722             this on every journal entry"
2723        );
2724    }
2725
2726    #[test]
2727    fn resolving_a_pid_nobody_holds_is_a_distinct_error() {
2728        // PID 0 is the idle/kernel process on Windows and the scheduler on
2729        // Linux; neither is a process this account can adopt, and on macOS
2730        // `proc_pidinfo` reports nothing for it. Using a child's PID after it
2731        // has been reaped is the honest test, so do that instead.
2732        let mut child = quick_exit().spawn().expect("the child starts");
2733        let pid = child.pid();
2734        child.wait().expect("the child exits");
2735
2736        match ProcessIdentity::resolve(pid) {
2737            Err(ProcessError::NoSuchProcess { pid: reported }) => assert_eq!(reported, pid),
2738            // A PID freed moments ago can legitimately be reused by an
2739            // unrelated process on a busy machine. That is not this test's
2740            // failure; it is the very thing the module handles.
2741            Ok(other) => assert_eq!(other.pid(), pid),
2742            Err(other) => panic!("unexpected error: {other}"),
2743        }
2744    }
2745
2746    // -----------------------------------------------------------------------
2747    // Restrictive handoff
2748    // -----------------------------------------------------------------------
2749
2750    /// Stands in for an encoded JIT configuration: long, base64-shaped, and
2751    /// the thing `07-security.md` says must never reach a process listing.
2752    fn jit_payload() -> SecretString {
2753        SecretString::from(
2754            "eyJhZ2VudCI6ICJydW5uZXItbWFuYWdlciIsICJqaXQiOiAidGhpcy1pcy1ub3QtYS1yZWFsLWNvbmZp\
2755             Zy1idXQtaXQtaXMtdGhlLXJpZ2h0LXNoYXBlLWFuZC1sZW5ndGgifQ=="
2756                .to_string(),
2757        )
2758    }
2759
2760    #[test]
2761    fn a_handoff_file_is_unreadable_by_other_local_users() {
2762        let directory = tempfile::tempdir().expect("a temporary directory");
2763        let payload = jit_payload();
2764        let handoff =
2765            RestrictiveHandoff::create(directory.path(), payload).expect("the file is created");
2766
2767        let contents = std::fs::read_to_string(handoff.path()).expect("this account can read it");
2768        assert_eq!(contents, jit_payload().expose_secret());
2769
2770        let permissions = handoff.permissions().expect("inspectable");
2771        assert!(
2772            !permissions.readable_by_other_local_users,
2773            "the JIT handoff is readable by other local accounts: {}",
2774            permissions.description
2775        );
2776    }
2777
2778    #[test]
2779    fn the_permissions_check_catches_a_world_readable_file() {
2780        // Without this, `a_handoff_file_is_unreadable_by_other_local_users`
2781        // could be passing because the check always says "no". Create a file
2782        // the ordinary way — inheriting whatever the directory grants, with no
2783        // restriction applied — and require the check to tell it apart from the
2784        // restrictive one.
2785        let directory = tempfile::tempdir().expect("a temporary directory");
2786
2787        let restrictive = directory.path().join("restrictive");
2788        drop(super::sys::create_restrictive_file(&restrictive).expect("created"));
2789        let restrictive_summary = permissions_summary(&restrictive).expect("inspectable");
2790        assert!(!restrictive_summary.readable_by_other_local_users);
2791
2792        let open = directory.path().join("open");
2793        std::fs::write(&open, b"not a secret").expect("created");
2794        make_world_readable(&open);
2795        let open_summary = permissions_summary(&open).expect("inspectable");
2796
2797        assert!(
2798            open_summary.readable_by_other_local_users,
2799            "a deliberately permissive file was reported as restricted, so the assertion in \
2800             `a_handoff_file_is_unreadable_by_other_local_users` proves nothing. \
2801             restrictive={} permissive={}",
2802            restrictive_summary.description, open_summary.description
2803        );
2804    }
2805
2806    #[cfg(unix)]
2807    fn make_world_readable(path: &Path) {
2808        use std::os::unix::fs::PermissionsExt;
2809        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o644))
2810            .expect("the mode can be widened");
2811    }
2812
2813    #[cfg(windows)]
2814    fn make_world_readable(path: &Path) {
2815        // `icacls` is part of Windows itself and is the shortest way to put a
2816        // real Everyone ACE on a real file. Test-only: nothing in the product
2817        // ever widens a DACL.
2818        //
2819        // Best effort, and the caller's assertion does not depend on it. A file
2820        // created the ordinary way already inherits the parent directory's
2821        // DACL, which is unprotected — and an unprotected DACL is by itself
2822        // something `dacl_grants_broad_access` must report, because this
2823        // program cannot vouch for what a directory it did not create grants.
2824        let _ = std::process::Command::new("icacls")
2825            .arg(path)
2826            .args(["/grant", "*S-1-1-0:(R)"])
2827            .stdout(std::process::Stdio::null())
2828            .stderr(std::process::Stdio::null())
2829            .status();
2830    }
2831
2832    #[test]
2833    fn a_handoff_file_is_deleted_on_the_success_path() {
2834        let directory = tempfile::tempdir().expect("a temporary directory");
2835        let handoff = RestrictiveHandoff::create(directory.path(), jit_payload()).expect("created");
2836        let path = handoff.path().to_path_buf();
2837        assert!(path.exists());
2838
2839        handoff.delete().expect("deletable");
2840        assert!(!path.exists(), "the handoff outlived its explicit deletion");
2841    }
2842
2843    #[test]
2844    fn a_handoff_file_is_deleted_on_the_failure_path() {
2845        let directory = tempfile::tempdir().expect("a temporary directory");
2846
2847        // A launch that fails after the handoff exists. `?` unwinds through
2848        // `RestrictiveHandoff`'s `Drop`, which is the only thing standing
2849        // between a failed start and a JIT configuration left on disk.
2850        fn launch_and_fail(directory: &Path) -> Result<PathBuf, ProcessError> {
2851            let handoff = RestrictiveHandoff::create(directory, jit_payload())
2852                .expect("the handoff is created");
2853            let path = handoff.path().to_path_buf();
2854            SpawnSpec::new("a-program-that-does-not-exist-anywhere")
2855                .arg(handoff.path())
2856                .spawn_with_handoff(&handoff)?;
2857            Ok(path)
2858        }
2859
2860        let before = std::fs::read_dir(directory.path())
2861            .expect("readable")
2862            .count();
2863        assert_eq!(before, 0, "the temporary directory should start empty");
2864
2865        let error = launch_and_fail(directory.path()).expect_err("the program does not exist");
2866        assert!(matches!(error, ProcessError::Spawn { .. }), "{error}");
2867
2868        let remaining: Vec<PathBuf> = std::fs::read_dir(directory.path())
2869            .expect("readable")
2870            .filter_map(Result::ok)
2871            .map(|entry| entry.path())
2872            .collect();
2873        assert!(
2874            remaining.is_empty(),
2875            "a failed start left the JIT handoff on disk: {remaining:?}"
2876        );
2877    }
2878
2879    #[test]
2880    fn a_handoff_file_is_deleted_when_a_panic_unwinds_past_it() {
2881        let directory = tempfile::tempdir().expect("a temporary directory");
2882        let root = directory.path().to_path_buf();
2883
2884        let panicked = std::panic::catch_unwind(move || {
2885            let _handoff = RestrictiveHandoff::create(&root, jit_payload()).expect("created");
2886            panic!("something went wrong after the handoff was written");
2887        });
2888        assert!(panicked.is_err());
2889
2890        let remaining: Vec<PathBuf> = std::fs::read_dir(directory.path())
2891            .expect("readable")
2892            .filter_map(Result::ok)
2893            .map(|entry| entry.path())
2894            .collect();
2895        assert!(
2896            remaining.is_empty(),
2897            "a panic left the JIT handoff on disk: {remaining:?}"
2898        );
2899    }
2900
2901    #[test]
2902    fn spawning_refuses_to_put_the_payload_in_an_argument() {
2903        let directory = tempfile::tempdir().expect("a temporary directory");
2904        let handoff = RestrictiveHandoff::create(directory.path(), jit_payload()).expect("created");
2905
2906        // The mistake `07-security.md`'s threat table names: the configuration
2907        // itself on the command line, where every local account's process
2908        // listing shows it.
2909        let spec = long_running()
2910            .arg("--jit-config")
2911            .arg(jit_payload().expose_secret());
2912
2913        let error = spec
2914            .spawn_with_handoff(&handoff)
2915            .expect_err("the payload must never reach a command line");
2916        match error {
2917            ProcessError::SecretInCommandLine { location, .. } => {
2918                assert!(location.starts_with("argument"), "{location}");
2919            }
2920            other => panic!("expected a refusal, got {other}"),
2921        }
2922    }
2923
2924    #[test]
2925    fn spawning_refuses_to_put_the_payload_in_the_environment() {
2926        let directory = tempfile::tempdir().expect("a temporary directory");
2927        let handoff = RestrictiveHandoff::create(directory.path(), jit_payload()).expect("created");
2928
2929        let spec = long_running().env("ACTIONS_RUNNER_JITCONFIG", jit_payload().expose_secret());
2930
2931        let error = spec
2932            .spawn_with_handoff(&handoff)
2933            .expect_err("the payload must not be inherited through the environment either");
2934        match error {
2935            ProcessError::SecretInCommandLine { location, .. } => {
2936                assert!(location.contains("ACTIONS_RUNNER_JITCONFIG"), "{location}");
2937            }
2938            other => panic!("expected a refusal, got {other}"),
2939        }
2940    }
2941
2942    #[test]
2943    fn runner_handoff_injects_the_supported_secret_input_without_an_argument() {
2944        let directory = tempfile::tempdir().expect("a temporary directory");
2945        let payload = jit_payload();
2946        let payload_length = payload.expose_secret().len();
2947        let handoff = RestrictiveHandoff::create(directory.path(), payload).expect("created");
2948        let spec = runner_jit_input_probe(payload_length);
2949
2950        let rendered: Vec<String> = spec
2951            .arguments()
2952            .iter()
2953            .map(|argument| argument.to_string_lossy().into_owned())
2954            .collect();
2955        assert!(
2956            rendered
2957                .iter()
2958                .all(|argument| !argument.contains(jit_payload().expose_secret())),
2959            "the JIT payload reached the command line: {rendered:?}"
2960        );
2961        assert!(
2962            rendered
2963                .iter()
2964                .all(|argument| argument != "--jit-config-file"),
2965            "the obsolete listener option returned: {rendered:?}"
2966        );
2967
2968        let mut child = spec
2969            .spawn_runner_with_handoff(&handoff)
2970            .expect("the probe starts");
2971        handoff
2972            .delete()
2973            .expect("the handoff is deleted immediately");
2974        let status = child.wait().expect("the probe exits");
2975        assert!(
2976            status.success(),
2977            "the child did not receive the complete {RUNNER_JIT_CONFIG_ENV} input: {status}"
2978        );
2979    }
2980
2981    #[cfg(windows)]
2982    fn runner_jit_input_probe(expected_length: usize) -> SpawnSpec {
2983        SpawnSpec::new("powershell.exe").args([
2984            "-NoProfile".into(),
2985            "-NonInteractive".into(),
2986            "-Command".into(),
2987            format!(
2988                "$value = [Environment]::GetEnvironmentVariable('{RUNNER_JIT_CONFIG_ENV}'); \
2989                 if ($null -eq $value -or $value.Length -ne {expected_length}) {{ exit 41 }}"
2990            ),
2991        ])
2992    }
2993
2994    #[cfg(unix)]
2995    fn runner_jit_input_probe(expected_length: usize) -> SpawnSpec {
2996        SpawnSpec::new("/bin/sh").args([
2997            "-c".to_owned(),
2998            format!("test \"${{#{RUNNER_JIT_CONFIG_ENV}}}\" -eq \"{expected_length}\""),
2999        ])
3000    }
3001
3002    #[test]
3003    fn spawning_allows_the_handoff_path_itself() {
3004        let directory = tempfile::tempdir().expect("a temporary directory");
3005        let handoff = RestrictiveHandoff::create(directory.path(), jit_payload()).expect("created");
3006
3007        let spec = long_running().arg("--jit-config-file").arg(handoff.path());
3008        let mut child = spec
3009            .spawn_with_handoff(&handoff)
3010            .expect("passing the path is the supported handoff");
3011
3012        // What a process listing would show: the path, and nothing that
3013        // contains the payload.
3014        let rendered: Vec<String> = spec
3015            .arguments()
3016            .iter()
3017            .map(|arg| arg.to_string_lossy().into_owned())
3018            .collect();
3019        let payload = jit_payload();
3020        assert!(
3021            rendered
3022                .iter()
3023                .all(|arg| !arg.contains(payload.expose_secret())),
3024            "the payload reached the argument vector: {rendered:?}"
3025        );
3026        assert!(
3027            rendered
3028                .iter()
3029                .any(|arg| arg == &handoff.path().display().to_string()),
3030            "the handoff path should be there: {rendered:?}"
3031        );
3032
3033        child.stop(Duration::from_secs(10)).expect("cleanup");
3034    }
3035
3036    /// What the launchd job below writes into its working directory.
3037    #[cfg(target_os = "macos")]
3038    const PRIORITY_REPORT: &str = "priority-report.txt";
3039
3040    /// The job of a launch agent rendered by `launchd_plist`, run by launchd
3041    /// and by nothing else.
3042    ///
3043    /// It starts one child exactly as the lifecycle starts a runner and writes
3044    /// its own base priority and the child's into its working directory, which
3045    /// the plist points at a directory the test owns.
3046    #[cfg(target_os = "macos")]
3047    #[test]
3048    #[ignore = "run only by launchd, as the job of the launch-agent priority test"]
3049    fn launch_agent_priority_helper() {
3050        let label = std::env::var("XPC_SERVICE_NAME").unwrap_or_default();
3051        assert!(
3052            label.contains("-selftest-"),
3053            "run only by launchd for the launch-agent priority test, not under {label:?}"
3054        );
3055        let mut child = long_running()
3056            .expect_normal_scheduling()
3057            .spawn()
3058            .expect("child starts");
3059        let report = format!(
3060            "agent_priority={}\nchild_priority={}\n",
3061            sys::base_priority(std::process::id()).expect("own priority"),
3062            sys::base_priority(child.pid()).expect("child priority"),
3063        );
3064        child.stop(Duration::from_secs(5)).expect("child stops");
3065        // Renamed into place so the test never reads half a report.
3066        let staged = format!("{PRIORITY_REPORT}.partial");
3067        std::fs::write(&staged, report).expect("report staged");
3068        std::fs::rename(&staged, PRIORITY_REPORT).expect("report written");
3069    }
3070
3071    /// Loads the plist `launchd_plist` renders for a test plan, passed through
3072    /// `edit`, as a launch agent; waits for its job's report and boots it out
3073    /// again. Returns `(agent priority, child priority)`.
3074    #[cfg(target_os = "macos")]
3075    fn priorities_under_launch_agent(tag: &str, edit: impl FnOnce(String) -> String) -> (i32, i32) {
3076        use crate::service::launchd_fixture::LoadedAgent;
3077        use crate::service::{InstallPlan, ServiceDirectories, ServiceIdentity, launchd_plist};
3078        use runner_manager_domain::model::StartMode;
3079
3080        let root = tempfile::tempdir().expect("a temporary directory");
3081        let directories = ServiceDirectories {
3082            config: root.path().join("config"),
3083            state: root.path().join("state"),
3084            runtime: root.path().join("runtime"),
3085            logs: root.path().join("logs"),
3086        };
3087        for directory in directories.all() {
3088            std::fs::create_dir_all(directory).expect("directory created");
3089        }
3090        let binary = crate::service::launchd_fixture::job_binary(root.path());
3091        let identity = ServiceIdentity::fixture(&format!("priority-{tag}-{}", std::process::id()));
3092        let label = identity.launchd_label();
3093        let plan = InstallPlan::unchecked(identity, StartMode::Login, binary, directories.clone())
3094            .with_arguments([
3095                "--ignored",
3096                "--exact",
3097                "process::tests::launch_agent_priority_helper",
3098                "--test-threads=1",
3099            ]);
3100        let plist = root.path().join(format!("{label}.plist"));
3101        std::fs::write(&plist, edit(launchd_plist(&plan))).expect("plist written");
3102        let _loaded = LoadedAgent::bootstrap(&label, &plist);
3103
3104        let report = directories.state.join(PRIORITY_REPORT);
3105        let deadline = std::time::Instant::now() + Duration::from_secs(90);
3106        let text = loop {
3107            if let Ok(text) = std::fs::read_to_string(&report) {
3108                break text;
3109            }
3110            assert!(
3111                std::time::Instant::now() < deadline,
3112                "the {tag} agent's job wrote no report; its stderr: {}",
3113                std::fs::read_to_string(directories.logs.join("runner-manager.launchd.err.log"))
3114                    .unwrap_or_default()
3115            );
3116            std::thread::sleep(Duration::from_millis(250));
3117        };
3118        let value = |name: &str| -> i32 {
3119            text.lines()
3120                .find_map(|line| line.strip_prefix(&format!("{name}=")))
3121                .and_then(|value| value.trim().parse().ok())
3122                .unwrap_or_else(|| panic!("no {name} in the {tag} report: {text}"))
3123        };
3124        (value("agent_priority"), value("child_priority"))
3125    }
3126
3127    /// A runner started by a daemon under the launch agent `launchd_plist`
3128    /// renders runs at normal priority.
3129    ///
3130    /// This is the test 0.4.31 lacked. Its test moved the parent into the
3131    /// background with `setpriority`, which a child can undo, so it passed while
3132    /// every real runner stayed at 4: launchd's `ProcessType` is a different
3133    /// mechanism and a child cannot undo it. Here launchd itself starts the job,
3134    /// from the plist the product installs.
3135    ///
3136    /// The control agent is the same plist with `ProcessType` set back to
3137    /// `Background`. Its child has to be throttled, which proves that launchd
3138    /// applies the job's class to descendants on this host. Without that, the
3139    /// rendered agent's normal-priority child would prove nothing.
3140    #[cfg(target_os = "macos")]
3141    #[test]
3142    fn a_runner_under_the_rendered_launch_agent_runs_at_normal_priority() {
3143        if !crate::service::launchd_fixture::enabled() {
3144            return;
3145        }
3146        let ceiling = sys::BACKGROUND_PRIORITY_CEILING;
3147        let process_type =
3148            |value: &str| format!("<key>ProcessType</key>\n  <string>{value}</string>");
3149        let rendered = process_type(crate::service::LAUNCHD_PROCESS_TYPE);
3150
3151        let (control_agent, control_child) = priorities_under_launch_agent("control", |plist| {
3152            assert!(plist.contains(&rendered), "{plist}");
3153            plist.replace(&rendered, &process_type("Background"))
3154        });
3155        assert!(
3156            control_agent <= ceiling && control_child <= ceiling,
3157            "a Background agent's job ({control_agent}) and its child ({control_child}) were not \
3158             throttled, so this host does not show the condition under test"
3159        );
3160
3161        let (agent, child) = priorities_under_launch_agent("rendered", |plist| plist);
3162        eprintln!(
3163            "Background control: job {control_agent}, runner {control_child}; \
3164             rendered plist: job {agent}, runner {child}"
3165        );
3166        assert!(
3167            child > ceiling,
3168            "a runner started under the rendered launch agent runs at background priority \
3169             {child} (agent {agent}); launchd applies the plist's ProcessType to every runner"
3170        );
3171    }
3172
3173    #[test]
3174    fn the_handoff_path_is_unique_per_handoff() {
3175        let directory = tempfile::tempdir().expect("a temporary directory");
3176        let first = RestrictiveHandoff::create(directory.path(), jit_payload()).expect("created");
3177        let second = RestrictiveHandoff::create(directory.path(), jit_payload()).expect("created");
3178
3179        assert_ne!(
3180            first.path(),
3181            second.path(),
3182            "two concurrent attempts must not share a handoff file"
3183        );
3184    }
3185
3186    #[test]
3187    fn the_payload_has_no_debug_or_display_that_reveals_it() {
3188        // The structural half of the control: even a careless
3189        // `format!("{:?}", …)` in a later task cannot print the configuration.
3190        let payload = jit_payload();
3191        let rendered = format!("{payload:?}");
3192        assert!(
3193            !rendered.contains(payload.expose_secret()),
3194            "SecretString's Debug leaked the payload: {rendered}"
3195        );
3196
3197        let directory = tempfile::tempdir().expect("a temporary directory");
3198        let handoff = RestrictiveHandoff::create(directory.path(), jit_payload()).expect("created");
3199        let rendered = format!("{handoff:?}");
3200        assert!(
3201            !rendered.contains(jit_payload().expose_secret()),
3202            "RestrictiveHandoff's Debug leaked the payload: {rendered}"
3203        );
3204    }
3205}