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 --- 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 +++++++++++++++++++++++++++++++++++++++++++++++++----- 6 files changed, 116 insertions(+), 14 deletions(-) (limited to 'src') 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); + } + } +} -- cgit v1.2.3