diff --git a/crates/ide-host/src/ops/debug.rs b/crates/ide-host/src/ops/debug.rs index 5ddcaf9ed..f6513ee0d 100644 --- a/crates/ide-host/src/ops/debug.rs +++ b/crates/ide-host/src/ops/debug.rs @@ -13,9 +13,13 @@ use std::path::{Path, PathBuf}; /// Starts a session owned by this window: its events (and those of child sessions) go here only. #[command(trust = trusted)] -pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> IdeResult { +pub async fn debug_start(host: &Host, window: &str, mut config: LaunchConfig) -> IdeResult { let project = host.project(window)?; project.require_trust()?; + let plugin_run = take_plugin_run(&mut config)?; + if let Some(run) = &plugin_run { + verify_plugin_run(host, window, run, Some(&config.adapter)).await?; + } let cancel = project.closed.child_token(); let unity_pid = if config.adapter == "unity" { if config.request != "attach" { @@ -36,7 +40,6 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide } else { None }; - let mut config = config; let enhanced = take_enhanced_redefinition(&mut config); let executor = take_executor(&mut config); let java_exec = java_exec_path(&config); @@ -179,6 +182,9 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide return Err(ide_core::IdeError::cancelled()); } host.require_trust(window)?; + if let Some(run) = &plugin_run { + verify_plugin_run(host, window, run, None).await?; + } let server_port = debug_server_port(&config); let exception_classes = server_port.and_then(|port| exception_class_backend(host, window, port)); let result = host.debugger.start_with_cancel(config, owner, custom, exception_classes, cancel).await; @@ -203,6 +209,36 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide result } +#[derive(serde::Deserialize)] +struct PluginRun { + config: ide_run::RunConfig, + program: String, +} + +fn take_plugin_run(config: &mut LaunchConfig) -> IdeResult> { + let Some(raw) = &config.extra_json else { return Ok(None) }; + if !raw.contains("__openideaPluginRun") { + return Ok(None); + } + let mut extra: serde_json::Map = + serde_json::from_str(raw).map_err(|e| ide_core::IdeError::invalid(e.to_string()))?; + let Some(run) = extra.remove("__openideaPluginRun") else { return Ok(None) }; + extra.remove(ide_dap::native::ADAPTER_COMMAND); + config.extra_json = Some(serde_json::Value::Object(extra).to_string()); + serde_json::from_value(run).map(Some).map_err(|e| ide_core::IdeError::invalid(e.to_string())) +} + +async fn verify_plugin_run(host: &Host, window: &str, run: &PluginRun, adapter: Option<&str>) -> IdeResult<()> { + let denied = |message| ide_core::IdeError::new(ide_core::error::ErrorKind::PermissionDenied, message); + let plugins = host.plugin_host().ok_or_else(|| denied("plugin host is not available"))?; + let (window, config) = (window.to_owned(), run.config.clone()); + let checked = host.blocking(move || plugins.prepare_debug_run(&window, config)).await?; + if checked.command != run.program || adapter.is_some_and(|name| checked.debug_adapter.as_deref() != Some(name)) { + return Err(denied("plugin debug configuration changed before launch")); + } + Ok(()) +} + fn native_debugger_command( root: &Path, settings: &ide_core::settings::CppDebuggerSettings, diff --git a/crates/ide-host/src/ops/run.rs b/crates/ide-host/src/ops/run.rs index 134737452..597c66c0c 100644 --- a/crates/ide-host/src/ops/run.rs +++ b/crates/ide-host/src/ops/run.rs @@ -373,28 +373,23 @@ async fn start_inner( if config.extras.target.is_none() { config.extras.target = ide_sdk::apply::run_target(&config, &project.settings.effective()).map(str::to_owned); } - if config.detected - && config.id.starts_with(ide_run::EXTERNAL_PREFIX) - && let Some(plugins) = host.plugin_host() - { - let provider = plugins.run_detection(); - let binary = - provider.launch(&config).map_err(|e| IdeError::new(ide_core::error::ErrorKind::PermissionDenied, e))?; - config.command = if config.extras.target.as_ref().is_some_and(|t| !t.is_empty()) { - provider - .detect(&project.root) - .into_iter() - .find(|c| c.id == config.id) - .ok_or_else(|| IdeError::not_found("plugin configuration no longer available"))? - .command - } else { - binary.to_string_lossy().into_owned() - }; - config.detected = false; - } let mut sink = project.sink.clone(); + let mut direct_stop = None; + let mut plugin_authorized = false; if let Some(plugins) = host.plugin_host() { - sink = plugins.run_operation_sink(window, &mut config, sink)?; + let (next_sink, matched_op, op_stop) = plugins.run_operation_sink(window, &project.root, &mut config, sink)?; + sink = next_sink; + if matched_op { + plugin_authorized = true; + direct_stop = op_stop; + } + } + if !plugin_authorized && let Some(owner) = crate::plugins::plugin_run_config_owner(&config)? { + let plugins = host.plugin_host().ok_or_else(|| { + IdeError::new(ide_core::error::ErrorKind::PermissionDenied, "plugin host is not available") + })?; + direct_stop = plugins.authorize_run_config(&project.root, &owner, &mut config)?; + plugin_authorized = true; } if let Some(agent) = agent { sink = agent.wrap_sink(sink); @@ -442,6 +437,8 @@ async fn start_inner( plots: None, capture_junit_reports: false, conda_prefix: None, + direct_stop: None, + plugin_authorized: true, }, sink, Box::new(move |c| on_output(c)), @@ -473,6 +470,8 @@ async fn start_inner( plots: None, capture_junit_reports: false, conda_prefix: None, + direct_stop: None, + plugin_authorized, }; project.require_trust()?; return host.processes.start( @@ -506,7 +505,7 @@ async fn start_inner( fallback.as_deref(), &settings, ); - } else { + } else if !plugin_authorized { ide_sdk::apply::resolve_run_command(&mut config, root, &settings); } if config.kind == "go" { @@ -617,6 +616,8 @@ async fn start_inner( plots: if is_python { super::plots::prepare(host, &project).await } else { None }, capture_junit_reports: config.is_test && config.extras.test_runner.as_deref() == Some("jvm"), conda_prefix, + direct_stop, + plugin_authorized, }; project.require_trust()?; if config.kind == "go" && matches!(config.args.first().map(String::as_str), Some("mod" | "work")) { diff --git a/crates/ide-host/src/plugins/execution.rs b/crates/ide-host/src/plugins/execution.rs index ab0507b62..44c45ca1f 100644 --- a/crates/ide-host/src/plugins/execution.rs +++ b/crates/ide-host/src/plugins/execution.rs @@ -591,30 +591,433 @@ impl PluginHost { } } +/// Owner of a plugin run configuration derived from its kind and/or id. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum PluginRunConfigOwner { + /// A configuration created from `[[contributes.runConfigTypes]]` (`kind = "plugin::"`). + CustomType { plugin: String, type_id: String }, + /// A detected plugin configuration (or its saved override), with `kind = "plugin"` or a `plugin:` id. + Detected { plugin: String, config_id: String }, +} + +/// Identifies the owning plugin for any plugin-authored run configuration. +pub(crate) fn plugin_run_config_owner(config: &ide_run::RunConfig) -> IdeResult> { + if let Some(rest) = config.kind.strip_prefix(ide_run::EXTERNAL_PREFIX) { + let Some((plugin, type_id)) = rest.split_once(':') else { + return Err(IdeError::invalid("invalid plugin run configuration kind")); + }; + if plugin.is_empty() || type_id.is_empty() || type_id.contains(':') { + return Err(IdeError::invalid("invalid plugin run configuration kind")); + } + let raw_id = config + .id + .strip_prefix("workspace:") + .and_then(|s| s.split_once(':')) + .map_or(config.id.as_str(), |(_, rest)| rest); + if let Some(id_plugin) = raw_id.strip_prefix(ide_run::EXTERNAL_PREFIX).and_then(|s| s.split(':').next()) + && id_plugin != plugin + { + return Err(IdeError::invalid("plugin run configuration id does not match its kind")); + } + return Ok(Some(PluginRunConfigOwner::CustomType { plugin: plugin.into(), type_id: type_id.into() })); + } + let raw_id = config + .id + .strip_prefix("workspace:") + .and_then(|s| s.split_once(':')) + .map_or(config.id.as_str(), |(_, rest)| rest); + if config.kind == "plugin" || raw_id.starts_with(ide_run::EXTERNAL_PREFIX) { + if config.kind != "plugin" { + return Err(IdeError::invalid("plugin detection id requires a plugin configuration kind")); + } + let Some((plugin, config_id)) = raw_id.strip_prefix(ide_run::EXTERNAL_PREFIX).and_then(|s| s.split_once(':')) + else { + return Err(IdeError::invalid("invalid plugin run configuration")); + }; + if plugin.is_empty() || config_id.is_empty() { + return Err(IdeError::invalid("invalid plugin run configuration")); + } + return Ok(Some(PluginRunConfigOwner::Detected { plugin: plugin.into(), config_id: config_id.into() })); + } + Ok(None) +} + +fn validate_plugin_program(program: &str) -> IdeResult<&str> { + if program.is_empty() + || program.len() > 256 + || program.chars().any(|c| c.is_whitespace() || c.is_control() || "|&;<>$`()".contains(c)) + || (program.contains(['/', '\\']) && !std::path::Path::new(program).is_absolute()) + { + return Err(IdeError::invalid( + "plugin run configuration command must name a single program or approved executable", + )); + } + Ok(program) +} + +fn validate_plugin_run_args(args: &[String]) -> IdeResult<()> { + if args.len() > 256 || args.iter().any(|a| a.len() > 32768 || a.contains('\0')) { + return Err(IdeError::invalid("invalid plugin run configuration arguments")); + } + Ok(()) +} + +fn is_loader_env(name: &str) -> bool { + matches!( + name.to_ascii_uppercase().as_str(), + "LD_PRELOAD" + | "LD_AUDIT" + | "LD_LIBRARY_PATH" + | "DYLD_INSERT_LIBRARIES" + | "DYLD_LIBRARY_PATH" + | "DYLD_FRAMEWORK_PATH" + | "DYLD_FALLBACK_LIBRARY_PATH" + | "DYLD_FALLBACK_FRAMEWORK_PATH" + ) +} + +fn validate_plugin_run_env(env: &std::collections::BTreeMap) -> IdeResult<()> { + if env.len() > 64 { + return Err(IdeError::invalid("at most 64 environment variables")); + } + for (name, value) in env { + if name.is_empty() || name.len() > 256 || name.contains(['=', '\0']) || name.chars().any(char::is_whitespace) { + return Err(IdeError::invalid(format!("{name:?} is not an environment variable name"))); + } + if value.len() > 32768 || value.contains('\0') { + return Err(IdeError::invalid(format!("the value of {name:?} is too long or holds a NUL"))); + } + if inherited_env(name) || is_loader_env(name) { + return Err(IdeError::invalid(format!( + "environment variable {name:?} cannot override an inherited or loader variable" + ))); + } + } + Ok(()) +} + +fn validate_plugin_cwd( + root: &std::path::Path, + cwd: Option<&ide_core::IpcPath>, +) -> IdeResult> { + let Some(path) = cwd.filter(|p| !p.as_os_str().is_empty()) else { + return Ok(None); + }; + let resolved = ide_plugin::resolve_in_root(root, &path.to_string_lossy()).map_err(IdeError::invalid)?; + Ok(Some(resolved.into())) +} + +fn parse_plugin_stop_command(line: &str) -> IdeResult<(String, Vec)> { + let trimmed = line.trim(); + if trimmed.is_empty() || trimmed.len() > 4096 || trimmed.contains(['\0', '\r', '\n']) { + return Err(IdeError::invalid("invalid plugin stop command")); + } + let mut tokens = Vec::new(); + let mut current = String::new(); + let mut in_token = false; + let mut quote: Option = None; + let mut chars = trimmed.chars().peekable(); + while let Some(c) = chars.next() { + match quote { + Some('\'') => { + if c == '\'' { + quote = None; + } else { + current.push(c); + } + } + Some('"') => { + if c == '"' { + quote = None; + } else if c == '\\' { + if let Some(&next) = chars.peek() + && matches!(next, '"' | '\\') + { + current.push(chars.next().unwrap()); + } else { + current.push('\\'); + } + } else { + current.push(c); + } + } + None => { + if c.is_ascii_whitespace() { + if in_token { + tokens.push(std::mem::take(&mut current)); + in_token = false; + } + } else if c == '\'' || c == '"' { + quote = Some(c); + in_token = true; + } else if c == '\\' { + let Some(escaped) = chars.next() else { + return Err(IdeError::invalid("plugin stop command has a trailing backslash")); + }; + current.push(escaped); + in_token = true; + } else if "|&;<>$`()".contains(c) { + return Err(IdeError::invalid( + "plugin stop command must invoke a single executable without shell syntax", + )); + } else { + current.push(c); + in_token = true; + } + } + Some(_) => unreachable!(), + } + } + if quote.is_some() { + return Err(IdeError::invalid("plugin stop command has an unclosed quote")); + } + if in_token { + tokens.push(current); + } + let Some((program, args)) = tokens.split_first() else { + return Err(IdeError::invalid("plugin stop command has no program")); + }; + let program = validate_plugin_program(program)?.to_owned(); + let args = args.to_vec(); + validate_plugin_run_args(&args)?; + Ok((program, args)) +} + +fn format_stop_display(program: &str, args: &[String]) -> String { + let quote = |s: &str| { + if !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "-_./:=@,+".contains(c)) { + s.to_owned() + } else { + format!("'{}'", s.replace('\'', "'\\''")) + } + }; + let mut out = quote(program); + for arg in args { + out.push(' '); + out.push_str("e(arg)); + } + out +} + +fn require_valid_debug_adapter(adapter: Option) -> IdeResult { + let Some(adapter) = adapter.filter(|a| !a.is_empty()) else { + return Err(IdeError::invalid("this configuration has no debugger")); + }; + if adapter.len() > 128 || adapter.chars().any(|c| c.is_whitespace() || c.is_control()) { + return Err(IdeError::invalid("invalid debug adapter")); + } + Ok(adapter) +} + impl PluginHost { + fn authorize_plugin_stop( + self: &Arc, + plugin: &str, + root: &std::path::Path, + stop_command: Option<&str>, + has_target: bool, + ) -> IdeResult> { + let Some(line) = stop_command.map(str::trim).filter(|s| !s.is_empty()) else { + return Ok(None); + }; + if has_target { + return Err(IdeError::invalid( + "custom stop commands are not supported for plugin configurations on a run target", + )); + } + let (stop_program, stop_args) = parse_plugin_stop_command(line)?; + let loaded = self.get(plugin)?; + if !loaded.status().is_live() { + return Err(IdeError::new( + ide_core::error::ErrorKind::PermissionDenied, + format!("plugin {plugin:?} is not enabled"), + )); + } + let pinned = self.program_for_project(plugin, &stop_program, Some(root))?; + let display = format_stop_display(&stop_program, &stop_args); + let weak = Arc::downgrade(self); + let plugin_id = plugin.to_owned(); + let program_name = stop_program; + let project_root = root.to_path_buf(); + let verify: Arc Result + Send + Sync> = Arc::new(move || { + let Some(plugins) = weak.upgrade() else { + return Err("plugin host is no longer available".into()); + }; + let loaded = plugins.get(&plugin_id).map_err(|e| e.to_string())?; + if !loaded.status().is_live() { + return Err(format!("plugin {plugin_id:?} is no longer enabled")); + } + plugins.program_for_project(&plugin_id, &program_name, Some(&project_root)).map_err(|e| e.to_string()) + }); + Ok(Some(ide_run::DirectStop { program: pinned, args: stop_args, display, verify: Some(verify) })) + } + + /// Authorizes a plugin-owned run configuration before `ProcessManager::start` (or remote target launch): + /// requires the plugin to be live, checks its `process:` grant & executable pin, constrains env & cwd, + /// and converts any `stop_command` into a shell-free re-verified [`ide_run::DirectStop`]. + pub(crate) fn authorize_run_config( + self: &Arc, + root: &std::path::Path, + owner: &PluginRunConfigOwner, + config: &mut ide_run::RunConfig, + ) -> IdeResult> { + if config.is_test && config.extras.emulate_terminal { + return Err(IdeError::invalid("test configurations cannot emulate a terminal")); + } + let has_target = config.extras.target.as_deref().is_some_and(|t| !t.is_empty()); + let plugin = match owner { + PluginRunConfigOwner::CustomType { plugin, type_id } => { + let loaded = self.get(plugin)?; + if !loaded.status().is_live() { + return Err(IdeError::new( + ide_core::error::ErrorKind::PermissionDenied, + format!("plugin {plugin:?} is not enabled"), + )); + } + if !self.ui.items(super::ui_points::RUN_CONFIG_TYPES, Some(plugin)).iter().any(|i| i.key == *type_id) { + return Err(IdeError::not_found(format!( + "plugin {plugin:?} does not declare run configuration type {type_id:?}" + ))); + } + let program = validate_plugin_program(&config.command)?.to_owned(); + validate_plugin_run_args(&config.args)?; + validate_plugin_run_env(&config.env)?; + if !has_target { + config.cwd = validate_plugin_cwd(root, config.cwd.as_ref())?; + } + let binary = self.program_for_project(plugin, &program, Some(root))?; + config.command = if has_target { program } else { binary.to_string_lossy().into_owned() }; + config.detected = false; + plugin.as_str() + } + PluginRunConfigOwner::Detected { plugin, .. } => { + if config.detected && config.id.starts_with(ide_run::EXTERNAL_PREFIX) { + let provider = self.run_detection(); + let binary = provider + .launch(config) + .map_err(|e| IdeError::new(ide_core::error::ErrorKind::PermissionDenied, e))?; + config.command = if has_target { + provider + .detect(root) + .into_iter() + .find(|c| c.id == config.id) + .ok_or_else(|| IdeError::not_found("plugin configuration no longer available"))? + .command + } else { + binary.to_string_lossy().into_owned() + }; + config.detected = false; + } else { + let loaded = self.get(plugin)?; + if !loaded.status().is_live() { + return Err(IdeError::new( + ide_core::error::ErrorKind::PermissionDenied, + format!("plugin {plugin:?} is not enabled"), + )); + } + let program = validate_plugin_program(&config.command)?.to_owned(); + validate_plugin_run_args(&config.args)?; + validate_plugin_run_env(&config.env)?; + if !has_target { + config.cwd = validate_plugin_cwd(root, config.cwd.as_ref())?; + } + let binary = self.program_for_project(plugin, &program, Some(root))?; + config.command = if has_target { program } else { binary.to_string_lossy().into_owned() }; + config.detected = false; + } + plugin.as_str() + } + }; + let stop = self.authorize_plugin_stop(plugin, root, config.extras.stop_command.as_deref(), has_target)?; + config.extras.stop_command = None; + Ok(stop) + } + /// Rechecks the owned configuration's program before Debug and every IDE rerun. pub fn prepare_debug_run(&self, client: &str, mut config: ide_run::RunConfig) -> IdeResult { - let Some((plugin, id)) = config.id.strip_prefix(ide_run::EXTERNAL_PREFIX).and_then(|s| s.split_once(':')) - else { + let Some(owner) = plugin_run_config_owner(&config)? else { return Err(IdeError::invalid("not a plugin configuration")); }; let workspace = self.shared.workspace().ok_or_else(IdeError::cancelled)?; - let owned = workspace.run_configuration(client, plugin, id).map_err(|e| IdeError::invalid(e.to_string()))?; - if owned.debug_adapter.is_none() { - return Err(IdeError::invalid("this configuration has no debugger")); + let project_root = self.shared.project_of(client); + match owner { + PluginRunConfigOwner::Detected { plugin, config_id } => { + let owned = workspace + .run_configuration(client, &plugin, &config_id) + .map_err(|e| IdeError::invalid(e.to_string()))?; + let loaded = self.get(&plugin)?; + if !loaded.status().is_live() { + return Err(IdeError::new( + ide_core::error::ErrorKind::PermissionDenied, + format!("plugin {plugin:?} is not enabled"), + )); + } + if config.extras.target.is_none() { + config.extras.target = owned.extras.target.clone(); + } + if config.extras.target.as_ref().is_some_and(|t| !t.is_empty()) { + return Err(IdeError::invalid("debugging this target is not supported")); + } + let adapter = require_valid_debug_adapter(config.debug_adapter.take().or(owned.debug_adapter))?; + let pinned_owned = self.program_for_project(&plugin, &owned.command, project_root.as_deref()); + let program = if config.command.is_empty() + || config.command == owned.command + || pinned_owned.as_ref().is_ok_and(|p| std::path::Path::new(&config.command) == p.as_path()) + { + owned.command + } else { + validate_plugin_program(&config.command)?.to_owned() + }; + validate_plugin_run_args(&config.args)?; + validate_plugin_run_env(&config.env)?; + if let Some(root) = project_root.as_deref() { + config.cwd = validate_plugin_cwd(root, config.cwd.as_ref())?; + } + config.command = self + .program_for_project(&plugin, &program, project_root.as_deref())? + .to_string_lossy() + .into_owned(); + config.debug_adapter = Some(adapter); + } + PluginRunConfigOwner::CustomType { plugin, type_id } => { + let root = project_root.ok_or_else(|| IdeError::invalid("no project in this window"))?; + if !workspace.trusted(&root) { + return Err(IdeError::new(ide_core::error::ErrorKind::PermissionDenied, "project is not trusted")); + } + let loaded = self.get(&plugin)?; + if !loaded.status().is_live() { + return Err(IdeError::new( + ide_core::error::ErrorKind::PermissionDenied, + format!("plugin {plugin:?} is not enabled"), + )); + } + let decl = self + .ui + .items(super::ui_points::RUN_CONFIG_TYPES, Some(&plugin)) + .into_iter() + .find(|i| i.key == type_id) + .ok_or_else(|| { + IdeError::not_found(format!( + "plugin {plugin:?} does not declare run configuration type {type_id:?}" + )) + })?; + if config.extras.target.as_ref().is_some_and(|t| !t.is_empty()) { + return Err(IdeError::invalid("debugging this target is not supported")); + } + let fallback_adapter = decl.decl.get("debugAdapter").and_then(|v| v.as_str()).map(str::to_owned); + let adapter = require_valid_debug_adapter(config.debug_adapter.take().or(fallback_adapter))?; + let program = validate_plugin_program(&config.command)?.to_owned(); + validate_plugin_run_args(&config.args)?; + validate_plugin_run_env(&config.env)?; + config.cwd = validate_plugin_cwd(&root, config.cwd.as_ref())?; + config.command = + self.program_for_project(&plugin, &program, Some(&root))?.to_string_lossy().into_owned(); + config.debug_adapter = Some(adapter); + } } - if config.extras.target.is_none() { - config.extras.target = owned.extras.target.clone(); - } - if config.extras.target.as_ref().is_some_and(|t| !t.is_empty()) { - return Err(IdeError::invalid("debugging this target is not supported")); - } - config.command = self - .program_for_project(plugin, &owned.command, self.shared.project_of(client).as_deref())? - .to_string_lossy() - .into_owned(); - config.debug_adapter = owned.debug_adapter; + config.extras.stop_command = None; config.extras.emulate_terminal = false; + config.detected = false; Ok(config) } } @@ -671,10 +1074,13 @@ impl PluginHost { pub(crate) fn run_operation_sink( self: &Arc, client: &str, + project_root: &std::path::Path, config: &mut ide_run::RunConfig, previous: Arc, - ) -> IdeResult> { - let Some(id) = config.extras.params.get(RUN_OPERATION).cloned() else { return Ok(previous) }; + ) -> IdeResult<(Arc, bool, Option)> { + let Some(id) = config.extras.params.get(RUN_OPERATION).cloned() else { + return Ok((previous, false, None)); + }; let origin = self.shared.operations.lock().get(&id).and_then(|op| { if op.client != client { return None; @@ -682,16 +1088,39 @@ impl PluginHost { let OperationKind::Run { configuration, program, .. } = &op.kind else { return None }; (configuration == &config.id).then(|| (op.plugin.clone(), op.root.clone(), program.clone())) }); - let Some((plugin, root, program)) = origin else { return Ok(previous) }; - let binary = self.program_for_project(&plugin, &program, root.as_deref())?; - config.command = if config.extras.target.as_ref().is_some_and(|t| !t.is_empty()) { - program - } else { - binary.to_string_lossy().into_owned() + let Some((plugin, root, program)) = origin else { + return Ok((previous, false, None)); }; + if !matches!(plugin_run_config_owner(config)?, Some(PluginRunConfigOwner::Detected { plugin: owner, .. }) if owner == plugin) + || root.as_deref().is_some_and(|root| root != project_root) + { + return Err(IdeError::invalid("plugin operation does not match its run configuration")); + } + let loaded = self.get(&plugin)?; + if !loaded.status().is_live() { + return Err(IdeError::new( + ide_core::error::ErrorKind::PermissionDenied, + format!("plugin {plugin:?} is not enabled"), + )); + } + let has_target = config.extras.target.as_deref().is_some_and(|t| !t.is_empty()); + validate_plugin_run_args(&config.args)?; + validate_plugin_run_env(&config.env)?; + if !has_target { + config.cwd = validate_plugin_cwd(project_root, config.cwd.as_ref())?; + } + let binary = self.program_for_project(&plugin, &program, root.as_deref())?; + config.command = if has_target { program } else { binary.to_string_lossy().into_owned() }; config.detected = false; + let stop = self.authorize_plugin_stop( + &plugin, + root.as_deref().unwrap_or(project_root), + config.extras.stop_command.as_deref(), + has_target, + )?; + config.extras.stop_command = None; let (weak, client) = (Arc::downgrade(self), client.to_owned()); - Ok(Arc::new(move |event: ide_core::IdeEvent| { + let wrapped = Arc::new(move |event: ide_core::IdeEvent| { if let ide_core::IdeEvent::RunExited { code, .. } = &event && let Some(plugins) = weak.upgrade() { @@ -699,7 +1128,8 @@ impl PluginHost { plugins.finish_operation(&client, &id, *code, stopped); } previous.emit(event); - })) + }); + Ok((wrapped, true, stop)) } pub(crate) fn run_operation_started(&self, client: &str, operation: &str, run: ide_core::RunId) { if let Some(op) = self @@ -821,4 +1251,39 @@ mod tests { c.output_mode = ide_plugin::PluginOutputMode::Pipes; assert!(validate_configurations(&root, &[c]).is_ok()); } + + #[test] + fn plugin_stop_command_parser_rejects_shell_syntax() { + assert_eq!(parse_plugin_stop_command("catalina stop").unwrap(), ("catalina".into(), vec!["stop".into()])); + assert_eq!( + parse_plugin_stop_command(r#""/opt/tomcat/bin/catalina" stop --force 'now'"#).unwrap(), + ("/opt/tomcat/bin/catalina".into(), vec!["stop".into(), "--force".into(), "now".into()]) + ); + for bad in [ + "", + " ", + "tool; touch /tmp/x", + "tool | cat", + "tool && id", + "tool $(id)", + "tool `id`", + "tool > out.txt", + "tool\nrm -rf /", + "./bin/tool stop", + "\"unclosed stop", + ] { + assert!(parse_plugin_stop_command(bad).is_err(), "{bad:?}"); + } + } + + #[test] + fn plugin_run_env_rejects_inherited_and_loader_vars() { + use std::collections::BTreeMap; + assert!(validate_plugin_run_env(&BTreeMap::from([("APP_PORT".into(), "8080".into())])).is_ok()); + for bad in ["LD_PRELOAD", "ld_library_path", "DYLD_INSERT_LIBRARIES", "DYLD_LIBRARY_PATH"] { + assert!(validate_plugin_run_env(&BTreeMap::from([(bad.into(), "/tmp/evil.so".into())])).is_err(), "{bad}"); + } + let (inherited, _) = std::env::vars().next().expect("inherited env"); + assert!(validate_plugin_run_env(&BTreeMap::from([(inherited, "x".into())])).is_err()); + } } diff --git a/crates/ide-host/src/plugins/mod.rs b/crates/ide-host/src/plugins/mod.rs index 7c05c285c..9153e3310 100644 --- a/crates/ide-host/src/plugins/mod.rs +++ b/crates/ide-host/src/plugins/mod.rs @@ -68,6 +68,7 @@ mod websocket; pub use api::{CredentialSecretStore, FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore}; pub use build_graph::{BuildGraph, GradleModule}; pub use docs::{MAX_PLUGIN_DOC, PluginDocs, explain_capabilities, plugin_docs}; +pub(crate) use execution::plugin_run_config_owner; pub(crate) use hover::merge as merge_hover; pub use icons::{ MAX_PLUGIN_ICON, map_asset as icon_theme_map_asset, plugin_icon, sanitize_svg, svg_prefix as icon_theme_svg_prefix, diff --git a/crates/ide-host/src/plugins/points.rs b/crates/ide-host/src/plugins/points.rs index df69450b6..9c56b38f1 100644 --- a/crates/ide-host/src/plugins/points.rs +++ b/crates/ide-host/src/plugins/points.rs @@ -97,6 +97,7 @@ pub fn register_builtin_points( registry.register(Arc::new(UiPoint::new(p::EDITOR_PANELS, ui.clone(), p::editor_panel)))?; registry.register(Arc::new(UiPoint::new(p::OVERLAYS, ui.clone(), p::overlay)))?; registry.register(Arc::new(UiPoint::new(p::DIALOGS, ui.clone(), p::dialog)))?; + registry.register(Arc::new(UiPoint::new(p::RUN_CONFIG_TYPES, ui.clone(), p::run_config_type)))?; registry.register(Arc::new(UiPoint::new(p::RUN_ANYTHING, ui.clone(), p::run_anything)))?; registry.register(Arc::new(UiPoint::new(p::MARKER_ICONS, ui.clone(), p::marker_icon)))?; registry.register(Arc::new(UiPoint::new(p::FILE_ICONS, ui.clone(), p::file_icon)))?; diff --git a/crates/ide-host/src/plugins/ui_points.rs b/crates/ide-host/src/plugins/ui_points.rs index 78cafc377..a5bc45228 100644 --- a/crates/ide-host/src/plugins/ui_points.rs +++ b/crates/ide-host/src/plugins/ui_points.rs @@ -62,6 +62,11 @@ //! width = 900 # pixels, 320–1600 //! height = 600 # pixels, 200–1200 //! +//! [[contributes.runConfigTypes]] +//! id = "tomcat" +//! label = "SmartTomcat" # shown in Add New Configuration and Edit Configurations +//! web = "web/run-config.html" # custom Run/Debug Configurations form (API 1.20) +//! //! [[contributes.fileIcons]] //! id = "drawing" //! patterns = ["*.excalidraw"] @@ -102,9 +107,10 @@ pub const CUSTOM_EDITORS: &str = "customEditors"; pub const EDITOR_PANELS: &str = "editorPanels"; pub const OVERLAYS: &str = "overlays"; pub const DIALOGS: &str = "dialogs"; +pub const RUN_CONFIG_TYPES: &str = "runConfigTypes"; pub const RUN_ANYTHING: &str = "runAnything"; /// The points whose declarations can name a `web` page (served, messaged, sent view events). -pub const WEB_POINTS: [&str; 5] = [VIEWS, CUSTOM_EDITORS, EDITOR_PANELS, OVERLAYS, DIALOGS]; +pub const WEB_POINTS: [&str; 6] = [VIEWS, CUSTOM_EDITORS, EDITOR_PANELS, OVERLAYS, DIALOGS, RUN_CONFIG_TYPES]; pub const FILE_ICONS: &str = "fileIcons"; pub const MARKER_ICONS: &str = "markerIcons"; pub const FILE_TEMPLATES: &str = "fileTemplates"; @@ -1031,6 +1037,154 @@ pub(super) fn dialog(pkg: &Package, decl: toml::Value) -> Result Ok(out) } +fn is_false(b: &bool) -> bool { + !*b +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RunConfigTypeDecl { + id: String, + label: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + group: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + icon: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + icon_dark: Option, + web: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + layout: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + height: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + command: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + args: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + debug_adapter: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + terminal: Option, + #[serde(default, skip_serializing_if = "is_false")] + owns_working_directory: bool, + #[serde(default, skip_serializing_if = "is_false")] + owns_environment: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + prepare_command: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + match_config_prefix: Option, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + defaults: BTreeMap, +} + +const RUN_CONFIG_HEIGHT: std::ops::RangeInclusive = 120..=1200; + +/// `[[contributes.runConfigTypes]]` (API 1.20): a custom Run/Debug Configurations +/// form rendered by a package web page (`openidea.runConfig`). +pub(super) fn run_config_type(pkg: &Package, decl: toml::Value) -> Result { + let d: RunConfigTypeDecl = decode(RUN_CONFIG_TYPES, decl)?; + pkg.manifest.needs_api(&format!("contributes.{RUN_CONFIG_TYPES}"), 20)?; + validate_item_id(&d.id, "run config type id")?; + let what = format!("run config type {:?}", d.id); + for point in [VIEWS, CUSTOM_EDITORS, EDITOR_PANELS, OVERLAYS, DIALOGS] { + if pkg.manifest.declarations(point).iter().any(|v| v.get("id").and_then(|i| i.as_str()) == Some(&d.id)) { + return Err(format!("{what}: {point} already declares the same id")); + } + } + if d.label.trim().is_empty() || d.label.len() > MAX_TITLE { + return Err(format!("{what}: `label` is 1–{MAX_TITLE} bytes")); + } + if let Some(desc) = &d.description + && (desc.trim().is_empty() || desc.len() > MAX_TITLE) + { + return Err(format!("{what}: `description` is 1–{MAX_TITLE} bytes")); + } + if let Some(group) = &d.group + && (group.trim().is_empty() || group.len() > 128) + { + return Err(format!("{what}: `group` is 1–128 bytes")); + } + if let Some(layout) = &d.layout + && layout != "embedded" + && layout != "full" + { + return Err(format!("{what}: `layout` is embedded or full")); + } + if let Some(height) = d.height + && !RUN_CONFIG_HEIGHT.contains(&height) + { + return Err(format!("{what}: `height` is {}–{} pixels", RUN_CONFIG_HEIGHT.start(), RUN_CONFIG_HEIGHT.end())); + } + if let Some(cmd) = &d.command { + let trimmed = cmd.trim(); + if trimmed != cmd + || trimmed.is_empty() + || trimmed.len() > 256 + || trimmed.chars().any(|c| c.is_whitespace() || c.is_control() || "|&;<>$`()".contains(c)) + || (trimmed.contains(['/', '\\']) && !Path::new(trimmed).is_absolute()) + { + return Err(format!( + "{what}: `command` must be a 1–256 byte program name or absolute path without whitespace or shell syntax" + )); + } + } + if !d.args.is_empty() && d.command.is_none() { + return Err(format!("{what}: `args` requires `command`")); + } + if d.args.len() > 64 || d.args.iter().any(|a| a.len() > 4096 || a.contains('\0')) { + return Err(format!("{what}: at most 64 arguments of up to 4096 bytes without NUL")); + } + if let Some(adapter) = &d.debug_adapter + && (adapter.is_empty() || adapter.len() > 128 || adapter.chars().any(|c| c.is_whitespace() || c == '\0')) + { + return Err(format!("{what}: `debugAdapter` is 1–128 bytes without whitespace")); + } + if let Some(cmd) = &d.prepare_command { + declared_command(pkg, RUN_CONFIG_TYPES, cmd)?; + } + if let Some(prefix) = &d.match_config_prefix + && (prefix.len() > 128 || prefix.contains('\0')) + { + return Err(format!("{what}: `matchConfigPrefix` is up to 128 bytes without NUL")); + } + if d.defaults.len() > 64 + || d.defaults + .iter() + .any(|(k, v)| k.is_empty() || k.len() > 128 || k.contains('\0') || v.len() > 16384 || v.contains('\0')) + { + return Err(format!("{what}: `defaults` allows at most 64 entries")); + } + + let mut files = super::web::web_files(pkg, &d.web, &what)?; + let mut assets = Vec::new(); + if let Some(icon) = &d.icon { + if icon.ends_with(".svg") { + let path = PathBuf::from(icon); + let svg = super::icons::read_icon(pkg, &path, super::icons::MAX_SVG)?; + files.push(path); + assets.push((format!("runConfigIcon/{}", d.id), svg)); + } else if icon.trim().is_empty() || icon.len() > 128 || icon.chars().any(char::is_control) { + return Err(format!("{what}: `icon` is 1–128 bytes without controls")); + } + } + if let Some(dark) = &d.icon_dark { + if !d.icon.as_deref().is_some_and(|i| i.ends_with(".svg")) || !dark.ends_with(".svg") { + return Err(format!("{what}: `iconDark` requires an .svg `icon` and an .svg path")); + } + let path = PathBuf::from(dark); + let svg = super::icons::read_icon(pkg, &path, super::icons::MAX_SVG)?; + files.push(path); + assets.push((format!("runConfigIconDark/{}", d.id), svg)); + } + + let mut out = UiDecl::new(d.id.clone(), d.label.clone(), json(&d)?); + out.files = files; + out.assets = assets; + Ok(out) +} + #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct FileIconDecl { @@ -1853,6 +2007,96 @@ modal = false", } } + #[test] + fn run_config_types_validate_api_fields_icons_and_collisions() { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(dir.path().join("web")).unwrap(); + std::fs::create_dir_all(dir.path().join("icons")).unwrap(); + std::fs::write(dir.path().join("web/form.html"), "
").unwrap(); + let svg = r#""#; + std::fs::write(dir.path().join("icons/tomcat.svg"), svg).unwrap(); + std::fs::write(dir.path().join("icons/tomcat_dark.svg"), svg).unwrap(); + + let minimal = r#"id = "acme.tomcat" +name = "Tomcat" +version = "0.1.0" +engines.openidea = "^1.20" + +[[contributes.runConfigTypes]] +id = "smart-tomcat" +label = "SmartTomcat" +web = "web/form.html" +"#; + let check = |source: &str| { + let manifest = ide_extension::Manifest::parse(source)?; + let decl = manifest.declarations(RUN_CONFIG_TYPES).into_iter().next().unwrap(); + run_config_type(&Package::new(manifest, dir.path().to_path_buf()), decl) + }; + + let valid = check(minimal).unwrap(); + assert_eq!((valid.key.as_str(), valid.label.as_str()), ("smart-tomcat", "SmartTomcat")); + assert_eq!(valid.files, [PathBuf::from("web/form.html")]); + assert!(valid.assets.is_empty()); + + let full = format!( + "{minimal}\ +description = \"Local Tomcat runner\"\n\ +group = \"Servers\"\n\ +icon = \"icons/tomcat.svg\"\n\ +iconDark = \"icons/tomcat_dark.svg\"\n\ +layout = \"full\"\n\ +height = 420\n\ +command = \"java\"\n\ +args = [\"-jar\", \"bootstrap.jar\"]\n\ +debugAdapter = \"java-debug\"\n\ +terminal = false\n\ +ownsWorkingDirectory = true\n\ +ownsEnvironment = true\n\ +prepareCommand = \"prepare\"\n\ +matchConfigPrefix = \"smart-tomcat:\"\n\ +defaults = {{ httpPort = \"8080\" }}\n\ +\n\ +[[contributes.commands]]\n\ +id = \"prepare\"\n\ +title = \"Prepare\"\n" + ); + let valid_full = check(&full).unwrap(); + assert_eq!(valid_full.json["layout"], "full"); + assert_eq!(valid_full.json["height"], 420); + assert_eq!(valid_full.json["ownsWorkingDirectory"], true); + assert_eq!(valid_full.json["ownsEnvironment"], true); + assert_eq!(valid_full.json["defaults"]["httpPort"], "8080"); + assert_eq!( + valid_full.assets.iter().map(|(k, _)| k.as_str()).collect::>(), + ["runConfigIcon/smart-tomcat", "runConfigIconDark/smart-tomcat"] + ); + + for (bad, error) in [ + (minimal.replace("^1.20", "^1.19"), "1.20"), + (minimal.replace(r#"label = "SmartTomcat""#, r#"label = " ""#), "`label`"), + (format!("{minimal}layout = \"modal\"\n"), "`layout`"), + (format!("{minimal}height = 119\n"), "120–1200"), + (format!("{minimal}height = 1201\n"), "120–1200"), + (format!("{minimal}args = [\"--port\"]\n"), "requires `command`"), + (format!("{minimal}command = \"java -jar\"\n"), "`command`"), + (format!("{minimal}command = \"./bin/tool\"\n"), "`command`"), + (format!("{minimal}prepareCommand = \"missing\"\n"), "not declared"), + (format!("{minimal}icon = \"terminal\"\niconDark = \"icons/tomcat_dark.svg\"\n"), "`iconDark`"), + (format!("{minimal}defaults = {{ \"\" = \"1\" }}\n"), "`defaults`"), + (minimal.replace("web/form.html", "web/missing.html"), "no such file"), + (format!("{minimal}\n[[contributes.views]]\nid = \"smart-tomcat\"\ntitle = \"V\"\n"), "already declares"), + ( + format!( + "{minimal}\n[[contributes.dialogs]]\nid = \"smart-tomcat\"\ntitle = \"D\"\nweb = \"web/form.html\"\nwidth = 400\nheight = 300\n" + ), + "already declares", + ), + ] { + let err = check(&bad).unwrap_err(); + assert!(err.contains(error), "{bad}\n→ {err}"); + } + } + #[test] fn run_anything_validates_api_prefix_title_and_code() { let source = "id = \"go\"\nname = \"Go\"\nversion = \"0.1.0\"\nengines.openidea = \"^1.18\"\nwasm = \"p.wasm\"\n\n[[contributes.runAnything]]\nprefix = \"task\"\n"; diff --git a/crates/ide-host/tests/plugin_workbench.rs b/crates/ide-host/tests/plugin_workbench.rs index 740241431..d818eae48 100644 --- a/crates/ide-host/tests/plugin_workbench.rs +++ b/crates/ide-host/tests/plugin_workbench.rs @@ -919,3 +919,257 @@ async fn run_target_validation_gates_launches_and_preserves_selection() { ); plugins.shutdown(); } + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +async fn plugin_run_config_types_enforce_process_grants_for_run_debug_and_stop() { + use ide_host::plugins::{Consent, PluginEvent, PluginHost}; + use ide_plugin::Limits; + use std::os::unix::fs::PermissionsExt; + + let f = Harness::new(); + f.host.set_project_trust(&f.root, true, false).await.unwrap(); + let plugins = Arc::new( + PluginHost::new( + f._tmp.path().join("plugins"), + Arc::new(|_: Option<&str>, _: PluginEvent| {}), + Limits::default(), + ) + .unwrap(), + ); + plugins.set_workspace(Some(Arc::new(f.workspace()))); + f.host.set_plugin_host(&plugins); + + let pkg = f._tmp.path().join("custom-run-plugin"); + std::fs::create_dir_all(pkg.join("web")).unwrap(); + std::fs::write(pkg.join("web/form.html"), "
").unwrap(); + std::fs::write( + pkg.join("plugin.toml"), + r#"id = "run-form-test" +name = "Run Form Test" +version = "0.1.0" +engines.openidea = "^1.20" + +[capabilities] +optional = ["process:custom-tool", "process:custom-stop"] + +[[contributes.runConfigTypes]] +id = "custom" +label = "Custom Tool" +web = "web/form.html" +debugAdapter = "debugpy" +"#, + ) + .unwrap(); + plugins.install_from_dir(&pkg, &Consent::default()).unwrap(); + + let tool = f._tmp.path().join("custom-tool-bin"); + std::fs::write( + &tool, + "#!/bin/sh\nif [ \"$1\" = \"--sleep\" ]; then\n echo \"sleeping\"\n sleep 30\n exit 0\nfi\necho \"pinned-custom-tool:$1\"\n", + ) + .unwrap(); + std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap(); + + let stop_tool = f._tmp.path().join("custom-stop-bin"); + std::fs::write(&stop_tool, "#!/bin/sh\nprintf 'stopped' > \"$1\"\n").unwrap(); + std::fs::set_permissions(&stop_tool, std::fs::Permissions::from_mode(0o755)).unwrap(); + + let make_config = |command: &str, stop_command: Option<&str>| ide_run::RunConfig { + id: "user:custom-1".into(), + name: "Custom Tool".into(), + kind: "plugin:run-form-test:custom".into(), + command: command.into(), + args: vec!["--hello".into()], + cwd: None, + env: Default::default(), + detected: false, + is_test: false, + debug_adapter: Some("debugpy".into()), + allow_parallel: false, + extras: ide_run::RunExtras { stop_command: stop_command.map(str::to_owned), ..Default::default() }, + }; + + // 1. Without `process:custom-tool` granted: Run, Debug, and saved overrides are all refused. + let ungranted = make_config("custom-tool", None); + let err = + ide_host::ops::run::run_start(&f.host, "main", ungranted.clone(), ide_host::ops::Channel::new(|_| {}), None) + .await + .unwrap_err(); + assert_eq!(err.kind, ide_core::error::ErrorKind::PermissionDenied, "{err}"); + + let shell_err = ide_host::ops::run::run_start( + &f.host, + "main", + make_config("/bin/sh", None), + ide_host::ops::Channel::new(|_| {}), + None, + ) + .await + .unwrap_err(); + assert_eq!(shell_err.kind, ide_core::error::ErrorKind::PermissionDenied, "{shell_err}"); + + let dbg_err = plugins.prepare_debug_run("main", ungranted.clone()).unwrap_err(); + assert_eq!(dbg_err.kind, ide_core::error::ErrorKind::PermissionDenied, "{dbg_err}"); + let debug_launch = |program: &std::path::Path| ide_dap::LaunchConfig { + name: ungranted.name.clone(), + adapter: "debugpy".into(), + request: "launch".into(), + program: None, + args: vec![], + cwd: Some(f.root.clone().into()), + env: Default::default(), + extra_json: Some( + serde_json::json!({ "__openideaPluginRun": { "config": ungranted, "program": program } }).to_string(), + ), + }; + + let malformed = ide_run::RunConfig { kind: "plugin:run-form-test".into(), ..ungranted.clone() }; + assert!( + ide_host::ops::run::run_start(&f.host, "main", malformed.clone(), ide_host::ops::Channel::new(|_| {}), None) + .await + .is_err() + ); + assert!(plugins.prepare_debug_run("main", malformed).is_err()); + + let unknown_type = ide_run::RunConfig { kind: "plugin:run-form-test:missing".into(), ..ungranted.clone() }; + assert!( + ide_host::ops::run::run_start(&f.host, "main", unknown_type.clone(), ide_host::ops::Channel::new(|_| {}), None) + .await + .is_err() + ); + assert!(plugins.prepare_debug_run("main", unknown_type).is_err()); + + let saved_detected = ide_run::RunConfig { + id: "plugin:run-form-test:saved".into(), + kind: "plugin".into(), + detected: false, + ..ungranted.clone() + }; + let saved_err = + ide_host::ops::run::run_start(&f.host, "main", saved_detected, ide_host::ops::Channel::new(|_| {}), None) + .await + .unwrap_err(); + assert_eq!(saved_err.kind, ide_core::error::ErrorKind::PermissionDenied, "{saved_err}"); + + // 2. Grant & pin `process:custom-tool`: Run and Debug resolve the pinned executable, + // while env/cwd escapes are still rejected. + plugins.choose_program("run-form-test", "process:custom-tool", Some(&f.root), Some(&tool)).unwrap(); + let canonical_tool = dunce::canonicalize(&tool).unwrap(); + + let output = Arc::new(parking_lot::Mutex::new(String::new())); + let captured = output.clone(); + let run = ide_host::ops::run::run_start( + &f.host, + "main", + ungranted.clone(), + ide_host::ops::Channel::new(move |chunk| { + if let ide_run::OutputChunk::Stdout { text } = chunk { + captured.lock().push_str(&text); + } + }), + None, + ) + .await + .unwrap(); + for _ in 0..100 { + if f.host.processes.list().iter().any(|r| r.id == run.id && !r.running) { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + assert!(output.lock().contains("pinned-custom-tool:--hello"), "{}", output.lock()); + + let prepared_dbg = plugins.prepare_debug_run("main", ungranted.clone()).unwrap(); + assert_eq!(std::path::Path::new(&prepared_dbg.command), canonical_tool); + assert_eq!(prepared_dbg.debug_adapter.as_deref(), Some("debugpy")); + + let mut bad_env = ungranted.clone(); + bad_env.env.insert("LD_PRELOAD".into(), "/tmp/evil.so".into()); + assert!( + ide_host::ops::run::run_start(&f.host, "main", bad_env.clone(), ide_host::ops::Channel::new(|_| {}), None) + .await + .is_err() + ); + assert!(plugins.prepare_debug_run("main", bad_env).is_err()); + + let outside_dir = f._tmp.path().join("outside"); + std::fs::create_dir_all(&outside_dir).unwrap(); + let mut bad_cwd = ungranted.clone(); + bad_cwd.cwd = Some(outside_dir.into()); + assert!( + ide_host::ops::run::run_start(&f.host, "main", bad_cwd.clone(), ide_host::ops::Channel::new(|_| {}), None) + .await + .is_err() + ); + assert!(plugins.prepare_debug_run("main", bad_cwd).is_err()); + + // 3. Stop command enforcement: requires grant, rejects shell syntax, and re-checks grant at Stop time. + let ungranted_stop = make_config("custom-tool", Some("custom-stop marker.txt")); + let stop_err = + ide_host::ops::run::run_start(&f.host, "main", ungranted_stop, ide_host::ops::Channel::new(|_| {}), None) + .await + .unwrap_err(); + assert_eq!(stop_err.kind, ide_core::error::ErrorKind::PermissionDenied, "{stop_err}"); + + let shell_stop = make_config("custom-tool", Some("custom-tool; touch evil")); + let shell_stop_err = + ide_host::ops::run::run_start(&f.host, "main", shell_stop, ide_host::ops::Channel::new(|_| {}), None) + .await + .unwrap_err(); + assert_eq!(shell_stop_err.kind, ide_core::error::ErrorKind::InvalidInput, "{shell_stop_err}"); + + plugins.choose_program("run-form-test", "process:custom-stop", Some(&f.root), Some(&stop_tool)).unwrap(); + let mut sleep_cfg = make_config("custom-tool", Some("custom-stop stopped.txt")); + sleep_cfg.args = vec!["--sleep".into()]; + let sleep_run = + ide_host::ops::run::run_start(&f.host, "main", sleep_cfg, ide_host::ops::Channel::new(|_| {}), None) + .await + .unwrap(); + ide_host::ops::run::run_stop(&f.host, "main", sleep_run.id).unwrap(); + for _ in 0..100 { + if f.host.processes.list().iter().any(|r| r.id == sleep_run.id && !r.running) { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + assert!(f.host.processes.list().iter().any(|r| r.id == sleep_run.id && !r.running)); + assert_eq!(std::fs::read_to_string(f.root.join("stopped.txt")).unwrap(), "stopped"); + + // Revoking `process:custom-stop` after Start prevents the stop command from running on Stop. + let mut revoked_stop_cfg = make_config("custom-tool", Some("custom-stop revoked.txt")); + revoked_stop_cfg.args = vec!["--sleep".into()]; + let revoked_run = + ide_host::ops::run::run_start(&f.host, "main", revoked_stop_cfg, ide_host::ops::Channel::new(|_| {}), None) + .await + .unwrap(); + plugins.set_capability("run-form-test", "process:custom-stop", false).unwrap(); + ide_host::ops::run::run_stop(&f.host, "main", revoked_run.id).unwrap(); + for _ in 0..100 { + if f.host.processes.list().iter().any(|r| r.id == revoked_run.id && !r.running) { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + assert!(f.host.processes.list().iter().any(|r| r.id == revoked_run.id && !r.running)); + assert!(!f.root.join("revoked.txt").exists()); + + // 4. Revoking `process:custom-tool` immediately blocks subsequent Run and Debug launches. + plugins.set_capability("run-form-test", "process:custom-tool", false).unwrap(); + let debug_err = + ide_host::ops::debug::debug_start(&f.host, "main", debug_launch(&canonical_tool)).await.unwrap_err(); + assert_eq!(debug_err.kind, ide_core::error::ErrorKind::PermissionDenied, "{debug_err}"); + assert_eq!( + ide_host::ops::run::run_start(&f.host, "main", ungranted.clone(), ide_host::ops::Channel::new(|_| {}), None) + .await + .unwrap_err() + .kind, + ide_core::error::ErrorKind::PermissionDenied + ); + assert_eq!( + plugins.prepare_debug_run("main", ungranted).unwrap_err().kind, + ide_core::error::ErrorKind::PermissionDenied + ); + + plugins.shutdown(); +} diff --git a/crates/ide-host/tests/plugins.rs b/crates/ide-host/tests/plugins.rs index 6a556f32a..713216f94 100644 --- a/crates/ide-host/tests/plugins.rs +++ b/crates/ide-host/tests/plugins.rs @@ -8187,3 +8187,80 @@ fn restricting_a_project_without_its_plugins_announces_nothing() { host.restrict_project(tmp.path()); assert!(!events.lock().iter().any(|(_, e)| matches!(e, PluginEvent::CommandsChanged))); } + +#[test] +fn run_config_types_serve_web_pages_assets_and_view_messages() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let pkg = tmp.path().join("custom-run"); + copy_dir(&sample("jobs"), &pkg); + std::fs::create_dir_all(pkg.join("web/assets")).unwrap(); + std::fs::create_dir_all(pkg.join("icons")).unwrap(); + std::fs::write(pkg.join("web/form.html"), "Form").unwrap(); + std::fs::write(pkg.join("web/assets/app.js"), "console.log('run-config');").unwrap(); + let svg = r#""#; + std::fs::write(pkg.join("icons/run.svg"), svg).unwrap(); + std::fs::write(pkg.join("icons/run_dark.svg"), svg).unwrap(); + std::fs::write( + pkg.join("plugin.toml"), + r#"id = "jobs" +name = "Custom Run" +version = "0.1.0" +engines.openidea = "^1.20" +wasm = "dist/plugin.wasm" +activation = ["on-view:jobs", "on-command:*"] + +[capabilities] +required = ["process:jobs"] + +[[contributes.runConfigTypes]] +id = "jobs" +label = "Custom Job" +group = "Servers" +icon = "icons/run.svg" +iconDark = "icons/run_dark.svg" +web = "web/form.html" +layout = "full" +prepareCommand = "prepare" + +[[contributes.commands]] +id = "prepare" +title = "Prepare" +"#, + ) + .unwrap(); + + let info = f.install(&pkg); + assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error); + + let items = f.host.ui_items("runConfigTypes"); + assert_eq!(items.len(), 1); + assert_eq!((items[0].plugin_id.as_str(), items[0].key.as_str()), ("jobs", "jobs")); + assert_eq!(items[0].decl["label"], "Custom Job"); + assert_eq!(items[0].decl["layout"], "full"); + + let light = f.host.assets("jobs", "runConfigIcon/jobs").unwrap(); + assert_eq!(light.len(), 1); + assert!(light[0].1.contains(" Some(message), + _ => None, + }); + assert_eq!(reply.as_deref(), Some("sync-form")); + + f.host.set_enabled("jobs", false).unwrap(); + assert!(f.host.web_page("jobs", "jobs").is_err()); +} diff --git a/crates/ide-run/src/external.rs b/crates/ide-run/src/external.rs index 340a714cb..0d73bb916 100644 --- a/crates/ide-run/src/external.rs +++ b/crates/ide-run/src/external.rs @@ -11,6 +11,17 @@ use std::sync::Arc; /// Id prefix of externally detected configurations (`plugin::`). pub const EXTERNAL_PREFIX: &str = "plugin:"; +/// True for any configuration owned by a plugin (`kind == "plugin"`, +/// `kind == "plugin::"`, or a `plugin:` id with optional `workspace::` prefix). +pub fn is_plugin_owned(config: &RunConfig) -> bool { + let raw_id = config + .id + .strip_prefix("workspace:") + .and_then(|rest| rest.split_once(':')) + .map_or(config.id.as_str(), |(_, rest)| rest); + config.kind == "plugin" || config.kind.starts_with(EXTERNAL_PREFIX) || raw_id.starts_with(EXTERNAL_PREFIX) +} + pub trait ExternalDetection: Send + Sync { /// Configurations for the project at `root`; ids start with [`EXTERNAL_PREFIX`]. fn detect(&self, root: &Path) -> Vec; @@ -90,4 +101,28 @@ mod tests { assert_eq!(err.kind, ide_core::error::ErrorKind::PermissionDenied); assert!(err.message.contains("not allowed")); } + + #[test] + fn plugin_custom_type_config_cannot_start_without_host_authorization() { + let tmp = tempfile::tempdir().unwrap(); + let custom = RunConfig { + id: "user:1".into(), + name: "Custom Plugin Config".into(), + kind: "plugin:acme:custom".into(), + command: "sh".into(), + args: vec!["-c".into(), "true".into()], + cwd: None, + env: Default::default(), + detected: false, + is_test: false, + debug_adapter: None, + allow_parallel: false, + extras: Default::default(), + }; + assert!(is_plugin_owned(&custom)); + let err = ProcessManager::new() + .start(tmp.path(), &custom, &StartOptions::default(), Arc::new(ide_core::NullSink), Box::new(|_| {})) + .unwrap_err(); + assert_eq!(err.kind, ide_core::error::ErrorKind::PermissionDenied); + } } diff --git a/crates/ide-run/src/lib.rs b/crates/ide-run/src/lib.rs index b03d4b5e2..179fefb9b 100644 --- a/crates/ide-run/src/lib.rs +++ b/crates/ide-run/src/lib.rs @@ -31,7 +31,7 @@ pub use detect::cmake::cache as cmake_cache; pub use detect::cmake::presets::{listed as cmake_listed_profiles, load as cmake_presets, profiles as cmake_profiles}; pub use detect::cmake::toolchain as cmake_toolchain; pub use detect::cmake::{build_configs as cmake_build_configs, file_api as cmake_file_api, prepare as prepare_cmake}; -pub use process::{DetachedProcessKills, ProcessManager, StartOptions}; +pub use process::{DetachedProcessKills, DirectStop, ProcessManager, StartOptions}; use ide_core::{IdeResult, RunId}; use serde::{Deserialize, Serialize}; @@ -284,7 +284,7 @@ pub struct RunAttach { pub buffered: Vec, } -pub use external::{EXTERNAL_PREFIX, ExternalDetection, set_external_detection}; +pub use external::{EXTERNAL_PREFIX, ExternalDetection, is_plugin_owned, set_external_detection}; /// Kinds whose command is a Python interpreter (or a runner of one): they get the project /// interpreter, `PYTHONUNBUFFERED` and the interpreter paths on `PYTHONPATH`. diff --git a/crates/ide-run/src/process.rs b/crates/ide-run/src/process.rs index 6527dbfbf..6692d0637 100644 --- a/crates/ide-run/src/process.rs +++ b/crates/ide-run/src/process.rs @@ -83,9 +83,35 @@ struct LaunchEnv { vars: BTreeMap, } +/// A shell-free stop command (executable + argv) authorized by the host. +#[derive(Clone)] +pub struct DirectStop { + pub program: PathBuf, + pub args: Vec, + pub display: String, + /// Re-verified right before executing the stop command (e.g. plugin `process:` grant & pin). + pub verify: Option Result + Send + Sync>>, +} + +impl std::fmt::Debug for DirectStop { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DirectStop") + .field("program", &self.program) + .field("args", &self.args) + .field("display", &self.display) + .field("verify", &self.verify.is_some()) + .finish() + } +} + +enum StopKind { + Shell(String), + Direct(DirectStop), +} + /// A configuration's stop command and where it runs. struct StopCommand { - line: String, + kind: StopKind, cwd: PathBuf, env: LaunchEnv, } @@ -147,6 +173,10 @@ pub struct StartOptions { pub capture_junit_reports: bool, /// The conda environment of a Python run's interpreter, activated for the run. pub conda_prefix: Option, + /// Shell-free stop command (argv) authorized by the host (used for plugin-owned configs). + pub direct_stop: Option, + /// Set by `ide-host` after authorizing a plugin-owned run configuration. + pub plugin_authorized: bool, } #[derive(Clone, Default)] @@ -417,10 +447,29 @@ impl ProcessManager { if config.command.trim().is_empty() { return Err(IdeError::invalid("run configuration has no command")); } - let approved = match crate::external::approved(config) { - Some(Ok(c)) => Some(c), - Some(Err(e)) => return Err(IdeError::new(ide_core::error::ErrorKind::PermissionDenied, e)), - None => None, + let approved = if crate::external::is_plugin_owned(config) { + if options.plugin_authorized { + None + } else if config.detected && config.id.starts_with(crate::external::EXTERNAL_PREFIX) { + if config.extras.stop_command.as_deref().is_some_and(|s| !s.trim().is_empty()) { + return Err(IdeError::new( + ide_core::error::ErrorKind::PermissionDenied, + "plugin stop commands must be authorized by the plugin host", + )); + } + match crate::external::approved(config) { + Some(Ok(c)) => Some(c), + Some(Err(e)) => return Err(IdeError::new(ide_core::error::ErrorKind::PermissionDenied, e)), + None => None, + } + } else { + return Err(IdeError::new( + ide_core::error::ErrorKind::PermissionDenied, + "plugin run configurations must be authorized by the plugin host", + )); + } + } else { + None }; let config = approved.as_ref().unwrap_or(config); let plan = crate::go::plan(root, config)?; @@ -435,6 +484,9 @@ impl ProcessManager { } crate::detect::cmake::prepare(config, &cwd)?; let mut inv = invocation(config, &cwd); + if (options.plugin_authorized || approved.is_some()) && inv.shell { + return Err(IdeError::invalid("plugin run configurations must launch an executable directly")); + } let extras = &config.extras; if extras.emulate_terminal && extras.stdin_file.is_some() { return Err(IdeError::invalid("input cannot be redirected from a file when emulating a terminal")); @@ -459,11 +511,15 @@ impl ProcessManager { Some(file) => tee_output(&resolve_cwd(root, Some(Path::new(file))), on_output)?, None => on_output, }; - let stop = extras.stop_command.as_deref().map(str::trim).filter(|l| !l.is_empty()).map(|line| StopCommand { - line: line.to_owned(), - cwd: cwd.clone(), - env: env.clone(), - }); + let stop = if let Some(direct) = options.direct_stop.clone() { + Some(StopCommand { kind: StopKind::Direct(direct), cwd: cwd.clone(), env: env.clone() }) + } else { + extras.stop_command.as_deref().map(str::trim).filter(|l| !l.is_empty()).map(|line| StopCommand { + kind: StopKind::Shell(line.to_owned()), + cwd: cwd.clone(), + env: env.clone(), + }) + }; // A terminal re-encodes output itself; pipes carry the process's bytes as they are. let notice = if extras.emulate_terminal { None } else { match_console_encoding(&mut inv, &mut env, config, options) }; @@ -1183,11 +1239,34 @@ fn apply_env(cmd: &mut Command, env: &LaunchEnv) { cmd.envs(&env.vars); } -/// Runs `stop.line` through the platform shell and waits for it (bounded), echoing it -/// and any error output to the console. +/// Runs `stop` and waits for it (bounded), echoing it and any error output to the console. fn run_stop_command(stop: &StopCommand, entry: &Entry) { - entry.emit_output(OutputChunk::System { text: format!("{}\n", stop.line) }); - let inv = shell_invocation(&stop.line, cfg!(windows), std::env::var("COMSPEC").ok()); + let (inv, display) = match &stop.kind { + StopKind::Shell(line) => (shell_invocation(line, cfg!(windows), std::env::var("COMSPEC").ok()), line.clone()), + StopKind::Direct(direct) => { + let program = match &direct.verify { + Some(verify) => match verify() { + Ok(pinned) => pinned, + Err(reason) => { + entry.emit_output(OutputChunk::Stderr { text: format!("Stop command refused: {reason}\n") }); + return; + } + }, + None => direct.program.clone(), + }; + ( + Invocation { + program, + args: direct.args.clone(), + raw_args: false, + shell: false, + display: direct.display.clone(), + }, + direct.display.clone(), + ) + } + }; + entry.emit_output(OutputChunk::System { text: format!("{display}\n") }); let mut cmd = Command::new(&inv.program); ide_core::process::prepare(&mut cmd); ide_core::process::own_group(&mut cmd); diff --git a/docs/en/plugins/manifest.mdx b/docs/en/plugins/manifest.mdx index 644392995..904f7b719 100644 --- a/docs/en/plugins/manifest.mdx +++ b/docs/en/plugins/manifest.mdx @@ -102,38 +102,39 @@ The user approves **required** capabilities as a whole when installing. **Option Each contribution point is a table (`[contributes.settings]`) or an array of tables (`[[contributes.commands]]`). Contributions are live as soon as the plugin is enabled, before its code loads. -| Point | Declaration | Code needed | Guide | -| ------------------- | ----------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `commands` | `id`, `title`, `category?`, `when?`, `icon?` | to run them | [Commands and actions](/en/plugins/guides/commands) | -| `menus` | `menu`, `command`, `when?`, `view?`, `submenu?` | no | [Commands and actions](/en/plugins/guides/commands) | -| `keymaps` | `command`, `key`, `mac?`, `when?` (Escape only) | no | [Commands and actions](/en/plugins/guides/commands) | -| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | [Views and decorations](/en/plugins/guides/views) | -| `settings` | `schema` (a JSON file), or `pages` (API 1.3), `title?` | no | [Lifecycle and events](/en/plugins/lifecycle#settings) | -| `secrets` | `name`, `label`, `description?` | to use them | [Permissions and capabilities](/en/plugins/capabilities#secrets) | -| `providers` | `kinds`, `languages` | yes | [Language features](/en/plugins/guides/language-features) | -| `documentIndexers` | `extensions` | yes | [Indexing](/en/plugins/guides/indexing) | -| `endpoints` | `files` (API 1.3) | yes | [README: Project HTTP endpoints](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#project-http-endpoints-api-13) | -| `searchCategories` | `id`, `title` (API 1.13) | yes | [Custom search categories](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-search-everywhere-categories-api-111) | -| `views` | `id`, `title`, `icon?`, `location`, `web?`, `group?`, `when?` | without `web` | [Views and decorations](/en/plugins/guides/views) | -| `customEditors` | `id`, `title`, `patterns`, `priority`, `layout?`, `web?` | without `web` | [Views and decorations](/en/plugins/guides/views) | -| `markerIcons` | `id`, `icon`, `iconDark?`, `markers?`, `tooltip?` (API 1.3): gutter marker icons | no | [Language features](/en/plugins/guides/language-features) | -| `editorPanels` | `id`, `web`, `width`, `when?` (API 1.9; needs `editor.read`) | no | [README: Editor panels](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#editor-panels) | -| `overlays` | `id`, `web`, `width`, `height`, `anchor?`, `when?`, `interactive?` (API 1.18) | no | [README: Overlays](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#overlays) | -| `runAnything` | `prefix`, `title?` (API 1.18) | no | [README: Run Anything entries](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#run-anything-entries-api-118) | -| `dialogs` | `id`, `title`, `web`, `width`, `height` (API 1.18) | no | [README: Dialogs](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#dialogs) | -| `fileIcons` | `id`, `patterns`, `icon`, `iconDark?` | no | [Icon themes](/en/plugins/guides/icon-themes) | -| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables` | no | [File actions](/en/plugins/guides/file-actions) | -| `snippets` | `language`, `path` (API 1.4) | no | [Language features](/en/plugins/guides/language-features) | -| `commitChecks` | `id`, `title` | yes | [README: Commits](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commits) | -| `serverCommands` | `server`, `command`, `run` (API 1.9) | yes | [README: Commands a server hands to the client](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commands-a-server-hands-to-the-client) | -| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?`, `outputMode?` | no | [Run targets](/en/plugins/guides/run-targets) | -| `runConfigurations` | `files` (API 1.4) | yes | [Run targets](/en/plugins/guides/run-targets) | -| `javaAgents` | `path`, `args?` (API 1.10); `vmOptions?`, `jdk?` (API 1.14); `executor?` (API 1.18) | no | [README: Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) | -| `skills` | `path` (`skills//SKILL.md`, API 1.15) | no | [README: API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) | -| `mcpTools` | `name`, `description`, `inputSchema`, `readOnly`, `destructive` (API 1.4) | yes | [MCP tools](/en/plugins/guides/mcp) | -| `themes` | `path`, `editor-scheme?` | no | [Themes](/en/plugins/guides/themes) | -| `iconThemes` | `id`, `label`, `path` | no | [Icon themes](/en/plugins/guides/icon-themes) | -| `languages` | `path` (a `languages/.toml` file) | no | [Adding a language](/en/languages/adding) | +| Point | Declaration | Code needed | Guide | +| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `commands` | `id`, `title`, `category?`, `when?`, `icon?` | to run them | [Commands and actions](/en/plugins/guides/commands) | +| `menus` | `menu`, `command`, `when?`, `view?`, `submenu?` | no | [Commands and actions](/en/plugins/guides/commands) | +| `keymaps` | `command`, `key`, `mac?`, `when?` (Escape only) | no | [Commands and actions](/en/plugins/guides/commands) | +| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | [Views and decorations](/en/plugins/guides/views) | +| `settings` | `schema` (a JSON file), or `pages` (API 1.3), `title?` | no | [Lifecycle and events](/en/plugins/lifecycle#settings) | +| `secrets` | `name`, `label`, `description?` | to use them | [Permissions and capabilities](/en/plugins/capabilities#secrets) | +| `providers` | `kinds`, `languages` | yes | [Language features](/en/plugins/guides/language-features) | +| `documentIndexers` | `extensions` | yes | [Indexing](/en/plugins/guides/indexing) | +| `endpoints` | `files` (API 1.3) | yes | [README: Project HTTP endpoints](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#project-http-endpoints-api-13) | +| `searchCategories` | `id`, `title` (API 1.13) | yes | [Custom search categories](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-search-everywhere-categories-api-111) | +| `views` | `id`, `title`, `icon?`, `location`, `web?`, `group?`, `when?` | without `web` | [Views and decorations](/en/plugins/guides/views) | +| `customEditors` | `id`, `title`, `patterns`, `priority`, `layout?`, `web?` | without `web` | [Views and decorations](/en/plugins/guides/views) | +| `markerIcons` | `id`, `icon`, `iconDark?`, `markers?`, `tooltip?` (API 1.3): gutter marker icons | no | [Language features](/en/plugins/guides/language-features) | +| `editorPanels` | `id`, `web`, `width`, `when?` (API 1.9; needs `editor.read`) | no | [README: Editor panels](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#editor-panels) | +| `overlays` | `id`, `web`, `width`, `height`, `anchor?`, `when?`, `interactive?` (API 1.18) | no | [README: Overlays](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#overlays) | +| `runAnything` | `prefix`, `title?` (API 1.18) | no | [README: Run Anything entries](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#run-anything-entries-api-118) | +| `dialogs` | `id`, `title`, `web`, `width`, `height` (API 1.18) | no | [README: Dialogs](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#dialogs) | +| `runConfigTypes` | `id`, `label`, `web`, `layout?`, `prepareCommand?`, `matchConfigPrefix?` (API 1.20; requires `process:` grants at Run/Debug/Stop) | no | [README: Custom run configuration forms](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-run-configuration-forms) | +| `fileIcons` | `id`, `patterns`, `icon`, `iconDark?` | no | [Icon themes](/en/plugins/guides/icon-themes) | +| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables` | no | [File actions](/en/plugins/guides/file-actions) | +| `snippets` | `language`, `path` (API 1.4) | no | [Language features](/en/plugins/guides/language-features) | +| `commitChecks` | `id`, `title` | yes | [README: Commits](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commits) | +| `serverCommands` | `server`, `command`, `run` (API 1.9) | yes | [README: Commands a server hands to the client](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commands-a-server-hands-to-the-client) | +| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?`, `outputMode?` | no | [Run targets](/en/plugins/guides/run-targets) | +| `runConfigurations` | `files` (API 1.4) | yes | [Run targets](/en/plugins/guides/run-targets) | +| `javaAgents` | `path`, `args?` (API 1.10); `vmOptions?`, `jdk?` (API 1.14); `executor?` (API 1.18) | no | [README: Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) | +| `skills` | `path` (`skills//SKILL.md`, API 1.15) | no | [README: API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) | +| `mcpTools` | `name`, `description`, `inputSchema`, `readOnly`, `destructive` (API 1.4) | yes | [MCP tools](/en/plugins/guides/mcp) | +| `themes` | `path`, `editor-scheme?` | no | [Themes](/en/plugins/guides/themes) | +| `iconThemes` | `id`, `label`, `path` | no | [Icon themes](/en/plugins/guides/icon-themes) | +| `languages` | `path` (a `languages/.toml` file) | no | [Adding a language](/en/languages/adding) | Item ids (commands, views, themes, …) match `[a-z0-9][a-z0-9._-]*`, at most 64 characters. Menus, shortcuts and status bar items refer to the plugin's own declared commands; inside the IDE a command's action id is `plugin..`. diff --git a/docs/zh/plugins/manifest.mdx b/docs/zh/plugins/manifest.mdx index 6f50b5119..99f81d149 100644 --- a/docs/zh/plugins/manifest.mdx +++ b/docs/zh/plugins/manifest.mdx @@ -102,38 +102,39 @@ optional = ["net:api.openai.com", "secrets"] 每个贡献点是一张表(`[contributes.settings]`)或一个表数组(`[[contributes.commands]]`)。插件启用后贡献立即生效,不需要等代码加载。 -| 贡献点 | 声明字段 | 需要代码 | 指南 | -| ------------------- | ------------------------------------------------------------------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `commands` | `id`、`title`、`category?`、`when?`、`icon?` | 执行时需要 | [命令与动作](/zh/plugins/guides/commands) | -| `menus` | `menu`、`command`、`when?`、`view?`、`submenu?` | 否 | [命令与动作](/zh/plugins/guides/commands) | -| `keymaps` | `command`、`key`、`mac?`、`when?`(仅 Escape) | 否 | [命令与动作](/zh/plugins/guides/commands) | -| `statusBar` | `id`、`text`、`tooltip?`、`command?`、`align?`、`priority?` | 否 | [视图与装饰](/zh/plugins/guides/views) | -| `settings` | `schema`(JSON 文件)或 `pages`(API 1.3)、`title?` | 否 | [生命周期与事件](/zh/plugins/lifecycle) | -| `secrets` | `name`、`label`、`description?` | 使用时需要 | [权限与能力](/zh/plugins/capabilities) | -| `providers` | `kinds`、`languages` | 是 | [语言功能](/zh/plugins/guides/language-features) | -| `documentIndexers` | `extensions` | 是 | [索引](/zh/plugins/guides/indexing) | -| `endpoints` | `files`(API 1.3) | 是 | [README:Project HTTP endpoints](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#project-http-endpoints-api-13) | -| `searchCategories` | `id`、`title`(API 1.13) | 是 | [自定义搜索分类](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-search-everywhere-categories-api-111) | -| `views` | `id`、`title`、`icon?`、`location`、`web?`、`group?`、`when?` | 无 `web` 时需要 | [视图与装饰](/zh/plugins/guides/views) | -| `customEditors` | `id`、`title`、`patterns`、`priority`、`layout?`、`web?` | 无 `web` 时需要 | [视图与装饰](/zh/plugins/guides/views) | -| `markerIcons` | `id`、`icon`、`iconDark?`、`markers?`、`tooltip?`(API 1.3):装订区标记图标 | 否 | [语言功能](/zh/plugins/guides/language-features) | -| `editorPanels` | `id`、`web`、`width`、`when?`(API 1.9;需要 `editor.read`) | 否 | [README:Editor panels](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#editor-panels) | -| `overlays` | `id`、`web`、`width`、`height`、`anchor?`、`when?`、`interactive?`(API 1.18) | 否 | [README:Overlays](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#overlays) | -| `runAnything` | `prefix`、`title?`(API 1.18) | 否 | [README:Run Anything entries](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#run-anything-entries-api-118) | -| `dialogs` | `id`、`title`、`web`、`width`、`height`(API 1.18) | 否 | [README:Dialogs](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#dialogs) | -| `fileIcons` | `id`、`patterns`、`icon`、`iconDark?` | 否 | [图标主题](/zh/plugins/guides/icon-themes) | -| `fileTemplates` | `id`、`name`、`extension`、`path`;API 1.3:`fileName`、`variables` | 否 | [文件操作](/zh/plugins/guides/file-actions) | -| `snippets` | `language`、`path`(API 1.4) | 否 | [语言功能](/zh/plugins/guides/language-features) | -| `commitChecks` | `id`、`title` | 是 | [README:Commits](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commits) | -| `serverCommands` | `server`、`command`、`run`(API 1.9) | 是 | [README:Commands a server hands to the client](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commands-a-server-hands-to-the-client) | -| `runDetectors` | `id`、`name`、`files`、`command`、`args?`、`test?`、`framework?`、`outputMode?`(API 1.18) | 否 | [运行目标](/zh/plugins/guides/run-targets) | -| `runConfigurations` | `files`(API 1.4) | 是 | [运行目标](/zh/plugins/guides/run-targets) | -| `javaAgents` | `path`、`args?`(API 1.10);`vmOptions?`、`jdk?`(API 1.14);`executor?`(API 1.18) | 否 | [README:Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) | -| `skills` | `path`(`skills//SKILL.md`,API 1.15) | 否 | [README:API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) | -| `mcpTools` | `name`、`description`、`inputSchema`、`readOnly`、`destructive`(API 1.4) | 是 | [MCP 工具](/zh/plugins/guides/mcp) | -| `themes` | `path`、`editor-scheme?` | 否 | [主题](/zh/plugins/guides/themes) | -| `iconThemes` | `id`、`label`、`path` | 否 | [图标主题](/zh/plugins/guides/icon-themes) | -| `languages` | `path`(`languages/.toml` 格式的文件) | 否 | [添加语言](/zh/languages/adding) | +| 贡献点 | 声明字段 | 需要代码 | 指南 | +| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `commands` | `id`、`title`、`category?`、`when?`、`icon?` | 执行时需要 | [命令与动作](/zh/plugins/guides/commands) | +| `menus` | `menu`、`command`、`when?`、`view?`、`submenu?` | 否 | [命令与动作](/zh/plugins/guides/commands) | +| `keymaps` | `command`、`key`、`mac?`、`when?`(仅 Escape) | 否 | [命令与动作](/zh/plugins/guides/commands) | +| `statusBar` | `id`、`text`、`tooltip?`、`command?`、`align?`、`priority?` | 否 | [视图与装饰](/zh/plugins/guides/views) | +| `settings` | `schema`(JSON 文件)或 `pages`(API 1.3)、`title?` | 否 | [生命周期与事件](/zh/plugins/lifecycle) | +| `secrets` | `name`、`label`、`description?` | 使用时需要 | [权限与能力](/zh/plugins/capabilities) | +| `providers` | `kinds`、`languages` | 是 | [语言功能](/zh/plugins/guides/language-features) | +| `documentIndexers` | `extensions` | 是 | [索引](/zh/plugins/guides/indexing) | +| `endpoints` | `files`(API 1.3) | 是 | [README:Project HTTP endpoints](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#project-http-endpoints-api-13) | +| `searchCategories` | `id`、`title`(API 1.13) | 是 | [自定义搜索分类](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-search-everywhere-categories-api-111) | +| `views` | `id`、`title`、`icon?`、`location`、`web?`、`group?`、`when?` | 无 `web` 时需要 | [视图与装饰](/zh/plugins/guides/views) | +| `customEditors` | `id`、`title`、`patterns`、`priority`、`layout?`、`web?` | 无 `web` 时需要 | [视图与装饰](/zh/plugins/guides/views) | +| `markerIcons` | `id`、`icon`、`iconDark?`、`markers?`、`tooltip?`(API 1.3):装订区标记图标 | 否 | [语言功能](/zh/plugins/guides/language-features) | +| `editorPanels` | `id`、`web`、`width`、`when?`(API 1.9;需要 `editor.read`) | 否 | [README:Editor panels](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#editor-panels) | +| `overlays` | `id`、`web`、`width`、`height`、`anchor?`、`when?`、`interactive?`(API 1.18) | 否 | [README:Overlays](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#overlays) | +| `runAnything` | `prefix`、`title?`(API 1.18) | 否 | [README:Run Anything entries](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#run-anything-entries-api-118) | +| `dialogs` | `id`、`title`、`web`、`width`、`height`(API 1.18) | 否 | [README:Dialogs](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#dialogs) | +| `runConfigTypes` | `id`、`label`、`web`、`layout?`、`prepareCommand?`、`matchConfigPrefix?`(API 1.20;Run/Debug/Stop 均需 `process:` 授权) | 否 | [README:Custom run configuration forms](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-run-configuration-forms) | +| `fileIcons` | `id`、`patterns`、`icon`、`iconDark?` | 否 | [图标主题](/zh/plugins/guides/icon-themes) | +| `fileTemplates` | `id`、`name`、`extension`、`path`;API 1.3:`fileName`、`variables` | 否 | [文件操作](/zh/plugins/guides/file-actions) | +| `snippets` | `language`、`path`(API 1.4) | 否 | [语言功能](/zh/plugins/guides/language-features) | +| `commitChecks` | `id`、`title` | 是 | [README:Commits](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commits) | +| `serverCommands` | `server`、`command`、`run`(API 1.9) | 是 | [README:Commands a server hands to the client](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commands-a-server-hands-to-the-client) | +| `runDetectors` | `id`、`name`、`files`、`command`、`args?`、`test?`、`framework?`、`outputMode?`(API 1.18) | 否 | [运行目标](/zh/plugins/guides/run-targets) | +| `runConfigurations` | `files`(API 1.4) | 是 | [运行目标](/zh/plugins/guides/run-targets) | +| `javaAgents` | `path`、`args?`(API 1.10);`vmOptions?`、`jdk?`(API 1.14);`executor?`(API 1.18) | 否 | [README:Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) | +| `skills` | `path`(`skills//SKILL.md`,API 1.15) | 否 | [README:API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) | +| `mcpTools` | `name`、`description`、`inputSchema`、`readOnly`、`destructive`(API 1.4) | 是 | [MCP 工具](/zh/plugins/guides/mcp) | +| `themes` | `path`、`editor-scheme?` | 否 | [主题](/zh/plugins/guides/themes) | +| `iconThemes` | `id`、`label`、`path` | 否 | [图标主题](/zh/plugins/guides/icon-themes) | +| `languages` | `path`(`languages/.toml` 格式的文件) | 否 | [添加语言](/zh/languages/adding) | 条目 id(命令、视图、主题等)匹配 `[a-z0-9][a-z0-9._-]*`,不超过 64 个字符。菜单、快捷键和状态栏项只能引用插件自己声明的命令;在 IDE 内部,命令的操作 id 是 `plugin..`。 diff --git a/plugins/README.md b/plugins/README.md index 2cfe575df..e04d41621 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -160,6 +160,7 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK. | `overlays` | `id`, `web`, `width`, `height` (pixels, 40–800), `anchor?`, `when?`, `interactive?` — floats over the workbench, never takes the focus (API 1.18; _Overlays_) | no | | `runAnything` | `prefix`, `title?` — Run Anything lines starting with `prefix`, answered by the `run-anything-provider` export (API 1.18; _Run Anything entries_) | no | | `dialogs` | `id`, `title`, `web`, `width` (320–1600), `height` (200–1200) — a modal, resizable dialog opened by `views::reveal(id)` (API 1.18; _Dialogs_) | no | +| `runConfigTypes` | `id`, `label`, `web`, `layout?` (`embedded` / `full`), `height?`, `icon?`, `iconDark?`, `group?`, `command?`, `args?`, `prepareCommand?`, `matchConfigPrefix?`, `defaults?` — a custom Run/Debug Configurations form (`openidea.runConfig`; API 1.20; _Custom run configuration forms_) | no | | `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no | | `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables = [{ name, prompt }]` — New menu | no | | `commitChecks` | `id`, `title` — a before-commit check in Commit Options (see _Commits_) | yes | @@ -2625,6 +2626,50 @@ IDE, so a dialog needs no capability. Only a dialog's page has `openidea.dialog` For something that stays open beside the editor without taking the keyboard, use an [overlay](#overlays) or a tool window. +#### Custom run configuration forms + +With API 1.20 (`engines.openidea = "^1.20"`), `[[contributes.runConfigTypes]]` +contributes a run configuration type whose settings form in **Run | Edit +Configurations…** is rendered by a package web page (`?openidea=run-config`): + +```toml +[[contributes.runConfigTypes]] +id = "smart-tomcat" +label = "SmartTomcat" +group = "Servers" +icon = "icons/tomcat.svg" +iconDark = "icons/tomcat_dark.svg" +web = "web/run-config.html" +layout = "embedded" # "embedded" (default) or "full" (replaces everything below Name) +height = 360 # embedded height in pixels, 120–1200 +ownsWorkingDirectory = false +ownsEnvironment = false +prepareCommand = "prepare" # optional command invoked before Run/Debug; returns a JSON patch +matchConfigPrefix = "" # optional id prefix for matching plugin:: entries +``` + +Inside the page, `openidea.runConfig` provides `get()`, `patch(patch)`, +`setErrors(errors)`, `setHeight(height)`, and `onChange(fn)` to read and update +the staged `RunConfig` draft (including `params`, `command`, `args`, `cwd`, `env`, +`debugAdapter`, and `name`), surface validation errors that block OK/Apply/Run, +and resize embedded forms. + +**Process grants and host launch checks.** Every launch (Run, Debug, and any +`stopCommand`) goes through host-owned plugin authorization: + +- Declare and obtain `process:` for both the executable launched on + Run/Debug (`command`, whether set in the manifest, form `patch()`, or + `prepareCommand`) and any program named by `stopCommand`. The host resolves + the exact pinned binary via the grant ledger before starting or debugging. +- `stopCommand` is parsed as ` [args...]` without a shell, invokes the + approved binary directly, and re-verifies its `process:` grant and file pin + at Stop time (rejected if revoked or changed, though process termination still + proceeds). +- `env` may only add non-inherited variables (replacing inherited variables such + as `PATH` or loader variables such as `LD_PRELOAD` / `DYLD_INSERT_LIBRARIES` + is refused, capped at 64 entries), and `cwd` must stay inside the trusted + project root. + ### Web frame PTYs (API 1.3) Packages requiring `engines.openidea = "^1.3"` can exchange JSON strings through diff --git a/src/features/debugger/__tests__/pluginRunConfigType.test.ts b/src/features/debugger/__tests__/pluginRunConfigType.test.ts new file mode 100644 index 000000000..8bdfabfdb --- /dev/null +++ b/src/features/debugger/__tests__/pluginRunConfigType.test.ts @@ -0,0 +1,86 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import { executeAction } from "@/platform/actions"; +import { useProject } from "@/platform/project"; +import { + provideNotificationService, + provideToolWindowService, + useDebugRunSessions, + type ToolWindowService, +} from "@/workbench/contributions"; +import type { RunConfig } from "@/platform/ipc"; +import { registerDebugActions } from "../actions"; +import { resetSessions, useDebug } from "../state"; + +const ipc = vi.hoisted(() => ({ + pluginPrepareDebugRun: vi.fn(), + debugStart: vi.fn(async () => ({ status: "ok" as const, data: 77 })), + debugStop: vi.fn(async () => ({ status: "ok" as const, data: null })), +})); + +vi.mock("@/platform/ipc", async (original) => { + const real = await original(); + return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } }; +}); + +const customConfig: RunConfig = { + id: "user:tomcat-1", + name: "Custom Python", + kind: "plugin:acme.custom:runner", + command: "python3", + args: ["app.py"], + cwd: null, + env: {}, + detected: false, + isTest: false, + debugAdapter: "debugpy", +}; + +beforeEach(() => { + resetSessions(); + useDebugRunSessions.setState({ sessions: [] }); + useProject.setState({ project: { root: "/p" } as never }); + provideNotificationService({ notify: vi.fn() }); + provideToolWindowService({ show: vi.fn() } as unknown as ToolWindowService); + vi.clearAllMocks(); +}); + +it("routes plugin:: configs through pluginPrepareDebugRun and retains the original config", async () => { + ipc.pluginPrepareDebugRun.mockResolvedValueOnce({ + status: "ok", + data: { ...customConfig, command: "/approved/python3" }, + }); + const dispose = registerDebugActions(); + try { + await executeAction("debug.startConfig", customConfig); + expect(ipc.pluginPrepareDebugRun).toHaveBeenCalledWith(customConfig); + expect(ipc.debugStart).toHaveBeenCalledWith( + expect.objectContaining({ + adapter: "debugpy", + extraJson: expect.stringContaining('"/approved/python3"'), + }), + ); + const launch = vi.mocked(ipc.debugStart).mock.calls[0] as unknown as [{ extraJson: string }]; + expect(JSON.parse(launch[0].extraJson).__openideaPluginRun).toEqual({ + config: customConfig, + program: "/approved/python3", + }); + expect(useDebug.getState().sessions[77]?.runConfig).toEqual(customConfig); + } finally { + dispose(); + } +}); + +it("does not start debugging when pluginPrepareDebugRun rejects due to missing grant", async () => { + ipc.pluginPrepareDebugRun.mockResolvedValueOnce({ + status: "error", + error: { kind: "permissionDenied", message: "process:custom-tool was not granted" }, + }); + const dispose = registerDebugActions(); + try { + await executeAction("debug.startConfig", customConfig); + expect(ipc.pluginPrepareDebugRun).toHaveBeenCalledWith(customConfig); + expect(ipc.debugStart).not.toHaveBeenCalled(); + } finally { + dispose(); + } +}); diff --git a/src/features/debugger/actions.ts b/src/features/debugger/actions.ts index 51916fd27..e24ce1990 100644 --- a/src/features/debugger/actions.ts +++ b/src/features/debugger/actions.ts @@ -152,6 +152,10 @@ function withExtra(launch: LaunchConfig, more: Record | undefin return { ...launch, extraJson: JSON.stringify({ ...extra, ...more }) }; } +function withPluginRun(launch: LaunchConfig, config: RunConfig, program: string): LaunchConfig { + return withExtra(launch, { __openideaPluginRun: { config, program } }); +} + function errorText(e: unknown) { return e instanceof Error ? e.message : String(e); } @@ -478,19 +482,26 @@ async function startConfig(arg: unknown) { return; } } - if (isRemoteConfig(config)) { + const pluginConfig = + config.kind === "plugin" || config.kind.startsWith("plugin:") || /^(?:workspace:[^:]+:)?plugin:/.test(config.id) + ? config + : null; + if (!pluginConfig && isRemoteConfig(config)) { await startRemote(config, root, show); return; } - if (isBrowserConfig(config)) { + if (!pluginConfig && isBrowserConfig(config)) { await startBrowser(config, root, show); return; } - if (isJavaDebuggable(config)) { + if (!pluginConfig && isJavaDebuggable(config)) { await startJavaConfig(config, root, origin ?? config, show); return; } - if (config.kind === "plugin") config = await call(commands.pluginPrepareDebugRun(config)); + const sessionOrigin = origin ?? config; + if (pluginConfig) { + config = await call(commands.pluginPrepareDebugRun(pluginConfig)); + } const dotnet = config.kind === "dotnet" && config.debugAdapter === "netcoredbg"; const prepared = dotnet ? await call(commands.runDotnetResolve(config, true)) : config; // php-debug starts the PHP chosen in Settings unless the command names one. @@ -512,7 +523,10 @@ async function startConfig(arg: unknown) { await maybeEditorService() ?.saveAll() .catch(() => undefined); - await startSession(launch, { runConfig: origin ?? config, show }); + await startSession(pluginConfig ? withPluginRun(launch, pluginConfig, config.command) : launch, { + runConfig: sessionOrigin, + show, + }); await xdebugCheck; } @@ -613,7 +627,7 @@ export function registerDebugActions(): () => void { const off = useDebug.subscribe(observe); try { await maybeEditorService()?.saveAll(); - id = await startSession(launch, { runConfig: config }); + id = await startSession(withPluginRun(launch, a.config, config.command), { runConfig: a.config }); if (id === null) { off(); throw new Error("Debug session did not start"); diff --git a/src/features/plugins/__tests__/runConfigForm.test.tsx b/src/features/plugins/__tests__/runConfigForm.test.tsx new file mode 100644 index 000000000..244e2b139 --- /dev/null +++ b/src/features/plugins/__tests__/runConfigForm.test.tsx @@ -0,0 +1,309 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import type { PluginInfo } from "@/bindings"; +import type { RunConfig } from "@/platform/ipc"; +import { resetRuns, useRun } from "@/features/run/store"; +import { EditConfigsOverlay } from "@/features/run/EditConfigsDialog"; +import { typeForConfig } from "@/features/run/types"; +import { useRunConfigTypes } from "@/workbench/contributions"; +import { createMemoryPluginsBackend, setPluginsBackend } from "../backend"; +import { usePlugins } from "../store"; +import { FRAME_TAG, frameDocument } from "../views/frame"; +import { + applyRunConfigPatch, + pluginRunConfigKind, + projectRunConfigType, + sanitizeRunConfigErrors, + type RunConfigTypeDecl, +} from "../views/runConfigForm"; + +function bridgeAt(search: string) { + const script = /