feat(plugins): validate run target launches (#2427)

Closes #2408

Plugin run targets were static argv wrappers: a plugin couldn't refuse a built-in Run/Test/Debug launch through its target (for example when its container project is stopped), so the wrapper started and could start the environment as a side effect. API 1.5 adds an optional run-target-validation export: after trust, ownership, process-grant and pin checks the host calls validate with the operation, bare program name and working directory; an error refuses the launch with the plugin's (prefixed, bounded) message and keeps the selected target. Plugins without the export behave as before. Calls wake reclaimed instances, use the host call timeout, are cancelled with the launch, and fail closed on trap/timeout; for remote projects validation runs on the server. SDK helpers, plugins/README.md and fixtures updated.
This commit is contained in:
l0ng-ai
2026-11-10 06:48:36 +08:00
committed by GitHub
parent 6c51e3307e
commit 0b6bf83b9e
116 changed files with 747 additions and 71 deletions
+30 -2
View File
@@ -9,6 +9,32 @@ use std::path::PathBuf;
/// Starts a session owned by this window: its events (and those of child sessions) go here only.
pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> IdeResult<DebugSessionId> {
debug_start_request(host, window, config, None).await
}
pub async fn debug_start_request(
host: &Host,
window: &str,
config: LaunchConfig,
request: Option<ide_core::RequestId>,
) -> IdeResult<DebugSessionId> {
let cancel = request.map(|id| host.begin_request(id)).unwrap_or_default();
let result = debug_start_inner(host, window, config, &cancel).await;
if let Some(id) = request {
host.end_request(id);
}
result
}
async fn debug_start_inner(
host: &Host,
window: &str,
config: LaunchConfig,
cancel: &ide_core::CancellationToken,
) -> IdeResult<DebugSessionId> {
if cancel.is_cancelled() {
return Err(ide_core::IdeError::cancelled());
}
host.require_trust(window)?;
let target_id = config
.extra_json
@@ -17,7 +43,7 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
.and_then(|v| v.get("__runTarget").and_then(|v| v.as_str()).map(str::to_owned));
if let Some(id) = target_id {
let owner = SessionOwner::new(host.owner_window(window), host.window_sink(window));
return target::start(host, window, config, owner, id).await;
return target::start(host, window, config, owner, id, cancel).await;
}
let mut config = match_java_debug_encoding(config, cfg!(windows));
if config.adapter == "debugpy"
@@ -392,7 +418,9 @@ pub async fn debug_redefine_classes(host: &Host, _window: &str, session: DebugSe
/// Commands of this module the remote server answers.
pub(crate) fn register(d: &mut Dispatcher) {
d.add("debug_start", |c| async move { debug_start(&c.host, &c.window, c.arg("config")?).await });
d.add("debug_start", |c| async move {
debug_start_request(&c.host, &c.window, c.arg("config")?, c.arg("request")?).await
});
d.add("debug_set_breakpoints", |c| async move {
debug_set_breakpoints(&c.host, &c.window, c.arg("path")?, c.arg("breakpoints")?).await
});
+19
View File
@@ -12,6 +12,7 @@ pub(super) async fn start(
mut config: LaunchConfig,
owner: SessionOwner,
id: String,
cancel: &ide_core::CancellationToken,
) -> IdeResult<ide_core::DebugSessionId> {
let project = host.project(window)?;
let plugins =
@@ -33,6 +34,23 @@ pub(super) async fn start(
{
return Err(IdeError::invalid("This debugger does not support plugin run targets"));
}
let program = config
.extra_json
.as_deref()
.and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok())
.and_then(|v| v.get("__runTargetProgram").and_then(|p| p.as_str()).map(str::to_owned))
.or_else(|| config.program.clone())
.unwrap_or_else(|| dbg.command.clone());
let metadata = serde_json::from_value(json!({"id":"debug", "name":config.name, "kind":"shell", "command":program, "args":[], "cwd":config.cwd, "env":{}, "detected":false, "isTest":false}))
.map_err(|e| IdeError::invalid(e.to_string()))?;
let (validator, root, target, token) = (plugins.clone(), project.root.clone(), id.clone(), cancel.clone());
host.blocking(move || {
validator.prepare_run_target_launch(&root, &target, &metadata, ide_plugin::RunTargetOperation::Debug, &token)
})
.await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mapping = TargetMapping {
paths: PathMapping::new(&project.root.to_string_lossy(), &container),
external_prefix: format!(
@@ -48,6 +66,7 @@ pub(super) async fn start(
.map_err(|e| IdeError::invalid(e.to_string()))?
.unwrap_or(json!({}));
extra.as_object_mut().ok_or_else(|| IdeError::invalid("invalid debug launch arguments"))?.remove("__runTarget");
extra.as_object_mut().unwrap().remove("__runTargetProgram");
// DAP paths already use target coordinates; adapter-native mappings stay identity.
if placement == "connect-back" {
config.program = None;
+36 -2
View File
@@ -203,8 +203,22 @@ pub fn apply_settings(host: &Host, window: &str, configs: Vec<RunConfig>) -> Ide
}
pub async fn start(host: &Host, window: &str, config: RunConfig, on_output: Emit<OutputChunk>) -> IdeResult<RunInfo> {
start_request(host, window, config, on_output, None).await
}
pub async fn start_request(
host: &Host,
window: &str,
config: RunConfig,
on_output: Emit<OutputChunk>,
request: Option<ide_core::RequestId>,
) -> IdeResult<RunInfo> {
let cancel = request.map(|id| host.begin_request(id)).unwrap_or_default();
let operation = config.extras.params.get("plugin.operation").cloned();
let result = start_inner(host, window, config, on_output).await;
let result = start_inner(host, window, config, on_output, &cancel).await;
if let Some(id) = request {
host.end_request(id);
}
if let (Ok(info), Some(operation), Some(plugins)) = (&result, operation, host.plugin_host()) {
plugins.run_operation_started(window, &operation, info.id);
}
@@ -216,7 +230,11 @@ async fn start_inner(
window: &str,
mut config: RunConfig,
on_output: Emit<OutputChunk>,
cancel: &ide_core::CancellationToken,
) -> IdeResult<RunInfo> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
host.require_trust(window)?;
let project = host.project(window)?;
if config.extras.target.is_none() {
@@ -259,7 +277,23 @@ async fn start_inner(
host.plugin_host().ok_or_else(|| IdeError::not_found("plugin run target is no longer available"))?;
let root = project.root.clone();
let id = id.to_owned();
let config = host.blocking(move || plugins.prepare_run_target(&root, &id, &config)).await?;
let token = cancel.clone();
let config = host
.blocking(move || {
let operation =
if config.extras.params.get("plugin.targetOperation").is_some_and(|op| op == "debug") {
ide_plugin::RunTargetOperation::Debug
} else if config.is_test {
ide_plugin::RunTargetOperation::Test
} else {
ide_plugin::RunTargetOperation::Run
};
plugins.prepare_run_target_launch(&root, &id, &config, operation, &token)
})
.await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
project.require_trust()?;
return host.processes.start(
&project.root,
+36 -3
View File
@@ -143,6 +143,8 @@ struct Meta {
retry_at: Option<Instant>,
/// The component exports `syntax-provider` (known once activated).
has_syntax: bool,
/// Known before activation can publish target registrations.
has_run_target_validation: bool,
/// Next `on-schedule` activation.
next_schedule: Option<Instant>,
/// The trusted publisher of a signed installed package.
@@ -164,6 +166,7 @@ impl Meta {
failures: 0,
retry_at: None,
has_syntax: false,
has_run_target_validation: false,
publisher: None,
next_schedule: None,
}
@@ -1432,6 +1435,20 @@ impl PluginHost {
cancel: Option<&ide_core::CancellationToken>,
f: impl Fn(&mut Runtime, Invocation) -> Result<R, CallError> + Clone + Send + 'static,
) -> IdeResult<R> {
self.code_call_with_budget(id, invocation, what, cancel, None, f)
}
fn code_call_with_budget<R: Send + 'static>(
&self,
id: &str,
invocation: Invocation,
what: &str,
cancel: Option<&ide_core::CancellationToken>,
budget: Option<Duration>,
f: impl Fn(&mut Runtime, Invocation) -> Result<R, CallError> + Clone + Send + 'static,
) -> IdeResult<R> {
let deadline = budget.map(|budget| Instant::now() + budget);
let fallback = ide_core::CancellationToken::new();
let plugin = self.get(id)?;
let client = invocation.client.clone();
{
@@ -1472,10 +1489,25 @@ impl PluginHost {
}
let started = Instant::now();
let (call, inv) = (f.clone(), invocation.clone());
let result = match cancel {
Some(cancel) => actor.call_cancellable(cancel, Duration::from_millis(50), move |rt| call(rt, inv)),
None => actor.call(None, move |rt| call(rt, inv)),
let result = match (deadline, cancel) {
(Some(deadline), cancel) => actor.call_bounded(
cancel.unwrap_or(&fallback),
Duration::from_millis(50),
deadline.saturating_duration_since(Instant::now()),
move |rt| call(rt, inv),
),
(None, Some(cancel)) => {
actor.call_cancellable(cancel, Duration::from_millis(50), move |rt| call(rt, inv))
}
(None, None) => actor.call(None, move |rt| call(rt, inv)),
};
if deadline.is_some() && matches!(result, Err(ActorError::SoftTimeout)) {
self.reap(&plugin, &actor, client.as_deref());
return Err(IdeError::new(
ide_core::error::ErrorKind::TimedOut,
format!("plugin {id:?} timed out while {what}"),
));
}
if matches!(result, Err(ActorError::Cancelled)) {
self.reap(&plugin, &actor, client.as_deref());
return Err(IdeError::cancelled());
@@ -2523,6 +2555,7 @@ impl PluginHost {
return Err(IdeError::internal(format!("plugin {:?} {e}", plugin.id())));
}
};
plugin.meta.lock().has_run_target_validation = rt.has_run_target_validation();
let crash = match rt.activate() {
Ok(_) => None,
Err(CallError::Trap(e)) => Some(format!("activation {e}")),
+66 -1
View File
@@ -101,6 +101,28 @@ impl PluginHost {
root: &Path,
id: &str,
config: &ide_run::RunConfig,
) -> IdeResult<ide_run::RunConfig> {
self.prepare_target(root, id, config, None)
}
/// Prepares a user launch, including the optional plugin validation gate.
pub fn prepare_run_target_launch(
&self,
root: &Path,
id: &str,
config: &ide_run::RunConfig,
operation: ide_plugin::RunTargetOperation,
cancel: &ide_core::CancellationToken,
) -> IdeResult<ide_run::RunConfig> {
self.prepare_target(root, id, config, Some((operation, cancel)))
}
fn prepare_target(
&self,
root: &Path,
id: &str,
config: &ide_run::RunConfig,
launch: Option<(ide_plugin::RunTargetOperation, &ide_core::CancellationToken)>,
) -> IdeResult<ide_run::RunConfig> {
if !self.shared.workspace().is_some_and(|w| w.trusted(root)) {
return Err(IdeError::new(ide_core::error::ErrorKind::PermissionDenied, "project is not trusted"));
@@ -113,7 +135,50 @@ impl PluginHost {
.cloned()
.ok_or_else(|| IdeError::not_found("plugin run target is no longer available"))?;
let program = self.program_for_project(&target.plugin_id, &target.target.program, Some(root))?;
ide_remote::plugin_target::prepare(root, &target.target, &program, config)
let wrapped = ide_remote::plugin_target::prepare(root, &target.target, &program, config)?;
let validates = self.get(&target.plugin_id)?.meta.lock().has_run_target_validation;
if let Some((operation, cancel)) = launch
&& validates
{
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let info = ide_plugin::RunTargetLaunch {
operation,
program: ide_run::wrap::program_name(&config.command),
cwd: wrapped.cwd.as_ref().unwrap().to_string_lossy().into_owned(),
};
let project_root = root.to_path_buf();
let invocation =
ide_plugin::Invocation { workspace_root: Some(project_root.clone()), ..Default::default() };
let (target_id, timeout) = (target.target.id.clone(), self.limits.timeout);
let result = self.code_call_with_budget(
&target.plugin_id,
invocation,
"validating the run target",
Some(cancel),
Some(timeout),
move |rt, _| {
rt.validate_run_target(
project_root.to_string_lossy().into_owned(),
target_id.clone(),
info.clone(),
timeout,
)
},
);
match result {
Ok(Ok(())) => {}
Ok(Err(message)) => return Err(IdeError::invalid(format!("{}: {message}", target.plugin_name))),
Err(error) if error.kind == ide_core::error::ErrorKind::Cancelled => return Err(error),
Err(error) => return Err(IdeError::unavailable(format!("{}: {error}", target.plugin_name))),
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
self.program_for_project(&target.plugin_id, &target.target.program, Some(root))?;
}
Ok(wrapped)
}
}
+1 -1
View File
@@ -262,7 +262,7 @@ impl Dispatcher {
.add("run_system_env", |_| async move { Ok(ide_run::system_env()) })
.add("run_start", |c| async move {
let on_output = c.channel("onOutput")?;
ops::run::start(&c.host, &c.window, c.arg("config")?, on_output).await
ops::run::start_request(&c.host, &c.window, c.arg("config")?, on_output, c.arg("request")?).await
})
.add("run_stop", |c| async move { ops::run::stop(&c.host, &c.window, c.arg("id")?) })
.add("run_stdin", |c| async move { ops::run::stdin(&c.host, c.arg("id")?, &c.arg::<String>("data")?) })
+132 -1
View File
@@ -396,7 +396,15 @@ async fn run_target_api15_overrides_and_frozen_api14_registration() {
for (arg, expected) in cases {
plugins.run_command(plugin, command, Some(arg), invocation()).unwrap();
let target = plugins.run_targets(&f.root).into_iter().find(|t| t.plugin_id == plugin).unwrap();
let wrapped = plugins.prepare_run_target(&f.root, &target.id, &config).unwrap();
let wrapped = plugins
.prepare_run_target_launch(
&f.root,
&target.id,
&config,
ide_plugin::RunTargetOperation::Run,
&Default::default(),
)
.unwrap();
assert_eq!(wrapped.args, expected);
assert_eq!(PathBuf::from(wrapped.command), tool);
assert_eq!(wrapped.cwd.unwrap(), f.root);
@@ -421,3 +429,126 @@ async fn run_target_api15_overrides_and_frozen_api14_registration() {
}
plugins.shutdown();
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn run_target_validation_gates_launches_and_preserves_selection() {
use ide_host::plugins::{Consent, PluginHost};
use ide_plugin::{Invocation, Limits, RunTargetOperation};
use std::os::unix::fs::PermissionsExt;
use std::time::Duration;
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>, _| {}),
Limits {
timeout: Duration::from_millis(200),
idle_timeout: Some(Duration::from_millis(20)),
restart_backoff: Duration::ZERO,
..Default::default()
},
)
.unwrap(),
);
plugins.set_workspace(Some(Arc::new(f.workspace())));
f.host.set_plugin_host(&plugins);
let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/execution");
plugins.install_from_dir(&fixture, &Consent::all()).unwrap();
let tool = f._tmp.path().join("wrapper");
std::fs::write(&tool, "#!/bin/sh\ntouch spawned\n").unwrap();
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
plugins.choose_program("execution", "process:execution-tool", Some(&f.root), Some(&tool)).unwrap();
let invocation =
|| Invocation { client: Some("main".into()), workspace_root: Some(f.root.clone()), ..Default::default() };
let config: ide_run::RunConfig = serde_json::from_value(serde_json::json!({
"id":"composer", "name":"Composer", "kind":"shell", "command":"/tools/composer", "args":["install"],
"env":{"SECRET":"not sent"}, "detected":false, "isTest":false,
}))
.unwrap();
for id in ["allow", "refuse", "long-refusal", "timeout", "trap"] {
plugins.run_command("execution", "target", Some(id), invocation()).unwrap();
}
let targets = plugins.run_targets(&f.root);
let id = |name: &str| targets.iter().find(|t| t.target.id == name).unwrap().id.clone();
for operation in [RunTargetOperation::Run, RunTargetOperation::Test, RunTargetOperation::Debug] {
plugins.prepare_run_target_launch(&f.root, &id("allow"), &config, operation, &Default::default()).unwrap();
let snapshot = plugins.run_command("execution", "validation", None, invocation()).unwrap().unwrap();
assert_eq!(snapshot, format!("{}|allow|{operation:?}|composer|{}", f.root.display(), f.root.display()));
}
tokio::time::sleep(Duration::from_millis(30)).await;
plugins.tick();
assert_eq!(plugins.info_of("execution").unwrap().status, ide_host::plugins::PluginStatus::Inactive);
plugins
.prepare_run_target_launch(&f.root, &id("allow"), &config, RunTargetOperation::Run, &Default::default())
.unwrap();
assert!(plugins.info_of("execution").unwrap().stats.reclaims > 0);
// Non-launch consumers (LSP and document reads) do not invoke validation.
assert!(plugins.prepare_run_target(&f.root, &id("refuse"), &config).is_ok());
let selected = id("refuse");
ide_host::plugins::run_targets::answer(&f.host, &plugins, "main", &selected, true).unwrap();
for is_test in [false, true] {
let mut config = config.clone();
config.is_test = is_test;
config.extras.target = Some(selected.clone());
let error = ide_host::ops::run::start(&f.host, "main", config, Arc::new(|_| {})).await.unwrap_err();
assert!(error.message.contains("Plugin execution tests: Project runtime is stopped"), "{error}");
assert!(f.host.processes.list().is_empty());
assert!(!f.root.join("spawned").exists());
assert_eq!(f.host.project("main").unwrap().settings.effective().run.default_target, selected);
assert_eq!(plugins.run_targets(&f.root).len(), targets.len());
}
for adapter in ["php-debug", "debugpy"] {
let launch = ide_dap::LaunchConfig {
name: "Refused debug".into(),
adapter: adapter.into(),
request: "launch".into(),
program: Some("app.php".into()),
args: Vec::new(),
cwd: Some(f.root.clone().into()),
env: Default::default(),
extra_json: Some(serde_json::json!({"__runTarget":selected, "__runTargetProgram":"php"}).to_string()),
};
let error = ide_host::ops::debug::debug_start(&f.host, "main", launch).await.unwrap_err();
assert!(error.message.contains("Project runtime is stopped"), "{adapter}: {error}");
assert!(f.host.debugger.sessions(None).is_empty());
}
let error = plugins
.prepare_run_target_launch(&f.root, &id("long-refusal"), &config, RunTargetOperation::Run, &Default::default())
.unwrap_err();
assert!(error.message.len() < 4200);
let request = ide_core::RequestId(2408);
let mut cfg = config.clone();
cfg.extras.target = Some(id("timeout"));
let worker = f.host.clone();
let pending = tokio::spawn(async move {
ide_host::ops::run::start_request(&worker, "main", cfg, Arc::new(|_| {}), Some(request)).await
});
tokio::time::sleep(Duration::from_millis(30)).await;
f.host.cancel_request(request);
assert_eq!(pending.await.unwrap().unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
for name in ["timeout", "trap"] {
let started = std::time::Instant::now();
let error = plugins
.prepare_run_target_launch(&f.root, &id(name), &config, RunTargetOperation::Run, &Default::default())
.unwrap_err();
assert!(error.message.contains("Plugin execution tests"), "{error}");
if name == "timeout" {
assert!(error.message.contains("timed out"), "{error}");
assert!(started.elapsed() < Duration::from_secs(2), "background tasks must not extend validation");
}
assert!(f.host.processes.list().is_empty());
}
// A cancelled launch never enters the wrapper.
let cancel = ide_core::CancellationToken::new();
cancel.cancel();
assert_eq!(
plugins
.prepare_run_target_launch(&f.root, &id("allow"), &config, RunTargetOperation::Run, &cancel)
.unwrap_err()
.kind,
ide_core::error::ErrorKind::Cancelled
);
plugins.shutdown();
}
+22
View File
@@ -634,6 +634,28 @@ async fn api14_stage3_remote_terminal_pins_and_exit_events_stay_on_the_execution
.await
.unwrap();
assert_eq!(invoke(&peer, "plugin_run_targets", json!({})).await.unwrap(), json!([]));
invoke(
&peer,
"plugin_run_command",
json!({"pluginId":"execution", "commandId":"target", "arg":"refuse", "editor":null}),
)
.await
.unwrap();
let targets = invoke(&peer, "plugin_run_targets", json!({})).await.unwrap();
let refused = targets[0]["id"].as_str().unwrap();
std::fs::remove_file(project.join("wrapped.txt")).unwrap();
let config = json!({"id":"refused", "name":"Refused", "kind":"shell", "command":"php", "args":[], "env":{}, "detected":false, "isTest":false, "target":refused});
let error = invoke(&peer, "run_start", json!({"config":config, "onOutput":{"$channel":40}})).await.unwrap_err();
assert!(error.to_string().contains("Project runtime is stopped"), "{error}");
assert!(!project.join("wrapped.txt").exists());
assert!(desktop.run_targets(&project).is_empty());
invoke(
&peer,
"plugin_run_command",
json!({"pluginId":"execution", "commandId":"untarget", "arg":"refuse", "editor":null}),
)
.await
.unwrap();
client.plugin_events.lock().clear();
client.events.lock().clear();
let runner = peer.clone();
+20 -6
View File
@@ -196,7 +196,7 @@ impl Actor {
grace: Duration,
f: impl FnOnce(&mut Runtime) -> Result<R, CallError> + Send + 'static,
) -> Result<R, ActorError> {
self.call_cancellable_before(cancel, grace, None, f)
self.call_cancellable_before(cancel, grace, None, false, f)
}
/// A cancellable editor call: queued work expires after `soft`, and a
@@ -209,7 +209,18 @@ impl Actor {
soft: Duration,
f: impl FnOnce(&mut Runtime) -> Result<R, CallError> + Send + 'static,
) -> Result<R, ActorError> {
self.call_cancellable_before(cancel, grace, Some(Instant::now() + soft), f)
self.call_cancellable_before(cancel, grace, Some(Instant::now() + soft), false, f)
}
/// A launch gate's deadline also interrupts running host calls and background tasks.
pub fn call_bounded<R: Send + 'static>(
&self,
cancel: &ide_core::CancellationToken,
grace: Duration,
timeout: Duration,
f: impl FnOnce(&mut Runtime) -> Result<R, CallError> + Send + 'static,
) -> Result<R, ActorError> {
self.call_cancellable_before(cancel, grace, Some(Instant::now() + timeout), true, f)
}
fn call_cancellable_before<R: Send + 'static>(
@@ -217,6 +228,7 @@ impl Actor {
cancel: &ide_core::CancellationToken,
grace: Duration,
deadline: Option<Instant>,
hard_deadline: bool,
f: impl FnOnce(&mut Runtime) -> Result<R, CallError> + Send + 'static,
) -> Result<R, ActorError> {
let (reply, result) = mpsc::sync_channel(1);
@@ -260,7 +272,7 @@ impl Actor {
match result.recv_timeout(Duration::from_millis(5)) {
Ok(outcome) if cancelled_at.is_some() => {
drop(outcome);
return Err(ActorError::Cancelled);
return Err(if cancel.is_cancelled() { ActorError::Cancelled } else { ActorError::SoftTimeout });
}
Ok(outcome) => return outcome,
Err(mpsc::RecvTimeoutError::Disconnected) => {
@@ -268,19 +280,21 @@ impl Actor {
}
Err(mpsc::RecvTimeoutError::Timeout) => {}
}
if !cancel.is_cancelled() {
let timed_out = hard_deadline && deadline.is_some_and(|t| Instant::now() >= t);
if !cancel.is_cancelled() && !timed_out {
if deadline.is_some_and(|t| Instant::now() >= t) && !*running.lock().unwrap_or_else(|e| e.into_inner())
{
return Err(ActorError::SoftTimeout);
}
continue;
}
let failure = || if cancel.is_cancelled() { ActorError::Cancelled } else { ActorError::SoftTimeout };
match cancelled_at {
None => {
cancelled_at = Some(Instant::now());
let running = running.lock().unwrap_or_else(|e| e.into_inner());
if !*running {
return Err(ActorError::Cancelled);
return Err(failure());
}
self.cancel.cancel_soft();
}
@@ -290,7 +304,7 @@ impl Actor {
if *running {
self.cancel();
}
return Err(ActorError::Cancelled);
return Err(failure());
}
Some(_) => {}
}
+16
View File
@@ -151,3 +151,19 @@ pub enum PluginTestEvent {
Output(TestOutput),
Other { kind: String, data: String },
}
/// Operation about to launch through a plugin-owned run target (API 1.5).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RunTargetOperation {
Run,
Debug,
Test,
}
/// Launch metadata available to a target validator; arguments and environment are omitted.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RunTargetLaunch {
pub operation: RunTargetOperation,
pub program: String,
pub cwd: String,
}
+37
View File
@@ -18,6 +18,7 @@ use crate::types::{
};
use crate::wit_host::injections_bindings::exports::openidea::plugin::injections as wit_inj;
use crate::wit_host::language_features_bindings::exports::openidea::plugin::language_features as wit_lf;
use crate::wit_host::run_target_validation_bindings::exports::openidea::plugin::run_target_validation as wit_rtv;
use crate::wit_host::{
bindings, commit_checks_bindings, details_bindings, endpoints_bindings, file_actions_bindings, hover_bindings,
indexing_bindings, inlay_bindings, providers_bindings, semantic_bindings, syntax_bindings, views_bindings,
@@ -925,6 +926,7 @@ pub struct Runtime {
/// What the component exports: the `plugin` world, plus optional interfaces.
struct Exports {
run_target_validation: Option<wit_rtv::Guest>,
language_features: Option<wit_lf::Guest>,
injections: Option<wit_inj::Guest>,
plugin: bindings::Plugin,
@@ -1062,6 +1064,7 @@ impl Runtime {
let endpoint_indices = wit_endpoints::GuestIndices::new(&pre).ok();
let configs_indices = wit_configs::GuestIndices::new(&pre).ok();
let tests_indices = wit_tests::GuestIndices::new(&pre).ok();
let validation_indices = wit_rtv::GuestIndices::new(&pre).ok();
let lf_indices = wit_lf::GuestIndices::new(&pre).ok();
let inj_indices = wit_inj::GuestIndices::new(&pre).ok();
let mcp_indices =
@@ -1073,6 +1076,8 @@ impl Runtime {
let test_results = tests_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
let language_features = lf_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
let injections = inj_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
let run_target_validation =
validation_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
let plugin = plugin_indices.load(&mut store, &instance).map_err(api_hint)?;
let syntax = match syntax_indices {
Some(indices) => Some(indices.load(&mut store, &instance).map_err(api_hint)?),
@@ -1125,6 +1130,7 @@ impl Runtime {
Ok(Self {
store,
exports: Exports {
run_target_validation,
language_features,
injections,
plugin,
@@ -1149,6 +1155,37 @@ impl Runtime {
})
}
pub fn has_run_target_validation(&self) -> bool {
self.exports.run_target_validation.is_some()
}
/// Missing optional validators allow the launch without a guest call.
pub fn validate_run_target(
&mut self,
root: String,
target: String,
launch: crate::RunTargetLaunch,
timeout: Duration,
) -> Result<Result<(), String>, CallError> {
if self.exports.run_target_validation.is_none() {
return Ok(Ok(()));
}
let invocation = Invocation { workspace_root: Some(root.clone().into()), ..Default::default() };
let launch = wit_rtv::LaunchInfo {
operation: match launch.operation {
crate::RunTargetOperation::Run => wit_rtv::Operation::Run,
crate::RunTargetOperation::Debug => wit_rtv::Operation::Debug,
crate::RunTargetOperation::Test => wit_rtv::Operation::Test,
},
program: launch.program,
cwd: launch.cwd,
};
self.call(invocation, timeout, |e, store| {
e.run_target_validation.as_ref().unwrap().call_validate(store, &root, &target, &launch)
})
.map(|r| r.map_err(|message| clip(message, 4096)))
}
/// Complete configurations from the optional API 1.4 export.
pub fn run_configurations(
&mut self,
+5
View File
@@ -2335,3 +2335,8 @@ pub(crate) mod mcp_bindings {
},
});
}
/// Optional API 1.5 run-target launch validation.
pub(crate) mod run_target_validation_bindings {
wasmtime::component::bindgen!({ world: "run-target-validator", path: "../../wit" });
}
Binary file not shown.
@@ -1 +1 @@
d81ad44c8f692952bbe4607767a4170764baa1679710247994d6b8eea0d10c61
023542d758cd359aa4d1282b95ddd2edca9fcf746862700705dd637b3e524571
Binary file not shown.
@@ -1 +1 @@
21c33be60354c4d5e46f4dee586b537ed8746bc2da0e64263a9f4e93b6e5894d
ef4cedb7ab9caa7a5a597fa8bd302e4e10607989c575af1ca0c237f2d8bb06c8
Binary file not shown.
@@ -1 +1 @@
d8c39a1706d6ba876bcab84f170449dadad4f77803825eeee6848e3d5554f849
c215812502ccbb85b08efb9da234e6e9709deb84a492b41e771c61d4c38a05fb
Binary file not shown.
@@ -1 +1 @@
7569252352dc948cfd842633ea830bb0f136d1490124d2263bcd639e4c6c3ee1
52efdb99877cded6fc5357d80f722975e314610b9d2bc91979b4b4cb05d8cdb8
Binary file not shown.
@@ -1 +1 @@
b9106a3fd3bfa4e33cfaa78cf5b76c4bb1c2b85f74c8757ede38d50076aee8cc
0fb78e5c48f267e529ceb719ceb1e5aca82f2288071e9a0cc14809c27e7cd15a
Binary file not shown.
@@ -1 +1 @@
50d8dea354f8ffe7ef944ba87f0b20691d1c7c352e0bcb1077d6c3d7d57cdd10
5a4c7a37b5ff83d62dcc3da616da3712113fa6257e834f51705a4f7e417e519a
Binary file not shown.
@@ -1 +1 @@
0fd9a8a38a8841a13ea8850218e7d890beb6d6d3ad5a70b9960a672fc5bd2335
e5598d719f6e66790858758718842e4474747c6e14eb3e1c29c4584b26279ef6
@@ -54,3 +54,7 @@ title = "untarget"
[[contributes.commands]]
id = "target-overrides"
title = "target-overrides"
[[contributes.commands]]
id = "validation"
title = "validation"
+23 -1
View File
@@ -79,6 +79,7 @@ impl Plugin for Execution {
Ok(None)
}
"events" => host::storage::get("events"),
"validation" => host::storage::get("validation"),
_ => Err(Error::NotFound(id.into())),
}
}
@@ -147,4 +148,25 @@ impl TestResults for Execution {
]
}
}
register_plugin!(Execution, run_configurations, test_results);
impl RunTargetValidation for Execution {
fn validate(&mut self, project: &str, target: &str, launch: &RunTargetLaunch) -> Result<(), String> {
host::storage::set(
"validation",
&format!("{project}|{target}|{:?}|{}|{}", launch.operation, launch.program, launch.cwd),
)
.unwrap();
match target {
"refuse" => Err("Project runtime is stopped".into()),
"long-refusal" => Err("x".repeat(10000)),
"trap" => panic!("validator failed"),
"timeout" => {
let _task = host::begin_task("Validation", true);
loop {
std::hint::spin_loop();
}
}
_ => Ok(()),
}
}
}
register_plugin!(Execution, run_configurations, test_results, run_target_validation);
Binary file not shown.
@@ -1 +1 @@
bbc685cc20c007f636ac4c5d746beeed1a7c2bd7c695d63406ee4f117ce2b9fb
18a37beb12a0a3da68345314f7bfbb9521e8819702ef50a1c81f29bc3112c997
Binary file not shown.
@@ -1 +1 @@
1f7162ecc79f15759955323d18f177f2509a74d45ba243e6b16c175d709d2e89
c464178ead4043d49d10e63430436f9e261b211b1a7ff18d146ed244975baf7d
Binary file not shown.
@@ -1 +1 @@
29fbb94310dabe5b17a02c798bfb3b12f33ed477c2ef40f487938b78c82217c2
655bbe70bf3280a6e301255955d3e99e68b29242538b60060f61082977019212
Binary file not shown.
@@ -1 +1 @@
fd770a1afbe7d72274489ff242acbc6a43dee26db4326912b72336af7895ac46
2987ca7af6f5ae800ed3bcf826b7f85b713371cb6efa483953e0a4974248f61f
Binary file not shown.
@@ -1 +1 @@
37de792bbee6fde3d67ff764ae44b89e445e2f26c8d08da51e4640330a467b01
ff914b1c3ae4709c86e8138cdc84ea500ebde77ac09dcd3722faeffeb25b3454
Binary file not shown.
@@ -1 +1 @@
756f63c986b1cec81ea90bbb3d6b3f85d8334dbd8f83910c2cdc80c416c9d66c
8db8367b3e0872ebcb03b7f37a55fa1510f52e7f40eb07e401a40a0019349eb8
Binary file not shown.
@@ -1 +1 @@
cbbf102678d2f7c5ecafb4ab4d1b3400d174a7a8f5b03294a08ee933cc00e113
8ec23043c138a4fe9ba13cdaf13b78b56032eea14f48caddde6e5016226e3d28
Binary file not shown.
@@ -1 +1 @@
544de6da356058e1922cbb5dc3baf6600854408e62dbfcc6b82deb88151f24c1
cde70a51050b29cbf553df08c6aadb660be51c9146ec1d3e186de55a3130a7c1
@@ -1 +1 @@
deae386bce1cfaad1ef53bcfbac5566ccc75701ba114f58694070fd33393e6c5
21ac46f028c4a151b1f89eac12ad8894d1dbc84a3489f3054dec239c87de5e4a
@@ -1 +1 @@
10ce571ece76b5827ee8978920b1308a28e68f1bf5720b0f647ea5fd707ee8f1
7981067231363be183e28e9aa0dd8cffb430783080c702a1843c361187b3f267
Binary file not shown.
@@ -1 +1 @@
ed1f9f0aea72e716741d7ef9ca7e32f6ad4a14407542820ae225ea950b6f8f17
e4fafd8b7ea6d9bb6d10836c8fc133a58277f68e293410d221372bced719a192
Binary file not shown.
@@ -1 +1 @@
ee185fdb8c1b2a63e502e81580d0d1c71e5ed04fd142179e7d3c30f9f1d874f7
c6d9a0c72cf63c1a4ddb9cb45fa7eaf2cd4d6e14d6977b6e834196ad526f0a2a
Binary file not shown.
@@ -1 +1 @@
cebb6995dc8c59add6cee7289040f5d0373f34c403084a349ff650bd1dcf3331
004d552137bc2d2654b7343a9368c14e8b8f07a03f31fb70b7ac42481bdfac8c
Binary file not shown.
@@ -1 +1 @@
12d2044f25d901f512da5e9ec06750d76e9bbd9e78d68f1f39466bcf0bea7c2a
bfbadd644f0b65d36817177a935f1262baf136ea26378902d01e9e3b6eec6412
Binary file not shown.
@@ -1 +1 @@
d5584311077faeb8780508d3aecc4a828291def9fabd139fd2a0fce2423f6f48
691d78767dadaa3bb8892b15592072cd343ca618d59e82653012de78e5072b22
Binary file not shown.
@@ -1 +1 @@
3bbf01325ae6acf1561d5a451fff60e82bee3ea8ec1cb1969aaada6e44d0b984
280029aedd5945d7ddff74431e8b95aa785974849f86edeb9537da3a091e7dc7
Binary file not shown.
@@ -1 +1 @@
ae23673dd954183f9c282a9cbca9551cd6a4169c7df5df57d5a46a96c5b67dce
a9f63e4356ee83109e94b19d69d5bef0e49ef6f1a46c37fb00821824b82a1f0e
Binary file not shown.
@@ -1 +1 @@
b15392faca085b6e5f352028842ab71b94e0cba5c5831df6a706ecd1a00228d2
18ff48039b86b8d2f071adefcba4c44e51d8b5726f9f670f31cf63473b1a657f
Binary file not shown.
@@ -1 +1 @@
d17868c5ce30ed1d7c21e99b802199b5fb49ea8b962433915d16db40eed11e16
3ae6657f9a01dfd7767c1a2d211baeba2fadca0f2f7e4c1df35d35dd4f348dba
Binary file not shown.
@@ -1 +1 @@
d765f7ae65ca7b904589b73f5580346a98b3423982ce3655759442c250218202
0ed690a8233920d47bcf162954eb5e8d15cd9fd4cd704232d5a92708cd49cb18
+33
View File
@@ -2541,6 +2541,39 @@ and diagnostic-related locations. Navigation inside these documents returns to
that server; editing and saving
are disabled. No WIT signature change is needed for this opt-in host setting.
### Validating run targets (API 1.5)
A plugin can export `run-target-validation.validate` to check current project
runtime state immediately before Run, Test or Debug. In the Rust SDK implement
`RunTargetValidation` and add `run_target_validation` to `register_plugin!`:
```rust
impl RunTargetValidation for MyPlugin {
fn validate(&mut self, project: &str, target_id: &str, launch: &RunTargetLaunch) -> Result<(), String> {
// Inspect runtime state through the plugin's granted APIs.
if runtime_is_running(project) { Ok(()) } else { Err("Project runtime is stopped".into()) }
}
}
register_plugin!(MyPlugin, run_target_validation);
```
The callback receives the project root, the plugin's own target id and
`RunTargetLaunch { operation, program, cwd }`. `operation` is Run, Debug or Test;
`program` is the bare program being wrapped, and `cwd` is the absolute local
working directory on the plugin's machine. Arguments and environment are omitted.
Trust, target ownership, process grants and executable pins are checked first.
No extra manifest contribution or capability is required; plugins without the
export retain their existing behavior. Language server startup and target document
reads do not invoke this user-launch gate.
`Err(message)` refuses startup through the normal launch error path, prefixed
with the plugin name and bounded to 4096 bytes. The registration and selected
target remain unchanged. A trap or timeout also refuses startup; cancellation
interrupts the callback. Calls wake idle-reclaimed instances and use the host's
normal call timeout (five seconds by default). For remote projects validation
runs on the server, alongside the plugin and wrapper. Native SDK tests can use
`MockHost::validate_run_target` to invoke their validator.
### Debugging run targets
Plugin targets require `container-root` for debugging. PHP uses `connect-back`: the
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
f5a9a182faefb9520664479cf2b926ced08806d4258b5790745d95a2df09e32c
2c50c70ca000609f9eaa2f197e0c3f4d9f397689211b77182505743e341ca925
Binary file not shown.
@@ -1 +1 @@
8b31a00cfb1bc12bf6a959ac63c4ac0ff9c589d23d85b76fd8d583cbe22ce4f3
b0bd637ce12972984c77774b2acae270c425f5b7177ad91c1dc62231eb098218
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
8bb797a7162fa056ddff521be27bea97be613d449adf963a60aa2a4e98fec225
bbb8845b97a504431625929ad8eb627773eb365f8b6728b9c33f43ab61e15687
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
a32f53654d20f9f2c63dcc4f935ece7da5d2f5a7b6353be2c852c2ff90210879
ce4ffc8dea00757ed4ff3ef7949563afca656987f9b589ef68c76a66140caa03
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
545f82f9b4f3fb8b8205728062eaf786efdcf8021b89e5a3f83f4729d67b70c8
e3aca14076ac010d3115123eebef58249c8200264d706c95c3177ec5215153c8
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
84eec5f62cf13b2a42efe2e3d0cd82ac4ba14289ad1996dd20d10e5e314faacb
a46eb4786834655a4706ee1b2219c52f390bbb3b38c5b74fd7127ff4dd8abd73
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
e3cf0c8796400e9cd1d078df3deb597c1eb05d90c24dbc071813d0dd165c0f74
57e5f1c3cece832b309d48fcf8e8cd2e2227de9bc993415b05c7562dc931edce
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
25067d01e6be39c86d0a0437293a11b39d7023d35f5c42322f814009c2c6f38f
5057bf63ee9af0ed529a8eb6fc803889d4fed08c83b480171494a4c28e60f7e7
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
72b4be4fedf6cddd4c73ce26b9cdf6495f1878d3b1a3aa376659af3d1fe21bda
46cd532de4daa85adb73beaae3f1ed078b7de14e7959a065f5e72b774c086c4c
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
f0ea10f9e0a24e9fd9d7f28198f4d15b74cd768889e50c7b79dbf3491c4c864d
428308db73d25b65fdad1fc2cfee28009befd7a2cdc6694f1c54bcb0dad700e7
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
423c63836d4534143c671e147ca92d46f1542212a538efbc980db89ec93a4ef2
d5155bf79f921bf90a3432cf4cd1b1aae31a08d1f0b61c9777649905fdfe2526
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
ed13572441774355ceada20a503fc051989fe16235564503b7394c3a597b322f
46bb85f125d5b9bd141abca3ff6456e58f58f45969c4a9d2106f59b6b2b80fdd
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
9065f67eb3a31cc7b87397aaa7e287491d0f6ddc69ff3c12ef3b171ee02edc2d
c149abe2339645a3472c399f2286123e1c82e3a76ec29c3768804dbbee90b39a
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
e34b4830edaf1917197e59839c8a403e394e9e84f9921cabd837442955ad1754
786bda583e0fcc63b2dd869fbde927a401388ea7a355fd7de9123f49c2bb1636
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
abea88f2e82077f6a2e1b428d583c2b79fcf985c485e25b4441aaa64336e7e28
7e04fc25c3bf14d8242a0b0f7fb93312a3fb1fb0034c732a7964a314ca4be4d0
+22
View File
@@ -237,3 +237,25 @@ impl From<PluginRunTarget> for PluginRunTargetWithOverrides {
}
}
}
/// Operation about to launch through a plugin-owned run target (API 1.5).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RunTargetOperation {
Run,
Debug,
Test,
}
/// Launch metadata available to a target validator; arguments and environment are omitted.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RunTargetLaunch {
pub operation: RunTargetOperation,
pub program: String,
pub cwd: String,
}
/// Optional pre-launch validation; register with `run_target_validation`.
pub trait RunTargetValidation {
/// Refuse with a user-facing explanation, or allow with `Ok(())`.
fn validate(&mut self, project: &str, target_id: &str, launch: &RunTargetLaunch) -> Result<(), String>;
}
+39
View File
@@ -286,6 +286,7 @@ macro_rules! register_plugin {
#[doc(hidden)]
#[macro_export]
macro_rules! __optional_exports {
(run_target_validation, $plugin:ty, $component:ident) => { $crate::__run_target_validation_exports!($plugin, $component); };
(injections, $plugin:ty, $component:ident) => { $crate::__injections_exports!($plugin, $component); };
(language_features, $plugin:ty, $component:ident) => { $crate::__language_features_exports!($plugin, $component); };
(mcp, $plugin:ty, $component:ident) => { $crate::__mcp_exports!($plugin, $component); };
@@ -1084,6 +1085,24 @@ pub mod __rt {
with::<T, _>(|p| p.call(tool, arguments, &ctx)).map_err(error_out)
}
pub fn validate_run_target<T: Plugin + crate::RunTargetValidation + Default>(
root: &str,
target: &str,
launch: crate::run_target_validation_bindings::exports::openidea::plugin::run_target_validation::LaunchInfo,
) -> Result<(), String> {
use crate::run_target_validation_bindings::exports::openidea::plugin::run_target_validation::Operation;
let launch = crate::RunTargetLaunch {
operation: match launch.operation {
Operation::Run => crate::RunTargetOperation::Run,
Operation::Debug => crate::RunTargetOperation::Debug,
Operation::Test => crate::RunTargetOperation::Test,
},
program: launch.program,
cwd: launch.cwd,
};
with::<T, _>(|p| p.validate(root, target, &launch))
}
pub fn configurations<T: Plugin + crate::RunConfigurations + Default>(
root: &str,
) -> Vec<crate::run_configurations_bindings::exports::openidea::plugin::run_configurations::RunConfiguration> {
@@ -1421,3 +1440,23 @@ macro_rules! __mcp_exports {
$crate::mcp_bindings::__export_mcp_world!($component with_types_in $crate::mcp_bindings);
};
}
#[cfg(target_arch = "wasm32")]
#[doc(hidden)]
pub mod run_target_validation_bindings {
wit_bindgen::generate!({ world: "run-target-validator", path: "wit", pub_export_macro: true,
export_macro_name: "__export_target_validation_world",
default_bindings_module: "openidea_plugin::run_target_validation_bindings" });
}
#[doc(hidden)]
#[macro_export]
macro_rules! __run_target_validation_exports {
($plugin:ty, $component:ident) => {
impl $crate::run_target_validation_bindings::exports::openidea::plugin::run_target_validation::Guest for $component {
fn validate(project: String, target: String, launch: $crate::run_target_validation_bindings::exports::openidea::plugin::run_target_validation::LaunchInfo) -> Result<(), String> {
$crate::__rt::validate_run_target::<$plugin>(&project, &target, launch)
}
}
$crate::run_target_validation_bindings::__export_target_validation_world!($component with_types_in $crate::run_target_validation_bindings);
};
}

Some files were not shown because too many files have changed in this diff Show More