Skip to main content

strands/sandbox/
posix_shell.rs

1//! A sandbox built on a POSIX shell.
2
3use std::sync::Arc;
4
5use async_trait::async_trait;
6use base64::Engine;
7use base64::engine::general_purpose::STANDARD;
8use futures::stream;
9
10use crate::error::{Error, Result, SandboxIsADirectoryError, SandboxPathNotFoundError, SandboxPermissionError};
11use crate::sandbox::base::{ExecuteOptions, ExecutionStream, Sandbox, final_result};
12use crate::sandbox::constants::{is_valid_env_key, is_valid_language, shell_quote};
13use crate::sandbox::types::FileInfo;
14use crate::tools::Tool;
15
16const MISSING_EXIT_CODE: i32 = 77;
17const DIRECTORY_EXIT_CODE: i32 = 78;
18const PERMISSION_EXIT_CODE: i32 = 79;
19
20/// Checks environment variable names against
21/// [`ENV_KEY_PATTERN`](crate::sandbox::ENV_KEY_PATTERN).
22///
23/// Backends that set the environment through process flags call this before passing the values
24/// on.
25///
26/// # Errors
27///
28/// `Invalid environment variable name: <key>` for the first invalid name.
29pub fn validate_env_keys(env: &[(String, String)]) -> Result<()> {
30    match env.iter().map(|(key, _)| key).find(|key| !is_valid_env_key(key)) {
31        Some(key) => Err(Error::other(format!("Invalid environment variable name: {key}"))),
32        None => Ok(()),
33    }
34}
35
36/// Builds the `export KEY='value' && ` prefix that applies `env` to a shell command, or `""`
37/// when there is none.
38///
39/// `export` (rather than an `env KEY=value` wrapper) sets the variables in the shell itself, so
40/// every stage of a pipeline inherits them, including the interpreter of
41/// [`execute_code_streaming`](Sandbox::execute_code_streaming). Values are
42/// [`shell_quote`](crate::sandbox::shell_quote)d; the trailing `&&` keeps a surrounding
43/// `cd ... && <prefix><command>` chain fail-fast.
44///
45/// ```
46/// use strands::sandbox::build_shell_env_prefix;
47///
48/// let env = [("FOO".to_owned(), "bar".to_owned())];
49/// assert_eq!(build_shell_env_prefix(Some(&env[..]))?, "export FOO='bar' && ");
50/// assert_eq!(build_shell_env_prefix(None)?, "");
51/// # Ok::<_, strands::Error>(())
52/// ```
53///
54/// # Errors
55///
56/// As [`validate_env_keys`].
57pub fn build_shell_env_prefix(env: Option<&[(String, String)]>) -> Result<String> {
58    let Some(env) = env.filter(|env| !env.is_empty()) else {
59        return Ok(String::new());
60    };
61    validate_env_keys(env)?;
62    let assignments: Vec<String> = env
63        .iter()
64        .map(|(key, value)| format!("{key}={}", shell_quote(value)))
65        .collect();
66    Ok(format!("export {} && ", assignments.join(" ")))
67}
68
69/// A sandbox where only a POSIX shell is available, such as a container, an SSH connection or a
70/// cloud runtime (`PosixShellSandbox`).
71///
72/// Implementors supply [`execute_streaming`](PosixShellSandbox::execute_streaming); code
73/// execution and the file operations run as shell commands through it. Override any of them
74/// with a native implementation where the backend has one. Every `PosixShellSandbox` is a
75/// [`Sandbox`].
76///
77/// `execute_streaming` must apply `options.env`: backends that build a shell command prepend
78/// [`build_shell_env_prefix`]; backends that pass the environment through process flags call
79/// [`validate_env_keys`] and pass the values on.
80///
81/// Call the operations through [`Sandbox`] (or a `dyn Sandbox`); with both traits in scope a
82/// method call on the implementing type is ambiguous.
83///
84/// ```no_run
85/// use std::process::Stdio;
86///
87/// use strands::sandbox::{
88///     ExecuteOptions, ExecutionResult, ExecutionStream, ExecutionStreamItem, PosixShellSandbox,
89///     Sandbox, build_shell_env_prefix, shell_quote,
90/// };
91/// use strands::Error;
92///
93/// /// Runs commands in a running container through `docker exec`.
94/// struct Container {
95///     name: String,
96/// }
97///
98/// impl PosixShellSandbox for Container {
99///     fn execute_streaming(&self, command: &str, options: ExecuteOptions) -> ExecutionStream {
100///         let prefix = build_shell_env_prefix(options.env.as_deref());
101///         let cwd = options.cwd.unwrap_or_else(|| "/".to_owned());
102///         let name = self.name.clone();
103///         let command = command.to_owned();
104///         Box::pin(futures::stream::once(async move {
105///             let script = format!("cd {} && {}{command}", shell_quote(&cwd), prefix?);
106///             let output = tokio::process::Command::new("docker")
107///                 .args(["exec", &name, "sh", "-c", &script])
108///                 .stdin(Stdio::null())
109///                 .output()
110///                 .await?;
111///             let result = ExecutionResult::new(
112///                 output.status.code().unwrap_or(1),
113///                 String::from_utf8_lossy(&output.stdout),
114///                 String::from_utf8_lossy(&output.stderr),
115///             );
116///             Ok::<_, Error>(ExecutionStreamItem::from(result))
117///         }))
118///     }
119/// }
120///
121/// # async fn demo() -> strands::Result<()> {
122/// let sandbox = Container { name: "dev".to_owned() };
123/// let _hostname = Sandbox::read_text(&sandbox, "/etc/hostname").await?;
124/// # Ok(())
125/// # }
126/// ```
127#[async_trait]
128pub trait PosixShellSandbox: Send + Sync + 'static {
129    /// Runs a shell command, streaming its output. See [`Sandbox::execute_streaming`].
130    fn execute_streaming(&self, command: &str, options: ExecuteOptions) -> ExecutionStream;
131
132    /// Pipes base64-encoded `code` into the interpreter through
133    /// [`execute_streaming`](PosixShellSandbox::execute_streaming). See
134    /// [`Sandbox::execute_code_streaming`].
135    fn execute_code_streaming(&self, code: &str, language: &str, options: ExecuteOptions) -> ExecutionStream {
136        if !is_valid_language(language) {
137            return error_stream(invalid_language(language));
138        }
139        let eof = heredoc_delimiter();
140        let encoded = STANDARD.encode(code);
141        let command = format!("base64 -d << '{eof}' | {language}\n{encoded}\n{eof}");
142        self.execute_streaming(&command, options)
143    }
144
145    /// Reads a file through `base64`, with exit codes that tell a missing path, a directory and
146    /// a permission failure apart. See [`Sandbox::read_file`].
147    async fn read_file(&self, path: &str) -> Result<Vec<u8>> {
148        let quoted = shell_quote(path);
149        // Locale-independent exit codes: 77 = missing, 78 = directory, 79 = permission denied.
150        // `test -e` is also false under an unsearchable ancestor, so the deepest existing one is
151        // checked. The braces keep a backend's `cd ... &&` prefix out of the `||`.
152        let command = format!(
153            "{{ test -e {quoted} || {{ p={quoted}; while p=$(dirname -- \"$p\"); ! test -d \"$p\"; do :; done; \
154             test -x \"$p\" || exit 79; exit 77; }}; \
155             test -r {quoted} || exit 79; test -d {quoted} && exit 78; base64 < {quoted}; }}"
156        );
157        let result = run(self, &command).await?;
158        match result.exit_code {
159            0 => decode_base64(&result.stdout),
160            MISSING_EXIT_CODE => Err(SandboxPathNotFoundError::new(path).into()),
161            DIRECTORY_EXIT_CODE => Err(SandboxIsADirectoryError::new(path).into()),
162            PERMISSION_EXIT_CODE => Err(SandboxPermissionError::new(path).into()),
163            _ => Err(failure(result.stderr, format!("Failed to read file: {path}"))),
164        }
165    }
166
167    /// Writes a file through `base64 -d`, creating parent directories with `mkdir -p`. See
168    /// [`Sandbox::write_file`].
169    async fn write_file(&self, path: &str, content: &[u8]) -> Result<()> {
170        let quoted = shell_quote(path);
171        let eof = heredoc_delimiter();
172        let encoded = STANDARD.encode(content);
173        let command = format!("mkdir -p \"$(dirname {quoted})\" && base64 -d << '{eof}' > {quoted}\n{encoded}\n{eof}");
174        let result = run(self, &command).await?;
175        if result.exit_code != 0 {
176            return Err(failure(result.stderr, format!("Failed to write file: {path}")));
177        }
178        Ok(())
179    }
180
181    /// Removes a file with `rm`. See [`Sandbox::remove_file`].
182    async fn remove_file(&self, path: &str) -> Result<()> {
183        let result = run(self, &format!("rm {}", shell_quote(path))).await?;
184        if result.exit_code != 0 {
185            return Err(failure(result.stderr, format!("Failed to remove file: {path}")));
186        }
187        Ok(())
188    }
189
190    /// Lists a directory by parsing `ls -1ap`. Entries carry `is_dir` but no size. See
191    /// [`Sandbox::list_files`].
192    async fn list_files(&self, path: &str) -> Result<Vec<FileInfo>> {
193        let quoted = shell_quote(path);
194        // Exit 77 tells a missing directory apart from ls's own failures, independent of locale.
195        let command = format!("test -d {quoted} || exit 77; env QUOTING_STYLE=literal ls -1ap {quoted}");
196        let result = run(self, &command).await?;
197        if result.exit_code == MISSING_EXIT_CODE {
198            return Err(SandboxPathNotFoundError::new(path).into());
199        }
200        if result.exit_code != 0 {
201            return Err(failure(result.stderr, format!("Failed to list directory: {path}")));
202        }
203        Ok(result.stdout.split('\n').filter_map(parse_ls_line).collect())
204    }
205
206    /// Tools this sandbox vends to an agent. See [`Sandbox::get_tools`].
207    fn get_tools(&self) -> Vec<Arc<dyn Tool>> {
208        Vec::new()
209    }
210}
211
212#[async_trait]
213impl<T: PosixShellSandbox + ?Sized> Sandbox for T {
214    fn execute_streaming(&self, command: &str, options: ExecuteOptions) -> ExecutionStream {
215        PosixShellSandbox::execute_streaming(self, command, options)
216    }
217
218    fn execute_code_streaming(&self, code: &str, language: &str, options: ExecuteOptions) -> ExecutionStream {
219        PosixShellSandbox::execute_code_streaming(self, code, language, options)
220    }
221
222    async fn read_file(&self, path: &str) -> Result<Vec<u8>> {
223        PosixShellSandbox::read_file(self, path).await
224    }
225
226    async fn write_file(&self, path: &str, content: &[u8]) -> Result<()> {
227        PosixShellSandbox::write_file(self, path, content).await
228    }
229
230    async fn remove_file(&self, path: &str) -> Result<()> {
231        PosixShellSandbox::remove_file(self, path).await
232    }
233
234    async fn list_files(&self, path: &str) -> Result<Vec<FileInfo>> {
235        PosixShellSandbox::list_files(self, path).await
236    }
237
238    fn get_tools(&self) -> Vec<Arc<dyn Tool>> {
239        PosixShellSandbox::get_tools(self)
240    }
241}
242
243async fn run<S: PosixShellSandbox + ?Sized>(
244    sandbox: &S,
245    command: &str,
246) -> Result<crate::sandbox::types::ExecutionResult> {
247    final_result(
248        PosixShellSandbox::execute_streaming(sandbox, command, ExecuteOptions::default()),
249        "execute_streaming",
250    )
251    .await
252}
253
254/// A here-document delimiter that cannot occur in base64 text (`STRANDS_EOF_` and 16 characters
255/// of a random UUID).
256pub(crate) fn heredoc_delimiter() -> String {
257    let id: String = uuid::Uuid::new_v4().to_string().chars().take(16).collect();
258    format!("STRANDS_EOF_{id}")
259}
260
261pub(crate) fn invalid_language(language: &str) -> Error {
262    Error::other(format!("language parameter contains invalid characters: {language}"))
263}
264
265pub(crate) fn error_stream(error: Error) -> ExecutionStream {
266    Box::pin(stream::iter([Err(error)]))
267}
268
269fn failure(stderr: String, fallback: String) -> Error {
270    Error::other(if stderr.is_empty() { fallback } else { stderr })
271}
272
273fn decode_base64(text: &str) -> Result<Vec<u8>> {
274    let compact: String = text.chars().filter(|c| !c.is_whitespace()).collect();
275    STANDARD.decode(compact).map_err(Error::other)
276}
277
278fn parse_ls_line(raw: &str) -> Option<FileInfo> {
279    let line = raw.strip_suffix('\r').unwrap_or(raw);
280    if line.is_empty() || line == "./" || line == "../" {
281        return None;
282    }
283    let (name, is_dir) = match line.strip_suffix('/') {
284        Some(name) => (name, true),
285        None => (line, false),
286    };
287    (!name.is_empty()).then(|| FileInfo::new(name).with_is_dir(is_dir))
288}
289
290#[cfg(test)]
291mod tests;