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