Skip to main content

runtimo_core/capabilities/
shell_exec.rs

1//! ShellExec capability — execute shell commands with full telemetry and audit trail.
2//!
3//! All commands execute via `sh -c`, providing full shell functionality:
4//! - Pipes: `ls | head -5`
5//! - Redirects: `echo hello > /tmp/file.txt`
6//! - Chaining: `echo first && echo second`
7//!
8//! # Guardrails (not security)
9//!
10//! **Threat model:** Agents making mistakes, not attackers.
11//! The blocklist catches obvious agent hallucinations/bugs.
12//!
13//! **What's blocked:**
14//! - Filesystem destruction: `rm -rf /`, `rm -rf` on system dirs (`/home`, `/etc`, `/usr`, `/var`, `/lib`, `/opt`, `/bin`, `/sbin`)
15//! - Shell expansion bypasses: `rm -rf ~` (tilde expansion)
16//! - Filesystem creation: `mkfs.*`, `mkswap`
17//! - Data destruction: `dd if=/dev/zero`
18//! - System commands: `shutdown`, `reboot`, `poweroff`
19//! - Disk operations: `fdisk`, `parted`
20//!
21//! **What protects you:**
22//! - Dangerous command blocklist
23//! - Resource limits (timeout, process isolation)
24//! - WAL audit trail (enables undo/recovery)
25//!
26//! # Features
27//!
28//! - Timeout enforcement (default 30s, configurable)
29//! - Output capture (stdout/stderr, bounded to 10MB)
30//! - PID tracking (child + grandchildren via /proc/{pid}/children)
31//! - Process group isolation (kills all descendants on timeout)
32//! - Telemetry before/after execution
33//! - WAL logging for audit trail
34//! - Stdin pipe support
35//!
36//! # Example
37//!
38//! ```rust,ignore
39//! use runtimo_core::capabilities::ShellExec;
40//! use runtimo_core::capability::{Capability, Context};
41//! use serde_json::json;
42//!
43//! let result = ShellExec.execute(
44//!     &json!({"cmd": "ls | head -5", "timeout_secs": 10}),
45//!     &Context { dry_run: false, job_id: "test".into(), working_dir: std::env::temp_dir() }
46//! ).unwrap();
47//! ```
48
49use crate::capability::{Capability, Context, Output};
50use crate::validation::path::{validate_path, PathContext};
51use crate::{Error, Result};
52use serde::{Deserialize, Serialize};
53use serde_json::Value;
54use std::fs;
55use std::io::{Read, Write};
56use std::os::unix::process::CommandExt;
57use std::process::{Child, Command, ExitStatus};
58use std::thread;
59use std::time::{Duration, Instant};
60
61type WaitResult = Result<(ExitStatus, Vec<u8>, Vec<u8>, Vec<u32>)>;
62
63const DEFAULT_TIMEOUT_SECS: u64 = 30;
64const MAX_OUTPUT_BYTES: usize = 10 * 1024 * 1024;
65const MAX_STDIN_BYTES: usize = 1024 * 1024;
66
67#[derive(Debug, Clone, Serialize, Deserialize)]
68pub struct ShellExecArgs {
69    pub cmd: String,
70    pub timeout_secs: Option<u64>,
71    pub cwd: Option<String>,
72    pub stdin: Option<String>,
73}
74
75fn is_dangerous_command(cmd: &str) -> Option<&'static str> {
76    let cmd_lower = cmd.to_lowercase();
77    if cmd_lower.contains("mkfs") || cmd_lower.contains("mkswap") {
78        return Some("filesystem creation commands are blocked");
79    }
80    if cmd_lower.contains("fdisk") || cmd_lower.contains("parted") {
81        return Some("disk partitioning commands are blocked");
82    }
83    if cmd_lower.contains(" dd ") || cmd_lower.starts_with("dd ") || cmd_lower.contains(" dd") {
84        return Some("dd (disk destroyer) is blocked");
85    }
86    if cmd_lower.contains("shutdown")
87        || cmd_lower.contains("reboot")
88        || cmd_lower.contains("poweroff")
89    {
90        return Some("system power commands are blocked");
91    }
92    if cmd_lower.contains("rm")
93        && (cmd_lower.contains("-rf")
94            || cmd_lower.contains("-fr")
95            || cmd_lower.contains(" -r ")
96            || cmd_lower.contains(" -f "))
97        && (cmd_lower.contains(" / ")
98            || cmd_lower.contains("/*")
99            || cmd_lower.contains("/dev")
100            || cmd_lower.contains("/boot")
101            || cmd_lower.contains("/home")
102            || cmd_lower.contains("/etc")
103            || cmd_lower.contains("/usr")
104            || cmd_lower.contains("/var")
105            || cmd_lower.contains("/lib")
106            || cmd_lower.contains("/opt")
107            || cmd_lower.contains("/bin")
108            || cmd_lower.contains("/sbin"))
109    {
110        return Some("rm -rf on system directories is blocked");
111    }
112    if cmd_lower.contains("rm")
113        && (cmd_lower.contains("-rf")
114            || cmd_lower.contains("-fr")
115            || cmd_lower.contains(" -r ")
116            || cmd_lower.contains(" -f "))
117        && cmd_lower.contains('~')
118    {
119        return Some("rm -rf with shell expansions is blocked — use explicit paths");
120    }
121    if cmd_lower.contains("chmod") && cmd_lower.contains("777") && cmd_lower.contains(" /") {
122        return Some("chmod 777 / is blocked");
123    }
124    None
125}
126
127#[allow(clippy::arithmetic_side_effects)] // -(pgid) negation is safe for valid PIDs
128fn wait_with_timeout(child: &mut Child, pgid: u32, timeout_secs: u64) -> WaitResult {
129    let start = Instant::now();
130    let timeout = Duration::from_secs(timeout_secs);
131    let child_pid = child.id();
132    let stdout_thread = child.stdout.take().map(|stdout| {
133        thread::spawn(move || {
134            let mut data = Vec::new();
135            let _ = stdout.take(MAX_OUTPUT_BYTES as u64).read_to_end(&mut data);
136            data
137        })
138    });
139    let stderr_thread = child.stderr.take().map(|stderr| {
140        thread::spawn(move || {
141            let mut data = Vec::new();
142            let _ = stderr.take(MAX_OUTPUT_BYTES as u64).read_to_end(&mut data);
143            data
144        })
145    });
146    let mut last_descendants: Vec<u32>;
147    loop {
148        if start.elapsed() > timeout {
149            // SAFETY: pgid is a valid process group ID from the spawned child; SIGKILL is well-defined;
150            // pgid as pid_t may wrap on 32-bit but pgid is always within pid_t range
151            #[allow(clippy::cast_possible_wrap)]
152            unsafe {
153                let _ = libc::kill(-(pgid as libc::pid_t), libc::SIGKILL);
154            }
155            let killed_descendants = get_all_descendants(child_pid);
156            let _ = child.wait();
157            let _ = stdout_thread.map(|h| h.join().unwrap_or_default());
158            let _ = stderr_thread.map(|h| h.join().unwrap_or_default());
159            return Err(Error::ExecutionFailed(format!(
160                "command timed out after {}s (killed {} descendants)",
161                timeout_secs,
162                killed_descendants.len()
163            )));
164        }
165        last_descendants = get_all_descendants(child_pid);
166        match child.try_wait() {
167            Ok(Some(status)) => {
168                let stdout_data = stdout_thread
169                    .map(|h| h.join().unwrap_or_default())
170                    .unwrap_or_default();
171                let stderr_data = stderr_thread
172                    .map(|h| h.join().unwrap_or_default())
173                    .unwrap_or_default();
174                return Ok((status, stdout_data, stderr_data, last_descendants));
175            }
176            Ok(None) => std::thread::sleep(Duration::from_millis(50)),
177            Err(e) => return Err(Error::ExecutionFailed(format!("error waiting: {}", e))),
178        }
179    }
180}
181
182fn get_direct_children(pid: u32) -> Vec<u32> {
183    let children_path = format!("/proc/{}/children", pid);
184    if let Ok(content) = fs::read_to_string(&children_path) {
185        content
186            .split_whitespace()
187            .filter_map(|s| s.parse::<u32>().ok())
188            .collect()
189    } else {
190        Vec::new()
191    }
192}
193
194fn get_all_descendants(pid: u32) -> Vec<u32> {
195    let mut descendants = Vec::new();
196    let mut stack = vec![pid];
197    let mut visited = std::collections::HashSet::new();
198    while let Some(current) = stack.pop() {
199        if visited.contains(&current) {
200            continue;
201        }
202        visited.insert(current);
203        let children = get_direct_children(current);
204        if children.is_empty() {
205            if let Ok(output) = std::process::Command::new("pgrep")
206                .arg("-P")
207                .arg(current.to_string())
208                .output()
209            {
210                if output.status.success() {
211                    let pgrep_lines = String::from_utf8_lossy(&output.stdout).to_string();
212                    let pgrep_children = pgrep_lines
213                        .lines()
214                        .filter_map(|s| s.trim().parse::<u32>().ok());
215                    for child in pgrep_children {
216                        if !visited.contains(&child) {
217                            descendants.push(child);
218                            stack.push(child);
219                        }
220                    }
221                    continue;
222                }
223            }
224        }
225        for child in children {
226            if !visited.contains(&child) {
227                descendants.push(child);
228                stack.push(child);
229            }
230        }
231    }
232    descendants
233}
234
235#[allow(clippy::exhaustive_structs)]
236pub struct ShellExec;
237
238impl Capability for ShellExec {
239    fn name(&self) -> &'static str {
240        "ShellExec"
241    }
242    fn description(&self) -> &'static str {
243        "exec cmd via sh -c, timeout, audit. Dangerous cmds: mkfs,fdisk,dd,shutdown,rm -rf / blocked."
244    }
245    fn schema(&self) -> Value {
246        serde_json::json!({
247            "type": "object",
248            "properties": {
249                "cmd": { "type": "string", "description": "Command to execute via sh -c" },
250                "timeout_secs": { "type": "integer", "minimum": 1, "maximum": 300 },
251                "cwd": { "type": "string" },
252                "stdin": { "type": "string" }
253            },
254            "required": ["cmd"]
255        })
256    }
257    fn validate(&self, args: &Value) -> Result<()> {
258        let args: ShellExecArgs = serde_json::from_value(args.clone())
259            .map_err(|e| Error::SchemaValidationFailed(e.to_string()))?;
260        if args.cmd.is_empty() {
261            return Err(Error::SchemaValidationFailed("cmd is empty".into()));
262        }
263        Ok(())
264    }
265    fn execute(&self, args: &Value, ctx: &Context) -> Result<Output> {
266        if ctx.dry_run {
267            return Ok(Output {
268                success: true,
269                data: serde_json::json!({ "cmd": args.get("cmd").and_then(|v| v.as_str()).unwrap_or(""), "dry_run": true }),
270                message: Some("DRY RUN".into()),
271            });
272        }
273        let args: ShellExecArgs = serde_json::from_value(args.clone())
274            .map_err(|e| Error::ExecutionFailed(e.to_string()))?;
275        let timeout = args.timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS);
276        if let Some(reason) = is_dangerous_command(&args.cmd) {
277            return Err(Error::ExecutionFailed(format!(
278                "dangerous command blocked: {}",
279                reason
280            )));
281        }
282        let mut cmd = Command::new("sh");
283        cmd.arg("-c").arg(&args.cmd);
284        if let Some(cwd) = &args.cwd {
285            let path_ctx = PathContext {
286                require_exists: true,
287                require_file: false,
288                ..Default::default()
289            };
290            let cwd_path = validate_path(cwd, &path_ctx)
291                .map_err(|e| Error::ExecutionFailed(format!("invalid cwd: {}", e)))?;
292            cmd.current_dir(cwd_path);
293        }
294        let mut child = cmd
295            .process_group(0)
296            .stdout(std::process::Stdio::piped())
297            .stderr(std::process::Stdio::piped())
298            .stdin(if args.stdin.is_some() {
299                std::process::Stdio::piped()
300            } else {
301                std::process::Stdio::null()
302            })
303            .spawn()
304            .map_err(|e| Error::ExecutionFailed(format!("failed to spawn: {}", e)))?;
305        let child_pid = child.id();
306        let pgid = child_pid;
307        if let Some(ref stdin_content) = args.stdin {
308            if stdin_content.len() > MAX_STDIN_BYTES {
309                return Err(Error::ExecutionFailed("stdin too large".into()));
310            }
311            if let Some(mut stdin_pipe) = child.stdin.take() {
312                let _ = stdin_pipe.write_all(stdin_content.as_bytes());
313            }
314        }
315        let (exit_status, stdout, stderr, descendants) =
316            wait_with_timeout(&mut child, pgid, timeout)?;
317        let mut spawned_pids = vec![child_pid];
318        spawned_pids.extend(descendants);
319        let stdout_str = String::from_utf8_lossy(&stdout).to_string();
320        let stderr_str = String::from_utf8_lossy(&stderr).to_string();
321        let success = exit_status.success();
322
323        Ok(Output {
324            success,
325            data: serde_json::json!({ "cmd": &args.cmd, "stdout": stdout_str, "stderr": stderr_str, "exit_code": exit_status.code().unwrap_or(-1), "pid": child_pid, "spawned_pids": spawned_pids, "timeout_secs": timeout, "timed_out": exit_status.code().is_none(), "truncated": stdout.len() >= MAX_OUTPUT_BYTES || stderr.len() >= MAX_OUTPUT_BYTES }),
326            message: if success {
327                Some("completed".into())
328            } else {
329                Some(format!("exit code {}", exit_status.code().unwrap_or(-1)))
330            },
331        })
332    }
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338    use crate::capability::Capability;
339    use std::time::Instant;
340    #[test]
341    fn executes_uptime() {
342        let r = ShellExec
343            .execute(
344                &serde_json::json!({"cmd": "uptime"}),
345                &Context {
346                    dry_run: false,
347                    job_id: "test".into(),
348                    working_dir: std::env::temp_dir(),
349                },
350            )
351            .unwrap();
352        assert!(r.success);
353    }
354    #[test]
355    fn pipes_work() {
356        let r = ShellExec
357            .execute(
358                &serde_json::json!({"cmd": "echo hi | cat"}),
359                &Context {
360                    dry_run: false,
361                    job_id: "test".into(),
362                    working_dir: std::env::temp_dir(),
363                },
364            )
365            .unwrap();
366        assert!(r.success);
367        assert!(r.data["stdout"].as_str().unwrap().contains("hi"));
368    }
369    #[test]
370    fn chaining_works() {
371        let r = ShellExec
372            .execute(
373                &serde_json::json!({"cmd": "echo a && echo b"}),
374                &Context {
375                    dry_run: false,
376                    job_id: "test".into(),
377                    working_dir: std::env::temp_dir(),
378                },
379            )
380            .unwrap();
381        assert!(r.success);
382    }
383    #[test]
384    fn blocks_dangerous() {
385        assert!(ShellExec
386            .execute(
387                &serde_json::json!({"cmd": "mkfs"}),
388                &Context {
389                    dry_run: false,
390                    job_id: "test".into(),
391                    working_dir: std::env::temp_dir()
392                }
393            )
394            .is_err());
395    }
396    #[test]
397    fn enforces_timeout() {
398        let s = Instant::now();
399        assert!(ShellExec
400            .execute(
401                &serde_json::json!({"cmd": "sleep 5", "timeout_secs": 1}),
402                &Context {
403                    dry_run: false,
404                    job_id: "test".into(),
405                    working_dir: std::env::temp_dir()
406                }
407            )
408            .is_err());
409        assert!(s.elapsed().as_secs() < 3);
410    }
411}