merry-process 0.1.1

Sandboxed host-process execution (Landlock/seccomp, Seatbelt, Windows Job Objects) for Merry.
Documentation
//! Domain-agnostic environment-variable isolation for child process actions.

use super::environment::validate_environment_name;
use merry_runtime::ProcessRunnerError;
use std::{
    collections::BTreeSet,
    env,
    ffi::{OsStr, OsString},
};

/// Default environment-variable prefix stripped from all child process actions
/// so Merry's own configuration and provider credentials never leak into
/// workspace commands.
pub const DEFAULT_REMOVED_ENV_PREFIX: &str = "MERRY_";

/// Domain-agnostic environment-variable isolation policy enforced by
/// `merry-process` across both isolated and host process runners.
///
/// By default, all inherited variables starting with `MERRY_` are stripped from
/// child processes so Merry-owned configuration, sandbox tokens, and provider
/// credentials cannot be observed by workspace commands. Callers may register
/// additional explicit variable names, which are both stripped from inherited
/// environments and rejected if an environment override attempts to re-inject
/// them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProcessEnvIsolation {
    removed_vars: Vec<OsString>,
    removed_prefixes: Vec<OsString>,
}

impl Default for ProcessEnvIsolation {
    fn default() -> Self {
        Self {
            removed_vars: Vec::new(),
            removed_prefixes: vec![OsString::from(DEFAULT_REMOVED_ENV_PREFIX)],
        }
    }
}

impl ProcessEnvIsolation {
    /// Appends explicit environment variable names to strip from child
    /// processes and block from environment overrides.
    pub fn extend_removed_vars(
        mut self,
        names: impl IntoIterator<Item = OsString>,
    ) -> Result<Self, ProcessRunnerError> {
        for name in names {
            validate_environment_name(&name)?;
            if !self
                .removed_vars
                .iter()
                .any(|existing| env_name_eq(existing, &name))
            {
                self.removed_vars.push(name);
            }
        }
        Ok(self)
    }

    /// Returns true when `name` is explicitly marked as a removed variable.
    #[must_use]
    pub fn is_explicitly_removed(&self, name: &OsStr) -> bool {
        self.removed_vars
            .iter()
            .any(|removed| env_name_eq(removed, name))
    }

    /// Returns true when `name` matches an explicit removed variable or prefix.
    #[must_use]
    pub fn matches_name(&self, name: &OsStr) -> bool {
        self.is_explicitly_removed(name)
            || self
                .removed_prefixes
                .iter()
                .any(|prefix| env_name_starts_with(name, prefix))
    }

    /// Rejects environment overrides that attempt to re-inject a variable
    /// explicitly marked for removal.
    pub fn validate_overrides(
        &self,
        overrides: &[(OsString, OsString)],
    ) -> Result<(), ProcessRunnerError> {
        for (name, _) in overrides {
            if self.is_explicitly_removed(name) {
                return Err(ProcessRunnerError::infrastructure(format!(
                    "process environment override cannot set isolated variable `{}`",
                    name.to_string_lossy()
                )));
            }
        }
        Ok(())
    }

    /// Resolves all concrete environment variable names to remove from the
    /// current process environment for one child spawn.
    ///
    /// Includes every explicitly registered variable name plus every currently
    /// set parent variable whose name matches `removed_prefixes`. Only variable
    /// names are returned; values are never copied.
    #[must_use]
    pub fn resolve_removed_names(&self) -> Vec<OsString> {
        self.resolve_removed_names_from(env::vars_os().map(|(name, _)| name))
    }

    /// Resolves concrete removed variable names against an explicit list of
    /// inherited parent variable names (deterministic for testing).
    #[must_use]
    pub fn resolve_removed_names_from(
        &self,
        inherited_names: impl IntoIterator<Item = OsString>,
    ) -> Vec<OsString> {
        let mut seen = BTreeSet::new();
        let mut names = Vec::new();
        for name in self.removed_vars.iter().cloned() {
            let key = canonical_env_key(&name);
            if seen.insert(key) {
                names.push(name);
            }
        }
        for name in inherited_names {
            if self.matches_name(&name) {
                let key = canonical_env_key(&name);
                if seen.insert(key) {
                    names.push(name);
                }
            }
        }
        names
    }

    /// Applies this isolation policy to a `tokio::process::Command` by calling
    /// `env_remove` for every resolved variable name.
    pub fn apply_to_tokio_command(&self, command: &mut tokio::process::Command) {
        for name in self.resolve_removed_names() {
            command.env_remove(name);
        }
    }
}

fn canonical_env_key(name: &OsStr) -> String {
    let text = name.to_string_lossy();
    if cfg!(windows) {
        text.to_ascii_uppercase()
    } else {
        text.into_owned()
    }
}

fn env_name_eq(left: &OsStr, right: &OsStr) -> bool {
    if cfg!(windows) {
        left.to_str()
            .zip(right.to_str())
            .is_some_and(|(a, b)| a.eq_ignore_ascii_case(b))
    } else {
        left == right
    }
}

fn env_name_starts_with(name: &OsStr, prefix: &OsStr) -> bool {
    let Some(name) = name.to_str() else {
        return false;
    };
    let Some(prefix) = prefix.to_str() else {
        return false;
    };
    if cfg!(windows) {
        name.len() >= prefix.len()
            && name.is_char_boundary(prefix.len())
            && name[..prefix.len()].eq_ignore_ascii_case(prefix)
    } else {
        name.starts_with(prefix)
    }
}

#[cfg(test)]
mod tests {
    use super::ProcessEnvIsolation;
    use std::ffi::OsString;

    #[test]
    fn default_isolation_strips_merry_prefix_and_preserves_workspace_vars() {
        let isolation = ProcessEnvIsolation::default();
        let removed = isolation.resolve_removed_names_from([
            OsString::from("PATH"),
            OsString::from("OPENAI_API_KEY"),
            OsString::from("MERRY_API_KEY"),
            OsString::from("MERRY_BASE_URL"),
            OsString::from("MERRY_MODEL"),
        ]);
        assert_eq!(
            removed,
            vec![
                OsString::from("MERRY_API_KEY"),
                OsString::from("MERRY_BASE_URL"),
                OsString::from("MERRY_MODEL"),
            ]
        );
        assert!(!isolation.matches_name(std::ffi::OsStr::new("OPENAI_API_KEY")));
        assert!(isolation.matches_name(std::ffi::OsStr::new("MERRY_API_KEY")));
    }

    #[test]
    fn explicit_removed_vars_reject_environment_overrides() {
        let isolation = ProcessEnvIsolation::default()
            .extend_removed_vars([OsString::from("CUSTOM_SECRET")])
            .expect("valid env var name");
        let error = isolation
            .validate_overrides(&[(
                OsString::from("CUSTOM_SECRET"),
                OsString::from("leaked-value"),
            )])
            .expect_err("explicitly isolated var must not be re-injected");
        assert!(error.to_string().contains("CUSTOM_SECRET"), "{error}");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn host_and_isolated_backends_strip_isolated_vars_from_child_processes() {
        use crate::{
            LocalProcessBackend, ProcessBackend, ProcessBackendMode, ProcessBackendOptions,
        };
        use merry_runtime::{ProcessActionIntent, ProcessEnvPolicy, ProcessRunnerContext};

        let temp = tempfile::tempdir().expect("tempdir");
        // `CARGO_MANIFEST_DIR` and `CARGO_PKG_NAME` are always set by Cargo
        // during tests; isolating only one proves scrubbing removes the target
        // without wiping unrelated workspace environment variables.
        assert!(std::env::var_os("CARGO_MANIFEST_DIR").is_some());
        assert!(std::env::var_os("CARGO_PKG_NAME").is_some());
        let isolation = ProcessEnvIsolation::default()
            .extend_removed_vars([OsString::from("CARGO_MANIFEST_DIR")])
            .expect("valid var name");
        let options = ProcessBackendOptions::new().with_env_isolation(isolation);
        let host_backend =
            LocalProcessBackend::new(temp.path(), ProcessBackendMode::Host, options.clone())
                .expect("host backend");
        let intent = ProcessActionIntent::new(
            vec![
                "/bin/sh".into(),
                "-c".into(),
                "printf '%s|%s' \"${CARGO_MANIFEST_DIR:-<absent>}\" \"${CARGO_PKG_NAME:-<absent>}\""
                    .into(),
            ],
            None,
            ProcessEnvPolicy::empty(),
            None,
            1024,
            1024,
        )
        .expect("intent");

        let host_output = host_backend
            .new_session()
            .runner()
            .run(
                intent.clone(),
                ProcessRunnerContext::new(Default::default()),
            )
            .await
            .expect("host run");
        assert_eq!(host_output.stdout_text(), "<absent>|merry-process");

        #[cfg(any(target_os = "linux", target_os = "macos"))]
        if crate::probe_workspace_sandbox().is_ok() {
            let isolated_backend =
                LocalProcessBackend::new(temp.path(), ProcessBackendMode::Isolated, options)
                    .expect("isolated backend");
            let isolated_output = isolated_backend
                .new_session()
                .runner()
                .run(intent, ProcessRunnerContext::new(Default::default()))
                .await
                .expect("isolated run");
            assert_eq!(isolated_output.stdout_text(), "<absent>|merry-process");
        }
    }
}