返回 CodeWhale
dsh_grant_tests.rs
根目录 / crates / engine / src / extension_host / dsh_grant_tests.rs
1 use std::path::Path;
2 use std::sync::Arc;
3 use std::sync::atomic::{AtomicBool, Ordering};
4 use std::time::Duration;
5
6 use serde_json::{Value, json};
7 use tokio::sync::mpsc;
8
9 use super::core_call::InvocationGuard;
10 use super::dsh_broker::{Arm, BrokerCall, BrokerFuture, BrokerMethods, BrokerRefusal, decode};
11 use super::protocol::{DshBrokerParams, DshService, HostRequest, RpcErrorWire, error_code};
12 use super::supervisor::HostRequestContext;
13 use super::tier::HostCohort;
14 use super::{ExtensionHostManager, ExtensionHostOptions};
15 use crate::tools::codemode::{ExtensionCaller, NestedCallGate};
16 use crate::tools::spec::ToolContext;
17 use codewhale_config::OwnerRef;
18 use codewhale_plugins::PluginRegistry;
19 use codewhale_plugins::activation::TestPolicyGuard;
20 use codewhale_plugins::discovery::{DiscoveryConfig, discover_with_config};
21 use codewhale_plugins::host_services::{
22 HostService, PersonVia, PluginApprover, ReviewApproval, TestOffer,
23 };
24
25 const HOST: u64 = 7;
26
27 struct Plugins {
28 _temp: codewhale_plugins::test_fixture::PluginTempDir,
29 config: DiscoveryConfig,
30 }
31
32 impl Plugins {
33 fn new(plugins: &[(&str, &[&str])]) -> Self {
34 let temp = codewhale_plugins::test_fixture::PluginTempDir::new().unwrap();
35 let root = temp.path();
36 let config = DiscoveryConfig {
37 workspace: root.join("project"),
38 user_plugins_dir: root.join("user"),
39 workspace_plugins_dir: root.join("workspace"),
40 builtin_plugin_dirs: Vec::new(),
41 state_path: root.join("state/plugin-state.json"),
42 };
43 std::fs::create_dir_all(&config.workspace).unwrap();
44 for (name, asks) in plugins {
45 let plugin = config.user_plugins_dir.join(name);
46 std::fs::create_dir_all(plugin.join("native")).unwrap();
47 std::fs::write(
48 plugin.join("native/index.mjs"),
49 "export function apply() {}\n",
50 )
51 .unwrap();
52 let asked = if asks.is_empty() {
53 String::new()
54 } else {
55 format!(
56 "[capabilities]\nhost_services = [{}]\n",
57 asks.iter()
58 .map(|service| format!("{service:?}"))
59 .collect::<Vec<_>>()
60 .join(", ")
61 )
62 };
63 std::fs::write(
64 plugin.join("plugin.toml"),
65 format!(
66 "schema_version = 1\n[plugin]\nname = {name:?}\nversion = \"1.0.0\"\n[native]\npath = \"native/index.mjs\"\n{asked}"
67 ),
68 )
69 .unwrap();
70 }
71 let plugins_fixture = Self {
72 _temp: temp,
73 config,
74 };
75 for (name, _) in plugins {
76 plugins_fixture.review(name, true);
77 }
78 plugins_fixture
79 }
80
81 fn registry(&self) -> PluginRegistry {
82 discover_with_config(&self.config)
83 }
84
85 fn review(&self, name: &str, showing_services: bool) {
86 let mut registry = self.registry();
87 let shown = registry
88 .host_service_review(name)
89 .filter(|_| showing_services)
90 .map(|review| review.token);
91 registry
92 .trust_reviewed(
93 name,
94 ReviewApproval {
95 approved_by: PluginApprover::person(PersonVia::Terminal),
96 host_services: shown,
97 },
98 )
99 .unwrap();
100 registry.enable(name).unwrap();
101 }
102 }
103
104 struct Host {
105 manager: ExtensionHostManager,
106 context: ToolContext,
107 gate: NestedCallGate,
108 }
109
110 fn host(workspace: &Path) -> Host {
111 let manager = ExtensionHostManager::new(ExtensionHostOptions::default());
112 let (tx_event, mut rx_event) = mpsc::channel(8);
113 tokio::spawn(async move { while rx_event.recv().await.is_some() {} });
114 let (gate, _requests) = NestedCallGate::new(None, tx_event, Duration::from_secs(60));
115 let context = ToolContext::new(workspace)
116 .with_session_objects(crate::rlm::session::SessionObjectSnapshot::new(
117 "grant-session".into(),
118 "fixture-model".into(),
119 workspace.to_path_buf(),
120 None,
121 Arc::new(Vec::new()),
122 ))
123 .with_origin_turn_id("grant-turn");
124 Host {
125 manager,
126 context,
127 gate: gate.for_extension(
128 ExtensionCaller {
129 origin: "extension:grant".to_string(),
130 tool: "grant_tool".to_string(),
131 scope: "ext:grant@hash".to_string(),
132 },
133 Vec::new(),
134 ),
135 }
136 }
137
138 impl Host {
139 fn load(&self, plugins: &Plugins, name: &str) -> OwnerRef {
140 let authority = plugins.registry().authority_for(name).unwrap();
141 let services = codewhale_plugins::registry::granted_host_services(&authority)
142 .unwrap()
143 .into_iter()
144 .filter_map(|service| DshService::parse(service.name()))
145 .collect();
146 let mut registry = self.manager.shared.registry.lock().unwrap();
147 let owner = registry
148 .begin_owner(
149 HostCohort::reviewed(),
150 authority.plugin_id.as_str(),
151 name,
152 Some(authority.clone()),
153 &authority.content_hash,
154 )
155 .unwrap();
156 registry.set_host_services(&owner, services);
157 registry.mark_active(&owner);
158 owner
159 }
160
161 fn mint(&self, cohort: HostCohort, owner: &OwnerRef) -> InvocationGuard {
162 self.manager
163 .shared
164 .core_calls
165 .begin_scoped(
166 cohort,
167 HOST,
168 owner,
169 "call-1",
170 self.gate.extension().unwrap().0,
171 &self.context,
172 &self.gate,
173 None,
174 String::new(),
175 &self.manager.shared.broker_services(owner),
176 )
177 .expect("an invocation")
178 }
179
180 fn services(&self, owner: &OwnerRef) -> Vec<&'static str> {
181 self.mint(HostCohort::reviewed(), owner)
182 .broker_tickets()
183 .unwrap_or_default()
184 .into_iter()
185 .filter_map(|wire| DshService::parse(&wire.service).map(DshService::name))
186 .collect()
187 }
188
189 async fn call(
190 &self,
191 table: &[(DshService, Arm)],
192 owner: &OwnerRef,
193 ticket: &str,
194 service: &str,
195 ) -> (Result<Value, RpcErrorWire>, Vec<String>) {
196 let (cx, mut violations, _cancel) = HostRequestContext::for_test(1);
197 let result = self
198 .manager
199 .shared
200 .core_calls
201 .serve_broker_in(
202 table,
203 &self.manager.shared,
204 HostCohort::reviewed(),
205 HOST,
206 DshBrokerParams {
207 owner: owner.clone(),
208 ticket: ticket.to_string(),
209 service: service.to_string(),
210 method: "echo".to_string(),
211 input: json!({ "text": "ok", "granted": ["llm"], "host_services": ["llm"] }),
212 },
213 cx,
214 )
215 .await;
216 let mut seen = Vec::new();
217 while let Ok(violation) = violations.try_recv() {
218 seen.push(violation);
219 }
220 (result, seen)
221 }
222 }
223
224 fn ticket(guard: &InvocationGuard, service: &str) -> String {
225 guard
226 .broker_tickets()
227 .unwrap_or_default()
228 .into_iter()
229 .find(|wire| wire.service == service)
230 .map(|wire| wire.ticket)
231 .unwrap_or_else(|| panic!("no {service} ticket"))
232 }
233
234 fn refusal(result: &Result<Value, RpcErrorWire>) -> (i64, String, String) {
235 let error = result.as_ref().expect_err("a refusal");
236 (
237 error.code,
238 error.data.as_ref().unwrap()["dsh_refusal"]
239 .as_str()
240 .unwrap()
241 .to_string(),
242 error.message.clone(),
243 )
244 }
245
246 fn not_granted(service: &str) -> (i64, String, String) {
247 (
248 error_code::REFUSED,
249 "not_granted".to_string(),
250 format!("the {service} service is not granted to this plugin"),
251 )
252 }
253
254 #[derive(serde::Deserialize)]
255 #[serde(tag = "method", content = "input")]
256 enum Echo {
257 #[serde(rename = "echo")]
258 Echo { text: String },
259 }
260
261 impl BrokerMethods for Echo {
262 const NAMES: &'static [&'static str] = &["echo"];
263 }
264
265 fn echo_arm(call: BrokerCall) -> BrokerFuture {
266 Box::pin(async move {
267 let Echo::Echo { text } = decode::<Echo>(&call)?;
268 Ok(json!({ "plugin": call.owner.plugin_id, "service": call.service.name(), "text": text }))
269 })
270 }
271
272 fn echo() -> Vec<(DshService, Arm)> {
273 DshService::ALL
274 .into_iter()
275 .map(|service| (service, echo_arm as Arm))
276 .collect()
277 }
278
279 static WAITING: AtomicBool = AtomicBool::new(false);
280 static WITHDRAWN: AtomicBool = AtomicBool::new(false);
281
282 fn waiting_arm(call: BrokerCall) -> BrokerFuture {
283 Box::pin(async move {
284 let cancel = call.context.cancel().clone();
285 tokio::spawn(async move {
286 cancel.cancelled().await;
287 WITHDRAWN.store(true, Ordering::SeqCst);
288 });
289 WAITING.store(true, Ordering::SeqCst);
290 std::future::pending::<()>().await;
291 Err(BrokerRefusal::NotAvailable(call.service))
292 })
293 }
294
295 async fn until(what: &str, done: impl Fn() -> bool) {
296 for _ in 0..400 {
297 if done() {
298 return;
299 }
300 tokio::time::sleep(Duration::from_millis(10)).await;
301 }
302 panic!("timed out waiting for {what}");
303 }
304
305 #[test]
306 fn the_engine_and_the_review_record_name_the_same_services() {
307 assert_eq!(
308 DshService::ALL.map(DshService::name),
309 HostService::ALL.map(HostService::name)
310 );
311 for service in DshService::ALL {
312 assert!(super::dsh_broker::offered(service), "{service:?}");
313 }
314 let _offer = TestOffer::only(&[HostService::Remote]);
315 assert!(super::dsh_broker::offered(DshService::Remote));
316 assert!(!super::dsh_broker::offered(DshService::Network));
317 }
318
319 #[test]
320 fn a_record_that_cannot_be_read_at_the_scan_loads_no_owner() {
321 let _policy = TestPolicyGuard::extension_host(true);
322 let plugins = Plugins::new(&[("alpha", &[])]);
323 let registry = plugins.registry();
324 let (sources, errors) = codewhale_plugins::runtime::active_component_sources(
325 &registry,
326 codewhale_plugins::activation::PluginActivationCapability::Native,
327 );
328 assert_eq!(sources.len(), 1, "{errors:?}");
329 plugins.registry().disable("alpha").unwrap();
330 let (desired, errors) = super::desired_owners_from(&registry, sources, errors);
331 assert!(desired.is_empty(), "{:?}", desired.keys());
332 assert_eq!(
333 errors
334 .iter()
335 .filter(|error| error
336 .contains("`alpha` was not loaded because its review record could not be read"))
337 .count(),
338 1,
339 "{errors:?}"
340 );
341 }
342
343 #[tokio::test]
344 async fn no_broker_ticket_is_minted_for_a_plugin_whose_reviewed_record_does_not_name_the_service() {
345 let _policy = TestPolicyGuard::extension_host(true);
346 let offer = TestOffer::only(&[HostService::Network, HostService::Llm]);
347 let granted = Plugins::new(&[("alpha", &["network"])]);
348 let host_a = host(&granted.config.workspace);
349 let alpha = host_a.load(&granted, "alpha");
350 assert_eq!(host_a.services(&alpha), vec!["network"]);
351 let guard = host_a.mint(HostCohort::reviewed(), &alpha);
352 let network = ticket(&guard, "network");
353 let (served, _) = host_a.call(&echo(), &alpha, &network, "network").await;
354 assert_eq!(served.unwrap()["service"], "network");
355 let (wrong, _) = host_a.call(&echo(), &alpha, &network, "llm").await;
356 assert_eq!(refusal(&wrong).1, "ticket_refused");
357
358 let ungranted = Plugins::new(&[("beta", &[])]);
359 let host_b = host(&ungranted.config.workspace);
360 let beta = host_b.load(&ungranted, "beta");
361 assert!(host_b.services(&beta).is_empty());
362 let forged = OwnerRef {
363 plugin_id: beta.plugin_id.clone(),
364 ..alpha.clone()
365 };
366 let (borrowed, _) = host_b.call(&echo(), &forged, &network, "network").await;
367 assert_eq!(refusal(&borrowed).1, "ticket_refused");
368
369 let unshown = Plugins::new(&[("gamma", &["network"])]);
370 unshown.review("gamma", false);
371 let host_c = host(&unshown.config.workspace);
372 let gamma = host_c.load(&unshown, "gamma");
373 assert!(
374 host_c.services(&gamma).is_empty(),
375 "a review that did not show the service grants none"
376 );
377
378 drop(offer);
379 let _none = TestOffer::only(&[]);
380 assert!(
381 host_a.services(&alpha).is_empty(),
382 "a build that offers no service mints no broker ticket, whatever is recorded"
383 );
384 let (unreachable, _) = host_a.call(&echo(), &alpha, &network, "network").await;
385 assert_eq!(refusal(&unreachable), not_granted("network"));
386 for service in DshService::ALL {
387 let (stub, _) = host_a
388 .call(super::dsh_broker::TABLE, &alpha, &network, service.name())
389 .await;
390 assert!(stub.is_err(), "{}", service.name());
391 }
392 }
393
394 #[tokio::test]
395 async fn no_broker_ticket_while_a_plugin_without_the_grant_shares_the_host() {
396 let _policy = TestPolicyGuard::extension_host(true);
397 let _offer = TestOffer::only(&[HostService::Network, HostService::Llm]);
398 let plugins = Plugins::new(&[
399 ("alpha", &["network", "llm"]),
400 ("beta", &[]),
401 ("gamma", &["network"]),
402 ]);
403 plugins.review("alpha", true);
404 let host = host(&plugins.config.workspace);
405 let alpha = host.load(&plugins, "alpha");
406 assert_eq!(host.services(&alpha), vec!["llm", "network"]);
407 let alone = host.mint(HostCohort::reviewed(), &alpha);
408 let network = ticket(&alone, "network");
409 let llm = ticket(&alone, "llm");
410
411 let gamma = host.load(&plugins, "gamma");
412 assert_eq!(host.services(&alpha), vec!["network"]);
413 assert_eq!(host.services(&gamma), vec!["network"]);
414 let (shared, _) = host.call(&echo(), &alpha, &network, "network").await;
415 assert_eq!(shared.unwrap()["plugin"], alpha.plugin_id);
416 let (unshared, _) = host.call(&echo(), &alpha, &llm, "llm").await;
417 assert_eq!(refusal(&unshared), not_granted("llm"));
418 let report = host
419 .manager
420 .shared
421 .registry
422 .lock()
423 .unwrap()
424 .take_withheld_report()
425 .unwrap();
426 assert_eq!(
427 report,
428 "host service `llm` is off: the review of `gamma` does not include it"
429 );
430 assert!(
431 host.manager
432 .shared
433 .registry
434 .lock()
435 .unwrap()
436 .take_withheld_report()
437 .is_none(),
438 "reported once"
439 );
440
441 let beta = {
442 let authority = plugins.registry().authority_for("beta").unwrap();
443 host.manager
444 .shared
445 .registry
446 .lock()
447 .unwrap()
448 .begin_owner(
449 HostCohort::reviewed(),
450 authority.plugin_id.as_str(),
451 "beta",
452 Some(authority.clone()),
453 &authority.content_hash,
454 )
455 .unwrap()
456 };
457 assert!(
458 host.services(&alpha).is_empty(),
459 "an activating plugin without the grant already withholds it"
460 );
461 assert!(host.services(&gamma).is_empty());
462 assert!(host.services(&beta).is_empty());
463 let (withheld, _) = host.call(&echo(), &alpha, &network, "network").await;
464 let own = Plugins::new(&[("delta", &[])]);
465 let other_host = self::host(&own.config.workspace);
466 let delta = other_host.load(&own, "delta");
467 let lacking = other_host.mint(HostCohort::reviewed(), &delta);
468 assert!(lacking.broker_tickets().is_none());
469 assert_eq!(
470 refusal(&withheld),
471 not_granted("network"),
472 "the refusal is the same whoever lacks the grant, and names nobody"
473 );
474 assert!(!refusal(&withheld).2.contains("beta"));
475 let report = host
476 .manager
477 .shared
478 .registry
479 .lock()
480 .unwrap()
481 .take_withheld_report()
482 .unwrap();
483 assert_eq!(
484 report,
485 "host service `llm` is off: the reviews of `beta`, `gamma` do not include it; host service `network` is off: the review of `beta` does not include it"
486 );
487 }
488
489 #[tokio::test]
490 async fn a_plugin_that_left_the_host_withholds_every_service_until_the_host_exits() {
491 let _policy = TestPolicyGuard::extension_host(true);
492 let _offer = TestOffer::only(&[HostService::Network]);
493 let plugins = Plugins::new(&[("alpha", &["network"]), ("gamma", &["network"])]);
494 plugins.review("alpha", true);
495 let host = host(&plugins.config.workspace);
496 let alpha = host.load(&plugins, "alpha");
497 let gamma = host.load(&plugins, "gamma");
498 assert_eq!(host.services(&alpha), vec!["network"]);
499 let guard = host.mint(HostCohort::reviewed(), &alpha);
500 let network = ticket(&guard, "network");
501 assert!(
502 !host
503 .manager
504 .shared
505 .registry
506 .lock()
507 .unwrap()
508 .host_services_await_restart(HostCohort::reviewed())
509 );
510
511 {
512 let mut registry = host.manager.shared.registry.lock().unwrap();
513 assert_eq!(registry.revoke_owner(&gamma.plugin_id), Some(gamma.clone()));
514 registry.forget_owner(&gamma.plugin_id);
515 assert!(registry.host_services_await_restart(HostCohort::reviewed()));
516 assert_eq!(
517 registry.take_withheld_report().unwrap(),
518 "host services are off until the plugin host restarts: a plugin that was turned off, changed or failed is still loaded in it"
519 );
520 }
521 assert!(
522 host.services(&alpha).is_empty(),
523 "code that was loaded cannot be unloaded: nothing is given until the process is gone"
524 );
525 let (lingering, _) = host.call(&echo(), &alpha, &network, "network").await;
526 assert_eq!(refusal(&lingering), not_granted("network"));
527
528 let again = host.load(&plugins, "gamma");
529 assert!(host.services(&alpha).is_empty());
530 assert!(host.services(&again).is_empty());
531
532 {
533 let mut registry = host.manager.shared.registry.lock().unwrap();
534 registry.host_exited(HostCohort::reviewed(), "planned restart");
535 assert!(!registry.host_services_await_restart(HostCohort::reviewed()));
536 }
537 let alpha = host.load(&plugins, "alpha");
538 assert_eq!(host.services(&alpha), vec!["network"]);
539
540 let failing = host.load(&plugins, "gamma");
541 host.manager
542 .shared
543 .registry
544 .lock()
545 .unwrap()
546 .mark_failed(&failing, super::registry::OwnerState::Failed("boom".into()));
547 assert!(host.services(&alpha).is_empty());
548 host.manager
549 .shared
550 .registry
551 .lock()
552 .unwrap()
553 .host_process_started(HostCohort::reviewed());
554 assert_eq!(host.services(&alpha), vec!["network"]);
555 }
556
557 #[tokio::test]
558 async fn a_grant_is_read_from_the_owner_record_at_mint_and_at_redeem_never_from_the_wire() {
559 let _policy = TestPolicyGuard::extension_host(true);
560 let _offer = TestOffer::only(&[HostService::Network, HostService::Llm]);
561 let plugins = Plugins::new(&[("alpha", &["network"])]);
562 let host = host(&plugins.config.workspace);
563 let alpha = host.load(&plugins, "alpha");
564 let guard = host.mint(HostCohort::reviewed(), &alpha);
565 let network = ticket(&guard, "network");
566 let (served, _) = host.call(&echo(), &alpha, &network, "network").await;
567 assert!(served.is_ok(), "{served:?}");
568 let (claimed, _) = host.call(&echo(), &alpha, &network, "llm").await;
569 assert_eq!(
570 refusal(&claimed).1,
571 "ticket_refused",
572 "input that claims a grant grants nothing"
573 );
574
575 plugins.review("alpha", false);
576 let (reviewed_again, _) = host.call(&echo(), &alpha, &network, "network").await;
577 assert_eq!(
578 refusal(&reviewed_again),
579 not_granted("network"),
580 "a new review that drops the service refuses the next call of the running tool"
581 );
582 assert_eq!(
583 host.services(&alpha),
584 vec!["network"],
585 "the owner record is replaced by reconcile; until then redeem reads the review record"
586 );
587
588 plugins.review("alpha", true);
589 let (stale, _) = host.call(&echo(), &alpha, &network, "network").await;
590 assert_eq!(
591 refusal(&stale),
592 not_granted("network"),
593 "an owner from before the review holds nothing, whatever the new review grants"
594 );
595 host.manager
596 .shared
597 .registry
598 .lock()
599 .unwrap()
600 .host_exited(HostCohort::reviewed(), "restart");
601 let current = host.load(&plugins, "alpha");
602 let guard = host.mint(HostCohort::reviewed(), &current);
603 let (fresh, _) = host
604 .call(&echo(), &current, &ticket(&guard, "network"), "network")
605 .await;
606 assert!(fresh.is_ok(), "{fresh:?}");
607
608 std::fs::write(&plugins.config.state_path, b"{ not json").unwrap();
609 let (unreadable, _) = host
610 .call(&echo(), &current, &ticket(&guard, "network"), "network")
611 .await;
612 assert_eq!(refusal(&unreadable), not_granted("network"));
613 }
614
615 #[tokio::test]
616 async fn a_disable_from_another_process_stops_broker_calls_of_a_running_tool() {
617 let _policy = TestPolicyGuard::extension_host(true);
618 let _offer = TestOffer::only(&[HostService::Network]);
619 let plugins = Plugins::new(&[("alpha", &["network"]), ("gamma", &["network"])]);
620 plugins.review("alpha", true);
621 let host = host(&plugins.config.workspace);
622 let alpha = host.load(&plugins, "alpha");
623 let _gamma = host.load(&plugins, "gamma");
624 let guard = host.mint(HostCohort::reviewed(), &alpha);
625 let network = ticket(&guard, "network");
626 let waiting: Vec<(DshService, Arm)> = vec![(DshService::Network, waiting_arm as Arm)];
627
628 let in_flight = host.call(&waiting, &alpha, &network, "network");
629 let elsewhere = async {
630 until("the arm to start", || WAITING.load(Ordering::SeqCst)).await;
631 plugins.registry().disable("gamma").unwrap();
632 };
633 let ((stopped, violations), ()) = tokio::join!(in_flight, elsewhere);
634 assert_eq!(
635 refusal(&stopped),
636 not_granted("network"),
637 "a co-hosted plugin turned off elsewhere withdraws the call in flight"
638 );
639 assert!(violations.is_empty());
640 until("the arm's cancellation", || {
641 WITHDRAWN.load(Ordering::SeqCst)
642 })
643 .await;
644
645 let (next, _) = host.call(&echo(), &alpha, &network, "network").await;
646 assert_eq!(refusal(&next), not_granted("network"));
647 assert_eq!(
648 host.services(&alpha),
649 vec!["network"],
650 "this process has not reconciled yet; the review record already refuses"
651 );
652
653 plugins.registry().enable("gamma").unwrap();
654 let (spent, _) = host.call(&echo(), &alpha, &network, "network").await;
655 assert_eq!(
656 refusal(&spent),
657 not_granted("network"),
658 "the loaded owner is from before the plugin was turned off"
659 );
660 plugins.registry().disable("alpha").unwrap();
661 let (own, _) = host.call(&echo(), &alpha, &network, "network").await;
662 assert_eq!(refusal(&own), not_granted("network"));
663 }
664
665 #[tokio::test]
666 async fn a_builtin_tier_owner_never_gets_a_broker_ticket() {
667 let _policy = TestPolicyGuard::extension_host(true);
668 let _offer = TestOffer::only(&HostService::ALL);
669 let workspace = tempfile::tempdir().unwrap();
670 let host = host(workspace.path());
671 let builtin = {
672 let mut registry = host.manager.shared.registry.lock().unwrap();
673 let owner = registry
674 .begin_owner(HostCohort::Builtin, "host:mcp", "mcp", None, "digest")
675 .unwrap();
676 registry.set_host_services(&owner, DshService::ALL.to_vec());
677 registry.mark_active(&owner);
678 assert!(
679 DshService::ALL
680 .into_iter()
681 .all(|service| !registry.host_service_granted(&owner, service))
682 );
683 owner
684 };
685 assert!(host.manager.shared.broker_services(&builtin).is_empty());
686 assert!(
687 host.mint(HostCohort::Builtin, &builtin)
688 .broker_tickets()
689 .is_none()
690 );
691 let _everything = super::dsh_broker::TestGrants::only(&DshService::ALL);
692 let forced = host
693 .manager
694 .shared
695 .core_calls
696 .begin(
697 HostCohort::Builtin,
698 HOST,
699 &builtin,
700 "call-2",
701 host.gate.extension().unwrap().0,
702 &host.context,
703 &host.gate,
704 )
705 .unwrap();
706 assert!(
707 forced.broker_tickets().is_none(),
708 "no override mints a broker ticket for the built-in tier"
709 );
710 }
711
712 #[tokio::test]
713 async fn a_broker_ticket_is_refused_by_core_call_checkpoint_question_and_subagent() {
714 let _policy = TestPolicyGuard::extension_host(true);
715 let _offer = TestOffer::only(&[HostService::Network]);
716 let plugins = Plugins::new(&[("alpha", &["network"])]);
717 let host = host(&plugins.config.workspace);
718 let alpha = host.load(&plugins, "alpha");
719 let guard = host.mint(HostCohort::reviewed(), &alpha);
720 let network = ticket(&guard, "network");
721 let shared = &host.manager.shared;
722 let cx = |id| HostRequestContext::for_test(id).0;
723 let refused = |result: Result<Value, RpcErrorWire>, what: &str| {
724 let error = result.expect_err(what);
725 assert_eq!(error.code, error_code::REFUSED, "{what}: {error:?}");
726 assert_eq!(
727 error.message, "the ticket is not valid for this request",
728 "{what}"
729 );
730 };
731
732 refused(
733 shared
734 .core_calls
735 .serve(
736 shared,
737 HostCohort::reviewed(),
738 HOST,
739 super::protocol::CoreCallParams {
740 owner: alpha.clone(),
741 ticket: network.clone(),
742 name: "read_file".into(),
743 input: json!({ "path": "x" }),
744 },
745 cx(1),
746 )
747 .await,
748 "core/call",
749 );
750 refused(
751 shared
752 .core_calls
753 .serve_checkpoint(
754 shared,
755 HostCohort::reviewed(),
756 HOST,
757 super::protocol::SessionCheckpointParams {
758 owner: alpha.clone(),
759 ticket: network.clone(),
760 },
761 cx(2),
762 )
763 .await,
764 "session/checkpoint",
765 );
766 refused(
767 shared
768 .core_calls
769 .serve_question(
770 shared,
771 HostCohort::reviewed(),
772 HOST,
773 super::protocol::UserQuestionParams {
774 owner: alpha.clone(),
775 ticket: network.clone(),
776 questions: Vec::new(),
777 },
778 cx(3),
779 )
780 .await,
781 "user-questions/ask",
782 );
783 refused(
784 shared
785 .core_calls
786 .serve_subagent(
787 shared,
788 HostCohort::reviewed(),
789 HOST,
790 HostRequest::SubagentStart(super::protocol::SubagentStartParams {
791 owner: alpha.clone(),
792 ticket: network.clone(),
793 child_id: "child".into(),
794 prompt: "p".into(),
795 model: None,
796 persona: None,
797 denied_tools: Vec::new(),
798 delivery: "caller".into(),
799 }),
800 cx(4),
801 )
802 .await,
803 "subagent/start",
804 );
805 refused(
806 shared
807 .core_calls
808 .serve_subagent(
809 shared,
810 HostCohort::reviewed(),
811 HOST,
812 HostRequest::SubagentPrompt(super::protocol::SubagentPromptParams {
813 owner: alpha.clone(),
814 ticket: network.clone(),
815 child_id: "child".into(),
816 prompt: "follow up".into(),
817 mode: "queue".into(),
818 }),
819 cx(5),
820 )
821 .await,
822 "subagent/prompt",
823 );
824 let (still_good, _) = host.call(&echo(), &alpha, &network, "network").await;
825 assert!(still_good.is_ok(), "{still_good:?}");
826 }
827
828 #[tokio::test]
829 async fn subagent_prompt_enforces_ticket_owner_and_retired_child_gating() {
830 let cx = |id| HostRequestContext::for_test(id).0;
831 let _policy = TestPolicyGuard::extension_host(true);
832 let _offer = TestOffer::only(&[HostService::Network]);
833 let plugins = Plugins::new(&[("alpha", &["network"]), ("beta", &[])]);
834 let host = host(&plugins.config.workspace);
835 let alpha = host.load(&plugins, "alpha");
836 let beta = host.load(&plugins, "beta");
837 let guard = host.mint(HostCohort::reviewed(), &alpha);
838 let subagent_ticket = guard
839 .subagent_ticket()
840 .expect("subagent ticket")
841 .to_string();
842 let shared = &host.manager.shared;
843
844 let wrong_owner = shared
845 .core_calls
846 .serve_subagent(
847 shared,
848 HostCohort::reviewed(),
849 HOST,
850 HostRequest::SubagentPrompt(super::protocol::SubagentPromptParams {
851 owner: beta.clone(),
852 ticket: subagent_ticket.clone(),
853 child_id: "member-1".into(),
854 prompt: "hello".into(),
855 mode: "queue".into(),
856 }),
857 cx(10),
858 )
859 .await;
860 assert_eq!(wrong_owner.unwrap_err().code, error_code::REFUSED);
861
862 let disposed = shared
863 .core_calls
864 .serve_subagent(
865 shared,
866 HostCohort::reviewed(),
867 HOST,
868 HostRequest::SubagentDispose(super::protocol::SubagentHandleParams {
869 owner: alpha.clone(),
870 ticket: subagent_ticket.clone(),
871 child_id: "member-1".into(),
872 }),
873 cx(11),
874 )
875 .await;
876 assert!(disposed.is_ok(), "{disposed:?}");
877
878 let retired = shared
879 .core_calls
880 .serve_subagent(
881 shared,
882 HostCohort::reviewed(),
883 HOST,
884 HostRequest::SubagentPrompt(super::protocol::SubagentPromptParams {
885 owner: alpha.clone(),
886 ticket: subagent_ticket,
887 child_id: "member-1".into(),
888 prompt: "hello after retire".into(),
889 mode: "followup".into(),
890 }),
891 cx(12),
892 )
893 .await;
894 let err = retired.unwrap_err();
895 assert_eq!(err.code, error_code::REFUSED);
896 assert!(err.message.contains("retired"), "{err:?}");
897 }
898
899 #[tokio::test]
900 async fn a_spent_or_just_ended_broker_ticket_is_a_limit_not_a_forgery() {
901 let _policy = TestPolicyGuard::extension_host(true);
902 let _offer = TestOffer::only(&[HostService::Network]);
903 let plugins = Plugins::new(&[("alpha", &["network"])]);
904 let host = host(&plugins.config.workspace);
905 let alpha = host.load(&plugins, "alpha");
906 let guard = host.mint(HostCohort::reviewed(), &alpha);
907 let network = ticket(&guard, "network");
908 for _ in 0..super::core_call::MAX_CALLS_PER_INVOCATION {
909 let (served, _) = host.call(&echo(), &alpha, &network, "network").await;
910 assert!(served.is_ok(), "{served:?}");
911 }
912 let (spent, violations) = host.call(&echo(), &alpha, &network, "network").await;
913 assert_eq!(
914 refusal(&spent),
915 (
916 error_code::REFUSED,
917 "limit".to_string(),
918 "this tool call's limit for the network service is used up".to_string()
919 )
920 );
921 assert!(violations.is_empty());
922
923 drop(guard);
924 let mut ended = Vec::new();
925 for _ in 0..(super::ticket::INVALID_BURST * 3) {
926 let (late, violations) = host.call(&echo(), &alpha, &network, "network").await;
927 assert_eq!(refusal(&late).1, "ticket_refused");
928 ended.extend(violations);
929 }
930 assert!(
931 ended.is_empty(),
932 "frames already in the pipe when a tool call ends do not end the host: {ended:?}"
933 );
934 for _ in 0..super::ticket::INVALID_BURST {
935 let (_, violations) = host.call(&echo(), &alpha, "cwt.guess", "network").await;
936 ended.extend(violations);
937 }
938 assert_eq!(ended.len(), 1, "a guessed ticket still does: {ended:?}");
939 }
940
940 lines RUST