vtcode-llm 0.185.4

LLM provider abstraction, client implementations, and streaming for VT Code
Documentation
//! Inherited environment policy for provider-owned child processes.

use std::ffi::{OsStr, OsString};
use std::path::Path;

use tokio::process::Command as TokioCommand;
use vtcode_commons::spawn_program::{ChildPath, command_for_spawn};
use vtcode_safety::sandboxing::should_filter_env_var;

/// Environment variables intentionally forwarded to the Copilot runtime.
///
/// These are the documented authentication inputs detected by the Copilot
/// adapter. They are re-added after the general credential filter so the
/// runtime can authenticate without receiving unrelated provider secrets.
pub(crate) const COPILOT_AUTH_ENV_VARS: &[&str] = &["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];

/// Environment variables intentionally forwarded to the optional `gh` auth
/// status probe.
pub(crate) const GITHUB_CLI_AUTH_ENV_VARS: &[&str] = &[
    "GH_TOKEN",
    "GITHUB_TOKEN",
    "GH_ENTERPRISE_TOKEN",
    "GITHUB_ENTERPRISE_TOKEN",
    "GH_HOST",
    "GITHUB_HOST",
];

/// Return the inherited environment after removing credential, cloud,
/// linker, and dynamic-loader variables.
pub(crate) fn filtered_provider_environment(allowed_env_vars: &[&str]) -> Vec<(OsString, OsString)> {
    filter_provider_environment(std::env::vars_os(), allowed_env_vars)
}

/// Filter an environment snapshot. Keeping this operation pure makes the
/// boundary testable without mutating process-global environment state.
fn filter_provider_environment<I>(environment: I, allowed_env_vars: &[&str]) -> Vec<(OsString, OsString)>
where
    I: IntoIterator<Item = (OsString, OsString)>,
{
    environment
        .into_iter()
        .filter_map(|(key, value)| {
            let key_text = key.to_str()?;
            let explicitly_allowed = allowed_env_vars.iter().any(|allowed| key_text.eq_ignore_ascii_case(allowed));
            if explicitly_allowed || !should_filter_env_var(key_text) {
                Some((key, value))
            } else {
                None
            }
        })
        .collect()
}

/// Build a provider child command that receives only the filtered environment.
///
/// The program is resolved against the filtered `PATH` before the environment is
/// cleared, so the standard library keeps launching it with `posix_spawn`
/// rather than falling back to `fork` (see `vtcode_commons::spawn_program`).
/// `cwd`, when given, is applied here because it affects that resolution.
pub(crate) fn provider_std_command(
    program: impl AsRef<OsStr>,
    cwd: Option<&Path>,
    allowed_env_vars: &[&str],
) -> std::process::Command {
    let environment = filtered_provider_environment(allowed_env_vars);
    let child_path = ChildPath::from_exact_env(environment.iter().map(|(key, value)| (key, value)));
    let mut command = command_for_spawn(program.as_ref(), child_path, cwd);
    if let Some(cwd) = cwd {
        let _ = command.current_dir(cwd);
    }
    let _ = command.env_clear().envs(environment);
    command
}

/// Tokio variant of [`provider_std_command`].
pub(crate) fn provider_tokio_command(
    program: impl AsRef<OsStr>,
    cwd: Option<&Path>,
    allowed_env_vars: &[&str],
) -> TokioCommand {
    TokioCommand::from(provider_std_command(program, cwd, allowed_env_vars))
}

/// Apply the filtered environment to a portable PTY command builder.
#[cfg(feature = "copilot")]
pub(crate) fn sanitize_pty_command_environment(command: &mut portable_pty::CommandBuilder, allowed_env_vars: &[&str]) {
    command.env_clear();
    for (key, value) in filtered_provider_environment(allowed_env_vars) {
        command.env(key, value);
    }
}

#[cfg(test)]
mod tests {
    use super::{COPILOT_AUTH_ENV_VARS, filter_provider_environment, provider_tokio_command};
    use std::ffi::{OsStr, OsString};
    use std::path::Path;
    use tokio::process::Command;

    fn names(environment: &[(OsString, OsString)]) -> Vec<&str> {
        environment.iter().filter_map(|(key, _)| key.to_str()).collect()
    }

    fn configured_value(command: &Command, key: &str) -> Option<String> {
        command.as_std().get_envs().find_map(|(name, value)| {
            if name.to_str()? == key {
                value.map(|value| value.to_string_lossy().into_owned())
            } else {
                None
            }
        })
    }

    #[test]
    fn filters_credentials_and_loader_overrides_but_preserves_runtime_values() {
        let environment = [
            ("PATH", "/usr/bin"),
            ("HOME", "/home/test"),
            ("VTCODE_PROVIDER_MODE", "local"),
            ("OPENAI_API_KEY", "openai-secret"),
            ("AWS_SECRET_ACCESS_KEY", "aws-secret"),
            ("CUSTOM_ACCESS_TOKEN", "token-secret"),
            ("LD_PRELOAD", "/tmp/injected.dylib"),
            ("DYLD_INSERT_LIBRARIES", "/tmp/injected.dylib"),
        ]
        .into_iter()
        .map(|(key, value)| (OsString::from(key), OsString::from(value)));

        let filtered = filter_provider_environment(environment, &[]);
        let names = names(&filtered);

        assert!(names.contains(&"PATH"));
        assert!(names.contains(&"HOME"));
        assert!(names.contains(&"VTCODE_PROVIDER_MODE"));
        assert!(!names.contains(&"OPENAI_API_KEY"));
        assert!(!names.contains(&"AWS_SECRET_ACCESS_KEY"));
        assert!(!names.contains(&"CUSTOM_ACCESS_TOKEN"));
        assert!(!names.contains(&"LD_PRELOAD"));
        assert!(!names.contains(&"DYLD_INSERT_LIBRARIES"));
    }

    #[test]
    fn allows_only_explicit_auth_exceptions() {
        let environment = [
            ("GITHUB_TOKEN", "github-secret"),
            ("OPENAI_API_KEY", "openai-secret"),
            ("PATH", "/usr/bin"),
        ]
        .into_iter()
        .map(|(key, value)| (OsString::from(key), OsString::from(value)));

        let filtered = filter_provider_environment(environment, COPILOT_AUTH_ENV_VARS);
        let names = names(&filtered);

        assert!(names.contains(&"GITHUB_TOKEN"));
        assert!(names.contains(&"PATH"));
        assert!(!names.contains(&"OPENAI_API_KEY"));
    }

    #[test]
    #[serial_test::serial]
    fn copilot_exception_preserves_only_its_auth_token() {
        // The sanitizer re-reads allowed variables from the process environment,
        // so seed them explicitly instead of assuming the invoking shell or CI
        // provides GITHUB_TOKEN. EnvGuard serializes env access; nextest also
        // isolates each test in its own process so these values cannot leak.
        let guard = vtcode_commons::env_lock::lock();
        guard.set_var("GITHUB_TOKEN", "github-from-process-a73");
        guard.set_var("OPENAI_API_KEY", "openai-from-process-b29");

        let command = provider_tokio_command("copilot", None, COPILOT_AUTH_ENV_VARS);

        assert_eq!(configured_value(&command, "GITHUB_TOKEN").as_deref(), Some("github-from-process-a73"));
        assert_eq!(configured_value(&command, "OPENAI_API_KEY"), None);
    }

    #[cfg(unix)]
    #[test]
    #[serial_test::serial]
    fn provider_command_resolves_bare_program_through_filtered_path() {
        let bin = tempfile::tempdir().unwrap();
        std::os::unix::fs::symlink("/bin/sh", bin.path().join("vtcode-provider-sh")).unwrap();
        let guard = vtcode_commons::env_lock::lock();
        guard.set_var("PATH", bin.path());

        let mut command = super::provider_std_command("vtcode-provider-sh", None, &[]);
        drop(guard);

        // Absolute program keeps std on posix_spawn despite env_clear().
        assert_eq!(std::path::Path::new(command.get_program()), bin.path().join("vtcode-provider-sh"));
        let output = command.args(["-c", "printf %s \"$0\""]).output().unwrap();
        assert!(output.status.success());
        assert_eq!(output.stdout, b"vtcode-provider-sh");
    }
}