harn_hostlib/process/handle.rs
1//! Process abstraction trait used by `tools/proc` and
2//! `tools/long_running`.
3//!
4//! Tier 1C of the de-flake epic (#1057). Production code spawns through
5//! the [`ProcessSpawner`] trait — the default implementation in
6//! `process::real` wraps `std::process::Child` and goes through
7//! `harn_vm::process_sandbox`. Tests install a `MockSpawner` (see
8//! `process::mock`) that returns deterministic [`MockProcess`] handles,
9//! so process-tool tests no longer depend on real subprocess scheduling
10//! or wall-clock timing.
11
12use std::collections::BTreeMap;
13use std::io::{self, Read, Write};
14use std::path::PathBuf;
15use std::sync::Arc;
16use std::time::Duration;
17
18pub use harn_vm::op_interrupt::{ProcessCleanupChild, ProcessCleanupReport};
19
20/// Resolved exit information for a finished process. Mirrors the subset of
21/// `std::process::ExitStatus` that the process-tool builtins surface.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub struct ExitStatus {
24 /// Exit code from `exit(2)` / `_exit(2)`. `None` means the process did not
25 /// exit normally (it was terminated by a signal).
26 pub code: Option<i32>,
27 /// Unix signal that terminated the process, when applicable. `None` on
28 /// non-Unix targets or when the process exited normally.
29 pub signal: Option<i32>,
30}
31
32impl ExitStatus {
33 /// Construct a normal exit with the given code.
34 pub fn from_code(code: i32) -> Self {
35 Self {
36 code: Some(code),
37 signal: None,
38 }
39 }
40
41 /// Construct a signal-terminated exit.
42 pub fn from_signal(signal: i32) -> Self {
43 Self {
44 code: None,
45 signal: Some(signal),
46 }
47 }
48}
49
50/// How a spawn should treat the parent's environment. Mirrors the legacy
51/// `EnvMode` from `tools/proc.rs`.
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub enum EnvMode {
54 /// Inherit the parent's environment, then apply `env` overrides.
55 InheritClean,
56 /// Clear the environment, then apply `env`.
57 Replace,
58 /// Inherit the parent's environment and apply `env` (default behaviour).
59 Patch,
60}
61
62/// Explicit secret-bearing environment variable names that the agent's
63/// `run`/`command_run` tool must never leak into a child process (and thus
64/// into the model context, since the child's stdout is returned to the
65/// model as the tool result). These are matched case-insensitively in
66/// addition to the suffix patterns in [`is_sensitive_env_name`].
67const EXPLICIT_SENSITIVE_ENV_NAMES: &[&str] = &[
68 "GITHUB_TOKEN",
69 "GH_TOKEN",
70 "HARN_CLOUD_API_KEY",
71 "BURIN_ADMIN_TOKEN",
72 "AWS_SECRET_ACCESS_KEY",
73 "AWS_SESSION_TOKEN",
74];
75
76/// Provider-namespace prefixes whose entire family of variables is treated
77/// as secret-bearing (e.g. `ANTHROPIC_API_KEY`, `OPENAI_ORG_ID`). Matched
78/// case-insensitively against the start of the variable name.
79const SENSITIVE_ENV_PREFIXES: &[&str] = &[
80 "ANTHROPIC_",
81 "OPENAI_",
82 "OPENROUTER_",
83 "FIREWORKS_",
84 "TOGETHER_",
85 "XAI_",
86 "GROQ_",
87];
88
89/// Returns `true` when an environment variable name looks like it carries a
90/// secret (provider API key, access token, OAuth client secret, etc.) and so
91/// must be stripped from a child process spawned by the agent's `run` tool.
92///
93/// The check is deliberately conservative about credentials but permissive
94/// about ordinary build/toolchain variables: `PATH`, `HOME`, `LANG`,
95/// `CARGO_HOME`, language toolchain vars, etc. are *not* sensitive and stay
96/// in the child environment so builds and tests still work.
97///
98/// Matching is case-insensitive and covers:
99/// - suffix patterns `_API_KEY`, `_TOKEN`, `_SECRET`, `_KEY`, `_PASSWORD`,
100/// `_PASSWD`, `_CREDENTIALS`;
101/// - the provider prefixes in [`SENSITIVE_ENV_PREFIXES`];
102/// - the explicit names in [`EXPLICIT_SENSITIVE_ENV_NAMES`].
103pub fn is_sensitive_env_name(name: &str) -> bool {
104 let upper = name.to_ascii_uppercase();
105 if EXPLICIT_SENSITIVE_ENV_NAMES.contains(&upper.as_str()) {
106 return true;
107 }
108 if SENSITIVE_ENV_PREFIXES
109 .iter()
110 .any(|prefix| upper.starts_with(prefix))
111 {
112 return true;
113 }
114 // Suffix patterns catch the long tail of provider/service credentials
115 // (`*_API_KEY`, `*_TOKEN`, `*_SECRET`, `*_KEY`, `*_PASSWORD`, `*_PASSWD`,
116 // `*_CREDENTIALS`) without enumerating every vendor. `_KEY` is the broadest;
117 // these suffixes still exclude benign names like `PATH`/`HOME`/`LANG` and
118 // `BUILD_KEYBOARD` that don't end in one of them.
119 upper.ends_with("_API_KEY")
120 || upper.ends_with("_TOKEN")
121 || upper.ends_with("_SECRET")
122 || upper.ends_with("_KEY")
123 || upper.ends_with("_PASSWORD")
124 || upper.ends_with("_PASSWD")
125 || upper.ends_with("_CREDENTIALS")
126}
127
128/// Parameters describing a single spawn. The spawner is responsible for any
129/// sandbox setup (Linux seccomp/landlock, macOS sandbox-exec, etc.) and for
130/// configuring the child's process group when requested.
131#[derive(Clone, Debug)]
132pub struct SpawnSpec {
133 /// Builtin name surfaced in error messages (e.g. `"hostlib_tools_run_command"`).
134 pub builtin: &'static str,
135 /// Program to execute. Must be non-empty (validated by the spawner).
136 pub program: String,
137 /// Arguments to pass to the program.
138 pub args: Vec<String>,
139 /// Working directory for the child. `None` inherits the parent's cwd.
140 pub cwd: Option<PathBuf>,
141 /// Environment overrides to apply (interpretation depends on `env_mode`).
142 pub env: BTreeMap<String, String>,
143 /// Variable names to strip from the inherited environment before `env`
144 /// overrides apply. A key present in both `env_remove` and `env` ends up
145 /// set (explicit overrides win). No effect under `EnvMode::Replace`,
146 /// which already starts from an empty environment.
147 pub env_remove: Vec<String>,
148 /// How to treat the parent's environment.
149 pub env_mode: EnvMode,
150 /// Whether stdin will be written to (`true`) or piped to /dev/null (`false`).
151 pub use_stdin: bool,
152 /// Set the child's process group to its own pid (`setpgid(0, 0)`). Used
153 /// for long-running handles so the kill-by-pgid path works.
154 pub configure_process_group: bool,
155}
156
157/// Handle to a running (or finished) process. Used by both the synchronous
158/// `proc::run` path and the long-running waiter thread.
159///
160/// The trait is intentionally small: the legacy code already managed
161/// stdout/stderr drain on dedicated threads, and stdin is written once after
162/// spawn — wrapping those reads/writes via boxed trait objects keeps the
163/// real and mock paths uniform without forcing async into the rest of the
164/// hostlib.
165pub trait ProcessHandle: Send {
166 /// OS process id, when available.
167 fn pid(&self) -> Option<u32>;
168
169 /// OS process group id, when available. Falls back to [`Self::pid`] on
170 /// platforms that don't expose process groups.
171 fn process_group_id(&self) -> Option<u32>;
172
173 /// Returns a killer that can terminate the process even after the
174 /// stdout/stderr/wait halves have been moved into the waiter thread.
175 fn killer(&self) -> Arc<dyn ProcessKiller>;
176
177 /// Take ownership of the stdin pipe, if the spawn requested one.
178 fn take_stdin(&mut self) -> Option<Box<dyn Write + Send>>;
179
180 /// Take ownership of the stdout reader.
181 fn take_stdout(&mut self) -> Option<Box<dyn Read + Send>>;
182
183 /// Take ownership of the stderr reader.
184 fn take_stderr(&mut self) -> Option<Box<dyn Read + Send>>;
185
186 /// Wait for the process to exit, optionally with a timeout, while
187 /// polling `interrupt`. On timeout the spawner kills the child process
188 /// tree (SIGKILL, historical semantics) and reports
189 /// [`WaitOutcome::TimedOut`]. When `interrupt` returns `true` (scope
190 /// cancellation, `deadline` expiry — see `harn_vm::op_interrupt`) the
191 /// spawner gracefully terminates the child's process tree (SIGTERM,
192 /// then SIGKILL after `harn_vm::op_interrupt::SUBPROCESS_TERM_GRACE`)
193 /// and reports [`WaitOutcome::Interrupted`].
194 fn wait_with_timeout(
195 &mut self,
196 timeout: Option<Duration>,
197 interrupt: &dyn Fn() -> bool,
198 ) -> io::Result<WaitOutcome>;
199
200 /// Block until the process exits, no timeout, no interrupt polling.
201 /// Used by the background (`background: true`) waiter thread, whose
202 /// children deliberately outlive scope cancellation and deadlines.
203 fn wait(&mut self) -> io::Result<ExitStatus>;
204}
205
206/// How a [`ProcessHandle::wait_with_timeout`] ended.
207#[derive(Clone, Debug, PartialEq, Eq)]
208pub enum WaitOutcome {
209 /// The process exited on its own.
210 Exited(ExitStatus),
211 /// The timeout elapsed; the spawner killed the child process tree.
212 TimedOut(ProcessCleanupReport),
213 /// The interrupt callback fired; the spawner gracefully terminated the
214 /// child's process tree.
215 Interrupted(ProcessCleanupReport),
216}
217
218/// Kill side of a [`ProcessHandle`]. Cloneable via `Arc` so cancellation
219/// works after the waiter thread has taken ownership of the handle itself.
220pub trait ProcessKiller: Send + Sync {
221 /// Send SIGKILL to the process tree/group when applicable.
222 fn kill(&self) -> ProcessCleanupReport;
223}
224
225/// Spawner abstraction: produces [`ProcessHandle`] instances.
226pub trait ProcessSpawner: Send + Sync {
227 /// Spawn the configured process.
228 fn spawn(&self, spec: SpawnSpec) -> Result<Box<dyn ProcessHandle>, ProcessError>;
229}
230
231/// Errors raised by a spawner. These map onto `HostlibError::Backend` /
232/// `HostlibError::InvalidParameter` at the call site so the script-side
233/// surface stays unchanged.
234#[derive(Clone, Debug, thiserror::Error)]
235pub enum ProcessError {
236 /// `argv` was empty or otherwise malformed.
237 #[error("invalid argv: {0}")]
238 InvalidArgv(String),
239 /// Sandbox setup (e.g. landlock policy assembly) failed.
240 #[error("sandbox setup failed: {0}")]
241 SandboxSetup(String),
242 /// Sandbox rejected the supplied cwd.
243 #[error("sandbox cwd rejected: {0}")]
244 SandboxCwd(String),
245 /// Sandbox rejected the spawn at execve time.
246 #[error("sandbox rejected spawn: {0}")]
247 SandboxSpawn(String),
248 /// Generic spawn failure (typically io::Error from `Command::spawn`).
249 #[error("spawn failed: {0}")]
250 Spawn(String),
251 /// A never-approvable UNIVERSAL catastrophic command (machine/disk/data
252 /// destruction) was rejected by the floor BEFORE spawning. Enforced
253 /// unconditionally at [`spawn_process`] — no `command_policy` required —
254 /// so it is universal across every hostlib process tool, embedders, and
255 /// standalone Harn. See
256 /// [`harn_vm::orchestration::universal_catastrophic_reason`].
257 #[error("{0}")]
258 CatastrophicFloor(String),
259}
260
261use std::cell::RefCell;
262
263thread_local! {
264 static THREAD_SPAWNER: RefCell<Option<Arc<dyn ProcessSpawner>>> = const { RefCell::new(None) };
265}
266
267/// Install a per-thread spawner used by `spawn_process` from this thread.
268/// Returns a guard that restores the previous spawner on drop. Tests use
269/// this to install a [`super::mock::MockSpawner`]; production never calls
270/// it (the default real spawner runs whenever no per-thread spawner is
271/// installed).
272///
273/// Thread-local rather than global so parallel test execution is safe.
274/// Process-tool spawns happen on the test's thread; the long-running
275/// waiter threads operate on the handle that was already returned, so
276/// they don't perform spawner lookups themselves.
277pub fn install_spawner(spawner: Arc<dyn ProcessSpawner>) -> SpawnerGuard {
278 let prev = THREAD_SPAWNER.with(|slot| slot.replace(Some(spawner)));
279 SpawnerGuard { prev: Some(prev) }
280}
281
282/// Guard returned by [`install_spawner`]. Restores the previous spawner on
283/// drop so installs nest correctly across tests.
284pub struct SpawnerGuard {
285 // Outer Option distinguishes "guard already restored" (None) from
286 // "guard owes a restore" (Some(_)); inner Option carries the previous
287 // spawner slot value (which can itself be None when no spawner was set).
288 #[allow(clippy::option_option)]
289 prev: Option<Option<Arc<dyn ProcessSpawner>>>,
290}
291
292impl Drop for SpawnerGuard {
293 fn drop(&mut self) {
294 if let Some(prev) = self.prev.take() {
295 THREAD_SPAWNER.with(|slot| {
296 *slot.borrow_mut() = prev;
297 });
298 }
299 }
300}
301
302/// Return the currently installed spawner for this thread, falling back
303/// to the default real spawner.
304pub fn current_spawner() -> Arc<dyn ProcessSpawner> {
305 THREAD_SPAWNER
306 .with(|slot| slot.borrow().clone())
307 .unwrap_or_else(super::real::default_spawner)
308}
309
310/// Spawn a process via the currently installed spawner.
311///
312/// This is the single chokepoint every hostlib process tool funnels through
313/// (`run_command`, `run_test`, `run_build_command`, `manage_packages`, and the
314/// long-running background path). The UNIVERSAL catastrophic-command floor is
315/// enforced HERE, UNCONDITIONALLY — no `command_policy` on the stack is
316/// required — so a machine/disk/data-destroying command (`rm -rf /`, fork bomb,
317/// `mkfs`, `dd of=<device>`, `chmod -R 000`, `truncate -s 0` of a source file,
318/// redirect-over-source, project-root delete) and the textual git-destructive
319/// family (`git reset --hard`, `git clean -fd`, force-push) is rejected before
320/// the child is ever created, on standalone Harn and under every embedder
321/// alike. Structured git builtins remain the reviewed path for legitimate
322/// force-with-lease workflows. The spec's raw `program`/`args` are classified
323/// BEFORE any sandbox wrapper is applied, so a `sandbox-exec`/`bwrap` prefix
324/// can't bury the real command.
325pub fn spawn_process(spec: SpawnSpec) -> Result<Box<dyn ProcessHandle>, ProcessError> {
326 let workspace_roots: Vec<String> = spec
327 .cwd
328 .as_ref()
329 .map(|cwd| vec![cwd.display().to_string()])
330 .unwrap_or_default();
331 if let Some(reason) = harn_vm::orchestration::universal_catastrophic_reason(
332 &spec.program,
333 &spec.args,
334 &workspace_roots,
335 ) {
336 return Err(ProcessError::CatastrophicFloor(reason));
337 }
338 current_spawner().spawn(spec)
339}
340
341#[cfg(test)]
342mod tests {
343 use super::is_sensitive_env_name;
344
345 #[test]
346 fn denies_secret_bearing_names() {
347 // Suffix patterns.
348 assert!(is_sensitive_env_name("ANTHROPIC_API_KEY"));
349 assert!(is_sensitive_env_name("OPENAI_API_KEY"));
350 assert!(is_sensitive_env_name("SOME_VENDOR_TOKEN"));
351 assert!(is_sensitive_env_name("MY_CLIENT_SECRET"));
352 assert!(is_sensitive_env_name("RANDOM_KEY"));
353 assert!(is_sensitive_env_name("DOCKER_PASSWORD"));
354 assert!(is_sensitive_env_name("TWINE_PASSWORD"));
355 assert!(is_sensitive_env_name("DATABASE_PASSWORD"));
356 assert!(is_sensitive_env_name("MYSQL_PASSWD"));
357 assert!(is_sensitive_env_name("GCP_CREDENTIALS"));
358 // Explicit names.
359 assert!(is_sensitive_env_name("GITHUB_TOKEN"));
360 assert!(is_sensitive_env_name("GH_TOKEN"));
361 assert!(is_sensitive_env_name("HARN_CLOUD_API_KEY"));
362 assert!(is_sensitive_env_name("BURIN_ADMIN_TOKEN"));
363 assert!(is_sensitive_env_name("AWS_SECRET_ACCESS_KEY"));
364 assert!(is_sensitive_env_name("AWS_SESSION_TOKEN"));
365 // Provider prefixes (even without a key/token suffix).
366 assert!(is_sensitive_env_name("OPENROUTER_BASE_URL"));
367 assert!(is_sensitive_env_name("FIREWORKS_ACCOUNT"));
368 assert!(is_sensitive_env_name("TOGETHER_ORG"));
369 assert!(is_sensitive_env_name("XAI_REGION"));
370 assert!(is_sensitive_env_name("GROQ_PROJECT"));
371 }
372
373 #[test]
374 fn allows_benign_build_and_toolchain_names() {
375 assert!(!is_sensitive_env_name("PATH"));
376 assert!(!is_sensitive_env_name("HOME"));
377 assert!(!is_sensitive_env_name("CARGO_HOME"));
378 assert!(!is_sensitive_env_name("LANG"));
379 assert!(!is_sensitive_env_name("LC_ALL"));
380 assert!(!is_sensitive_env_name("TERM"));
381 assert!(!is_sensitive_env_name("USER"));
382 assert!(!is_sensitive_env_name("RUSTUP_HOME"));
383 assert!(!is_sensitive_env_name("CARGO_TARGET_DIR"));
384 assert!(!is_sensitive_env_name("SHELL"));
385 // `_KEY`/`_PASSWORD` suffixes match only at the end, so words that
386 // merely embed those substrings are not swept.
387 assert!(!is_sensitive_env_name("BUILD_KEYBOARD"));
388 assert!(!is_sensitive_env_name("PASSWORD_HASH_ROUNDS"));
389 // Bare names without an underscore-prefixed suffix are not caught,
390 // matching the existing convention (bare `TOKEN` is not swept either).
391 assert!(!is_sensitive_env_name("PASSWORD"));
392 assert!(!is_sensitive_env_name("TOKEN"));
393 }
394
395 #[test]
396 fn matches_case_insensitively() {
397 assert!(is_sensitive_env_name("anthropic_api_key"));
398 assert!(is_sensitive_env_name("github_token"));
399 assert!(!is_sensitive_env_name("path"));
400 }
401}