cosca 0.10.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! Process-tree containment. Spawn a child as a kill-group root and tear the
//! whole tree down as a unit. Mechanisms, strongest first, all *best-effort in
//! their own way* (the variant names the teardown method, not a quality grade):
//!
//! - [`Containment::CgroupV2`] (Linux): leaf cgroup + `cgroup.kill` — fork-proof.
//! - [`Containment::JobObject`] (Windows): Job + `KILL_ON_JOB_CLOSE`.
//! - [`Containment::ProcessGroup`]/[`Containment::Session`] (Unix): `killpg`.
//! - [`Containment::FdMarker`] (macOS): inherited-fd marker sweep — survives setsid/reparenting.
//! - [`Containment::TreeWalk`] (all): identity-aware descendant kill at teardown.
//! - [`Containment::Delegated`]: a nested member — the outermost root tears it down.
//! - [`Containment::None`]: not contained — lone-process semantics.
//!
//! This is NOT a security sandbox: a determined child escapes every mechanism
//! (broker-spawned helpers, privilege, `setsid` out of a process group). It
//! reliably tears down *cooperative* trees and reports the achieved guarantee.
//!
//! [`Containment`] answers "who tears this tree down". What cooperative signal `terminate()`
//! sends the child is an independent axis — see [`stop`](crate::stop).

use std::fmt;

/// The teardown mechanism actually achieved for a spawned child (queried via
/// `Child::containment()`). Runtime-detected — the same binary meets hosts with
/// and without cgroup v2 / inside and outside an existing job. A request that asks for
/// [`ContainMode::Strongest`] gets the strongest mechanism its host offers or an error; one that
/// asks for [`ContainMode::BestEffort`] may get a weaker one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Containment {
    /// Linux cgroup v2 leaf + `cgroup.kill`. Fork-proof; a confined child can't leave.
    ///
    /// Dropping the handle kills the tree, waits for it to drain, then removes the leaf directory
    /// once, reporting at `warn` a leaf that still refuses removal: something another party put
    /// there since — a process moved in, a child cgroup, or a mount. See
    /// [`kill_on_drop`](crate::Command::kill_on_drop) for how long the wait can run.
    ///
    /// The removal goes by the leaf's name, checked first against the leaf cosca holds. A party
    /// with write access to the delegated parent, which already controls the subtree, can still
    /// swap the name between the check and the removal.
    ///
    /// Each leaf holds an inotify instance for its lifetime, to watch its drain; it counts against
    /// `fs.inotify.max_user_instances` (128 per user by default). A spawn that cannot get one is
    /// not contained in a leaf: it fails under `Strongest`, and degrades, as for any other failed
    /// step, under `BestEffort`. The first
    /// [`wait_tree`](crate::Child::wait_tree) on a handle that finds the tree still running, and
    /// may block, also starts one thread, owned by that handle, which reads the watch for every
    /// wait on it; dropping the handle stops and joins it. A wait that finds the tree drained, or
    /// whose timeout has already passed, starts none.
    ///
    /// A handle that opted out — [`Child::detach`](crate::Child::detach) or
    /// [`kill_on_drop(false)`](crate::Command::kill_on_drop) — never kills, and removes the leaf
    /// only if the tree has already exited; see `kill_on_drop` for when it stays.
    CgroupV2,
    /// Windows Job Object + `KILL_ON_JOB_CLOSE`. Kernel-enforced for direct descendants.
    JobObject,
    /// Unix process group (`setpgid`/`process_group(0)`) + `killpg`. A `setsid` child escapes.
    ProcessGroup,
    /// Unix session (`setsid`) + `killpg`. A nested-`setsid` child escapes.
    Session,
    /// macOS inherited-fd marker: every descendant carries an inherited pipe descriptor, so
    /// membership survives `setsid`, `setpgid`, double-fork reparenting to launchd and `exec`.
    /// Teardown kills the union of three channels: marker holders and the ppid walk each
    /// verify the target's identity before signalling; the process group (when one was
    /// created) is signalled by `killpg(pgid)` with no additional re-verification beyond what
    /// the process-group mechanism already does — the same pgid-reuse caveat documented in
    /// `src/containment/unix.rs` applies to the FIRST group signal exactly as it does today.
    /// `kill_tree` (SIGKILL) re-snapshots the host and repeats until a pass finds nothing or the
    /// new-identity count stops falling (no fixed pass count). `Err` can then also mean the tree
    /// was still forking: a process forked during the last pass may be left running. A LATER pass
    /// re-signals the group too (closing a gap the single-shot `ProcessGroup` mechanism does not
    /// need to close: a process joining the group strictly between passes), but ONLY when that pass's own
    /// marker-holder scan just confirmed a live, `getpgid`-verified member of the group — proof
    /// the pgid had not yet been recycled at that instant — so a later pass never adds a NEW,
    /// unconditional instance of the reuse risk beyond pass 1's existing one (see
    /// `Marker::sweep_pass`, `src/containment/fdmarker.rs`, for the full argument and its
    /// stated limits). `terminate_tree` (SIGTERM, catchable and ignorable) takes exactly one
    /// pass and does not chase forks. In that pass, and in a chosen signal sent to a tree, the signal
    /// goes to the tree's process group, where it has one, and once by its identity to each member the
    /// walk or the marker scan finds; a member of the group that the walk or the scan also finds is sent
    /// it twice. Two sends of one signal pending together merge, so a handler that keeps its process
    /// running runs once or twice.
    ///
    /// Naive-child containment, not a sandbox. A member leaves the set by closing the
    /// descriptor, by being spawned through a path that scrubs inherited descriptors (Python's
    /// `subprocess`, Node's `child_process`, `POSIX_SPAWN_CLOEXEC_DEFAULT`), by changing
    /// credentials (e.g. `exec`ing a setuid binary makes its fd table unqueryable), or by being
    /// otherwise unqueryable — a holder whose identity or fd table the OS refuses to report is
    /// left running rather than signalled blind. The marker descriptor is inherited-only, not
    /// an IPC channel: a member that writes to it blocks (nothing drains it), and after
    /// `detach()` a write raises `SIGPIPE` instead. A spawn elevated THROUGH a `sudo`/`doas`/
    /// `pkexec` wrapper never reports this variant, since that wrapper closes every descriptor
    /// >= 3 before exec; an already-elevated caller's spawn has no such wrapper and can.
    FdMarker,
    /// Identity-aware descendant enumeration at teardown. Misses reparented orphans, and the children
    /// of a parent that exits during the call, the root included. It names the
    /// tree by the root's identity, so a spawn whose root's identity the OS refuses to report
    /// (see [`Child::id`](crate::Child::id)) fails with that error rather than returning one.
    TreeWalk,
    /// A nested member of an ancestor's containment group/job: this child joined the
    /// tree the outermost root owns, so it drives no teardown itself (`can_teardown()`
    /// is `false`) and its `_tree` ops return `Unsupported`. The root tears the tree down.
    ///
    /// It is still independently signallable through its own handle, by its child's stop action
    /// ([`Child::terminate`](crate::Child::terminate)) — owning no tree is not the same as having no
    /// cooperative shutdown.
    Delegated,
    /// No containment — `kill`/drop act on the lone process.
    None,
}

impl Containment {
    /// Whether this handle can drive tree teardown (`kill_tree`/`terminate_tree` act
    /// rather than returning `Unsupported`).
    pub fn can_teardown(&self) -> bool {
        match self {
            Containment::CgroupV2
            | Containment::JobObject
            | Containment::ProcessGroup
            | Containment::Session
            | Containment::FdMarker
            | Containment::TreeWalk => true,
            Containment::None | Containment::Delegated => false,
        }
    }

    /// Whether this handle can observe the whole tree's exit via a real kernel edge
    /// (`wait_tree`/`wait_tree_timeout` act rather than returning `Unsupported`).
    ///
    /// A strict subset of [`can_teardown`](Self::can_teardown): `ProcessGroup`/`Session`
    /// (`killpg`-based) and `TreeWalk` (identity re-enumeration) can tear a tree down but
    /// expose no single kernel object whose state says "every member has exited" — only
    /// `CgroupV2` (`cgroup.events`'s `populated` key), `JobObject` (the job's completion-port
    /// process-count edge) and `FdMarker` (the marker pipe's EOF) do.
    pub fn can_observe_drain(&self) -> bool {
        matches!(
            self,
            Containment::CgroupV2 | Containment::JobObject | Containment::FdMarker
        )
    }
}

/// Whether every member of the contained tree has exited (not reaped — a descriptor/kernel-state
/// change, never a collected zombie; a caller wanting a status still waits on the root).
///
/// `AllMembersExited` and `AllMarkersClosed` are NOT interchangeable evidence, despite both
/// meaning "nothing more to wait for from this channel". [`Containment::CgroupV2`]'s
/// `cgroup.events` `populated` field and [`Containment::JobObject`]'s job membership count are
/// KERNEL-OWNED: a live process cannot leave either set without exiting, so `AllMembersExited`
/// from either is positive, sufficient proof the whole tree is gone — safe to skip a hard sweep
/// on. [`Containment::FdMarker`]'s pipe EOF is ADVISORY, not membership-owning: a live process
/// can leave the marker's holder set early by closing its own copy of the inherited descriptor
/// (deliberately, or as a side effect of something else it does) while remaining alive —
/// undetectable by this edge alone. Treat `AllMarkersClosed` as "no more evidence of survivors
/// from this channel", never as proof no survivor exists; in particular, never use it alone to
/// skip a hard sweep.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TreeDrain {
    /// Every member of the tree has exited, confirmed by a kernel-owned membership count a live
    /// process cannot leave without exiting. Statuses have NOT been collected.
    AllMembersExited,
    /// The macOS fd marker's last held copy of the marker descriptor closed. Advisory, not
    /// authoritative — see this type's own doc.
    AllMarkersClosed,
    /// The tree was not seen drained by the deadline.
    MembersRemain,
}

impl TreeDrain {
    /// Whether this verdict is, on its own with no corroboration, positive kernel-confirmed
    /// proof the whole tree exited — strong enough that a hard sweep afterward would be pure
    /// overhead and can be skipped. Only `AllMembersExited` qualifies; see this type's own doc
    /// for why `AllMarkersClosed` does not. Named for the decision, not the mechanism, and
    /// matched exhaustively (no wildcard) so adding a future variant is a compile error HERE —
    /// the one place this decision is made — rather than a silent default at every call site
    /// that would otherwise need its own copy of this match.
    pub(crate) fn permits_skipping_sweep(&self) -> bool {
        match self {
            TreeDrain::AllMembersExited => true,
            TreeDrain::AllMarkersClosed | TreeDrain::MembersRemain => false,
        }
    }
}

impl fmt::Display for Containment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Containment::CgroupV2 => "cgroup v2",
            Containment::JobObject => "job object",
            Containment::ProcessGroup => "process group",
            Containment::Session => "session",
            Containment::FdMarker => "inherited-fd marker",
            Containment::TreeWalk => "process-tree walk",
            Containment::Delegated => "delegated",
            Containment::None => "none",
        })
    }
}

/// The teardown strategy a caller *requests* via `Command::contain_with`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ContainMode {
    /// The strongest kernel container this host offers, or an error: the mechanism is chosen by
    /// what the host offers, and a failure to set it up fails the spawn with [`Error::Containment`]
    /// naming the mechanism and the cause, before the program runs. It never falls back to a
    /// weaker one; [`ContainMode::BestEffort`] does.
    ///
    /// - **Linux:** a cgroup v2 leaf, when the host offers one: `/proc/self/cgroup` names this
    ///   process's cgroup in the unified hierarchy, and the kernel lets this process use it. The
    ///   setup calls decide that, not a permission check beforehand. A host that offers none (no
    ///   `/proc/self/cgroup`, a cgroup v1 host, or a refusal from the kernel (`EACCES`, `EPERM` or
    ///   `EROFS`) when the own cgroup is opened, the leaf is made, or the leaf's `cgroup.procs` is
    ///   opened, or an own cgroup its mount does not show) gets a process group, with no error; so
    ///   does a host whose new leaf has no `cgroup.kill` (a kernel before Linux 5.14), and the
    ///   leaf is removed. Every other failure fails the spawn: a limit such as `cgroup.max.depth`,
    ///   the inotify watch, and the child's own placement write, whose failure stops the child
    ///   before `exec`. A child whose placement the spawn cannot learn (its status channel cannot
    ///   be read) is not trusted to be in its leaf: the spawn fails as [`Error::MayHaveStarted`],
    ///   with the child torn down and the leaf killed through.
    /// - **macOS:** the inherited-fd marker, always offered. A failure to install it fails the
    ///   spawn. An explicit [`Session`](ContainMode::Session) or [`TreeWalk`](ContainMode::TreeWalk)
    ///   installs the marker too, and degrades when it fails.
    /// - **Windows:** a Job Object, always offered. A failure to create the Job or assign the child
    ///   to it fails the spawn: the child, created suspended, is terminated and reaped before it
    ///   runs, and the error names the Job Object, with the OS error as its source. The spawn
    ///   answers not started only when it has proved that from the process: its initial thread is
    ///   still suspended, it has no other thread, and the loader has not initialised it. Otherwise
    ///   it answers [`Error::MayHaveStarted`].
    ///
    /// [`Error::Containment`]: crate::error::Error::Containment
    /// [`Error::MayHaveStarted`]: crate::error::Error::MayHaveStarted
    Strongest,
    /// The strongest kernel container that sets up, else the next one down, rather than an error.
    /// A cgroup v2 leaf on Linux, a Job Object on Windows and the inherited-fd marker on macOS,
    /// each falling back (to a process group on Linux and macOS, to [`ContainMode::TreeWalk`] on
    /// Windows) rather than to no containment. A fallback is logged at `warn`, and
    /// [`Child::containment`](crate::Child::containment) reports what the spawn got.
    ///
    /// - **Linux:** a failed step of setting up the leaf (no cgroup offered, no `cgroup.kill`, the
    ///   leaf's directory, `cgroup.procs` or inotify watch), or a child whose placement write
    ///   failed, degrades to the process group the spawn set up. A child that ends before it
    ///   reports its placement never ran its program, so that spawn fails as one that did not
    ///   start, as under `Strongest`, instead of handing back a child that never ran. A child
    ///   whose placement the spawn cannot learn does not degrade either: it fails as under
    ///   `Strongest`.
    /// - **macOS:** a failed install of the fd marker degrades to the process group.
    /// - **Windows:** a child that cannot be assigned to its Job Object is resumed anyway and
    ///   contained by [`ContainMode::TreeWalk`].
    ///
    /// [`Error::Containment`]: crate::error::Error::Containment
    BestEffort,
    /// Identity-aware process-tree walk at teardown — selectable directly (e.g.
    /// for a child known to `setsid` out of a process group). The spawn fails if the OS refuses to
    /// report the root's identity.
    TreeWalk,
    /// Unix session containment via `setsid`: the child becomes a session leader
    /// and process-group leader, detached from any controlling terminal.
    /// Teardown sends `SIGKILL`/`SIGTERM` to the process group (which equals the
    /// session's initial process group). Useful for daemon-like children that
    /// must not inherit the parent's controlling terminal.
    ///
    /// **Mutual exclusivity:** `setsid` makes the child a session *and*
    /// process-group leader simultaneously; `setpgid`/`process_group(0)` on a
    /// session leader fails with `EPERM`. Therefore `Session` applies `setsid`
    /// *instead of* `process_group(0)` — never both.
    ///
    /// **Self-`setsid` escape:** a child that calls `setsid` itself (or
    /// `setpgid`) can leave the session. This is documented and applies equally
    /// to `ProcessGroup` containment. `Session` provides TTY detach and
    /// session grouping; it is not a security sandbox.
    ///
    /// On macOS this request installs the fd marker as well, and still degrades to the session
    /// when that fails. On Windows this request is treated as `Strongest`, failures included.
    Session,
}

impl ContainMode {
    /// Whether the mechanism this mode picks is the only one it accepts: a failure to set it up
    /// fails the spawn, where every other mode degrades to the mechanism below it. `Session` has no
    /// session on Windows, and is a Job Object there as `Strongest` is.
    pub(crate) fn is_strict(self) -> bool {
        match self {
            ContainMode::Strongest => true,
            ContainMode::Session => cfg!(windows),
            ContainMode::BestEffort | ContainMode::TreeWalk => false,
        }
    }
}

/// Whether a kill-group root marks its descendants as already-contained.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Nesting {
    /// Mark descendants (default): nested contained spawns join THIS group.
    #[default]
    Mark,
    /// Leave descendants unmarked: a contained child's own contained spawns
    /// create their own groups (which nest inside this one on Windows).
    Opaque,
}

/// The resolved containment request carried on a `Command` (crate-internal).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ContainRequest {
    /// `None` = not contained.
    pub mode: Option<ContainMode>,
    pub nesting: Nesting,
}

impl Default for ContainRequest {
    fn default() -> ContainRequest {
        ContainRequest {
            mode: None,
            nesting: Nesting::Mark,
        }
    }
}

/// The reserved, inherited env marker for kill-group root detection. Windows
/// jobs nest but Unix process groups do not, so only the OUTERMOST `.contain()`
/// creates a group; descendants inherit this marker and join it. **Reserved and
/// load-bearing: nothing outside this crate may set it.**
pub(crate) const NESTED_ENV: &str = "__COSCA_GROUP_ROOT";

#[cfg(unix)]
#[path = "containment/unix.rs"]
pub(crate) mod unix;

#[path = "containment/cgroup.rs"]
pub(crate) mod cgroup;

#[cfg(windows)]
#[path = "containment/windows.rs"]
pub(crate) mod windows;

/// The public Job Object primitive — see [`job::Job`].
#[cfg(windows)]
#[path = "containment/job.rs"]
pub(crate) mod job;
#[cfg(windows)]
pub use job::Job;

#[path = "containment/enumerate.rs"]
pub(crate) mod enumerate;

#[cfg(target_os = "macos")]
#[path = "containment/fdmarker.rs"]
pub(crate) mod fdmarker;

#[cfg(any(target_os = "macos", test))]
#[path = "containment/sweep_passes.rs"]
pub(crate) mod sweep_passes;

#[path = "containment/treewalk.rs"]
pub(crate) mod treewalk;

#[path = "containment/dispatch.rs"]
pub(crate) mod dispatch;

#[path = "containment/mechanism.rs"]
pub(crate) mod mechanism;

#[path = "containment/drain_edge.rs"]
pub(crate) mod drain_edge;

#[cfg(test)]
#[path = "containment/fake.rs"]
pub(crate) mod fake;

#[path = "containment/tree.rs"]
mod tree;

#[path = "containment/tree_kill.rs"]
pub(crate) mod tree_kill;

#[path = "containment/root.rs"]
mod root;

#[path = "containment/skip.rs"]
mod skip;
#[cfg(unix)]
pub(crate) use dispatch::marks_child_environment;
#[cfg(target_os = "linux")]
pub(crate) use dispatch::ChildHandle;
#[cfg(unix)]
pub(crate) use dispatch::DropView;
#[allow(
    unused_imports,
    reason = "not every re-exported name here is consumed on every target/feature combination; re-exporting uniformly beats per-item cfg_attr gating"
)]
pub(crate) use dispatch::{attach, prepare, Attachment, Prepared, TreeKilled};
#[allow(
    unused_imports,
    reason = "a mechanism is named outside containment/ only by tests and the macOS late spawn"
)]
pub(crate) use mechanism::{Contains, Mechanism};
#[cfg(all(test, unix))]
pub(crate) use root::Refusal;
pub(crate) use root::Root;
#[cfg(unix)]
pub(crate) use root::Seen;
#[cfg(unix)]
pub(crate) use root::{check_number, NotItsGroup};
pub(crate) use skip::{earlier_of, SendOutcome, Skip, TerminateOutcome, TreeStop};
#[cfg(unix)]
pub(crate) use skip::{SkipCall, Why};
pub(crate) use tree::Tree;
#[allow(
    unused_imports,
    reason = "a wait is named outside containment/ only by the callers that wait; the rest send alone"
)]
pub(crate) use tree_kill::{KillWait, TreeKill};

#[cfg(target_os = "macos")]
#[path = "containment/marker_eof.rs"]
pub(crate) mod marker_eof;

#[cfg(test)]
#[path = "containment_tests.rs"]
mod containment_tests;

#[cfg(all(test, target_os = "linux"))]
#[path = "containment/strongest_tests.rs"]
mod strongest_tests;

#[cfg(all(test, windows))]
#[path = "containment/strongest_windows_tests.rs"]
mod strongest_windows_tests;