2599 lines · 93.9 KB · Rust
RawDownload
use remote::Interactive;use std::{    any::Any,    borrow::Borrow,    path::{Path, PathBuf},    str::FromStr as _,    sync::Arc,    time::Duration,}; use anyhow::{Context as _, Result, bail};use collections::HashMap;use fs::{Fs, RemoveOptions, RenameOptions};use futures::StreamExt as _;use gpui::{    AppContext as _, AsyncApp, Context, Entity, EventEmitter, SharedString, Subscription, Task,};use http_client::{HttpClient, github::AssetKind};use node_runtime::NodeRuntime;use remote::RemoteClient;use rpc::{    AnyProtoClient, TypedEnvelope,    proto::{self, ExternalExtensionAgent},};use schemars::JsonSchema;use semver::Version;use serde::{Deserialize, Serialize};use settings::{RegisterSetting, SettingsStore};use task::{Shell, SpawnInTerminal};use util::{ResultExt as _, debug_panic}; use crate::ProjectEnvironment; #[derive(Deserialize, Serialize, Clone, PartialEq, Eq, JsonSchema)]pub struct AgentServerCommand {    #[serde(rename = "command")]    pub path: PathBuf,    #[serde(default)]    pub args: Vec<String>,    pub env: Option<HashMap<String, String>>,} impl std::fmt::Debug for AgentServerCommand {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        let filtered_env = self.env.as_ref().map(|env| {            env.iter()                .map(|(k, v)| {                    (                        k,                        if util::redact::should_redact(k) {                            "[REDACTED]"                        } else {                            v                        },                    )                })                .collect::<Vec<_>>()        });         f.debug_struct("AgentServerCommand")            .field("path", &self.path)            .field("args", &self.args)            .field("env", &filtered_env)            .finish()    }} #[derive(Clone, Debug, PartialEq, Eq, Hash)]pub struct ExternalAgentServerName(pub SharedString); impl std::fmt::Display for ExternalAgentServerName {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        write!(f, "{}", self.0)    }} impl From<&'static str> for ExternalAgentServerName {    fn from(value: &'static str) -> Self {        ExternalAgentServerName(value.into())    }} impl From<ExternalAgentServerName> for SharedString {    fn from(value: ExternalAgentServerName) -> Self {        value.0    }} impl Borrow<str> for ExternalAgentServerName {    fn borrow(&self) -> &str {        &self.0    }} pub trait ExternalAgentServer {    fn get_command(        &mut self,        root_dir: Option<&str>,        extra_env: HashMap<String, String>,        status_tx: Option<watch::Sender<SharedString>>,        new_version_available_tx: Option<watch::Sender<Option<String>>>,        cx: &mut AsyncApp,    ) -> Task<Result<(AgentServerCommand, String, Option<task::SpawnInTerminal>)>>;     fn as_any_mut(&mut self) -> &mut dyn Any;} impl dyn ExternalAgentServer {    fn downcast_mut<T: ExternalAgentServer + 'static>(&mut self) -> Option<&mut T> {        self.as_any_mut().downcast_mut()    }} enum AgentServerStoreState {    Local {        node_runtime: NodeRuntime,        fs: Arc<dyn Fs>,        project_environment: Entity<ProjectEnvironment>,        downstream_client: Option<(u64, AnyProtoClient)>,        settings: Option<AllAgentServersSettings>,        http_client: Arc<dyn HttpClient>,        extension_agents: Vec<(            Arc<str>,            String,            HashMap<String, extension::TargetConfig>,            HashMap<String, String>,            Option<String>,        )>,        _subscriptions: [Subscription; 1],    },    Remote {        project_id: u64,        upstream_client: Entity<RemoteClient>,    },    Collab,} pub struct AgentServerStore {    state: AgentServerStoreState,    external_agents: HashMap<ExternalAgentServerName, Box<dyn ExternalAgentServer>>,    agent_icons: HashMap<ExternalAgentServerName, SharedString>,    agent_display_names: HashMap<ExternalAgentServerName, SharedString>,} pub struct AgentServersUpdated; impl EventEmitter<AgentServersUpdated> for AgentServerStore {} #[cfg(test)]mod ext_agent_tests {    use super::*;    use std::{collections::HashSet, fmt::Write as _};     // Helper to build a store in Collab mode so we can mutate internal maps without    // needing to spin up a full project environment.    fn collab_store() -> AgentServerStore {        AgentServerStore {            state: AgentServerStoreState::Collab,            external_agents: HashMap::default(),            agent_icons: HashMap::default(),            agent_display_names: HashMap::default(),        }    }     // A simple fake that implements ExternalAgentServer without needing async plumbing.    struct NoopExternalAgent;     impl ExternalAgentServer for NoopExternalAgent {        fn get_command(            &mut self,            _root_dir: Option<&str>,            _extra_env: HashMap<String, String>,            _status_tx: Option<watch::Sender<SharedString>>,            _new_version_available_tx: Option<watch::Sender<Option<String>>>,            _cx: &mut AsyncApp,        ) -> Task<Result<(AgentServerCommand, String, Option<task::SpawnInTerminal>)>> {            Task::ready(Ok((                AgentServerCommand {                    path: PathBuf::from("noop"),                    args: Vec::new(),                    env: None,                },                "".to_string(),                None,            )))        }         fn as_any_mut(&mut self) -> &mut dyn Any {            self        }    }     #[test]    fn external_agent_server_name_display() {        let name = ExternalAgentServerName(SharedString::from("Ext: Tool"));        let mut s = String::new();        write!(&mut s, "{name}").unwrap();        assert_eq!(s, "Ext: Tool");    }     #[test]    fn sync_extension_agents_removes_previous_extension_entries() {        let mut store = collab_store();         // Seed with a couple of agents that will be replaced by extensions        store.external_agents.insert(            ExternalAgentServerName(SharedString::from("foo-agent")),            Box::new(NoopExternalAgent) as Box<dyn ExternalAgentServer>,        );        store.external_agents.insert(            ExternalAgentServerName(SharedString::from("bar-agent")),            Box::new(NoopExternalAgent) as Box<dyn ExternalAgentServer>,        );        store.external_agents.insert(            ExternalAgentServerName(SharedString::from("custom")),            Box::new(NoopExternalAgent) as Box<dyn ExternalAgentServer>,        );         // Simulate the removal phase: if we're syncing extensions that provide        // "foo-agent" and "bar-agent", those should be removed first        let extension_agent_names: HashSet<String> =            ["foo-agent".to_string(), "bar-agent".to_string()]                .into_iter()                .collect();         let keys_to_remove: Vec<_> = store            .external_agents            .keys()            .filter(|name| extension_agent_names.contains(name.0.as_ref()))            .cloned()            .collect();         for key in keys_to_remove {            store.external_agents.remove(&key);        }         // Only the custom entry should remain.        let remaining: Vec<_> = store            .external_agents            .keys()            .map(|k| k.0.to_string())            .collect();        assert_eq!(remaining, vec!["custom".to_string()]);    }     #[test]    fn resolve_extension_icon_path_allows_valid_paths() {        // Create a temporary directory structure for testing        let temp_dir = tempfile::tempdir().unwrap();        let extensions_dir = temp_dir.path();        let ext_dir = extensions_dir.join("my-extension");        std::fs::create_dir_all(&ext_dir).unwrap();         // Create a valid icon file        let icon_path = ext_dir.join("icon.svg");        std::fs::write(&icon_path, "<svg></svg>").unwrap();         // Test that a valid relative path works        let result = super::resolve_extension_icon_path(extensions_dir, "my-extension", "icon.svg");        assert!(result.is_some());        assert!(result.unwrap().ends_with("icon.svg"));    }     #[test]    fn resolve_extension_icon_path_allows_nested_paths() {        let temp_dir = tempfile::tempdir().unwrap();        let extensions_dir = temp_dir.path();        let ext_dir = extensions_dir.join("my-extension");        let icons_dir = ext_dir.join("assets").join("icons");        std::fs::create_dir_all(&icons_dir).unwrap();         let icon_path = icons_dir.join("logo.svg");        std::fs::write(&icon_path, "<svg></svg>").unwrap();         let result = super::resolve_extension_icon_path(            extensions_dir,            "my-extension",            "assets/icons/logo.svg",        );        assert!(result.is_some());        assert!(result.unwrap().ends_with("logo.svg"));    }     #[test]    fn resolve_extension_icon_path_blocks_path_traversal() {        let temp_dir = tempfile::tempdir().unwrap();        let extensions_dir = temp_dir.path();         // Create two extension directories        let ext1_dir = extensions_dir.join("extension1");        let ext2_dir = extensions_dir.join("extension2");        std::fs::create_dir_all(&ext1_dir).unwrap();        std::fs::create_dir_all(&ext2_dir).unwrap();         // Create a file in extension2        let secret_file = ext2_dir.join("secret.svg");        std::fs::write(&secret_file, "<svg>secret</svg>").unwrap();         // Try to access extension2's file from extension1 using path traversal        let result = super::resolve_extension_icon_path(            extensions_dir,            "extension1",            "../extension2/secret.svg",        );        assert!(            result.is_none(),            "Path traversal to sibling extension should be blocked"        );    }     #[test]    fn resolve_extension_icon_path_blocks_absolute_escape() {        let temp_dir = tempfile::tempdir().unwrap();        let extensions_dir = temp_dir.path();        let ext_dir = extensions_dir.join("my-extension");        std::fs::create_dir_all(&ext_dir).unwrap();         // Create a file outside the extensions directory        let outside_file = temp_dir.path().join("outside.svg");        std::fs::write(&outside_file, "<svg>outside</svg>").unwrap();         // Try to escape to parent directory        let result =            super::resolve_extension_icon_path(extensions_dir, "my-extension", "../outside.svg");        assert!(            result.is_none(),            "Path traversal to parent directory should be blocked"        );    }     #[test]    fn resolve_extension_icon_path_blocks_deep_traversal() {        let temp_dir = tempfile::tempdir().unwrap();        let extensions_dir = temp_dir.path();        let ext_dir = extensions_dir.join("my-extension");        std::fs::create_dir_all(&ext_dir).unwrap();         // Try deep path traversal        let result = super::resolve_extension_icon_path(            extensions_dir,            "my-extension",            "../../../../../../etc/passwd",        );        assert!(            result.is_none(),            "Deep path traversal should be blocked (file doesn't exist)"        );    }     #[test]    fn resolve_extension_icon_path_returns_none_for_nonexistent() {        let temp_dir = tempfile::tempdir().unwrap();        let extensions_dir = temp_dir.path();        let ext_dir = extensions_dir.join("my-extension");        std::fs::create_dir_all(&ext_dir).unwrap();         // Try to access a file that doesn't exist        let result =            super::resolve_extension_icon_path(extensions_dir, "my-extension", "nonexistent.svg");        assert!(result.is_none(), "Nonexistent file should return None");    }} impl AgentServerStore {    /// Synchronizes extension-provided agent servers with the store.    pub fn sync_extension_agents<'a, I>(        &mut self,        manifests: I,        extensions_dir: PathBuf,        cx: &mut Context<Self>,    ) where        I: IntoIterator<Item = (&'a str, &'a extension::ExtensionManifest)>,    {        // Collect manifests first so we can iterate twice        let manifests: Vec<_> = manifests.into_iter().collect();         // Remove all extension-provided agents        // (They will be re-added below if they're in the currently installed extensions)        self.external_agents.retain(|name, agent| {            if agent.downcast_mut::<LocalExtensionArchiveAgent>().is_some() {                self.agent_icons.remove(name);                self.agent_display_names.remove(name);                false            } else {                // Keep the hardcoded external agents that don't come from extensions                // (In the future we may move these over to being extensions too.)                true            }        });         // Insert agent servers from extension manifests        match &mut self.state {            AgentServerStoreState::Local {                extension_agents, ..            } => {                extension_agents.clear();                for (ext_id, manifest) in manifests {                    for (agent_name, agent_entry) in &manifest.agent_servers {                        // Store display name from manifest                        self.agent_display_names.insert(                            ExternalAgentServerName(agent_name.clone().into()),                            SharedString::from(agent_entry.name.clone()),                        );                         let icon_path = if let Some(icon) = &agent_entry.icon {                            if let Some(absolute_icon_path) =                                resolve_extension_icon_path(&extensions_dir, ext_id, icon)                            {                                self.agent_icons.insert(                                    ExternalAgentServerName(agent_name.clone().into()),                                    SharedString::from(absolute_icon_path.clone()),                                );                                Some(absolute_icon_path)                            } else {                                None                            }                        } else {                            None                        };                         extension_agents.push((                            agent_name.clone(),                            ext_id.to_owned(),                            agent_entry.targets.clone(),                            agent_entry.env.clone(),                            icon_path,                        ));                    }                }                self.reregister_agents(cx);            }            AgentServerStoreState::Remote {                project_id,                upstream_client,            } => {                let mut agents = vec![];                for (ext_id, manifest) in manifests {                    for (agent_name, agent_entry) in &manifest.agent_servers {                        // Store display name from manifest                        self.agent_display_names.insert(                            ExternalAgentServerName(agent_name.clone().into()),                            SharedString::from(agent_entry.name.clone()),                        );                         let icon = if let Some(icon) = &agent_entry.icon {                            if let Some(absolute_icon_path) =                                resolve_extension_icon_path(&extensions_dir, ext_id, icon)                            {                                self.agent_icons.insert(                                    ExternalAgentServerName(agent_name.clone().into()),                                    SharedString::from(absolute_icon_path.clone()),                                );                                Some(absolute_icon_path)                            } else {                                None                            }                        } else {                            None                        };                         agents.push(ExternalExtensionAgent {                            name: agent_name.to_string(),                            icon_path: icon,                            extension_id: ext_id.to_string(),                            targets: agent_entry                                .targets                                .iter()                                .map(|(k, v)| (k.clone(), v.to_proto()))                                .collect(),                            env: agent_entry                                .env                                .iter()                                .map(|(k, v)| (k.clone(), v.clone()))                                .collect(),                        });                    }                }                upstream_client                    .read(cx)                    .proto_client()                    .send(proto::ExternalExtensionAgentsUpdated {                        project_id: *project_id,                        agents,                    })                    .log_err();            }            AgentServerStoreState::Collab => {                // Do nothing            }        }         cx.emit(AgentServersUpdated);    }     pub fn agent_icon(&self, name: &ExternalAgentServerName) -> Option<SharedString> {        self.agent_icons.get(name).cloned()    }} /// Safely resolves an extension icon path, ensuring it stays within the extension directory.

Lines 1–500 of 2599.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t