Skip to main content

openmoat_core/policy/
env_name.rs

1//! `openmoat run`'s environment settings: whether it passes on the whole
2//! environment it is started from or only an allowlist (`sandbox.env`,
3//! ADR-105), and the form of a name a person may add to that allowlist
4//! (ADR-077): a name, never a value or a pattern, so nothing can be written
5//! that lets every variable through.
6
7use serde::{Deserialize, Serialize};
8
9/// `sandbox.env` (ADR-105): what `openmoat run` passes on of the environment
10/// it is started from. Absent, the default, which is [`RunEnv::DEFAULT`].
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(rename_all = "lowercase")]
13pub enum RunEnv {
14    /// Every inherited variable, a brokered secret's excepted.
15    Inherited,
16    /// Only the allowlist: a base every program needs, the agent's own names
17    /// from its spec, `sandbox.env_allow` and `--env`.
18    Scrubbed,
19}
20
21impl RunEnv {
22    /// What `openmoat run` does when no policy says and no flag asks.
23    pub const DEFAULT: Self = Self::Inherited;
24}
25
26/// Why `name` cannot be added to the allowlist; `None` when it can. A name is
27/// a letter or `_`, then letters, digits and `_`.
28#[must_use]
29pub fn env_name_problem(name: &str) -> Option<&'static str> {
30    if name.is_empty() {
31        return Some("must not be empty");
32    }
33    if name.contains('=') {
34        return Some("must be a name, not `NAME=value`");
35    }
36    if name.contains(['*', '?', '[', ']']) {
37        return Some("must be a plain name, not a pattern");
38    }
39    let mut chars = name.chars();
40    let starts_well = chars
41        .next()
42        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_');
43    if starts_well && chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {
44        None
45    } else {
46        Some("must be letters, digits and `_`, not starting with a digit")
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use super::env_name_problem;
53
54    #[test]
55    fn plain_names_are_accepted() {
56        for name in ["PATH", "_", "MY_VAR_2", "lower"] {
57            assert_eq!(env_name_problem(name), None, "{name}");
58        }
59    }
60
61    #[test]
62    fn values_patterns_and_junk_are_refused() {
63        for name in [
64            "", "A=b", "*", "AWS_*", "A?", "[A]", "1A", "A-B", "A B", "A.B",
65        ] {
66            assert!(env_name_problem(name).is_some(), "{name}");
67        }
68    }
69}