vtcode-config 0.187.0

Config loader components shared across VT Code and downstream adopters
Documentation
//! Config security validation: restricted agent fields, provider
//! endpoint/credential hygiene, and sandbox settings.

use super::*;

impl ConfigManager {
    pub(super) fn validate_restricted_agent_fields(
        layer_stack: &ConfigLayerStack,
        origins: &hashbrown::HashMap<String, ConfigLayerMetadata>,
    ) -> Result<()> {
        if let Some(origin) = origins.get("agent.persistent_memory.directory_override")
            && let Some(layer) = layer_stack.layers().iter().find(|layer| layer.metadata == *origin)
        {
            match layer.source {
                ConfigLayerSource::System { .. }
                | ConfigLayerSource::User { .. }
                | ConfigLayerSource::Project { .. } => {}
                ConfigLayerSource::Workspace { .. } | ConfigLayerSource::Runtime => {
                    bail!(
                        "agent.persistent_memory.directory_override may only be set in system, user, or project-profile configuration layers"
                    );
                }
            }
        }

        Ok(())
    }

    /// Reject provider settings from repository-controlled layers before they
    /// can reach provider registration or request handling.
    ///
    /// Workspace and project files are repository-controlled input. They may
    /// configure ordinary agent behavior, but must not introduce executable
    /// authentication commands or redirect provider requests/credentials.
    /// `load_from_file` is an explicit user opt-in and therefore passes
    /// `explicit_config_is_trusted = true`.
    pub(super) fn validate_provider_security_fields(
        layer_stack: &ConfigLayerStack,
        origins: &hashbrown::HashMap<String, ConfigLayerMetadata>,
        config: &VTCodeConfig,
        explicit_config_is_trusted: bool,
    ) -> Result<()> {
        if explicit_config_is_trusted {
            return Ok(());
        }

        if !config.custom_providers.is_empty()
            && let Some(origin) = origins.get("custom_providers")
            && let Some(layer) = Self::enabled_layer_for_origin(layer_stack, origin)
            && Self::is_repository_controlled_source(&layer.source)
        {
            return Err(RepositoryProviderSecurityViolation {
                source: layer.source.clone(),
                message: format!(
                    "repository-controlled configuration cannot define `custom_providers` (including `auth.command`); move custom provider settings to system, user, or an explicitly selected config file (source: {})",
                    layer.source.label()
                ),
            }
            .into());
        }

        for (path, origin) in origins {
            if path == "auth.copilot.command"
                && config
                    .auth
                    .copilot
                    .command
                    .as_deref()
                    .is_some_and(|command| !command.trim().is_empty())
                && let Some(layer) = Self::enabled_layer_for_origin(layer_stack, origin)
                && Self::is_repository_controlled_source(&layer.source)
            {
                bail!(
                    "repository-controlled configuration cannot set `auth.copilot.command`; configure it in system, user, or an explicitly selected config file (source: {})",
                    layer.source.label()
                );
            }
            if !Self::is_provider_endpoint_or_credential_path(path) {
                continue;
            }

            let Some(layer) = Self::enabled_layer_for_origin(layer_stack, origin) else {
                continue;
            };
            if Self::is_repository_controlled_source(&layer.source) {
                return Err(RepositoryProviderSecurityViolation {
                    source: layer.source.clone(),
                    message: format!(
                        "repository-controlled configuration cannot set `{path}`; provider endpoints and credential environment variables must be configured in system, user, or an explicitly selected config file (source: {})",
                        layer.source.label()
                    ),
                }
                .into());
            }
        }

        Ok(())
    }

    /// Reject *relaxing* sandbox values from repository-controlled layers.
    ///
    /// `vtcode.toml` checked into a repository is untrusted input. It may carry
    /// the ordinary serialized defaults (which are not a widening), but it
    /// must not turn off a boundary a trusted layer enabled, switch to full
    /// access, open the network, drop credential path blocking, or weaken
    /// seccomp/resource limits. System/user config and explicitly selected
    /// files remain authoritative, matching the provider-security split.
    pub(super) fn validate_sandbox_security_fields(
        layer_stack: &ConfigLayerStack,
        origins: &hashbrown::HashMap<String, ConfigLayerMetadata>,
        explicit_config_is_trusted: bool,
    ) -> Result<()> {
        if explicit_config_is_trusted {
            return Ok(());
        }

        let trusted_enabled = layer_stack.layers().iter().any(|layer| {
            layer.is_enabled()
                && matches!(layer.source, ConfigLayerSource::System { .. } | ConfigLayerSource::User { .. })
                && Self::toml_bool_at(&layer.config, "sandbox.enabled") == Some(true)
        });

        for (path, origin) in origins {
            let Some(layer) = Self::enabled_layer_for_origin(layer_stack, origin) else {
                continue;
            };
            if !Self::is_repository_controlled_source(&layer.source) {
                continue;
            }
            let value = Self::toml_value_at(&layer.config, path);
            let relaxing = match path.as_str() {
                "sandbox.enabled" => trusted_enabled && value.and_then(toml::Value::as_bool) == Some(false),
                "sandbox.default_policy" => value
                    .and_then(toml::Value::as_str)
                    .is_some_and(|policy| matches!(policy, "danger_full_access" | "external")),
                "sandbox.network.policy" => value.and_then(toml::Value::as_str) == Some("allow_all"),
                "sandbox.network.allow_all" => value.and_then(toml::Value::as_bool) == Some(true),
                "sandbox.sensitive_paths.use_defaults" => value.and_then(toml::Value::as_bool) == Some(false),
                "sandbox.sensitive_paths.exceptions" => {
                    value.and_then(toml::Value::as_array).is_some_and(|paths| !paths.is_empty())
                }
                "sandbox.resource_limits.preset" => value
                    .and_then(toml::Value::as_str)
                    .is_some_and(|preset| matches!(preset, "unlimited" | "generous")),
                "sandbox.seccomp.enabled" => value.and_then(toml::Value::as_bool) == Some(false),
                "sandbox.seccomp.profile" => value
                    .and_then(toml::Value::as_str)
                    .is_some_and(|profile| matches!(profile, "permissive" | "disabled")),
                "sandbox.seccomp.log_only" => value.and_then(toml::Value::as_bool) == Some(true),
                _ => false,
            };
            if relaxing {
                bail!(
                    "repository-controlled configuration cannot relax `{path}`; the sandbox boundary must come from system, user, or an explicitly selected config file (source: {})",
                    layer.source.label()
                );
            }
        }

        Ok(())
    }

    pub(super) fn toml_value_at<'a>(root: &'a toml::Value, path: &str) -> Option<&'a toml::Value> {
        path.split('.').try_fold(root, |value, part| value.get(part))
    }

    pub(super) fn toml_bool_at(root: &toml::Value, path: &str) -> Option<bool> {
        Self::toml_value_at(root, path).and_then(toml::Value::as_bool)
    }
}