Skip to main content

merry_process/process_runner/
env_isolation.rs

1//! Domain-agnostic environment-variable isolation for child process actions.
2
3use super::environment::validate_environment_name;
4use merry_runtime::ProcessRunnerError;
5use std::{
6    collections::BTreeSet,
7    env,
8    ffi::{OsStr, OsString},
9};
10
11/// Default environment-variable prefix stripped from all child process actions
12/// so Merry's own configuration and provider credentials never leak into
13/// workspace commands.
14pub const DEFAULT_REMOVED_ENV_PREFIX: &str = "MERRY_";
15
16/// Domain-agnostic environment-variable isolation policy enforced by
17/// `merry-process` across both isolated and host process runners.
18///
19/// By default, all inherited variables starting with `MERRY_` are stripped from
20/// child processes so Merry-owned configuration, sandbox tokens, and provider
21/// credentials cannot be observed by workspace commands. Callers may register
22/// additional explicit variable names, which are both stripped from inherited
23/// environments and rejected if an environment override attempts to re-inject
24/// them.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct ProcessEnvIsolation {
27    removed_vars: Vec<OsString>,
28    removed_prefixes: Vec<OsString>,
29}
30
31impl Default for ProcessEnvIsolation {
32    fn default() -> Self {
33        Self {
34            removed_vars: Vec::new(),
35            removed_prefixes: vec![OsString::from(DEFAULT_REMOVED_ENV_PREFIX)],
36        }
37    }
38}
39
40impl ProcessEnvIsolation {
41    /// Appends explicit environment variable names to strip from child
42    /// processes and block from environment overrides.
43    pub fn extend_removed_vars(
44        mut self,
45        names: impl IntoIterator<Item = OsString>,
46    ) -> Result<Self, ProcessRunnerError> {
47        for name in names {
48            validate_environment_name(&name)?;
49            if !self
50                .removed_vars
51                .iter()
52                .any(|existing| env_name_eq(existing, &name))
53            {
54                self.removed_vars.push(name);
55            }
56        }
57        Ok(self)
58    }
59
60    /// Returns true when `name` is explicitly marked as a removed variable.
61    #[must_use]
62    pub fn is_explicitly_removed(&self, name: &OsStr) -> bool {
63        self.removed_vars
64            .iter()
65            .any(|removed| env_name_eq(removed, name))
66    }
67
68    /// Returns true when `name` matches an explicit removed variable or prefix.
69    #[must_use]
70    pub fn matches_name(&self, name: &OsStr) -> bool {
71        self.is_explicitly_removed(name)
72            || self
73                .removed_prefixes
74                .iter()
75                .any(|prefix| env_name_starts_with(name, prefix))
76    }
77
78    /// Rejects environment overrides that attempt to re-inject a variable
79    /// explicitly marked for removal.
80    pub fn validate_overrides(
81        &self,
82        overrides: &[(OsString, OsString)],
83    ) -> Result<(), ProcessRunnerError> {
84        for (name, _) in overrides {
85            if self.is_explicitly_removed(name) {
86                return Err(ProcessRunnerError::infrastructure(format!(
87                    "process environment override cannot set isolated variable `{}`",
88                    name.to_string_lossy()
89                )));
90            }
91        }
92        Ok(())
93    }
94
95    /// Resolves all concrete environment variable names to remove from the
96    /// current process environment for one child spawn.
97    ///
98    /// Includes every explicitly registered variable name plus every currently
99    /// set parent variable whose name matches `removed_prefixes`. Only variable
100    /// names are returned; values are never copied.
101    #[must_use]
102    pub fn resolve_removed_names(&self) -> Vec<OsString> {
103        self.resolve_removed_names_from(env::vars_os().map(|(name, _)| name))
104    }
105
106    /// Resolves concrete removed variable names against an explicit list of
107    /// inherited parent variable names (deterministic for testing).
108    #[must_use]
109    pub fn resolve_removed_names_from(
110        &self,
111        inherited_names: impl IntoIterator<Item = OsString>,
112    ) -> Vec<OsString> {
113        let mut seen = BTreeSet::new();
114        let mut names = Vec::new();
115        for name in self.removed_vars.iter().cloned() {
116            let key = canonical_env_key(&name);
117            if seen.insert(key) {
118                names.push(name);
119            }
120        }
121        for name in inherited_names {
122            if self.matches_name(&name) {
123                let key = canonical_env_key(&name);
124                if seen.insert(key) {
125                    names.push(name);
126                }
127            }
128        }
129        names
130    }
131
132    /// Applies this isolation policy to a `tokio::process::Command` by calling
133    /// `env_remove` for every resolved variable name.
134    pub fn apply_to_tokio_command(&self, command: &mut tokio::process::Command) {
135        for name in self.resolve_removed_names() {
136            command.env_remove(name);
137        }
138    }
139}
140
141fn canonical_env_key(name: &OsStr) -> String {
142    let text = name.to_string_lossy();
143    if cfg!(windows) {
144        text.to_ascii_uppercase()
145    } else {
146        text.into_owned()
147    }
148}
149
150fn env_name_eq(left: &OsStr, right: &OsStr) -> bool {
151    if cfg!(windows) {
152        left.to_str()
153            .zip(right.to_str())
154            .is_some_and(|(a, b)| a.eq_ignore_ascii_case(b))
155    } else {
156        left == right
157    }
158}
159
160fn env_name_starts_with(name: &OsStr, prefix: &OsStr) -> bool {
161    let Some(name) = name.to_str() else {
162        return false;
163    };
164    let Some(prefix) = prefix.to_str() else {
165        return false;
166    };
167    if cfg!(windows) {
168        name.len() >= prefix.len()
169            && name.is_char_boundary(prefix.len())
170            && name[..prefix.len()].eq_ignore_ascii_case(prefix)
171    } else {
172        name.starts_with(prefix)
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::ProcessEnvIsolation;
179    use std::ffi::OsString;
180
181    #[test]
182    fn default_isolation_strips_merry_prefix_and_preserves_workspace_vars() {
183        let isolation = ProcessEnvIsolation::default();
184        let removed = isolation.resolve_removed_names_from([
185            OsString::from("PATH"),
186            OsString::from("OPENAI_API_KEY"),
187            OsString::from("MERRY_API_KEY"),
188            OsString::from("MERRY_BASE_URL"),
189            OsString::from("MERRY_MODEL"),
190        ]);
191        assert_eq!(
192            removed,
193            vec![
194                OsString::from("MERRY_API_KEY"),
195                OsString::from("MERRY_BASE_URL"),
196                OsString::from("MERRY_MODEL"),
197            ]
198        );
199        assert!(!isolation.matches_name(std::ffi::OsStr::new("OPENAI_API_KEY")));
200        assert!(isolation.matches_name(std::ffi::OsStr::new("MERRY_API_KEY")));
201    }
202
203    #[test]
204    fn explicit_removed_vars_reject_environment_overrides() {
205        let isolation = ProcessEnvIsolation::default()
206            .extend_removed_vars([OsString::from("CUSTOM_SECRET")])
207            .expect("valid env var name");
208        let error = isolation
209            .validate_overrides(&[(
210                OsString::from("CUSTOM_SECRET"),
211                OsString::from("leaked-value"),
212            )])
213            .expect_err("explicitly isolated var must not be re-injected");
214        assert!(error.to_string().contains("CUSTOM_SECRET"), "{error}");
215    }
216
217    #[cfg(unix)]
218    #[tokio::test]
219    async fn host_and_isolated_backends_strip_isolated_vars_from_child_processes() {
220        use crate::{
221            LocalProcessBackend, ProcessBackend, ProcessBackendMode, ProcessBackendOptions,
222        };
223        use merry_runtime::{ProcessActionIntent, ProcessEnvPolicy, ProcessRunnerContext};
224
225        let temp = tempfile::tempdir().expect("tempdir");
226        // `CARGO_MANIFEST_DIR` and `CARGO_PKG_NAME` are always set by Cargo
227        // during tests; isolating only one proves scrubbing removes the target
228        // without wiping unrelated workspace environment variables.
229        assert!(std::env::var_os("CARGO_MANIFEST_DIR").is_some());
230        assert!(std::env::var_os("CARGO_PKG_NAME").is_some());
231        let isolation = ProcessEnvIsolation::default()
232            .extend_removed_vars([OsString::from("CARGO_MANIFEST_DIR")])
233            .expect("valid var name");
234        let options = ProcessBackendOptions::new().with_env_isolation(isolation);
235        let host_backend =
236            LocalProcessBackend::new(temp.path(), ProcessBackendMode::Host, options.clone())
237                .expect("host backend");
238        let intent = ProcessActionIntent::new(
239            vec![
240                "/bin/sh".into(),
241                "-c".into(),
242                "printf '%s|%s' \"${CARGO_MANIFEST_DIR:-<absent>}\" \"${CARGO_PKG_NAME:-<absent>}\""
243                    .into(),
244            ],
245            None,
246            ProcessEnvPolicy::empty(),
247            None,
248            1024,
249            1024,
250        )
251        .expect("intent");
252
253        let host_output = host_backend
254            .new_session()
255            .runner()
256            .run(
257                intent.clone(),
258                ProcessRunnerContext::new(Default::default()),
259            )
260            .await
261            .expect("host run");
262        assert_eq!(host_output.stdout_text(), "<absent>|merry-process");
263
264        #[cfg(any(target_os = "linux", target_os = "macos"))]
265        if crate::probe_workspace_sandbox().is_ok() {
266            let isolated_backend =
267                LocalProcessBackend::new(temp.path(), ProcessBackendMode::Isolated, options)
268                    .expect("isolated backend");
269            let isolated_output = isolated_backend
270                .new_session()
271                .runner()
272                .run(intent, ProcessRunnerContext::new(Default::default()))
273                .await
274                .expect("isolated run");
275            assert_eq!(isolated_output.stdout_text(), "<absent>|merry-process");
276        }
277    }
278}