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