strands/sandbox/
posix_shell.rs1use 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
20pub 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
36pub 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#[async_trait]
128pub trait PosixShellSandbox: Send + Sync + 'static {
129 fn execute_streaming(&self, command: &str, options: ExecuteOptions) -> ExecutionStream;
131
132 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 async fn read_file(&self, path: &str) -> Result<Vec<u8>> {
148 let quoted = shell_quote(path);
149 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 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 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 async fn list_files(&self, path: &str) -> Result<Vec<FileInfo>> {
193 let quoted = shell_quote(path);
194 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 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
254pub(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;