Skip to main content

strands/sandbox/
constants.rs

1//! Validation patterns and shell quoting shared by the sandboxes.
2
3/// The pattern a language or interpreter name must match (`LANGUAGE_PATTERN`): letters, digits,
4/// dots, hyphens and underscores. Path separators, spaces and shell metacharacters are rejected.
5pub const LANGUAGE_PATTERN: &str = "^[a-zA-Z0-9._-]+$";
6
7/// The pattern an environment variable name must match (`ENV_KEY_PATTERN`): a letter or
8/// underscore, then letters, digits or underscores (POSIX names).
9pub const ENV_KEY_PATTERN: &str = "^[a-zA-Z_][a-zA-Z0-9_]*$";
10
11/// Whether `language` matches [`LANGUAGE_PATTERN`].
12pub(crate) fn is_valid_language(language: &str) -> bool {
13    !language.is_empty()
14        && language
15            .bytes()
16            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
17}
18
19/// Whether `key` matches [`ENV_KEY_PATTERN`].
20pub(crate) fn is_valid_env_key(key: &str) -> bool {
21    let mut bytes = key.bytes();
22    let Some(first) = bytes.next() else {
23        return false;
24    };
25    (first.is_ascii_alphabetic() || first == b'_') && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
26}
27
28/// Shell-escapes a value for a POSIX shell command.
29///
30/// Wraps the value in single quotes and escapes embedded single quotes as `'\''`. Single quotes
31/// disable every expansion (variables, backticks, globbing).
32///
33/// ```
34/// use strands::sandbox::shell_quote;
35///
36/// assert_eq!(shell_quote("it's"), r"'it'\''s'");
37/// ```
38#[must_use]
39pub fn shell_quote(value: &str) -> String {
40    format!("'{}'", value.replace('\'', r"'\''"))
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn language_pattern_accepts_interpreter_names_only() {
49        for valid in ["python3", "node", "fake-lang.99", "py_thon"] {
50            assert!(is_valid_language(valid), "{valid}");
51        }
52        for invalid in ["", "../../bin/sh", "python;rm -rf /", "python -c", "pythön"] {
53            assert!(!is_valid_language(invalid), "{invalid}");
54        }
55    }
56
57    #[test]
58    fn env_key_pattern_accepts_posix_names_only() {
59        for valid in ["FOO", "_foo", "F00_BAR"] {
60            assert!(is_valid_env_key(valid), "{valid}");
61        }
62        for invalid in ["", "1FOO", "BAD-KEY", "BAD KEY", "FÖO"] {
63            assert!(!is_valid_env_key(invalid), "{invalid}");
64        }
65    }
66
67    #[test]
68    fn shell_quote_wraps_in_single_quotes_and_escapes_them() {
69        assert_eq!(shell_quote("with spaces"), "'with spaces'");
70        assert_eq!(shell_quote("$(whoami)"), "'$(whoami)'");
71        assert_eq!(shell_quote("it's"), r"'it'\''s'");
72        assert_eq!(shell_quote(""), "''");
73    }
74}