lean_ctx/shell/containment/mod.rs
1// SPDX-License-Identifier: Apache-2.0
2//! Process containment for agent-tool calls and SDK sessions (Unix).
3//!
4//! Two rules hold for every signal sent from this module:
5//!
6//! 1. A process group is signalled by its number only while that number is
7//! pinned by an unreaped child of the signalling process that belongs to
8//! the group (POSIX: a process id is not reused while a process group with
9//! that id exists, and a group exists until its last member — a zombie
10//! included — is gone).
11//! 2. The signalling process has verified that it is not a member of the
12//! group. If that cannot be shown, nothing is signalled.
13//!
14//! The parts:
15//!
16//! - [`CallGuard`]: one guard process per agent-tool call. It joins the call's
17//! group, leaves a pin behind, moves to a group of its own and waits for its
18//! input to end — the call finished, or the Engine is gone. Then it ends the
19//! call's group, repeatedly, until no live member is left.
20//! - the session starter (`starter`): the process an SDK starts. It runs the
21//! Engine in a new group, stays outside, and ends that group when the Engine
22//! exits, when it is asked to, or when its parent is gone. A guard of the
23//! first kind covers the starter's own death, and the Engine's program is
24//! not executed before that guard is ready (`gate`).
25//! - the spawn helper (`spawn_helper`, `spawner`): the MCP shell
26//! (`server/execute.rs`) leads a session of its own (`setsid`), and a guard
27//! started outside that session cannot join its group. One long-lived
28//! helper per Engine process is the parent of those shells instead; it ends
29//! what it still holds when the Engine is gone without a word.
30//!
31//! Windows is not covered here; nothing in this module is built there. Its
32//! containment is in `shell::process_tree`: a kill-on-close Job Object per
33//! MCP shell call, and for an SDK session the Engine's own kill-on-close job
34//! (`contain_requested_session`), which answers the same request variable
35//! with the same acknowledgement.
36
37use std::time::{Duration, Instant};
38
39/// Whether helpers and guards start as this test harness's ignored helper
40/// test (`tests::HELPER_TEST`) instead of the hidden modes of the `lean-ctx`
41/// binary. Always in the Engine's unit tests; under `test-support` only in the
42/// unit-test harnesses of the server and engine-ext crates, which mount that
43/// test at the same path — never in the `lean-ctx` binary that integration
44/// tests spawn.
45#[cfg(any(test, feature = "test-support"))]
46fn harness_helper() -> bool {
47 #[cfg(test)]
48 {
49 true
50 }
51 #[cfg(not(test))]
52 {
53 static HARNESS: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
54 *HARNESS.get_or_init(|| {
55 std::env::current_exe()
56 .ok()
57 .and_then(|exe| exe.file_name().map(|n| n.to_string_lossy().into_owned()))
58 .is_some_and(|name| {
59 name.starts_with("lean_ctx_server-") || name.starts_with("lean_ctx_ext-")
60 })
61 })
62 }
63}
64
65mod gate;
66mod guard;
67mod spawn_helper;
68mod spawner;
69mod starter;
70#[cfg(any(test, feature = "test-support"))]
71#[cfg_attr(not(test), allow(dead_code, unused_imports, clippy::unwrap_used))]
72pub mod tests;
73mod wire;
74
75pub use gate::{Refusal, start_behind_guard};
76#[cfg(any(test, feature = "test-support"))]
77pub use guard::force_outcome_for_test;
78pub use guard::{CallGuard, GuardOutcome};
79pub(crate) use spawn_helper::lead_new_session;
80pub use spawner::{HelpedChild, HelperSpawn, shutdown_spawn_helper, spawn_shell};
81
82/// Whether this process is the `lean-ctx` binary, which is what can be
83/// started as a guard. Set by [`dispatch_hidden_mode`], the first thing the
84/// binary's entry point calls; true in this crate's own unit tests, whose
85/// binary carries a helper that runs the same guard.
86static GUARD_HOST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(cfg!(test));
87
88/// [`GUARD_HOST`], or the server crate's unit-test harness, whose binary
89/// carries the same helper test (`harness_helper`).
90fn guard_host() -> bool {
91 #[cfg(any(test, feature = "test-support"))]
92 if harness_helper() {
93 return true;
94 }
95 GUARD_HOST.load(std::sync::atomic::Ordering::Relaxed)
96}
97
98/// Starts an Engine child that is not an agent-tool call (bounded captures,
99/// the sandbox runner, the credential reader) behind its guard: the program
100/// is executed only once the guard is ready ([`start_behind_guard`]).
101/// `command` must ask for a process group of its own and is not to be
102/// spawned again.
103///
104/// One addition to that contract: in a process that is not the `lean-ctx`
105/// binary — this crate linked into another executable — there is nothing
106/// that could be started as a guard. Such a child is then started exactly as
107/// it was before guards existed (`None` for the guard). An agent-tool call
108/// does not get this exception; it uses [`start_behind_guard`] itself.
109///
110/// Limit, stated plainly: library embedders and every executable other than
111/// `lean-ctx` get NO call guard at these sites. Their children are ended by
112/// the sites' own timeout and limit paths only; if such a host process dies,
113/// nothing ends what it had started. This is logged once per process at debug
114/// level.
115// pub only for lean-ctx-engine-ext; not public API
116#[doc(hidden)]
117pub fn start_guarded_child(
118 command: &mut std::process::Command,
119) -> Result<(std::process::Child, Option<CallGuard>), Refusal> {
120 if !guard_host() {
121 note_no_guard_host();
122 return command
123 .spawn()
124 .map(|child| (child, None))
125 .map_err(Refusal::NotStarted);
126 }
127 start_behind_guard(command).map(|(child, guard)| (child, Some(guard)))
128}
129
130/// Says once per process, at debug level, that this executable cannot start
131/// guards or a spawn helper.
132fn note_no_guard_host() {
133 static NOTED: std::sync::Once = std::sync::Once::new();
134 NOTED.call_once(|| {
135 tracing::debug!(
136 "process guard unavailable: this executable is not lean-ctx; child processes run without a guard"
137 );
138 });
139}
140
141/// Hidden mode: the guard of one process group. `__group-guard --group <pgid>`.
142pub(crate) const GUARD_MODE: &str = "__group-guard";
143/// Hidden mode: the session starter.
144/// `__session-starter [--ack] [--watch-parent] [--control-fd <n>] -- <program> [args…]`.
145pub(crate) const STARTER_MODE: &str = "__session-starter";
146/// Hidden mode: the spawn helper of one Engine process. `__spawn-helper`, no
147/// arguments; standard input is the Engine's socket.
148pub(crate) const HELPER_MODE: &str = "__spawn-helper";
149/// Set to `1` by an SDK on an `engine …` start: the binary then runs as the
150/// session starter of that same command line.
151pub(crate) const SESSION_ENV: &str = "LEAN_CTX_SESSION_CONTAINMENT";
152/// The starter's acknowledgement: the first line on standard output, before
153/// the Engine is started. An Engine without this mode never writes it.
154pub(crate) const SESSION_ACK: &[u8] = b"{\"leanctx_session_containment\":1}\n";
155
156/// The command line is not one of the hidden modes' forms.
157pub(crate) const EXIT_USAGE: i32 = 64;
158/// The topology could not be verified or the group could not be ended.
159pub(crate) const EXIT_CONTAINMENT: i32 = 70;
160
161/// What a caller is told when a call's process group could not be confirmed
162/// as ended. Fixed text: no process id, no time, nothing of the run (#498).
163pub const END_NOTICE: &str =
164 "[lean-ctx: processes started by this command could not be confirmed as ended]";
165
166/// What a caller is told when an MCP shell command ran without the spawn
167/// helper: nothing would have ended it had lean-ctx died meanwhile. Fixed
168/// text, as above.
169pub const HELPER_NOTICE: &str = "[lean-ctx: this command ran without the process helper; had lean-ctx stopped, nothing would have ended it]";
170
171/// What a caller is told when the spawn helper went away without saying
172/// whether it had started the command. Nothing seen afterwards can prove
173/// that a command did not run, so it is never started a second time. Fixed
174/// text, as above.
175pub const UNCLEAR_NOTICE: &str =
176 "[lean-ctx: this command may or may not have run; it was not repeated]";
177
178/// What a caller is told when a command finished and the word that lets what
179/// it left running go on could not be handed to the spawn helper: a helper
180/// that never read it ends those processes. Fixed text, as above.
181pub const RELEASE_NOTICE: &str = "[lean-ctx: this command finished, but lean-ctx could not confirm that its background processes were left running]";
182
183/// The notice for a guard outcome; `None` when the group is known to be empty.
184pub fn end_notice(outcome: GuardOutcome) -> Option<&'static str> {
185 (outcome != GuardOutcome::Ended).then_some(END_NOTICE)
186}
187
188/// How long a group may take to become empty once it is being ended.
189const END_BUDGET: Duration = Duration::from_secs(5);
190
191/// Runs the hidden mode this invocation asks for, if any, and returns its exit
192/// code. Called before any other start-up work: no configuration, no data
193/// directory, no logging, no telemetry.
194pub fn dispatch_hidden_mode() -> Option<i32> {
195 GUARD_HOST.store(true, std::sync::atomic::Ordering::Relaxed);
196 let mut args = std::env::args_os();
197 let _program = args.next();
198 let first = args.next()?;
199 if first == GUARD_MODE {
200 return Some(guard::main(args));
201 }
202 if first == STARTER_MODE {
203 return Some(starter::main_explicit(args));
204 }
205 if first == HELPER_MODE {
206 return Some(spawn_helper::main(args));
207 }
208 if first == "engine" && std::env::var_os(SESSION_ENV).is_some_and(|value| value == "1") {
209 // `None`: this binary cannot name itself. It then runs as a plain
210 // Engine and writes no acknowledgement, which the SDK reports.
211 return starter::main_requested();
212 }
213 None
214}
215
216/// What became of a group that was to be ended.
217#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub(crate) enum GroupEnd {
219 /// No live member was left, seen twice in a row after the last signal.
220 Empty,
221 /// The signals were sent; the process table could not be read.
222 Unconfirmed,
223 /// Live members remained when the budget was spent.
224 Survivors,
225 /// Nothing was signalled: the caller is a member of the group, or the
226 /// number is not a group this process could own.
227 Refused,
228}
229
230/// Ends the group `group` with SIGKILL, again and again until no live member
231/// is left — a member that forks while the group is signalled can leave a
232/// child the signal did not reach.
233///
234/// Caller contract (rule 1 above): for the whole call, an unreaped child of
235/// this process is a member of `group`. Rule 2 is checked here.
236pub(crate) fn end_pinned_group(group: libc::pid_t, budget: Duration) -> GroupEnd {
237 const ROUNDS_WITHOUT_SIGHT: u32 = 5;
238 // 0/negative/1, this process, or the group this process is in: refused
239 // before any signal (`group_target` checks getpgrp).
240 let Some(group) = u32::try_from(group)
241 .ok()
242 .and_then(|group| crate::ipc::process::group_target(group).ok())
243 else {
244 return GroupEnd::Refused;
245 };
246 let deadline = Instant::now() + budget;
247 let mut rounds = 0_u32;
248 loop {
249 // SAFETY: plain syscall; the group id is pinned by the caller's
250 // unreaped child and this process is not a member. The result is not
251 // used: an empty group answers ESRCH, Darwin answers EPERM for a group
252 // of zombies only.
253 unsafe { libc::killpg(group, libc::SIGKILL) };
254 rounds += 1;
255 let pause = Duration::from_millis(u64::from(rounds.min(10)) * 2);
256 // The next signal is sent only after a live member was seen, or —
257 // without sight of the process table — for a few rounds on the pin
258 // alone. Once the group is seen empty, nothing more is sent.
259 std::thread::sleep(pause);
260 let seen = live_members(group);
261 if seen == Some(0) {
262 std::thread::sleep(pause);
263 if live_members(group) == Some(0) {
264 return GroupEnd::Empty;
265 }
266 } else if seen.is_none() && rounds >= ROUNDS_WITHOUT_SIGHT {
267 return GroupEnd::Unconfirmed;
268 }
269 if Instant::now() >= deadline {
270 return GroupEnd::Survivors;
271 }
272 }
273}
274
275/// How many live (not zombie) processes are members of `group`, read from the
276/// process table. `None` when it cannot be read. Sends no signal.
277pub fn live_members(group: libc::pid_t) -> Option<usize> {
278 let ps = ["/bin/ps", "/usr/bin/ps"]
279 .into_iter()
280 .find(|path| std::path::Path::new(path).is_file())
281 .unwrap_or("ps");
282 let output = std::process::Command::new(ps)
283 .args(["-A", "-o", "pgid=", "-o", "stat="])
284 .stdin(std::process::Stdio::null())
285 .stderr(std::process::Stdio::null())
286 .output()
287 .ok()?;
288 if !output.status.success() {
289 return None;
290 }
291 Some(count_live(&String::from_utf8_lossy(&output.stdout), group))
292}
293
294/// Counts the rows `<pgid> <state>` of `group` whose state is not a zombie's.
295fn count_live(table: &str, group: libc::pid_t) -> usize {
296 table
297 .lines()
298 .filter(|line| {
299 let mut fields = line.split_whitespace();
300 let in_group = fields
301 .next()
302 .and_then(|pgid| pgid.parse::<libc::pid_t>().ok())
303 == Some(group);
304 in_group && !fields.next().is_some_and(|state| state.starts_with('Z'))
305 })
306 .count()
307}
308
309/// Writes all of `bytes` to the descriptor, without any buffering of ours.
310fn write_fd(fd: libc::c_int, mut bytes: &[u8]) -> bool {
311 while !bytes.is_empty() {
312 // SAFETY: the pointer and length describe `bytes`.
313 let written = unsafe { libc::write(fd, bytes.as_ptr().cast(), bytes.len()) };
314 if written > 0 {
315 bytes = &bytes[written as usize..];
316 } else if std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted {
317 return false;
318 }
319 }
320 true
321}
322
323/// The signals a host may send to "everything"; `handler` is `SIG_IGN` or a
324/// handler function.
325fn set_termination_signals(handler: libc::sighandler_t) {
326 for signal in [libc::SIGTERM, libc::SIGINT, libc::SIGHUP] {
327 // SAFETY: installs a disposition; the handler, where it is one, only
328 // stores to an atomic.
329 unsafe { libc::signal(signal, handler) };
330 }
331 // SAFETY: a closed peer must surface as a write error, not end us.
332 unsafe { libc::signal(libc::SIGPIPE, libc::SIG_IGN) };
333}