fix(plugins): ask before loading a changed Java agent (#4003)

When a plugin's Java agent jar changed, the host already refused to load it until java.agent was granted again, but Settings still showed the permission as granted, so the agent silently disappeared from Run/Debug. PluginInfo now carries the agent's file name, arguments and whether its jar still matches the approved hash; Settings › Plugins warns about a changed jar and offers Approve new jar, which grants the permission again.

Co-authored-by: NeverKnowsTomorrow <36879844+NeverKnowsTomorrow@users.noreply.github.com>
This commit is contained in:
Q
2026-11-17 21:20:40 +08:00
committed by GitHub
co-authored by NeverKnowsTomorrow
parent 39f709def5
commit a83bad107c
11 changed files with 137 additions and 11 deletions
+7 -3
View File
@@ -33,10 +33,10 @@ struct Decl {
}
#[derive(Clone, Debug)]
struct Agent {
pub(super) struct Agent {
/// The jar, resolved inside the package.
jar: PathBuf,
args: Option<String>,
pub(super) jar: PathBuf,
pub(super) args: Option<String>,
}
/// Agents of enabled plugins.
@@ -47,6 +47,10 @@ pub struct JavaAgents {
}
impl JavaAgents {
pub(super) fn for_plugin(&self, plugin: &str) -> Option<Agent> {
self.items.read().iter().find(|(_, id, _)| id == plugin).map(|(_, _, agent)| agent.clone())
}
fn add(self: &Arc<Self>, plugin: String, agent: Agent) -> Disposable {
let seq = self.seq.fetch_add(1, Ordering::Relaxed);
self.items.write().push((seq, plugin, agent));
+20
View File
@@ -3087,6 +3087,26 @@ impl PluginHost {
homepage: m.homepage.clone(),
change_notes: m.change_notes.clone(),
icon: p.icon.clone(),
java_agent: self.java_agents.for_plugin(&m.id).map(|agent| {
let pin = self
.ledger
.lock()
.get(&p.subject())
.filter(|grant| grant.has(&Capability::JavaAgent))
.and_then(|grant| grant.binaries.get(&Capability::JavaAgent.to_string()).cloned());
let approved = pin.as_ref().is_some_and(|pin| {
pin.path == agent.jar && ledger::file_hash(&pin.path).is_ok_and(|hash| hash == pin.hash)
});
PluginJavaAgent {
file_name: agent
.jar
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| agent.jar.display().to_string()),
args: agent.args,
approved,
}
}),
source: p.source,
path: p.dir().to_path_buf().into(),
enabled: !self.state.lock().disabled.contains(&m.id),
+14
View File
@@ -55,6 +55,18 @@ impl PluginStatus {
}
}
/// The Java agent a plugin contributes, for Settings › Plugins.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PluginJavaAgent {
/// The jar's file name.
pub file_name: String,
/// The optional argument passed after `=`.
pub args: Option<String>,
/// The jar still has the hash recorded when `java.agent` was granted.
pub approved: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PluginInfo {
@@ -66,6 +78,8 @@ pub struct PluginInfo {
pub homepage: Option<String>,
pub change_notes: Option<String>,
pub icon: Option<PluginIcon>,
/// The Java agent this plugin declares, and whether it is still approved.
pub java_agent: Option<PluginJavaAgent>,
pub source: PluginSource,
/// Package directory.
pub path: ide_core::IpcPath,
+9
View File
@@ -2204,6 +2204,10 @@ fn java_agent_loads_only_while_granted_and_unchanged() {
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 agent = info.java_agent.clone().expect("agent metadata");
assert_eq!(agent.file_name, "fixture agent.jar");
assert_eq!(agent.args.as_deref(), Some("mode=test"));
assert!(!agent.approved);
let source = f.host.java_agents();
let launch = || {
let agents = ide_run::java_agent::approved(&source.agents());
@@ -2217,6 +2221,7 @@ fn java_agent_loads_only_while_granted_and_unchanged() {
// 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));
assert!(info.java_agent.as_ref().is_some_and(|agent| agent.approved));
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();
@@ -2228,7 +2233,11 @@ fn java_agent_loads_only_while_granted_and_unchanged() {
let (args, notes) = launch();
assert_eq!(args, plain);
assert!(notes.len() == 1 && notes[0].contains("changed since it was approved"), "{notes:?}");
let changed = f.host.info_of("java-agent").unwrap();
assert!(!changed.java_agent.as_ref().unwrap().approved, "Settings must show the changed jar");
f.host.set_capability("java-agent", "java.agent", false).unwrap();
f.host.set_capability("java-agent", "java.agent", true).unwrap();
assert!(f.host.info_of("java-agent").unwrap().java_agent.as_ref().is_some_and(|a| a.approved));
assert_eq!(launch(), (with_agent.clone(), vec![]));
// Revoked, then the plugin disabled: no agent either way.
+4 -2
View File
@@ -2217,8 +2217,10 @@ args = "optional-arguments" # optional
`[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
`java.agent` again in Settings › Plugins. Settings shows the agent's file name
and arguments next to the permission, and when the jar no longer matches the
approved hash it shows the reason and an **Approve new jar** action. Refusing
or revoking it keeps the rest
of the plugin working, and the next launch has no agent.
- The IDE adds one `-javaagent:<absolute path>[=<args>]` argument to the Java
command line of **Application**, **Spring Boot** and **JAR Application**
+12
View File
@@ -8880,6 +8880,8 @@ export type PluginInfo = {
homepage: string | null,
changeNotes: string | null,
icon: PluginIcon | null,
/** The Java agent this plugin declares, and whether it is still approved. */
javaAgent: PluginJavaAgent | null,
source: PluginSource,
/** Package directory. */
path: IpcPath,
@@ -8914,6 +8916,16 @@ export type PluginInfo = {
extensionPoints: ExtensionPointInfo[],
};
/** The Java agent a plugin contributes, for Settings › Plugins. */
export type PluginJavaAgent = {
/** The jar's file name. */
fileName: string,
/** The optional argument passed after `=`. */
args: string | null,
/** The jar still has the hash recorded when `java.agent` was granted. */
approved: boolean,
};
/**
* Commands of this module the remote server answers.
* Versioned plugin visuals, refreshed after the editor synchronizes its buffer.
+21 -4
View File
@@ -581,7 +581,7 @@ function CapabilityList({ plugin, busy }: { plugin: PluginInfo; busy: boolean })
c.id.startsWith("process:") ? (
<ProgramPermission plugin={plugin} cap={c} disabled={busy || !confirmed} />
) : (
c.id === "java.agent" && <JavaAgentDetail plugin={plugin} />
c.id === "java.agent" && <JavaAgentDetail plugin={plugin} cap={c} disabled={busy || !confirmed} />
)
}
>
@@ -601,14 +601,31 @@ function CapabilityList({ plugin, busy }: { plugin: PluginInfo; busy: boolean })
}
/** The agent a `java.agent` grant loads: its jar's file name and arguments, as `-javaagent:` takes them. */
function JavaAgentDetail({ plugin }: { plugin: PluginInfo }) {
const agent = plugin.contributions.find((c) => c.point === "javaAgents");
function JavaAgentDetail({ plugin, cap, disabled }: { plugin: PluginInfo; cap: CapabilityInfo; disabled: boolean }) {
const agent = plugin.javaAgent;
if (!agent) return null;
const approve = async () => {
// Revoking and granting again recomputes the jar's hash in the host.
if (await setPluginCapability(plugin.id, cap.id, false)) {
await setPluginCapability(plugin.id, cap.id, true);
}
};
return (
<div className={styles.programPermission}>
<span className={clsx(styles.mono, styles.programPath)} aria-label={tx("Java agent")}>
{agent.label}
{agent.fileName}
{agent.args ? `=${agent.args}` : ""}
</span>
{cap.granted && !agent.approved && (
<div className={styles.error} role="alert">
<p>
<T>The agent jar changed since you approved it. Approve the new jar before the next launch.</T>
</p>
<Button size="small" variant="primary" disabled={disabled} onClick={() => void approve()}>
<T>Approve new jar</T>
</Button>
</div>
)}
</div>
);
}
@@ -69,6 +69,7 @@ function plugin(partial: Partial<PluginInfo> & Pick<PluginInfo, "id">): PluginIn
homepage: null,
changeNotes: null,
icon: null,
javaAgent: null,
source: "installed",
path: `/plugins/${partial.id}`,
enabled: true,
@@ -1604,6 +1605,7 @@ describe("marketplace", () => {
},
],
contributions: [{ point: "javaAgents", label: "spring-agent.jar=port=0" }],
javaAgent: { fileName: "spring-agent.jar", args: "port=0", approved: true },
}),
]),
);
@@ -1613,6 +1615,47 @@ describe("marketplace", () => {
expect(within(permissions).getByLabelText("Java agent")).toHaveTextContent("spring-agent.jar=port=0");
});
it("warns when a granted Java agent jar changed and can approve it again", async () => {
const user = userEvent.setup();
const base = createMemoryPluginsBackend([
plugin({
id: "spring",
name: "Spring",
hasCode: false,
status: "static",
javaAgent: { fileName: "spring-agent.jar", args: null, approved: false },
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" }],
}),
]);
const calls: [string, string, boolean][] = [];
setPluginsBackend({
...base,
setCapability: async (id, capability, granted) => {
calls.push([id, capability, granted]);
return base.setCapability(id, capability, granted);
},
});
render(<PluginsPage initialTab="installed" />);
const permissions = await screen.findByRole("list", { name: "Permissions" });
expect(within(permissions).getByRole("alert")).toHaveTextContent("The agent jar changed since you approved it");
await user.click(within(permissions).getByRole("button", { name: "Approve new jar" }));
await waitFor(() =>
expect(calls).toEqual([
["spring", "java.agent", false],
["spring", "java.agent", true],
]),
);
});
it("offers to roll back an update", async () => {
const base = createMemoryPluginsBackend([
plugin({ id: "p", name: "P", version: "2.0.0", previousVersion: "1.0.0" }),
+1
View File
@@ -453,6 +453,7 @@ function samplePlugins(): PluginInfo[] {
homepage: null,
changeNotes: null,
icon: null,
javaAgent: null,
source: "installed" as const,
enabled: true,
error: null,
+3 -1
View File
@@ -2370,5 +2370,7 @@
"Install IDE Copy": "Install IDE Copy",
"Not installed:": "Not installed:",
"Additional servers": "Additional servers",
"Run alongside the one above": "Run alongside the one above"
"Run alongside the one above": "Run alongside the one above",
"The agent jar changed since you approved it. Approve the new jar before the next launch.": "The agent jar changed since you approved it. Approve the new jar before the next launch.",
"Approve new jar": "Approve new jar"
}
+3 -1
View File
@@ -8748,5 +8748,7 @@
"Install IDE Copy": "安装到 IDE",
"Not installed:": "未安装:",
"Additional servers": "附加服务器",
"Run alongside the one above": "与上面选中的服务器同时运行"
"Run alongside the one above": "与上面选中的服务器同时运行",
"The agent jar changed since you approved it. Approve the new jar before the next launch.": "Agent jar 在授权后发生了变化。请先批准新的 jar,再启动应用。",
"Approve new jar": "批准新的 jar"
}