bounded_command/
command.rs1use std::collections::HashMap;
6use std::sync::{Mutex, OnceLock};
7
8pub const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(2_500);
11
12pub const MAX_CAPTURE_BYTES: usize = 8 * 1024 * 1024;
15
16fn which_cache() -> &'static Mutex<HashMap<String, bool>> {
19 static CACHE: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new();
20 CACHE.get_or_init(|| Mutex::new(HashMap::new()))
21}
22
23pub fn which(binary: &str) -> bool {
25 if let Ok(cache) = which_cache().lock()
26 && let Some(hit) = cache.get(binary)
27 {
28 return *hit;
29 }
30 let found = path_lookup(binary);
31 if let Ok(mut cache) = which_cache().lock() {
32 cache.insert(binary.to_string(), found);
33 }
34 found
35}
36
37fn path_lookup(binary: &str) -> bool {
39 fn is_executable_file(p: &std::path::Path) -> bool {
42 #[cfg(unix)]
43 {
44 use std::os::unix::fs::PermissionsExt as _;
45 std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
46 }
47 #[cfg(not(unix))]
48 {
49 std::fs::metadata(p).is_ok_and(|m| m.is_file())
50 }
51 }
52
53 #[cfg(test)]
54 tests::PATH_LOOKUPS.with(|lookups| lookups.set(lookups.get().saturating_add(1)));
55
56 if binary.is_empty() {
57 return false;
58 }
59 if binary.contains('/') || binary.contains(std::path::MAIN_SEPARATOR) {
60 return is_executable_file(std::path::Path::new(binary));
61 }
62 let Some(path) = std::env::var_os("PATH") else {
63 return false;
64 };
65 std::env::split_paths(&path)
66 .filter(|dir| !dir.as_os_str().is_empty())
67 .any(|dir| is_executable_file(&dir.join(binary)))
68}
69
70pub fn run_capture(binary: &str, args: &[&str]) -> Result<String, String> {
76 run_capture_within(binary, args, DEFAULT_TIMEOUT)
77}
78
79pub fn run_capture_within(
80 binary: &str,
81 args: &[&str],
82 timeout: std::time::Duration,
83) -> Result<String, String> {
84 if !which(binary) {
85 return Err(format!("{binary} not installed"));
86 }
87 let output = crate::run(binary, args, None, MAX_CAPTURE_BYTES, timeout)
88 .map_err(|error| bounded_error(binary, error))?;
89 if !output.status.success() {
90 let stderr = output.stderr_diagnostic();
91 return Err(format!(
92 "{binary} exited with status {:?}: {stderr}",
93 output.status.code()
94 ));
95 }
96 String::from_utf8(output.stdout).map_err(|e| format!("{binary} stdout not utf-8: {e}"))
97}
98
99pub fn run(binary: &str, args: &[&str]) -> Result<(), String> {
100 let _ = run_capture(binary, args)?;
101 Ok(())
102}
103
104fn bounded_error(binary: &str, error: crate::Error) -> String {
105 match error {
106 crate::Error::InputTooLarge => {
107 format!("{binary} input exceeded the safety limit")
108 }
109 crate::Error::OutputTooLarge { limit, .. } => {
110 format!("{binary} output exceeded the {limit} byte safety limit")
111 }
112 crate::Error::Timeout(milliseconds) => {
113 format!("{binary} timed out after {milliseconds} ms")
114 }
115 other => format!("{binary} process failed: {other}"),
116 }
117}
118
119#[cfg(test)]
120mod tests {
121 use super::*;
122 use std::time::Instant;
123
124 thread_local! {
125 pub(super) static PATH_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
126 }
127
128 #[test]
129 fn helper_commands_are_bounded_by_output_limits_and_deadlines() {
130 {
131 assert!(which("head"), "head is required for the output-limit probe");
132 let bytes = (MAX_CAPTURE_BYTES + 4096).to_string();
133 let args = ["-c", bytes.as_str(), "/dev/zero"];
134 let capture = run_capture_within("head", &args, tilo_test_env::hang_bound())
136 .expect_err("oversized stdout must be rejected");
137 assert!(capture.contains("output exceeded"), "{capture}");
138 }
139 {
142 assert!(
145 which("sleep"),
146 "`sleep` is required to exercise the run_capture deadline"
147 );
148 let over = tilo_test_env::hang_bound().as_secs() * 2;
151 let arg = format!("{over}");
152 let started = Instant::now();
153 let result = run_capture("sleep", &[arg.as_str()]);
154 let elapsed = started.elapsed();
155
156 let err = result.expect_err("a command outliving the deadline must not report success");
157 assert!(
158 err.contains("timed out"),
159 "expected a timeout error, got: {err}"
160 );
161 assert!(
162 elapsed < tilo_test_env::hang_bound(),
163 "run_capture returned after {elapsed:?}; its {DEFAULT_TIMEOUT:?} kill path did \
164 not fire"
165 );
166 }
167 }
168
169 #[test]
170 fn which_resolves_from_path_memoised_and_reports_missing_binaries() {
171 {
174 assert!(
175 which("sh"),
176 "`sh` is on $PATH in every environment this runs in; a probe \
177 that cannot see it is answering about itself"
178 );
179 assert!(
180 !which("tilo-no-such-binary-should-ever-exist"),
181 "a name that is on no $PATH entry must not be reported as found"
182 );
183 assert!(which("/bin/sh") || which("/usr/bin/sh"));
185 assert!(!which("/definitely/not/here/sh"));
186 assert!(!which(""), "the empty name is not a binary");
187 }
188 {
191 let first = which("sh");
192 let looked = PATH_LOOKUPS.with(std::cell::Cell::get);
193 for _ in 0..200 {
194 assert_eq!(which("sh"), first);
195 }
196 let lookups = PATH_LOOKUPS.with(std::cell::Cell::get) - looked;
197 assert_eq!(
198 lookups, 0,
199 "200 memoised probes looked up $PATH {lookups} times"
200 );
201 }
202 {
205 let r = run("definitely-not-a-real-binary-tilo-test", &["--help"]);
206 assert!(r.is_err());
207 let msg = r.unwrap_err();
208 assert!(msg.contains("not installed"), "got: {msg}");
209 }
210 }
211}