Skip to main content

strands/sandbox/
not_a_sandbox_local_environment.rs

1//! The host as a sandbox, with no isolation.
2
3use std::cmp::Ordering;
4use std::ffi::OsString;
5use std::io::ErrorKind;
6use std::path::{Path, PathBuf};
7
8use async_trait::async_trait;
9use base64::Engine;
10use base64::engine::general_purpose::STANDARD;
11
12use crate::error::{Error, Result, SandboxIsADirectoryError, SandboxPathNotFoundError, SandboxPermissionError};
13use crate::sandbox::base::{ExecuteOptions, ExecutionStream, Sandbox};
14use crate::sandbox::constants::{is_valid_language, shell_quote};
15use crate::sandbox::posix_shell::{
16    build_shell_env_prefix, error_stream, heredoc_delimiter, invalid_language, validate_env_keys,
17};
18use crate::sandbox::stream_process::{StreamProcessOptions, stream_process};
19use crate::sandbox::types::FileInfo;
20
21const POWERSHELL: &str = "powershell.exe";
22const POWERSHELL_NOT_FOUND: &str = "PowerShell not found: powershell.exe is required to run commands on Windows";
23
24/// Runs commands and file operations directly on the host, with no isolation
25/// (`NotASandboxLocalEnvironment`). The agent's default when no sandbox is configured.
26///
27/// Commands run in `sh -c` on POSIX systems and in Windows PowerShell on Windows. Relative paths
28/// resolve against the process's current directory, and so does a command without a `cwd`.
29///
30/// ```no_run
31/// use strands::sandbox::{ExecuteOptions, NotASandboxLocalEnvironment, Sandbox};
32///
33/// # async fn demo() -> strands::Result<()> {
34/// let host = NotASandboxLocalEnvironment::new();
35/// let result = host.execute("echo hello", ExecuteOptions::default()).await?;
36/// assert_eq!(result.stdout.trim(), "hello");
37/// # Ok(())
38/// # }
39/// ```
40#[derive(Debug, Clone, Copy, Default)]
41#[non_exhaustive]
42pub struct NotASandboxLocalEnvironment {}
43
44impl NotASandboxLocalEnvironment {
45    /// Creates the local environment.
46    #[must_use]
47    pub fn new() -> Self {
48        Self {}
49    }
50}
51
52#[async_trait]
53impl Sandbox for NotASandboxLocalEnvironment {
54    fn execute_streaming(&self, command: &str, options: ExecuteOptions) -> ExecutionStream {
55        let cwd = match resolve_cwd(options.cwd) {
56            Ok(cwd) => cwd,
57            Err(error) => return error_stream(error),
58        };
59        if cfg!(windows) {
60            // No `sh` on Windows: cwd and env go through the spawn, not a shell prefix.
61            let env = match windows_env(options.env.as_deref()) {
62                Ok(env) => env,
63                Err(error) => return error_stream(error),
64            };
65            let process_options = StreamProcessOptions {
66                timeout: options.timeout,
67                signal: options.signal,
68                enoent_message: Some(POWERSHELL_NOT_FOUND.to_owned()),
69                cwd: Some(cwd),
70                env: Some(env),
71                input: None,
72            };
73            return stream_process(POWERSHELL, powershell_args(command), process_options);
74        }
75        let prefix = match build_shell_env_prefix(options.env.as_deref()) {
76            Ok(prefix) => prefix,
77            Err(error) => return error_stream(error),
78        };
79        let script = format!("cd {} && {prefix}{command}", shell_quote(&cwd));
80        let process_options = StreamProcessOptions {
81            timeout: options.timeout,
82            signal: options.signal,
83            ..StreamProcessOptions::default()
84        };
85        stream_process("sh", vec!["-c".to_owned(), script], process_options)
86    }
87
88    fn execute_code_streaming(&self, code: &str, language: &str, options: ExecuteOptions) -> ExecutionStream {
89        if !is_valid_language(language) {
90            return error_stream(invalid_language(language));
91        }
92        let cwd = match resolve_cwd(options.cwd) {
93            Ok(cwd) => cwd,
94            Err(error) => return error_stream(error),
95        };
96        let enoent_message = Some(format!("Language interpreter not found: {language}"));
97        if cfg!(windows) {
98            // No shell involved: the interpreter is spawned directly and reads the code from stdin.
99            let env = match windows_env(options.env.as_deref()) {
100                Ok(env) => env,
101                Err(error) => return error_stream(error),
102            };
103            let process_options = StreamProcessOptions {
104                timeout: options.timeout,
105                signal: options.signal,
106                enoent_message,
107                cwd: Some(cwd),
108                env: Some(env),
109                input: Some(code.to_owned()),
110            };
111            return stream_process(language, Vec::new(), process_options);
112        }
113        let prefix = match build_shell_env_prefix(options.env.as_deref()) {
114            Ok(prefix) => prefix,
115            Err(error) => return error_stream(error),
116        };
117        let eof = heredoc_delimiter();
118        let encoded = STANDARD.encode(code);
119        let script = format!(
120            "cd {} && {prefix}base64 -d << '{eof}' | {language}\n{encoded}\n{eof}",
121            shell_quote(&cwd)
122        );
123        let process_options = StreamProcessOptions {
124            timeout: options.timeout,
125            signal: options.signal,
126            enoent_message,
127            ..StreamProcessOptions::default()
128        };
129        stream_process("sh", vec!["-c".to_owned(), script], process_options)
130    }
131
132    async fn read_file(&self, path: &str) -> Result<Vec<u8>> {
133        let full_path = resolve_path(path)?;
134        match tokio::fs::read(&full_path).await {
135            Ok(content) => Ok(content),
136            Err(error) if cfg!(windows) && is_directory(&full_path).await => {
137                Err(SandboxIsADirectoryError::new(path).with_source(error).into())
138            }
139            Err(error) => Err(read_error(path, error)),
140        }
141    }
142
143    async fn write_file(&self, path: &str, content: &[u8]) -> Result<()> {
144        let full_path = resolve_path(path)?;
145        if let Some(parent) = full_path.parent() {
146            tokio::fs::create_dir_all(parent).await?;
147        }
148        tokio::fs::write(&full_path, content).await?;
149        Ok(())
150    }
151
152    async fn remove_file(&self, path: &str) -> Result<()> {
153        tokio::fs::remove_file(resolve_path(path)?).await?;
154        Ok(())
155    }
156
157    async fn list_files(&self, path: &str) -> Result<Vec<FileInfo>> {
158        let full_path = resolve_path(path)?;
159        let mut entries = tokio::fs::read_dir(&full_path)
160            .await
161            .map_err(|error| list_error(path, error))?;
162        let mut names = Vec::new();
163        while let Some(entry) = entries.next_entry().await? {
164            names.push(entry.file_name().to_string_lossy().into_owned());
165        }
166        names.sort_by(|a, b| locale_compare(a, b));
167        let mut results = Vec::with_capacity(names.len());
168        for name in names {
169            results.push(file_info(&full_path, name).await);
170        }
171        Ok(results)
172    }
173}
174
175async fn file_info(directory: &Path, name: String) -> FileInfo {
176    match tokio::fs::metadata(directory.join(&name)).await {
177        Ok(metadata) => FileInfo::new(name)
178            .with_is_dir(metadata.is_dir())
179            .with_size(metadata.len()),
180        Err(_) => FileInfo::new(name),
181    }
182}
183
184/// Whether a failed read hit a directory. Windows reports that as access denied, or as not found
185/// when the path ends in a separator.
186async fn is_directory(path: &Path) -> bool {
187    tokio::fs::metadata(path).await.is_ok_and(|metadata| metadata.is_dir())
188}
189
190fn resolve_path(path: &str) -> Result<PathBuf> {
191    let path = Path::new(path);
192    if path.is_absolute() {
193        return Ok(path.to_path_buf());
194    }
195    Ok(std::env::current_dir()?.join(path))
196}
197
198fn resolve_cwd(cwd: Option<String>) -> Result<String> {
199    match cwd {
200        Some(cwd) => Ok(cwd),
201        None => Ok(std::env::current_dir()?.to_string_lossy().into_owned()),
202    }
203}
204
205/// A missing entry or a file where a directory was expected.
206fn is_missing_path(error: &std::io::Error) -> bool {
207    matches!(error.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory)
208}
209
210fn read_error(path: &str, error: std::io::Error) -> Error {
211    if is_missing_path(&error) {
212        return SandboxPathNotFoundError::new(path).with_source(error).into();
213    }
214    match error.kind() {
215        ErrorKind::IsADirectory => SandboxIsADirectoryError::new(path).with_source(error).into(),
216        ErrorKind::PermissionDenied => SandboxPermissionError::new(path).with_source(error).into(),
217        _ => error.into(),
218    }
219}
220
221fn list_error(path: &str, error: std::io::Error) -> Error {
222    if is_missing_path(&error) {
223        return SandboxPathNotFoundError::new(path).with_source(error).into();
224    }
225    error.into()
226}
227
228/// Orders names the way a locale-aware comparison usually does: letters case-insensitively first,
229/// then lowercase before uppercase.
230fn locale_compare(a: &str, b: &str) -> Ordering {
231    a.to_lowercase().cmp(&b.to_lowercase()).then_with(|| b.cmp(a))
232}
233
234/// The argv that runs `command` in Windows PowerShell.
235///
236/// `-EncodedCommand` (base64 of UTF-16LE) carries the script without command-line quoting; it
237/// inflates the text 2.67x against Windows' 32,767-character limit, so commands over about 12 KB
238/// fail to spawn. The wrapper makes output UTF-8 (5.1 defaults to the OEM code page) and mirrors
239/// `sh -c`'s exit code: the last statement's success, or the failing native command's own code.
240/// `$ErrorActionPreference` is left alone because `Stop` turns native stderr output into a
241/// terminating error.
242pub(crate) fn powershell_args(command: &str) -> Vec<String> {
243    let script = [
244        "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8",
245        "$OutputEncoding = [System.Text.UTF8Encoding]::new($false)",
246        command,
247        "$ok = $?",
248        "if (-not $ok) { if ($LASTEXITCODE) { exit $LASTEXITCODE } else { exit 1 } }",
249    ]
250    .join("\n");
251    vec![
252        "-NoProfile".to_owned(),
253        "-NonInteractive".to_owned(),
254        "-EncodedCommand".to_owned(),
255        encode_utf16le_base64(&script),
256    ]
257}
258
259pub(crate) fn encode_utf16le_base64(text: &str) -> String {
260    let bytes: Vec<u8> = text.encode_utf16().flat_map(u16::to_le_bytes).collect();
261    STANDARD.encode(bytes)
262}
263
264fn windows_env(extra: Option<&[(String, String)]>) -> Result<Vec<(OsString, OsString)>> {
265    if let Some(extra) = extra {
266        validate_env_keys(extra)?;
267    }
268    Ok(env_with(std::env::vars_os(), extra))
269}
270
271/// `host` with `extra` applied. Windows names are case-insensitive, so `PATH` replaces `Path`.
272pub(crate) fn env_with(
273    host: impl IntoIterator<Item = (OsString, OsString)>,
274    extra: Option<&[(String, String)]>,
275) -> Vec<(OsString, OsString)> {
276    let mut env: Vec<(OsString, OsString)> = host.into_iter().collect();
277    for (key, value) in extra.into_iter().flatten() {
278        let lowered = key.to_lowercase();
279        env.retain(|(existing, _)| existing.to_string_lossy().to_lowercase() != lowered);
280        env.push((key.into(), value.into()));
281    }
282    env
283}
284
285#[cfg(test)]
286mod tests;