Skip to main content

base/interface/exec/
env.rs

1//! The environment a child process on this machine starts from.
2//!
3//! Every program the engine launches — a `Bash` / `Monitor` command, a command
4//! hook, an MCP stdio server, the engine's own git and `pdftotext` — gets its
5//! environment from here, so that what a model can read with `printenv` is
6//! decided in one place. The engine's own credentials never pass by default;
7//! everything else does unless the operator switches to an allowlist.
8//!
9//! Which variables are credentials is decided where configuration names them:
10//! a settings file, a plugin, the MCP policy or the host each report the
11//! variables they read a secret from ([`hold_back_credential`]) before any
12//! child starts under them.
13
14use std::collections::BTreeSet;
15use std::ffi::{OsStr, OsString};
16
17#[derive(
18    Debug,
19    Clone,
20    Copy,
21    Default,
22    PartialEq,
23    Eq,
24    serde::Serialize,
25    serde::Deserialize,
26    schemars::JsonSchema,
27)]
28#[serde(rename_all = "snake_case")]
29pub enum SubprocessEnvMode {
30    /// The host's environment, minus the engine's own credentials.
31    #[default]
32    Inherit,
33    /// Only the variables a shell needs to work, plus `allow`.
34    Allowlist,
35}
36
37/// `sandbox.env` in settings.json.
38#[derive(
39    Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
40)]
41pub struct SubprocessEnv {
42    #[serde(default)]
43    pub mode: SubprocessEnvMode,
44    /// Variables passed through whatever the mode would do with them — in
45    /// `allowlist` mode the extra names to keep, in `inherit` mode a way to
46    /// hand one of the engine's own credentials (a provider's `api_key_env`,
47    /// a variable an MCP server's configuration reads) to every child on
48    /// purpose.
49    #[serde(default, skip_serializing_if = "Vec::is_empty")]
50    pub allow: Vec<String>,
51}
52
53/// What `allowlist` mode keeps without being asked.
54const BASELINE: &[&str] = &[
55    "PATH",
56    "HOME",
57    "USER",
58    "LOGNAME",
59    "SHELL",
60    "TERM",
61    "LANG",
62    "LC_ALL",
63    "LC_CTYPE",
64    "TMPDIR",
65    "TZ",
66    #[cfg(windows)]
67    "SYSTEMROOT",
68    #[cfg(windows)]
69    "COMSPEC",
70    #[cfg(windows)]
71    "PATHEXT",
72    #[cfg(windows)]
73    "TEMP",
74    #[cfg(windows)]
75    "TMP",
76    #[cfg(windows)]
77    "USERPROFILE",
78    #[cfg(windows)]
79    "APPDATA",
80    #[cfg(windows)]
81    "LOCALAPPDATA",
82];
83
84/// Environment variables the engine has been told hold a secret: a
85/// provider's `api_key_env`, what an MCP server's configuration reads
86/// ([`variables_an_mcp_server_reads`]), the enterprise IdP's
87/// `client_secret_env`, the OTLP exporter's headers. Only ever grows: a
88/// settings reload adds what the new files name, and a name the files stop
89/// naming still holds the same secret in this process's environment.
90static NAMED_CREDENTIALS: std::sync::RwLock<BTreeSet<String>> =
91    std::sync::RwLock::new(BTreeSet::new());
92
93/// From now on, treat the variable `name` as one of the engine's own
94/// credentials: no child process inherits it unless a policy's `allow` names
95/// it. Process-wide, because the environment children inherit from is. The
96/// variables a shell cannot work without are never held back, whatever a
97/// settings file names.
98pub fn hold_back_credential(name: &str) {
99    if name.is_empty() || BASELINE.contains(&name) {
100        return;
101    }
102    let mut named = NAMED_CREDENTIALS
103        .write()
104        .unwrap_or_else(std::sync::PoisonError::into_inner);
105    named.insert(name.to_string());
106}
107
108/// The engine's own credentials: the `ANTHROPIC_*` variables, the daemon's
109/// bearer token, and whatever [`hold_back_credential`] was told.
110pub fn is_engine_credential(name: &OsStr) -> bool {
111    let name = name.to_string_lossy();
112    name.starts_with("ANTHROPIC_")
113        || name == "AGIX_DAEMON_TOKEN"
114        || NAMED_CREDENTIALS
115            .read()
116            .unwrap_or_else(std::sync::PoisonError::into_inner)
117            .contains(name.as_ref())
118}
119
120/// The variables `input` refers to as `$VAR`, `${VAR}` or `${VAR:-…}`.
121pub fn referenced_vars(input: &str) -> Vec<String> {
122    let named = std::cell::RefCell::new(Vec::new());
123    expand_vars_with(input, |name| {
124        named.borrow_mut().push(name.to_string());
125        None
126    });
127    named.into_inner()
128}
129
130/// The variables of this process's environment an `mcp_servers` entry reads
131/// when it connects: every `$VAR` in its `command`, `args`, `env`, `url` and
132/// `headers`, and the variables its `oauth` block names
133/// (`client_secret_env`, `private_key_jwt.key_env`).
134pub fn variables_an_mcp_server_reads(server: &serde_json::Value) -> Vec<String> {
135    use serde_json::Value;
136    let field = |key: &str| server.get(key);
137    let strings = ["command", "url"]
138        .into_iter()
139        .filter_map(|key| field(key)?.as_str())
140        .chain(
141            field("args")
142                .and_then(Value::as_array)
143                .into_iter()
144                .flatten()
145                .filter_map(Value::as_str),
146        )
147        .chain(
148            ["env", "headers"]
149                .into_iter()
150                .filter_map(|key| field(key)?.as_object())
151                .flatten()
152                .filter_map(|(_, v)| v.as_str()),
153        );
154    let mut names: Vec<String> = strings.flat_map(referenced_vars).collect();
155    let oauth = field("oauth");
156    names.extend(
157        [
158            oauth.and_then(|o| o.get("client_secret_env")),
159            oauth
160                .and_then(|o| o.get("private_key_jwt"))
161                .and_then(|k| k.get("key_env")),
162        ]
163        .into_iter()
164        .flatten()
165        .filter_map(Value::as_str)
166        .map(str::to_string),
167    );
168    names
169}
170
171/// [`hold_back_credential`] for every variable
172/// [`variables_an_mcp_server_reads`] finds in `server`.
173pub fn hold_back_what_an_mcp_server_reads(server: &serde_json::Value) {
174    for name in variables_an_mcp_server_reads(server) {
175        hold_back_credential(&name);
176    }
177}
178
179/// Expand `$VAR`, `${VAR}`, `${VAR:-default}` (the default when unset or
180/// empty) and `$$` (a literal `$`) in `input`, with the variables `lookup`
181/// gives. A variable it does not give expands to nothing.
182pub fn expand_vars_with(input: &str, lookup: impl Fn(&str) -> Option<String>) -> String {
183    let chars: Vec<char> = input.chars().collect();
184    let mut out = String::with_capacity(input.len());
185    let mut i = 0;
186    while i < chars.len() {
187        let c = chars[i];
188        if c != '$' {
189            out.push(c);
190            i += 1;
191            continue;
192        }
193        if i + 1 >= chars.len() {
194            out.push('$');
195            i += 1;
196            continue;
197        }
198        let next = chars[i + 1];
199        if next == '$' {
200            out.push('$');
201            i += 2;
202            continue;
203        }
204        if next == '{' {
205            let mut end = None;
206            let mut j = i + 2;
207            while j < chars.len() {
208                if chars[j] == '}' {
209                    end = Some(j);
210                    break;
211                }
212                j += 1;
213            }
214            if let Some(j) = end {
215                let body: String = chars[i + 2..j].iter().collect();
216                let (name, default) = match body.split_once(":-") {
217                    Some((n, d)) => (n.to_string(), Some(d.to_string())),
218                    None => (body, None),
219                };
220                match lookup(&name) {
221                    Some(v) if !v.is_empty() => out.push_str(&v),
222                    _ => {
223                        if let Some(d) = default {
224                            out.push_str(&d);
225                        }
226                    }
227                }
228                i = j + 1;
229                continue;
230            }
231            out.push('$');
232            i += 1;
233            continue;
234        }
235        let start = i + 1;
236        let mut j = start;
237        while j < chars.len() {
238            let ch = chars[j];
239            let valid =
240                ch.is_ascii_alphabetic() || ch == '_' || (j > start && ch.is_ascii_alphanumeric());
241            if !valid {
242                break;
243            }
244            j += 1;
245        }
246        if j > start {
247            let name: String = chars[start..j].iter().collect();
248            if let Some(v) = lookup(&name) {
249                out.push_str(&v);
250            }
251            i = j;
252        } else {
253            out.push('$');
254            i += 1;
255        }
256    }
257    out
258}
259
260/// Never inherited: `CDPATH` would make a child shell's `cd foo` reach a
261/// directory outside the project that the permission check, which reads the
262/// literal `foo`, never saw.
263fn never_inherited(name: &OsStr) -> bool {
264    name == "CDPATH"
265}
266
267/// What [`SubprocessEnv::resolve`] decides to do to the environment a child
268/// would otherwise inherit.
269#[derive(Debug, PartialEq, Eq)]
270pub enum EnvPlan {
271    /// Inherit it, minus these.
272    Remove(Vec<OsString>),
273    /// Start from nothing but these.
274    Replace(Vec<(OsString, OsString)>),
275}
276
277/// How much of the environment a process starts from: a mark on a
278/// [`ProcessSpec`](super::ProcessSpec) a provider reads, not a list of
279/// variables, since a remote provider's environment is not this machine's.
280#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
281pub enum EnvScope {
282    /// What `sandbox.env` gives every child.
283    #[default]
284    Session,
285    /// Only what a shell needs to run: `PATH HOME USER LOGNAME SHELL TERM
286    /// LANG LC_* TZ TMPDIR`. `sandbox.env.allow` adds nothing to
287    /// it.
288    Minimal,
289}
290
291const MINIMAL: &[&str] = &[
292    "PATH", "HOME", "USER", "LOGNAME", "SHELL", "TERM", "LANG", "TZ", "TMPDIR",
293];
294
295impl EnvScope {
296    pub fn keeps_under_minimal(name: &OsStr) -> bool {
297        let name = name.to_string_lossy();
298        MINIMAL.contains(&name.as_ref()) || name.starts_with("LC_")
299    }
300}
301
302impl SubprocessEnv {
303    /// [`Self::resolve`] for a child whose spec says `scope`.
304    pub fn resolve_in(
305        &self,
306        scope: EnvScope,
307        host: impl IntoIterator<Item = (OsString, OsString)>,
308    ) -> EnvPlan {
309        match scope {
310            EnvScope::Session => self.resolve(host),
311            EnvScope::Minimal => EnvPlan::Replace(
312                host.into_iter()
313                    .filter(|(name, _)| {
314                        EnvScope::keeps_under_minimal(name)
315                            && !never_inherited(name)
316                            && !is_engine_credential(name)
317                    })
318                    .collect(),
319            ),
320        }
321    }
322
323    /// What a child starting from `host` gets, as the policy says. Applying
324    /// it to a command on this machine is `platform`'s.
325    pub fn resolve(&self, host: impl IntoIterator<Item = (OsString, OsString)>) -> EnvPlan {
326        let allowed = |name: &OsStr| self.allow.iter().any(|a| OsStr::new(a) == name);
327        match self.mode {
328            SubprocessEnvMode::Inherit => EnvPlan::Remove(
329                host.into_iter()
330                    .map(|(name, _)| name)
331                    .filter(|name| {
332                        never_inherited(name) || (is_engine_credential(name) && !allowed(name))
333                    })
334                    .collect(),
335            ),
336            SubprocessEnvMode::Allowlist => EnvPlan::Replace(
337                host.into_iter()
338                    .filter(|(name, _)| {
339                        !never_inherited(name)
340                            && (BASELINE.iter().any(|b| OsStr::new(b) == name) || allowed(name))
341                    })
342                    .collect(),
343            ),
344        }
345    }
346}
347
348#[cfg(test)]
349mod tests {
350    use super::*;
351
352    fn host() -> Vec<(OsString, OsString)> {
353        [
354            ("PATH", "/bin"),
355            ("HOME", "/home/u"),
356            ("ANTHROPIC_API_KEY", "sk-canary"),
357            ("ANTHROPIC_BASE_URL", "https://example"),
358            ("AGIX_DAEMON_TOKEN", "t"),
359            ("GITHUB_TOKEN", "gh"),
360            ("SSH_AUTH_SOCK", "/tmp/agent"),
361            ("CDPATH", "/"),
362        ]
363        .into_iter()
364        .map(|(k, v)| (k.into(), v.into()))
365        .collect()
366    }
367
368    fn names(plan: EnvPlan) -> Vec<String> {
369        let mut names: Vec<String> = match plan {
370            EnvPlan::Remove(n) => n.into_iter().map(|n| n.into_string().unwrap()).collect(),
371            EnvPlan::Replace(v) => v
372                .into_iter()
373                .map(|(n, _)| n.into_string().unwrap())
374                .collect(),
375        };
376        names.sort();
377        names
378    }
379
380    #[test]
381    fn the_minimal_scope_keeps_what_a_shell_needs_and_ignores_allow() {
382        let mut host = host();
383        host.extend([
384            ("LC_MESSAGES".into(), "C".into()),
385            ("EDITOR".into(), "vi".into()),
386        ]);
387        let policy = SubprocessEnv {
388            mode: SubprocessEnvMode::Inherit,
389            allow: vec!["GITHUB_TOKEN".into()],
390        };
391        assert_eq!(
392            names(policy.resolve_in(EnvScope::Minimal, host.clone())),
393            ["HOME", "LC_MESSAGES", "PATH"]
394        );
395        assert_eq!(
396            policy.resolve_in(EnvScope::Session, host.clone()),
397            policy.resolve(host)
398        );
399    }
400
401    #[test]
402    fn inherit_drops_the_engines_credentials_and_cdpath() {
403        let plan = SubprocessEnv::default().resolve(host());
404        assert_eq!(
405            names(plan),
406            [
407                "AGIX_DAEMON_TOKEN",
408                "ANTHROPIC_API_KEY",
409                "ANTHROPIC_BASE_URL",
410                "CDPATH",
411            ]
412        );
413    }
414
415    #[test]
416    fn a_variable_a_provider_key_is_read_from_is_held_back_too() {
417        hold_back_credential("AGIX_ENV_TEST_PROVIDER_KEY");
418        let mut host = host();
419        host.push(("AGIX_ENV_TEST_PROVIDER_KEY".into(), "sk-canary".into()));
420        assert!(names(SubprocessEnv::default().resolve(host.clone()))
421            .contains(&"AGIX_ENV_TEST_PROVIDER_KEY".to_string()));
422        let passed_on_purpose = SubprocessEnv {
423            allow: vec!["AGIX_ENV_TEST_PROVIDER_KEY".into()],
424            ..Default::default()
425        };
426        assert!(!names(passed_on_purpose.resolve(host))
427            .contains(&"AGIX_ENV_TEST_PROVIDER_KEY".to_string()));
428    }
429
430    #[test]
431    fn what_an_mcp_server_reads_from_this_process() {
432        let server = serde_json::json!({
433            "type": "streamable_http",
434            "command": "$BIN_DIR/x",
435            "args": ["--token", "${ARG_TOKEN:-none}", "$$LITERAL"],
436            "env": {"GITHUB_TOKEN": "$GH_TOKEN", "FIXED": "value"},
437            "url": "https://h/mcp?key=${URL_KEY}",
438            "headers": {"Authorization": "Bearer $HEADER_TOKEN"},
439            "oauth": {"client_id": "c", "client_secret_env": "SECRET_VAR",
440                      "private_key_jwt": {"key_env": "SIGNING_KEY"}},
441        });
442        let mut names = variables_an_mcp_server_reads(&server);
443        names.sort();
444        assert_eq!(
445            names,
446            [
447                "ARG_TOKEN",
448                "BIN_DIR",
449                "GH_TOKEN",
450                "HEADER_TOKEN",
451                "SECRET_VAR",
452                "SIGNING_KEY",
453                "URL_KEY"
454            ]
455        );
456    }
457
458    #[test]
459    fn a_variable_an_mcp_server_reads_is_held_back() {
460        let server = serde_json::json!({"type": "stdio", "command": "x",
461            "env": {"T": "$AGIX_ENV_TEST_MCP_TOKEN"}});
462        hold_back_what_an_mcp_server_reads(&server);
463        assert!(is_engine_credential(OsStr::new("AGIX_ENV_TEST_MCP_TOKEN")));
464        assert!(!is_engine_credential(OsStr::new("T")));
465    }
466
467    #[test]
468    fn a_variable_a_shell_needs_is_never_held_back() {
469        hold_back_credential("PATH");
470        assert!(!is_engine_credential(OsStr::new("PATH")));
471    }
472
473    #[test]
474    fn cdpath_is_never_kept_even_when_named() {
475        let policy = SubprocessEnv {
476            mode: SubprocessEnvMode::Allowlist,
477            allow: vec!["CDPATH".into()],
478        };
479        assert_eq!(names(policy.resolve(host())), ["HOME", "PATH"]);
480    }
481
482    #[test]
483    fn inherit_can_be_told_to_pass_a_credential_on_purpose() {
484        let policy = SubprocessEnv {
485            allow: vec!["ANTHROPIC_API_KEY".into()],
486            ..Default::default()
487        };
488        assert_eq!(
489            names(policy.resolve(host())),
490            ["AGIX_DAEMON_TOKEN", "ANTHROPIC_BASE_URL", "CDPATH"]
491        );
492    }
493
494    #[test]
495    fn allowlist_keeps_the_baseline_and_what_was_named() {
496        let policy = SubprocessEnv {
497            mode: SubprocessEnvMode::Allowlist,
498            allow: vec!["SSH_AUTH_SOCK".into()],
499        };
500        assert_eq!(
501            names(policy.resolve(host())),
502            ["HOME", "PATH", "SSH_AUTH_SOCK"]
503        );
504    }
505
506    #[test]
507    fn the_settings_shape() {
508        let p: SubprocessEnv =
509            serde_json::from_str(r#"{"mode":"allowlist","allow":["GITHUB_TOKEN"]}"#).unwrap();
510        assert_eq!(p.mode, SubprocessEnvMode::Allowlist);
511        assert_eq!(p.allow, ["GITHUB_TOKEN"]);
512        let d: SubprocessEnv = serde_json::from_str("{}").unwrap();
513        assert_eq!(d, SubprocessEnv::default());
514    }
515}