From c7afd1ea752aeff0310ac7c6b78d091ac360c760 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 15:38:57 +0100 Subject: 0.4.3: kill process groups, bound bash output, keep the key out of tool env - setsid-style process group kill on timeout and on Ctrl-C - 64 MiB RLIMIT_FSIZE so a runaway command cannot fill /tmp - OPENCODE_API_KEY removed from child environment - sessions 0600/0700, history 0600 and trimmed --- CHANGELOG.md | 17 +++++++++ Cargo.lock | 2 +- Cargo.toml | 2 +- src/agent.rs | 19 ++++++++-- src/doctor.rs | 15 +++++++- src/line.rs | 13 ++++++- src/session.rs | 12 ++++++ src/tools/mod.rs | 4 +- src/tools/shell.rs | 67 ++++++++++++++++++++++++++++++--- tests/sessions.rs | 6 +++ tests/tools.rs | 106 ++++++++++++++++++++++++++++++++++++++++++----------- 11 files changed, 225 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9867621..79acd31 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,23 @@ break the interface, **PATCH** for bug fixes. file, and the tool schemas the model sees. Anything a script or a resumed session could depend on counts as API. +## 0.4.3 + +### Fixed +- `bash` timeouts killed only the direct `sh`, leaving `make`, `cargo` or `sleep` + running on the 2-core box. The command now runs in its own process group and + the whole group is killed on timeout or on Ctrl-C. +- `bash` output was unbounded on disk while being truncated on read; the child now + has a 64 MiB file-size limit and reports when it hit it. +- A long-running command can now be stopped with Ctrl-C instead of waiting out + the 120 s timeout. +- `OPENCODE_API_KEY` was inherited by every command, so a failing build that + dumped the environment would put the key in the transcript and send it back to + the provider. It is removed from the child environment. +- Session files are created `0600` and their directories `0700`; older `0644` + files are tightened on open. History is `0600` and its file is trimmed. +- `--doctor` warns when the key file is readable by other users. + ## 0.4.2 ### Fixed diff --git a/Cargo.lock b/Cargo.lock index d2dc605..0d49260 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "agent686" -version = "0.4.0" +version = "0.4.2" dependencies = [ "crossterm", "libc", diff --git a/Cargo.toml b/Cargo.toml index 51c046a..faf882f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "agent686" -version = "0.4.2" +version = "0.4.3" edition = "2021" description = "A small coding agent for a 32-bit Debian box" publish = false diff --git a/src/agent.rs b/src/agent.rs index 46da069..9e2a431 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -159,6 +159,7 @@ pub fn run_turn( let mut last: Option = None; let mut aborted = false; let mut denied = 0usize; + let mut truncated: Option = None; loop { if cancel.load(std::sync::atomic::Ordering::Relaxed) { @@ -184,6 +185,9 @@ pub fn run_turn( } } + if outcome.finish.as_deref() == Some("length") { + truncated = Some("the model hit its output limit; the answer is cut off".into()); + } let assistant = assistant_message(&outcome); push(session, history, assistant, Some(outcome.reasoning.as_str())); @@ -204,7 +208,7 @@ pub fn run_turn( let result = if aborted { ToolOutcome::Failed("aborted by the user before this call ran".into()) } else { - execute(&call, approver) + execute(&call, approver, cancel) }; if result.denied() { denied += 1; @@ -226,6 +230,9 @@ pub fn run_turn( if aborted { eprintln!("aborted"); } + if let Some(note) = truncated { + eprintln!("agent686: {note}"); + } if let Some(outcome) = last { ui::status(steps, started.elapsed(), &outcome); } @@ -281,12 +288,16 @@ fn repair_tool_results(session: &mut Session, history: &mut Vec) { } } -fn execute(call: &provider::ToolCall, approver: &mut Approver) -> ToolOutcome { +fn execute( + call: &provider::ToolCall, + approver: &mut Approver, + cancel: &AtomicBool, +) -> ToolOutcome { let args: Value = serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({})); ui::tool_line(&call.name, &args); match tools::approval(&call.name) { - Approval::Never => match tools::run(&call.name, &args) { + Approval::Never => match tools::run(&call.name, &args, cancel) { Ok(output) => ToolOutcome::Ok(output), Err(error) => ToolOutcome::Failed(error), }, @@ -306,7 +317,7 @@ fn execute(call: &provider::ToolCall, approver: &mut Approver) -> ToolOutcome { Approval::EveryCall => { let cmd = args.get("cmd").and_then(|v| v.as_str()).unwrap_or(""); if approver.allow_bash(cmd) { - match tools::run(&call.name, &args) { + match tools::run(&call.name, &args, cancel) { Ok(output) => ToolOutcome::Ok(output), Err(error) => ToolOutcome::Failed(error), } diff --git a/src/doctor.rs b/src/doctor.rs index 42d24a8..65fca50 100644 --- a/src/doctor.rs +++ b/src/doctor.rs @@ -19,7 +19,20 @@ pub fn run(cfg: &Config) -> i32 { match config::key_source() { KeySource::Env => row(true, "key", "present in OPENCODE_API_KEY"), - KeySource::File(path) => row(true, "key", &format!("present in {}", path.display())), + KeySource::File(path) => { + row(true, "key", &format!("present in {}", path.display())); + use std::os::unix::fs::PermissionsExt; + if let Ok(meta) = std::fs::metadata(&path) { + if meta.permissions().mode() & 0o077 != 0 { + println!( + "{:<13} {:<4} {} is readable by other users; chmod 600 it", + "key perms", + "WARN", + path.display() + ); + } + } + } KeySource::Missing => { row( false, diff --git a/src/line.rs b/src/line.rs index 6b93f06..4989734 100644 --- a/src/line.rs +++ b/src/line.rs @@ -1,4 +1,5 @@ use std::io::{self, IsTerminal, Write}; +use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; use crossterm::cursor::{MoveToColumn, MoveUp}; @@ -324,7 +325,8 @@ fn history_path() -> PathBuf { } fn load_history() -> Vec { - let text = std::fs::read_to_string(history_path()).unwrap_or_default(); + let path = history_path(); + let text = std::fs::read_to_string(&path).unwrap_or_default(); let mut lines: Vec = text .split('\n') .filter(|line| !line.trim().is_empty() && !line.starts_with('\u{0}')) @@ -332,6 +334,11 @@ fn load_history() -> Vec { .collect(); if lines.len() > HISTORY_LIMIT { lines.drain(..lines.len() - HISTORY_LIMIT); + // Keep the file from growing without bound, not just the in-memory list. + if lines.len() * 2 < text.lines().count() { + let body: Vec = lines.iter().map(|line| line.replace('\n', "\u{0}")).collect(); + let _ = std::fs::write(&path, format!("{}\n", body.join("\n"))); + } } lines } @@ -341,11 +348,15 @@ fn append_history(line: &str) { if let Some(parent) = path.parent() { let _ = std::fs::create_dir_all(parent); } + if let Some(parent) = path.parent() { + let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)); + } if let Ok(mut file) = std::fs::OpenOptions::new() .create(true) .append(true) .open(&path) { + let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)); // One record per line, so newlines inside a prompt are escaped. let _ = writeln!(file, "{}", line.replace('\n', "\u{0}")); } diff --git a/src/session.rs b/src/session.rs index 9f2b699..f27a188 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1,6 +1,8 @@ use std::fs::{File, OpenOptions}; use std::hash::{Hash, Hasher}; use std::io::{BufRead, BufReader, Read, Write}; +use std::os::unix::fs::PermissionsExt; +use std::path::Path; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; @@ -41,6 +43,11 @@ pub fn sessions_dir() -> PathBuf { data_root().join("sessions") } +/// Sessions contain the whole conversation, so they are for this user only. +fn restrict(path: &Path, mode: u32) { + let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)); +} + pub struct Session { pub id: String, pub model: String, @@ -66,12 +73,15 @@ impl Session { pub fn create_as(id: String, model: &str, system: &Value) -> Result { let dir = sessions_dir(); std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + restrict(&data_root(), 0o700); + restrict(&dir, 0o700); let path = dir.join(format!("{id}.jsonl")); let mut file = OpenOptions::new() .create_new(true) .append(true) .open(&path) .map_err(|e| format!("{}: {e}", path.display()))?; + restrict(&path, 0o600); let header = json!({ "t": "header", @@ -141,6 +151,8 @@ impl Session { .append(true) .open(&path) .map_err(|e| format!("{}: {e}", path.display()))?; + // Older builds created these 0644. + restrict(&path, 0o600); Ok(( Session { diff --git a/src/tools/mod.rs b/src/tools/mod.rs index 7a1a26d..a8851ab 100644 --- a/src/tools/mod.rs +++ b/src/tools/mod.rs @@ -25,12 +25,12 @@ pub fn approval(name: &str) -> Approval { } /// Tools that execute immediately. -pub fn run(name: &str, args: &Value) -> Result { +pub fn run(name: &str, args: &Value, cancel: &std::sync::atomic::AtomicBool) -> Result { match name { "read" => fs::read(args), "grep" => fs::grep(args), "glob" => fs::glob(args), - "bash" => shell::bash(args, std::time::Duration::from_secs(120)), + "bash" => shell::bash(args, std::time::Duration::from_secs(120), cancel), other => Err(unknown(other)), } } diff --git a/src/tools/shell.rs b/src/tools/shell.rs index 9c214fb..29d2375 100644 --- a/src/tools/shell.rs +++ b/src/tools/shell.rs @@ -1,17 +1,25 @@ use std::fs::File; use std::io::{Read, Seek, SeekFrom}; +use std::os::unix::process::{CommandExt, ExitStatusExt}; use std::path::PathBuf; use std::process::{Command, Stdio}; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::time::{Duration, Instant}; use serde_json::Value; const HEAD_BYTES: usize = 64 * 1024; const TAIL_BYTES: i64 = 16 * 1024; +/// The child cannot write more than this, so a runaway command cannot fill /tmp +/// and take the machine down with it. +const MAX_OUTPUT_BYTES: u64 = 64 * 1024 * 1024; static COUNTER: AtomicU64 = AtomicU64::new(0); -pub fn bash(args: &Value, timeout: Duration) -> Result { +pub fn bash( + args: &Value, + timeout: Duration, + cancel: &AtomicBool, +) -> Result { let cmd = match args.get("cmd").and_then(|v| v.as_str()) { Some(cmd) => cmd.to_string(), None => return Err("missing required argument `cmd`".into()), @@ -37,25 +45,53 @@ pub fn bash(args: &Value, timeout: Duration) -> Result { let stdout = file.try_clone().map_err(|e| e.to_string())?; let stderr = file.try_clone().map_err(|e| e.to_string())?; - let mut child = Command::new("sh") + let mut command = Command::new("sh"); + command .arg("-c") .arg(&cmd) .current_dir(&cwd) .stdin(Stdio::null()) .stdout(Stdio::from(stdout)) .stderr(Stdio::from(stderr)) + // The harness owns the key; no build script needs it, and a failing + // command that dumps the environment would put it in the transcript. + .env_remove("OPENCODE_API_KEY") + // Own process group, so the whole tree can be killed and so terminal + // Ctrl-C does not race our own handling. + .process_group(0); + unsafe { + command.pre_exec(|| { + let limit = libc::rlimit { + rlim_cur: MAX_OUTPUT_BYTES, + rlim_max: MAX_OUTPUT_BYTES, + }; + if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + + let mut child = command .spawn() .map_err(|e| format!("failed to start sh: {e}"))?; + let group = child.id() as i32; let deadline = Instant::now() + timeout; let mut timed_out = false; + let mut aborted = false; let status = loop { + if cancel.load(Ordering::Relaxed) { + aborted = true; + kill_group(group); + break child.wait().map_err(|e| e.to_string())?; + } match child.try_wait().map_err(|e| e.to_string())? { Some(status) => break status, None => { if Instant::now() >= deadline { - let _ = child.kill(); timed_out = true; + kill_group(group); break child.wait().map_err(|e| e.to_string())?; } std::thread::sleep(Duration::from_millis(20)); @@ -63,6 +99,9 @@ pub fn bash(args: &Value, timeout: Duration) -> Result { } }; + // A child that blew the file-size limit was killed by SIGXFSZ. + let over_limit = status.signal() == Some(libc::SIGXFSZ); + let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?; drop(file); let _ = std::fs::remove_file(&path); @@ -71,7 +110,14 @@ pub fn bash(args: &Value, timeout: Duration) -> Result { if !out.is_empty() && !out.ends_with('\n') { out.push('\n'); } - if timed_out { + if over_limit { + out.push_str(&format!( + "[output exceeded {} MiB; command killed]", + MAX_OUTPUT_BYTES / (1024 * 1024) + )); + } else if aborted { + out.push_str("[aborted by the user]"); + } else if timed_out { out.push_str(&format!( "[timed out after {:.1}s; process killed]", timeout.as_secs_f64() @@ -80,7 +126,6 @@ pub fn bash(args: &Value, timeout: Duration) -> Result { match status.code() { Some(code) => out.push_str(&format!("[exit {code}]")), None => { - use std::os::unix::process::ExitStatusExt; out.push_str(&format!( "[killed by signal {}]", status.signal().unwrap_or_default() @@ -127,3 +172,13 @@ fn read_capped(file: &mut File) -> Result { } Ok(String::from_utf8_lossy(&out).into_owned()) } + +/// SIGKILL the whole process group the command created. `child.kill()` would +/// only reach `sh`, leaving `sh`'s children running on the 2-core box. +fn kill_group(pid: i32) { + if pid > 0 { + unsafe { + libc::kill(-pid, libc::SIGKILL); + } + } +} diff --git a/tests/sessions.rs b/tests/sessions.rs index 8d17fc5..b445242 100644 --- a/tests/sessions.rs +++ b/tests/sessions.rs @@ -35,6 +35,12 @@ fn sessions_create_list_and_replay() { ) .unwrap(); + { + use std::os::unix::fs::PermissionsExt; + let mode = fs::metadata(alpha.path()).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600, "sessions must not be group/world readable"); + } + assert!(session::exists("alpha")); assert!(!session::exists("nope")); diff --git a/tests/tools.rs b/tests/tools.rs index 8463d8d..c30128e 100644 --- a/tests/tools.rs +++ b/tests/tools.rs @@ -5,6 +5,11 @@ use std::time::Duration; use serde_json::json; use agent686::tools::{self, shell}; +use std::sync::atomic::AtomicBool; + +fn run(name: &str, args: &serde_json::Value) -> Result { + tools::run(name, args, &AtomicBool::new(false)) +} fn temp_dir(tag: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("agent686-test-{tag}-{}", std::process::id())); @@ -73,7 +78,7 @@ fn read_numbers_lines_and_reports_truncation() { let path = dir.join("f.txt"); fs::write(&path, "one\ntwo\nthree\nfour\n").unwrap(); - let text = tools::run("read", &json!({ "path": path, "limit": 2 })).unwrap(); + let text = run("read", &json!({ "path": path, "limit": 2 })).unwrap(); assert!(text.contains(" 1\tone"), "{text}"); assert!(text.contains(" 2\ttwo"), "{text}"); assert!(text.contains("continue with offset=3"), "{text}"); @@ -86,10 +91,10 @@ fn grep_finds_lines_and_honours_case() { let path = dir.join("f.txt"); fs::write(&path, "alpha\nbeta\nALPHA\n").unwrap(); - let text = tools::run("grep", &json!({ "pattern": "alpha", "path": dir })).unwrap(); + let text = run("grep", &json!({ "pattern": "alpha", "path": dir })).unwrap(); assert_eq!(text.lines().count(), 1, "{text}"); - let text = tools::run( + let text = run( "grep", &json!({ "pattern": "alpha", "path": dir, "ignore_case": true }), ) @@ -106,30 +111,30 @@ fn glob_supports_double_star_and_bare_names() { fs::write(dir.join("sub/deep/c.rs"), "").unwrap(); fs::write(dir.join("sub/note.txt"), "").unwrap(); - let text = tools::run("glob", &json!({ "pattern": "**/*.rs", "path": dir })).unwrap(); + let text = run("glob", &json!({ "pattern": "**/*.rs", "path": dir })).unwrap(); assert_eq!(text.lines().count(), 3, "{text}"); - let text = tools::run("glob", &json!({ "pattern": "*.rs", "path": dir })).unwrap(); + let text = run("glob", &json!({ "pattern": "*.rs", "path": dir })).unwrap(); assert_eq!(text.lines().count(), 3, "{text}"); - let text = tools::run("glob", &json!({ "pattern": "sub/*.rs", "path": dir })).unwrap(); + let text = run("glob", &json!({ "pattern": "sub/*.rs", "path": dir })).unwrap(); assert_eq!(text.lines().count(), 1, "{text}"); assert!(text.contains("b.rs"), "{text}"); } #[test] fn bash_reports_exit_code_and_times_out() { - let text = tools::run("bash", &json!({ "cmd": "echo hi; exit 3" })).unwrap(); + let text = run("bash", &json!({ "cmd": "echo hi; exit 3" })).unwrap(); assert!(text.contains("hi"), "{text}"); assert!(text.contains("[exit 3]"), "{text}"); - let text = shell::bash(&json!({ "cmd": "sleep 5" }), Duration::from_millis(150)).unwrap(); + let text = shell::bash(&json!({ "cmd": "sleep 5" }), Duration::from_millis(150), &AtomicBool::new(false)).unwrap(); assert!(text.contains("timed out after"), "{text}"); } #[test] fn bash_rejects_a_missing_cwd() { - let error = tools::run("bash", &json!({ "cmd": "true", "cwd": "/nonexistent-dir-xyz" })) + let error = run("bash", &json!({ "cmd": "true", "cwd": "/nonexistent-dir-xyz" })) .err() .expect("missing cwd must fail"); assert!(error.contains("cwd is not a directory"), "{error}"); @@ -137,7 +142,7 @@ fn bash_rejects_a_missing_cwd() { #[test] fn unknown_tool_is_an_error_not_a_panic() { - let error = tools::run("teleport", &json!({})).err().unwrap(); + let error = run("teleport", &json!({})).err().unwrap(); assert!(error.contains("unknown tool"), "{error}"); } @@ -151,7 +156,7 @@ fn read_streams_large_files_and_reports_the_next_offset() { } fs::write(&path, body).unwrap(); - let text = tools::run("read", &json!({ "path": path, "offset": 990, "limit": 5 })).unwrap(); + let text = run("read", &json!({ "path": path, "offset": 990, "limit": 5 })).unwrap(); assert!(text.contains(" 990\tline 990"), "{text}"); assert!(text.contains(" 994\tline 994"), "{text}"); assert!(!text.contains("line 995"), "{text}"); @@ -164,7 +169,7 @@ fn read_clips_a_single_enormous_line() { let path = dir.join("one-line.txt"); fs::write(&path, "x".repeat(5 * 1024 * 1024)).unwrap(); - let text = tools::run("read", &json!({ "path": path })).unwrap(); + let text = run("read", &json!({ "path": path })).unwrap(); assert!(text.starts_with(" 1\tx"), "{text}"); assert!(text.contains("line truncated"), "{text}"); // Bounded by the per-line cap, not by the file size. @@ -176,7 +181,7 @@ fn read_reports_an_offset_past_the_end() { let dir = temp_dir("read-eof"); let path = dir.join("short.txt"); fs::write(&path, "only\n").unwrap(); - let text = tools::run("read", &json!({ "path": path, "offset": 9 })).unwrap(); + let text = run("read", &json!({ "path": path, "offset": 9 })).unwrap(); assert!(text.contains("fewer than 9 lines"), "{text}"); } @@ -185,10 +190,10 @@ fn read_refuses_binaries_and_directories() { let dir = temp_dir("read-binary"); let binary = dir.join("blob.bin"); fs::write(&binary, [0u8, 1, 2, 3, 0, 9]).unwrap(); - let error = tools::run("read", &json!({ "path": binary })).err().unwrap(); + let error = run("read", &json!({ "path": binary })).err().unwrap(); assert!(error.contains("binary"), "{error}"); - let error = tools::run("read", &json!({ "path": dir })).err().unwrap(); + let error = run("read", &json!({ "path": dir })).err().unwrap(); assert!(error.contains("is a directory"), "{error}"); } @@ -197,7 +202,7 @@ fn read_handles_a_missing_trailing_newline() { let dir = temp_dir("read-no-newline"); let path = dir.join("f.txt"); fs::write(&path, "one\ntwo").unwrap(); - let text = tools::run("read", &json!({ "path": path })).unwrap(); + let text = run("read", &json!({ "path": path })).unwrap(); assert!(text.contains(" 2\ttwo"), "{text}"); assert!(!text.contains("continue with offset"), "{text}"); } @@ -211,13 +216,13 @@ fn grep_uses_regular_expressions_by_default() { ) .unwrap(); - let text = tools::run("grep", &json!({ "pattern": r"fn\s+main", "path": dir })).unwrap(); + let text = run("grep", &json!({ "pattern": r"fn\s+main", "path": dir })).unwrap(); assert_eq!(text.lines().count(), 1, "{text}"); - let text = tools::run("grep", &json!({ "pattern": r"fn\s+\w+", "path": dir })).unwrap(); + let text = run("grep", &json!({ "pattern": r"fn\s+\w+", "path": dir })).unwrap(); assert_eq!(text.lines().count(), 2, "{text}"); - let text = tools::run( + let text = run( "grep", &json!({ "pattern": r"FN\s+MAIN", "path": dir, "ignore_case": true }), ) @@ -231,11 +236,11 @@ fn grep_fixed_matches_literally_and_bad_patterns_explain_themselves() { fs::write(dir.join("f.txt"), "cost is a+b\nand ab\n").unwrap(); // As a regex, `a+b` matches the "ab" on line 2, not the literal "a+b". - let text = tools::run("grep", &json!({ "pattern": "a+b", "path": dir })).unwrap(); + let text = run("grep", &json!({ "pattern": "a+b", "path": dir })).unwrap(); assert_eq!(text.lines().count(), 1, "{text}"); assert!(text.contains("and ab"), "{text}"); - let text = tools::run( + let text = run( "grep", &json!({ "pattern": "a+b", "path": dir, "fixed": true }), ) @@ -243,9 +248,66 @@ fn grep_fixed_matches_literally_and_bad_patterns_explain_themselves() { assert_eq!(text.lines().count(), 1, "{text}"); assert!(text.contains("cost is a+b"), "{text}"); - let error = tools::run("grep", &json!({ "pattern": "(", "path": dir })) + let error = run("grep", &json!({ "pattern": "(", "path": dir })) .err() .expect("invalid regex must fail"); assert!(error.contains("invalid regex"), "{error}"); assert!(error.contains("fixed"), "{error}"); } + +fn running(pid: i32) -> bool { + // A zombie has already exited; anything but Z means still alive. + match fs::read_to_string(format!("/proc/{pid}/stat")) { + Ok(stat) => stat + .rsplit(')') + .next() + .and_then(|rest| rest.split_whitespace().next()) + .map(|state| state != "Z") + .unwrap_or(false), + Err(_) => false, + } +} + +#[test] +fn bash_timeout_kills_the_whole_process_group() { + let dir = temp_dir("bash-group"); + let pidfile = dir.join("pid"); + let cmd = format!("sleep 30 & echo $! > {}; wait", pidfile.display()); + + let text = shell::bash( + &json!({ "cmd": cmd }), + Duration::from_millis(300), + &AtomicBool::new(false), + ) + .unwrap(); + assert!(text.contains("timed out"), "{text}"); + + std::thread::sleep(Duration::from_millis(300)); + let pid: i32 = fs::read_to_string(&pidfile).unwrap().trim().parse().unwrap(); + assert!(!running(pid), "grandchild {pid} survived the timeout"); +} + +#[test] +fn bash_stops_promptly_when_the_turn_is_cancelled() { + let started = std::time::Instant::now(); + let text = shell::bash( + &json!({ "cmd": "sleep 30" }), + Duration::from_secs(20), + &AtomicBool::new(true), + ) + .unwrap(); + assert!(text.contains("aborted by the user"), "{text}"); + assert!(started.elapsed() < Duration::from_secs(2)); +} + +#[test] +fn bash_does_not_inherit_the_api_key() { + std::env::set_var("OPENCODE_API_KEY", "do-not-leak-me"); + let text = run( + "bash", + &json!({ "cmd": "env | grep -c '^OPENCODE_API_KEY=' || true" }), + ) + .unwrap(); + std::env::remove_var("OPENCODE_API_KEY"); + assert!(text.contains('0'), "the key was visible to the child: {text}"); +} -- cgit v1.2.3