Skip to content

Commit 55f96c2

Browse files
feat(plugins): expose the agent protection service (#421)
Expose scoped provider registration and policy persistence to trusted plugins. Register cleanup before native IPC and wait for native host initialization. Signed-off-by: Alex Rosenzweig <[email protected]>
1 parent f3676ce commit 55f96c2

11 files changed

Lines changed: 388 additions & 15 deletions

File tree

‎crates/plugin-manager/src/lib.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,11 @@ pub struct Manager {
248248
safe_mode: bool,
249249
}
250250
impl Manager {
251+
/// Host control-plane location that protected workers must not modify.
252+
pub fn storage_root(&self) -> &std::path::Path {
253+
&self.root
254+
}
255+
251256
pub fn open(home: Option<PathBuf>, profile: &str, safe_mode: bool) -> Result<Self> {
252257
valid_id(profile)?;
253258
let home = home

‎docs/agent-security.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,13 @@ cargo test -p buzz-agent-controller real_listeners_protect_future_run_controls_a
2323
The test uses two real ACP listeners and the production launch/supervisor functions, with a synthetic relay and ACP worker. It overrides only the resulting command's relay URL to a local plaintext fixture; saved records retain valid secure origins. Explicit gates hold A inside its sandbox before B's controls exist, check both directions of control-file protection, swap the source launcher before B's first task, kill B during a prompt, and verify successful recovery and subsequent work. OAuth/temp writes and paired supervisor cleanup are also checked. The controller start wiring has separate ordinary lifecycle tests. This does not attest real Goose, app UI, human acceptance, or non-macOS behavior.
2424

2525
The native host verifies executable availability and identity, but the provider is responsible for enforcing the supplied policy and every protected path. This contract requires a trusted native caller; plugin exposure is a separate layer.
26+
27+
## Desktop plugin API
28+
29+
The desktop `agentSecurity` service exposes this capability to trusted installed plugins. Policy UI, experimental opt-in and enforcement belong to the external provider plugin.
30+
31+
Use `ctx.agentSecurity` from a plugin scope. `register(executable)` returns an asynchronous disposable lease. Scope disposal unregisters that lease, including registration that completes after disposal. Native requests wait for host initialization; successful registration retries eligible start-on-launch agents without blocking plugin activation. The desktop host adds the plugin store to the protected control paths.
32+
33+
`snapshot()` returns the defaults revision, default binding, per-agent bindings and available provider IDs. `saveDefaults(revision, policy)` uses the defaults revision; `saveAgent(id, revision, policy)` uses the agent revision from `agentControl`. A null policy explicitly clears a binding.
34+
35+
Plugin ownership scoping prevents accidental service misuse; it is not a hostile-JavaScript permission boundary. Providers remain responsible for enforcing the native launch contract above.

‎src-tauri/build.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ fn main() {
7272
"agent_control_read_log",
7373
"goose_install",
7474
"pi_install",
75+
"agent_security",
7576
"agent_control_save",
7677
"agent_control_save_defaults",
7778
"agent_control_start_on_app_launch",

‎src-tauri/capabilities/default.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
"allow-agent-control-read-log",
5151
"allow-goose-install",
5252
"allow-pi-install",
53+
"allow-agent-security",
5354
"allow-agent-control-save",
5455
"allow-agent-control-save-defaults",
5556
"allow-agent-control-start-on-app-launch",

‎src-tauri/src/agents.rs‎

Lines changed: 55 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -330,12 +330,15 @@ impl Host {
330330
agent.start_on_app_launch.then_some((agent.id, None))
331331
})
332332
.collect();
333-
let controller = Controller::new(
333+
let mut controller = Controller::new(
334334
store,
335335
credentials.clone(),
336336
bundle,
337337
legacy_parent.join("dev.local.buzz.agent-ownership"),
338338
);
339+
controller.protect_control_paths(
340+
crate::Manager::from_env().map(|manager| vec![manager.storage_root().to_path_buf()]),
341+
);
339342
Ok(Self {
340343
inventory_warnings,
341344
controller,
@@ -495,33 +498,43 @@ impl AgentHost {
495498
paths: Result<(PathBuf, PathBuf, PathBuf), String>,
496499
resources: Result<PathBuf, String>,
497500
) -> Self {
501+
Self::initialize_with(move || {
502+
let bundle = resources.and_then(RuntimeBundle::new);
503+
paths.and_then(|(root, legacy, workspace)| {
504+
Host::open(
505+
root,
506+
legacy,
507+
workspace,
508+
bundle,
509+
Arc::new(PlatformCredentials::default()),
510+
)
511+
})
512+
})
513+
}
514+
fn initialize_with(open: impl FnOnce() -> Result<Host, String> + Send + 'static) -> Self {
498515
let state = Arc::new(Mutex::new(Err(
499516
"Agent runtime is initializing; retry shortly".into(),
500517
)));
501518
let closed = Arc::new(AtomicBool::new(false));
502519
let admission = Arc::new(tokio::sync::Mutex::new(()));
520+
// Initialization is the first admitted operation. Callers wait for its
521+
// real outcome rather than treating the placeholder as a permanent error.
522+
let initializing = admission
523+
.clone()
524+
.try_lock_owned()
525+
.expect("new admission mutex");
503526
let owner = Self(state.clone(), closed.clone(), admission.clone());
504527
tauri::async_runtime::spawn(async move {
505-
let opened = tauri::async_runtime::spawn_blocking(move || {
506-
let bundle = resources.and_then(RuntimeBundle::new);
507-
paths.and_then(|(root, legacy, workspace)| {
508-
Host::open(
509-
root,
510-
legacy,
511-
workspace,
512-
bundle,
513-
Arc::new(PlatformCredentials::default()),
514-
)
515-
})
516-
})
517-
.await
518-
.unwrap_or_else(|_| Err("Agent runtime initialization failed".into()));
528+
let opened = tauri::async_runtime::spawn_blocking(open)
529+
.await
530+
.unwrap_or_else(|_| Err("Agent runtime initialization failed".into()));
519531
if closed.load(Ordering::SeqCst) {
520532
return;
521533
}
522534
if let Ok(mut state) = state.lock() {
523535
*state = opened;
524536
}
537+
drop(initializing); // restore itself enters through native admission.
525538
Self(state, closed, admission).restore().await;
526539
});
527540
owner
@@ -1402,3 +1415,30 @@ fn refuse_legacy() -> Result<(), String> {
14021415
}
14031416
refuse_legacy_listing(&String::from_utf8_lossy(&output.stdout))
14041417
}
1418+
1419+
/// Trusted plugin service: native state remains authoritative for all start paths.
1420+
#[tauri::command]
1421+
pub(crate) async fn agent_security(
1422+
state: tauri::State<'_, AgentHost>,
1423+
request: buzz_agent_controller::security::Request,
1424+
) -> Result<serde_json::Value, String> {
1425+
let owner = state.inner().clone();
1426+
let provider = match &request {
1427+
buzz_agent_controller::security::Request::Register { provider, .. } => {
1428+
Some(provider.clone())
1429+
}
1430+
_ => None,
1431+
};
1432+
let result = run(owner.clone(), move |host| host.controller.security(request)).await?;
1433+
if let Some(provider) = provider {
1434+
tauri::async_runtime::spawn(async move {
1435+
let ids = owner
1436+
.with(|host| host.controller.security_restore_ids(&provider))
1437+
.unwrap_or_default();
1438+
for id in ids {
1439+
let _ = start(owner.clone(), id, Action::Start, true, None, None).await;
1440+
}
1441+
});
1442+
}
1443+
Ok(result)
1444+
}

‎src-tauri/src/agents/tests.rs‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2534,3 +2534,74 @@ fn startup_parks_metadata_without_credentials_or_runtime_and_follows_removal() {
25342534
assert_eq!(reopened["agents"], json!([]));
25352535
assert_eq!(reopened["inventoryWarnings"], json!([]));
25362536
}
2537+
2538+
#[tokio::test]
2539+
async fn protection_registration_waits_for_initialization_without_retrying() {
2540+
use buzz_agent_controller::security::Request;
2541+
let dir = tempfile::tempdir().unwrap();
2542+
let root = dir.path().to_path_buf();
2543+
let (release, held) = std::sync::mpsc::channel();
2544+
let host = AgentHost::initialize_with(move || {
2545+
held.recv().map_err(|_| "Initialization gate closed")?;
2546+
Host::open(
2547+
root.join("store"),
2548+
root.join("legacy"),
2549+
root.join("workspace"),
2550+
Err(RUNTIME_GATE.into()),
2551+
Arc::new(RejectingCredentials),
2552+
)
2553+
});
2554+
let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2555+
let counted = calls.clone();
2556+
let executable = dir.path().join("launcher");
2557+
std::fs::write(&executable, "synthetic launcher bytes").unwrap();
2558+
#[cfg(unix)]
2559+
{
2560+
use std::os::unix::fs::PermissionsExt;
2561+
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o700)).unwrap();
2562+
}
2563+
let mut registration = std::pin::pin!(run(host.clone(), move |h| {
2564+
counted.fetch_add(1, Ordering::SeqCst);
2565+
h.controller.security(Request::Register {
2566+
provider: "fixture.security".into(),
2567+
executable,
2568+
})
2569+
}));
2570+
assert_pending(registration.as_mut()).await;
2571+
assert_eq!(calls.load(Ordering::SeqCst), 0);
2572+
release.send(()).unwrap();
2573+
assert!(registration.await.unwrap()["lease"].is_string());
2574+
assert_eq!(calls.load(Ordering::SeqCst), 1);
2575+
let snapshot = run(host.clone(), |h| h.controller.security(Request::Snapshot))
2576+
.await
2577+
.unwrap();
2578+
assert_eq!(snapshot["availableProviders"], json!(["fixture.security"]));
2579+
host.shutdown().unwrap();
2580+
}
2581+
2582+
#[tokio::test]
2583+
async fn initialization_failure_and_shutdown_refuse_queued_registration() {
2584+
for shutdown in [false, true] {
2585+
let (release, held) = std::sync::mpsc::channel();
2586+
let host = AgentHost::initialize_with(move || {
2587+
held.recv().map_err(|_| "Initialization gate closed")?;
2588+
Err("Synthetic initialization failure".into())
2589+
});
2590+
let mut registration = std::pin::pin!(run::<()>(host.clone(), |_| {
2591+
panic!("registration must not execute without a usable host")
2592+
}));
2593+
assert_pending(registration.as_mut()).await;
2594+
if shutdown {
2595+
host.shutdown().unwrap();
2596+
}
2597+
release.send(()).unwrap();
2598+
assert_eq!(
2599+
registration.await.unwrap_err(),
2600+
if shutdown {
2601+
"Agent host is shutting down"
2602+
} else {
2603+
"Synthetic initialization failure"
2604+
}
2605+
);
2606+
}
2607+
}

‎src-tauri/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,7 @@ fn commands<R: tauri::Runtime>() -> impl Fn(tauri::ipc::Invoke<R>) -> bool + Sen
424424
pi_install,
425425
agent_control_use_here,
426426
agent_control_local_clone_settings,
427+
agents::agent_security,
427428
agent_control_save,
428429
agent_control_save_defaults,
429430
agent_control_delete,

‎src/app/services.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
createIdentity,
44
nativeIdentityEnabled,
55
} from "../features/identity/service";
6+
import { AgentSecurityService } from "../features/agents/security";
67
import { SettingsCardsService } from "../features/settings/service";
78
import { TemplateProvidersService } from "../features/channel-templates/provider";
89
import { IdentityNamesService } from "../features/identity-names/service";
@@ -43,6 +44,7 @@ export function createServices() {
4344
bundled: bundledPlugins,
4445
});
4546
const agentControl = provideAgentControl(ctx);
47+
new AgentSecurityService(ctx);
4648
const navigationHost = provideNavigation(ctx);
4749
const navigation = navigationHost.navigation;
4850
const browser = new BrowserService(ctx);
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
import { expect, test, vi } from "vitest";
2+
import { Context } from "@deepseek-ai/cordis";
3+
import { AgentSecurityService, type SecurityHost } from "./security";
4+
5+
test("plugin scope revokes a late native registration and cannot leave an enabled provider", async () => {
6+
const ctx = new Context();
7+
let complete!: (v: { lease: string }) => void;
8+
const pending = new Promise<{ lease: string }>((r) => {
9+
complete = r;
10+
});
11+
const requests: Record<string, unknown>[] = [];
12+
const host: SecurityHost = async <T>(request: Record<string, unknown>) => {
13+
requests.push(request);
14+
return (request.kind === "register" ? await pending : {}) as T;
15+
};
16+
new AgentSecurityService(ctx, host);
17+
let registration: Promise<unknown> | undefined;
18+
const plugin = ctx
19+
.extend({ pluginOwner: { id: "fixture.security", revision: "1" } })
20+
.plugin({
21+
inject: ["agentSecurity"],
22+
apply(scope: Context) {
23+
registration = scope.agentSecurity.register("/fixture/launcher");
24+
void registration.catch(() => {});
25+
},
26+
});
27+
await vi.waitFor(() => expect(requests).toHaveLength(1));
28+
const disposal = plugin.dispose();
29+
complete({ lease: "lease-one" });
30+
await disposal;
31+
await expect(registration).rejects.toThrow("disabled");
32+
expect(requests).toContainEqual({
33+
kind: "unregister",
34+
provider: "fixture.security",
35+
lease: "lease-one",
36+
});
37+
await ctx.fiber.dispose();
38+
});
39+
40+
test("a retained service cannot register after its plugin scope is disposed", async () => {
41+
const ctx = new Context();
42+
const host = vi.fn(async () => ({ lease: "unexpected" }));
43+
new AgentSecurityService(ctx, host as SecurityHost);
44+
let service: Context["agentSecurity"] | undefined;
45+
const plugin = ctx
46+
.extend({ pluginOwner: { id: "fixture.security", revision: "1" } })
47+
.plugin({
48+
inject: ["agentSecurity"],
49+
apply(scope: Context) {
50+
service = scope.agentSecurity;
51+
},
52+
});
53+
await vi.waitFor(() => expect(service).toBeDefined());
54+
await plugin.dispose();
55+
if (!service) throw new Error("Plugin service was not initialized");
56+
await expect(service.register("/fixture/launcher")).rejects.toThrow(
57+
"inactive context",
58+
);
59+
expect(host).not.toHaveBeenCalled();
60+
await ctx.fiber.dispose();
61+
expect(host).not.toHaveBeenCalled();
62+
});
63+
64+
test("explicit and scope disposal unregister a successful registration only once", async () => {
65+
const ctx = new Context();
66+
const requests: Record<string, unknown>[] = [];
67+
new AgentSecurityService(ctx, async <T>(request: Record<string, unknown>) => {
68+
requests.push(request);
69+
return { lease: "lease-one" } as T;
70+
});
71+
let registration:
72+
| ReturnType<Context["agentSecurity"]["register"]>
73+
| undefined;
74+
const plugin = ctx
75+
.extend({ pluginOwner: { id: "fixture.security", revision: "1" } })
76+
.plugin({
77+
inject: ["agentSecurity"],
78+
apply(scope: Context) {
79+
registration = scope.agentSecurity.register("/fixture/launcher");
80+
},
81+
});
82+
await vi.waitFor(() => expect(registration).toBeDefined());
83+
if (!registration) throw new Error("Plugin registration was not started");
84+
const provider = await registration;
85+
await provider.dispose();
86+
await provider.dispose();
87+
await plugin.dispose();
88+
await ctx.fiber.dispose();
89+
expect(requests).toEqual([
90+
{
91+
kind: "register",
92+
provider: "fixture.security",
93+
executable: "/fixture/launcher",
94+
},
95+
{ kind: "unregister", provider: "fixture.security", lease: "lease-one" },
96+
]);
97+
});
98+
99+
test("failed registration does not unregister a provider it never acquired", async () => {
100+
const ctx = new Context();
101+
const host = vi.fn(async () => {
102+
throw new Error("launcher unavailable");
103+
});
104+
new AgentSecurityService(ctx, host);
105+
let registration: Promise<unknown> | undefined;
106+
const plugin = ctx
107+
.extend({ pluginOwner: { id: "fixture.security", revision: "1" } })
108+
.plugin({
109+
inject: ["agentSecurity"],
110+
apply(scope: Context) {
111+
registration = scope.agentSecurity.register("/fixture/launcher");
112+
void registration.catch(() => {});
113+
},
114+
});
115+
await vi.waitFor(() => expect(registration).toBeDefined());
116+
await expect(registration).rejects.toThrow("launcher unavailable");
117+
await plugin.dispose();
118+
await ctx.fiber.dispose();
119+
expect(host).toHaveBeenCalledTimes(1);
120+
});

0 commit comments

Comments
 (0)