diff --git a/crates/ide-extension/src/capability.rs b/crates/ide-extension/src/capability.rs index d5a27c8f8..ae314fb19 100644 --- a/crates/ide-extension/src/capability.rs +++ b/crates/ide-extension/src/capability.rs @@ -55,6 +55,9 @@ pub enum Capability { FsRead(String), /// Write files outside the project under one path. FsWrite(String), + /// Load the plugin's Java agent into the JVMs of Java run configurations. Never + /// declared: it comes from `[[contributes.javaAgents]]`. + JavaAgent, } /// How a grant is presented (plan 4.2). @@ -90,7 +93,8 @@ impl Capability { | Self::Process(_) | Self::Lsp(_) | Self::FsRead(_) - | Self::FsWrite(_) => Risk::High, + | Self::FsWrite(_) + | Self::JavaAgent => Risk::High, } } @@ -135,6 +139,7 @@ impl Capability { } Self::FsRead(path) => format!("Read files under {path}, outside the project"), Self::FsWrite(path) => format!("Change files under {path}, outside the project"), + Self::JavaAgent => "Run code inside the Java applications you start".into(), } } @@ -259,6 +264,7 @@ impl fmt::Display for Capability { Self::Lsp(s) => write!(f, "lsp:{s}"), Self::FsRead(p) => write!(f, "fs.read:{p}"), Self::FsWrite(p) => write!(f, "fs.write:{p}"), + Self::JavaAgent => f.write_str("java.agent"), } } } @@ -335,6 +341,7 @@ impl FromStr for Capability { "events" => Self::Events, "events.input" => Self::InputEvents, "clipboard" => Self::Clipboard, + "java.agent" => Self::JavaAgent, _ => return Err(format!("unknown capability {s:?}")), }) } @@ -392,6 +399,7 @@ mod tests { "process:cargo", "lsp:phoxite", "lsp:rust-analyzer", + "java.agent", ] { assert_eq!(s.parse::().unwrap().to_string(), s); } @@ -427,6 +435,8 @@ mod tests { assert_eq!(Capability::Lsp("phoxite".into()).risk(), Risk::High); assert!(!Capability::Lsp("phoxite".into()).covers(&Capability::Lsp("intelephense".into()))); assert!(Capability::Storage.auto_migrates() && !Capability::EditorWrite.auto_migrates()); + assert_eq!(Capability::JavaAgent.risk(), Risk::High); + assert!(!Capability::JavaAgent.auto_migrates()); } /// A trusted project's files name programs the IDE starts by itself: the git and language diff --git a/crates/ide-extension/src/ledger.rs b/crates/ide-extension/src/ledger.rs index 6e800a0fb..4e0f31021 100644 --- a/crates/ide-extension/src/ledger.rs +++ b/crates/ide-extension/src/ledger.rs @@ -10,6 +10,8 @@ //! - `process:` grants record the program's absolute path and file //! hash at grant time. Calls use that path, never a `PATH` lookup, and fail //! when the file changed (re-confirmation needed). +//! - `java.agent` grants record the agent jar's path and hash the same way; +//! a launch adds the agent only while the jar still has that hash. use crate::capability::{Capability, Risk}; use serde::{Deserialize, Serialize}; @@ -267,7 +269,7 @@ impl Ledger { if cap == &Capability::NetAsk { grant.net_hosts.clear(); } - if let Capability::Process(_) = cap { + if let Capability::Process(_) | Capability::JavaAgent = cap { grant.binaries.remove(&s); for binaries in grant.project_binaries.values_mut() { binaries.remove(&s); @@ -290,7 +292,7 @@ impl Ledger { self.grants.get_mut(subject).is_some_and(|g| g.net_hosts.remove(host)) } - /// Records the program approved for a `process:` grant. + /// Records the program approved for a `process:` grant (or the jar of a `java.agent` one). pub fn set_binary(&mut self, subject: &Subject, cap: &Capability, binary: BinaryGrant) { if let Some(grant) = self.grants.get_mut(subject) { grant.binaries.insert(cap.to_string(), binary); @@ -675,6 +677,21 @@ mod tests { assert!(l.check_binary(&r.subject, &cap).unwrap_err().contains("changed")); } + #[test] + fn revoking_java_agent_forgets_its_jar() { + let mut l = Ledger::in_memory(); + let r = req("1.0.0", "h", &[], &["java.agent"]); + let cap = Capability::JavaAgent; + let jar = BinaryGrant { path: "/plugins/p/agent.jar".into(), hash: "abc".into() }; + l.confirm(&r, std::slice::from_ref(&cap), [(cap.to_string(), jar.clone())].into()); + assert_eq!(l.pinned_binary(&r.subject, &cap), Some(jar.clone())); + l.set(&r.subject, &cap, false); + assert_eq!(l.pinned_binary(&r.subject, &cap), None); + // Granting again without a new hash does not bring the old one back. + l.set(&r.subject, &cap, true); + assert_eq!(l.pinned_binary(&r.subject, &cap), None); + } + #[test] fn hashes_and_grouping() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-extension/src/manifest.rs b/crates/ide-extension/src/manifest.rs index 75beb83e4..2db8c44ab 100644 --- a/crates/ide-extension/src/manifest.rs +++ b/crates/ide-extension/src/manifest.rs @@ -360,6 +360,11 @@ impl Manifest { if matches!(cap, Capability::Lsp(_)) { self.needs_api(&format!("capability `{cap}`"), 9)?; } + if matches!(cap, Capability::JavaAgent) { + return Err( + "`java.agent` comes from `[[contributes.javaAgents]]`: remove it from [capabilities]".into() + ); + } } if let Some(dark) = &self.icon_dark { if self.icon.is_none() { @@ -730,6 +735,14 @@ required = [\"lsp:phoxite\"] assert_eq!(m.capabilities.required, [Capability::Lsp("phoxite".into())]); } + #[test] + fn java_agent_capability_is_not_declared() { + for list in ["required", "optional"] { + let caps = format!("[capabilities]\n{list} = [\"java.agent\"]\n"); + assert!(err(&format!("{}{caps}", BASE.replace("^1.2", "^1.10"))).contains("contributes.javaAgents")); + } + } + #[test] fn parses_icons() { let m = Manifest::parse(&format!("{BASE}icon = \"icon.svg\"\nicon-dark = \"icon_dark.svg\"\n")).unwrap(); diff --git a/crates/ide-host/src/ops/debug.rs b/crates/ide-host/src/ops/debug.rs index bc080c96f..1c10fdb09 100644 --- a/crates/ide-host/src/ops/debug.rs +++ b/crates/ide-host/src/ops/debug.rs @@ -31,6 +31,8 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide } else { None }; + let agents = if is_jvm_launch(&config) { ide_run::java_agent::current() } else { Default::default() }; + let config = add_java_agents(config, &agents.options); let mut config = match_java_debug_encoding(start_java_attach_listener(config, cfg!(windows)), cfg!(windows)); if config.adapter == "debugpy" && config.request == "launch" @@ -119,6 +121,15 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide let server_port = debug_server_port(&config); let result = host.debugger.start_with(config, owner, custom).await; flush_output(); + if let Ok(id) = &result { + let sink = host.window_sink(label); + for note in &agents.notes { + sink.emit(ide_core::IdeEvent::Debug { + session: *id, + event: ide_core::event::DebugEvent::Output { category: "console".into(), output: format!("{note}\n") }, + }); + } + } if result.is_err() && let Some(pid) = unity_pid { @@ -165,6 +176,45 @@ fn attach_jvm_inspector(host: &Host, window: &str, session: DebugSessionId, port } } +/// A JVM the debugger starts itself: an Application or Spring Boot configuration, launched by +/// java-debug or the Kotlin debugger (JAR Application debugs through a run with a JDWP agent). +fn is_jvm_launch(config: &LaunchConfig) -> bool { + config.request == "launch" && matches!(config.adapter.as_str(), "java-debug" | ide_dap::kotlin::ADAPTER) +} + +/// Plugins' Java agents ([`ide_run::java_agent`]) after the configuration's VM options: +/// java-debug's `vmArgs` (one line, or a list) or the Kotlin debugger's `vmArguments` (a list). +fn add_java_agents(mut config: LaunchConfig, options: &[String]) -> LaunchConfig { + if options.is_empty() || !is_jvm_launch(&config) { + return config; + } + let Some(serde_json::Value::Object(mut extra)) = + config.extra_json.as_deref().and_then(|e| serde_json::from_str(e).ok()) + else { + return config; + }; + let key = if config.adapter == "java-debug" { "vmArgs" } else { "vmArguments" }; + let value = match extra.get(key) { + None | Some(serde_json::Value::Null) if key == "vmArgs" => { + ide_run::java_agent::add_to_vm_args_text("", options).into() + } + Some(serde_json::Value::String(text)) => ide_run::java_agent::add_to_vm_args_text(text, options).into(), + None | Some(serde_json::Value::Null) | Some(serde_json::Value::Array(_)) => { + let mut list: Vec = extra + .get(key) + .and_then(serde_json::Value::as_array) + .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect()) + .unwrap_or_default(); + ide_run::java_agent::add_to_vm_args(&mut list, options); + list.into() + } + Some(_) => return config, + }; + extra.insert(key.into(), value); + config.extra_json = Some(serde_json::Value::Object(extra).to_string()); + config +} + /// The JVM memory tab reads the class table over the attach socket, which only exists once the /// JVM has started its attach listener. The flag goes first so the user's arguments still win. /// Not on Windows (`windows`: the JVM runs there), which the memory view does not support. @@ -818,6 +868,36 @@ mod tests { ); } + #[test] + fn plugin_java_agents_join_the_vm_options_of_jvm_launches() { + let agent = "-javaagent:/my plugins/agent.jar=port=0".to_owned(); + let options = std::slice::from_ref(&agent); + let field = |config: &LaunchConfig, key: &str| { + serde_json::from_str::(config.extra_json.as_deref().unwrap()).unwrap()[key].clone() + }; + let debugged = + add_java_agents(launch("java-debug", "launch", serde_json::json!({"vmArgs": "-Xmx1g"})), options); + assert_eq!(vm_args(&debugged), "-Xmx1g \"-javaagent:/my plugins/agent.jar=port=0\""); + assert_eq!(add_java_agents(debugged.clone(), options).extra_json, debugged.extra_json, "not added twice"); + let none = add_java_agents(launch("java-debug", "launch", serde_json::json!({"vmArgs": null})), options); + assert_eq!(vm_args(&none), "\"-javaagent:/my plugins/agent.jar=port=0\""); + let list = add_java_agents(launch("java-debug", "launch", serde_json::json!({"vmArgs": ["-Xmx1g"]})), options); + assert_eq!(vm_args(&list), serde_json::json!(["-Xmx1g", agent])); + let kotlin = launch(ide_dap::kotlin::ADAPTER, "launch", serde_json::json!({"vmArguments": ["-Xmx1g"]})); + assert_eq!(field(&add_java_agents(kotlin, options), "vmArguments"), serde_json::json!(["-Xmx1g", agent])); + let kotlin = launch(ide_dap::kotlin::ADAPTER, "launch", serde_json::json!({})); + assert_eq!(field(&add_java_agents(kotlin, options), "vmArguments"), serde_json::json!([agent])); + // Attaching (remote debug included), other adapters, and no granted agent: unchanged. + for config in [ + launch("java-debug", "attach", serde_json::json!({"vmArgs": "-Xmx1g"})), + launch("debugpy", "launch", serde_json::json!({"vmArgs": "-Xmx1g"})), + ] { + assert_eq!(add_java_agents(config.clone(), options).extra_json, config.extra_json); + } + let config = launch("java-debug", "launch", serde_json::json!({"vmArgs": "-Xmx1g"})); + assert_eq!(add_java_agents(config.clone(), &[]).extra_json, config.extra_json); + } + #[test] fn debug_server_port_only_for_local_java_debug() { let port = |adapter: &str, request: &str, extra| debug_server_port(&launch(adapter, request, extra)); diff --git a/crates/ide-host/src/ops/run.rs b/crates/ide-host/src/ops/run.rs index ee2363cd8..459aa613d 100644 --- a/crates/ide-host/src/ops/run.rs +++ b/crates/ide-host/src/ops/run.rs @@ -301,6 +301,8 @@ async fn start_inner( if config.command.is_empty() { return Err(IdeError::invalid("run configuration has no command")); } + let on_target = config.extras.target.as_deref().is_some_and(|t| !t.is_empty()); + add_java_agents(&mut config, &on_output, !on_target); // Settings › Run Targets: over SSH, or in a container. if config.kind == "tomcat" && config.extras.target.as_deref().is_some_and(|t| !t.is_empty()) { return Err(IdeError::invalid("Tomcat Local requires the local machine")); @@ -446,6 +448,29 @@ async fn start_inner( host.processes.start(&project.root, &config, &options, sink, Box::new(move |c| on_output(c))) } +/// Plugins' Java agents (`[[contributes.javaAgents]]`, granted `java.agent`) for the JVM of an +/// Application, Spring Boot or JAR Application configuration started on this machine. A JVM on a +/// run target gets none; the console says so, and why an approved agent was left out. +fn add_java_agents(config: &mut RunConfig, on_output: &Emit, local: bool) { + if !ide_run::java_agent::applies(&config.kind) { + return; + } + let agents = ide_run::java_agent::current(); + let say = |text: &str| on_output(OutputChunk::System { text: format!("{text}\n") }); + if !local { + if !agents.options.is_empty() { + say( + "Plugin Java agents were not added: they load only into JVMs started on this machine, not on a run target.", + ); + } + return; + } + for note in &agents.notes { + say(note); + } + ide_run::java_agent::add_to_args(&mut config.args, &agents.options); +} + /// The Ruby test reporter's directory, installed on demand, for runs that take it. fn ruby_reporter_dir(host: &Host, config: &RunConfig) -> Option { if !ide_run::ruby_reporter::applies(config) { diff --git a/crates/ide-host/src/plugins/java_agents.rs b/crates/ide-host/src/plugins/java_agents.rs new file mode 100644 index 000000000..bedb99041 --- /dev/null +++ b/crates/ide-host/src/plugins/java_agents.rs @@ -0,0 +1,250 @@ +//! The `javaAgents` extension point (API 1.10): a Java agent the host loads into the +//! JVM of Application, Spring Boot and JAR Application configurations. +//! +//! ```toml +//! [[contributes.javaAgents]] +//! path = "agent/openidea-spring-agent.jar" # inside the package +//! args = "optional-arguments" # optional +//! ``` +//! +//! One agent per plugin. The declaration derives the optional high-risk `java.agent` +//! capability; granting it records the jar's hash, and a launch adds the agent only +//! while the jar still has it ([`ide_run::java_agent`]). + +use ide_extension::{Capability, Disposable, ExtensionPoint, Manifest, Package, Placement, Prepared, decode}; +use ide_language::ProgramPin; +use ide_run::java_agent::{ContributedAgent, JavaAgentSource}; +use parking_lot::RwLock; +use serde::Deserialize; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +pub const POINT_ID: &str = "javaAgents"; +const MAX_ARGS: usize = 4096; + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct Decl { + path: PathBuf, + #[serde(default)] + args: Option, +} + +#[derive(Clone, Debug)] +struct Agent { + /// The jar, resolved inside the package. + jar: PathBuf, + args: Option, +} + +/// Agents of enabled plugins. +#[derive(Default)] +pub struct JavaAgents { + items: RwLock>, + seq: AtomicU64, +} + +impl JavaAgents { + fn add(self: &Arc, plugin: String, agent: Agent) -> Disposable { + let seq = self.seq.fetch_add(1, Ordering::Relaxed); + self.items.write().push((seq, plugin, agent)); + let weak = Arc::downgrade(self); + Disposable::new(move || { + if let Some(this) = weak.upgrade() { + this.items.write().retain(|(s, _, _)| *s != seq); + } + }) + } +} + +pub struct JavaAgentsPoint { + store: Arc, +} + +impl JavaAgentsPoint { + pub fn new(store: Arc) -> Self { + Self { store } + } +} + +impl ExtensionPoint for JavaAgentsPoint { + fn id(&self) -> &'static str { + POINT_ID + } + + fn placement(&self) -> Placement { + Placement::Workspace + } + + fn prepare(&self, pkg: &Package, decl: toml::Value) -> Result { + pkg.manifest.needs_api("contributes.javaAgents", 10)?; + if pkg.manifest.declarations(POINT_ID).len() > 1 { + return Err("contributes.javaAgents: a plugin contributes at most one Java agent".into()); + } + let d: Decl = decode(POINT_ID, decl)?; + let jar = resolve(&pkg.dir, &d.path)?; + let args = d.args.filter(|a| !a.is_empty()); + if let Some(args) = &args + && (args.len() > MAX_ARGS || args.contains(|c: char| c.is_control())) + { + return Err(format!("contributes.javaAgents: `args` must be one line of at most {MAX_ARGS} bytes")); + } + let label = label(&d.path, args.as_deref()); + let (store, plugin) = (self.store.clone(), pkg.id().to_owned()); + let agent = Agent { jar, args }; + Ok(Prepared::new(label, move || Ok(store.add(plugin, agent))).file(d.path).capability(Capability::JavaAgent)) + } +} + +/// What Settings › Plugins shows: the jar's file name and its arguments, as `-javaagent:` takes them. +fn label(path: &Path, args: Option<&str>) -> String { + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + match args { + Some(args) => format!("{name}={args}"), + None => name, + } +} + +/// The jar a package's declaration names, as an absolute path inside the package: +/// `..`, absolute paths and symlinks that lead out of it are refused. +fn resolve(dir: &Path, rel: &Path) -> Result { + ide_extension::check_relative(rel, "contributes.javaAgents: `path`")?; + let root = dunce::canonicalize(dir).map_err(|e| format!("plugin directory: {e}"))?; + let jar = dunce::canonicalize(dir.join(rel)) + .map_err(|_| format!("contributes.javaAgents: {}: no such file in the plugin", rel.display()))?; + if !jar.starts_with(&root) { + return Err(format!("contributes.javaAgents: {}: points outside the plugin", rel.display())); + } + if !jar.is_file() { + return Err(format!("contributes.javaAgents: {}: not a file", rel.display())); + } + Ok(jar) +} + +/// The jar the package at `dir` declares, for recording its hash when `java.agent` +/// is granted (before the declaration has taken effect, as on install). +pub(super) fn declared_jar(manifest: &Manifest, dir: &Path) -> Option { + let decl = manifest.declarations(POINT_ID).into_iter().next()?; + let d: Decl = decode(POINT_ID, decl).ok()?; + resolve(dir, &d.path).ok() +} + +type Pins = Arc>>; + +/// [`JavaAgentSource`] over the agents and the hashes granted for them. +pub struct PluginJavaAgents { + pub(super) store: Arc, + pub(super) pins: Pins, +} + +impl JavaAgentSource for PluginJavaAgents { + fn agents(&self) -> Vec { + let cap = Capability::JavaAgent.to_string(); + let pins = self.pins.read(); + self.store + .items + .read() + .iter() + .map(|(_, plugin, agent)| ContributedAgent { + plugin: plugin.clone(), + jar: agent.jar.clone(), + args: agent.args.clone(), + approved_hash: pins.get(&(plugin.clone(), cap.clone())).map(|pin| pin.hash.clone()), + }) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const MANIFEST: &str = + "id = \"acme.spring\"\nname = \"Spring\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.10\"\n"; + + fn package(dir: &Path, manifest: &str) -> Package { + std::fs::create_dir_all(dir.join("agent")).unwrap(); + std::fs::write(dir.join("agent/spring agent.jar"), b"PK").unwrap(); + Package::new(Manifest::parse(manifest).unwrap(), dir.to_path_buf()) + } + + fn prepare(pkg: &Package) -> Result { + let point = JavaAgentsPoint::new(Arc::default()); + let decls = pkg.manifest.declarations(POINT_ID); + let mut last = Err("no declaration".into()); + for decl in decls { + last = Ok(point.prepare(pkg, decl)?); + } + last + } + + #[test] + fn parses_the_declaration_and_derives_the_capability() { + let tmp = tempfile::tempdir().unwrap(); + let toml = format!( + "{MANIFEST}[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nargs = \"port=0,trace\"\n" + ); + let pkg = package(tmp.path(), &toml); + let prepared = prepare(&pkg).unwrap(); + assert_eq!(prepared.capabilities, [Capability::JavaAgent]); + assert_eq!(prepared.files, [PathBuf::from("agent/spring agent.jar")]); + assert_eq!(prepared.label, "spring agent.jar=port=0,trace"); + let jar = declared_jar(&pkg.manifest, &pkg.dir).unwrap(); + assert_eq!(jar, dunce::canonicalize(tmp.path().join("agent/spring agent.jar")).unwrap()); + + let store: Arc = Arc::default(); + let point = JavaAgentsPoint::new(store.clone()); + let decl = pkg.manifest.declarations(POINT_ID).remove(0); + let disposable = (point.prepare(&pkg, decl).unwrap().commit)().unwrap(); + let source = PluginJavaAgents { store: store.clone(), pins: Arc::default() }; + let agents = source.agents(); + assert_eq!(agents.len(), 1); + assert_eq!( + (agents[0].plugin.as_str(), agents[0].args.as_deref(), agents[0].approved_hash.as_ref()), + ("acme.spring", Some("port=0,trace"), None) + ); + source.pins.write().insert(("acme.spring".into(), "java.agent".into()), ProgramPin::approve(&jar).unwrap()); + assert!(source.agents()[0].approved_hash.is_some()); + disposable.dispose(); + assert!(source.agents().is_empty(), "disabling the plugin drops its agent"); + } + + #[test] + fn refuses_what_would_fail_at_launch() { + let tmp = tempfile::tempdir().unwrap(); + let outside = tempfile::tempdir().unwrap(); + std::fs::write(outside.path().join("evil.jar"), b"PK").unwrap(); + let refused = |n: usize, manifest: &str| { + let dir = tmp.path().join(n.to_string()); + prepare(&package(&dir, manifest)).map(|_| ()).unwrap_err() + }; + let case = |n: usize, body: &str| refused(n, &format!("{MANIFEST}{body}")); + let agent = |path: &str| format!("[[contributes.javaAgents]]\npath = \"{path}\"\n"); + assert!(case(0, &agent("../evil.jar")).contains("relative path inside the plugin")); + assert!(case(1, &agent("/etc/passwd")).contains("relative path inside the plugin")); + assert!(case(2, &agent("agent/missing.jar")).contains("no such file")); + assert!(case(3, &agent("agent")).contains("not a file")); + let two = format!("{}{}", agent("agent/spring agent.jar"), agent("agent/spring agent.jar")); + assert!(case(4, &two).contains("at most one Java agent")); + assert!( + case(5, "[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nargs = \"a\\nb\"\n") + .contains("one line") + ); + assert!( + case(6, "[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nmain = \"x\"\n") + .contains("unknown field") + ); + let old = format!("{}{}", MANIFEST.replace("^1.10", "^1.9"), agent("agent/spring agent.jar")); + assert!(refused(7, &old).contains("new in plugin API 1.10")); + #[cfg(unix)] + { + let dir = tmp.path().join("8"); + let pkg = package(&dir, &format!("{MANIFEST}{}", agent("agent/link.jar"))); + std::os::unix::fs::symlink(outside.path().join("evil.jar"), dir.join("agent/link.jar")).unwrap(); + assert!(prepare(&pkg).map(|_| ()).unwrap_err().contains("points outside the plugin")); + assert_eq!(declared_jar(&pkg.manifest, &pkg.dir), None); + } + } +} diff --git a/crates/ide-host/src/plugins/mod.rs b/crates/ide-host/src/plugins/mod.rs index 577c27ed1..f8da780ae 100644 --- a/crates/ide-host/src/plugins/mod.rs +++ b/crates/ide-host/src/plugins/mod.rs @@ -37,6 +37,7 @@ mod inlay_hints; mod install; pub mod intellij; mod ipc; +mod java_agents; pub mod language_features; mod market; mod mcp; @@ -378,6 +379,8 @@ pub struct PluginHost { ui: Arc, languages: Arc, run_detectors: Arc, + /// `[[contributes.javaAgents]]` of enabled plugins. + java_agents: Arc, /// `[[contributes.providers]]` of enabled plugins. providers: Arc, navigation: Mutex, @@ -457,7 +460,9 @@ impl PluginHost { let languages = PluginLanguages::new(); let run_detectors: Arc = Arc::default(); let providers: Arc = Arc::default(); - register_builtin_points(®istry, &ui, &languages, &run_detectors, &providers).map_err(IdeError::internal)?; + let java_agents: Arc = Arc::default(); + register_builtin_points(®istry, &ui, &languages, &run_detectors, &java_agents, &providers) + .map_err(IdeError::internal)?; let pins: Arc>> = Arc::default(); let policy_pins = pins.clone(); languages.set_process_policy(Arc::new(move |plugin, cap| { @@ -491,6 +496,7 @@ impl PluginHost { ui, languages, run_detectors, + java_agents, providers, navigation: Mutex::default(), endpoints: Mutex::default(), @@ -991,8 +997,8 @@ impl PluginHost { }; // Consent covers what the install page showed. let request = request_for(&subject, &pkg.manifest, &hash, &set.capabilities); - self.record_consent(&request, consent); let dir = install::active_dir(&root).ok_or_else(|| IdeError::internal("the installed version is missing"))?; + self.record_consent(&request, consent, agent_jar_grant(&pkg.manifest, &dir)); self.load_dir(&dir, PluginSource::Installed, None); if let Some(previous) = previous { let failed = self @@ -1110,7 +1116,7 @@ impl PluginHost { let hash = self.package_hash_of(&plugin); let extra = plugin.meta.lock().declared_extra.clone(); let request = request_for(&plugin.subject(), plugin.manifest(), &hash, &extra); - self.record_consent(&request, consent); + self.record_consent(&request, consent, agent_jar_grant(plugin.manifest(), plugin.dir())); self.stop(&plugin); if !self.state.lock().disabled.contains(id) { self.start(&plugin); @@ -1160,6 +1166,12 @@ impl PluginHost { return Err(IdeError::invalid(format!("plugin {id:?} has not been confirmed yet"))); } ledger.set(&subject, &cap, granted); + if granted + && cap == Capability::JavaAgent + && let Some(jar) = agent_jar_grant(plugin.manifest(), plugin.dir()) + { + ledger.set_binary(&subject, &cap, jar); + } if granted && let Capability::Process(program) = &cap && let Some(bin) = ledger @@ -1696,6 +1708,11 @@ impl PluginHost { }) } + /// Plugins' `javaAgents`, for [`ide_run::java_agent::set_java_agent_source`]. + pub fn java_agents(&self) -> Arc { + Arc::new(java_agents::PluginJavaAgents { store: self.java_agents.clone(), pins: self.pins.clone() }) + } + /// The syntax of plugin languages, for [`ide_language::set_external_syntax`]. pub fn syntax_provider(self: &Arc) -> Arc { Arc::new(PluginSyntax(Arc::downgrade(self))) @@ -2933,7 +2950,7 @@ impl PluginHost { } let declared = plugin.manifest().capabilities.all().cloned().chain(plugin.meta.lock().declared_extra.clone()); - for cap in declared.filter(|c| matches!(c, Capability::Process(_))) { + for cap in declared.filter(|c| matches!(c, Capability::Process(_) | Capability::JavaAgent)) { if let Some(bin) = ledger.pinned_binary(&subject, &cap) { pins.insert( (plugin.id().to_owned(), cap.to_string()), @@ -2994,7 +3011,9 @@ impl PluginHost { self.save_ledger(&ledger); } - fn record_consent(&self, request: &Request<'_>, consent: &Consent) { + /// `agent_jar`: the jar of the plugin's `javaAgents` declaration, recorded when + /// `java.agent` is accepted. + fn record_consent(&self, request: &Request<'_>, consent: &Consent, agent_jar: Option) { let accepted: Vec = request.optional.iter().filter(|c| consent.accepts(c)).cloned().collect(); let choices: BTreeMap<_, _> = { let ledger = self.ledger.lock(); @@ -3016,6 +3035,7 @@ impl PluginHost { .get(&c.to_string()) .map_or_else(|| self.resolve_binary(program), |path| ledger::approve_program(path).ok()) .map(|b| (c.to_string(), b)), + Capability::JavaAgent => agent_jar.clone().map(|jar| (c.to_string(), jar)), _ => None, }) .collect(); @@ -3094,6 +3114,13 @@ impl Drop for PluginHost { } } +/// The jar of a package's `javaAgents` declaration with its hash now, for a `java.agent` grant. +fn agent_jar_grant(manifest: &Manifest, dir: &Path) -> Option { + let path = java_agents::declared_jar(manifest, dir)?; + let hash = ledger::file_hash(&path).map_err(|e| tracing::info!("java.agent: {}: {e}", path.display())).ok()?; + Some(BinaryGrant { path, hash }) +} + fn request_for<'a>(subject: &Subject, m: &'a Manifest, hash: &'a str, declared: &[Capability]) -> Request<'a> { let mut optional = m.capabilities.optional.clone(); // What declarations need (a language server's `process:`) is optional: diff --git a/crates/ide-host/src/plugins/points.rs b/crates/ide-host/src/plugins/points.rs index 654158eab..15ecd5423 100644 --- a/crates/ide-host/src/plugins/points.rs +++ b/crates/ide-host/src/plugins/points.rs @@ -64,6 +64,7 @@ pub fn register_builtin_points( ui: &Arc, languages: &Arc, run_detectors: &Arc, + java_agents: &Arc, providers: &Arc, ) -> Result<(), String> { registry.register(Arc::new(UiPoint::new(COMMANDS, ui.clone(), command)))?; @@ -71,6 +72,7 @@ pub fn register_builtin_points( registry.register(Arc::new(LanguagesPoint::new(languages.clone())))?; registry.register(Arc::new(UiPoint::new(super::icons::POINT_ID, ui.clone(), super::icons::icon_theme)))?; registry.register(Arc::new(super::run_detectors::RunDetectorsPoint::new(run_detectors.clone())))?; + registry.register(Arc::new(super::java_agents::JavaAgentsPoint::new(java_agents.clone())))?; registry.register(Arc::new(super::navigation::IndexersPoint))?; registry.register(Arc::new(super::providers::ProvidersPoint::new(providers.clone())))?; registry.register(Arc::new(UiPoint::new(super::providers::SECRETS_POINT, ui.clone(), super::providers::secret)))?; diff --git a/crates/ide-host/tests/plugins.rs b/crates/ide-host/tests/plugins.rs index 8d1670946..84e6cc6ab 100644 --- a/crates/ide-host/tests/plugins.rs +++ b/crates/ide-host/tests/plugins.rs @@ -2151,6 +2151,60 @@ fn run_detectors_offer_granted_commands_in_marked_projects() { assert!(detection.launch(config).unwrap_err().contains("no longer enabled")); } +/// A plugin's Java agent (`[[contributes.javaAgents]]`, the `java-agent` fixture): an optional +/// high-risk `java.agent` capability; refusing or revoking it keeps the plugin working and the +/// launch gets no agent; granting it pins the jar, which may not change afterwards. +#[test] +fn java_agent_loads_only_while_granted_and_unchanged() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let pkg = tmp.path().join("java-agent"); + copy_dir(&sample("java-agent"), &pkg); + let preview = f.host.preview_install(&pkg).unwrap(); + let cap = preview.capabilities.iter().find(|c| c.id == "java.agent").expect("derived from the declaration"); + assert!(cap.optional && cap.risk == ide_extension::Risk::High && !cap.granted); + assert_eq!(cap.description, "Run code inside the Java applications you start"); + + // Refused on install: the plugin is on, Java launches get no agent. + let info = f.host.install_from_dir(&pkg, &Consent::default()).unwrap(); + assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error); + assert!(info.contributions.iter().any(|c| c.point == "javaAgents" && c.label == "fixture agent.jar=mode=test")); + let source = f.host.java_agents(); + let launch = || { + let agents = ide_run::java_agent::approved(&source.agents()); + let mut args: Vec = ["-Xmx1g", "-cp", "/p/classes", "app.Main"].map(String::from).into(); + ide_run::java_agent::add_to_args(&mut args, &agents.options); + (args, agents.notes) + }; + let plain: Vec = ["-Xmx1g", "-cp", "/p/classes", "app.Main"].map(String::from).into(); + assert_eq!(launch(), (plain.clone(), vec![])); + + // Granted: the installed jar with its arguments, one argument after the VM options. + let info = f.host.set_capability("java-agent", "java.agent", true).unwrap(); + assert!(info.capabilities.iter().any(|c| c.id == "java.agent" && c.granted)); + let jar = dunce::canonicalize(f.installed("java-agent").join("agent/fixture agent.jar")).unwrap(); + let option = format!("-javaagent:{}=mode=test", jar.display()); + let mut with_agent = plain.clone(); + with_agent.insert(3, option.clone()); + assert_eq!(launch(), (with_agent.clone(), vec![])); + + // The jar changed since it was granted: left out, with a reason, until approved again. + std::fs::write(&jar, "swapped").unwrap(); + let (args, notes) = launch(); + assert_eq!(args, plain); + assert!(notes.len() == 1 && notes[0].contains("changed since it was approved"), "{notes:?}"); + f.host.set_capability("java-agent", "java.agent", true).unwrap(); + assert_eq!(launch(), (with_agent.clone(), vec![])); + + // Revoked, then the plugin disabled: no agent either way. + f.host.set_capability("java-agent", "java.agent", false).unwrap(); + assert_eq!(f.status("java-agent"), PluginStatus::Static); + assert_eq!(launch(), (plain.clone(), vec![])); + f.host.set_capability("java-agent", "java.agent", true).unwrap(); + f.host.set_enabled("java-agent", false).unwrap(); + assert_eq!(launch(), (plain, vec![])); +} + /// Compiled components are cached across runs (keyed by module and /// engine), so a cold activation only deserializes. #[test] diff --git a/crates/ide-plugin/tests/fixtures/java-agent/agent/fixture agent.jar b/crates/ide-plugin/tests/fixtures/java-agent/agent/fixture agent.jar new file mode 100644 index 000000000..f2a33ea21 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/java-agent/agent/fixture agent.jar @@ -0,0 +1 @@ +Not a real agent: the tests check the grant and the command line, not the JVM. diff --git a/crates/ide-plugin/tests/fixtures/java-agent/plugin.toml b/crates/ide-plugin/tests/fixtures/java-agent/plugin.toml new file mode 100644 index 000000000..fc3763387 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/java-agent/plugin.toml @@ -0,0 +1,10 @@ +id = "java-agent" +name = "Java agent tests" +version = "0.1.0" +engines.openidea = "^1.10" + +# Contribution only: the host loads the agent into Java run configurations once the user +# grants the `java.agent` capability this declaration derives. +[[contributes.javaAgents]] +path = "agent/fixture agent.jar" +args = "mode=test" diff --git a/crates/ide-run/src/java_agent.rs b/crates/ide-run/src/java_agent.rs new file mode 100644 index 000000000..c737adddc --- /dev/null +++ b/crates/ide-run/src/java_agent.rs @@ -0,0 +1,303 @@ +//! Java agents of plugins (`[[contributes.javaAgents]]`): the JVM of an Application, +//! Spring Boot or JAR Application configuration gets one `-javaagent:[=]` +//! per plugin whose `java.agent` capability the user granted, for Run and Debug alike. +//! +//! The grant records the jar's content hash; an agent whose jar no longer has it is +//! left out (with a console line) until the user approves it again. The desktop +//! installs the [`JavaAgentSource`]; elsewhere (`openidea-server`) there is none, so +//! remote projects never get an agent. + +use ide_language::ProgramPin; +use parking_lot::RwLock; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +/// Run configuration kinds whose JVM gets the agents. +pub const KINDS: &[&str] = &["application", "spring-boot", "jar-application"]; + +pub fn applies(kind: &str) -> bool { + KINDS.contains(&kind) +} + +/// An agent a plugin contributes, as it stands right before a launch. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ContributedAgent { + pub plugin: String, + /// The jar in the plugin's package (absolute). + pub jar: PathBuf, + pub args: Option, + /// The jar's hash recorded when the user granted `java.agent`; `None`: not granted. + pub approved_hash: Option, +} + +/// The agents of the enabled plugins. +pub trait JavaAgentSource: Send + Sync { + fn agents(&self) -> Vec; +} + +static SOURCE: RwLock>> = RwLock::new(None); + +/// Installs (or removes) the source [`current`] reads. +pub fn set_java_agent_source(source: Option>) { + *SOURCE.write() = source; +} + +/// What a launch adds: the `-javaagent:` options, and a console line per agent left out. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Agents { + pub options: Vec, + pub notes: Vec, +} + +/// The agents the installed source allows now (none without a source). +pub fn current() -> Agents { + let source = SOURCE.read().clone(); + source.map(|s| approved(&s.agents())).unwrap_or_default() +} + +/// Granted agents whose jar still has the hash approved for it; an ungranted one is +/// left out silently, a changed or missing jar with a note. +pub fn approved(agents: &[ContributedAgent]) -> Agents { + let mut out = Agents::default(); + for agent in agents { + let Some(hash) = &agent.approved_hash else { continue }; + let pin = ProgramPin { path: agent.jar.clone(), hash: hash.clone() }; + match pin.verify() { + Ok(jar) => out.options.push(option(jar, agent.args.as_deref())), + Err(e) => out.notes.push(format!("The Java agent of plugin {} was not added: {e}", agent.plugin)), + } + } + out +} + +/// `-javaagent:[=]`, one argument: the JVM takes the path as it is, spaces included. +pub fn option(jar: &Path, args: Option<&str>) -> String { + match args.filter(|a| !a.is_empty()) { + Some(args) => format!("-javaagent:{}={args}", jar.display()), + None => format!("-javaagent:{}", jar.display()), + } +} + +/// Adds `options` to `java` arguments after the VM options (before the main class or +/// `-jar`), each as its own argument; one already there is not added again. +pub fn add_to_args(args: &mut Vec, options: &[String]) { + let mut at = crate::java_cmdline::vm_options_end(args); + for option in options { + if args[..at].contains(option) { + continue; + } + args.insert(at, option.clone()); + at += 1; + } +} + +/// The same for a list of VM options (the Kotlin debugger's `vmArguments`). +pub fn add_to_vm_args(vm_args: &mut Vec, options: &[String]) { + for option in options { + if !vm_args.contains(option) { + vm_args.push(option.clone()); + } + } +} + +/// The same for VM options written as one line (java-debug's `vmArgs`): an option with +/// spaces is quoted the way the debugger's launch arguments are. +pub fn add_to_vm_args_text(vm_args: &str, options: &[String]) -> String { + let present = split_text(vm_args); + let mut out = vm_args.trim().to_owned(); + for option in options { + if present.contains(option) { + continue; + } + if !out.is_empty() { + out.push(' '); + } + out.push_str("e(option)); + } + out +} + +/// As the frontend's `joinJavaArgs` writes one argument. +fn quote(arg: &str) -> String { + if !arg.is_empty() && !arg.contains(|c: char| c.is_whitespace() || c == '"') { + return arg.to_owned(); + } + let mut out = String::from('"'); + for c in arg.chars() { + if c == '"' || c == '\\' { + out.push('\\'); + } + out.push(c); + } + out.push('"'); + out +} + +/// Splits a line of arguments written by [`quote`] (or by hand: unquoted words). +fn split_text(text: &str) -> Vec { + let mut out = Vec::new(); + let mut chars = text.chars().peekable(); + loop { + while chars.next_if(|c| c.is_whitespace()).is_some() {} + if chars.peek().is_none() { + return out; + } + let mut arg = String::new(); + let mut quoted = false; + while let Some(c) = chars.next() { + match c { + '"' => quoted = !quoted, + '\\' if quoted && matches!(chars.peek(), Some('"' | '\\')) => arg.extend(chars.next()), + c if c.is_whitespace() && !quoted => break, + c => arg.push(c), + } + } + out.push(arg); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn strings(a: &[&str]) -> Vec { + a.iter().map(|s| (*s).to_owned()).collect() + } + + struct Jar { + _dir: tempfile::TempDir, + path: PathBuf, + hash: String, + } + + /// An agent jar in a directory whose name has a space. + fn jar() -> Jar { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("my plugins").join("agent.jar"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"PK agent").unwrap(); + let hash = ProgramPin::approve(&path).unwrap().hash; + Jar { _dir: dir, path, hash } + } + + fn agent(jar: &Jar, args: Option<&str>, granted: bool) -> ContributedAgent { + ContributedAgent { + plugin: "acme.spring".into(), + jar: jar.path.clone(), + args: args.map(str::to_owned), + approved_hash: granted.then(|| jar.hash.clone()), + } + } + + #[test] + fn only_granted_agents_with_their_approved_jar_are_added() { + let jar = jar(); + assert_eq!(approved(&[agent(&jar, None, false)]), Agents::default(), "no grant: nothing, silently"); + let granted = approved(&[agent(&jar, Some("port=0"), true)]); + assert_eq!(granted.options, [format!("-javaagent:{}=port=0", jar.path.display())]); + assert!(granted.notes.is_empty()); + + std::fs::write(&jar.path, b"PK swapped").unwrap(); + let changed = approved(&[agent(&jar, None, true)]); + assert!(changed.options.is_empty()); + assert_eq!(changed.notes.len(), 1); + assert!(changed.notes[0].contains("acme.spring") && changed.notes[0].contains("changed since it was approved")); + + std::fs::remove_file(&jar.path).unwrap(); + let missing = approved(&[agent(&jar, None, true)]); + assert!(missing.options.is_empty() && missing.notes.len() == 1); + } + + #[test] + fn run_adds_one_argument_after_the_vm_options() { + let jar = jar(); + let options = approved(&[agent(&jar, None, true)]).options; + let option = format!("-javaagent:{}", jar.path.display()); + assert!(option.contains("my plugins"), "the path keeps its space, unquoted: {option}"); + + // Application / Spring Boot: after the user's VM options and the classpath, before the main class. + let mut args = strings(&["-Xmx1g", "-cp", "/p/classes", "app.Main", "--server.port=0"]); + add_to_args(&mut args, &options); + assert_eq!(args, strings(&["-Xmx1g", "-cp", "/p/classes", &option, "app.Main", "--server.port=0"])); + // Already there (the user added it, or a second pass): not added again. + let again = args.clone(); + add_to_args(&mut args, &options); + assert_eq!(args, again); + + // JAR Application, Debug: after the JDWP agent and the user's options, before `-jar`. + let jdwp = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0"; + let mut args = strings(&[jdwp, "-Dx=1", "-jar", "app.jar", "-v"]); + add_to_args(&mut args, &options); + assert_eq!(args, strings(&[jdwp, "-Dx=1", &option, "-jar", "app.jar", "-v"])); + + // A program argument equal to the option is not a VM option. + let mut args = strings(&["app.Main", &option]); + add_to_args(&mut args, &options); + assert_eq!(args, strings(&[&option, "app.Main", &option])); + + let mut untouched = strings(&["-cp", "x", "Main"]); + add_to_args(&mut untouched, &[]); + assert_eq!(untouched, strings(&["-cp", "x", "Main"])); + } + + #[test] + fn a_shortened_command_line_keeps_the_agent_as_its_own_argument() { + let jar = jar(); + let options = approved(&[agent(&jar, None, true)]).options; + let classpath = vec!["/home/u/.m2/repository/org/x/lib/1.0/lib-1.0.jar"; 4000].join(":"); + let mut args = strings(&["-Xmx1g", "-cp", &classpath, "app.Main"]); + add_to_args(&mut args, &options); + let dir = tempfile::tempdir().unwrap(); + let jdk = dir.path().join("jdk"); + std::fs::create_dir_all(jdk.join("bin")).unwrap(); + std::fs::write(jdk.join("release"), "JAVA_VERSION=\"21.0.3\"").unwrap(); + let shortened = crate::java_cmdline::shorten(&jdk.join("bin/java"), &args, dir.path(), false, dir.path()) + .unwrap() + .expect("too long for one argument"); + assert_eq!(shortened.how, crate::java_cmdline::Shortening::ArgFile); + // Only the classpath moves into the argfile; the agent stays one argument, path and all. + assert_eq!(shortened.args.len(), 4); + assert_eq!(shortened.args[2], options[0]); + assert!(!std::fs::read_to_string(&shortened.file).unwrap().contains("javaagent")); + } + + #[test] + fn debug_adds_the_option_to_the_debuggers_vm_options() { + let jar = jar(); + let options = approved(&[agent(&jar, Some("trace sql"), true)]).options; + let option = format!("-javaagent:{}=trace sql", jar.path.display()); + assert_eq!(options, std::slice::from_ref(&option)); + + // java-debug: one line, quoted like the frontend quotes VM options with spaces. + let text = add_to_vm_args_text("-Xmx1g -Dspring.output.ansi.enabled=always", &options); + assert!(text.starts_with("-Xmx1g -Dspring.output.ansi.enabled=always \"-javaagent:"), "{text}"); + assert_eq!(split_text(&text), strings(&["-Xmx1g", "-Dspring.output.ansi.enabled=always", &option])); + assert_eq!(add_to_vm_args_text(&text, &options), text, "not added twice"); + assert_eq!(split_text(&add_to_vm_args_text("", &options)), std::slice::from_ref(&option)); + assert_eq!(add_to_vm_args_text(" -Xmx1g ", &[]), "-Xmx1g"); + + // The Kotlin debugger: a list. + let mut list = strings(&["-Xmx1g"]); + add_to_vm_args(&mut list, &options); + add_to_vm_args(&mut list, &options); + assert_eq!(list, strings(&["-Xmx1g", &option])); + } + + #[test] + fn quoting_round_trips() { + for arg in ["plain", "with space", r#"q"uote"#, r"C:\Program Files\a.jar", ""] { + assert_eq!(split_text("e(arg)), [arg.to_owned()], "{arg}"); + } + assert_eq!(split_text(" a \"b c\" d "), strings(&["a", "b c", "d"])); + } + + #[test] + fn kinds() { + for kind in ["application", "spring-boot", "jar-application"] { + assert!(applies(kind), "{kind}"); + } + for kind in ["junit", "maven", "gradle", "tomcat", "java-file", "remote-jvm-debug"] { + assert!(!applies(kind), "{kind}"); + } + } +} diff --git a/crates/ide-run/src/java_cmdline.rs b/crates/ide-run/src/java_cmdline.rs index 4680e6e69..e70d3fbf5 100644 --- a/crates/ide-run/src/java_cmdline.rs +++ b/crates/ide-run/src/java_cmdline.rs @@ -140,6 +140,20 @@ fn path_options(args: &[String]) -> (Option, Option) { (cp, mp) } +/// Where the VM options of `java` arguments end: the index of the main class, `-jar` or +/// `-m` / `--module` (the arguments' length when there is none). +pub fn vm_options_end(args: &[String]) -> usize { + let mut i = 0; + while i < args.len() { + let a = args[i].as_str(); + if matches!(a, "-jar" | "-m" | "--module") || a.starts_with("--module=") || !a.starts_with(['-', '@']) { + return i; + } + i += if WITH_VALUE.contains(&a) { 2 } else { 1 }; + } + args.len() +} + /// A shortened command line and the temporary file it refers to (delete it once the process exits). #[derive(Debug)] pub struct Shortened { @@ -378,6 +392,15 @@ mod tests { assert_eq!(path_options(&strings(&["Main", "-cp", "x"])), (None, None)); } + #[test] + fn vm_options_end_before_the_main_class_or_jar() { + assert_eq!(vm_options_end(&strings(&["-Xmx1g", "-cp", "x.jar", "Main", "-v"])), 3); + assert_eq!(vm_options_end(&strings(&["--add-opens", "a/b=ALL", "-jar", "app.jar"])), 2); + assert_eq!(vm_options_end(&strings(&["@opts", "-m", "mod/app.Main"])), 1); + assert_eq!(vm_options_end(&strings(&["--module=mod/app.Main"])), 0); + assert_eq!(vm_options_end(&strings(&["-Xmx1g"])), 1); + } + #[test] fn urls_are_encoded_and_directories_end_with_a_slash() { assert_eq!(file_url("/p/a b/x.jar", false), "file:/p/a%20b/x.jar"); diff --git a/crates/ide-run/src/lib.rs b/crates/ide-run/src/lib.rs index 6b3845db4..c0fb2346d 100644 --- a/crates/ide-run/src/lib.rs +++ b/crates/ide-run/src/lib.rs @@ -8,6 +8,7 @@ mod external; pub mod go; pub mod gradle_jvm; pub mod import; +pub mod java_agent; pub mod java_cmdline; pub mod junit; mod process; diff --git a/docs/en/plugins/capabilities.mdx b/docs/en/plugins/capabilities.mdx index f43cc4fa3..17a564a47 100644 --- a/docs/en/plugins/capabilities.mdx +++ b/docs/en/plugins/capabilities.mdx @@ -52,6 +52,7 @@ Later: | `fs.write:` | High | `host::fs` writes outside the projects, under that path; does not imply reading | 1.3 | | `process:` | High | Run that program: `run_process`, `run_command`, `start`, terminals, language servers, debug adapters, runs | 1.0 | | `lsp:` | High | Send that running language server its own requests (`language_server_request`); trusted projects only | 1.9 | +| `java.agent` | High | Run the plugin's Java agent inside the Java applications you start (see [Java agents](#java-agents)) | 1.10 | | `ipc:` | High | Local Unix sockets or Windows named pipes on the project machine | 1.4 | | `ide.commands` | High | Run any IDE action or another plugin's command as if the user chose it, including running programs, committing and pushing. The plugin's own commands are exempt. | 1.4 | @@ -66,6 +67,14 @@ The **API** column is the oldest plugin API the manifest may admit when it decla - `process:` grants are also derived from what a contribution starts: a language's `language-servers` and `debugger`, and a run detector's `command`. These are optional: refusing one keeps the rest of the plugin working. - Processes run in the project root of a trusted project. Plugins can only add environment variables, never replace or remove them. +## Java agents + +`java.agent` lets a plugin's Java agent run inside the Java applications the user starts. It comes from a `[[contributes.javaAgents]]` declaration (one per plugin, a jar inside the package), is never listed under `[capabilities]`, and is optional: refusing or revoking it keeps the rest of the plugin working, and the next launch has no agent. + +- On grant, the IDE records the jar's content hash and checks it again before every launch. A changed jar is left out, with a line in the run console, until the user approves `java.agent` again. **Settings › Plugins** shows the agent's file name and arguments next to the permission. +- The IDE adds one `-javaagent:[=]` argument after the VM options of **Application**, **Spring Boot** and **JAR Application** configurations, for Run and Debug alike, and only for projects on this machine. +- Tests, Maven and Gradle goals, application servers, remote JVM debug, run targets and remote projects get no agent in this version. See [README: Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110). + ## Files outside the project - `fs.read:` grants reading a directory (at any depth) or one file outside the open projects. The path is resolved to its real location before it is compared, so a symlink out of the granted directory is refused, and `/opt/see` does not cover `/opt/seeyon`. Granting a whole file system (`/`, `C:\`) is refused. `~/` stands for the home directory. diff --git a/docs/en/plugins/manifest.mdx b/docs/en/plugins/manifest.mdx index a84a8cab9..f2be564df 100644 --- a/docs/en/plugins/manifest.mdx +++ b/docs/en/plugins/manifest.mdx @@ -122,6 +122,7 @@ Each contribution point is a table (`[contributes.settings]`) or an array of tab | `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?` | 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) | no | [README: Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) | | `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) | diff --git a/docs/zh/plugins/capabilities.mdx b/docs/zh/plugins/capabilities.mdx index 5146f743e..607bdd9a6 100644 --- a/docs/zh/plugins/capabilities.mdx +++ b/docs/zh/plugins/capabilities.mdx @@ -52,6 +52,7 @@ optional = ["net:api.example.com", "secrets"] | `fs.write:` | 高 | 通过 `host::fs` 写入项目外、该路径下的文件;不包含读权限 | 1.3 | | `process:` | 高 | 运行该程序:`run_process`、`run_command`、`start`、终端、语言服务器、调试适配器、运行配置 | 1.0 | | `lsp:` | 高 | 向正在运行的该语言服务器发送它自己的请求(`language_server_request`);仅限受信任的项目 | 1.9 | +| `java.agent` | 高 | 在你启动的 Java 应用中运行插件的 Java 代理(见下文“Java 代理”) | 1.10 | | `ipc:` | 高 | 项目所在机器上的本地 Unix 套接字或 Windows 命名管道 | 1.4 | | `ide.commands` | 高 | 像用户亲自选择一样运行任意 IDE 操作或其他插件的命令,包括运行程序、提交和推送。插件自己的命令不受此限制。 | 1.4 | @@ -66,6 +67,14 @@ optional = ["net:api.example.com", "secrets"] - `process:` 授权也会从贡献中推导出来:语言的 `language-servers` 和 `debugger`,以及运行检测器的 `command`。这些都是 optional 的,拒绝其中一个不影响插件的其他功能。 - 进程在受信任项目的项目根目录中运行。插件只能新增环境变量,不能替换或删除已有的变量。 +## Java 代理 + +`java.agent` 让插件的 Java 代理在用户启动的 Java 应用中运行。它来自 `[[contributes.javaAgents]]` 声明(每个插件一个,是插件包内的 jar),不在 `[capabilities]` 中声明,并且是 optional 的:拒绝或撤销它不影响插件的其他功能,下一次启动就不带代理。 + +- 授权时,IDE 记录 jar 的内容哈希,并在每次启动前重新检查。jar 变化后不会被加载,运行控制台中会有一行说明,直到用户重新批准 `java.agent`。**设置 › 插件** 在该权限旁显示代理的文件名和参数。 +- IDE 在 **Application**、**Spring Boot** 和 **JAR Application** 配置的 VM 选项之后添加一个 `-javaagent:<绝对路径>[=<参数>]` 参数,运行和调试都一样,且只对本机上的项目生效。 +- 这一版本中,测试、Maven 和 Gradle 目标、应用服务器、远程 JVM 调试、运行目标和远程项目都不加载代理。参见 [README:Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110)。 + ## 项目以外的文件 - `fs.read:` 授权读取打开的项目之外的一个目录(任意深度)或一个文件。路径先解析到真实位置再比较,所以指向授权目录之外的符号链接会被拒绝,`/opt/see` 也不覆盖 `/opt/seeyon`。授权整个文件系统(`/`、`C:\`)会被拒绝。`~/` 表示用户主目录。 diff --git a/docs/zh/plugins/manifest.mdx b/docs/zh/plugins/manifest.mdx index 21e6e3e97..6fa442c96 100644 --- a/docs/zh/plugins/manifest.mdx +++ b/docs/zh/plugins/manifest.mdx @@ -122,6 +122,7 @@ optional = ["net:api.openai.com", "secrets"] | `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?` | 否 | [运行目标](/zh/plugins/guides/run-targets) | | `runConfigurations` | `files`(API 1.4) | 是 | [运行目标](/zh/plugins/guides/run-targets) | +| `javaAgents` | `path`、`args?`(API 1.10) | 否 | [README:Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) | | `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) | diff --git a/plugins/README.md b/plugins/README.md index 27a8c8e40..ae163274c 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -144,6 +144,7 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK. | `languages` | `path` (`languages/.toml` format, see §6) | no | | `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?` (API 1.4; §6.2) | no | | `runConfigurations` | `files`: marker files for the optional `run-configurations` export (API 1.4) | yes | +| `javaAgents` | `path` (a jar in the package), `args?` — a Java agent for Java run configurations, behind `java.agent` (API 1.10; _Java agents_) | no | | `mcpTools` | `name`, `description`, `inputSchema` (package JSON Schema path), `readOnly`, `destructive` (API 1.4; see _Plugin MCP tools_) | yes | | `snippets` | `language`, `path` (named JSON snippets; API 1.4) | no | | `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes | @@ -359,6 +360,7 @@ machine. Users can revoke optional capabilities in Settings › Plugins. | `events.input` | medium | `action-performed` and `input-mode-changed` events | | `process:` | high | `Project::run_process`, language servers, debug adapters, runs | | `lsp:` | high | API 1.9: `Project::language_server_request` / `language_server_notify` to that running language server (its name in the language definition); trusted projects only | +| `java.agent` | high | API 1.10: the `[[contributes.javaAgents]]` jar runs inside the Java applications you start; derived from that declaration, never listed | | `net:` | medium | `host::fetch` over HTTPS (also loopback HTTP); `*.example.com` matches subdomains | | `net:ask` | medium | Ask the user at the first request to an HTTPS (or loopback) host that is not declared; one answer per host, revocable; API 1.5 | | `net.http:` | medium | Unencrypted HTTP to that host; API 1.4, same wildcard rules as `net:` | @@ -368,7 +370,8 @@ machine. Users can revoke optional capabilities in Settings › Plugins. `process:` capabilities are also derived from what the contributions start: a language's `language-servers` and `debugger` commands and a run detector's -`command`. Those are optional — refusing one keeps the rest of the plugin +`command`. A `[[contributes.javaAgents]]` declaration derives `java.agent` the +same way (see _Java agents_). Those are optional — refusing one keeps the rest of the plugin working. On grant the program is resolved to an absolute path and its content hash is recorded; it is checked again right before every start, and a replaced file is refused until the user approves it again. In a remote project the @@ -432,6 +435,9 @@ matching SDK. Released 1.9 plugins keep working. New in 1.10: side alone, as for the IDE's own added and deleted files, instead of next to an empty text. Both `None` is `Invalid`. Web views send `null` for that side in `{ op: "open-diff", ... }`. +- **`[[contributes.javaAgents]]`** loads a Java agent from the package into the + JVM of Application, Spring Boot and JAR Application configurations, behind the + high-risk `java.agent` capability. See _Java agents_. ### API 1.9 @@ -2084,6 +2090,45 @@ The host accepts replies only from that plugin and window. Content is limited to 1 Mi UTF-16 units and each side of a diff to 8 Mi, with at most 16 actions and one Save action. +### Java agents (API 1.10) + +A plugin that observes or instruments the user's application (request +mappings, traces, SQL) can have the IDE load a Java agent into the JVMs it +starts. Declare the agent; no code is needed: + +```toml +engines.openidea = "^1.10" + +[[contributes.javaAgents]] +path = "agent/openidea-spring-agent.jar" # inside the package, like every manifest path +args = "optional-arguments" # optional +``` + +- One agent per plugin. A second declaration, a `path` that leaves the package + (`..`, an absolute path, a symlink pointing outside) or a missing file is + refused when the manifest is read, so a bad path fails at install, not at + launch. `args` is one line. +- The declaration derives the optional high-risk capability `java.agent`, "Run + code inside the Java applications you start". It is not listed under + `[capabilities]` (a manifest that lists it is refused). On grant the IDE + records the jar's content hash and checks it again before every launch; a + changed jar is left out, with a line in the console, until the user approves + `java.agent` again in Settings › Plugins, which shows the agent's file name + and arguments next to the permission. Refusing or revoking it keeps the rest + of the plugin working, and the next launch has no agent. +- The IDE adds one `-javaagent:[=]` argument to the Java + command line of **Application**, **Spring Boot** and **JAR Application** + configurations, for Run and Debug alike, after the configuration's VM + options. Arguments are separate argv items (no shell), so a path with spaces + needs no quoting; a shortened command line moves only the classpath into its + argument file. The same `-javaagent:` already among the VM options is not + added again. +- Not in this version: tests (JUnit), Maven and Gradle goals (an Application + set to _Build and run using: Gradle_ runs as a Gradle task), application + servers (Tomcat), remote JVM debug, configurations on a run target, and + remote projects. In a remote project the JVM runs on the server, so the + agent is skipped and the run console says so in one line. + ### Plugin-backed content editor tabs (API 1.3) A web view can open an editor tab on content the plugin supplies, with diff --git a/src-tauri/src/commands/plugin.rs b/src-tauri/src/commands/plugin.rs index 281461d32..447cdb94f 100644 --- a/src-tauri/src/commands/plugin.rs +++ b/src-tauri/src/commands/plugin.rs @@ -110,6 +110,8 @@ pub fn create_host(app: &AppHandle, data_dir: &Path, project_host: &Arc = { iconThemes: "File Icon Themes", languages: "Languages", providers: "Editor Providers", + javaAgents: "Java Agents", locales: "Translations", }; @@ -581,7 +582,11 @@ function CapabilityList({ plugin, busy }: { plugin: PluginInfo; busy: boolean }) key={c.id} cap={c} program={ - c.id.startsWith("process:") && + c.id.startsWith("process:") ? ( + + ) : ( + c.id === "java.agent" && + ) } > c.point === "javaAgents"); + if (!agent) return null; + return ( +
+ + {agent.label} + +
+ ); +} + /** A host the user allowed through `net:ask` ("always"); removing it asks again next time. */ function NetHostRow({ plugin, host, disabled }: { plugin: PluginInfo; host: string; disabled: boolean }) { return ( diff --git a/src/features/plugins/__tests__/plugins.test.tsx b/src/features/plugins/__tests__/plugins.test.tsx index 5eb1644fb..6f8f2eab0 100644 --- a/src/features/plugins/__tests__/plugins.test.tsx +++ b/src/features/plugins/__tests__/plugins.test.tsx @@ -1550,6 +1550,33 @@ describe("marketplace", () => { }, ); + it("shows the Java agent next to the java.agent permission", async () => { + setPluginsBackend( + createMemoryPluginsBackend([ + plugin({ + id: "spring", + name: "Spring", + hasCode: false, + status: "static", + capabilities: [ + { + id: "java.agent", + risk: "high", + description: "Run code inside the Java applications you start", + optional: true, + granted: true, + }, + ], + contributions: [{ point: "javaAgents", label: "spring-agent.jar=port=0" }], + }), + ]), + ); + render(); + const permissions = await screen.findByRole("list", { name: "Permissions" }); + expect(within(permissions).getByText("Run code inside the Java applications you start")).toBeInTheDocument(); + expect(within(permissions).getByLabelText("Java agent")).toHaveTextContent("spring-agent.jar=port=0"); + }); + it("offers to roll back an update", async () => { const base = createMemoryPluginsBackend([ plugin({ id: "p", name: "P", version: "2.0.0", previousVersion: "1.0.0" }), diff --git a/src/features/run/store.ts b/src/features/run/store.ts index 562fc4375..b8426f261 100644 --- a/src/features/run/store.ts +++ b/src/features/run/store.ts @@ -25,6 +25,7 @@ import { JavaBuildFailedError, parseJavaArgs, prepareJavaLaunch, + remoteJavaAgentNote, } from "@/platform/javaLaunch"; import { downloadJdkActions } from "@/platform/jdk"; import { buildToolRecovery } from "@/platform/buildToolRecovery"; @@ -1015,6 +1016,8 @@ async function startRunIn( started = rt.dotnetReports.launch(started); } if (runtimes.get(sessionId)?.generation !== generation) return getSession(sessionId) ?? null; + const agentNote = await remoteJavaAgentNote(started); + if (agentNote) enqueue(sessionId, { kind: "system", text: agentNote }); const processStarted = performance.now(); const request = { id: nextRequestId(), controller: new AbortController() }; rt.resolveRequest = request; diff --git a/src/platform/javaLaunch.test.ts b/src/platform/javaLaunch.test.ts new file mode 100644 index 000000000..6fbed8f61 --- /dev/null +++ b/src/platform/javaLaunch.test.ts @@ -0,0 +1,51 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import type { CapabilityInfo, PluginInfo } from "@/platform/ipc"; + +const state = vi.hoisted(() => ({ remote: false, plugins: [] as unknown[] })); +vi.mock("@/platform/remote", () => ({ isRemoteWindow: () => state.remote })); +vi.mock("@/platform/ipc", async (original) => { + const real = await original(); + return { + ...real, + commands: { + ...real.commands, + pluginList: vi.fn(() => Promise.resolve({ status: "ok", data: { plugins: state.plugins } })), + }, + }; +}); + +const { remoteJavaAgentNote } = await import("./javaLaunch"); + +function plugin(name: string, enabled: boolean, granted: boolean | null): PluginInfo { + const capabilities: CapabilityInfo[] = + granted === null ? [] : [{ id: "java.agent", risk: "high", description: "", optional: true, granted }]; + return { name, enabled, capabilities } as unknown as PluginInfo; +} + +beforeEach(() => { + state.remote = true; + state.plugins = [ + plugin("Spring Agent", true, true), + plugin("Refused", true, false), + plugin("Off", false, true), + plugin("Theme", true, null), + ]; +}); + +it("says once that a remote Java launch got no agent, naming the plugins with a granted one", async () => { + for (const kind of ["application", "spring-boot", "jar-application"]) { + expect(await remoteJavaAgentNote({ kind })).toBe( + "Java agents of Spring Agent were not added: they load only in local projects.\n", + ); + } +}); + +it("says nothing for local projects, other kinds, or without a granted agent", async () => { + expect(await remoteJavaAgentNote({ kind: "maven" })).toBeNull(); + expect(await remoteJavaAgentNote({ kind: "junit" })).toBeNull(); + state.remote = false; + expect(await remoteJavaAgentNote({ kind: "application" })).toBeNull(); + state.remote = true; + state.plugins = [plugin("Refused", true, false)]; + expect(await remoteJavaAgentNote({ kind: "application" })).toBeNull(); +}); diff --git a/src/platform/javaLaunch.ts b/src/platform/javaLaunch.ts index 73c32c34d..368b51052 100644 --- a/src/platform/javaLaunch.ts +++ b/src/platform/javaLaunch.ts @@ -15,6 +15,7 @@ import { } from "@/platform/ipc"; import { tx } from "@/platform/i18n"; import { useBuildPresentation } from "@/platform/projectPresentation"; +import { isRemoteWindow } from "@/platform/remote"; export const CLASSPATH = "${classpath}"; export const TEST_CLASSPATH = "${testClasspath}"; @@ -25,6 +26,25 @@ export function isJvmApplication(config: Pick): boolean { return JVM_APPLICATION_KINDS.includes(config.kind); } +/** Run configuration kinds whose JVM gets the plugins' Java agents (`[[contributes.javaAgents]]`). */ +const JAVA_AGENT_KINDS = ["application", "spring-boot", "jar-application"]; + +/** + * The console line of a Java launch in a remote project, when plugins with a granted + * `java.agent` would have added their agent: the JVM runs on the server, and agents load + * only into JVMs on this machine. `null` otherwise. Plugins are the desktop's own. + */ +export async function remoteJavaAgentNote(config: Pick): Promise { + if (!JAVA_AGENT_KINDS.includes(config.kind) || !isRemoteWindow()) return null; + const snapshot = await call(commands.pluginList()).catch(() => null); + const names = (snapshot?.plugins ?? []) + .filter((p) => p.enabled && p.capabilities.some((c) => c.id === "java.agent" && c.granted)) + .map((p) => p.name); + if (!names.length) return null; + const list = names.join(", "); + return tx`Java agents of ${list} were not added: they load only in local projects.` + "\n"; +} + /** `java` options whose value is the next argument. */ const WITH_VALUE = new Set([ "-cp", diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 543e3631e..ed835d474 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2317,5 +2317,8 @@ "Reformatted {formatted} of {length} files": "Reformatted {formatted} of {length} files", "Skipped {count} files without a formatter: {names}": "Skipped {count} files without a formatter: {names}", "Open Settings in a separate window": "Open Settings in a separate window", - "When off, Settings opens as a dialog in the project window, which is faster": "When off, Settings opens as a dialog in the project window, which is faster" + "When off, Settings opens as a dialog in the project window, which is faster": "When off, Settings opens as a dialog in the project window, which is faster", + "Run code inside the Java applications you start": "Run code inside the Java applications you start", + "Java agents of {list} were not added: they load only in local projects.": "Java agents of {list} were not added: they load only in local projects.", + "Java agent": "Java agent" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 0541b6627..8cdd6149d 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -8701,5 +8701,8 @@ "Reformatted {formatted} of {length} files": "已重新格式化 {formatted}/{length} 个文件", "Skipped {count} files without a formatter: {names}": "已跳过 {count} 个没有格式化程序的文件:{names}", "Open Settings in a separate window": "在单独的窗口中打开设置", - "When off, Settings opens as a dialog in the project window, which is faster": "关闭时,设置以对话框形式在项目窗口中打开,速度更快" + "When off, Settings opens as a dialog in the project window, which is faster": "关闭时,设置以对话框形式在项目窗口中打开,速度更快", + "Run code inside the Java applications you start": "在你启动的 Java 应用中运行代码", + "Java agents of {list} were not added: they load only in local projects.": "未添加 {list} 的 Java 代理:Java 代理只加载到本地项目中。", + "Java agent": "Java 代理" }