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() || name.contains('*') || 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/// Treat every variable `pattern` names as a credential, as
109/// [`hold_back_credential`] does one: a name, or a prefix ending in `*`
110/// (`HARNIX_CREDENTIAL_*`). Refused, holding back nothing, with the variable
111/// it would cover that every command needs.
112pub fn hold_back_host_secrets(pattern: &str) -> Result<(), String> {
113    let covers = |name: &str| names_cover(pattern, name);
114    let needed = BASELINE.iter().chain(MINIMAL).find(|name| covers(name));
115    if let Some(needed) =
116        needed.or((pattern.starts_with("LC_") || covers("LC_")).then_some(&"LC_*"))
117    {
118        return Err(format!(
119            "it would hold back `{needed}`, which every command needs"
120        ));
121    }
122    NAMED_CREDENTIALS
123        .write()
124        .unwrap_or_else(std::sync::PoisonError::into_inner)
125        .insert(pattern.to_string());
126    Ok(())
127}
128
129/// The engine's own credentials: the `ANTHROPIC_*` variables, the daemon's
130/// bearer token, and whatever [`hold_back_credential`] and
131/// [`hold_back_host_secrets`] were told.
132pub fn is_engine_credential(name: &OsStr) -> bool {
133    let name = name.to_string_lossy();
134    name.starts_with("ANTHROPIC_")
135        || name == "AGIX_DAEMON_TOKEN"
136        || NAMED_CREDENTIALS
137            .read()
138            .unwrap_or_else(std::sync::PoisonError::into_inner)
139            .iter()
140            .any(|held| names_cover(held, &name))
141}
142
143/// Whether `pattern` — a name, or a prefix ending in `*` — names `name`;
144/// regardless of case on Windows, whose environment does not tell them apart.
145fn names_cover(pattern: &str, name: &str) -> bool {
146    let fold = |s: &str| match cfg!(windows) {
147        true => s.to_ascii_uppercase(),
148        false => s.to_owned(),
149    };
150    let (pattern, name) = (fold(pattern), fold(name));
151    let prefix = pattern.strip_suffix('*');
152    prefix.map_or(name == pattern, |prefix| name.starts_with(prefix))
153}
154
155/// The variables `input` refers to as `$VAR`, `${VAR}` or `${VAR:-…}`.
156pub fn referenced_vars(input: &str) -> Vec<String> {
157    let named = std::cell::RefCell::new(Vec::new());
158    expand_vars_with(input, |name| {
159        named.borrow_mut().push(name.to_string());
160        None
161    });
162    named.into_inner()
163}
164
165/// The variables of this process's environment an `mcp_servers` entry reads
166/// when it connects: every `$VAR` in its `command`, `args`, `env`, `url` and
167/// `headers`, and the variables its `oauth` block names
168/// (`client_secret_env`, `private_key_jwt.key_env`).
169pub fn variables_an_mcp_server_reads(server: &serde_json::Value) -> Vec<String> {
170    use serde_json::Value;
171    let field = |key: &str| server.get(key);
172    let strings = ["command", "url"]
173        .into_iter()
174        .filter_map(|key| field(key)?.as_str())
175        .chain(
176            field("args")
177                .and_then(Value::as_array)
178                .into_iter()
179                .flatten()
180                .filter_map(Value::as_str),
181        )
182        .chain(
183            ["env", "headers"]
184                .into_iter()
185                .filter_map(|key| field(key)?.as_object())
186                .flatten()
187                .filter_map(|(_, v)| v.as_str()),
188        );
189    let mut names: Vec<String> = strings.flat_map(referenced_vars).collect();
190    let oauth = field("oauth");
191    names.extend(
192        [
193            oauth.and_then(|o| o.get("client_secret_env")),
194            oauth
195                .and_then(|o| o.get("private_key_jwt"))
196                .and_then(|k| k.get("key_env")),
197        ]
198        .into_iter()
199        .flatten()
200        .filter_map(Value::as_str)
201        .map(str::to_string),
202    );
203    names
204}
205
206/// [`hold_back_credential`] for every variable
207/// [`variables_an_mcp_server_reads`] finds in `server`.
208pub fn hold_back_what_an_mcp_server_reads(server: &serde_json::Value) {
209    for name in variables_an_mcp_server_reads(server) {
210        hold_back_credential(&name);
211    }
212}
213
214/// Expand `$VAR`, `${VAR}`, `${VAR:-default}` (the default when unset or
215/// empty) and `$$` (a literal `$`) in `input`, with the variables `lookup`
216/// gives. A variable it does not give expands to nothing.
217pub fn expand_vars_with(input: &str, lookup: impl Fn(&str) -> Option<String>) -> String {
218    let chars: Vec<char> = input.chars().collect();
219    let mut out = String::with_capacity(input.len());
220    let mut i = 0;
221    while i < chars.len() {
222        let c = chars[i];
223        if c != '$' {
224            out.push(c);
225            i += 1;
226            continue;
227        }
228        if i + 1 >= chars.len() {
229            out.push('$');
230            i += 1;
231            continue;
232        }
233        let next = chars[i + 1];
234        if next == '$' {
235            out.push('$');
236            i += 2;
237            continue;
238        }
239        if next == '{' {
240            let mut end = None;
241            let mut j = i + 2;
242            while j < chars.len() {
243                if chars[j] == '}' {
244                    end = Some(j);
245                    break;
246                }
247                j += 1;
248            }
249            if let Some(j) = end {
250                let body: String = chars[i + 2..j].iter().collect();
251                let (name, default) = match body.split_once(":-") {
252                    Some((n, d)) => (n.to_string(), Some(d.to_string())),
253                    None => (body, None),
254                };
255                match lookup(&name) {
256                    Some(v) if !v.is_empty() => out.push_str(&v),
257                    _ => {
258                        if let Some(d) = default {
259                            out.push_str(&d);
260                        }
261                    }
262                }
263                i = j + 1;
264                continue;
265            }
266            out.push('$');
267            i += 1;
268            continue;
269        }
270        let start = i + 1;
271        let mut j = start;
272        while j < chars.len() {
273            let ch = chars[j];
274            let valid =
275                ch.is_ascii_alphabetic() || ch == '_' || (j > start && ch.is_ascii_alphanumeric());
276            if !valid {
277                break;
278            }
279            j += 1;
280        }
281        if j > start {
282            let name: String = chars[start..j].iter().collect();
283            if let Some(v) = lookup(&name) {
284                out.push_str(&v);
285            }
286            i = j;
287        } else {
288            out.push('$');
289            i += 1;
290        }
291    }
292    out
293}
294
295/// Never inherited: `CDPATH` would make a child shell's `cd foo` reach a
296/// directory outside the project that the permission check, which reads the
297/// literal `foo`, never saw.
298fn never_inherited(name: &OsStr) -> bool {
299    name == "CDPATH"
300}
301
302/// What [`SubprocessEnv::resolve`] decides to do to the environment a child
303/// would otherwise inherit.
304#[derive(Debug, PartialEq, Eq)]
305pub enum EnvPlan {
306    /// Inherit it, minus these.
307    Remove(Vec<OsString>),
308    /// Start from nothing but these.
309    Replace(Vec<(OsString, OsString)>),
310}
311
312/// How much of the environment a process starts from: a mark on a
313/// [`ProcessSpec`](super::ProcessSpec) a provider reads, not a list of
314/// variables, since a remote provider's environment is not this machine's.
315#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
316pub enum EnvScope {
317    /// What `sandbox.env` gives every child.
318    #[default]
319    Session,
320    /// Only what a shell needs to run: `PATH HOME USER LOGNAME SHELL TERM
321    /// LANG LC_* TZ TMPDIR`. `sandbox.env.allow` adds nothing to
322    /// it.
323    Minimal,
324}
325
326const MINIMAL: &[&str] = &[
327    "PATH", "HOME", "USER", "LOGNAME", "SHELL", "TERM", "LANG", "TZ", "TMPDIR",
328];
329
330impl EnvScope {
331    pub fn keeps_under_minimal(name: &OsStr) -> bool {
332        let name = name.to_string_lossy();
333        MINIMAL.contains(&name.as_ref()) || name.starts_with("LC_")
334    }
335}
336
337impl SubprocessEnv {
338    /// [`Self::resolve`] for a child whose spec says `scope`.
339    pub fn resolve_in(
340        &self,
341        scope: EnvScope,
342        host: impl IntoIterator<Item = (OsString, OsString)>,
343    ) -> EnvPlan {
344        match scope {
345            EnvScope::Session => self.resolve(host),
346            EnvScope::Minimal => EnvPlan::Replace(
347                host.into_iter()
348                    .filter(|(name, _)| {
349                        EnvScope::keeps_under_minimal(name)
350                            && !never_inherited(name)
351                            && !is_engine_credential(name)
352                    })
353                    .collect(),
354            ),
355        }
356    }
357
358    /// What a child starting from `host` gets, as the policy says. Applying
359    /// it to a command on this machine is `platform`'s.
360    pub fn resolve(&self, host: impl IntoIterator<Item = (OsString, OsString)>) -> EnvPlan {
361        let allowed = |name: &OsStr| self.allow.iter().any(|a| OsStr::new(a) == name);
362        match self.mode {
363            SubprocessEnvMode::Inherit => EnvPlan::Remove(
364                host.into_iter()
365                    .map(|(name, _)| name)
366                    .filter(|name| {
367                        never_inherited(name) || (is_engine_credential(name) && !allowed(name))
368                    })
369                    .collect(),
370            ),
371            SubprocessEnvMode::Allowlist => EnvPlan::Replace(
372                host.into_iter()
373                    .filter(|(name, _)| {
374                        !never_inherited(name)
375                            && (BASELINE.iter().any(|b| OsStr::new(b) == name) || allowed(name))
376                    })
377                    .collect(),
378            ),
379        }
380    }
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386
387    fn host() -> Vec<(OsString, OsString)> {
388        [
389            ("PATH", "/bin"),
390            ("HOME", "/home/u"),
391            ("ANTHROPIC_API_KEY", "sk-canary"),
392            ("ANTHROPIC_BASE_URL", "https://example"),
393            ("AGIX_DAEMON_TOKEN", "t"),
394            ("GITHUB_TOKEN", "gh"),
395            ("SSH_AUTH_SOCK", "/tmp/agent"),
396            ("CDPATH", "/"),
397        ]
398        .into_iter()
399        .map(|(k, v)| (k.into(), v.into()))
400        .collect()
401    }
402
403    fn names(plan: EnvPlan) -> Vec<String> {
404        let mut names: Vec<String> = match plan {
405            EnvPlan::Remove(n) => n.into_iter().map(|n| n.into_string().unwrap()).collect(),
406            EnvPlan::Replace(v) => v
407                .into_iter()
408                .map(|(n, _)| n.into_string().unwrap())
409                .collect(),
410        };
411        names.sort();
412        names
413    }
414
415    #[test]
416    fn the_minimal_scope_keeps_what_a_shell_needs_and_ignores_allow() {
417        let mut host = host();
418        host.extend([
419            ("LC_MESSAGES".into(), "C".into()),
420            ("EDITOR".into(), "vi".into()),
421        ]);
422        let policy = SubprocessEnv {
423            mode: SubprocessEnvMode::Inherit,
424            allow: vec!["GITHUB_TOKEN".into()],
425        };
426        assert_eq!(
427            names(policy.resolve_in(EnvScope::Minimal, host.clone())),
428            ["HOME", "LC_MESSAGES", "PATH"]
429        );
430        assert_eq!(
431            policy.resolve_in(EnvScope::Session, host.clone()),
432            policy.resolve(host)
433        );
434    }
435
436    #[test]
437    fn inherit_drops_the_engines_credentials_and_cdpath() {
438        let plan = SubprocessEnv::default().resolve(host());
439        assert_eq!(
440            names(plan),
441            [
442                "AGIX_DAEMON_TOKEN",
443                "ANTHROPIC_API_KEY",
444                "ANTHROPIC_BASE_URL",
445                "CDPATH",
446            ]
447        );
448    }
449
450    #[test]
451    fn a_variable_a_provider_key_is_read_from_is_held_back_too() {
452        hold_back_credential("AGIX_ENV_TEST_PROVIDER_KEY");
453        let mut host = host();
454        host.push(("AGIX_ENV_TEST_PROVIDER_KEY".into(), "sk-canary".into()));
455        assert!(names(SubprocessEnv::default().resolve(host.clone()))
456            .contains(&"AGIX_ENV_TEST_PROVIDER_KEY".to_string()));
457        let passed_on_purpose = SubprocessEnv {
458            allow: vec!["AGIX_ENV_TEST_PROVIDER_KEY".into()],
459            ..Default::default()
460        };
461        assert!(!names(passed_on_purpose.resolve(host))
462            .contains(&"AGIX_ENV_TEST_PROVIDER_KEY".to_string()));
463    }
464
465    #[test]
466    fn what_an_mcp_server_reads_from_this_process() {
467        let server = serde_json::json!({
468            "type": "streamable_http",
469            "command": "$BIN_DIR/x",
470            "args": ["--token", "${ARG_TOKEN:-none}", "$$LITERAL"],
471            "env": {"GITHUB_TOKEN": "$GH_TOKEN", "FIXED": "value"},
472            "url": "https://h/mcp?key=${URL_KEY}",
473            "headers": {"Authorization": "Bearer $HEADER_TOKEN"},
474            "oauth": {"client_id": "c", "client_secret_env": "SECRET_VAR",
475                      "private_key_jwt": {"key_env": "SIGNING_KEY"}},
476        });
477        let mut names = variables_an_mcp_server_reads(&server);
478        names.sort();
479        assert_eq!(
480            names,
481            [
482                "ARG_TOKEN",
483                "BIN_DIR",
484                "GH_TOKEN",
485                "HEADER_TOKEN",
486                "SECRET_VAR",
487                "SIGNING_KEY",
488                "URL_KEY"
489            ]
490        );
491    }
492
493    #[test]
494    fn a_variable_an_mcp_server_reads_is_held_back() {
495        let server = serde_json::json!({"type": "stdio", "command": "x",
496            "env": {"T": "$AGIX_ENV_TEST_MCP_TOKEN"}});
497        hold_back_what_an_mcp_server_reads(&server);
498        assert!(is_engine_credential(OsStr::new("AGIX_ENV_TEST_MCP_TOKEN")));
499        assert!(!is_engine_credential(OsStr::new("T")));
500    }
501
502    #[test]
503    fn a_variable_a_shell_needs_is_never_held_back() {
504        hold_back_credential("PATH");
505        assert!(!is_engine_credential(OsStr::new("PATH")));
506    }
507
508    #[test]
509    fn cdpath_is_never_kept_even_when_named() {
510        let policy = SubprocessEnv {
511            mode: SubprocessEnvMode::Allowlist,
512            allow: vec!["CDPATH".into()],
513        };
514        assert_eq!(names(policy.resolve(host())), ["HOME", "PATH"]);
515    }
516
517    #[test]
518    fn inherit_can_be_told_to_pass_a_credential_on_purpose() {
519        let policy = SubprocessEnv {
520            allow: vec!["ANTHROPIC_API_KEY".into()],
521            ..Default::default()
522        };
523        assert_eq!(
524            names(policy.resolve(host())),
525            ["AGIX_DAEMON_TOKEN", "ANTHROPIC_BASE_URL", "CDPATH"]
526        );
527    }
528
529    #[test]
530    fn allowlist_keeps_the_baseline_and_what_was_named() {
531        let policy = SubprocessEnv {
532            mode: SubprocessEnvMode::Allowlist,
533            allow: vec!["SSH_AUTH_SOCK".into()],
534        };
535        assert_eq!(
536            names(policy.resolve(host())),
537            ["HOME", "PATH", "SSH_AUTH_SOCK"]
538        );
539    }
540
541    #[test]
542    fn a_host_prefix_holds_back_what_it_covers_unless_allowed() {
543        hold_back_host_secrets("HOSTSECRETTEST_*").unwrap();
544        let host = vec![
545            (OsString::from("PATH"), OsString::from("/bin")),
546            (OsString::from("HOSTSECRETTEST_A"), OsString::from("s")),
547            (OsString::from("HOSTSECRETTESTB"), OsString::from("s")),
548        ];
549        assert_eq!(
550            names(SubprocessEnv::default().resolve(host.clone())),
551            ["HOSTSECRETTEST_A"]
552        );
553        let allowed = SubprocessEnv {
554            allow: vec!["HOSTSECRETTEST_A".into()],
555            ..Default::default()
556        };
557        assert!(names(allowed.resolve(host)).is_empty());
558    }
559
560    #[test]
561    fn a_host_pattern_that_would_hold_back_what_a_shell_needs_is_refused() {
562        for pattern in ["*", "P*", "PATH", "HOME", "LC_ALL", "LC*", "LC_X*"] {
563            assert!(hold_back_host_secrets(pattern).is_err(), "{pattern}");
564        }
565        if cfg!(windows) {
566            for pattern in ["Pa*", "Path", "SystemRoot*"] {
567                assert!(hold_back_host_secrets(pattern).is_err(), "{pattern}");
568            }
569        }
570        assert!(!is_engine_credential(OsStr::new("PATH")));
571    }
572
573    #[test]
574    fn the_settings_shape() {
575        let p: SubprocessEnv =
576            serde_json::from_str(r#"{"mode":"allowlist","allow":["GITHUB_TOKEN"]}"#).unwrap();
577        assert_eq!(p.mode, SubprocessEnvMode::Allowlist);
578        assert_eq!(p.allow, ["GITHUB_TOKEN"]);
579        let d: SubprocessEnv = serde_json::from_str("{}").unwrap();
580        assert_eq!(d, SubprocessEnv::default());
581    }
582}