Use native POSIX spawning for command hooks (#47610)

## Why

Unix command hooks use a `pre_exec` callback to detach from the controlling terminal, forcing the launcher to fork. Native spawn attributes can create the detached session without that callback.

## What changed

- Route Unix hooks through `codex_utils_pty::Command` with `ProcessMode::NewSession`.
- Extend the native `posix_spawn` launcher to detached Linux sessions, retaining compatibility fallbacks for unsupported libc features and executable handling.
- Preserve the session environment snapshot, hook overrides, and restricted-variable filtering.

## Testing

Add regression coverage for launches without parent forks, terminal detachment, environment and argument handling, Linux `PATH` lookup, and executable compatibility. Cover process-group cleanup on cancellation and timeout, including descendants holding output pipes open, and preservation of background descendants after completed hooks.

GitOrigin-RevId: dbe2cf12d84aa79868cfb55ace40c7d5b5282703
This commit is contained in:
Charlie Marsh
2026-09-23 18:24:05 +00:00
committed by copyberry
parent 50fc133d05
commit 7aa6519909
11 changed files with 620 additions and 160 deletions
+46 -45
View File
@@ -1,10 +1,10 @@
use std::collections::HashMap;
#[cfg(not(windows))]
use std::ffi::OsStr;
use std::ffi::OsString;
use std::future::Future;
use std::io::ErrorKind;
use std::path::Path;
#[cfg(not(unix))]
use std::process::Stdio;
use std::sync::Arc;
use std::sync::Mutex;
@@ -13,11 +13,14 @@ use std::time::Duration;
use std::time::Instant;
use async_channel::Sender;
use codex_protocol::shell_environment::scrub_non_inheritable_env_vars;
use codex_protocol::shell_environment::is_non_inheritable_env_var;
#[cfg(unix)]
use codex_utils_pty::Command;
#[cfg(windows)]
use codex_utils_pty::JobObject;
use futures::future::try_join;
use tokio::io::AsyncWriteExt;
#[cfg(not(unix))]
use tokio::process::Command;
use tokio::sync::Semaphore;
use tokio::task::JoinSet;
@@ -206,7 +209,7 @@ impl CommandHookRuntime {
pub(crate) async fn run_command(
runtime: &CommandHookRuntime,
handler: &ConfiguredHandler,
command: &str,
command_line: &str,
env: &HashMap<String, String>,
input_json: &str,
cwd: &Path,
@@ -214,21 +217,8 @@ pub(crate) async fn run_command(
let started_at = chrono::Utc::now().timestamp();
let started = Instant::now();
let mut command = build_command(&runtime.shell, command, &runtime.environment, env);
command
.current_dir(cwd)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
#[cfg(unix)]
// Keep process-group cleanup without inheriting the controlling terminal, where
// shell startup can otherwise stop the hook on background terminal I/O.
// SAFETY: detach_from_tty only performs async-signal-safe process setup.
unsafe {
command.pre_exec(codex_utils_pty::process_group::detach_from_tty);
}
let mut command = build_command(&runtime.shell, command_line, &runtime.environment, env);
command.current_dir(cwd);
#[cfg(windows)]
let mut process_tree_job = JobObject::create().ok();
@@ -401,45 +391,60 @@ fn build_command(
env: &HashMap<String, String>,
) -> Command {
let mut command = if shell.program.is_empty() {
default_shell_command(environment)
Command::new(default_shell_program(environment))
} else {
Command::new(&shell.program)
};
if shell.program.is_empty() {
#[cfg(windows)]
command.raw_arg(format!(r#""{command_line}""#));
command.arg("/C");
#[cfg(not(windows))]
command.arg(command_line);
command.arg("-lc");
} else {
command.args(&shell.args);
#[cfg(windows)]
if shell.args.iter().any(|arg| arg.eq_ignore_ascii_case("/c")) {
command.raw_arg(format!(r#""{command_line}""#));
} else {
command.arg(command_line);
}
#[cfg(not(windows))]
}
#[cfg(windows)]
if shell.program.is_empty() || shell.args.iter().any(|arg| arg.eq_ignore_ascii_case("/c")) {
command.raw_arg(format!(r#""{command_line}""#));
} else {
command.arg(command_line);
}
// Replay the session snapshot instead of inheriting the live process environment.
command.env_clear();
command.envs(environment.iter().cloned());
command.envs(env);
scrub_non_inheritable_env_vars(command.as_std_mut());
#[cfg(not(windows))]
command.arg(command_line);
#[cfg(unix)]
command.process_mode(codex_utils_pty::ProcessMode::NewSession);
#[cfg(not(unix))]
command
.env_clear()
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
// Both launchers start with an empty environment. Replay the session snapshot
// before hook overrides, filtering restricted names from both sources.
command.envs(
environment
.iter()
.map(|(key, value)| (key.as_os_str(), value.as_os_str()))
.chain(
env.iter()
.map(|(key, value)| (OsStr::new(key), OsStr::new(value))),
)
.filter(|(key, _)| !key.to_str().is_some_and(is_non_inheritable_env_var)),
);
command
}
fn default_shell_command(environment: &[(OsString, OsString)]) -> Command {
fn default_shell_program(environment: &[(OsString, OsString)]) -> OsString {
#[cfg(windows)]
let (environment_variable, fallback_program, argument) = ("COMSPEC", "cmd.exe", "/C");
let (environment_variable, fallback_program) = ("COMSPEC", "cmd.exe");
#[cfg(not(windows))]
let (environment_variable, fallback_program, argument) = ("SHELL", "/bin/sh", "-lc");
let (environment_variable, fallback_program) = ("SHELL", "/bin/sh");
let program = environment
environment
.iter()
.find(|(key, _)| {
#[cfg(windows)]
@@ -454,11 +459,7 @@ fn default_shell_command(environment: &[(OsString, OsString)]) -> Command {
}
})
.map(|(_, value)| value.clone())
.unwrap_or_else(|| OsString::from(fallback_program));
let mut command = Command::new(program);
command.arg(argument);
command
.unwrap_or_else(|| OsString::from(fallback_program))
}
#[cfg(test)]
+316 -59
View File
@@ -1,5 +1,4 @@
use std::collections::HashMap;
use std::ffi::OsStr;
use std::ffi::OsString;
#[cfg(windows)]
use std::fs;
@@ -33,6 +32,7 @@ use super::CommandShell;
use super::ConfiguredHandler;
use super::MAX_CONCURRENT_ASYNC_HOOKS;
use super::build_command;
use super::default_shell_program;
use super::run_command;
use crate::events::user_prompt_submit::UserPromptSubmitRequest;
@@ -139,8 +139,60 @@ async fn hook_shell_startup_does_not_stop_on_controlling_terminal() {
result_sender,
);
let result = run_command(&runtime, &handler, command, &env, "{}", temp.path()).await;
#[cfg(any(target_os = "linux", target_os = "macos"))]
static FORKS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
use std::sync::atomic::Ordering;
extern "C" fn record_parent_fork() {
FORKS.fetch_add(1, Ordering::SeqCst);
}
// Registration cannot be undone, so keep it in this isolated TTY child.
// SAFETY: The callback only updates a lock-free atomic in the parent.
assert_eq!(
unsafe {
libc::pthread_atfork(
/*prepare*/ None,
Some(record_parent_fork),
/*child*/ None,
)
},
0
);
let mut baseline = tokio::process::Command::new("/bin/sh");
baseline.args(["-c", "exit 0"]);
// SAFETY: A no-op callback forces fork for the positive control.
unsafe {
baseline.pre_exec(|| Ok(()));
}
assert!(baseline.status().await.expect("fork control").success());
assert_eq!(FORKS.load(Ordering::SeqCst), 1);
}
let result = run_command(&runtime, &handler, command, &env, "{}", temp.path()).await;
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
#[cfg(all(target_os = "linux", target_env = "gnu"))]
let native_chdir_supported = {
// SAFETY: Only inspect symbol availability, matching the launcher.
!unsafe {
libc::dlsym(
libc::RTLD_DEFAULT,
c"posix_spawn_file_actions_addchdir_np".as_ptr(),
)
}
.is_null()
};
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
let native_chdir_supported = true;
if native_chdir_supported {
assert_eq!(
FORKS.load(std::sync::atomic::Ordering::SeqCst),
1,
"hook must avoid forking its parent"
);
}
}
assert_eq!(result.exit_code, Some(0), "stderr: {}", result.stderr);
assert_eq!(result.stdout, "hook-ran");
assert_eq!(result.error, None);
@@ -330,8 +382,8 @@ async fn command_hook_does_not_expose_configured_noise_auth_token() {
assert_eq!(result.error, None);
}
#[test]
fn build_command_replays_snapshot_before_hook_overrides_and_scrubbing() {
#[tokio::test]
async fn build_command_replays_snapshot_before_hook_overrides_and_scrubbing() {
#[cfg(unix)]
let non_unicode_value = OsString::from_vec(vec![b'v', 0xff]);
let environment = vec![
@@ -348,10 +400,7 @@ fn build_command_replays_snapshot_before_hook_overrides_and_scrubbing() {
OsString::from("captured-noise-token"),
),
#[cfg(unix)]
(
OsString::from("CODEX_HOOK_NON_UNICODE"),
non_unicode_value.clone(),
),
(OsString::from("CODEX_HOOK_NON_UNICODE"), non_unicode_value),
];
let env = HashMap::from([
("CODEX_HOOK_OVERRIDE".to_string(), "configured".to_string()),
@@ -361,36 +410,45 @@ fn build_command_replays_snapshot_before_hook_overrides_and_scrubbing() {
"configured-noise-token".to_string(),
),
]);
#[cfg(not(windows))]
let (program, args, command_line) = (
"/bin/sh",
vec!["-c".to_string()],
"printf '%s\\n' \"$CODEX_HOOK_SNAPSHOT\" \"$CODEX_HOOK_OVERRIDE\" \"$CODEX_HOOK_SAFE_ENV\" \"${CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN-absent}\" \"$CODEX_HOOK_NON_UNICODE\"",
);
#[cfg(windows)]
let (program, args, command_line) = (
"cmd.exe",
vec!["/D".to_string(), "/C".to_string()],
"echo %CODEX_HOOK_SNAPSHOT%&echo %CODEX_HOOK_OVERRIDE%&echo %CODEX_HOOK_SAFE_ENV%&if defined CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN (echo leaked) else (echo absent)",
);
let command = build_command(
&CommandShell {
program: "configured-shell".to_string(),
args: vec!["-c".to_string()],
program: program.to_string(),
args,
},
"echo hook-ran",
command_line,
&environment,
&env,
);
assert_eq!(
configured_environment_value(&command, "CODEX_HOOK_SNAPSHOT"),
Some(Some(OsString::from("captured")))
);
assert_eq!(
configured_environment_value(&command, "CODEX_HOOK_OVERRIDE"),
Some(Some(OsString::from("configured")))
);
assert_eq!(
configured_environment_value(&command, "CODEX_HOOK_SAFE_ENV"),
Some(Some(OsString::from("visible")))
);
assert_eq!(
configured_environment_value(&command, CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR),
None
);
#[cfg(not(unix))]
let mut command = command;
let output = command
.spawn()
.expect("spawn hook")
.wait_with_output()
.await
.expect("hook output");
assert!(output.status.success(), "{output:?}");
#[cfg(unix)]
assert_eq!(
configured_environment_value(&command, "CODEX_HOOK_NON_UNICODE"),
Some(Some(non_unicode_value))
output.stdout,
b"captured\nconfigured\nvisible\nabsent\nv\xff\n"
);
#[cfg(windows)]
assert_eq!(
output.stdout,
b"captured\r\nconfigured\r\nvisible\r\nabsent\r\n"
);
}
@@ -400,25 +458,9 @@ fn fallback_shell_uses_snapshot() {
let (name, program) = ("comspec", r"C:\captured\cmd.exe");
#[cfg(not(windows))]
let (name, program) = ("SHELL", "/captured/shell");
let command = build_command(
&CommandShell {
program: String::new(),
args: Vec::new(),
},
"echo hook-ran",
&[(OsString::from(name), OsString::from(program))],
&HashMap::new(),
);
assert_eq!(command.as_std().get_program(), OsStr::new(program));
#[cfg(not(windows))]
assert_eq!(
command
.as_std()
.get_args()
.map(OsStr::to_os_string)
.collect::<Vec<_>>(),
vec![OsString::from("-lc"), OsString::from("echo hook-ran")]
default_shell_program(&[(OsString::from(name), OsString::from(program))]),
OsString::from(program),
);
}
@@ -445,17 +487,6 @@ fn runtime_with_environment(
(runtime, result_receiver)
}
fn configured_environment_value(
command: &tokio::process::Command,
name: &str,
) -> Option<Option<OsString>> {
command
.as_std()
.get_envs()
.find(|(key, _)| *key == OsStr::new(name))
.map(|(_, value)| value.map(OsStr::to_os_string))
}
fn write_handler(temp: &TempDir, source: &str) -> ConfiguredHandler {
let script_path = temp.path().join("async_hook.py");
std::fs::write(&script_path, source).expect("write async test hook");
@@ -693,3 +724,229 @@ print(json.dumps({{
"shutdown must not deliver a late async result"
);
}
#[cfg(unix)]
async fn process_is_running(pid: &str) -> bool {
let output = tokio::process::Command::new("ps")
.args(["-p", pid, "-o", "stat="])
.output()
.await
.expect("inspect hook process state");
assert!(output.stderr.is_empty(), "{output:?}");
assert!(output.status.success() || output.status.code() == Some(1));
String::from_utf8_lossy(&output.stdout)
.split_whitespace()
.any(|state| !state.starts_with('Z'))
}
#[cfg(unix)]
#[tokio::test]
async fn cancelled_and_timed_out_hooks_kill_their_process_group() {
enum Termination {
Cancellation,
Timeout,
}
for termination in [Termination::Cancellation, Termination::Timeout] {
let temp = tempdir().expect("create temp dir");
let mut handler = write_handler(
&temp,
r#"import os
from pathlib import Path
import subprocess
import time
child = subprocess.Popen(['sleep', '60'])
Path('hook-pids.tmp').write_text(f'{os.getpid()} {child.pid}')
Path('hook-pids.tmp').rename('hook-pids')
time.sleep(60)
"#,
);
handler.timeout_sec = 2;
let ConfiguredHandlerKind::Command { command, env, .. } = &handler.kind else {
panic!("expected command hook");
};
let (mut runtime, _result_receiver) = runtime();
runtime.shell.program = "/bin/sh".into();
runtime.shell.args = vec!["-c".into()];
let mut run = Box::pin(run_command(
&runtime,
&handler,
command,
env,
"{}",
temp.path(),
));
let pids = timeout(Duration::from_secs(10), async {
loop {
if let Ok(pids) = std::fs::read_to_string(temp.path().join("hook-pids")) {
break pids;
}
tokio::select! {
result = &mut run => panic!("hook exited before cancellation: {result:?}"),
_ = sleep(Duration::from_millis(10)) => {}
}
}
})
.await
.expect("hook and descendant must start");
match termination {
Termination::Cancellation => drop(run),
Termination::Timeout => {
let result = timeout(Duration::from_secs(10), run)
.await
.expect("hook timeout completes");
assert_eq!(result.error, Some("hook timed out after 2s".to_string()));
}
}
timeout(Duration::from_secs(10), async {
loop {
let mut all_stopped = true;
for pid in pids.split_whitespace() {
all_stopped &= !process_is_running(pid).await;
}
if all_stopped {
break;
}
sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("cancellation and timeout must stop both hook and descendant");
}
}
#[cfg(unix)]
#[tokio::test]
async fn completed_hook_preserves_background_descendant() {
for exit_code in [0, 23] {
let temp = tempdir().expect("create temp dir");
let handler = write_handler(
&temp,
&format!(
r#"import subprocess
subprocess.Popen(
['sh', '-c', 'i=0; while [ ! -f release-descendant ] && [ "$i" -lt 500 ]; do sleep 0.01; i=$((i + 1)); done; printf survived > descendant-result.tmp; mv descendant-result.tmp descendant-result'],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
raise SystemExit({exit_code})
"#
),
);
let ConfiguredHandlerKind::Command { command, env, .. } = &handler.kind else {
panic!("expected command hook");
};
let (mut runtime, _result_receiver) = runtime();
runtime.shell.program = "/bin/sh".into();
runtime.shell.args = vec!["-c".into()];
let result = run_command(&runtime, &handler, command, env, "{}", temp.path()).await;
// Release even on a failed assertion so a failed test does not leak a waiter.
std::fs::write(temp.path().join("release-descendant"), "").expect("release descendant");
assert_eq!((result.exit_code, result.error), (Some(exit_code), None));
let result_path = temp.path().join("descendant-result");
timeout(Duration::from_secs(10), async {
while !result_path.exists() {
sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("completed hook must leave its descendant running");
assert_eq!(std::fs::read_to_string(result_path).unwrap(), "survived");
}
}
#[cfg(unix)]
#[tokio::test]
async fn exited_hook_leader_with_open_descendant_output_still_times_out() {
let temp = tempdir().expect("create temp dir");
let mut handler = write_handler(
&temp,
r#"from pathlib import Path
import subprocess
child = subprocess.Popen(['sleep', '60'])
Path('descendant-pid').write_text(str(child.pid))
"#,
);
handler.timeout_sec = 2;
let ConfiguredHandlerKind::Command { command, env, .. } = &handler.kind else {
panic!("expected command hook");
};
let (mut runtime, _result_receiver) = runtime();
runtime.shell.program = "/bin/sh".into();
runtime.shell.args = vec!["-c".into()];
let result = run_command(&runtime, &handler, command, env, "{}", temp.path()).await;
assert_eq!(result.error, Some("hook timed out after 2s".to_string()));
let pid = std::fs::read_to_string(temp.path().join("descendant-pid"))
.expect("descendant started before its parent exited");
timeout(Duration::from_secs(10), async {
while process_is_running(pid.trim()).await {
sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("hook timeout must stop the descendant after the leader exits");
}
#[cfg(unix)]
#[tokio::test]
async fn hook_rejects_nul_arguments_before_execution() {
for nul_in_shell_args in [false, true] {
let root = tempdir().expect("tempdir");
let (mut runtime, _receiver) = runtime();
runtime.shell = CommandShell {
program: "/usr/bin/touch".to_string(),
args: if nul_in_shell_args {
vec!["bad\0arg".to_string()]
} else {
Vec::new()
},
};
let command = if nul_in_shell_args { "ran" } else { "bad\0arg" };
let handler = write_handler(&root, "");
let result = run_command(
&runtime,
&handler,
command,
&HashMap::new(),
"",
root.path(),
)
.await;
assert!(result.error.is_some(), "invalid hook ran: {result:?}");
assert_eq!(result.exit_code, None);
assert!(!root.path().join("ran").exists());
assert!(!root.path().join("<string-with-nul>").exists());
}
}
#[cfg(unix)]
#[tokio::test]
async fn hook_rejects_nul_in_configured_and_default_shell_program() {
for configured in [false, true] {
let root = tempdir().expect("tempdir");
let (mut runtime, _receiver) = runtime_with_environment(Arc::new(vec![(
OsString::from("SHELL"),
OsString::from("/bin/sh\0"),
)]));
if configured {
runtime.shell.program = "/bin/sh\0".to_string();
}
let handler = write_handler(&root, "");
let result = run_command(
&runtime,
&handler,
"printf ran > ran",
&HashMap::new(),
"",
root.path(),
)
.await;
assert_eq!(
result.error.as_deref(),
Some("nul byte found in provided data")
);
assert_eq!(result.exit_code, None);
assert!(!root.path().join("ran").exists());
}
}