| 1 | use std::fs; |
| 2 | use std::path::{Path, PathBuf}; |
| 3 | use std::sync::Arc; |
| 4 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 5 | |
| 6 | use codewhale_config::{AppMode, OwnerRef}; |
| 7 | use codewhale_execpolicy::ApprovalMode; |
| 8 | use codewhale_plugins::PluginRegistry; |
| 9 | use codewhale_plugins::activation::TestPolicyGuard; |
| 10 | use codewhale_plugins::discovery::{DiscoveryConfig, discover_with_config}; |
| 11 | use codewhale_plugins::host_services::{ |
| 12 | AgentApproval, AgentPosture, HostService, PersonVia, PluginApprover, ReviewApproval, TestOffer, |
| 13 | }; |
| 14 | use codewhale_skill_install::install::INSTALLED_FROM_MARKER; |
| 15 | use serde_json::{Value, json}; |
| 16 | use tokio_util::sync::CancellationToken; |
| 17 | |
| 18 | use super::super::core_call::{BrokerContext, InvocationGuard}; |
| 19 | use super::super::creator_policy::{ |
| 20 | AdmittedChangeKind, CreatorDecider, CreatorDecisionCarrier, plan_change_async, |
| 21 | }; |
| 22 | use super::super::dsh_broker::{BrokerActTool, TABLE}; |
| 23 | use super::super::protocol::{DshBrokerParams, DshService, RpcErrorWire, error_code}; |
| 24 | use super::super::registry::OwnerState; |
| 25 | use super::super::supervisor::HostRequestContext; |
| 26 | use super::super::test_support::fake_authority; |
| 27 | use super::super::tier::HostCohort; |
| 28 | use super::super::{ExtensionHostManager, ExtensionHostOptions, TestManagerGuard}; |
| 29 | use super::{MAX_TEXT_BYTES, clean_diagnostic_fragment, diagnostic_path, sanitize_inline, serve}; |
| 30 | use crate::core::engine::{HumanDecision, LivePosture, LiveRuntimeAuthority}; |
| 31 | use crate::rlm::session::SessionObjectSnapshot; |
| 32 | use crate::tools::codemode::{ExtensionCaller, NestedCallGate, NestedCallVerdict, NestedDecision}; |
| 33 | use crate::tools::spec::{ToolContext, ToolError}; |
| 34 | |
| 35 | struct PluginsFixture { |
| 36 | _temp: tempfile::TempDir, |
| 37 | config: DiscoveryConfig, |
| 38 | manager: Arc<ExtensionHostManager>, |
| 39 | creator: OwnerRef, |
| 40 | mcp: OwnerRef, |
| 41 | plugin_owner: OwnerRef, |
| 42 | context: ToolContext, |
| 43 | gate: NestedCallGate, |
| 44 | posture: LivePosture, |
| 45 | asked: Arc<AtomicUsize>, |
| 46 | } |
| 47 | |
| 48 | impl PluginsFixture { |
| 49 | fn new() -> Self { |
| 50 | let options = ExtensionHostOptions::default(); |
| 51 | let temp = tempfile::tempdir().expect("tempdir"); |
| 52 | let workspace = temp.path().join("project"); |
| 53 | let user_plugins_dir = temp.path().join("user"); |
| 54 | let workspace_plugins_dir = workspace.join(".codewhale/plugins"); |
| 55 | let builtin_dir = temp.path().join("builtin"); |
| 56 | fs::create_dir_all(&workspace).unwrap(); |
| 57 | fs::create_dir_all(&user_plugins_dir).unwrap(); |
| 58 | fs::create_dir_all(&workspace_plugins_dir).unwrap(); |
| 59 | fs::create_dir_all(&builtin_dir).unwrap(); |
| 60 | let config = DiscoveryConfig { |
| 61 | workspace: workspace.clone(), |
| 62 | user_plugins_dir, |
| 63 | workspace_plugins_dir, |
| 64 | builtin_plugin_dirs: vec![builtin_dir], |
| 65 | state_path: temp.path().join("state/plugin-state.json"), |
| 66 | }; |
| 67 | |
| 68 | let manager = Arc::new(ExtensionHostManager::new(options)); |
| 69 | let (creator, mcp, plugin_owner) = { |
| 70 | let mut registry = manager.shared.registry.lock().unwrap(); |
| 71 | let creator = registry |
| 72 | .begin_owner( |
| 73 | HostCohort::Builtin, |
| 74 | "host:creator", |
| 75 | "creator", |
| 76 | None, |
| 77 | "digest", |
| 78 | ) |
| 79 | .unwrap(); |
| 80 | registry.mark_active(&creator); |
| 81 | let mcp = registry |
| 82 | .begin_owner(HostCohort::Builtin, "host:mcp", "mcp", None, "digest") |
| 83 | .unwrap(); |
| 84 | registry.mark_active(&mcp); |
| 85 | let plugin_owner = registry |
| 86 | .begin_owner( |
| 87 | HostCohort::reviewed(), |
| 88 | "user/hash/alpha", |
| 89 | "alpha", |
| 90 | Some(fake_authority("alpha")), |
| 91 | "hash", |
| 92 | ) |
| 93 | .unwrap(); |
| 94 | registry.mark_active(&plugin_owner); |
| 95 | (creator, mcp, plugin_owner) |
| 96 | }; |
| 97 | |
| 98 | let asked = Arc::new(AtomicUsize::new(0)); |
| 99 | let asked_in_gate = Arc::clone(&asked); |
| 100 | let gate = NestedCallGate::answering_for_test(move |name, input| { |
| 101 | asked_in_gate.fetch_add(1, Ordering::SeqCst); |
| 102 | NestedCallVerdict::Run { |
| 103 | name: name.to_string(), |
| 104 | input: input.clone(), |
| 105 | supports_parallel: false, |
| 106 | decision: NestedDecision::Auto, |
| 107 | hook_context: None, |
| 108 | } |
| 109 | }) |
| 110 | .for_extension( |
| 111 | ExtensionCaller { |
| 112 | origin: "extension:creator".to_string(), |
| 113 | tool: "creator_tool".to_string(), |
| 114 | scope: "ext:host:creator@digest".to_string(), |
| 115 | }, |
| 116 | BrokerActTool::all().to_vec(), |
| 117 | ); |
| 118 | |
| 119 | let posture = LivePosture::for_tests(&workspace, ApprovalMode::Suggest); |
| 120 | let mut context = ToolContext::new(&workspace) |
| 121 | .with_session_objects(SessionObjectSnapshot::new( |
| 122 | "plugins-session".into(), |
| 123 | "fixture-model".into(), |
| 124 | workspace, |
| 125 | None, |
| 126 | Arc::new(Vec::new()), |
| 127 | )) |
| 128 | .with_origin_turn_id("plugins-turn") |
| 129 | .with_origin_tool_call_id("plugins-tool-call"); |
| 130 | context.live_posture = Some(posture.clone()); |
| 131 | |
| 132 | Self { |
| 133 | _temp: temp, |
| 134 | config, |
| 135 | manager, |
| 136 | creator, |
| 137 | mcp, |
| 138 | plugin_owner, |
| 139 | context, |
| 140 | gate, |
| 141 | posture, |
| 142 | asked, |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | fn reload_registry(&mut self) -> Arc<PluginRegistry> { |
| 147 | let registry = Arc::new(discover_with_config(&self.config)); |
| 148 | self.context = self |
| 149 | .context |
| 150 | .clone() |
| 151 | .with_plugin_registry(Arc::clone(®istry)); |
| 152 | registry |
| 153 | } |
| 154 | |
| 155 | fn begin( |
| 156 | &self, |
| 157 | owner: &OwnerRef, |
| 158 | cohort: HostCohort, |
| 159 | context: &ToolContext, |
| 160 | ) -> InvocationGuard { |
| 161 | let caller = self.gate.extension().unwrap().0.clone(); |
| 162 | let services = self.manager.shared.broker_services(owner); |
| 163 | self.manager |
| 164 | .shared |
| 165 | .core_calls |
| 166 | .begin_scoped( |
| 167 | cohort, |
| 168 | 7, |
| 169 | owner, |
| 170 | "call-1", |
| 171 | &caller, |
| 172 | context, |
| 173 | &self.gate, |
| 174 | None, |
| 175 | String::new(), |
| 176 | &services, |
| 177 | ) |
| 178 | .expect("an invocation") |
| 179 | } |
| 180 | |
| 181 | async fn call_broker( |
| 182 | &self, |
| 183 | owner: &OwnerRef, |
| 184 | cohort: HostCohort, |
| 185 | ticket: &str, |
| 186 | method: &str, |
| 187 | input: Value, |
| 188 | ) -> Result<Value, RpcErrorWire> { |
| 189 | let (cx, _violations, _cancel) = HostRequestContext::for_test(100); |
| 190 | self.manager |
| 191 | .shared |
| 192 | .core_calls |
| 193 | .serve_broker_in( |
| 194 | TABLE, |
| 195 | &self.manager.shared, |
| 196 | cohort, |
| 197 | 7, |
| 198 | DshBrokerParams { |
| 199 | owner: owner.clone(), |
| 200 | ticket: ticket.to_string(), |
| 201 | service: "plugins".to_string(), |
| 202 | method: method.to_string(), |
| 203 | input, |
| 204 | }, |
| 205 | cx, |
| 206 | ) |
| 207 | .await |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | fn plugin_ticket(guard: &InvocationGuard) -> Option<String> { |
| 212 | guard |
| 213 | .broker_tickets() |
| 214 | .unwrap_or_default() |
| 215 | .into_iter() |
| 216 | .find(|wire| wire.service == "plugins") |
| 217 | .map(|wire| wire.ticket) |
| 218 | } |
| 219 | |
| 220 | fn write_toml_plugin(root: &Path, dir_name: &str, toml_body: &str) -> PathBuf { |
| 221 | let plugin = root.join(dir_name); |
| 222 | fs::create_dir_all(&plugin).unwrap(); |
| 223 | fs::write(plugin.join("plugin.toml"), toml_body).unwrap(); |
| 224 | plugin |
| 225 | } |
| 226 | |
| 227 | fn write_skill(plugin: &Path, name: &str) { |
| 228 | let dir = plugin.join("skills").join(name); |
| 229 | fs::create_dir_all(&dir).unwrap(); |
| 230 | fs::write( |
| 231 | dir.join("SKILL.md"), |
| 232 | format!("---\nname: {name}\ndescription: test skill\n---\nbody\n"), |
| 233 | ) |
| 234 | .unwrap(); |
| 235 | } |
| 236 | |
| 237 | fn approve_reviewed(registry: &mut PluginRegistry, selector: &str, approver: PluginApprover) { |
| 238 | let token = if matches!(approver, PluginApprover::CommandLine) { |
| 239 | None |
| 240 | } else { |
| 241 | registry |
| 242 | .host_service_review_for(selector, &approver) |
| 243 | .map(|review| review.token) |
| 244 | }; |
| 245 | registry |
| 246 | .trust_reviewed( |
| 247 | selector, |
| 248 | ReviewApproval { |
| 249 | approved_by: approver, |
| 250 | host_services: token, |
| 251 | }, |
| 252 | ) |
| 253 | .unwrap(); |
| 254 | } |
| 255 | |
| 256 | fn refusal(result: &Result<Value, RpcErrorWire>) -> (i64, String) { |
| 257 | let error = result.as_ref().expect_err("expected refusal"); |
| 258 | let code = error |
| 259 | .data |
| 260 | .as_ref() |
| 261 | .and_then(|data| data["dsh_refusal"].as_str()) |
| 262 | .unwrap_or_else(|| panic!("missing dsh_refusal: {error:?}")) |
| 263 | .to_string(); |
| 264 | (error.code, code) |
| 265 | } |
| 266 | |
| 267 | fn detached_call( |
| 268 | owner: OwnerRef, |
| 269 | method: &str, |
| 270 | input: Value, |
| 271 | ) -> super::super::dsh_broker::BrokerCall { |
| 272 | super::super::dsh_broker::BrokerCall { |
| 273 | context: BrokerContext::detached_for_test(&owner, DshService::Plugins), |
| 274 | owner, |
| 275 | session_id: "detached-session".into(), |
| 276 | service: DshService::Plugins, |
| 277 | method: method.into(), |
| 278 | input, |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | #[tokio::test(flavor = "current_thread")] |
| 283 | async fn list_has_one_entry_per_plugin_and_says_who_approved() { |
| 284 | let _policy = TestPolicyGuard::extension_host(true); |
| 285 | let _offer = TestOffer::only(&[HostService::Network]); |
| 286 | let mut f = PluginsFixture::new(); |
| 287 | |
| 288 | let person_dir = write_toml_plugin( |
| 289 | &f.config.user_plugins_dir, |
| 290 | "alpha", |
| 291 | "schema_version = 1\n[plugin]\nname = \"alpha\"\nversion = \"1.2.3\"\ndescription = \"Alpha plugin\"\n[skills]\npath = \"skills\"\n[capabilities]\nhost_services = [\"network\", \"llm\"]\n", |
| 292 | ); |
| 293 | write_skill(&person_dir, "alpha-skill"); |
| 294 | fs::write(person_dir.join(INSTALLED_FROM_MARKER), "local\n").unwrap(); |
| 295 | |
| 296 | let agent_dir = write_toml_plugin( |
| 297 | &f.config.workspace_plugins_dir, |
| 298 | "beta", |
| 299 | "schema_version = 1\n[plugin]\nname = \"beta\"\nversion = \"2.0.0\"\n[commands]\npath = \"commands\"\n", |
| 300 | ); |
| 301 | fs::create_dir_all(agent_dir.join("commands")).unwrap(); |
| 302 | fs::write(agent_dir.join("commands/beta-cmd.md"), "do beta\n").unwrap(); |
| 303 | |
| 304 | let unreviewed_dir = write_toml_plugin( |
| 305 | &f.config.user_plugins_dir, |
| 306 | "gamma", |
| 307 | "schema_version = 1\n[plugin]\nname = \"gamma\"\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n", |
| 308 | ); |
| 309 | write_skill(&unreviewed_dir, "gamma-skill"); |
| 310 | |
| 311 | let builtin_dir = write_toml_plugin( |
| 312 | &f.config.builtin_plugin_dirs[0], |
| 313 | "core-pack", |
| 314 | "schema_version = 1\n[plugin]\nname = \"core-pack\"\nversion = \"0.1.0\"\n[skills]\npath = \"skills\"\n", |
| 315 | ); |
| 316 | write_skill(&builtin_dir, "builtin-skill"); |
| 317 | |
| 318 | let mut registry = discover_with_config(&f.config); |
| 319 | approve_reviewed( |
| 320 | &mut registry, |
| 321 | "alpha", |
| 322 | PluginApprover::person(PersonVia::Terminal), |
| 323 | ); |
| 324 | registry.enable("alpha").unwrap(); |
| 325 | |
| 326 | let agent_approver = PluginApprover::Agent(AgentApproval { |
| 327 | posture: AgentPosture::AutoReview, |
| 328 | workspace: f.config.workspace.to_string_lossy().into_owned(), |
| 329 | thread_id: Some("thread-alpha".into()), |
| 330 | turn_id: Some("turn-alpha".into()), |
| 331 | tool_call_id: Some("call-alpha".into()), |
| 332 | }); |
| 333 | approve_reviewed(&mut registry, "beta", agent_approver.clone()); |
| 334 | registry.enable_by("beta", agent_approver).unwrap(); |
| 335 | |
| 336 | f.reload_registry(); |
| 337 | |
| 338 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 339 | let ticket = plugin_ticket(&guard).unwrap(); |
| 340 | |
| 341 | let listed = f |
| 342 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "list", json!({})) |
| 343 | .await |
| 344 | .unwrap(); |
| 345 | assert_eq!(listed["truncated"], false); |
| 346 | assert!(listed.get("diagnostic").is_none()); |
| 347 | let entries = listed["entries"].as_array().unwrap(); |
| 348 | assert_eq!(entries.len(), 4); |
| 349 | |
| 350 | let find = |name: &str| { |
| 351 | entries |
| 352 | .iter() |
| 353 | .find(|entry| entry["name"] == name) |
| 354 | .unwrap_or_else(|| panic!("missing {name}: {listed}")) |
| 355 | }; |
| 356 | |
| 357 | let alpha = find("alpha"); |
| 358 | assert_eq!(alpha["version"], "1.2.3"); |
| 359 | assert_eq!(alpha["description"], "Alpha plugin"); |
| 360 | assert_eq!(alpha["enabled"], true); |
| 361 | assert_eq!(alpha["installed"], true); |
| 362 | assert_eq!(alpha["removable"], true); |
| 363 | assert!(alpha.get("readOnlyReason").is_none()); |
| 364 | assert_eq!(alpha["availability"], "profile"); |
| 365 | assert_eq!(alpha["official"], false); |
| 366 | assert_eq!(alpha["optional"], false); |
| 367 | assert_eq!(alpha["updatable"], false); |
| 368 | assert_eq!(alpha["overrides"], json!([])); |
| 369 | assert_eq!( |
| 370 | alpha["rows"], |
| 371 | json!([{ |
| 372 | "rowId": "skills", |
| 373 | "moduleName": "alpha/skills", |
| 374 | "entryId": "alpha/skills", |
| 375 | }]) |
| 376 | ); |
| 377 | assert_eq!(alpha["codewhale"]["plugin"], "alpha"); |
| 378 | assert_eq!(alpha["codewhale"]["scope"], "user"); |
| 379 | assert_eq!(alpha["codewhale"]["trust"], "trusted"); |
| 380 | assert_eq!(alpha["codewhale"]["active"], true); |
| 381 | assert_eq!(alpha["codewhale"]["approved_by"]["kind"], "person"); |
| 382 | assert_eq!(alpha["codewhale"]["approved_by"]["via"], "terminal"); |
| 383 | assert_eq!(alpha["codewhale"]["approved_by"]["this_project"], true); |
| 384 | let services = alpha["codewhale"]["services"].as_array().unwrap(); |
| 385 | assert_eq!(services.len(), 2, "{services:?}"); |
| 386 | assert!(services.contains(&json!({"service": "network", "state": "can use"}))); |
| 387 | assert!(services.contains(&json!({ |
| 388 | "service": "llm", |
| 389 | "state": "this version does not offer it", |
| 390 | }))); |
| 391 | |
| 392 | let beta = find("beta"); |
| 393 | assert_eq!(beta["removable"], false); |
| 394 | assert_eq!(beta["availability"], "profile"); |
| 395 | assert_eq!(beta["codewhale"]["scope"], "workspace"); |
| 396 | assert_eq!(beta["codewhale"]["approved_by"]["kind"], "agent"); |
| 397 | assert_eq!(beta["codewhale"]["approved_by"]["posture"], "auto_review"); |
| 398 | assert_eq!(beta["codewhale"]["approved_by"]["this_project"], true); |
| 399 | assert_eq!(beta["codewhale"]["enabled_by"]["kind"], "agent"); |
| 400 | assert_eq!(beta["codewhale"]["enabled_by"]["posture"], "auto_review"); |
| 401 | assert_eq!(beta["codewhale"]["enabled_by"]["this_project"], true); |
| 402 | |
| 403 | let gamma = find("gamma"); |
| 404 | assert_eq!(gamma["enabled"], false); |
| 405 | assert_eq!(gamma["removable"], false); |
| 406 | assert_eq!(gamma["codewhale"]["trust"], "not-reviewed"); |
| 407 | assert_eq!(gamma["codewhale"]["approved_by"], json!(null)); |
| 408 | assert_eq!(gamma["codewhale"]["enabled_by"], json!(null)); |
| 409 | |
| 410 | let builtin = find("core-pack"); |
| 411 | assert_eq!(builtin["availability"], "installation"); |
| 412 | assert_eq!(builtin["removable"], false); |
| 413 | assert_eq!(builtin["readOnlyReason"], "management-required"); |
| 414 | assert_eq!(builtin["codewhale"]["scope"], "builtin"); |
| 415 | |
| 416 | let status = f |
| 417 | .call_broker( |
| 418 | &f.creator, |
| 419 | HostCohort::Builtin, |
| 420 | &ticket, |
| 421 | "status", |
| 422 | json!({}), |
| 423 | ) |
| 424 | .await |
| 425 | .unwrap(); |
| 426 | let status_rows = status["entries"].as_array().unwrap(); |
| 427 | assert_eq!(status_rows.len(), 4); |
| 428 | let alpha_row = status_rows |
| 429 | .iter() |
| 430 | .find(|row| row["entryId"] == "alpha/skills") |
| 431 | .unwrap(); |
| 432 | assert_eq!(alpha_row["patchId"], "alpha"); |
| 433 | assert!(alpha_row.get("readOnlyReason").is_none()); |
| 434 | let builtin_row = status_rows |
| 435 | .iter() |
| 436 | .find(|row| row["entryId"] == "core-pack/skills") |
| 437 | .unwrap(); |
| 438 | assert_eq!(builtin_row["readOnlyReason"], "management-required"); |
| 439 | assert!(builtin_row.get("patchId").is_none()); |
| 440 | } |
| 441 | |
| 442 | #[tokio::test(flavor = "current_thread")] |
| 443 | async fn an_agent_record_of_another_project_shows_no_path_and_no_conversation() { |
| 444 | let _policy = TestPolicyGuard::extension_host(true); |
| 445 | let mut f = PluginsFixture::new(); |
| 446 | |
| 447 | let other_workspace = f._temp.path().join("secret-other-project-workspace-77"); |
| 448 | fs::create_dir_all(&other_workspace).unwrap(); |
| 449 | let plugin_dir = write_toml_plugin( |
| 450 | &f.config.user_plugins_dir, |
| 451 | "shared-agent", |
| 452 | "schema_version = 1\n[plugin]\nname = \"shared-agent\"\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n", |
| 453 | ); |
| 454 | write_skill(&plugin_dir, "other-skill"); |
| 455 | |
| 456 | let other_config = DiscoveryConfig { |
| 457 | workspace: other_workspace.clone(), |
| 458 | ..f.config.clone() |
| 459 | }; |
| 460 | let mut other_registry = discover_with_config(&other_config); |
| 461 | let foreign_thread = "thread-secret-9988"; |
| 462 | let foreign_turn = "turn-secret-7766"; |
| 463 | let foreign_call = "call-secret-5544"; |
| 464 | let foreign_approver = PluginApprover::Agent(AgentApproval { |
| 465 | posture: AgentPosture::FullAccess, |
| 466 | workspace: other_workspace.to_string_lossy().into_owned(), |
| 467 | thread_id: Some(foreign_thread.into()), |
| 468 | turn_id: Some(foreign_turn.into()), |
| 469 | tool_call_id: Some(foreign_call.into()), |
| 470 | }); |
| 471 | approve_reviewed( |
| 472 | &mut other_registry, |
| 473 | "shared-agent", |
| 474 | foreign_approver.clone(), |
| 475 | ); |
| 476 | other_registry |
| 477 | .enable_by("shared-agent", foreign_approver) |
| 478 | .unwrap(); |
| 479 | |
| 480 | f.reload_registry(); |
| 481 | |
| 482 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 483 | let ticket = plugin_ticket(&guard).unwrap(); |
| 484 | |
| 485 | let listed = f |
| 486 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "list", json!({})) |
| 487 | .await |
| 488 | .unwrap(); |
| 489 | let wire = listed.to_string(); |
| 490 | assert!( |
| 491 | !wire.contains("secret-other-project-workspace-77"), |
| 492 | "{wire}" |
| 493 | ); |
| 494 | assert!(!wire.contains(foreign_thread), "{wire}"); |
| 495 | assert!(!wire.contains(foreign_turn), "{wire}"); |
| 496 | assert!(!wire.contains(foreign_call), "{wire}"); |
| 497 | |
| 498 | let entry = &listed["entries"][0]; |
| 499 | assert_eq!(entry["codewhale"]["approved_by"]["kind"], "agent"); |
| 500 | assert_eq!(entry["codewhale"]["approved_by"]["posture"], "full_access"); |
| 501 | assert_eq!(entry["codewhale"]["approved_by"]["this_project"], false); |
| 502 | assert!(entry["codewhale"]["approved_by"].get("workspace").is_none()); |
| 503 | assert!(entry["codewhale"]["approved_by"].get("thread_id").is_none()); |
| 504 | assert!(entry["codewhale"]["approved_by"].get("turn_id").is_none()); |
| 505 | assert!( |
| 506 | entry["codewhale"]["approved_by"] |
| 507 | .get("tool_call_id") |
| 508 | .is_none() |
| 509 | ); |
| 510 | } |
| 511 | |
| 512 | #[tokio::test(flavor = "current_thread")] |
| 513 | async fn status_carries_the_hosts_activation_error() { |
| 514 | let mut f = PluginsFixture::new(); |
| 515 | let _manager = TestManagerGuard::install(Arc::clone(&f.manager)); |
| 516 | let _policy = TestPolicyGuard::extension_host(true); |
| 517 | |
| 518 | let native_dir = write_toml_plugin( |
| 519 | &f.config.user_plugins_dir, |
| 520 | "native-broken", |
| 521 | "schema_version = 1\n[plugin]\nname = \"native-broken\"\nversion = \"0.2.0\"\n[native]\npath = \"index.mjs\"\n[skills]\npath = \"skills\"\n", |
| 522 | ); |
| 523 | fs::write(native_dir.join("index.mjs"), "export function apply() {}\n").unwrap(); |
| 524 | write_skill(&native_dir, "helper-skill"); |
| 525 | |
| 526 | let mut registry = discover_with_config(&f.config); |
| 527 | approve_reviewed( |
| 528 | &mut registry, |
| 529 | "native-broken", |
| 530 | PluginApprover::person(PersonVia::Terminal), |
| 531 | ); |
| 532 | registry.enable("native-broken").unwrap(); |
| 533 | let loaded_registry = f.reload_registry(); |
| 534 | let plugin_id = loaded_registry |
| 535 | .get("native-broken") |
| 536 | .unwrap() |
| 537 | .id |
| 538 | .as_str() |
| 539 | .to_string(); |
| 540 | |
| 541 | { |
| 542 | let mut owners = f.manager.shared.registry.lock().unwrap(); |
| 543 | let owner = owners |
| 544 | .begin_owner( |
| 545 | HostCohort::reviewed(), |
| 546 | &plugin_id, |
| 547 | "native-broken", |
| 548 | Some(fake_authority(&plugin_id)), |
| 549 | "hash", |
| 550 | ) |
| 551 | .unwrap(); |
| 552 | owners.mark_failed(&owner, OwnerState::Failed("boom initializing host".into())); |
| 553 | } |
| 554 | |
| 555 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 556 | let ticket = plugin_ticket(&guard).unwrap(); |
| 557 | |
| 558 | let status_on = f |
| 559 | .call_broker( |
| 560 | &f.creator, |
| 561 | HostCohort::Builtin, |
| 562 | &ticket, |
| 563 | "status", |
| 564 | json!({}), |
| 565 | ) |
| 566 | .await |
| 567 | .unwrap(); |
| 568 | let rows_on = status_on["entries"].as_array().unwrap(); |
| 569 | assert_eq!(rows_on.len(), 2); |
| 570 | let native_on = rows_on |
| 571 | .iter() |
| 572 | .find(|row| row["entryId"] == "native-broken/native/index.mjs") |
| 573 | .unwrap(); |
| 574 | let skill_on = rows_on |
| 575 | .iter() |
| 576 | .find(|row| row["entryId"] == "native-broken/skills") |
| 577 | .unwrap(); |
| 578 | assert_eq!(native_on["enabled"], true); |
| 579 | assert_eq!(native_on["fiberPhase"], "failed"); |
| 580 | assert_eq!(native_on["readOnlyReason"], "unaddressable"); |
| 581 | assert!(native_on.get("patchId").is_none()); |
| 582 | assert!( |
| 583 | native_on["diagnostic"] |
| 584 | .as_str() |
| 585 | .unwrap() |
| 586 | .contains("boom initializing host"), |
| 587 | "{native_on}" |
| 588 | ); |
| 589 | assert_eq!(skill_on["fiberPhase"], json!(null)); |
| 590 | assert_eq!(skill_on["readOnlyReason"], "unaddressable"); |
| 591 | |
| 592 | drop(_policy); |
| 593 | let _policy_off = TestPolicyGuard::extension_host(false); |
| 594 | let status_off = f |
| 595 | .call_broker( |
| 596 | &f.creator, |
| 597 | HostCohort::Builtin, |
| 598 | &ticket, |
| 599 | "status", |
| 600 | json!({}), |
| 601 | ) |
| 602 | .await |
| 603 | .unwrap(); |
| 604 | let native_off = status_off["entries"] |
| 605 | .as_array() |
| 606 | .unwrap() |
| 607 | .iter() |
| 608 | .find(|row| row["entryId"] == "native-broken/native/index.mjs") |
| 609 | .unwrap(); |
| 610 | assert_eq!(native_off["fiberPhase"], json!(null)); |
| 611 | assert!( |
| 612 | native_off["diagnostic"] |
| 613 | .as_str() |
| 614 | .unwrap() |
| 615 | .contains("plugin host is switched off"), |
| 616 | "{native_off}" |
| 617 | ); |
| 618 | } |
| 619 | |
| 620 | #[tokio::test(flavor = "current_thread")] |
| 621 | async fn posture_names_the_live_mode_in_dsh_words() { |
| 622 | let mut f = PluginsFixture::new(); |
| 623 | f.reload_registry(); |
| 624 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 625 | let ticket = plugin_ticket(&guard).unwrap(); |
| 626 | |
| 627 | let cases = [ |
| 628 | (AppMode::Plan, ApprovalMode::Suggest, "read-only", "plan"), |
| 629 | (AppMode::Plan, ApprovalMode::Bypass, "read-only", "plan"), |
| 630 | ( |
| 631 | AppMode::Agent, |
| 632 | ApprovalMode::Suggest, |
| 633 | "workspace-write", |
| 634 | "ask", |
| 635 | ), |
| 636 | ( |
| 637 | AppMode::Agent, |
| 638 | ApprovalMode::AcceptEdits, |
| 639 | "workspace-write", |
| 640 | "accept_edits", |
| 641 | ), |
| 642 | ( |
| 643 | AppMode::Agent, |
| 644 | ApprovalMode::Auto, |
| 645 | "workspace-write", |
| 646 | "auto_review", |
| 647 | ), |
| 648 | ( |
| 649 | AppMode::Agent, |
| 650 | ApprovalMode::Bypass, |
| 651 | "danger-full-access", |
| 652 | "full_access", |
| 653 | ), |
| 654 | ( |
| 655 | AppMode::Agent, |
| 656 | ApprovalMode::Never, |
| 657 | "workspace-write", |
| 658 | "never", |
| 659 | ), |
| 660 | ]; |
| 661 | |
| 662 | for (app_mode, approval_mode, expected_mode, expected_permission) in cases { |
| 663 | f.posture.switch_mode_for_tests(app_mode, approval_mode); |
| 664 | let answer = f |
| 665 | .call_broker( |
| 666 | &f.creator, |
| 667 | HostCohort::Builtin, |
| 668 | &ticket, |
| 669 | "posture", |
| 670 | json!({}), |
| 671 | ) |
| 672 | .await |
| 673 | .unwrap(); |
| 674 | assert_eq!( |
| 675 | answer, |
| 676 | json!({ |
| 677 | "mode": expected_mode, |
| 678 | "permission_mode": expected_permission, |
| 679 | "admitted_by_person": false, |
| 680 | }) |
| 681 | ); |
| 682 | } |
| 683 | drop(guard); |
| 684 | |
| 685 | let admitted = f |
| 686 | .context |
| 687 | .clone() |
| 688 | .with_human_decision(HumanDecision::for_test("creator_tool", &json!({}))); |
| 689 | f.posture |
| 690 | .switch_mode_for_tests(AppMode::Agent, ApprovalMode::Suggest); |
| 691 | let admitted_guard = f.begin(&f.creator, HostCohort::Builtin, &admitted); |
| 692 | let admitted_ticket = plugin_ticket(&admitted_guard).unwrap(); |
| 693 | let answer = f |
| 694 | .call_broker( |
| 695 | &f.creator, |
| 696 | HostCohort::Builtin, |
| 697 | &admitted_ticket, |
| 698 | "posture", |
| 699 | json!({}), |
| 700 | ) |
| 701 | .await |
| 702 | .unwrap(); |
| 703 | assert_eq!( |
| 704 | answer, |
| 705 | json!({ |
| 706 | "mode": "workspace-write", |
| 707 | "permission_mode": "ask", |
| 708 | "admitted_by_person": true, |
| 709 | }) |
| 710 | ); |
| 711 | } |
| 712 | |
| 713 | #[tokio::test(flavor = "current_thread")] |
| 714 | async fn a_read_raises_no_card_in_ask_and_lands_on_the_tool_result() { |
| 715 | let mut f = PluginsFixture::new(); |
| 716 | f.reload_registry(); |
| 717 | f.posture |
| 718 | .switch_mode_for_tests(AppMode::Agent, ApprovalMode::Suggest); |
| 719 | let card_prompts = Arc::new(AtomicUsize::new(0)); |
| 720 | let card_prompts_in_gate = Arc::clone(&card_prompts); |
| 721 | f.gate = NestedCallGate::answering_for_test(move |_, _| { |
| 722 | card_prompts_in_gate.fetch_add(1, Ordering::SeqCst); |
| 723 | NestedCallVerdict::Refused { |
| 724 | error: ToolError::permission_denied("unexpected card"), |
| 725 | decision: NestedDecision::Denied, |
| 726 | } |
| 727 | }) |
| 728 | .for_extension( |
| 729 | ExtensionCaller { |
| 730 | origin: "extension:creator".to_string(), |
| 731 | tool: "creator_tool".to_string(), |
| 732 | scope: "ext:host:creator@digest".to_string(), |
| 733 | }, |
| 734 | BrokerActTool::all().to_vec(), |
| 735 | ); |
| 736 | |
| 737 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 738 | let ticket = plugin_ticket(&guard).unwrap(); |
| 739 | |
| 740 | for method in ["list", "status", "posture"] { |
| 741 | let answer = f |
| 742 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, method, json!({})) |
| 743 | .await; |
| 744 | assert!(answer.is_ok(), "{method}: {answer:?}"); |
| 745 | } |
| 746 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 747 | assert_eq!(card_prompts.load(Ordering::SeqCst), 0); |
| 748 | |
| 749 | let receipts = guard.receipts().expect("receipts"); |
| 750 | assert_eq!(receipts["broker_acts"]["total"], 3, "{receipts}"); |
| 751 | let acts = receipts["broker_acts"]["acts"].as_array().unwrap(); |
| 752 | assert_eq!(acts.len(), 3); |
| 753 | for (act, method) in acts.iter().zip(["list", "status", "posture"]) { |
| 754 | assert_eq!(act["service"], "plugins"); |
| 755 | assert_eq!(act["method"], method); |
| 756 | assert_eq!(act["outcome"], "read"); |
| 757 | } |
| 758 | } |
| 759 | |
| 760 | #[tokio::test(flavor = "current_thread")] |
| 761 | async fn a_wrong_shaped_input_gets_invalid_input() { |
| 762 | let mut f = PluginsFixture::new(); |
| 763 | f.reload_registry(); |
| 764 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 765 | let ticket = plugin_ticket(&guard).unwrap(); |
| 766 | |
| 767 | for method in ["list", "status", "posture"] { |
| 768 | for bad_input in [ |
| 769 | json!({"workspace": "/elsewhere"}), |
| 770 | json!({"session": "other"}), |
| 771 | json!({"offset": 1}), |
| 772 | json!([1]), |
| 773 | json!("bad"), |
| 774 | ] { |
| 775 | let err = f |
| 776 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, method, bad_input) |
| 777 | .await; |
| 778 | assert_eq!( |
| 779 | refusal(&err), |
| 780 | (error_code::INVALID_PARAMS, "invalid_input".into()), |
| 781 | "{method}" |
| 782 | ); |
| 783 | } |
| 784 | } |
| 785 | assert!(guard.receipts().is_none()); |
| 786 | } |
| 787 | |
| 788 | #[tokio::test(flavor = "current_thread")] |
| 789 | async fn a_sub_agent_caller_is_refused() { |
| 790 | let mut f = PluginsFixture::new(); |
| 791 | f.reload_registry(); |
| 792 | |
| 793 | let mut sub_context = f.context.clone(); |
| 794 | sub_context.execution.owner_agent_id = Some("sub-agent-1".into()); |
| 795 | let sub_guard = f.begin(&f.creator, HostCohort::Builtin, &sub_context); |
| 796 | assert!(plugin_ticket(&sub_guard).is_none()); |
| 797 | |
| 798 | let root_guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 799 | let root_ticket = plugin_ticket(&root_guard).unwrap(); |
| 800 | drop(root_guard); |
| 801 | |
| 802 | for method in ["list", "status", "posture"] { |
| 803 | let err = f |
| 804 | .call_broker( |
| 805 | &f.creator, |
| 806 | HostCohort::Builtin, |
| 807 | &root_ticket, |
| 808 | method, |
| 809 | json!({}), |
| 810 | ) |
| 811 | .await; |
| 812 | assert_eq!( |
| 813 | refusal(&err), |
| 814 | (error_code::REFUSED, "ticket_refused".into()), |
| 815 | "{method}" |
| 816 | ); |
| 817 | } |
| 818 | assert!(sub_guard.receipts().is_none()); |
| 819 | } |
| 820 | |
| 821 | #[tokio::test(flavor = "current_thread")] |
| 822 | async fn an_owner_that_is_not_the_creator_module_is_refused() { |
| 823 | let mut f = PluginsFixture::new(); |
| 824 | f.reload_registry(); |
| 825 | |
| 826 | { |
| 827 | let mut owners = f.manager.shared.registry.lock().unwrap(); |
| 828 | let forged_err = owners |
| 829 | .begin_owner( |
| 830 | HostCohort::reviewed(), |
| 831 | "host:creator", |
| 832 | "forged-creator", |
| 833 | Some(fake_authority("forged-creator")), |
| 834 | "hash", |
| 835 | ) |
| 836 | .unwrap_err(); |
| 837 | assert!(forged_err.contains("host:creator"), "{forged_err}"); |
| 838 | } |
| 839 | |
| 840 | let plugin_guard = f.begin(&f.plugin_owner, HostCohort::reviewed(), &f.context); |
| 841 | assert!(plugin_ticket(&plugin_guard).is_none()); |
| 842 | let mcp_guard = f.begin(&f.mcp, HostCohort::Builtin, &f.context); |
| 843 | assert!(plugin_ticket(&mcp_guard).is_none()); |
| 844 | |
| 845 | let forged_owner = OwnerRef { |
| 846 | plugin_id: "host:creator".into(), |
| 847 | generation: 99, |
| 848 | owner_token: "forged-token".into(), |
| 849 | }; |
| 850 | |
| 851 | let creator_guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 852 | let creator_ticket = plugin_ticket(&creator_guard).unwrap(); |
| 853 | |
| 854 | for method in ["list", "status", "posture"] { |
| 855 | for (owner, tier) in [ |
| 856 | (&f.plugin_owner, HostCohort::reviewed()), |
| 857 | (&f.mcp, HostCohort::Builtin), |
| 858 | (&forged_owner, HostCohort::reviewed()), |
| 859 | ] { |
| 860 | let err = f |
| 861 | .call_broker(owner, tier, &creator_ticket, method, json!({})) |
| 862 | .await; |
| 863 | assert_eq!( |
| 864 | refusal(&err), |
| 865 | (error_code::REFUSED, "ticket_refused".into()), |
| 866 | "{owner:?} {method}" |
| 867 | ); |
| 868 | } |
| 869 | |
| 870 | for owner in [&f.plugin_owner, &f.mcp] { |
| 871 | let arm_err = serve(detached_call(owner.clone(), method, json!({}))).await; |
| 872 | assert!( |
| 873 | matches!( |
| 874 | arm_err, |
| 875 | Err(super::super::dsh_broker::BrokerRefusal::Refused { |
| 876 | service: DshService::Plugins, |
| 877 | .. |
| 878 | }) |
| 879 | ), |
| 880 | "{owner:?} {method}: {arm_err:?}" |
| 881 | ); |
| 882 | } |
| 883 | } |
| 884 | assert!(creator_guard.receipts().is_none()); |
| 885 | } |
| 886 | |
| 887 | #[tokio::test(flavor = "current_thread")] |
| 888 | async fn a_session_without_a_registry_answers_not_available() { |
| 889 | let f = PluginsFixture::new(); |
| 890 | assert!(f.context.plugin_registry.is_none()); |
| 891 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 892 | let ticket = plugin_ticket(&guard).unwrap(); |
| 893 | |
| 894 | for method in ["list", "status"] { |
| 895 | let err = f |
| 896 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, method, json!({})) |
| 897 | .await; |
| 898 | assert_eq!( |
| 899 | refusal(&err), |
| 900 | (error_code::NOT_AVAILABLE, "not_available".into()), |
| 901 | "{method}" |
| 902 | ); |
| 903 | } |
| 904 | |
| 905 | let mut no_posture = f.context.clone(); |
| 906 | no_posture.live_posture = None; |
| 907 | no_posture.plugin_registry = Some(Arc::new(discover_with_config(&f.config))); |
| 908 | let no_posture_guard = f.begin(&f.creator, HostCohort::Builtin, &no_posture); |
| 909 | let no_posture_ticket = plugin_ticket(&no_posture_guard).unwrap(); |
| 910 | let err = f |
| 911 | .call_broker( |
| 912 | &f.creator, |
| 913 | HostCohort::Builtin, |
| 914 | &no_posture_ticket, |
| 915 | "posture", |
| 916 | json!({}), |
| 917 | ) |
| 918 | .await; |
| 919 | assert_eq!( |
| 920 | refusal(&err), |
| 921 | (error_code::NOT_AVAILABLE, "not_available".into()) |
| 922 | ); |
| 923 | } |
| 924 | |
| 925 | #[tokio::test(flavor = "current_thread")] |
| 926 | async fn a_long_list_is_cut_and_says_so() { |
| 927 | let mut f = PluginsFixture::new(); |
| 928 | let skill_paths: Vec<String> = (0..35).map(|idx| format!("skills/s{idx:02}")).collect(); |
| 929 | let command_paths: Vec<String> = (0..35).map(|idx| format!("commands/c{idx:02}")).collect(); |
| 930 | let big_manifest = format!( |
| 931 | "schema_version = 1\n[plugin]\nname = \"many-rows\"\nversion = \"1.0.0\"\n[skills]\npaths = {skill_paths:?}\n[commands]\npaths = {command_paths:?}\n" |
| 932 | ); |
| 933 | let big_dir = write_toml_plugin(&f.config.user_plugins_dir, "many-rows", &big_manifest); |
| 934 | for rel in skill_paths.iter().chain(command_paths.iter()) { |
| 935 | fs::create_dir_all(big_dir.join(rel)).unwrap(); |
| 936 | } |
| 937 | |
| 938 | f.reload_registry(); |
| 939 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 940 | let ticket = plugin_ticket(&guard).unwrap(); |
| 941 | |
| 942 | let single_listed = f |
| 943 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "list", json!({})) |
| 944 | .await |
| 945 | .unwrap(); |
| 946 | assert_eq!(single_listed["truncated"], true); |
| 947 | assert_eq!( |
| 948 | single_listed["entries"][0]["rows"] |
| 949 | .as_array() |
| 950 | .unwrap() |
| 951 | .len(), |
| 952 | 64 |
| 953 | ); |
| 954 | |
| 955 | let single_status = f |
| 956 | .call_broker( |
| 957 | &f.creator, |
| 958 | HostCohort::Builtin, |
| 959 | &ticket, |
| 960 | "status", |
| 961 | json!({}), |
| 962 | ) |
| 963 | .await |
| 964 | .unwrap(); |
| 965 | assert_eq!(single_status["truncated"], false); |
| 966 | assert_eq!(single_status["entries"].as_array().unwrap().len(), 70); |
| 967 | |
| 968 | for idx in 0..105 { |
| 969 | let name = format!("pack-{idx:03}"); |
| 970 | let dir = write_toml_plugin( |
| 971 | &f.config.user_plugins_dir, |
| 972 | &name, |
| 973 | &format!( |
| 974 | "schema_version = 1\n[plugin]\nname = {name:?}\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n" |
| 975 | ), |
| 976 | ); |
| 977 | write_skill(&dir, "s1"); |
| 978 | } |
| 979 | |
| 980 | drop(guard); |
| 981 | f.reload_registry(); |
| 982 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 983 | let ticket = plugin_ticket(&guard).unwrap(); |
| 984 | |
| 985 | let listed = f |
| 986 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "list", json!({})) |
| 987 | .await |
| 988 | .unwrap(); |
| 989 | assert_eq!(listed["truncated"], true); |
| 990 | assert_eq!(listed["entries"].as_array().unwrap().len(), 100); |
| 991 | |
| 992 | let status = f |
| 993 | .call_broker( |
| 994 | &f.creator, |
| 995 | HostCohort::Builtin, |
| 996 | &ticket, |
| 997 | "status", |
| 998 | json!({}), |
| 999 | ) |
| 1000 | .await |
| 1001 | .unwrap(); |
| 1002 | assert_eq!(status["truncated"], true); |
| 1003 | assert_eq!(status["entries"].as_array().unwrap().len(), 100); |
| 1004 | } |
| 1005 | |
| 1006 | #[tokio::test(flavor = "current_thread")] |
| 1007 | async fn changing_methods_reject_unknown_fields_and_missing_registry_or_posture() { |
| 1008 | let mut f = PluginsFixture::new(); |
| 1009 | let no_registry_guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 1010 | let no_registry_ticket = plugin_ticket(&no_registry_guard).unwrap(); |
| 1011 | for (method, input) in [ |
| 1012 | ("install", json!({"target": "alpha"})), |
| 1013 | ("remove", json!({"target": "alpha"})), |
| 1014 | ("enable", json!({"target": "alpha"})), |
| 1015 | ("disable", json!({"target": "alpha"})), |
| 1016 | ] { |
| 1017 | let err = f |
| 1018 | .call_broker( |
| 1019 | &f.creator, |
| 1020 | HostCohort::Builtin, |
| 1021 | &no_registry_ticket, |
| 1022 | method, |
| 1023 | input, |
| 1024 | ) |
| 1025 | .await; |
| 1026 | assert_eq!( |
| 1027 | refusal(&err), |
| 1028 | (error_code::NOT_AVAILABLE, "not_available".into()), |
| 1029 | "missing registry {method}" |
| 1030 | ); |
| 1031 | } |
| 1032 | drop(no_registry_guard); |
| 1033 | |
| 1034 | f.reload_registry(); |
| 1035 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 1036 | let ticket = plugin_ticket(&guard).unwrap(); |
| 1037 | |
| 1038 | for (method, input) in [ |
| 1039 | ("install", json!({"target": "alpha", "extra": 1})), |
| 1040 | ("remove", json!({"target": "alpha", "extra": 1})), |
| 1041 | ("enable", json!({"target": "alpha", "extra": 1})), |
| 1042 | ("disable", json!({"target": "alpha", "extra": 1})), |
| 1043 | ("install", json!({})), |
| 1044 | ("remove", json!({})), |
| 1045 | ("enable", json!({})), |
| 1046 | ("disable", json!({})), |
| 1047 | ] { |
| 1048 | let err = f |
| 1049 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, method, input) |
| 1050 | .await; |
| 1051 | assert_eq!( |
| 1052 | refusal(&err), |
| 1053 | (error_code::INVALID_PARAMS, "invalid_input".into()), |
| 1054 | "schema {method}" |
| 1055 | ); |
| 1056 | } |
| 1057 | |
| 1058 | let mut no_posture = f.context.clone(); |
| 1059 | no_posture.live_posture = None; |
| 1060 | let np_guard = f.begin(&f.creator, HostCohort::Builtin, &no_posture); |
| 1061 | let np_ticket = plugin_ticket(&np_guard).unwrap(); |
| 1062 | for method in ["install", "remove", "enable", "disable"] { |
| 1063 | let err = f |
| 1064 | .call_broker( |
| 1065 | &f.creator, |
| 1066 | HostCohort::Builtin, |
| 1067 | &np_ticket, |
| 1068 | method, |
| 1069 | json!({"target": "alpha"}), |
| 1070 | ) |
| 1071 | .await; |
| 1072 | assert_eq!( |
| 1073 | refusal(&err), |
| 1074 | (error_code::NOT_AVAILABLE, "not_available".into()), |
| 1075 | "no posture {method}" |
| 1076 | ); |
| 1077 | } |
| 1078 | assert!(guard.receipts().is_none()); |
| 1079 | } |
| 1080 | |
| 1081 | #[tokio::test(flavor = "current_thread")] |
| 1082 | async fn a_state_error_lists_plugins_as_disabled_with_scrubbed_top_diagnostic() { |
| 1083 | let mut f = PluginsFixture::new(); |
| 1084 | let dir = write_toml_plugin( |
| 1085 | &f.config.user_plugins_dir, |
| 1086 | "corrupt-state-plugin", |
| 1087 | "schema_version = 1\n[plugin]\nname = \"corrupt-state-plugin\"\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n", |
| 1088 | ); |
| 1089 | write_skill(&dir, "s1"); |
| 1090 | |
| 1091 | let mut clean = discover_with_config(&f.config); |
| 1092 | approve_reviewed( |
| 1093 | &mut clean, |
| 1094 | "corrupt-state-plugin", |
| 1095 | PluginApprover::person(PersonVia::Terminal), |
| 1096 | ); |
| 1097 | clean.enable("corrupt-state-plugin").unwrap(); |
| 1098 | fs::write(&f.config.state_path, "{ not valid json sk-secret-123456").unwrap(); |
| 1099 | |
| 1100 | let broken = f.reload_registry(); |
| 1101 | assert!(broken.state_error().is_some()); |
| 1102 | |
| 1103 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 1104 | let ticket = plugin_ticket(&guard).unwrap(); |
| 1105 | |
| 1106 | let listed = f |
| 1107 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "list", json!({})) |
| 1108 | .await |
| 1109 | .unwrap(); |
| 1110 | assert_eq!(listed["entries"][0]["enabled"], false); |
| 1111 | assert_eq!(listed["entries"][0]["codewhale"]["active"], false); |
| 1112 | assert_eq!( |
| 1113 | listed["entries"][0]["codewhale"]["approved_by"], |
| 1114 | json!(null) |
| 1115 | ); |
| 1116 | assert_eq!(listed["entries"][0]["codewhale"]["enabled_by"], json!(null)); |
| 1117 | assert_eq!(listed["entries"][0]["codewhale"]["services"], json!([])); |
| 1118 | let diag = listed["diagnostic"].as_str().unwrap(); |
| 1119 | assert!( |
| 1120 | !diag.contains(f._temp.path().to_string_lossy().as_ref()), |
| 1121 | "{diag}" |
| 1122 | ); |
| 1123 | |
| 1124 | let status = f |
| 1125 | .call_broker( |
| 1126 | &f.creator, |
| 1127 | HostCohort::Builtin, |
| 1128 | &ticket, |
| 1129 | "status", |
| 1130 | json!({}), |
| 1131 | ) |
| 1132 | .await |
| 1133 | .unwrap(); |
| 1134 | assert_eq!(status["entries"][0]["enabled"], false); |
| 1135 | assert_eq!(status["entries"][0]["fiberPhase"], json!(null)); |
| 1136 | assert!(status["diagnostic"].is_string()); |
| 1137 | } |
| 1138 | |
| 1139 | #[tokio::test(flavor = "current_thread")] |
| 1140 | async fn fifty_reads_hit_the_per_call_ceiling() { |
| 1141 | let mut f = PluginsFixture::new(); |
| 1142 | f.reload_registry(); |
| 1143 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 1144 | let ticket = plugin_ticket(&guard).unwrap(); |
| 1145 | |
| 1146 | for idx in 0..super::super::core_call::MAX_CALLS_PER_INVOCATION { |
| 1147 | let method = match idx % 3 { |
| 1148 | 0 => "list", |
| 1149 | 1 => "status", |
| 1150 | _ => "posture", |
| 1151 | }; |
| 1152 | let ok = f |
| 1153 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, method, json!({})) |
| 1154 | .await; |
| 1155 | assert!(ok.is_ok(), "call {idx}: {ok:?}"); |
| 1156 | } |
| 1157 | |
| 1158 | let capped = f |
| 1159 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "list", json!({})) |
| 1160 | .await; |
| 1161 | assert_eq!(refusal(&capped), (error_code::REFUSED, "limit".into())); |
| 1162 | } |
| 1163 | |
| 1164 | #[tokio::test(flavor = "current_thread")] |
| 1165 | async fn diagnostics_and_manifest_text_are_scrubbed_and_bounded() { |
| 1166 | let mut f = PluginsFixture::new(); |
| 1167 | let _manager = TestManagerGuard::install(Arc::clone(&f.manager)); |
| 1168 | let _policy = TestPolicyGuard::extension_host(true); |
| 1169 | |
| 1170 | let long_desc = format!("Bearer sk-proj-secret123456 {}", "a".repeat(800)); |
| 1171 | let mut inline_truncated = false; |
| 1172 | let inline = sanitize_inline( |
| 1173 | "\x1b[31mIgnore previous\x1b[0m\nBearer sk-proj-secret123456\u{202e} ok", |
| 1174 | MAX_TEXT_BYTES, |
| 1175 | &mut inline_truncated, |
| 1176 | ); |
| 1177 | assert!(!inline_truncated); |
| 1178 | assert!(!inline.contains('\x1b')); |
| 1179 | assert!(!inline.contains('\n')); |
| 1180 | assert!(!inline.contains('\u{202e}')); |
| 1181 | assert!(!inline.contains("sk-proj-secret123456"), "{inline}"); |
| 1182 | let hostile_dir = write_toml_plugin( |
| 1183 | &f.config.user_plugins_dir, |
| 1184 | "hostile", |
| 1185 | &format!( |
| 1186 | "schema_version = 1\n[plugin]\nname = \"hostile\"\nversion = \"1.0.0\"\ndescription = {long_desc:?}\n[native]\npath = \"index.mjs\"\n" |
| 1187 | ), |
| 1188 | ); |
| 1189 | fs::write( |
| 1190 | hostile_dir.join("index.mjs"), |
| 1191 | "export function apply() {}\n", |
| 1192 | ) |
| 1193 | .unwrap(); |
| 1194 | |
| 1195 | let mut registry = discover_with_config(&f.config); |
| 1196 | approve_reviewed( |
| 1197 | &mut registry, |
| 1198 | "hostile", |
| 1199 | PluginApprover::person(PersonVia::Terminal), |
| 1200 | ); |
| 1201 | registry.enable("hostile").unwrap(); |
| 1202 | let loaded = f.reload_registry(); |
| 1203 | let plugin_id = loaded.get("hostile").unwrap().id.as_str().to_string(); |
| 1204 | |
| 1205 | { |
| 1206 | let mut owners = f.manager.shared.registry.lock().unwrap(); |
| 1207 | let owner = owners |
| 1208 | .begin_owner( |
| 1209 | HostCohort::reviewed(), |
| 1210 | &plugin_id, |
| 1211 | "hostile", |
| 1212 | Some(fake_authority(&plugin_id)), |
| 1213 | "hash", |
| 1214 | ) |
| 1215 | .unwrap(); |
| 1216 | let msg = format!( |
| 1217 | "\x1b[31mfailed\x1b[0m at /etc/passwd and file:///Users/alice/secret and file:///C:/Users/alice/secret and `/Users/alice/backtick` and </Users/alice/angle> and {}/native/index.mjs Bearer sk-proj-secret123456 \u{202e}https://example.com/docs/a {}", |
| 1218 | loaded.get("hostile").unwrap().canonical_root.display(), |
| 1219 | "z".repeat(1200) |
| 1220 | ); |
| 1221 | owners.mark_failed(&owner, OwnerState::Failed(msg)); |
| 1222 | } |
| 1223 | |
| 1224 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 1225 | let ticket = plugin_ticket(&guard).unwrap(); |
| 1226 | |
| 1227 | let listed = f |
| 1228 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "list", json!({})) |
| 1229 | .await |
| 1230 | .unwrap(); |
| 1231 | assert_eq!(listed["truncated"], true); |
| 1232 | let desc = listed["entries"][0]["description"].as_str().unwrap(); |
| 1233 | assert!(desc.len() <= 512, "{desc}"); |
| 1234 | assert!(!desc.contains('\x1b')); |
| 1235 | assert!(!desc.contains('\n')); |
| 1236 | assert!(!desc.contains('\u{202e}')); |
| 1237 | assert!(!desc.contains("sk-proj-secret123456"), "{desc}"); |
| 1238 | |
| 1239 | let status = f |
| 1240 | .call_broker( |
| 1241 | &f.creator, |
| 1242 | HostCohort::Builtin, |
| 1243 | &ticket, |
| 1244 | "status", |
| 1245 | json!({}), |
| 1246 | ) |
| 1247 | .await |
| 1248 | .unwrap(); |
| 1249 | assert_eq!(status["truncated"], true); |
| 1250 | let diag = status["entries"][0]["diagnostic"].as_str().unwrap(); |
| 1251 | assert!(diag.len() <= 1024, "{diag}"); |
| 1252 | assert!(!diag.contains("/etc/passwd"), "{diag}"); |
| 1253 | assert!(!diag.contains("file://"), "{diag}"); |
| 1254 | assert!(!diag.contains("/Users/alice"), "{diag}"); |
| 1255 | assert!(!diag.contains("C:/Users/alice"), "{diag}"); |
| 1256 | assert!(!diag.contains("backtick"), "{diag}"); |
| 1257 | assert!(!diag.contains("angle"), "{diag}"); |
| 1258 | assert!(diag.contains("<outside-path>"), "{diag}"); |
| 1259 | assert!(!diag.contains("sk-proj-secret123456"), "{diag}"); |
| 1260 | assert!(!diag.contains('\x1b')); |
| 1261 | assert!(!diag.contains('\u{202e}')); |
| 1262 | assert!(diag.contains("https://example.com/docs/a"), "{diag}"); |
| 1263 | assert!(diag.contains("native/index.mjs"), "{diag}"); |
| 1264 | |
| 1265 | let extra = clean_diagnostic_fragment( |
| 1266 | "bad={/var/secret} and|<file:///C:/Users/alice/win> and|C:\\Users\\alice\\win2", |
| 1267 | ); |
| 1268 | assert!(!extra.contains("/var/secret"), "{extra}"); |
| 1269 | assert!(!extra.contains("file://"), "{extra}"); |
| 1270 | assert!(!extra.contains("Users"), "{extra}"); |
| 1271 | assert!(extra.contains("<outside-path>"), "{extra}"); |
| 1272 | assert_eq!( |
| 1273 | diagnostic_path( |
| 1274 | Path::new("/private/var/tmp/p"), |
| 1275 | Path::new("/var/tmp/p/plugin.toml") |
| 1276 | ), |
| 1277 | "plugin.toml" |
| 1278 | ); |
| 1279 | assert_eq!( |
| 1280 | diagnostic_path( |
| 1281 | Path::new("/private/var/tmp/p"), |
| 1282 | Path::new("/private/var/tmp/p/../../etc/passwd") |
| 1283 | ), |
| 1284 | "<outside-path>" |
| 1285 | ); |
| 1286 | } |
| 1287 | |
| 1288 | #[cfg(unix)] |
| 1289 | #[tokio::test(flavor = "current_thread")] |
| 1290 | async fn symlinked_install_record_does_not_mark_user_plugin_removable() { |
| 1291 | let mut f = PluginsFixture::new(); |
| 1292 | let plugin_dir = write_toml_plugin( |
| 1293 | &f.config.user_plugins_dir, |
| 1294 | "sym-user", |
| 1295 | "schema_version = 1\n[plugin]\nname = \"sym-user\"\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n", |
| 1296 | ); |
| 1297 | write_skill(&plugin_dir, "s1"); |
| 1298 | f.reload_registry(); |
| 1299 | let target = f._temp.path().join("outside-marker"); |
| 1300 | fs::write(&target, "local\n").unwrap(); |
| 1301 | std::os::unix::fs::symlink(&target, plugin_dir.join(INSTALLED_FROM_MARKER)).unwrap(); |
| 1302 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 1303 | let ticket = plugin_ticket(&guard).unwrap(); |
| 1304 | |
| 1305 | let listed = f |
| 1306 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "list", json!({})) |
| 1307 | .await |
| 1308 | .unwrap(); |
| 1309 | assert_eq!(listed["entries"].as_array().unwrap().len(), 1); |
| 1310 | assert_eq!(listed["entries"][0]["name"], "sym-user"); |
| 1311 | assert_eq!(listed["entries"][0]["removable"], false); |
| 1312 | } |
| 1313 | |
| 1314 | #[tokio::test(flavor = "current_thread")] |
| 1315 | async fn status_keeps_later_plugins_when_an_earlier_plugin_truncates_a_field() { |
| 1316 | let mut f = PluginsFixture::new(); |
| 1317 | let _manager = TestManagerGuard::install(Arc::clone(&f.manager)); |
| 1318 | let _policy = TestPolicyGuard::extension_host(true); |
| 1319 | |
| 1320 | let first_dir = write_toml_plugin( |
| 1321 | &f.config.user_plugins_dir, |
| 1322 | "00-hostile", |
| 1323 | "schema_version = 1\n[plugin]\nname = \"00-hostile\"\nversion = \"1.0.0\"\n[native]\npath = \"index.mjs\"\n", |
| 1324 | ); |
| 1325 | fs::write(first_dir.join("index.mjs"), "export function apply() {}\n").unwrap(); |
| 1326 | |
| 1327 | let second_dir = write_toml_plugin( |
| 1328 | &f.config.workspace_plugins_dir, |
| 1329 | "zz-healthy", |
| 1330 | "schema_version = 1\n[plugin]\nname = \"zz-healthy\"\nversion = \"1.0.0\"\n[native]\npath = \"index.mjs\"\n", |
| 1331 | ); |
| 1332 | fs::write(second_dir.join("index.mjs"), "export function apply() {}\n").unwrap(); |
| 1333 | |
| 1334 | let mut registry = discover_with_config(&f.config); |
| 1335 | for name in ["00-hostile", "zz-healthy"] { |
| 1336 | approve_reviewed( |
| 1337 | &mut registry, |
| 1338 | name, |
| 1339 | PluginApprover::person(PersonVia::Terminal), |
| 1340 | ); |
| 1341 | registry.enable(name).unwrap(); |
| 1342 | } |
| 1343 | let loaded = f.reload_registry(); |
| 1344 | let first_id = loaded.get("00-hostile").unwrap().id.as_str().to_string(); |
| 1345 | let second_id = loaded.get("zz-healthy").unwrap().id.as_str().to_string(); |
| 1346 | |
| 1347 | { |
| 1348 | let mut owners = f.manager.shared.registry.lock().unwrap(); |
| 1349 | let first_owner = owners |
| 1350 | .begin_owner( |
| 1351 | HostCohort::reviewed(), |
| 1352 | &first_id, |
| 1353 | "00-hostile", |
| 1354 | Some(fake_authority(&first_id)), |
| 1355 | "hash-1", |
| 1356 | ) |
| 1357 | .unwrap(); |
| 1358 | owners.mark_failed(&first_owner, OwnerState::Failed("boom ".repeat(300))); |
| 1359 | |
| 1360 | let second_owner = owners |
| 1361 | .begin_owner( |
| 1362 | HostCohort::reviewed(), |
| 1363 | &second_id, |
| 1364 | "zz-healthy", |
| 1365 | Some(fake_authority(&second_id)), |
| 1366 | "hash-2", |
| 1367 | ) |
| 1368 | .unwrap(); |
| 1369 | owners.mark_active(&second_owner); |
| 1370 | } |
| 1371 | f.manager.shared.plugin_diagnostic( |
| 1372 | &second_id, |
| 1373 | "plugin `zz-healthy` active (tools: ping; commands: )".into(), |
| 1374 | ); |
| 1375 | |
| 1376 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 1377 | let ticket = plugin_ticket(&guard).unwrap(); |
| 1378 | let status = f |
| 1379 | .call_broker( |
| 1380 | &f.creator, |
| 1381 | HostCohort::Builtin, |
| 1382 | &ticket, |
| 1383 | "status", |
| 1384 | json!({}), |
| 1385 | ) |
| 1386 | .await |
| 1387 | .unwrap(); |
| 1388 | assert_eq!(status["truncated"], true); |
| 1389 | let rows = status["entries"].as_array().unwrap(); |
| 1390 | assert_eq!(rows.len(), 2, "{status}"); |
| 1391 | assert_eq!(rows[0]["entryId"], "00-hostile/native/index.mjs"); |
| 1392 | assert_eq!(rows[0]["fiberPhase"], "failed"); |
| 1393 | assert!(rows[0]["diagnostic"].as_str().unwrap().len() <= 1024); |
| 1394 | assert_eq!(rows[1]["entryId"], "zz-healthy/native/index.mjs"); |
| 1395 | assert_eq!(rows[1]["fiberPhase"], "active"); |
| 1396 | assert!(rows[1].get("diagnostic").is_none(), "{rows:?}"); |
| 1397 | } |
| 1398 | |
| 1399 | #[tokio::test(flavor = "current_thread")] |
| 1400 | async fn plugins_tools_returns_the_invocation_caller_tools() { |
| 1401 | let _policy = TestPolicyGuard::extension_host(true); |
| 1402 | let mut f = PluginsFixture::new(); |
| 1403 | let specs = crate::tools::registry::ToolRegistryBuilder::new() |
| 1404 | .with_file_tools() |
| 1405 | .build(ToolContext::new(f.context.workspace.clone())) |
| 1406 | .all(); |
| 1407 | let caller = f.gate.extension().unwrap().0.clone(); |
| 1408 | f.gate = f.gate.clone().for_extension(caller, specs); |
| 1409 | |
| 1410 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 1411 | let ticket = plugin_ticket(&guard).unwrap(); |
| 1412 | let answer = f |
| 1413 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "tools", json!({})) |
| 1414 | .await |
| 1415 | .unwrap(); |
| 1416 | let names = answer["names"].as_array().unwrap(); |
| 1417 | assert!(names.iter().any(|name| name.as_str() == Some("read_file"))); |
| 1418 | assert!(names.iter().any(|name| name.as_str() == Some("write_file"))); |
| 1419 | } |
| 1420 | |
| 1421 | #[tokio::test(flavor = "current_thread")] |
| 1422 | async fn plugins_tools_leaves_out_hidden_and_disallowed_tools() { |
| 1423 | let _policy = TestPolicyGuard::extension_host(true); |
| 1424 | let mut f = PluginsFixture::new(); |
| 1425 | let mut specs = crate::tools::registry::ToolRegistryBuilder::new() |
| 1426 | .with_file_tools() |
| 1427 | .build(ToolContext::new(f.context.workspace.clone())) |
| 1428 | .all(); |
| 1429 | specs.extend(BrokerActTool::all().to_vec()); |
| 1430 | let caller = f.gate.extension().unwrap().0.clone(); |
| 1431 | f.gate = f.gate.clone().for_extension(caller, specs); |
| 1432 | f.context.disallowed_tools = vec!["read_file".to_string()]; |
| 1433 | |
| 1434 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 1435 | let ticket = plugin_ticket(&guard).unwrap(); |
| 1436 | let answer = f |
| 1437 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "tools", json!({})) |
| 1438 | .await |
| 1439 | .unwrap(); |
| 1440 | let names = answer["names"].as_array().unwrap(); |
| 1441 | assert!(!names.iter().any(|name| name.as_str() == Some("read_file"))); |
| 1442 | assert!( |
| 1443 | !names |
| 1444 | .iter() |
| 1445 | .any(|name| name.as_str() == Some("dsh_broker_act")) |
| 1446 | ); |
| 1447 | assert!( |
| 1448 | !names |
| 1449 | .iter() |
| 1450 | .any(|name| name.as_str() == Some("dsh_broker_reach")) |
| 1451 | ); |
| 1452 | assert!(names.iter().any(|name| name.as_str() == Some("write_file"))); |
| 1453 | } |
| 1454 | |
| 1455 | #[tokio::test(flavor = "current_thread")] |
| 1456 | async fn plugins_tools_is_refused_for_a_plugin_tier_owner_and_a_sub_agent() { |
| 1457 | let _policy = TestPolicyGuard::extension_host(true); |
| 1458 | let f = PluginsFixture::new(); |
| 1459 | |
| 1460 | let guard = f.begin(&f.plugin_owner, HostCohort::reviewed(), &f.context); |
| 1461 | assert!(plugin_ticket(&guard).is_none()); |
| 1462 | |
| 1463 | let mut sub_context = f.context.clone(); |
| 1464 | sub_context.execution.owner_agent_id = Some("sub-agent-1".into()); |
| 1465 | let sub_guard = f.begin(&f.creator, HostCohort::Builtin, &sub_context); |
| 1466 | assert!(plugin_ticket(&sub_guard).is_none()); |
| 1467 | |
| 1468 | let creator_guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 1469 | let creator_ticket = plugin_ticket(&creator_guard).unwrap(); |
| 1470 | let plugin_err = f |
| 1471 | .call_broker( |
| 1472 | &f.plugin_owner, |
| 1473 | HostCohort::reviewed(), |
| 1474 | &creator_ticket, |
| 1475 | "tools", |
| 1476 | json!({}), |
| 1477 | ) |
| 1478 | .await; |
| 1479 | assert_eq!( |
| 1480 | refusal(&plugin_err), |
| 1481 | (error_code::REFUSED, "ticket_refused".into()) |
| 1482 | ); |
| 1483 | let arm_err = serve(detached_call(f.plugin_owner.clone(), "tools", json!({}))).await; |
| 1484 | assert!(matches!( |
| 1485 | arm_err, |
| 1486 | Err(super::super::dsh_broker::BrokerRefusal::Refused { |
| 1487 | service: DshService::Plugins, |
| 1488 | .. |
| 1489 | }) |
| 1490 | )); |
| 1491 | drop(creator_guard); |
| 1492 | let revoked_err = f |
| 1493 | .call_broker( |
| 1494 | &f.creator, |
| 1495 | HostCohort::Builtin, |
| 1496 | &creator_ticket, |
| 1497 | "tools", |
| 1498 | json!({}), |
| 1499 | ) |
| 1500 | .await; |
| 1501 | assert_eq!( |
| 1502 | refusal(&revoked_err), |
| 1503 | (error_code::REFUSED, "ticket_refused".into()) |
| 1504 | ); |
| 1505 | } |
| 1506 | |
| 1507 | #[tokio::test(flavor = "current_thread")] |
| 1508 | async fn plugins_list_and_status_never_return_config_values() { |
| 1509 | let _policy = TestPolicyGuard::extension_host(true); |
| 1510 | let mut f = PluginsFixture::new(); |
| 1511 | let secret = "SECRET_VALUE_NEVER_LEAK_98765"; |
| 1512 | let body = format!( |
| 1513 | "schema_version = 1\n[plugin]\nname = \"secretive\"\nversion = \"1.0.0\"\n[plugins.secretive.config]\napi_key = \"{secret}\"\n" |
| 1514 | ); |
| 1515 | write_toml_plugin(&f.config.user_plugins_dir, "secretive", &body); |
| 1516 | f.reload_registry(); |
| 1517 | |
| 1518 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 1519 | let ticket = plugin_ticket(&guard).unwrap(); |
| 1520 | let list = f |
| 1521 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "list", json!({})) |
| 1522 | .await |
| 1523 | .unwrap(); |
| 1524 | let status = f |
| 1525 | .call_broker( |
| 1526 | &f.creator, |
| 1527 | HostCohort::Builtin, |
| 1528 | &ticket, |
| 1529 | "status", |
| 1530 | json!({}), |
| 1531 | ) |
| 1532 | .await |
| 1533 | .unwrap(); |
| 1534 | let list_str = serde_json::to_string(&list).unwrap(); |
| 1535 | let status_str = serde_json::to_string(&status).unwrap(); |
| 1536 | assert!(!list_str.contains(secret)); |
| 1537 | assert!(!status_str.contains(secret)); |
| 1538 | } |
| 1539 | |
| 1540 | fn copy_dir_tree(src: &Path, dst: &Path) { |
| 1541 | fs::create_dir_all(dst).unwrap(); |
| 1542 | for entry in fs::read_dir(src).unwrap() { |
| 1543 | let entry = entry.unwrap(); |
| 1544 | let ty = entry.file_type().unwrap(); |
| 1545 | let target = dst.join(entry.file_name()); |
| 1546 | if ty.is_dir() { |
| 1547 | copy_dir_tree(&entry.path(), &target); |
| 1548 | } else { |
| 1549 | fs::copy(entry.path(), &target).unwrap(); |
| 1550 | } |
| 1551 | } |
| 1552 | } |
| 1553 | |
| 1554 | fn broker_to_pm_input(method: &str, input: &Value) -> Value { |
| 1555 | let mut map = input.as_object().cloned().unwrap_or_default(); |
| 1556 | map.insert("action".to_string(), json!(method)); |
| 1557 | Value::Object(map) |
| 1558 | } |
| 1559 | |
| 1560 | fn decider_for_posture(authority: &LiveRuntimeAuthority) -> CreatorDecider { |
| 1561 | match authority.approval_mode() { |
| 1562 | ApprovalMode::Bypass => CreatorDecider::Agent(AgentPosture::FullAccess), |
| 1563 | ApprovalMode::Auto => CreatorDecider::Agent(AgentPosture::AutoReview), |
| 1564 | _ => CreatorDecider::Person, |
| 1565 | } |
| 1566 | } |
| 1567 | |
| 1568 | fn synthetic_carrier_for( |
| 1569 | method: &str, |
| 1570 | input: &Value, |
| 1571 | decider: CreatorDecider, |
| 1572 | admitted_authority: LiveRuntimeAuthority, |
| 1573 | in_agent_scope: bool, |
| 1574 | ) -> CreatorDecisionCarrier { |
| 1575 | let raw_target = input |
| 1576 | .get("target") |
| 1577 | .and_then(Value::as_str) |
| 1578 | .unwrap_or("") |
| 1579 | .to_string(); |
| 1580 | let change = match method { |
| 1581 | "install" => AdmittedChangeKind::LocalInstall { |
| 1582 | raw_target: raw_target.clone(), |
| 1583 | canon_source: PathBuf::from(&raw_target), |
| 1584 | is_dsh: false, |
| 1585 | plugin_name: "synthetic".to_string(), |
| 1586 | pre_hash: "0".repeat(64), |
| 1587 | capability_hash: "0".repeat(64), |
| 1588 | want_enabled: input |
| 1589 | .get("enabled") |
| 1590 | .and_then(Value::as_bool) |
| 1591 | .unwrap_or(true), |
| 1592 | expected_gate_target: format!("synthetic {} {raw_target}", "0".repeat(64)), |
| 1593 | shown_service_lines: Vec::new(), |
| 1594 | preview_warnings: Vec::new(), |
| 1595 | remaining_writes: Arc::new(AtomicUsize::new(1)), |
| 1596 | }, |
| 1597 | "remove" => AdmittedChangeKind::Remove { |
| 1598 | plugin_id: "synthetic/id".to_string(), |
| 1599 | plugin_name: raw_target, |
| 1600 | expected_gate_target: "synthetic synthetic/id".to_string(), |
| 1601 | remaining_writes: Arc::new(AtomicUsize::new(1)), |
| 1602 | }, |
| 1603 | "enable" | "disable" => AdmittedChangeKind::Toggle { |
| 1604 | enabled: method == "enable", |
| 1605 | plugin_id: "synthetic/id".to_string(), |
| 1606 | plugin_name: raw_target, |
| 1607 | content_hash: "0".repeat(64), |
| 1608 | capability_hash: "0".repeat(64), |
| 1609 | expected_gate_target: "synthetic".to_string(), |
| 1610 | shown_service_lines: Vec::new(), |
| 1611 | shown_service_token: None, |
| 1612 | remaining_writes: Arc::new(AtomicUsize::new(1)), |
| 1613 | }, |
| 1614 | other => panic!("unsupported broker change method {other}"), |
| 1615 | }; |
| 1616 | CreatorDecisionCarrier { |
| 1617 | decider, |
| 1618 | admitted_authority, |
| 1619 | in_agent_scope, |
| 1620 | change, |
| 1621 | } |
| 1622 | } |
| 1623 | |
| 1624 | impl PluginsFixture { |
| 1625 | async fn admit_context( |
| 1626 | &self, |
| 1627 | base: &ToolContext, |
| 1628 | method: &str, |
| 1629 | input: &Value, |
| 1630 | decider: CreatorDecider, |
| 1631 | ) -> Result<ToolContext, ToolError> { |
| 1632 | let pm_input = broker_to_pm_input(method, input); |
| 1633 | let plan = plan_change_async(base, &pm_input, &CancellationToken::new()).await?; |
| 1634 | let authority = base |
| 1635 | .live_posture |
| 1636 | .as_ref() |
| 1637 | .expect("live_posture on fixture") |
| 1638 | .read(); |
| 1639 | let carrier = plan.build_carrier(decider, authority)?; |
| 1640 | Ok(base.clone().with_creator_decision(carrier)) |
| 1641 | } |
| 1642 | |
| 1643 | async fn call_admitted( |
| 1644 | &self, |
| 1645 | base: &ToolContext, |
| 1646 | method: &str, |
| 1647 | input: Value, |
| 1648 | ) -> Result<Value, RpcErrorWire> { |
| 1649 | let decider = decider_for_posture(&self.posture.read()); |
| 1650 | let admitted = self |
| 1651 | .admit_context(base, method, &input, decider) |
| 1652 | .await |
| 1653 | .expect("admit_context should succeed"); |
| 1654 | let guard = self.begin(&self.creator, HostCohort::Builtin, &admitted); |
| 1655 | let ticket = plugin_ticket(&guard).unwrap(); |
| 1656 | self.call_broker(&self.creator, HostCohort::Builtin, &ticket, method, input) |
| 1657 | .await |
| 1658 | } |
| 1659 | |
| 1660 | async fn call_admitted_with_receipts( |
| 1661 | &self, |
| 1662 | base: &ToolContext, |
| 1663 | method: &str, |
| 1664 | input: Value, |
| 1665 | ) -> (Result<Value, RpcErrorWire>, Value) { |
| 1666 | let decider = decider_for_posture(&self.posture.read()); |
| 1667 | let admitted = self |
| 1668 | .admit_context(base, method, &input, decider) |
| 1669 | .await |
| 1670 | .expect("admit_context should succeed"); |
| 1671 | let guard = self.begin(&self.creator, HostCohort::Builtin, &admitted); |
| 1672 | let ticket = plugin_ticket(&guard).unwrap(); |
| 1673 | let res = self |
| 1674 | .call_broker(&self.creator, HostCohort::Builtin, &ticket, method, input) |
| 1675 | .await; |
| 1676 | let receipts = guard.receipts().unwrap_or(Value::Null); |
| 1677 | (res, receipts) |
| 1678 | } |
| 1679 | } |
| 1680 | |
| 1681 | fn write_skill_bundle(root: &Path, dir_name: &str, plugin_name: &str, version: &str) -> PathBuf { |
| 1682 | let body = format!( |
| 1683 | "schema_version = 1\n[plugin]\nname = \"{plugin_name}\"\nversion = \"{version}\"\n" |
| 1684 | ); |
| 1685 | let dir = write_toml_plugin(root, dir_name, &body); |
| 1686 | write_skill(&dir, "helper"); |
| 1687 | dir |
| 1688 | } |
| 1689 | |
| 1690 | fn write_native_bundle(root: &Path, dir_name: &str, plugin_name: &str, version: &str) -> PathBuf { |
| 1691 | let body = format!( |
| 1692 | "schema_version = 1\n[plugin]\nname = \"{plugin_name}\"\nversion = \"{version}\"\n[native]\npath = \"native/index.mjs\"\n" |
| 1693 | ); |
| 1694 | let dir = write_toml_plugin(root, dir_name, &body); |
| 1695 | fs::create_dir_all(dir.join("native")).unwrap(); |
| 1696 | fs::write(dir.join("native/index.mjs"), "export function apply() {}\n").unwrap(); |
| 1697 | dir |
| 1698 | } |
| 1699 | |
| 1700 | fn read_install_receipt(plugin_dir: &Path) -> Value { |
| 1701 | let raw = fs::read_to_string(plugin_dir.join(INSTALLED_FROM_MARKER)).unwrap(); |
| 1702 | serde_json::from_str(&raw).unwrap() |
| 1703 | } |
| 1704 | |
| 1705 | fn dsh_template_dir(name: &str) -> PathBuf { |
| 1706 | Path::new(env!("CARGO_MANIFEST_DIR")) |
| 1707 | .join("../skills/assets/dsh-creator/skills/cordis-plugin-development/templates") |
| 1708 | .join(name) |
| 1709 | } |
| 1710 | |
| 1711 | #[tokio::test(flavor = "current_thread")] |
| 1712 | async fn full_access_installs_a_folder_in_the_project_and_records_the_agent() { |
| 1713 | let _policy = TestPolicyGuard::extension_host(true); |
| 1714 | let mut f = PluginsFixture::new(); |
| 1715 | let _manager = TestManagerGuard::install(Arc::new(ExtensionHostManager::new( |
| 1716 | ExtensionHostOptions::default(), |
| 1717 | ))); |
| 1718 | f.reload_registry(); |
| 1719 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 1720 | |
| 1721 | let src = write_skill_bundle( |
| 1722 | &f.config.workspace, |
| 1723 | "agent-skill-src", |
| 1724 | "agent-skill", |
| 1725 | "1.2.3", |
| 1726 | ); |
| 1727 | let (installed, receipts) = f |
| 1728 | .call_admitted_with_receipts( |
| 1729 | &f.context, |
| 1730 | "install", |
| 1731 | json!({"target": src.to_string_lossy()}), |
| 1732 | ) |
| 1733 | .await; |
| 1734 | let installed = installed.unwrap(); |
| 1735 | assert_eq!(installed["application"], "applied", "{installed}"); |
| 1736 | assert_eq!(installed["stage"], "enable"); |
| 1737 | assert_eq!(installed["changed"], true); |
| 1738 | assert_eq!(installed["enabled"], true); |
| 1739 | assert_eq!(installed["bundle"], "agent-skill"); |
| 1740 | assert_eq!(installed["version"], "1.2.3"); |
| 1741 | let warnings = installed["warnings"].as_array().unwrap(); |
| 1742 | assert!( |
| 1743 | warnings |
| 1744 | .iter() |
| 1745 | .any(|w| w == "enabled for this project only"), |
| 1746 | "{warnings:?}" |
| 1747 | ); |
| 1748 | assert!( |
| 1749 | warnings |
| 1750 | .iter() |
| 1751 | .any(|w| w == "approved by the agent in Full Access"), |
| 1752 | "{warnings:?}" |
| 1753 | ); |
| 1754 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 1755 | assert_eq!(receipts["broker_acts"]["total"], 2, "{receipts}"); |
| 1756 | let acts = receipts["broker_acts"]["acts"].as_array().unwrap(); |
| 1757 | let gate_act = acts.iter().find(|act| act.get("effect").is_some()).unwrap(); |
| 1758 | assert_eq!(gate_act["effect"], "write"); |
| 1759 | assert_eq!(gate_act["outcome"], "allowed"); |
| 1760 | assert_eq!(gate_act["decider"], "agent"); |
| 1761 | assert_eq!(gate_act["posture"], "full_access"); |
| 1762 | |
| 1763 | f.reload_registry(); |
| 1764 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 1765 | let ticket = plugin_ticket(&guard).unwrap(); |
| 1766 | |
| 1767 | let listed = f |
| 1768 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "list", json!({})) |
| 1769 | .await |
| 1770 | .unwrap(); |
| 1771 | let entry = listed["entries"] |
| 1772 | .as_array() |
| 1773 | .unwrap() |
| 1774 | .iter() |
| 1775 | .find(|row| row["name"] == "agent-skill") |
| 1776 | .unwrap(); |
| 1777 | assert_eq!(entry["codewhale"]["approved_by"]["kind"], "agent"); |
| 1778 | assert_eq!(entry["codewhale"]["approved_by"]["posture"], "full_access"); |
| 1779 | assert_eq!(entry["codewhale"]["approved_by"]["this_project"], true); |
| 1780 | assert_eq!(entry["codewhale"]["enabled_by"]["this_project"], true); |
| 1781 | |
| 1782 | let receipt = read_install_receipt(&f.config.user_plugins_dir.join("agent-skill")); |
| 1783 | let recorded_spec = receipt["spec"].as_str().unwrap(); |
| 1784 | let recorded_path = recorded_spec.strip_prefix("path:").unwrap_or(recorded_spec); |
| 1785 | assert_eq!( |
| 1786 | fs::canonicalize(recorded_path).unwrap(), |
| 1787 | fs::canonicalize(&src).unwrap(), |
| 1788 | "{receipt}" |
| 1789 | ); |
| 1790 | assert!( |
| 1791 | receipt["install_nonce"] |
| 1792 | .as_str() |
| 1793 | .is_some_and(|n| !n.is_empty()), |
| 1794 | "{receipt}" |
| 1795 | ); |
| 1796 | assert!( |
| 1797 | receipt["content_digest"] |
| 1798 | .as_str() |
| 1799 | .is_some_and(|h| h.len() == 64), |
| 1800 | "{receipt}" |
| 1801 | ); |
| 1802 | |
| 1803 | drop(guard); |
| 1804 | let deco_src = f.config.workspace.join("deco-src"); |
| 1805 | copy_dir_tree(&dsh_template_dir("decoration"), &deco_src); |
| 1806 | let deco = f |
| 1807 | .call_admitted( |
| 1808 | &f.context, |
| 1809 | "install", |
| 1810 | json!({"target": deco_src.to_string_lossy()}), |
| 1811 | ) |
| 1812 | .await |
| 1813 | .unwrap(); |
| 1814 | assert_eq!(deco["application"], "failed", "{deco}"); |
| 1815 | assert_eq!(deco["stage"], "enable"); |
| 1816 | assert_eq!(deco["changed"], true); |
| 1817 | assert_eq!(deco["enabled"], true); |
| 1818 | assert_eq!(deco["error"]["code"], "operation-error"); |
| 1819 | assert_eq!( |
| 1820 | deco["error"]["diagnostic"].as_str(), |
| 1821 | Some("the plugin host is not running for this session"), |
| 1822 | "{deco}" |
| 1823 | ); |
| 1824 | |
| 1825 | let mcp_src = f.config.workspace.join("mcp-src"); |
| 1826 | copy_dir_tree(&dsh_template_dir("mcp"), &mcp_src); |
| 1827 | let mcp_input = json!({"target": mcp_src.to_string_lossy()}); |
| 1828 | let mcp_plan = plan_change_async( |
| 1829 | &f.context, |
| 1830 | &broker_to_pm_input("install", &mcp_input), |
| 1831 | &CancellationToken::new(), |
| 1832 | ) |
| 1833 | .await |
| 1834 | .unwrap(); |
| 1835 | assert!(mcp_plan.in_agent_scope); |
| 1836 | let mcp_ctx = f.context.clone().with_creator_decision( |
| 1837 | mcp_plan |
| 1838 | .build_carrier( |
| 1839 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 1840 | f.posture.read(), |
| 1841 | ) |
| 1842 | .unwrap(), |
| 1843 | ); |
| 1844 | let mcp_guard = f.begin(&f.creator, HostCohort::Builtin, &mcp_ctx); |
| 1845 | let mcp_ticket = plugin_ticket(&mcp_guard).unwrap(); |
| 1846 | let mcp = f |
| 1847 | .call_broker( |
| 1848 | &f.creator, |
| 1849 | HostCohort::Builtin, |
| 1850 | &mcp_ticket, |
| 1851 | "install", |
| 1852 | mcp_input, |
| 1853 | ) |
| 1854 | .await |
| 1855 | .unwrap(); |
| 1856 | assert_eq!(mcp["application"], "failed", "{mcp}"); |
| 1857 | assert_eq!(mcp["stage"], "enable"); |
| 1858 | assert_eq!(mcp["changed"], true); |
| 1859 | assert_eq!(mcp["enabled"], true); |
| 1860 | assert_eq!(mcp["error"]["code"], "operation-error"); |
| 1861 | drop(mcp_guard); |
| 1862 | } |
| 1863 | |
| 1864 | #[tokio::test(flavor = "current_thread")] |
| 1865 | async fn full_access_refuses_what_the_agent_did_not_write() { |
| 1866 | let mut f = PluginsFixture::new(); |
| 1867 | let ws_user_plugins = f.config.workspace.join("user-plugins"); |
| 1868 | f.config.user_plugins_dir = ws_user_plugins.clone(); |
| 1869 | let person_dir = write_skill_bundle(&ws_user_plugins, "person-plug", "person-plug", "1.0.0"); |
| 1870 | let person_ext = write_skill_bundle(f._temp.path(), "person-ext-src", "person-plug", "1.0.0"); |
| 1871 | fs::write( |
| 1872 | person_dir.join(INSTALLED_FROM_MARKER), |
| 1873 | json!({ |
| 1874 | "schema_version": 2, |
| 1875 | "spec": format!("path:{}", person_ext.display()), |
| 1876 | "url": null, |
| 1877 | "source_checksum": "", |
| 1878 | "content_digest": "", |
| 1879 | "installed_name": "person-plug", |
| 1880 | "registry_version": null, |
| 1881 | "install_nonce": "nonce-person-refuse", |
| 1882 | }) |
| 1883 | .to_string(), |
| 1884 | ) |
| 1885 | .unwrap(); |
| 1886 | write_skill_bundle( |
| 1887 | &f.config.builtin_plugin_dirs[0], |
| 1888 | "core-pack", |
| 1889 | "core-pack", |
| 1890 | "1.0.0", |
| 1891 | ); |
| 1892 | let mut reg = discover_with_config(&f.config); |
| 1893 | approve_reviewed( |
| 1894 | &mut reg, |
| 1895 | "person-plug", |
| 1896 | PluginApprover::person(PersonVia::ApprovalCard), |
| 1897 | ); |
| 1898 | let _ = reg; |
| 1899 | |
| 1900 | f.reload_registry(); |
| 1901 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 1902 | |
| 1903 | let outside = write_skill_bundle(f._temp.path(), "outside-src", "outside-plugin", "1.0.0"); |
| 1904 | let git_hidden = write_skill_bundle( |
| 1905 | &f.config.workspace.join(".git"), |
| 1906 | "hidden-plugin", |
| 1907 | "hidden-plugin", |
| 1908 | "1.0.0", |
| 1909 | ); |
| 1910 | let inside_user = write_skill_bundle( |
| 1911 | &ws_user_plugins.join("nested"), |
| 1912 | "in-user-src", |
| 1913 | "in-user-plugin", |
| 1914 | "1.0.0", |
| 1915 | ); |
| 1916 | |
| 1917 | let targets: Vec<(&str, String)> = [ |
| 1918 | ("npm spec", "npm:pkg@1.0.0".to_string()), |
| 1919 | ("outside workspace", outside.to_string_lossy().into_owned()), |
| 1920 | ("inside .git", git_hidden.to_string_lossy().into_owned()), |
| 1921 | ( |
| 1922 | "inside user_plugins_dir", |
| 1923 | inside_user.to_string_lossy().into_owned(), |
| 1924 | ), |
| 1925 | ] |
| 1926 | .into_iter() |
| 1927 | .chain({ |
| 1928 | #[cfg(unix)] |
| 1929 | { |
| 1930 | let link_dst = f.config.workspace.join("linked-outside"); |
| 1931 | std::os::unix::fs::symlink(outside_path_clone(f._temp.path()), &link_dst).unwrap(); |
| 1932 | Some(( |
| 1933 | "symlinked workspace dir", |
| 1934 | link_dst.to_string_lossy().into_owned(), |
| 1935 | )) |
| 1936 | } |
| 1937 | #[cfg(not(unix))] |
| 1938 | { |
| 1939 | None |
| 1940 | } |
| 1941 | }) |
| 1942 | .collect(); |
| 1943 | |
| 1944 | let state_before = fs::read(&f.config.state_path).unwrap(); |
| 1945 | |
| 1946 | for (label, target) in targets { |
| 1947 | let input = json!({"target": target}); |
| 1948 | let plan = plan_change_async( |
| 1949 | &f.context, |
| 1950 | &broker_to_pm_input("install", &input), |
| 1951 | &CancellationToken::new(), |
| 1952 | ) |
| 1953 | .await; |
| 1954 | if label == "symlinked workspace dir" { |
| 1955 | let err = plan.expect_err(label); |
| 1956 | assert!( |
| 1957 | format!("{err:?}").contains("cannot traverse symbolic links"), |
| 1958 | "{label}: {err:?}" |
| 1959 | ); |
| 1960 | continue; |
| 1961 | } |
| 1962 | let plan = plan.expect(label); |
| 1963 | assert!(!plan.in_agent_scope, "{label}"); |
| 1964 | assert!( |
| 1965 | plan.build_carrier( |
| 1966 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 1967 | f.posture.read() |
| 1968 | ) |
| 1969 | .is_err(), |
| 1970 | "{label}" |
| 1971 | ); |
| 1972 | |
| 1973 | let mut forged = plan |
| 1974 | .build_carrier(CreatorDecider::Person, f.posture.read()) |
| 1975 | .expect(label); |
| 1976 | forged.decider = CreatorDecider::Agent(AgentPosture::FullAccess); |
| 1977 | forged.in_agent_scope = true; |
| 1978 | let forged_ctx = f.context.clone().with_creator_decision(forged); |
| 1979 | let guard = f.begin(&f.creator, HostCohort::Builtin, &forged_ctx); |
| 1980 | let ticket = plugin_ticket(&guard).unwrap(); |
| 1981 | let res = f |
| 1982 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "install", input) |
| 1983 | .await; |
| 1984 | if label == "npm spec" { |
| 1985 | assert_eq!(refusal(&res), (error_code::REFUSED, "refused".into())); |
| 1986 | } else { |
| 1987 | let res = res.unwrap(); |
| 1988 | assert_eq!(res["application"], "failed", "{label}: {res}"); |
| 1989 | assert_eq!(res["changed"], false, "{label}: {res}"); |
| 1990 | assert_eq!(res["error"]["code"], "operation-error", "{label}: {res}"); |
| 1991 | assert!( |
| 1992 | res["error"]["diagnostic"] |
| 1993 | .as_str() |
| 1994 | .unwrap() |
| 1995 | .contains("ask the person: step to Ask, or use the Plugins page"), |
| 1996 | "{label}: {res}" |
| 1997 | ); |
| 1998 | } |
| 1999 | } |
| 2000 | |
| 2001 | for method in ["disable", "remove"] { |
| 2002 | let person_input = json!({"target": "person-plug"}); |
| 2003 | let person_plan = plan_change_async( |
| 2004 | &f.context, |
| 2005 | &broker_to_pm_input(method, &person_input), |
| 2006 | &CancellationToken::new(), |
| 2007 | ) |
| 2008 | .await |
| 2009 | .unwrap(); |
| 2010 | assert!(!person_plan.in_agent_scope, "{method} person"); |
| 2011 | assert!( |
| 2012 | person_plan |
| 2013 | .build_carrier( |
| 2014 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 2015 | f.posture.read() |
| 2016 | ) |
| 2017 | .is_err() |
| 2018 | ); |
| 2019 | let mut forged_person = person_plan |
| 2020 | .build_carrier(CreatorDecider::Person, f.posture.read()) |
| 2021 | .unwrap(); |
| 2022 | forged_person.decider = CreatorDecider::Agent(AgentPosture::FullAccess); |
| 2023 | forged_person.in_agent_scope = true; |
| 2024 | let forged_person_ctx = f.context.clone().with_creator_decision(forged_person); |
| 2025 | let p_guard = f.begin(&f.creator, HostCohort::Builtin, &forged_person_ctx); |
| 2026 | let p_ticket = plugin_ticket(&p_guard).unwrap(); |
| 2027 | let person_res = f |
| 2028 | .call_broker( |
| 2029 | &f.creator, |
| 2030 | HostCohort::Builtin, |
| 2031 | &p_ticket, |
| 2032 | method, |
| 2033 | person_input, |
| 2034 | ) |
| 2035 | .await |
| 2036 | .unwrap(); |
| 2037 | assert_eq!( |
| 2038 | person_res["application"], "failed", |
| 2039 | "{method}: {person_res}" |
| 2040 | ); |
| 2041 | assert_eq!(person_res["changed"], false); |
| 2042 | assert!( |
| 2043 | person_res["error"]["diagnostic"] |
| 2044 | .as_str() |
| 2045 | .unwrap() |
| 2046 | .contains("was approved by a person"), |
| 2047 | "{person_res}" |
| 2048 | ); |
| 2049 | |
| 2050 | let builtin_input = json!({"target": "core-pack"}); |
| 2051 | if method == "remove" { |
| 2052 | assert!( |
| 2053 | plan_change_async( |
| 2054 | &f.context, |
| 2055 | &broker_to_pm_input(method, &builtin_input), |
| 2056 | &CancellationToken::new(), |
| 2057 | ) |
| 2058 | .await |
| 2059 | .is_err(), |
| 2060 | "{method} builtin" |
| 2061 | ); |
| 2062 | } else { |
| 2063 | let builtin_plan = plan_change_async( |
| 2064 | &f.context, |
| 2065 | &broker_to_pm_input(method, &builtin_input), |
| 2066 | &CancellationToken::new(), |
| 2067 | ) |
| 2068 | .await |
| 2069 | .unwrap(); |
| 2070 | assert!(!builtin_plan.in_agent_scope, "{method} builtin"); |
| 2071 | assert!( |
| 2072 | builtin_plan |
| 2073 | .build_carrier( |
| 2074 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 2075 | f.posture.read() |
| 2076 | ) |
| 2077 | .is_err() |
| 2078 | ); |
| 2079 | } |
| 2080 | let forged_builtin_ctx = f |
| 2081 | .context |
| 2082 | .clone() |
| 2083 | .with_creator_decision(synthetic_carrier_for( |
| 2084 | method, |
| 2085 | &builtin_input, |
| 2086 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 2087 | f.posture.read(), |
| 2088 | true, |
| 2089 | )); |
| 2090 | let b_guard = f.begin(&f.creator, HostCohort::Builtin, &forged_builtin_ctx); |
| 2091 | let b_ticket = plugin_ticket(&b_guard).unwrap(); |
| 2092 | let builtin_res = f |
| 2093 | .call_broker( |
| 2094 | &f.creator, |
| 2095 | HostCohort::Builtin, |
| 2096 | &b_ticket, |
| 2097 | method, |
| 2098 | builtin_input, |
| 2099 | ) |
| 2100 | .await |
| 2101 | .unwrap(); |
| 2102 | assert_eq!( |
| 2103 | builtin_res["application"], "failed", |
| 2104 | "{method}: {builtin_res}" |
| 2105 | ); |
| 2106 | assert_eq!(builtin_res["changed"], false); |
| 2107 | assert_eq!(builtin_res["error"]["code"], "management-required"); |
| 2108 | } |
| 2109 | |
| 2110 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 2111 | assert_eq!(fs::read(&f.config.state_path).unwrap(), state_before); |
| 2112 | } |
| 2113 | |
| 2114 | #[cfg(unix)] |
| 2115 | fn outside_path_clone(temp_root: &Path) -> PathBuf { |
| 2116 | let dir = temp_root.join("outside-symlink-target"); |
| 2117 | if !dir.exists() { |
| 2118 | write_skill_bundle( |
| 2119 | temp_root, |
| 2120 | "outside-symlink-target", |
| 2121 | "linked-outside", |
| 2122 | "1.0.0", |
| 2123 | ); |
| 2124 | } |
| 2125 | dir |
| 2126 | } |
| 2127 | |
| 2128 | #[tokio::test(flavor = "current_thread")] |
| 2129 | async fn ask_asks_once_and_records_the_person() { |
| 2130 | let mut f = PluginsFixture::new(); |
| 2131 | f.reload_registry(); |
| 2132 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 2133 | |
| 2134 | let src = write_skill_bundle(f._temp.path(), "ext-ask-src", "ext-ask", "0.9.0"); |
| 2135 | let (res, receipts) = f |
| 2136 | .call_admitted_with_receipts( |
| 2137 | &f.context, |
| 2138 | "install", |
| 2139 | json!({"target": src.to_string_lossy()}), |
| 2140 | ) |
| 2141 | .await; |
| 2142 | let res = res.unwrap(); |
| 2143 | assert_eq!(res["application"], "applied", "{res}"); |
| 2144 | assert_eq!(res["stage"], "enable"); |
| 2145 | assert_eq!(res["changed"], true); |
| 2146 | assert_eq!(res["enabled"], true); |
| 2147 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 2148 | assert_eq!(receipts["broker_acts"]["total"], 2, "{receipts}"); |
| 2149 | let acts = receipts["broker_acts"]["acts"].as_array().unwrap(); |
| 2150 | let gate_act = acts.iter().find(|act| act.get("effect").is_some()).unwrap(); |
| 2151 | assert_eq!(gate_act["outcome"], "allowed"); |
| 2152 | assert_eq!(gate_act["decider"], "person"); |
| 2153 | assert_eq!(gate_act["posture"], "approval_card"); |
| 2154 | let warnings = res["warnings"].as_array().unwrap(); |
| 2155 | assert!( |
| 2156 | warnings.iter().any(|w| w == "enabled for every project"), |
| 2157 | "{warnings:?}" |
| 2158 | ); |
| 2159 | assert!( |
| 2160 | warnings.iter().any(|w| w == "approved by you"), |
| 2161 | "{warnings:?}" |
| 2162 | ); |
| 2163 | |
| 2164 | f.reload_registry(); |
| 2165 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 2166 | let ticket = plugin_ticket(&guard).unwrap(); |
| 2167 | |
| 2168 | let listed = f |
| 2169 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "list", json!({})) |
| 2170 | .await |
| 2171 | .unwrap(); |
| 2172 | let entry = listed["entries"] |
| 2173 | .as_array() |
| 2174 | .unwrap() |
| 2175 | .iter() |
| 2176 | .find(|row| row["name"] == "ext-ask") |
| 2177 | .unwrap(); |
| 2178 | assert_eq!(entry["codewhale"]["approved_by"]["kind"], "person"); |
| 2179 | assert_eq!(entry["codewhale"]["approved_by"]["via"], "approval_card"); |
| 2180 | drop(guard); |
| 2181 | |
| 2182 | let disabled_src = write_skill_bundle(f._temp.path(), "ext-off-src", "ext-off", "0.1.0"); |
| 2183 | let res_off = f |
| 2184 | .call_admitted( |
| 2185 | &f.context, |
| 2186 | "install", |
| 2187 | json!({"target": disabled_src.to_string_lossy(), "enabled": false}), |
| 2188 | ) |
| 2189 | .await |
| 2190 | .unwrap(); |
| 2191 | assert_eq!(res_off["application"], "applied", "{res_off}"); |
| 2192 | assert_eq!(res_off["stage"], "install"); |
| 2193 | assert_eq!(res_off["changed"], true); |
| 2194 | assert_eq!(res_off["enabled"], false); |
| 2195 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 2196 | } |
| 2197 | |
| 2198 | #[tokio::test(flavor = "current_thread")] |
| 2199 | async fn a_no_on_the_card_changes_nothing() { |
| 2200 | let mut f = PluginsFixture::new(); |
| 2201 | let src = write_skill_bundle(f._temp.path(), "deny-src", "deny-install", "1.0.0"); |
| 2202 | let existing = write_skill_bundle(&f.config.workspace, "seeded-src", "seeded-plug", "1.0.0"); |
| 2203 | |
| 2204 | f.reload_registry(); |
| 2205 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 2206 | let init = f |
| 2207 | .call_admitted( |
| 2208 | &f.context, |
| 2209 | "install", |
| 2210 | json!({"target": existing.to_string_lossy()}), |
| 2211 | ) |
| 2212 | .await |
| 2213 | .unwrap(); |
| 2214 | assert_eq!(init["application"], "applied"); |
| 2215 | |
| 2216 | let state_before = fs::read(&f.config.state_path).unwrap(); |
| 2217 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 2218 | f.asked.store(0, Ordering::SeqCst); |
| 2219 | |
| 2220 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 2221 | let ticket = plugin_ticket(&guard).unwrap(); |
| 2222 | for (method, input) in [ |
| 2223 | ("install", json!({"target": src.to_string_lossy()})), |
| 2224 | ("disable", json!({"target": "seeded-plug"})), |
| 2225 | ("enable", json!({"target": "seeded-plug"})), |
| 2226 | ("remove", json!({"target": "seeded-plug"})), |
| 2227 | ] { |
| 2228 | let err = f |
| 2229 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, method, input) |
| 2230 | .await; |
| 2231 | assert_eq!( |
| 2232 | refusal(&err), |
| 2233 | (error_code::REFUSED, "refused".into()), |
| 2234 | "{method}" |
| 2235 | ); |
| 2236 | } |
| 2237 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 2238 | assert_eq!(fs::read(&f.config.state_path).unwrap(), state_before); |
| 2239 | assert!(!f.config.user_plugins_dir.join("deny-install").exists()); |
| 2240 | assert!(f.config.user_plugins_dir.join("seeded-plug").is_dir()); |
| 2241 | } |
| 2242 | |
| 2243 | #[tokio::test(flavor = "current_thread")] |
| 2244 | async fn auto_review_records_the_agent_with_its_posture() { |
| 2245 | let mut f = PluginsFixture::new(); |
| 2246 | f.reload_registry(); |
| 2247 | f.posture.switch_for_tests(ApprovalMode::Auto); |
| 2248 | |
| 2249 | let in_ws = write_skill_bundle(&f.config.workspace, "auto-in", "auto-in", "1.0.0"); |
| 2250 | let out_ws = write_skill_bundle(f._temp.path(), "auto-out", "auto-out", "1.0.0"); |
| 2251 | |
| 2252 | let ok = f |
| 2253 | .call_admitted( |
| 2254 | &f.context, |
| 2255 | "install", |
| 2256 | json!({"target": in_ws.to_string_lossy()}), |
| 2257 | ) |
| 2258 | .await |
| 2259 | .unwrap(); |
| 2260 | assert_eq!(ok["application"], "applied", "{ok}"); |
| 2261 | assert!( |
| 2262 | ok["warnings"] |
| 2263 | .as_array() |
| 2264 | .unwrap() |
| 2265 | .iter() |
| 2266 | .any(|w| w == "approved by the agent in Auto-Review"), |
| 2267 | "{ok}" |
| 2268 | ); |
| 2269 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 2270 | |
| 2271 | f.reload_registry(); |
| 2272 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 2273 | let ticket = plugin_ticket(&guard).unwrap(); |
| 2274 | |
| 2275 | let listed = f |
| 2276 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "list", json!({})) |
| 2277 | .await |
| 2278 | .unwrap(); |
| 2279 | let entry = listed["entries"] |
| 2280 | .as_array() |
| 2281 | .unwrap() |
| 2282 | .iter() |
| 2283 | .find(|row| row["name"] == "auto-in") |
| 2284 | .unwrap(); |
| 2285 | assert_eq!(entry["codewhale"]["approved_by"]["kind"], "agent"); |
| 2286 | assert_eq!(entry["codewhale"]["approved_by"]["posture"], "auto_review"); |
| 2287 | drop(guard); |
| 2288 | |
| 2289 | let out_input = json!({"target": out_ws.to_string_lossy()}); |
| 2290 | let out_plan = plan_change_async( |
| 2291 | &f.context, |
| 2292 | &broker_to_pm_input("install", &out_input), |
| 2293 | &CancellationToken::new(), |
| 2294 | ) |
| 2295 | .await |
| 2296 | .unwrap(); |
| 2297 | assert!(!out_plan.in_agent_scope); |
| 2298 | assert!( |
| 2299 | out_plan |
| 2300 | .build_carrier( |
| 2301 | CreatorDecider::Agent(AgentPosture::AutoReview), |
| 2302 | f.posture.read() |
| 2303 | ) |
| 2304 | .is_err() |
| 2305 | ); |
| 2306 | let mut forged = out_plan |
| 2307 | .build_carrier(CreatorDecider::Person, f.posture.read()) |
| 2308 | .unwrap(); |
| 2309 | forged.decider = CreatorDecider::Agent(AgentPosture::AutoReview); |
| 2310 | forged.in_agent_scope = true; |
| 2311 | let forged_ctx = f.context.clone().with_creator_decision(forged); |
| 2312 | let forged_guard = f.begin(&f.creator, HostCohort::Builtin, &forged_ctx); |
| 2313 | let forged_ticket = plugin_ticket(&forged_guard).unwrap(); |
| 2314 | let refused = f |
| 2315 | .call_broker( |
| 2316 | &f.creator, |
| 2317 | HostCohort::Builtin, |
| 2318 | &forged_ticket, |
| 2319 | "install", |
| 2320 | out_input, |
| 2321 | ) |
| 2322 | .await |
| 2323 | .unwrap(); |
| 2324 | assert_eq!(refused["application"], "failed", "{refused}"); |
| 2325 | assert_eq!(refused["changed"], false); |
| 2326 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 2327 | } |
| 2328 | |
| 2329 | #[tokio::test(flavor = "current_thread")] |
| 2330 | async fn plan_changes_nothing() { |
| 2331 | let mut f = PluginsFixture::new(); |
| 2332 | let existing = write_skill_bundle( |
| 2333 | &f.config.workspace, |
| 2334 | "plan-existing", |
| 2335 | "plan-existing", |
| 2336 | "1.0.0", |
| 2337 | ); |
| 2338 | f.reload_registry(); |
| 2339 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 2340 | let res = f |
| 2341 | .call_admitted( |
| 2342 | &f.context, |
| 2343 | "install", |
| 2344 | json!({"target": existing.to_string_lossy()}), |
| 2345 | ) |
| 2346 | .await |
| 2347 | .unwrap(); |
| 2348 | assert_eq!(res["application"], "applied"); |
| 2349 | |
| 2350 | let state_before = fs::read(&f.config.state_path).unwrap(); |
| 2351 | let new_src = write_skill_bundle(&f.config.workspace, "plan-new", "plan-new", "1.0.0"); |
| 2352 | |
| 2353 | for (label, mode, approval_mode) in [ |
| 2354 | ("never", AppMode::Agent, ApprovalMode::Never), |
| 2355 | ("plan", AppMode::Plan, ApprovalMode::Suggest), |
| 2356 | ] { |
| 2357 | f.posture.switch_mode_for_tests(mode, approval_mode); |
| 2358 | for (method, input) in [ |
| 2359 | ("install", json!({"target": new_src.to_string_lossy()})), |
| 2360 | ("disable", json!({"target": "plan-existing"})), |
| 2361 | ("enable", json!({"target": "plan-existing"})), |
| 2362 | ("remove", json!({"target": "plan-existing"})), |
| 2363 | ] { |
| 2364 | let carrier = synthetic_carrier_for( |
| 2365 | method, |
| 2366 | &input, |
| 2367 | CreatorDecider::Person, |
| 2368 | f.posture.read(), |
| 2369 | false, |
| 2370 | ); |
| 2371 | let ctx = f.context.clone().with_creator_decision(carrier); |
| 2372 | let guard = f.begin(&f.creator, HostCohort::Builtin, &ctx); |
| 2373 | let ticket = plugin_ticket(&guard).unwrap(); |
| 2374 | let err = f |
| 2375 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, method, input) |
| 2376 | .await; |
| 2377 | assert_eq!( |
| 2378 | refusal(&err), |
| 2379 | (error_code::REFUSED, "refused".into()), |
| 2380 | "{label} {method}" |
| 2381 | ); |
| 2382 | } |
| 2383 | } |
| 2384 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 2385 | assert_eq!(fs::read(&f.config.state_path).unwrap(), state_before); |
| 2386 | assert!(!f.config.user_plugins_dir.join("plan-new").exists()); |
| 2387 | assert!(f.config.user_plugins_dir.join("plan-existing").is_dir()); |
| 2388 | } |
| 2389 | |
| 2390 | #[tokio::test(flavor = "current_thread")] |
| 2391 | async fn the_dial_moved_to_plan_during_the_card_changes_nothing() { |
| 2392 | let mut f = PluginsFixture::new(); |
| 2393 | let seeded = write_skill_bundle(&f.config.workspace, "dial-seed", "dial-seed", "1.0.0"); |
| 2394 | f.reload_registry(); |
| 2395 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 2396 | let res = f |
| 2397 | .call_admitted( |
| 2398 | &f.context, |
| 2399 | "install", |
| 2400 | json!({"target": seeded.to_string_lossy()}), |
| 2401 | ) |
| 2402 | .await |
| 2403 | .unwrap(); |
| 2404 | assert_eq!(res["application"], "applied"); |
| 2405 | |
| 2406 | let state_before = fs::read(&f.config.state_path).unwrap(); |
| 2407 | let candidate = write_skill_bundle(f._temp.path(), "dial-cand", "dial-cand", "1.0.0"); |
| 2408 | |
| 2409 | for (method, input) in [ |
| 2410 | ("install", json!({"target": candidate.to_string_lossy()})), |
| 2411 | ("disable", json!({"target": "dial-seed"})), |
| 2412 | ("enable", json!({"target": "dial-seed"})), |
| 2413 | ("remove", json!({"target": "dial-seed"})), |
| 2414 | ] { |
| 2415 | f.posture |
| 2416 | .switch_mode_for_tests(AppMode::Agent, ApprovalMode::Suggest); |
| 2417 | let admitted = f |
| 2418 | .admit_context(&f.context, method, &input, CreatorDecider::Person) |
| 2419 | .await |
| 2420 | .unwrap(); |
| 2421 | f.posture |
| 2422 | .switch_mode_for_tests(AppMode::Plan, ApprovalMode::Suggest); |
| 2423 | let guard = f.begin(&f.creator, HostCohort::Builtin, &admitted); |
| 2424 | let ticket = plugin_ticket(&guard).unwrap(); |
| 2425 | let err = f |
| 2426 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, method, input) |
| 2427 | .await; |
| 2428 | assert_eq!( |
| 2429 | refusal(&err), |
| 2430 | (error_code::REFUSED, "refused".into()), |
| 2431 | "{method}" |
| 2432 | ); |
| 2433 | assert_eq!(fs::read(&f.config.state_path).unwrap(), state_before); |
| 2434 | assert!(!f.config.user_plugins_dir.join("dial-cand").exists()); |
| 2435 | assert!(f.config.user_plugins_dir.join("dial-seed").is_dir()); |
| 2436 | } |
| 2437 | } |
| 2438 | |
| 2439 | #[tokio::test(flavor = "current_thread")] |
| 2440 | async fn the_arm_calls_the_gate_itself() { |
| 2441 | let mut f = PluginsFixture::new(); |
| 2442 | let src = write_skill_bundle(f._temp.path(), "gate-src", "gate-plug", "1.0.0"); |
| 2443 | f.reload_registry(); |
| 2444 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 2445 | |
| 2446 | for (method, input) in [ |
| 2447 | ("install", json!({"target": src.to_string_lossy()})), |
| 2448 | ("disable", json!({"target": "gate-plug"})), |
| 2449 | ("enable", json!({"target": "gate-plug"})), |
| 2450 | ("remove", json!({"target": "gate-plug"})), |
| 2451 | ] { |
| 2452 | let (res, receipts) = f |
| 2453 | .call_admitted_with_receipts(&f.context, method, input) |
| 2454 | .await; |
| 2455 | let res = res.unwrap(); |
| 2456 | assert_eq!(res["application"], "applied", "{method}: {res}"); |
| 2457 | assert_eq!(receipts["broker_acts"]["total"], 2, "{method}: {receipts}"); |
| 2458 | let acts = receipts["broker_acts"]["acts"].as_array().unwrap(); |
| 2459 | let gate_act = acts.iter().find(|act| act.get("effect").is_some()).unwrap(); |
| 2460 | let outcome_act = acts |
| 2461 | .iter() |
| 2462 | .find(|act| act.get("application").is_some()) |
| 2463 | .unwrap(); |
| 2464 | assert_eq!(gate_act["method"], method, "{gate_act}"); |
| 2465 | assert_eq!(gate_act["effect"], "write", "{gate_act}"); |
| 2466 | assert_eq!(gate_act["outcome"], "allowed", "{gate_act}"); |
| 2467 | assert_eq!(gate_act["decider"], "person", "{gate_act}"); |
| 2468 | assert_eq!(gate_act["posture"], "approval_card", "{gate_act}"); |
| 2469 | assert_eq!(outcome_act["method"], method, "{outcome_act}"); |
| 2470 | assert_eq!(outcome_act["application"], "applied", "{outcome_act}"); |
| 2471 | assert_eq!(outcome_act["approver"], "person", "{outcome_act}"); |
| 2472 | assert_eq!(outcome_act["posture"], "approval_card", "{outcome_act}"); |
| 2473 | } |
| 2474 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 2475 | } |
| 2476 | |
| 2477 | #[tokio::test(flavor = "current_thread")] |
| 2478 | async fn an_install_whose_tree_differs_from_its_receipt_fails() { |
| 2479 | let mut f = PluginsFixture::new(); |
| 2480 | f.reload_registry(); |
| 2481 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 2482 | |
| 2483 | let src = write_skill_bundle( |
| 2484 | &f.config.workspace, |
| 2485 | "tamper-install-src", |
| 2486 | "tamper-inst", |
| 2487 | "1.0.0", |
| 2488 | ); |
| 2489 | super::set_post_install_hook_for_test(Box::new(|installed_dir, _| { |
| 2490 | let _ = fs::write( |
| 2491 | installed_dir.join("skills/helper/SKILL.md"), |
| 2492 | "---\nname: helper\ndescription: tampered\n---\ntampered body\n", |
| 2493 | ); |
| 2494 | })); |
| 2495 | |
| 2496 | let res = f |
| 2497 | .call_admitted( |
| 2498 | &f.context, |
| 2499 | "install", |
| 2500 | json!({"target": src.to_string_lossy()}), |
| 2501 | ) |
| 2502 | .await |
| 2503 | .unwrap(); |
| 2504 | assert_eq!(res["application"], "failed", "{res}"); |
| 2505 | assert_eq!(res["stage"], "install"); |
| 2506 | assert_eq!(res["changed"], true); |
| 2507 | assert_eq!(res["enabled"], false); |
| 2508 | assert_eq!(res["error"]["code"], "operation-error"); |
| 2509 | assert_eq!(res["error"]["diagnostic"], "changed after review"); |
| 2510 | |
| 2511 | let reg = discover_with_config(&f.config); |
| 2512 | let loaded = reg.get("tamper-inst").unwrap(); |
| 2513 | assert!(!loaded.enabled); |
| 2514 | assert!(!loaded.trusted()); |
| 2515 | } |
| 2516 | |
| 2517 | #[tokio::test(flavor = "current_thread")] |
| 2518 | async fn the_act_names_the_full_hash_before_the_path() { |
| 2519 | use codewhale_plugins::manifest::PluginManifest; |
| 2520 | |
| 2521 | let mut f = PluginsFixture::new(); |
| 2522 | let src = write_skill_bundle(f._temp.path(), "hash-src", "hash-plug", "1.0.0"); |
| 2523 | let expected_hash = PluginManifest::validate_from_path(&src.join("plugin.toml")) |
| 2524 | .unwrap() |
| 2525 | .content_hash; |
| 2526 | f.reload_registry(); |
| 2527 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 2528 | |
| 2529 | let (installed, install_receipts) = f |
| 2530 | .call_admitted_with_receipts( |
| 2531 | &f.context, |
| 2532 | "install", |
| 2533 | json!({"target": src.to_string_lossy()}), |
| 2534 | ) |
| 2535 | .await; |
| 2536 | assert_eq!(installed.unwrap()["application"], "applied"); |
| 2537 | let disabled = f |
| 2538 | .call_admitted(&f.context, "disable", json!({"target": "hash-plug"})) |
| 2539 | .await |
| 2540 | .unwrap(); |
| 2541 | assert_eq!(disabled["application"], "applied"); |
| 2542 | let (enabled, enable_receipts) = f |
| 2543 | .call_admitted_with_receipts(&f.context, "enable", json!({"target": "hash-plug"})) |
| 2544 | .await; |
| 2545 | assert_eq!(enabled.unwrap()["application"], "applied"); |
| 2546 | |
| 2547 | let reg = discover_with_config(&f.config); |
| 2548 | let loaded = reg.get("hash-plug").unwrap(); |
| 2549 | |
| 2550 | let install_target = install_receipts["broker_acts"]["acts"] |
| 2551 | .as_array() |
| 2552 | .unwrap() |
| 2553 | .iter() |
| 2554 | .find(|act| act.get("effect").is_some()) |
| 2555 | .and_then(|act| act["target"].as_str()) |
| 2556 | .unwrap(); |
| 2557 | let src_str = src.to_string_lossy(); |
| 2558 | let expected_install_prefix = format!("hash-plug {expected_hash} {src_str}"); |
| 2559 | assert_eq!(install_target, expected_install_prefix); |
| 2560 | assert!( |
| 2561 | install_target.find(&expected_hash).unwrap() |
| 2562 | < install_target.find(src_str.as_ref()).unwrap() |
| 2563 | ); |
| 2564 | |
| 2565 | let enable_target = enable_receipts["broker_acts"]["acts"] |
| 2566 | .as_array() |
| 2567 | .unwrap() |
| 2568 | .iter() |
| 2569 | .find(|act| act.get("effect").is_some()) |
| 2570 | .and_then(|act| act["target"].as_str()) |
| 2571 | .unwrap(); |
| 2572 | assert_eq!( |
| 2573 | enable_target, |
| 2574 | format!("hash-plug {} {}", loaded.content_hash, loaded.id.as_str()) |
| 2575 | ); |
| 2576 | assert!( |
| 2577 | enable_target.find(&loaded.content_hash).unwrap() |
| 2578 | < enable_target.find(loaded.id.as_str()).unwrap() |
| 2579 | ); |
| 2580 | } |
| 2581 | |
| 2582 | #[tokio::test(flavor = "current_thread")] |
| 2583 | async fn bytes_changed_after_the_gate_fail_as_changed_after_review() { |
| 2584 | let mut f = PluginsFixture::new(); |
| 2585 | let src = write_skill_bundle(f._temp.path(), "race-install-src", "race-install", "1.0.0"); |
| 2586 | let stable_src = write_skill_bundle( |
| 2587 | &f.config.workspace, |
| 2588 | "race-enable-src", |
| 2589 | "race-enable", |
| 2590 | "1.0.0", |
| 2591 | ); |
| 2592 | f.reload_registry(); |
| 2593 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 2594 | let init = f |
| 2595 | .call_admitted( |
| 2596 | &f.context, |
| 2597 | "install", |
| 2598 | json!({"target": stable_src.to_string_lossy(), "enabled": false}), |
| 2599 | ) |
| 2600 | .await |
| 2601 | .unwrap(); |
| 2602 | assert_eq!(init["application"], "applied"); |
| 2603 | |
| 2604 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 2605 | let install_input = json!({"target": src.to_string_lossy()}); |
| 2606 | let admitted_install = f |
| 2607 | .admit_context( |
| 2608 | &f.context, |
| 2609 | "install", |
| 2610 | &install_input, |
| 2611 | CreatorDecider::Person, |
| 2612 | ) |
| 2613 | .await |
| 2614 | .unwrap(); |
| 2615 | fs::write( |
| 2616 | src.join("skills/helper/SKILL.md"), |
| 2617 | "---\nname: helper\ndescription: raced\n---\nchanged\n", |
| 2618 | ) |
| 2619 | .unwrap(); |
| 2620 | let guard = f.begin(&f.creator, HostCohort::Builtin, &admitted_install); |
| 2621 | let ticket = plugin_ticket(&guard).unwrap(); |
| 2622 | let install_res = f |
| 2623 | .call_broker( |
| 2624 | &f.creator, |
| 2625 | HostCohort::Builtin, |
| 2626 | &ticket, |
| 2627 | "install", |
| 2628 | install_input, |
| 2629 | ) |
| 2630 | .await |
| 2631 | .unwrap(); |
| 2632 | assert_eq!(install_res["application"], "failed", "{install_res}"); |
| 2633 | assert_eq!(install_res["changed"], false); |
| 2634 | assert_eq!(install_res["error"]["diagnostic"], "changed after review"); |
| 2635 | assert!(!f.config.user_plugins_dir.join("race-install").exists()); |
| 2636 | |
| 2637 | let installed_dir = f.config.user_plugins_dir.join("race-enable"); |
| 2638 | let enable_input = json!({"target": "race-enable"}); |
| 2639 | let admitted_enable = f |
| 2640 | .admit_context(&f.context, "enable", &enable_input, CreatorDecider::Person) |
| 2641 | .await |
| 2642 | .unwrap(); |
| 2643 | fs::write( |
| 2644 | installed_dir.join("skills/helper/SKILL.md"), |
| 2645 | "---\nname: helper\ndescription: raced\n---\nchanged on disk\n", |
| 2646 | ) |
| 2647 | .unwrap(); |
| 2648 | let guard2 = f.begin(&f.creator, HostCohort::Builtin, &admitted_enable); |
| 2649 | let ticket2 = plugin_ticket(&guard2).unwrap(); |
| 2650 | let enable_res = f |
| 2651 | .call_broker( |
| 2652 | &f.creator, |
| 2653 | HostCohort::Builtin, |
| 2654 | &ticket2, |
| 2655 | "enable", |
| 2656 | enable_input, |
| 2657 | ) |
| 2658 | .await |
| 2659 | .unwrap(); |
| 2660 | assert_eq!(enable_res["application"], "failed", "{enable_res}"); |
| 2661 | assert_eq!(enable_res["changed"], false); |
| 2662 | assert_eq!(enable_res["error"]["diagnostic"], "changed after review"); |
| 2663 | assert!( |
| 2664 | !discover_with_config(&f.config) |
| 2665 | .get("race-enable") |
| 2666 | .unwrap() |
| 2667 | .enabled |
| 2668 | ); |
| 2669 | } |
| 2670 | |
| 2671 | #[tokio::test(flavor = "current_thread")] |
| 2672 | async fn the_dial_moved_during_the_card_decides_who_is_recorded() { |
| 2673 | let mut f = PluginsFixture::new(); |
| 2674 | let in_ws = write_skill_bundle(&f.config.workspace, "move-in-src", "move-in", "1.0.0"); |
| 2675 | let out_ws = write_skill_bundle(f._temp.path(), "move-out-src", "move-out", "1.0.0"); |
| 2676 | let hook_ws = write_skill_bundle(&f.config.workspace, "move-hook-src", "move-hook", "1.0.0"); |
| 2677 | f.reload_registry(); |
| 2678 | |
| 2679 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 2680 | let in_input = json!({"target": in_ws.to_string_lossy()}); |
| 2681 | let admitted_in = f |
| 2682 | .admit_context(&f.context, "install", &in_input, CreatorDecider::Person) |
| 2683 | .await |
| 2684 | .unwrap(); |
| 2685 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 2686 | let guard = f.begin(&f.creator, HostCohort::Builtin, &admitted_in); |
| 2687 | let ticket = plugin_ticket(&guard).unwrap(); |
| 2688 | let ask_to_full = f |
| 2689 | .call_broker( |
| 2690 | &f.creator, |
| 2691 | HostCohort::Builtin, |
| 2692 | &ticket, |
| 2693 | "install", |
| 2694 | in_input, |
| 2695 | ) |
| 2696 | .await |
| 2697 | .unwrap(); |
| 2698 | assert_eq!(ask_to_full["application"], "applied", "{ask_to_full}"); |
| 2699 | assert!( |
| 2700 | ask_to_full["warnings"] |
| 2701 | .as_array() |
| 2702 | .unwrap() |
| 2703 | .iter() |
| 2704 | .any(|w| w == "approved by you"), |
| 2705 | "{ask_to_full}" |
| 2706 | ); |
| 2707 | let reg = discover_with_config(&f.config); |
| 2708 | assert!(matches!( |
| 2709 | reg.get("move-in").unwrap().approved_by, |
| 2710 | Some(codewhale_plugins::host_services::PluginApprover::Person { .. }) |
| 2711 | )); |
| 2712 | |
| 2713 | let out_plan = plan_change_async( |
| 2714 | &f.context, |
| 2715 | &broker_to_pm_input("install", &json!({"target": out_ws.to_string_lossy()})), |
| 2716 | &CancellationToken::new(), |
| 2717 | ) |
| 2718 | .await |
| 2719 | .unwrap(); |
| 2720 | assert!(!out_plan.in_agent_scope); |
| 2721 | assert!( |
| 2722 | out_plan |
| 2723 | .build_carrier( |
| 2724 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 2725 | f.posture.read() |
| 2726 | ) |
| 2727 | .is_err() |
| 2728 | ); |
| 2729 | assert!(!f.config.user_plugins_dir.join("move-out").exists()); |
| 2730 | |
| 2731 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 2732 | let posture_for_hook = f.posture.clone(); |
| 2733 | super::set_post_install_hook_for_test(Box::new(move |_, _| { |
| 2734 | posture_for_hook.switch_for_tests(ApprovalMode::Suggest); |
| 2735 | })); |
| 2736 | let full_to_ask = f |
| 2737 | .call_admitted( |
| 2738 | &f.context, |
| 2739 | "install", |
| 2740 | json!({"target": hook_ws.to_string_lossy()}), |
| 2741 | ) |
| 2742 | .await |
| 2743 | .unwrap(); |
| 2744 | assert_eq!(full_to_ask["application"], "failed", "{full_to_ask}"); |
| 2745 | assert_eq!(full_to_ask["changed"], true); |
| 2746 | assert_eq!(full_to_ask["enabled"], false); |
| 2747 | assert!( |
| 2748 | full_to_ask["error"]["diagnostic"] |
| 2749 | .as_str() |
| 2750 | .unwrap() |
| 2751 | .contains("permission mode changed after installation"), |
| 2752 | "{full_to_ask}" |
| 2753 | ); |
| 2754 | let reg2 = discover_with_config(&f.config); |
| 2755 | let hook_loaded = reg2.get("move-hook").unwrap(); |
| 2756 | assert!(!hook_loaded.enabled); |
| 2757 | assert!(hook_loaded.approved_by.is_none()); |
| 2758 | } |
| 2759 | |
| 2760 | #[tokio::test(flavor = "current_thread")] |
| 2761 | async fn a_sub_agent_caller_is_refused_on_changing_methods() { |
| 2762 | let mut f = PluginsFixture::new(); |
| 2763 | f.reload_registry(); |
| 2764 | let mut sub_context = f.context.clone(); |
| 2765 | sub_context.execution.owner_agent_id = Some("sub-agent-1".into()); |
| 2766 | let sub_guard = f.begin(&f.creator, HostCohort::Builtin, &sub_context); |
| 2767 | assert!(plugin_ticket(&sub_guard).is_none()); |
| 2768 | |
| 2769 | let root_guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 2770 | let root_ticket = plugin_ticket(&root_guard).unwrap(); |
| 2771 | drop(root_guard); |
| 2772 | |
| 2773 | for method in ["install", "remove", "enable", "disable"] { |
| 2774 | let err = f |
| 2775 | .call_broker( |
| 2776 | &f.creator, |
| 2777 | HostCohort::Builtin, |
| 2778 | &root_ticket, |
| 2779 | method, |
| 2780 | json!({"target": "alpha"}), |
| 2781 | ) |
| 2782 | .await; |
| 2783 | assert_eq!( |
| 2784 | refusal(&err), |
| 2785 | (error_code::REFUSED, "ticket_refused".into()), |
| 2786 | "{method}" |
| 2787 | ); |
| 2788 | } |
| 2789 | assert!(sub_guard.receipts().is_none()); |
| 2790 | } |
| 2791 | |
| 2792 | #[tokio::test(flavor = "current_thread")] |
| 2793 | async fn a_plugin_tier_owner_is_refused_on_changing_methods() { |
| 2794 | let mut f = PluginsFixture::new(); |
| 2795 | f.reload_registry(); |
| 2796 | let creator_guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 2797 | let creator_ticket = plugin_ticket(&creator_guard).unwrap(); |
| 2798 | let forged_owner = OwnerRef { |
| 2799 | plugin_id: "host:creator".into(), |
| 2800 | generation: 99, |
| 2801 | owner_token: "forged-token".into(), |
| 2802 | }; |
| 2803 | |
| 2804 | for method in ["install", "remove", "enable", "disable"] { |
| 2805 | for (owner, tier) in [ |
| 2806 | (&f.plugin_owner, HostCohort::reviewed()), |
| 2807 | (&f.mcp, HostCohort::Builtin), |
| 2808 | (&forged_owner, HostCohort::reviewed()), |
| 2809 | ] { |
| 2810 | let err = f |
| 2811 | .call_broker( |
| 2812 | owner, |
| 2813 | tier, |
| 2814 | &creator_ticket, |
| 2815 | method, |
| 2816 | json!({"target": "alpha"}), |
| 2817 | ) |
| 2818 | .await; |
| 2819 | assert_eq!( |
| 2820 | refusal(&err), |
| 2821 | (error_code::REFUSED, "ticket_refused".into()), |
| 2822 | "{owner:?} {method}" |
| 2823 | ); |
| 2824 | } |
| 2825 | |
| 2826 | for owner in [&f.plugin_owner, &f.mcp] { |
| 2827 | let arm_err = serve(detached_call( |
| 2828 | owner.clone(), |
| 2829 | method, |
| 2830 | json!({"target": "alpha"}), |
| 2831 | )) |
| 2832 | .await; |
| 2833 | assert!( |
| 2834 | matches!( |
| 2835 | arm_err, |
| 2836 | Err(super::super::dsh_broker::BrokerRefusal::Refused { |
| 2837 | service: DshService::Plugins, |
| 2838 | .. |
| 2839 | }) |
| 2840 | ), |
| 2841 | "{owner:?} {method}: {arm_err:?}" |
| 2842 | ); |
| 2843 | } |
| 2844 | } |
| 2845 | assert!(creator_guard.receipts().is_none()); |
| 2846 | } |
| 2847 | |
| 2848 | #[tokio::test(flavor = "current_thread")] |
| 2849 | async fn the_managed_policy_answers_overridden() { |
| 2850 | let mut f = PluginsFixture::new(); |
| 2851 | let src = write_skill_bundle(&f.config.workspace, "policy-src", "policy-plug", "1.0.0"); |
| 2852 | let src2 = write_skill_bundle( |
| 2853 | &f.config.workspace, |
| 2854 | "policy-src-2", |
| 2855 | "policy-plug-2", |
| 2856 | "1.0.0", |
| 2857 | ); |
| 2858 | f.reload_registry(); |
| 2859 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 2860 | |
| 2861 | let installed_off = f |
| 2862 | .call_admitted( |
| 2863 | &f.context, |
| 2864 | "install", |
| 2865 | json!({"target": src2.to_string_lossy(), "enabled": false}), |
| 2866 | ) |
| 2867 | .await |
| 2868 | .unwrap(); |
| 2869 | assert_eq!(installed_off["application"], "applied"); |
| 2870 | |
| 2871 | let policy_path = f.config.state_path.with_file_name("managed-policy.json"); |
| 2872 | fs::write( |
| 2873 | &policy_path, |
| 2874 | r#"{"schema_version":1,"allowed_plugins":[],"allow_unlisted":false}"#, |
| 2875 | ) |
| 2876 | .unwrap(); |
| 2877 | |
| 2878 | let overridden_install = f |
| 2879 | .call_admitted( |
| 2880 | &f.context, |
| 2881 | "install", |
| 2882 | json!({"target": src.to_string_lossy()}), |
| 2883 | ) |
| 2884 | .await |
| 2885 | .unwrap(); |
| 2886 | assert_eq!( |
| 2887 | overridden_install["application"], "overridden", |
| 2888 | "{overridden_install}" |
| 2889 | ); |
| 2890 | assert_eq!(overridden_install["stage"], "enable"); |
| 2891 | assert_eq!(overridden_install["changed"], true); |
| 2892 | assert_eq!(overridden_install["enabled"], false); |
| 2893 | assert_eq!(overridden_install["error"]["code"], "operation-error"); |
| 2894 | assert!( |
| 2895 | overridden_install["error"]["diagnostic"] |
| 2896 | .as_str() |
| 2897 | .unwrap() |
| 2898 | .contains("managed plugin policy"), |
| 2899 | "{overridden_install}" |
| 2900 | ); |
| 2901 | |
| 2902 | let overridden_enable = f |
| 2903 | .call_admitted(&f.context, "enable", json!({"target": "policy-plug-2"})) |
| 2904 | .await |
| 2905 | .unwrap(); |
| 2906 | assert_eq!( |
| 2907 | overridden_enable["application"], "overridden", |
| 2908 | "{overridden_enable}" |
| 2909 | ); |
| 2910 | assert_eq!(overridden_enable["stage"], "enable"); |
| 2911 | assert_eq!(overridden_enable["changed"], false); |
| 2912 | assert_eq!(overridden_enable["enabled"], false); |
| 2913 | assert_eq!(overridden_enable["error"]["code"], "operation-error"); |
| 2914 | } |
| 2915 | |
| 2916 | #[tokio::test(flavor = "current_thread")] |
| 2917 | async fn removal_keeps_the_data_folder_and_says_where() { |
| 2918 | let mut f = PluginsFixture::new(); |
| 2919 | let src = write_skill_bundle(&f.config.workspace, "rem-src", "rem-plug", "1.0.0"); |
| 2920 | f.reload_registry(); |
| 2921 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 2922 | |
| 2923 | let inst = f |
| 2924 | .call_admitted( |
| 2925 | &f.context, |
| 2926 | "install", |
| 2927 | json!({"target": src.to_string_lossy()}), |
| 2928 | ) |
| 2929 | .await |
| 2930 | .unwrap(); |
| 2931 | assert_eq!(inst["application"], "applied"); |
| 2932 | |
| 2933 | let reg = discover_with_config(&f.config); |
| 2934 | let plugin_id = reg.get("rem-plug").unwrap().id.as_str().to_string(); |
| 2935 | let data_dir = |
| 2936 | super::super::supervisor::plugin_data_dir(f._temp.path(), &plugin_id, "rem-plug"); |
| 2937 | fs::create_dir_all(&data_dir).unwrap(); |
| 2938 | fs::write(data_dir.join("keep.txt"), "user state").unwrap(); |
| 2939 | |
| 2940 | let removed = f |
| 2941 | .call_admitted(&f.context, "remove", json!({"target": "rem-plug"})) |
| 2942 | .await |
| 2943 | .unwrap(); |
| 2944 | assert_eq!(removed["application"], "applied", "{removed}"); |
| 2945 | assert_eq!(removed["stage"], "remove"); |
| 2946 | assert_eq!(removed["changed"], true); |
| 2947 | assert_eq!(removed["enabled"], false); |
| 2948 | assert_eq!(removed["bundle"], "rem-plug"); |
| 2949 | let expected_leaf = data_dir.file_name().unwrap().to_string_lossy().into_owned(); |
| 2950 | assert!( |
| 2951 | removed["warnings"].as_array().unwrap().iter().any(|w| { |
| 2952 | w.as_str().is_some_and(|line| { |
| 2953 | line.contains("~/.codewhale/extension-host/data/plugins/") |
| 2954 | && line.contains(&expected_leaf) |
| 2955 | }) |
| 2956 | }), |
| 2957 | "{removed}" |
| 2958 | ); |
| 2959 | assert!(data_dir.join("keep.txt").is_file()); |
| 2960 | assert!(!f.config.user_plugins_dir.join("rem-plug").exists()); |
| 2961 | } |
| 2962 | |
| 2963 | #[tokio::test(flavor = "current_thread")] |
| 2964 | async fn no_second_store() { |
| 2965 | let mut f = PluginsFixture::new(); |
| 2966 | let src = write_skill_bundle(&f.config.workspace, "store-src", "store-plug", "1.0.0"); |
| 2967 | f.reload_registry(); |
| 2968 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 2969 | |
| 2970 | let res = f |
| 2971 | .call_admitted( |
| 2972 | &f.context, |
| 2973 | "install", |
| 2974 | json!({"target": src.to_string_lossy()}), |
| 2975 | ) |
| 2976 | .await |
| 2977 | .unwrap(); |
| 2978 | assert_eq!(res["application"], "applied"); |
| 2979 | |
| 2980 | assert!(f.config.state_path.is_file()); |
| 2981 | assert!( |
| 2982 | f.config |
| 2983 | .user_plugins_dir |
| 2984 | .join("store-plug") |
| 2985 | .join(INSTALLED_FROM_MARKER) |
| 2986 | .is_file() |
| 2987 | ); |
| 2988 | let state_parent = f.config.state_path.parent().unwrap(); |
| 2989 | let files: Vec<String> = fs::read_dir(state_parent) |
| 2990 | .unwrap() |
| 2991 | .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) |
| 2992 | .collect(); |
| 2993 | assert!( |
| 2994 | files |
| 2995 | .iter() |
| 2996 | .all(|name| name.starts_with("plugin-state") || name == ".runtime"), |
| 2997 | "{files:?}" |
| 2998 | ); |
| 2999 | |
| 3000 | let rediscovered = discover_with_config(&f.config); |
| 3001 | let loaded = rediscovered.get("store-plug").unwrap(); |
| 3002 | assert!(loaded.enabled); |
| 3003 | assert!(loaded.trusted()); |
| 3004 | assert!(loaded.install_nonce.is_some()); |
| 3005 | |
| 3006 | let off = f |
| 3007 | .call_admitted(&f.context, "disable", json!({"target": "store-plug"})) |
| 3008 | .await |
| 3009 | .unwrap(); |
| 3010 | assert_eq!(off["application"], "applied", "{off}"); |
| 3011 | let removed = f |
| 3012 | .call_admitted(&f.context, "remove", json!({"target": "store-plug"})) |
| 3013 | .await |
| 3014 | .unwrap(); |
| 3015 | assert_eq!(removed["application"], "applied", "{removed}"); |
| 3016 | let after_remove_files: Vec<String> = fs::read_dir(state_parent) |
| 3017 | .unwrap() |
| 3018 | .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) |
| 3019 | .collect(); |
| 3020 | assert!( |
| 3021 | after_remove_files |
| 3022 | .iter() |
| 3023 | .all(|name| name.starts_with("plugin-state") || name == ".runtime"), |
| 3024 | "{after_remove_files:?}" |
| 3025 | ); |
| 3026 | let user_entries: Vec<String> = fs::read_dir(&f.config.user_plugins_dir) |
| 3027 | .unwrap() |
| 3028 | .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) |
| 3029 | .collect(); |
| 3030 | assert!(user_entries.is_empty(), "{user_entries:?}"); |
| 3031 | } |
| 3032 | |
| 3033 | #[tokio::test(flavor = "current_thread")] |
| 3034 | async fn the_agent_cannot_turn_off_or_remove_a_record_not_its_own_and_a_person_can() { |
| 3035 | use codewhale_plugins::host_services::{ |
| 3036 | AgentApproval, AgentPosture as PluginAgentPosture, PersonVia, PluginApprover, |
| 3037 | ReviewApproval, |
| 3038 | }; |
| 3039 | |
| 3040 | let mut f = PluginsFixture::new(); |
| 3041 | let person_dir = write_skill_bundle( |
| 3042 | &f.config.user_plugins_dir, |
| 3043 | "person-plug", |
| 3044 | "person-plug", |
| 3045 | "1.0.0", |
| 3046 | ); |
| 3047 | let external_src = write_skill_bundle(f._temp.path(), "person-src", "person-plug", "1.0.0"); |
| 3048 | fs::write( |
| 3049 | person_dir.join(INSTALLED_FROM_MARKER), |
| 3050 | json!({ |
| 3051 | "schema_version": 2, |
| 3052 | "spec": format!("path:{}", external_src.display()), |
| 3053 | "url": null, |
| 3054 | "source_checksum": "", |
| 3055 | "content_digest": "", |
| 3056 | "installed_name": "person-plug", |
| 3057 | "registry_version": null, |
| 3058 | "install_nonce": "nonce-person", |
| 3059 | }) |
| 3060 | .to_string(), |
| 3061 | ) |
| 3062 | .unwrap(); |
| 3063 | |
| 3064 | let other_ws_dir = write_skill_bundle( |
| 3065 | &f.config.user_plugins_dir, |
| 3066 | "other-proj-plug", |
| 3067 | "other-proj-plug", |
| 3068 | "1.0.0", |
| 3069 | ); |
| 3070 | let other_ws_src = f._temp.path().join("other-project/src"); |
| 3071 | fs::create_dir_all(&other_ws_src).unwrap(); |
| 3072 | fs::write( |
| 3073 | other_ws_dir.join(INSTALLED_FROM_MARKER), |
| 3074 | json!({ |
| 3075 | "schema_version": 2, |
| 3076 | "spec": format!("path:{}", other_ws_src.display()), |
| 3077 | "url": null, |
| 3078 | "source_checksum": "", |
| 3079 | "content_digest": "", |
| 3080 | "installed_name": "other-proj-plug", |
| 3081 | "registry_version": null, |
| 3082 | "install_nonce": "nonce-other", |
| 3083 | }) |
| 3084 | .to_string(), |
| 3085 | ) |
| 3086 | .unwrap(); |
| 3087 | |
| 3088 | let cli_dir = write_skill_bundle(&f.config.user_plugins_dir, "cli-plug", "cli-plug", "1.0.0"); |
| 3089 | fs::write( |
| 3090 | cli_dir.join(INSTALLED_FROM_MARKER), |
| 3091 | json!({ |
| 3092 | "schema_version": 2, |
| 3093 | "spec": "path:/tmp/cli", |
| 3094 | "url": null, |
| 3095 | "source_checksum": "", |
| 3096 | "content_digest": "", |
| 3097 | "installed_name": "cli-plug", |
| 3098 | "registry_version": null, |
| 3099 | "install_nonce": "nonce-cli", |
| 3100 | }) |
| 3101 | .to_string(), |
| 3102 | ) |
| 3103 | .unwrap(); |
| 3104 | |
| 3105 | let no_marker_dir = write_skill_bundle( |
| 3106 | &f.config.user_plugins_dir, |
| 3107 | "legacy-plug", |
| 3108 | "legacy-plug", |
| 3109 | "1.0.0", |
| 3110 | ); |
| 3111 | let _ = no_marker_dir; |
| 3112 | |
| 3113 | let mut reg = discover_with_config(&f.config); |
| 3114 | approve_reviewed( |
| 3115 | &mut reg, |
| 3116 | "person-plug", |
| 3117 | PluginApprover::person(PersonVia::ApprovalCard), |
| 3118 | ); |
| 3119 | let other_agent = PluginApprover::Agent(AgentApproval { |
| 3120 | posture: PluginAgentPosture::FullAccess, |
| 3121 | workspace: f |
| 3122 | ._temp |
| 3123 | .path() |
| 3124 | .join("other-project") |
| 3125 | .to_string_lossy() |
| 3126 | .into_owned(), |
| 3127 | thread_id: Some("t-other".into()), |
| 3128 | turn_id: Some("u-other".into()), |
| 3129 | tool_call_id: Some("c-other".into()), |
| 3130 | }); |
| 3131 | let other_id = reg.get("other-proj-plug").unwrap().id.as_str().to_string(); |
| 3132 | let other_host_review = reg |
| 3133 | .host_service_review_for(&other_id, &other_agent) |
| 3134 | .unwrap(); |
| 3135 | let mut reg_other = DiscoveryConfig { |
| 3136 | workspace: f._temp.path().join("other-project"), |
| 3137 | workspace_plugins_dir: f._temp.path().join("other-project/.codewhale/plugins"), |
| 3138 | ..f.config.clone() |
| 3139 | }; |
| 3140 | let mut other_reg = discover_with_config(®_other); |
| 3141 | other_reg |
| 3142 | .trust_reviewed( |
| 3143 | &other_id, |
| 3144 | ReviewApproval { |
| 3145 | approved_by: other_agent.clone(), |
| 3146 | host_services: Some(other_host_review.token), |
| 3147 | }, |
| 3148 | ) |
| 3149 | .unwrap(); |
| 3150 | other_reg.enable_by(&other_id, other_agent).unwrap(); |
| 3151 | |
| 3152 | reg_other.workspace = f.config.workspace.clone(); |
| 3153 | let mut reg = discover_with_config(&f.config); |
| 3154 | approve_reviewed(&mut reg, "cli-plug", PluginApprover::CommandLine); |
| 3155 | approve_reviewed( |
| 3156 | &mut reg, |
| 3157 | "legacy-plug", |
| 3158 | PluginApprover::person(PersonVia::Terminal), |
| 3159 | ); |
| 3160 | |
| 3161 | f.reload_registry(); |
| 3162 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 3163 | |
| 3164 | for (method, target) in [ |
| 3165 | ("disable", "person-plug"), |
| 3166 | ("remove", "person-plug"), |
| 3167 | ("disable", "other-proj-plug"), |
| 3168 | ("remove", "other-proj-plug"), |
| 3169 | ("disable", "cli-plug"), |
| 3170 | ("remove", "cli-plug"), |
| 3171 | ("disable", "legacy-plug"), |
| 3172 | ] { |
| 3173 | let input = json!({"target": target}); |
| 3174 | let plan = plan_change_async( |
| 3175 | &f.context, |
| 3176 | &broker_to_pm_input(method, &input), |
| 3177 | &CancellationToken::new(), |
| 3178 | ) |
| 3179 | .await |
| 3180 | .unwrap(); |
| 3181 | assert!(!plan.in_agent_scope, "{method} {target}"); |
| 3182 | assert!( |
| 3183 | plan.build_carrier( |
| 3184 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 3185 | f.posture.read() |
| 3186 | ) |
| 3187 | .is_err(), |
| 3188 | "{method} {target}" |
| 3189 | ); |
| 3190 | |
| 3191 | let mut forged = plan |
| 3192 | .build_carrier(CreatorDecider::Person, f.posture.read()) |
| 3193 | .unwrap(); |
| 3194 | forged.decider = CreatorDecider::Agent(AgentPosture::FullAccess); |
| 3195 | forged.in_agent_scope = true; |
| 3196 | let forged_ctx = f.context.clone().with_creator_decision(forged); |
| 3197 | let guard = f.begin(&f.creator, HostCohort::Builtin, &forged_ctx); |
| 3198 | let ticket = plugin_ticket(&guard).unwrap(); |
| 3199 | let res = f |
| 3200 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, method, input) |
| 3201 | .await |
| 3202 | .unwrap(); |
| 3203 | assert_eq!(res["application"], "failed", "{method} {target}: {res}"); |
| 3204 | assert_eq!(res["changed"], false, "{method} {target}: {res}"); |
| 3205 | assert!( |
| 3206 | res["error"]["diagnostic"] |
| 3207 | .as_str() |
| 3208 | .unwrap() |
| 3209 | .contains("ask the person: step to Ask, or use the Plugins page"), |
| 3210 | "{method} {target}: {res}" |
| 3211 | ); |
| 3212 | } |
| 3213 | |
| 3214 | let legacy_rm_input = json!({"target": "legacy-plug"}); |
| 3215 | assert!( |
| 3216 | plan_change_async( |
| 3217 | &f.context, |
| 3218 | &broker_to_pm_input("remove", &legacy_rm_input), |
| 3219 | &CancellationToken::new(), |
| 3220 | ) |
| 3221 | .await |
| 3222 | .is_err() |
| 3223 | ); |
| 3224 | let legacy_ctx = f |
| 3225 | .context |
| 3226 | .clone() |
| 3227 | .with_creator_decision(synthetic_carrier_for( |
| 3228 | "remove", |
| 3229 | &legacy_rm_input, |
| 3230 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 3231 | f.posture.read(), |
| 3232 | true, |
| 3233 | )); |
| 3234 | let legacy_guard = f.begin(&f.creator, HostCohort::Builtin, &legacy_ctx); |
| 3235 | let legacy_ticket = plugin_ticket(&legacy_guard).unwrap(); |
| 3236 | let legacy_remove = f |
| 3237 | .call_broker( |
| 3238 | &f.creator, |
| 3239 | HostCohort::Builtin, |
| 3240 | &legacy_ticket, |
| 3241 | "remove", |
| 3242 | legacy_rm_input, |
| 3243 | ) |
| 3244 | .await |
| 3245 | .unwrap(); |
| 3246 | assert_eq!(legacy_remove["error"]["code"], "not-removable"); |
| 3247 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 3248 | |
| 3249 | let saved_state = fs::read(&f.config.state_path).unwrap(); |
| 3250 | fs::write(&f.config.state_path, "{corrupt json").unwrap(); |
| 3251 | f.reload_registry(); |
| 3252 | for method in ["disable", "remove"] { |
| 3253 | let input = json!({"target": "person-plug"}); |
| 3254 | let corrupt_ctx = f |
| 3255 | .context |
| 3256 | .clone() |
| 3257 | .with_creator_decision(synthetic_carrier_for( |
| 3258 | method, |
| 3259 | &input, |
| 3260 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 3261 | f.posture.read(), |
| 3262 | true, |
| 3263 | )); |
| 3264 | let corrupt_guard = f.begin(&f.creator, HostCohort::Builtin, &corrupt_ctx); |
| 3265 | let corrupt_ticket = plugin_ticket(&corrupt_guard).unwrap(); |
| 3266 | let res = f |
| 3267 | .call_broker( |
| 3268 | &f.creator, |
| 3269 | HostCohort::Builtin, |
| 3270 | &corrupt_ticket, |
| 3271 | method, |
| 3272 | input, |
| 3273 | ) |
| 3274 | .await |
| 3275 | .unwrap(); |
| 3276 | assert_eq!(res["application"], "failed", "corrupt {method}: {res}"); |
| 3277 | assert!( |
| 3278 | res["error"]["diagnostic"] |
| 3279 | .as_str() |
| 3280 | .unwrap() |
| 3281 | .contains("no valid review record"), |
| 3282 | "corrupt {method}: {res}" |
| 3283 | ); |
| 3284 | } |
| 3285 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 3286 | fs::write(&f.config.state_path, saved_state).unwrap(); |
| 3287 | f.reload_registry(); |
| 3288 | |
| 3289 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 3290 | for (method, target) in [ |
| 3291 | ("disable", "person-plug"), |
| 3292 | ("enable", "person-plug"), |
| 3293 | ("remove", "person-plug"), |
| 3294 | ("disable", "other-proj-plug"), |
| 3295 | ("remove", "cli-plug"), |
| 3296 | ] { |
| 3297 | let res = f |
| 3298 | .call_admitted(&f.context, method, json!({"target": target})) |
| 3299 | .await |
| 3300 | .unwrap(); |
| 3301 | assert_eq!( |
| 3302 | res["application"], "applied", |
| 3303 | "person {method} {target}: {res}" |
| 3304 | ); |
| 3305 | } |
| 3306 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 3307 | } |
| 3308 | |
| 3309 | #[tokio::test(flavor = "current_thread")] |
| 3310 | async fn remove_then_install_of_the_same_bytes_is_a_new_record() { |
| 3311 | let mut f = PluginsFixture::new(); |
| 3312 | let src = write_skill_bundle(&f.config.workspace, "reinst-src", "reinst-plug", "1.0.0"); |
| 3313 | f.reload_registry(); |
| 3314 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 3315 | |
| 3316 | let first = f |
| 3317 | .call_admitted( |
| 3318 | &f.context, |
| 3319 | "install", |
| 3320 | json!({"target": src.to_string_lossy()}), |
| 3321 | ) |
| 3322 | .await |
| 3323 | .unwrap(); |
| 3324 | assert_eq!(first["application"], "applied"); |
| 3325 | let nonce1 = discover_with_config(&f.config) |
| 3326 | .get("reinst-plug") |
| 3327 | .unwrap() |
| 3328 | .install_nonce |
| 3329 | .clone() |
| 3330 | .unwrap(); |
| 3331 | |
| 3332 | let removed = f |
| 3333 | .call_admitted(&f.context, "remove", json!({"target": "reinst-plug"})) |
| 3334 | .await |
| 3335 | .unwrap(); |
| 3336 | assert_eq!(removed["application"], "applied"); |
| 3337 | |
| 3338 | let second = f |
| 3339 | .call_admitted( |
| 3340 | &f.context, |
| 3341 | "install", |
| 3342 | json!({"target": src.to_string_lossy()}), |
| 3343 | ) |
| 3344 | .await |
| 3345 | .unwrap(); |
| 3346 | assert_eq!(second["application"], "applied", "{second}"); |
| 3347 | let reg2 = discover_with_config(&f.config); |
| 3348 | let loaded2 = reg2.get("reinst-plug").unwrap(); |
| 3349 | let nonce2 = loaded2.install_nonce.clone().unwrap(); |
| 3350 | assert_ne!(nonce1, nonce2); |
| 3351 | assert!(loaded2.enabled); |
| 3352 | } |
| 3353 | |
| 3354 | #[tokio::test(flavor = "current_thread")] |
| 3355 | async fn an_agent_approved_plugin_with_code_runs_in_agent_cohort_and_promotes_on_review() { |
| 3356 | let Some(node) = super::super::test_support::node_for_tests( |
| 3357 | "an_agent_approved_plugin_with_code_runs_in_agent_cohort_and_promotes_on_review", |
| 3358 | ) else { |
| 3359 | return; |
| 3360 | }; |
| 3361 | let _policy = TestPolicyGuard::extension_host(true); |
| 3362 | let mut f = PluginsFixture::new(); |
| 3363 | f.manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions { |
| 3364 | runtime: codewhale_config::extension_host::ExtensionHostRuntime::Node, |
| 3365 | node_override: Some(node), |
| 3366 | root: Some(f._temp.path().join("host-root")), |
| 3367 | ..Default::default() |
| 3368 | })); |
| 3369 | { |
| 3370 | let mut reg = f.manager.shared.registry.lock().unwrap(); |
| 3371 | f.creator = reg |
| 3372 | .begin_owner( |
| 3373 | HostCohort::Builtin, |
| 3374 | "host:creator", |
| 3375 | "creator", |
| 3376 | None, |
| 3377 | "digest", |
| 3378 | ) |
| 3379 | .unwrap(); |
| 3380 | reg.mark_active(&f.creator); |
| 3381 | } |
| 3382 | let _manager = TestManagerGuard::install(Arc::clone(&f.manager)); |
| 3383 | let initial_reg = f.reload_registry(); |
| 3384 | let _engine = f.manager.attach(initial_reg); |
| 3385 | let _ = _engine.set_creator_demand(true); |
| 3386 | |
| 3387 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 3388 | let src = write_native_bundle(&f.config.workspace, "native-src", "native-plug", "1.0.0"); |
| 3389 | |
| 3390 | let agent_install = f |
| 3391 | .call_admitted( |
| 3392 | &f.context, |
| 3393 | "install", |
| 3394 | json!({"target": src.to_string_lossy()}), |
| 3395 | ) |
| 3396 | .await |
| 3397 | .unwrap(); |
| 3398 | assert_eq!(agent_install["application"], "applied", "{agent_install}"); |
| 3399 | assert_eq!(agent_install["changed"], true); |
| 3400 | assert_eq!(agent_install["enabled"], true); |
| 3401 | assert!(agent_install.get("error").is_none(), "{agent_install}"); |
| 3402 | let plugin_id = discover_with_config(&f.config) |
| 3403 | .get("native-plug") |
| 3404 | .unwrap() |
| 3405 | .id |
| 3406 | .as_str() |
| 3407 | .to_string(); |
| 3408 | assert_eq!(f.manager.owner_state(&plugin_id), Some(OwnerState::Active)); |
| 3409 | assert_eq!( |
| 3410 | f.manager |
| 3411 | .owner_report(&plugin_id) |
| 3412 | .and_then(|report| report.cohort), |
| 3413 | Some(HostCohort::agent(&f.config.workspace)) |
| 3414 | ); |
| 3415 | |
| 3416 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 3417 | let person_enable = f |
| 3418 | .call_admitted(&f.context, "enable", json!({"target": "native-plug"})) |
| 3419 | .await |
| 3420 | .unwrap(); |
| 3421 | assert_eq!(person_enable["application"], "applied", "{person_enable}"); |
| 3422 | assert_eq!(person_enable["enabled"], true); |
| 3423 | assert!( |
| 3424 | person_enable["warnings"] |
| 3425 | .as_array() |
| 3426 | .unwrap() |
| 3427 | .iter() |
| 3428 | .any(|w| w == "approved by you"), |
| 3429 | "{person_enable}" |
| 3430 | ); |
| 3431 | assert_eq!(f.manager.owner_state(&plugin_id), Some(OwnerState::Active)); |
| 3432 | assert_eq!( |
| 3433 | f.manager |
| 3434 | .owner_report(&plugin_id) |
| 3435 | .and_then(|report| report.cohort), |
| 3436 | Some(HostCohort::reviewed()) |
| 3437 | ); |
| 3438 | |
| 3439 | f.manager.shutdown().await; |
| 3440 | } |
| 3441 | |
| 3442 | #[tokio::test(flavor = "current_thread")] |
| 3443 | async fn a_plugin_without_code_is_applied() { |
| 3444 | let _policy = TestPolicyGuard::extension_host(true); |
| 3445 | let mut f = PluginsFixture::new(); |
| 3446 | f.reload_registry(); |
| 3447 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 3448 | let src = write_skill_bundle(&f.config.workspace, "no-code-src", "no-code-plug", "1.0.0"); |
| 3449 | |
| 3450 | let res = f |
| 3451 | .call_admitted( |
| 3452 | &f.context, |
| 3453 | "install", |
| 3454 | json!({"target": src.to_string_lossy()}), |
| 3455 | ) |
| 3456 | .await |
| 3457 | .unwrap(); |
| 3458 | assert_eq!(res["application"], "applied", "{res}"); |
| 3459 | assert_eq!(res["enabled"], true); |
| 3460 | } |
| 3461 | |
| 3462 | #[tokio::test(flavor = "current_thread")] |
| 3463 | async fn a_remote_source_is_not_fetched_before_the_gate() { |
| 3464 | use codewhale_net::network_policy::{NetworkPolicy, NetworkPolicyDecider}; |
| 3465 | use codewhale_skill_install::bounded_tar::test_archives::archive_from_entries; |
| 3466 | |
| 3467 | let mut f = PluginsFixture::new(); |
| 3468 | f.reload_registry(); |
| 3469 | |
| 3470 | for (label, mode, approval_mode) in [ |
| 3471 | ("never", AppMode::Agent, ApprovalMode::Never), |
| 3472 | ("plan", AppMode::Plan, ApprovalMode::Suggest), |
| 3473 | ] { |
| 3474 | f.posture.switch_mode_for_tests(mode, approval_mode); |
| 3475 | let input = json!({"target": "github:nonexistent-owner-zz/nonexistent-repo-zz"}); |
| 3476 | let carrier = synthetic_carrier_for( |
| 3477 | "install", |
| 3478 | &input, |
| 3479 | CreatorDecider::Person, |
| 3480 | f.posture.read(), |
| 3481 | false, |
| 3482 | ); |
| 3483 | let ctx = f.context.clone().with_creator_decision(carrier); |
| 3484 | let plan_guard = f.begin(&f.creator, HostCohort::Builtin, &ctx); |
| 3485 | let plan_ticket = plugin_ticket(&plan_guard).unwrap(); |
| 3486 | let plan_err = f |
| 3487 | .call_broker( |
| 3488 | &f.creator, |
| 3489 | HostCohort::Builtin, |
| 3490 | &plan_ticket, |
| 3491 | "install", |
| 3492 | input, |
| 3493 | ) |
| 3494 | .await; |
| 3495 | assert_eq!( |
| 3496 | refusal(&plan_err), |
| 3497 | (error_code::REFUSED, "refused".into()), |
| 3498 | "{label}" |
| 3499 | ); |
| 3500 | assert_eq!(f.asked.load(Ordering::SeqCst), 0, "{label}"); |
| 3501 | } |
| 3502 | |
| 3503 | f.posture |
| 3504 | .switch_mode_for_tests(AppMode::Agent, ApprovalMode::Suggest); |
| 3505 | f.asked.store(0, Ordering::SeqCst); |
| 3506 | |
| 3507 | let remote_input = json!({"target": "https://127.0.0.1:9/never-fetched.tgz"}); |
| 3508 | let plan = plan_change_async( |
| 3509 | &f.context, |
| 3510 | &broker_to_pm_input("install", &remote_input), |
| 3511 | &CancellationToken::new(), |
| 3512 | ) |
| 3513 | .await |
| 3514 | .unwrap(); |
| 3515 | assert!(!plan.in_agent_scope); |
| 3516 | assert!(plan.unseen_network_fetch); |
| 3517 | assert!(plan.auto_review_summary.is_none()); |
| 3518 | assert!(plan.card_description.contains("127.0.0.1")); |
| 3519 | assert!( |
| 3520 | plan.build_carrier( |
| 3521 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 3522 | f.posture.read() |
| 3523 | ) |
| 3524 | .is_err() |
| 3525 | ); |
| 3526 | |
| 3527 | let unapproved_guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 3528 | let unapproved_ticket = plugin_ticket(&unapproved_guard).unwrap(); |
| 3529 | let ask_err = f |
| 3530 | .call_broker( |
| 3531 | &f.creator, |
| 3532 | HostCohort::Builtin, |
| 3533 | &unapproved_ticket, |
| 3534 | "install", |
| 3535 | remote_input.clone(), |
| 3536 | ) |
| 3537 | .await; |
| 3538 | assert_eq!(refusal(&ask_err), (error_code::REFUSED, "refused".into())); |
| 3539 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 3540 | |
| 3541 | let blocked_ctx = f |
| 3542 | .context |
| 3543 | .clone() |
| 3544 | .with_network_policy(NetworkPolicyDecider::new(NetworkPolicy::default(), None)); |
| 3545 | let policy_blocked = f |
| 3546 | .call_admitted(&blocked_ctx, "install", remote_input) |
| 3547 | .await |
| 3548 | .unwrap(); |
| 3549 | assert_eq!(policy_blocked["application"], "failed", "{policy_blocked}"); |
| 3550 | assert_eq!(policy_blocked["changed"], false, "{policy_blocked}"); |
| 3551 | assert_eq!(policy_blocked["error"]["code"], "operation-error"); |
| 3552 | |
| 3553 | let archive = archive_from_entries(&[ |
| 3554 | ( |
| 3555 | "remote-skill/plugin.toml", |
| 3556 | b"schema_version = 1\n[plugin]\nname = \"remote-skill\"\nversion = \"1.0.0\"\n", |
| 3557 | ), |
| 3558 | ( |
| 3559 | "remote-skill/skills/helper/SKILL.md", |
| 3560 | b"---\nname: helper\ndescription: remote skill\n---\nbody\n", |
| 3561 | ), |
| 3562 | ]); |
| 3563 | let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); |
| 3564 | let port = listener.local_addr().unwrap().port(); |
| 3565 | let hits = Arc::new(AtomicUsize::new(0)); |
| 3566 | let hits_srv = Arc::clone(&hits); |
| 3567 | let server = std::thread::spawn(move || { |
| 3568 | let Ok((mut stream, _)) = listener.accept() else { |
| 3569 | return; |
| 3570 | }; |
| 3571 | hits_srv.fetch_add(1, Ordering::SeqCst); |
| 3572 | let mut request = Vec::new(); |
| 3573 | let mut buf = [0_u8; 1024]; |
| 3574 | loop { |
| 3575 | use std::io::Read as _; |
| 3576 | let read = stream.read(&mut buf).unwrap_or(0); |
| 3577 | if read == 0 { |
| 3578 | break; |
| 3579 | } |
| 3580 | request.extend_from_slice(&buf[..read]); |
| 3581 | if request.windows(4).any(|window| window == b"\r\n\r\n") { |
| 3582 | break; |
| 3583 | } |
| 3584 | } |
| 3585 | use std::io::Write as _; |
| 3586 | let head = format!( |
| 3587 | "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", |
| 3588 | archive.len() |
| 3589 | ); |
| 3590 | let _ = stream.write_all(head.as_bytes()); |
| 3591 | let _ = stream.write_all(&archive); |
| 3592 | let _ = stream.flush(); |
| 3593 | }); |
| 3594 | |
| 3595 | let url = format!("http://127.0.0.1:{port}/remote-skill.tar.gz"); |
| 3596 | let allow_policy = NetworkPolicy { |
| 3597 | allow: vec!["127.0.0.1".to_string()], |
| 3598 | ..NetworkPolicy::default() |
| 3599 | }; |
| 3600 | let allow_ctx = f |
| 3601 | .context |
| 3602 | .clone() |
| 3603 | .with_network_policy(NetworkPolicyDecider::new(allow_policy, None)); |
| 3604 | let remote_ok_input = json!({"target": url}); |
| 3605 | let ok_plan = plan_change_async( |
| 3606 | &allow_ctx, |
| 3607 | &broker_to_pm_input("install", &remote_ok_input), |
| 3608 | &CancellationToken::new(), |
| 3609 | ) |
| 3610 | .await |
| 3611 | .unwrap(); |
| 3612 | assert!(ok_plan.unseen_network_fetch); |
| 3613 | assert_eq!(hits.load(Ordering::SeqCst), 0); |
| 3614 | |
| 3615 | let ok_carrier = ok_plan |
| 3616 | .build_carrier(CreatorDecider::Person, f.posture.read()) |
| 3617 | .unwrap(); |
| 3618 | let admitted_allow_ctx = allow_ctx.with_creator_decision(ok_carrier); |
| 3619 | let ok_guard = f.begin(&f.creator, HostCohort::Builtin, &admitted_allow_ctx); |
| 3620 | let ok_ticket = plugin_ticket(&ok_guard).unwrap(); |
| 3621 | let installed = f |
| 3622 | .call_broker( |
| 3623 | &f.creator, |
| 3624 | HostCohort::Builtin, |
| 3625 | &ok_ticket, |
| 3626 | "install", |
| 3627 | remote_ok_input, |
| 3628 | ) |
| 3629 | .await |
| 3630 | .unwrap(); |
| 3631 | assert_eq!(installed["application"], "applied", "{installed}"); |
| 3632 | assert_eq!(installed["stage"], "install"); |
| 3633 | assert_eq!(installed["changed"], true); |
| 3634 | assert_eq!(installed["enabled"], false); |
| 3635 | assert!( |
| 3636 | installed["warnings"] |
| 3637 | .as_array() |
| 3638 | .unwrap() |
| 3639 | .iter() |
| 3640 | .any(|w| w.as_str().is_some_and(|s| s.contains("/plugin trust"))), |
| 3641 | "{installed}" |
| 3642 | ); |
| 3643 | let reg = discover_with_config(&f.config); |
| 3644 | let loaded = reg.get("remote-skill").unwrap(); |
| 3645 | assert!(!loaded.enabled); |
| 3646 | assert!(loaded.approved_by.is_none()); |
| 3647 | let _ = server.join(); |
| 3648 | } |
| 3649 | |
| 3650 | #[tokio::test(flavor = "current_thread")] |
| 3651 | async fn a_row_that_is_not_the_only_row_is_refused_and_a_sole_row_switches_the_plugin() { |
| 3652 | let mut f = PluginsFixture::new(); |
| 3653 | let two_src = write_toml_plugin( |
| 3654 | &f.config.workspace, |
| 3655 | "two-src", |
| 3656 | "schema_version = 1\n[plugin]\nname = \"two\"\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n[commands]\npath = \"commands\"\n", |
| 3657 | ); |
| 3658 | write_skill(&two_src, "helper"); |
| 3659 | fs::create_dir_all(two_src.join("commands")).unwrap(); |
| 3660 | fs::write(two_src.join("commands/extra.md"), "extra command\n").unwrap(); |
| 3661 | let one_src = write_toml_plugin( |
| 3662 | &f.config.workspace, |
| 3663 | "one-src", |
| 3664 | "schema_version = 1\n[plugin]\nname = \"one\"\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n", |
| 3665 | ); |
| 3666 | write_skill(&one_src, "helper"); |
| 3667 | |
| 3668 | f.reload_registry(); |
| 3669 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 3670 | |
| 3671 | for src in [&two_src, &one_src] { |
| 3672 | let res = f |
| 3673 | .call_admitted( |
| 3674 | &f.context, |
| 3675 | "install", |
| 3676 | json!({"target": src.to_string_lossy()}), |
| 3677 | ) |
| 3678 | .await |
| 3679 | .unwrap(); |
| 3680 | assert_eq!(res["application"], "applied", "{res}"); |
| 3681 | } |
| 3682 | |
| 3683 | for method in ["disable", "enable"] { |
| 3684 | let with_row = f |
| 3685 | .call_admitted( |
| 3686 | &f.context, |
| 3687 | method, |
| 3688 | json!({"target": "two", "row": "two/skills"}), |
| 3689 | ) |
| 3690 | .await |
| 3691 | .unwrap(); |
| 3692 | assert_eq!(with_row["application"], "failed", "{method}: {with_row}"); |
| 3693 | assert_eq!(with_row["changed"], false); |
| 3694 | assert_eq!( |
| 3695 | with_row["error"]["diagnostic"], |
| 3696 | "Codewhale switches a plugin as a whole; use set_bundle" |
| 3697 | ); |
| 3698 | |
| 3699 | let slash_payload = json!({"target": "two/skills"}); |
| 3700 | let slash_ctx = f |
| 3701 | .context |
| 3702 | .clone() |
| 3703 | .with_creator_decision(synthetic_carrier_for( |
| 3704 | method, |
| 3705 | &slash_payload, |
| 3706 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 3707 | f.posture.read(), |
| 3708 | true, |
| 3709 | )); |
| 3710 | let slash_guard = f.begin(&f.creator, HostCohort::Builtin, &slash_ctx); |
| 3711 | let slash_ticket = plugin_ticket(&slash_guard).unwrap(); |
| 3712 | let slash_res = f |
| 3713 | .call_broker( |
| 3714 | &f.creator, |
| 3715 | HostCohort::Builtin, |
| 3716 | &slash_ticket, |
| 3717 | method, |
| 3718 | slash_payload, |
| 3719 | ) |
| 3720 | .await |
| 3721 | .unwrap(); |
| 3722 | assert_eq!(slash_res["application"], "failed", "{method}: {slash_res}"); |
| 3723 | assert_eq!(slash_res["changed"], false); |
| 3724 | assert_eq!( |
| 3725 | slash_res["error"]["diagnostic"], |
| 3726 | "Codewhale switches a plugin as a whole; use set_bundle" |
| 3727 | ); |
| 3728 | |
| 3729 | let missing_row = f |
| 3730 | .call_admitted( |
| 3731 | &f.context, |
| 3732 | method, |
| 3733 | json!({"target": "two", "row": "two/nonexistent"}), |
| 3734 | ) |
| 3735 | .await |
| 3736 | .unwrap(); |
| 3737 | assert_eq!( |
| 3738 | missing_row["application"], "failed", |
| 3739 | "{method}: {missing_row}" |
| 3740 | ); |
| 3741 | assert_eq!( |
| 3742 | missing_row["error"]["code"], "unknown-plugin", |
| 3743 | "{missing_row}" |
| 3744 | ); |
| 3745 | } |
| 3746 | |
| 3747 | let off = f |
| 3748 | .call_admitted( |
| 3749 | &f.context, |
| 3750 | "disable", |
| 3751 | json!({"target": "one", "row": "one/skills"}), |
| 3752 | ) |
| 3753 | .await |
| 3754 | .unwrap(); |
| 3755 | assert_eq!(off["application"], "applied", "{off}"); |
| 3756 | assert_eq!(off["stage"], "disable", "{off}"); |
| 3757 | assert_eq!(off["changed"], true); |
| 3758 | assert_eq!(off["enabled"], false); |
| 3759 | |
| 3760 | let on_admitted = f |
| 3761 | .admit_context( |
| 3762 | &f.context, |
| 3763 | "enable", |
| 3764 | &json!({"target": "one"}), |
| 3765 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 3766 | ) |
| 3767 | .await |
| 3768 | .unwrap(); |
| 3769 | let on_guard = f.begin(&f.creator, HostCohort::Builtin, &on_admitted); |
| 3770 | let on_ticket = plugin_ticket(&on_guard).unwrap(); |
| 3771 | let on = f |
| 3772 | .call_broker( |
| 3773 | &f.creator, |
| 3774 | HostCohort::Builtin, |
| 3775 | &on_ticket, |
| 3776 | "enable", |
| 3777 | json!({"target": "one/skills"}), |
| 3778 | ) |
| 3779 | .await |
| 3780 | .unwrap(); |
| 3781 | assert_eq!(on["application"], "applied", "{on}"); |
| 3782 | assert_eq!(on["stage"], "enable", "{on}"); |
| 3783 | assert_eq!(on["changed"], true); |
| 3784 | assert_eq!(on["enabled"], true); |
| 3785 | } |
| 3786 | |
| 3787 | #[tokio::test(flavor = "current_thread")] |
| 3788 | async fn approved_builds_answers_stale_approval_and_invalid_specs_fail() { |
| 3789 | let mut f = PluginsFixture::new(); |
| 3790 | let src = write_skill_bundle(&f.config.workspace, "stale-src", "stale-plug", "1.0.0"); |
| 3791 | let dup = write_skill_bundle(&f.config.workspace, "stale-dup", "stale-plug", "2.0.0"); |
| 3792 | f.reload_registry(); |
| 3793 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 3794 | |
| 3795 | let stale_input = json!({"target": src.to_string_lossy(), "approved_builds": ["dep-a"]}); |
| 3796 | let stale_ctx = f |
| 3797 | .context |
| 3798 | .clone() |
| 3799 | .with_creator_decision(synthetic_carrier_for( |
| 3800 | "install", |
| 3801 | &stale_input, |
| 3802 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 3803 | f.posture.read(), |
| 3804 | true, |
| 3805 | )); |
| 3806 | let stale_guard = f.begin(&f.creator, HostCohort::Builtin, &stale_ctx); |
| 3807 | let stale_ticket = plugin_ticket(&stale_guard).unwrap(); |
| 3808 | let stale = f |
| 3809 | .call_broker( |
| 3810 | &f.creator, |
| 3811 | HostCohort::Builtin, |
| 3812 | &stale_ticket, |
| 3813 | "install", |
| 3814 | stale_input, |
| 3815 | ) |
| 3816 | .await |
| 3817 | .unwrap(); |
| 3818 | assert_eq!(stale["application"], "failed", "{stale}"); |
| 3819 | assert_eq!(stale["changed"], false); |
| 3820 | assert_eq!(stale["error"]["code"], "stale-approval"); |
| 3821 | |
| 3822 | let reg_warn = f |
| 3823 | .call_admitted( |
| 3824 | &f.context, |
| 3825 | "install", |
| 3826 | json!({"target": src.to_string_lossy(), "registry": "https://registry.example"}), |
| 3827 | ) |
| 3828 | .await |
| 3829 | .unwrap(); |
| 3830 | assert_eq!(reg_warn["application"], "applied", "{reg_warn}"); |
| 3831 | assert!( |
| 3832 | reg_warn["warnings"].as_array().unwrap().iter().any(|w| { |
| 3833 | w == "registry was ignored; Codewhale installs from the configured source" |
| 3834 | }), |
| 3835 | "{reg_warn}" |
| 3836 | ); |
| 3837 | |
| 3838 | let already = f |
| 3839 | .call_admitted( |
| 3840 | &f.context, |
| 3841 | "install", |
| 3842 | json!({"target": dup.to_string_lossy()}), |
| 3843 | ) |
| 3844 | .await |
| 3845 | .unwrap(); |
| 3846 | assert_eq!(already["application"], "failed", "{already}"); |
| 3847 | assert_eq!(already["changed"], false); |
| 3848 | assert_eq!(already["error"]["code"], "already-installed"); |
| 3849 | |
| 3850 | for bad in [ |
| 3851 | "@scope/pkg@^1.0.0", |
| 3852 | "npm:pkg@^1.0.0", |
| 3853 | "http://example.com/pkg.tgz", |
| 3854 | "relative/dir", |
| 3855 | ] { |
| 3856 | let bad_input = json!({"target": bad}); |
| 3857 | let bad_ctx = f |
| 3858 | .context |
| 3859 | .clone() |
| 3860 | .with_creator_decision(synthetic_carrier_for( |
| 3861 | "install", |
| 3862 | &bad_input, |
| 3863 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 3864 | f.posture.read(), |
| 3865 | true, |
| 3866 | )); |
| 3867 | let guard = f.begin(&f.creator, HostCohort::Builtin, &bad_ctx); |
| 3868 | let ticket = plugin_ticket(&guard).unwrap(); |
| 3869 | let invalid = f |
| 3870 | .call_broker( |
| 3871 | &f.creator, |
| 3872 | HostCohort::Builtin, |
| 3873 | &ticket, |
| 3874 | "install", |
| 3875 | bad_input, |
| 3876 | ) |
| 3877 | .await |
| 3878 | .unwrap(); |
| 3879 | assert_eq!(invalid["application"], "failed", "{bad}: {invalid}"); |
| 3880 | assert_eq!(invalid["changed"], false, "{bad}: {invalid}"); |
| 3881 | assert_eq!(invalid["error"]["code"], "invalid-spec", "{bad}: {invalid}"); |
| 3882 | } |
| 3883 | } |
| 3884 | |
| 3885 | #[tokio::test(flavor = "current_thread")] |
| 3886 | async fn the_recorded_source_path_reads_back_for_update() { |
| 3887 | let mut f = PluginsFixture::new(); |
| 3888 | let src = write_skill_bundle(&f.config.workspace, "upd-src", "upd-plug", "1.0.0"); |
| 3889 | f.reload_registry(); |
| 3890 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 3891 | |
| 3892 | let v1 = f |
| 3893 | .call_admitted( |
| 3894 | &f.context, |
| 3895 | "install", |
| 3896 | json!({"target": src.to_string_lossy()}), |
| 3897 | ) |
| 3898 | .await |
| 3899 | .unwrap(); |
| 3900 | assert_eq!(v1["application"], "applied"); |
| 3901 | |
| 3902 | let recorded_source = read_install_receipt(&f.config.user_plugins_dir.join("upd-plug"))["spec"] |
| 3903 | .as_str() |
| 3904 | .unwrap() |
| 3905 | .to_string(); |
| 3906 | let recorded_path = recorded_source |
| 3907 | .strip_prefix("path:") |
| 3908 | .unwrap_or_else(|| panic!("expected path: spec, got {recorded_source}")); |
| 3909 | assert_eq!( |
| 3910 | fs::canonicalize(recorded_path).unwrap(), |
| 3911 | fs::canonicalize(&src).unwrap() |
| 3912 | ); |
| 3913 | |
| 3914 | fs::write( |
| 3915 | src.join("plugin.toml"), |
| 3916 | "schema_version = 1\n[plugin]\nname = \"upd-plug\"\nversion = \"2.0.0\"\n", |
| 3917 | ) |
| 3918 | .unwrap(); |
| 3919 | let rm = f |
| 3920 | .call_admitted(&f.context, "remove", json!({"target": "upd-plug"})) |
| 3921 | .await |
| 3922 | .unwrap(); |
| 3923 | assert_eq!(rm["application"], "applied"); |
| 3924 | |
| 3925 | let v2 = f |
| 3926 | .call_admitted(&f.context, "install", json!({"target": recorded_source})) |
| 3927 | .await |
| 3928 | .unwrap(); |
| 3929 | assert_eq!(v2["application"], "applied", "{v2}"); |
| 3930 | assert_eq!(v2["version"], "2.0.0"); |
| 3931 | } |
| 3932 | |
| 3933 | #[tokio::test(flavor = "current_thread")] |
| 3934 | async fn cancellation_half_done_removal_missing_identity_and_oversized_bundle() { |
| 3935 | let mut f = PluginsFixture::new(); |
| 3936 | let src = write_skill_bundle(&f.config.workspace, "edge-src", "edge-plug", "1.0.0"); |
| 3937 | let big_src = write_skill_bundle(&f.config.workspace, "big-src", "big-plug", "1.0.0"); |
| 3938 | fs::write( |
| 3939 | big_src.join("payload.bin"), |
| 3940 | vec![b'x'; (codewhale_plugins::install::DEFAULT_MAX_SIZE_BYTES as usize) + 1024], |
| 3941 | ) |
| 3942 | .unwrap(); |
| 3943 | |
| 3944 | f.reload_registry(); |
| 3945 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 3946 | |
| 3947 | let mut no_tool_call = f.context.clone(); |
| 3948 | no_tool_call.origin_tool_call_id = None; |
| 3949 | let missing_id = f |
| 3950 | .call_admitted( |
| 3951 | &no_tool_call, |
| 3952 | "install", |
| 3953 | json!({"target": src.to_string_lossy()}), |
| 3954 | ) |
| 3955 | .await |
| 3956 | .unwrap(); |
| 3957 | assert_eq!(missing_id["application"], "failed", "{missing_id}"); |
| 3958 | assert_eq!(missing_id["changed"], false); |
| 3959 | assert!(!f.config.user_plugins_dir.join("edge-plug").exists()); |
| 3960 | |
| 3961 | let big_input = json!({"target": big_src.to_string_lossy()}); |
| 3962 | assert!( |
| 3963 | plan_change_async( |
| 3964 | &f.context, |
| 3965 | &broker_to_pm_input("install", &big_input), |
| 3966 | &CancellationToken::new(), |
| 3967 | ) |
| 3968 | .await |
| 3969 | .is_err() |
| 3970 | ); |
| 3971 | let big_ctx = f |
| 3972 | .context |
| 3973 | .clone() |
| 3974 | .with_creator_decision(synthetic_carrier_for( |
| 3975 | "install", |
| 3976 | &big_input, |
| 3977 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 3978 | f.posture.read(), |
| 3979 | true, |
| 3980 | )); |
| 3981 | let big_guard = f.begin(&f.creator, HostCohort::Builtin, &big_ctx); |
| 3982 | let big_ticket = plugin_ticket(&big_guard).unwrap(); |
| 3983 | let too_big = f |
| 3984 | .call_broker( |
| 3985 | &f.creator, |
| 3986 | HostCohort::Builtin, |
| 3987 | &big_ticket, |
| 3988 | "install", |
| 3989 | big_input, |
| 3990 | ) |
| 3991 | .await |
| 3992 | .unwrap(); |
| 3993 | assert_eq!(too_big["application"], "failed", "{too_big}"); |
| 3994 | assert_eq!(too_big["changed"], false); |
| 3995 | assert!(!f.config.user_plugins_dir.join("big-plug").exists()); |
| 3996 | drop(big_guard); |
| 3997 | |
| 3998 | let cancel_admitted = f |
| 3999 | .admit_context( |
| 4000 | &f.context, |
| 4001 | "install", |
| 4002 | &json!({"target": src.to_string_lossy()}), |
| 4003 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 4004 | ) |
| 4005 | .await |
| 4006 | .unwrap(); |
| 4007 | super::set_post_install_hook_for_test(Box::new(|_, cancel| { |
| 4008 | cancel.cancel(); |
| 4009 | })); |
| 4010 | let cancel_guard = f.begin(&f.creator, HostCohort::Builtin, &cancel_admitted); |
| 4011 | let cancel_ticket = plugin_ticket(&cancel_guard).unwrap(); |
| 4012 | let cancelled = f |
| 4013 | .call_broker( |
| 4014 | &f.creator, |
| 4015 | HostCohort::Builtin, |
| 4016 | &cancel_ticket, |
| 4017 | "install", |
| 4018 | json!({"target": src.to_string_lossy()}), |
| 4019 | ) |
| 4020 | .await |
| 4021 | .unwrap(); |
| 4022 | assert_eq!(cancelled["application"], "failed", "{cancelled}"); |
| 4023 | assert_eq!(cancelled["changed"], true, "{cancelled}"); |
| 4024 | assert_eq!(cancelled["enabled"], false, "{cancelled}"); |
| 4025 | assert_eq!(cancelled["error"]["code"], "operation-error", "{cancelled}"); |
| 4026 | assert!( |
| 4027 | cancelled["error"]["diagnostic"] |
| 4028 | .as_str() |
| 4029 | .unwrap() |
| 4030 | .contains("cancelled after installation"), |
| 4031 | "{cancelled}" |
| 4032 | ); |
| 4033 | let loaded_after_cancel = discover_with_config(&f.config) |
| 4034 | .get("edge-plug") |
| 4035 | .unwrap() |
| 4036 | .clone(); |
| 4037 | assert!(!loaded_after_cancel.enabled); |
| 4038 | assert!(!loaded_after_cancel.trusted()); |
| 4039 | drop(cancel_guard); |
| 4040 | |
| 4041 | let rm_src = write_skill_bundle(&f.config.workspace, "half-src", "half-plug", "1.0.0"); |
| 4042 | let half_inst = f |
| 4043 | .call_admitted( |
| 4044 | &f.context, |
| 4045 | "install", |
| 4046 | json!({"target": rm_src.to_string_lossy()}), |
| 4047 | ) |
| 4048 | .await |
| 4049 | .unwrap(); |
| 4050 | assert_eq!(half_inst["application"], "applied"); |
| 4051 | super::set_post_disable_hook_for_test(Box::new(|plugin| { |
| 4052 | let _ = fs::remove_file(plugin.canonical_root.join(INSTALLED_FROM_MARKER)); |
| 4053 | })); |
| 4054 | let half_rm = f |
| 4055 | .call_admitted(&f.context, "remove", json!({"target": "half-plug"})) |
| 4056 | .await |
| 4057 | .unwrap(); |
| 4058 | assert_eq!(half_rm["application"], "failed", "{half_rm}"); |
| 4059 | assert_eq!(half_rm["changed"], true); |
| 4060 | assert_eq!(half_rm["enabled"], false); |
| 4061 | assert!( |
| 4062 | half_rm["error"]["diagnostic"] |
| 4063 | .as_str() |
| 4064 | .unwrap() |
| 4065 | .starts_with("plugin was turned off, then removal failed:"), |
| 4066 | "{half_rm}" |
| 4067 | ); |
| 4068 | assert!( |
| 4069 | !discover_with_config(&f.config) |
| 4070 | .get("half-plug") |
| 4071 | .unwrap() |
| 4072 | .enabled |
| 4073 | ); |
| 4074 | } |
| 4075 | |
| 4076 | #[cfg(windows)] |
| 4077 | #[tokio::test(flavor = "current_thread")] |
| 4078 | async fn a_drive_letter_target_is_inside_the_project_on_canonical_paths() { |
| 4079 | let mut f = PluginsFixture::new(); |
| 4080 | let src = write_skill_bundle(&f.config.workspace, "win-drive-src", "win-drive", "1.0.0"); |
| 4081 | let raw = src.to_string_lossy().into_owned(); |
| 4082 | let flipped = if raw.starts_with(|c: char| c.is_ascii_alphabetic()) |
| 4083 | && raw.as_bytes().get(1) == Some(&b':') |
| 4084 | { |
| 4085 | let mut chars: Vec<char> = raw.chars().collect(); |
| 4086 | chars[0] = if chars[0].is_ascii_uppercase() { |
| 4087 | chars[0].to_ascii_lowercase() |
| 4088 | } else { |
| 4089 | chars[0].to_ascii_uppercase() |
| 4090 | }; |
| 4091 | chars.into_iter().collect() |
| 4092 | } else { |
| 4093 | raw |
| 4094 | }; |
| 4095 | f.reload_registry(); |
| 4096 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 4097 | let res = f |
| 4098 | .call_admitted(&f.context, "install", json!({"target": flipped})) |
| 4099 | .await |
| 4100 | .unwrap(); |
| 4101 | assert_eq!(res["application"], "applied", "{res}"); |
| 4102 | } |
| 4103 | |
| 4104 | #[cfg(windows)] |
| 4105 | #[tokio::test(flavor = "current_thread")] |
| 4106 | async fn a_junction_in_the_source_is_refused() { |
| 4107 | let mut f = PluginsFixture::new(); |
| 4108 | let src = write_skill_bundle(&f.config.workspace, "win-junc-src", "win-junc", "1.0.0"); |
| 4109 | let outside = f._temp.path().join("win-outside"); |
| 4110 | fs::create_dir_all(&outside).unwrap(); |
| 4111 | fs::write(outside.join("secret.txt"), "secret").unwrap(); |
| 4112 | let junction = src.join("junc"); |
| 4113 | let status = std::process::Command::new("cmd") |
| 4114 | .arg("/C") |
| 4115 | .arg("mklink") |
| 4116 | .arg("/J") |
| 4117 | .arg(&junction) |
| 4118 | .arg(&outside) |
| 4119 | .status() |
| 4120 | .unwrap(); |
| 4121 | assert!(status.success(), "mklink /J failed"); |
| 4122 | |
| 4123 | f.reload_registry(); |
| 4124 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 4125 | let junc_input = json!({"target": src.to_string_lossy()}); |
| 4126 | assert!( |
| 4127 | plan_change_async( |
| 4128 | &f.context, |
| 4129 | &broker_to_pm_input("install", &junc_input), |
| 4130 | &CancellationToken::new(), |
| 4131 | ) |
| 4132 | .await |
| 4133 | .is_err() |
| 4134 | ); |
| 4135 | let junc_ctx = f |
| 4136 | .context |
| 4137 | .clone() |
| 4138 | .with_creator_decision(synthetic_carrier_for( |
| 4139 | "install", |
| 4140 | &junc_input, |
| 4141 | CreatorDecider::Person, |
| 4142 | f.posture.read(), |
| 4143 | false, |
| 4144 | )); |
| 4145 | let guard = f.begin(&f.creator, HostCohort::Builtin, &junc_ctx); |
| 4146 | let ticket = plugin_ticket(&guard).unwrap(); |
| 4147 | let res = f |
| 4148 | .call_broker( |
| 4149 | &f.creator, |
| 4150 | HostCohort::Builtin, |
| 4151 | &ticket, |
| 4152 | "install", |
| 4153 | junc_input, |
| 4154 | ) |
| 4155 | .await |
| 4156 | .unwrap(); |
| 4157 | assert_eq!(res["application"], "failed", "{res}"); |
| 4158 | assert_eq!(res["changed"], false); |
| 4159 | assert!(!f.config.user_plugins_dir.join("win-junc").exists()); |
| 4160 | } |
| 4161 | |
| 4162 | #[tokio::test(flavor = "current_thread")] |
| 4163 | async fn fresh_home_without_user_plugins_dir_installs_local_project_plugin() { |
| 4164 | let mut f = PluginsFixture::new(); |
| 4165 | fs::remove_dir_all(&f.config.user_plugins_dir).unwrap(); |
| 4166 | let src = write_skill_bundle(&f.config.workspace, "fresh-home-src", "fresh-home", "1.0.0"); |
| 4167 | f.reload_registry(); |
| 4168 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 4169 | |
| 4170 | let res = f |
| 4171 | .call_admitted( |
| 4172 | &f.context, |
| 4173 | "install", |
| 4174 | json!({"target": src.to_string_lossy()}), |
| 4175 | ) |
| 4176 | .await |
| 4177 | .unwrap(); |
| 4178 | assert_eq!(res["application"], "applied", "{res}"); |
| 4179 | assert_eq!(res["changed"], true); |
| 4180 | assert_eq!(res["enabled"], true); |
| 4181 | let installed_dir = f.config.user_plugins_dir.join("fresh-home"); |
| 4182 | assert!(installed_dir.is_dir()); |
| 4183 | let receipt = read_install_receipt(&installed_dir); |
| 4184 | assert!( |
| 4185 | receipt["install_nonce"] |
| 4186 | .as_str() |
| 4187 | .is_some_and(|n| !n.is_empty()), |
| 4188 | "{receipt}" |
| 4189 | ); |
| 4190 | f.reload_registry(); |
| 4191 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 4192 | let ticket = plugin_ticket(&guard).unwrap(); |
| 4193 | let listed = f |
| 4194 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "list", json!({})) |
| 4195 | .await |
| 4196 | .unwrap(); |
| 4197 | let entry = listed["entries"] |
| 4198 | .as_array() |
| 4199 | .unwrap() |
| 4200 | .iter() |
| 4201 | .find(|row| row["name"] == "fresh-home") |
| 4202 | .unwrap(); |
| 4203 | assert_eq!(entry["codewhale"]["approved_by"]["kind"], "agent"); |
| 4204 | assert_eq!(entry["codewhale"]["approved_by"]["posture"], "full_access"); |
| 4205 | assert_eq!(entry["codewhale"]["approved_by"]["this_project"], true); |
| 4206 | } |
| 4207 | |
| 4208 | #[cfg(unix)] |
| 4209 | #[tokio::test(flavor = "current_thread")] |
| 4210 | async fn dangling_user_plugins_dir_symlink_fails_closed_in_agent_mode() { |
| 4211 | let mut f = PluginsFixture::new(); |
| 4212 | fs::remove_dir_all(&f.config.user_plugins_dir).unwrap(); |
| 4213 | let missing_target = f._temp.path().join("missing-user-plugins-target"); |
| 4214 | std::os::unix::fs::symlink(&missing_target, &f.config.user_plugins_dir).unwrap(); |
| 4215 | let src = write_skill_bundle( |
| 4216 | &f.config.workspace, |
| 4217 | "dangling-up-src", |
| 4218 | "dangling-up", |
| 4219 | "1.0.0", |
| 4220 | ); |
| 4221 | f.reload_registry(); |
| 4222 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 4223 | |
| 4224 | let install_input = json!({"target": src.to_string_lossy()}); |
| 4225 | let plan = plan_change_async( |
| 4226 | &f.context, |
| 4227 | &broker_to_pm_input("install", &install_input), |
| 4228 | &CancellationToken::new(), |
| 4229 | ) |
| 4230 | .await |
| 4231 | .unwrap(); |
| 4232 | assert!(!plan.in_agent_scope); |
| 4233 | assert!( |
| 4234 | plan.build_carrier( |
| 4235 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 4236 | f.posture.read() |
| 4237 | ) |
| 4238 | .is_err() |
| 4239 | ); |
| 4240 | let dangling_ctx = f |
| 4241 | .context |
| 4242 | .clone() |
| 4243 | .with_creator_decision(synthetic_carrier_for( |
| 4244 | "install", |
| 4245 | &install_input, |
| 4246 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 4247 | f.posture.read(), |
| 4248 | true, |
| 4249 | )); |
| 4250 | let guard = f.begin(&f.creator, HostCohort::Builtin, &dangling_ctx); |
| 4251 | let ticket = plugin_ticket(&guard).unwrap(); |
| 4252 | let res = f |
| 4253 | .call_broker( |
| 4254 | &f.creator, |
| 4255 | HostCohort::Builtin, |
| 4256 | &ticket, |
| 4257 | "install", |
| 4258 | install_input, |
| 4259 | ) |
| 4260 | .await |
| 4261 | .unwrap(); |
| 4262 | assert_eq!(res["application"], "failed", "{res}"); |
| 4263 | assert_eq!(res["changed"], false); |
| 4264 | assert_eq!(res["error"]["code"], "operation-error"); |
| 4265 | assert!(!missing_target.exists()); |
| 4266 | } |
| 4267 | |
| 4268 | #[tokio::test(flavor = "current_thread")] |
| 4269 | async fn plan_and_never_skip_fs_probes_and_nonexistent_path_does_not_leak() { |
| 4270 | let mut f = PluginsFixture::new(); |
| 4271 | f.reload_registry(); |
| 4272 | let nonexistent = f._temp.path().join("does-not-exist-anywhere/plugin"); |
| 4273 | assert!(!nonexistent.exists()); |
| 4274 | |
| 4275 | for (label, mode, approval_mode) in [ |
| 4276 | ("never", AppMode::Agent, ApprovalMode::Never), |
| 4277 | ("plan", AppMode::Plan, ApprovalMode::Suggest), |
| 4278 | ] { |
| 4279 | f.posture.switch_mode_for_tests(mode, approval_mode); |
| 4280 | let input = json!({"target": nonexistent.to_string_lossy()}); |
| 4281 | let carrier = synthetic_carrier_for( |
| 4282 | "install", |
| 4283 | &input, |
| 4284 | CreatorDecider::Person, |
| 4285 | f.posture.read(), |
| 4286 | false, |
| 4287 | ); |
| 4288 | let ctx = f.context.clone().with_creator_decision(carrier); |
| 4289 | let guard = f.begin(&f.creator, HostCohort::Builtin, &ctx); |
| 4290 | let ticket = plugin_ticket(&guard).unwrap(); |
| 4291 | let err = f |
| 4292 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "install", input) |
| 4293 | .await; |
| 4294 | assert_eq!( |
| 4295 | refusal(&err), |
| 4296 | (error_code::REFUSED, "refused".into()), |
| 4297 | "{label}" |
| 4298 | ); |
| 4299 | assert_eq!(f.asked.load(Ordering::SeqCst), 0, "{label}"); |
| 4300 | } |
| 4301 | } |
| 4302 | |
| 4303 | #[tokio::test(flavor = "current_thread")] |
| 4304 | async fn ask_defers_external_non_bundle_and_symlink_ancestor_until_after_write_gate() { |
| 4305 | let mut f = PluginsFixture::new(); |
| 4306 | f.reload_registry(); |
| 4307 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 4308 | |
| 4309 | let nonexistent = f._temp.path().join("external-nonexistent/plugin"); |
| 4310 | let non_bundle = f._temp.path().join("external-empty-dir"); |
| 4311 | fs::create_dir_all(&non_bundle).unwrap(); |
| 4312 | let bad_toml_dir = write_toml_plugin( |
| 4313 | f._temp.path(), |
| 4314 | "external-bad-toml", |
| 4315 | "this is not = [valid toml", |
| 4316 | ); |
| 4317 | |
| 4318 | let invalid_before_card = vec![ |
| 4319 | nonexistent.to_string_lossy().into_owned(), |
| 4320 | non_bundle.to_string_lossy().into_owned(), |
| 4321 | bad_toml_dir.to_string_lossy().into_owned(), |
| 4322 | ]; |
| 4323 | for raw_target in &invalid_before_card { |
| 4324 | assert!( |
| 4325 | plan_change_async( |
| 4326 | &f.context, |
| 4327 | &broker_to_pm_input("install", &json!({"target": raw_target})), |
| 4328 | &CancellationToken::new(), |
| 4329 | ) |
| 4330 | .await |
| 4331 | .is_err(), |
| 4332 | "{raw_target}" |
| 4333 | ); |
| 4334 | } |
| 4335 | |
| 4336 | #[cfg(unix)] |
| 4337 | let extra_target = { |
| 4338 | let via_ancestor_link = f._temp.path().join("ancestor-wrap"); |
| 4339 | fs::create_dir_all(&via_ancestor_link).unwrap(); |
| 4340 | let _linked_bundle = |
| 4341 | write_skill_bundle(&via_ancestor_link, "nested", "ancestor-linked", "1.0.0"); |
| 4342 | let parent_link = f._temp.path().join("parent-symlink"); |
| 4343 | std::os::unix::fs::symlink(&via_ancestor_link, &parent_link).unwrap(); |
| 4344 | let linked_path = parent_link.join("nested").to_string_lossy().into_owned(); |
| 4345 | assert!( |
| 4346 | plan_change_async( |
| 4347 | &f.context, |
| 4348 | &broker_to_pm_input("install", &json!({"target": linked_path})), |
| 4349 | &CancellationToken::new(), |
| 4350 | ) |
| 4351 | .await |
| 4352 | .is_err(), |
| 4353 | "{linked_path}" |
| 4354 | ); |
| 4355 | Some(linked_path) |
| 4356 | }; |
| 4357 | #[cfg(not(unix))] |
| 4358 | let extra_target: Option<String> = None; |
| 4359 | let targets: Vec<String> = invalid_before_card |
| 4360 | .into_iter() |
| 4361 | .chain(extra_target) |
| 4362 | .collect(); |
| 4363 | |
| 4364 | for raw_target in &targets { |
| 4365 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 4366 | let ticket = plugin_ticket(&guard).unwrap(); |
| 4367 | let err = f |
| 4368 | .call_broker( |
| 4369 | &f.creator, |
| 4370 | HostCohort::Builtin, |
| 4371 | &ticket, |
| 4372 | "install", |
| 4373 | json!({"target": raw_target}), |
| 4374 | ) |
| 4375 | .await; |
| 4376 | assert_eq!(refusal(&err), (error_code::REFUSED, "refused".into())); |
| 4377 | |
| 4378 | let syn_input = json!({"target": raw_target}); |
| 4379 | let syn_ctx = f |
| 4380 | .context |
| 4381 | .clone() |
| 4382 | .with_creator_decision(synthetic_carrier_for( |
| 4383 | "install", |
| 4384 | &syn_input, |
| 4385 | CreatorDecider::Person, |
| 4386 | f.posture.read(), |
| 4387 | false, |
| 4388 | )); |
| 4389 | let syn_guard = f.begin(&f.creator, HostCohort::Builtin, &syn_ctx); |
| 4390 | let syn_ticket = plugin_ticket(&syn_guard).unwrap(); |
| 4391 | let res = f |
| 4392 | .call_broker( |
| 4393 | &f.creator, |
| 4394 | HostCohort::Builtin, |
| 4395 | &syn_ticket, |
| 4396 | "install", |
| 4397 | syn_input, |
| 4398 | ) |
| 4399 | .await |
| 4400 | .unwrap(); |
| 4401 | assert_eq!(res["application"], "failed", "{raw_target}: {res}"); |
| 4402 | assert_eq!(res["changed"], false); |
| 4403 | } |
| 4404 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 4405 | } |
| 4406 | |
| 4407 | #[tokio::test(flavor = "current_thread")] |
| 4408 | async fn local_dsh_with_unresolved_npm_deps_gates_reach_refuses_agent_and_denies_prompt_policy_without_network() |
| 4409 | { |
| 4410 | use codewhale_net::network_policy::{Decision, NetworkPolicy, NetworkPolicyDecider}; |
| 4411 | |
| 4412 | let mut f = PluginsFixture::new(); |
| 4413 | let dsh_src = f.config.workspace.join("dsh-npm-src"); |
| 4414 | copy_dir_tree(&dsh_template_dir("decoration"), &dsh_src); |
| 4415 | let mut pkg_json: Value = |
| 4416 | serde_json::from_str(&fs::read_to_string(dsh_src.join("package.json")).unwrap()).unwrap(); |
| 4417 | pkg_json["dependencies"] = json!({"zod": "^4.0.0"}); |
| 4418 | fs::write( |
| 4419 | dsh_src.join("package.json"), |
| 4420 | serde_json::to_string_pretty(&pkg_json).unwrap(), |
| 4421 | ) |
| 4422 | .unwrap(); |
| 4423 | fs::write( |
| 4424 | dsh_src.join("index.js"), |
| 4425 | "import { z } from 'zod';\nexport function apply() { return z; }\n", |
| 4426 | ) |
| 4427 | .unwrap(); |
| 4428 | f.reload_registry(); |
| 4429 | |
| 4430 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 4431 | let install_input = json!({"target": dsh_src.to_string_lossy()}); |
| 4432 | let plan = plan_change_async( |
| 4433 | &f.context, |
| 4434 | &broker_to_pm_input("install", &install_input), |
| 4435 | &CancellationToken::new(), |
| 4436 | ) |
| 4437 | .await |
| 4438 | .unwrap(); |
| 4439 | assert!(!plan.in_agent_scope); |
| 4440 | assert!(plan.unseen_network_fetch); |
| 4441 | assert!(plan.auto_review_summary.is_none()); |
| 4442 | assert!(plan.card_description.contains("registry.npmjs.org")); |
| 4443 | let agent_err = plan |
| 4444 | .build_carrier( |
| 4445 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 4446 | f.posture.read(), |
| 4447 | ) |
| 4448 | .unwrap_err(); |
| 4449 | assert!( |
| 4450 | agent_err.to_string().contains("registry.npmjs.org"), |
| 4451 | "{agent_err}" |
| 4452 | ); |
| 4453 | |
| 4454 | let mut forged = plan |
| 4455 | .build_carrier(CreatorDecider::Person, f.posture.read()) |
| 4456 | .unwrap(); |
| 4457 | forged.decider = CreatorDecider::Agent(AgentPosture::FullAccess); |
| 4458 | forged.in_agent_scope = true; |
| 4459 | let forged_ctx = f.context.clone().with_creator_decision(forged); |
| 4460 | let agent_guard = f.begin(&f.creator, HostCohort::Builtin, &forged_ctx); |
| 4461 | let agent_ticket = plugin_ticket(&agent_guard).unwrap(); |
| 4462 | let agent_res = f |
| 4463 | .call_broker( |
| 4464 | &f.creator, |
| 4465 | HostCohort::Builtin, |
| 4466 | &agent_ticket, |
| 4467 | "install", |
| 4468 | install_input.clone(), |
| 4469 | ) |
| 4470 | .await; |
| 4471 | assert_eq!(refusal(&agent_res), (error_code::REFUSED, "refused".into())); |
| 4472 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 4473 | |
| 4474 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 4475 | let expected_reach = format!( |
| 4476 | "{} npm dependencies from registry.npmjs.org", |
| 4477 | dsh_src.to_string_lossy() |
| 4478 | ); |
| 4479 | let deny_guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 4480 | let deny_ticket = plugin_ticket(&deny_guard).unwrap(); |
| 4481 | let reach_denied = f |
| 4482 | .call_broker( |
| 4483 | &f.creator, |
| 4484 | HostCohort::Builtin, |
| 4485 | &deny_ticket, |
| 4486 | "install", |
| 4487 | install_input.clone(), |
| 4488 | ) |
| 4489 | .await; |
| 4490 | assert_eq!( |
| 4491 | refusal(&reach_denied), |
| 4492 | (error_code::REFUSED, "refused".into()) |
| 4493 | ); |
| 4494 | |
| 4495 | let prompt_ctx = f |
| 4496 | .context |
| 4497 | .clone() |
| 4498 | .with_network_policy(NetworkPolicyDecider::new(NetworkPolicy::default(), None)); |
| 4499 | let (prompt_res, prompt_receipts) = f |
| 4500 | .call_admitted_with_receipts(&prompt_ctx, "install", install_input.clone()) |
| 4501 | .await; |
| 4502 | let prompt_res = prompt_res.unwrap(); |
| 4503 | assert_eq!(prompt_res["application"], "failed", "{prompt_res}"); |
| 4504 | assert_eq!(prompt_res["changed"], false); |
| 4505 | assert_eq!(prompt_res["error"]["code"], "operation-error"); |
| 4506 | assert!( |
| 4507 | prompt_res["error"]["diagnostic"] |
| 4508 | .as_str() |
| 4509 | .unwrap() |
| 4510 | .to_ascii_lowercase() |
| 4511 | .contains("network approval required for registry.npmjs.org"), |
| 4512 | "{prompt_res}" |
| 4513 | ); |
| 4514 | let reach_acts: Vec<Value> = prompt_receipts["broker_acts"]["acts"] |
| 4515 | .as_array() |
| 4516 | .unwrap() |
| 4517 | .iter() |
| 4518 | .filter(|act| act["effect"] == "reach") |
| 4519 | .cloned() |
| 4520 | .collect(); |
| 4521 | assert_eq!(reach_acts.len(), 1, "{prompt_receipts}"); |
| 4522 | assert_eq!(reach_acts[0]["target"], expected_reach); |
| 4523 | assert_eq!(reach_acts[0]["outcome"], "allowed"); |
| 4524 | assert_eq!(reach_acts[0]["decider"], "person"); |
| 4525 | |
| 4526 | let deny_policy = NetworkPolicy { |
| 4527 | default: Decision::Deny.into(), |
| 4528 | ..NetworkPolicy::default() |
| 4529 | }; |
| 4530 | let deny_policy_ctx = f |
| 4531 | .context |
| 4532 | .clone() |
| 4533 | .with_network_policy(NetworkPolicyDecider::new(deny_policy, None)); |
| 4534 | let deny_res = f |
| 4535 | .call_admitted(&deny_policy_ctx, "install", install_input) |
| 4536 | .await |
| 4537 | .unwrap(); |
| 4538 | assert_eq!(deny_res["application"], "failed", "{deny_res}"); |
| 4539 | assert_eq!(deny_res["changed"], false); |
| 4540 | assert!( |
| 4541 | deny_res["error"]["diagnostic"] |
| 4542 | .as_str() |
| 4543 | .unwrap() |
| 4544 | .to_ascii_lowercase() |
| 4545 | .contains("network access denied for registry.npmjs.org"), |
| 4546 | "{deny_res}" |
| 4547 | ); |
| 4548 | assert!(!f.config.user_plugins_dir.join("my-decoration").exists()); |
| 4549 | } |
| 4550 | |
| 4551 | #[tokio::test(flavor = "current_thread")] |
| 4552 | async fn remote_dial_move_during_reach_leaves_nothing_on_disk() { |
| 4553 | let mut f = PluginsFixture::new(); |
| 4554 | f.reload_registry(); |
| 4555 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 4556 | let input = json!({"target": "https://127.0.0.1:9/remote.tgz"}); |
| 4557 | let admitted = f |
| 4558 | .admit_context(&f.context, "install", &input, CreatorDecider::Person) |
| 4559 | .await |
| 4560 | .unwrap(); |
| 4561 | f.posture.switch_for_tests(ApprovalMode::Never); |
| 4562 | |
| 4563 | let guard = f.begin(&f.creator, HostCohort::Builtin, &admitted); |
| 4564 | let ticket = plugin_ticket(&guard).unwrap(); |
| 4565 | let res = f |
| 4566 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "install", input) |
| 4567 | .await; |
| 4568 | assert_eq!(refusal(&res), (error_code::REFUSED, "refused".into())); |
| 4569 | assert_eq!(fs::read_dir(&f.config.user_plugins_dir).unwrap().count(), 0); |
| 4570 | } |
| 4571 | |
| 4572 | #[tokio::test(flavor = "current_thread")] |
| 4573 | async fn toggle_enable_missing_identity_and_managed_policy_upgrade_keep_state_atomic() { |
| 4574 | let mut f = PluginsFixture::new(); |
| 4575 | let src = write_skill_bundle(&f.config.workspace, "atomic-src", "atomic-plug", "1.0.0"); |
| 4576 | f.reload_registry(); |
| 4577 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 4578 | |
| 4579 | let installed = f |
| 4580 | .call_admitted( |
| 4581 | &f.context, |
| 4582 | "install", |
| 4583 | json!({"target": src.to_string_lossy(), "enabled": false}), |
| 4584 | ) |
| 4585 | .await |
| 4586 | .unwrap(); |
| 4587 | assert_eq!(installed["application"], "applied", "{installed}"); |
| 4588 | assert_eq!(installed["enabled"], false); |
| 4589 | |
| 4590 | let mut ctx_without_identity = f.context.clone(); |
| 4591 | ctx_without_identity.origin_turn_id = None; |
| 4592 | ctx_without_identity.origin_tool_call_id = None; |
| 4593 | let no_id_res = f |
| 4594 | .call_admitted( |
| 4595 | &ctx_without_identity, |
| 4596 | "enable", |
| 4597 | json!({"target": "atomic-plug"}), |
| 4598 | ) |
| 4599 | .await |
| 4600 | .unwrap(); |
| 4601 | assert_eq!(no_id_res["application"], "failed", "{no_id_res}"); |
| 4602 | assert_eq!(no_id_res["changed"], false); |
| 4603 | assert_eq!(no_id_res["enabled"], false); |
| 4604 | assert_eq!(no_id_res["error"]["code"], "operation-error"); |
| 4605 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 4606 | |
| 4607 | let policy_path = f.config.state_path.with_file_name("managed-policy.json"); |
| 4608 | fs::write( |
| 4609 | &policy_path, |
| 4610 | r#"{"schema_version":1,"allowed_plugins":[],"allow_unlisted":false}"#, |
| 4611 | ) |
| 4612 | .unwrap(); |
| 4613 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 4614 | let overridden = f |
| 4615 | .call_admitted(&f.context, "enable", json!({"target": "atomic-plug"})) |
| 4616 | .await |
| 4617 | .unwrap(); |
| 4618 | assert_eq!(overridden["application"], "overridden", "{overridden}"); |
| 4619 | assert_eq!(overridden["changed"], false); |
| 4620 | assert_eq!(overridden["enabled"], false); |
| 4621 | |
| 4622 | let persisted = discover_with_config(&f.config); |
| 4623 | let loaded = persisted.get("atomic-plug").unwrap(); |
| 4624 | assert!(!loaded.enabled); |
| 4625 | assert!(matches!(loaded.approved_by, Some(PluginApprover::Agent(_)))); |
| 4626 | } |
| 4627 | |
| 4628 | #[tokio::test(flavor = "current_thread")] |
| 4629 | async fn remove_rejects_ambiguous_target_non_sole_row_and_symlinked_install_marker() { |
| 4630 | let mut f = PluginsFixture::new(); |
| 4631 | let two_src = write_toml_plugin( |
| 4632 | &f.config.workspace, |
| 4633 | "rm-two-src", |
| 4634 | "schema_version = 1\n[plugin]\nname = \"rm-two\"\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n[commands]\npath = \"commands\"\n", |
| 4635 | ); |
| 4636 | write_skill(&two_src, "helper"); |
| 4637 | fs::create_dir_all(two_src.join("commands")).unwrap(); |
| 4638 | fs::write(two_src.join("commands/extra.md"), "extra\n").unwrap(); |
| 4639 | |
| 4640 | let dup_user = write_skill_bundle( |
| 4641 | &f.config.user_plugins_dir, |
| 4642 | "shared-user", |
| 4643 | "shared-plug", |
| 4644 | "1.0.0", |
| 4645 | ); |
| 4646 | fs::write(dup_user.join(INSTALLED_FROM_MARKER), "local\n").unwrap(); |
| 4647 | let _dup_ws = write_skill_bundle( |
| 4648 | &f.config.workspace_plugins_dir, |
| 4649 | "shared-ws", |
| 4650 | "shared-plug", |
| 4651 | "1.0.0", |
| 4652 | ); |
| 4653 | |
| 4654 | f.reload_registry(); |
| 4655 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 4656 | |
| 4657 | let inst_two = f |
| 4658 | .call_admitted( |
| 4659 | &f.context, |
| 4660 | "install", |
| 4661 | json!({"target": two_src.to_string_lossy()}), |
| 4662 | ) |
| 4663 | .await |
| 4664 | .unwrap(); |
| 4665 | assert_eq!(inst_two["application"], "applied", "{inst_two}"); |
| 4666 | |
| 4667 | let row_input = json!({"target": "rm-two/skills"}); |
| 4668 | assert!( |
| 4669 | plan_change_async( |
| 4670 | &f.context, |
| 4671 | &broker_to_pm_input("remove", &row_input), |
| 4672 | &CancellationToken::new(), |
| 4673 | ) |
| 4674 | .await |
| 4675 | .is_err() |
| 4676 | ); |
| 4677 | let row_ctx = f |
| 4678 | .context |
| 4679 | .clone() |
| 4680 | .with_creator_decision(synthetic_carrier_for( |
| 4681 | "remove", |
| 4682 | &row_input, |
| 4683 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 4684 | f.posture.read(), |
| 4685 | true, |
| 4686 | )); |
| 4687 | let row_guard = f.begin(&f.creator, HostCohort::Builtin, &row_ctx); |
| 4688 | let row_ticket = plugin_ticket(&row_guard).unwrap(); |
| 4689 | let row_rm = f |
| 4690 | .call_broker( |
| 4691 | &f.creator, |
| 4692 | HostCohort::Builtin, |
| 4693 | &row_ticket, |
| 4694 | "remove", |
| 4695 | row_input, |
| 4696 | ) |
| 4697 | .await |
| 4698 | .unwrap(); |
| 4699 | assert_eq!(row_rm["application"], "failed", "{row_rm}"); |
| 4700 | assert_eq!(row_rm["error"]["code"], "operation-error"); |
| 4701 | |
| 4702 | for (method, target) in [("remove", "shared-plug"), ("enable", "shared-plug")] { |
| 4703 | let ambig_input = json!({"target": target}); |
| 4704 | let plan = plan_change_async( |
| 4705 | &f.context, |
| 4706 | &broker_to_pm_input(method, &ambig_input), |
| 4707 | &CancellationToken::new(), |
| 4708 | ) |
| 4709 | .await |
| 4710 | .unwrap(); |
| 4711 | assert!(!plan.in_agent_scope, "{method}"); |
| 4712 | assert!( |
| 4713 | plan.build_carrier( |
| 4714 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 4715 | f.posture.read() |
| 4716 | ) |
| 4717 | .is_err(), |
| 4718 | "{method}" |
| 4719 | ); |
| 4720 | let ambig_ctx = f |
| 4721 | .context |
| 4722 | .clone() |
| 4723 | .with_creator_decision(synthetic_carrier_for( |
| 4724 | method, |
| 4725 | &ambig_input, |
| 4726 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 4727 | f.posture.read(), |
| 4728 | true, |
| 4729 | )); |
| 4730 | let ambig_guard = f.begin(&f.creator, HostCohort::Builtin, &ambig_ctx); |
| 4731 | let ambig_ticket = plugin_ticket(&ambig_guard).unwrap(); |
| 4732 | let res = f |
| 4733 | .call_broker( |
| 4734 | &f.creator, |
| 4735 | HostCohort::Builtin, |
| 4736 | &ambig_ticket, |
| 4737 | method, |
| 4738 | ambig_input, |
| 4739 | ) |
| 4740 | .await |
| 4741 | .unwrap(); |
| 4742 | assert_eq!(res["application"], "failed", "{method}: {res}"); |
| 4743 | assert_eq!(res["error"]["code"], "operation-error", "{method}: {res}"); |
| 4744 | } |
| 4745 | |
| 4746 | #[cfg(unix)] |
| 4747 | { |
| 4748 | let target_marker = f._temp.path().join("outside-marker.json"); |
| 4749 | fs::write(&target_marker, r#"{"approved_by":"agent"}"#).unwrap(); |
| 4750 | let sym_dir = write_skill_bundle( |
| 4751 | &f.config.user_plugins_dir, |
| 4752 | "sym-marker", |
| 4753 | "sym-marker", |
| 4754 | "1.0.0", |
| 4755 | ); |
| 4756 | std::os::unix::fs::symlink(&target_marker, sym_dir.join(INSTALLED_FROM_MARKER)).unwrap(); |
| 4757 | f.reload_registry(); |
| 4758 | let sym_input = json!({"target": "sym-marker"}); |
| 4759 | assert!( |
| 4760 | plan_change_async( |
| 4761 | &f.context, |
| 4762 | &broker_to_pm_input("remove", &sym_input), |
| 4763 | &CancellationToken::new(), |
| 4764 | ) |
| 4765 | .await |
| 4766 | .is_err() |
| 4767 | ); |
| 4768 | let sym_ctx = f |
| 4769 | .context |
| 4770 | .clone() |
| 4771 | .with_creator_decision(synthetic_carrier_for( |
| 4772 | "remove", |
| 4773 | &sym_input, |
| 4774 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 4775 | f.posture.read(), |
| 4776 | true, |
| 4777 | )); |
| 4778 | let sym_guard = f.begin(&f.creator, HostCohort::Builtin, &sym_ctx); |
| 4779 | let sym_ticket = plugin_ticket(&sym_guard).unwrap(); |
| 4780 | let sym_rm = f |
| 4781 | .call_broker( |
| 4782 | &f.creator, |
| 4783 | HostCohort::Builtin, |
| 4784 | &sym_ticket, |
| 4785 | "remove", |
| 4786 | sym_input, |
| 4787 | ) |
| 4788 | .await |
| 4789 | .unwrap(); |
| 4790 | assert_eq!(sym_rm["application"], "failed", "{sym_rm}"); |
| 4791 | assert_eq!(sym_rm["error"]["code"], "not-removable"); |
| 4792 | assert!(sym_dir.is_dir()); |
| 4793 | } |
| 4794 | } |
| 4795 | |
| 4796 | #[tokio::test(flavor = "current_thread")] |
| 4797 | async fn disable_and_remove_synchronously_revoke_tickets_and_cross_workspace_user_scope() { |
| 4798 | let _policy = TestPolicyGuard::extension_host(true); |
| 4799 | let mut f = PluginsFixture::new(); |
| 4800 | let ws_b = f._temp.path().join("project-b"); |
| 4801 | fs::create_dir_all(ws_b.join(".codewhale/plugins")).unwrap(); |
| 4802 | let config_b = DiscoveryConfig { |
| 4803 | workspace: ws_b.clone(), |
| 4804 | user_plugins_dir: f.config.user_plugins_dir.clone(), |
| 4805 | workspace_plugins_dir: ws_b.join(".codewhale/plugins"), |
| 4806 | builtin_plugin_dirs: f.config.builtin_plugin_dirs.clone(), |
| 4807 | state_path: f.config.state_path.clone(), |
| 4808 | }; |
| 4809 | |
| 4810 | let _manager = TestManagerGuard::install(Arc::clone(&f.manager)); |
| 4811 | let reg_a = f.reload_registry(); |
| 4812 | let _engine_a = f.manager.attach(reg_a); |
| 4813 | let _ = _engine_a.set_creator_demand(true); |
| 4814 | let _engine_b = f.manager.attach(Arc::new(discover_with_config(&config_b))); |
| 4815 | |
| 4816 | let src = write_skill_bundle(&f.config.workspace, "sync-rev-src", "sync-rev", "1.0.0"); |
| 4817 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 4818 | |
| 4819 | let inst = f |
| 4820 | .call_admitted( |
| 4821 | &f.context, |
| 4822 | "install", |
| 4823 | json!({"target": src.to_string_lossy()}), |
| 4824 | ) |
| 4825 | .await |
| 4826 | .unwrap(); |
| 4827 | assert_eq!(inst["application"], "applied", "{inst}"); |
| 4828 | |
| 4829 | let live_reg = discover_with_config(&f.config); |
| 4830 | let loaded = live_reg.get("sync-rev").unwrap(); |
| 4831 | let plugin_id = loaded.id.as_str().to_string(); |
| 4832 | let live_auth = live_reg.authority_for(&plugin_id).unwrap(); |
| 4833 | let b_snap = super::super::caller_view(&ws_b, None, None).unwrap(); |
| 4834 | assert!(b_snap.get("sync-rev").is_some_and(|p| p.enabled)); |
| 4835 | |
| 4836 | let plug_owner = { |
| 4837 | let mut reg = f.manager.shared.registry.lock().unwrap(); |
| 4838 | let owner = reg |
| 4839 | .begin_owner( |
| 4840 | HostCohort::reviewed(), |
| 4841 | &plugin_id, |
| 4842 | "sync-rev", |
| 4843 | Some(live_auth.clone()), |
| 4844 | &loaded.content_hash, |
| 4845 | ) |
| 4846 | .unwrap(); |
| 4847 | reg.mark_active(&owner); |
| 4848 | owner |
| 4849 | }; |
| 4850 | assert!( |
| 4851 | f.manager |
| 4852 | .owner_report_for(&plugin_id, Some(&live_auth)) |
| 4853 | .is_some_and(|r| r.state == Some(OwnerState::Active)) |
| 4854 | ); |
| 4855 | assert!( |
| 4856 | f.manager |
| 4857 | .owner_report_for(&plugin_id, Some(&fake_authority("stale"))) |
| 4858 | .is_none() |
| 4859 | ); |
| 4860 | |
| 4861 | let tickets_before_plug = f.manager.shared.core_calls.live_tickets(); |
| 4862 | let plug_guard = f.begin(&plug_owner, HostCohort::reviewed(), &f.context); |
| 4863 | let tickets_with_plug = f.manager.shared.core_calls.live_tickets(); |
| 4864 | assert!(tickets_with_plug > tickets_before_plug); |
| 4865 | |
| 4866 | let disabled = f |
| 4867 | .call_admitted(&f.context, "disable", json!({"target": "sync-rev"})) |
| 4868 | .await |
| 4869 | .unwrap(); |
| 4870 | assert_eq!(disabled["application"], "applied", "{disabled}"); |
| 4871 | assert_eq!(disabled["enabled"], false); |
| 4872 | |
| 4873 | assert!( |
| 4874 | f.manager |
| 4875 | .shared |
| 4876 | .registry |
| 4877 | .lock() |
| 4878 | .unwrap() |
| 4879 | .owner(&plugin_id) |
| 4880 | .is_none() |
| 4881 | ); |
| 4882 | assert_eq!( |
| 4883 | f.manager.shared.core_calls.live_tickets(), |
| 4884 | tickets_before_plug |
| 4885 | ); |
| 4886 | let b_snap_after_disable = super::super::caller_view(&ws_b, None, None).unwrap(); |
| 4887 | assert!( |
| 4888 | b_snap_after_disable |
| 4889 | .get("sync-rev") |
| 4890 | .is_some_and(|p| !p.enabled) |
| 4891 | ); |
| 4892 | drop(plug_guard); |
| 4893 | |
| 4894 | let stale_owner = { |
| 4895 | let mut reg = f.manager.shared.registry.lock().unwrap(); |
| 4896 | let owner = reg |
| 4897 | .begin_owner( |
| 4898 | HostCohort::reviewed(), |
| 4899 | &plugin_id, |
| 4900 | "sync-rev", |
| 4901 | Some(live_auth), |
| 4902 | &loaded.content_hash, |
| 4903 | ) |
| 4904 | .unwrap(); |
| 4905 | reg.mark_active(&owner); |
| 4906 | owner |
| 4907 | }; |
| 4908 | let tickets_before_stale = f.manager.shared.core_calls.live_tickets(); |
| 4909 | let stale_guard = f.begin(&stale_owner, HostCohort::reviewed(), &f.context); |
| 4910 | let tickets_before_rm = f.manager.shared.core_calls.live_tickets(); |
| 4911 | assert!(tickets_before_rm > tickets_before_stale); |
| 4912 | |
| 4913 | let removed = f |
| 4914 | .call_admitted(&f.context, "remove", json!({"target": "sync-rev"})) |
| 4915 | .await |
| 4916 | .unwrap(); |
| 4917 | assert_eq!(removed["application"], "applied", "{removed}"); |
| 4918 | assert!( |
| 4919 | f.manager |
| 4920 | .shared |
| 4921 | .registry |
| 4922 | .lock() |
| 4923 | .unwrap() |
| 4924 | .owner(&plugin_id) |
| 4925 | .is_none() |
| 4926 | ); |
| 4927 | assert_eq!( |
| 4928 | f.manager.shared.core_calls.live_tickets(), |
| 4929 | tickets_before_stale |
| 4930 | ); |
| 4931 | let b_snap_after_rm = super::super::caller_view(&ws_b, None, None).unwrap(); |
| 4932 | assert!(b_snap_after_rm.get("sync-rev").is_none()); |
| 4933 | drop(stale_guard); |
| 4934 | f.manager.shutdown().await; |
| 4935 | } |
| 4936 | |
| 4937 | #[tokio::test(flavor = "current_thread")] |
| 4938 | async fn remote_dsh_with_external_npm_deps_discloses_npm_reach_before_npm_access() { |
| 4939 | use codewhale_net::network_policy::{NetworkPolicy, NetworkPolicyDecider}; |
| 4940 | use codewhale_skill_install::bounded_tar::test_archives::archive_from_entries; |
| 4941 | |
| 4942 | let pkg_json = serde_json::json!({ |
| 4943 | "name": "@demo/remote-dsh", |
| 4944 | "version": "1.0.0", |
| 4945 | "main": "lib/index.js", |
| 4946 | "dependencies": { "zod": "^4.0.0" }, |
| 4947 | "dsh": { "bundle": { "patch": "./cordis.patch.yml" } } |
| 4948 | }) |
| 4949 | .to_string(); |
| 4950 | let archive = archive_from_entries(&[ |
| 4951 | ("dsh-remote/package.json", pkg_json.as_bytes()), |
| 4952 | ( |
| 4953 | "dsh-remote/cordis.patch.yml", |
| 4954 | b"- insert:\n - id: entry\n name: ./lib/index.js\n", |
| 4955 | ), |
| 4956 | ( |
| 4957 | "dsh-remote/lib/index.js", |
| 4958 | b"import { z } from 'zod';\nexport function apply() { return z; }\n", |
| 4959 | ), |
| 4960 | ]); |
| 4961 | |
| 4962 | let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); |
| 4963 | let port = listener.local_addr().unwrap().port(); |
| 4964 | let bodies = vec![archive.clone(), archive]; |
| 4965 | let server = std::thread::spawn(move || { |
| 4966 | for body in bodies { |
| 4967 | let Ok((mut stream, _)) = listener.accept() else { |
| 4968 | return; |
| 4969 | }; |
| 4970 | let mut request = Vec::new(); |
| 4971 | let mut buf = [0_u8; 1024]; |
| 4972 | loop { |
| 4973 | use std::io::Read as _; |
| 4974 | let read = stream.read(&mut buf).unwrap_or(0); |
| 4975 | if read == 0 { |
| 4976 | break; |
| 4977 | } |
| 4978 | request.extend_from_slice(&buf[..read]); |
| 4979 | if request.windows(4).any(|window| window == b"\r\n\r\n") { |
| 4980 | break; |
| 4981 | } |
| 4982 | } |
| 4983 | use std::io::Write as _; |
| 4984 | let head = format!( |
| 4985 | "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", |
| 4986 | body.len() |
| 4987 | ); |
| 4988 | let _ = stream.write_all(head.as_bytes()); |
| 4989 | let _ = stream.write_all(&body); |
| 4990 | let _ = stream.flush(); |
| 4991 | } |
| 4992 | }); |
| 4993 | |
| 4994 | let url = format!("http://127.0.0.1:{port}/plugin.tar.gz"); |
| 4995 | let expected_archive_reach = format!("{url} from 127.0.0.1"); |
| 4996 | let expected_npm_reach = format!("{url} npm dependencies from registry.npmjs.org"); |
| 4997 | |
| 4998 | let mut f = PluginsFixture::new(); |
| 4999 | f.reload_registry(); |
| 5000 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 5001 | |
| 5002 | let net_policy = NetworkPolicy { |
| 5003 | allow: vec!["127.0.0.1".to_string()], |
| 5004 | ..NetworkPolicy::default() |
| 5005 | }; |
| 5006 | let net_ctx = f |
| 5007 | .context |
| 5008 | .clone() |
| 5009 | .with_network_policy(NetworkPolicyDecider::new(net_policy, None)); |
| 5010 | |
| 5011 | let (prompt_res, prompt_receipts) = f |
| 5012 | .call_admitted_with_receipts(&net_ctx, "install", json!({"target": url})) |
| 5013 | .await; |
| 5014 | let prompt_res = prompt_res.unwrap(); |
| 5015 | assert_eq!(prompt_res["application"], "failed", "{prompt_res}"); |
| 5016 | assert_eq!(prompt_res["changed"], false); |
| 5017 | assert_eq!(prompt_res["error"]["code"], "operation-error"); |
| 5018 | assert!( |
| 5019 | prompt_res["error"]["diagnostic"] |
| 5020 | .as_str() |
| 5021 | .unwrap() |
| 5022 | .to_ascii_lowercase() |
| 5023 | .contains("network approval required for registry.npmjs.org"), |
| 5024 | "{prompt_res}" |
| 5025 | ); |
| 5026 | let prompt_reaches: Vec<Value> = prompt_receipts["broker_acts"]["acts"] |
| 5027 | .as_array() |
| 5028 | .unwrap() |
| 5029 | .iter() |
| 5030 | .filter(|act| act["effect"] == "reach") |
| 5031 | .cloned() |
| 5032 | .collect(); |
| 5033 | assert_eq!(prompt_reaches.len(), 2, "{prompt_receipts}"); |
| 5034 | assert_eq!(prompt_reaches[0]["target"], expected_archive_reach); |
| 5035 | assert_eq!(prompt_reaches[0]["outcome"], "allowed"); |
| 5036 | assert_eq!(prompt_reaches[0]["decider"], "person"); |
| 5037 | assert_eq!(prompt_reaches[1]["target"], expected_npm_reach); |
| 5038 | assert_eq!(prompt_reaches[1]["outcome"], "allowed"); |
| 5039 | assert_eq!(prompt_reaches[1]["decider"], "person"); |
| 5040 | assert_eq!(fs::read_dir(&f.config.user_plugins_dir).unwrap().count(), 0); |
| 5041 | |
| 5042 | let one_slot_plan = plan_change_async( |
| 5043 | &net_ctx, |
| 5044 | &broker_to_pm_input("install", &json!({"target": url})), |
| 5045 | &CancellationToken::new(), |
| 5046 | ) |
| 5047 | .await |
| 5048 | .unwrap(); |
| 5049 | let mut one_slot_carrier = one_slot_plan |
| 5050 | .build_carrier(CreatorDecider::Person, f.posture.read()) |
| 5051 | .unwrap(); |
| 5052 | if let AdmittedChangeKind::UnseenFetchInstall { |
| 5053 | remaining_reach, .. |
| 5054 | } = &mut one_slot_carrier.change |
| 5055 | { |
| 5056 | *remaining_reach = Arc::new(AtomicUsize::new(1)); |
| 5057 | } |
| 5058 | let deny_ctx = net_ctx.with_creator_decision(one_slot_carrier); |
| 5059 | let deny_guard = f.begin(&f.creator, HostCohort::Builtin, &deny_ctx); |
| 5060 | let deny_ticket = plugin_ticket(&deny_guard).unwrap(); |
| 5061 | let deny_res = f |
| 5062 | .call_broker( |
| 5063 | &f.creator, |
| 5064 | HostCohort::Builtin, |
| 5065 | &deny_ticket, |
| 5066 | "install", |
| 5067 | json!({"target": url}), |
| 5068 | ) |
| 5069 | .await; |
| 5070 | assert_eq!(refusal(&deny_res), (error_code::REFUSED, "refused".into())); |
| 5071 | let deny_receipts = deny_guard.receipts().unwrap(); |
| 5072 | let deny_reaches: Vec<Value> = deny_receipts["broker_acts"]["acts"] |
| 5073 | .as_array() |
| 5074 | .unwrap() |
| 5075 | .iter() |
| 5076 | .filter(|act| act["effect"] == "reach") |
| 5077 | .cloned() |
| 5078 | .collect(); |
| 5079 | assert_eq!(deny_reaches.len(), 2, "{deny_receipts}"); |
| 5080 | assert_eq!(deny_reaches[0]["target"], expected_archive_reach); |
| 5081 | assert_eq!(deny_reaches[0]["outcome"], "allowed"); |
| 5082 | assert_eq!(deny_reaches[1]["target"], expected_npm_reach); |
| 5083 | assert_eq!(deny_reaches[1]["outcome"], "refused"); |
| 5084 | assert_eq!(fs::read_dir(&f.config.user_plugins_dir).unwrap().count(), 0); |
| 5085 | let _ = server.join(); |
| 5086 | } |
| 5087 | |
| 5088 | #[tokio::test(flavor = "current_thread")] |
| 5089 | async fn plugins_install_prefers_dsh_package_when_plugin_json_also_present() { |
| 5090 | let mut f = PluginsFixture::new(); |
| 5091 | |
| 5092 | let dsh_dual = f.config.workspace.join("dsh-dual-clean"); |
| 5093 | copy_dir_tree(&dsh_template_dir("decoration"), &dsh_dual); |
| 5094 | let (conversion, _) = codewhale_plugins::install::preview_dsh(&dsh_dual).unwrap(); |
| 5095 | let mut sibling = serde_json::Map::new(); |
| 5096 | sibling.insert( |
| 5097 | "$schema".to_string(), |
| 5098 | Value::String(codewhale_plugins::agent_plugin::PLUGIN_SCHEMA_URL.to_string()), |
| 5099 | ); |
| 5100 | sibling.insert( |
| 5101 | "name".to_string(), |
| 5102 | Value::String(conversion.plugin_name.clone()), |
| 5103 | ); |
| 5104 | if let Some(version) = &conversion.source_version { |
| 5105 | sibling.insert("version".to_string(), Value::String(version.clone())); |
| 5106 | } |
| 5107 | fs::write( |
| 5108 | dsh_dual.join("plugin.json"), |
| 5109 | serde_json::to_string_pretty(&Value::Object(sibling)).unwrap(), |
| 5110 | ) |
| 5111 | .unwrap(); |
| 5112 | |
| 5113 | f.reload_registry(); |
| 5114 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 5115 | let installed = f |
| 5116 | .call_admitted( |
| 5117 | &f.context, |
| 5118 | "install", |
| 5119 | json!({"target": dsh_dual.to_string_lossy(), "enabled": false}), |
| 5120 | ) |
| 5121 | .await |
| 5122 | .unwrap(); |
| 5123 | assert_eq!(installed["application"], "applied", "{installed}"); |
| 5124 | assert_eq!(installed["changed"], true); |
| 5125 | let receipt = read_install_receipt(&f.config.user_plugins_dir.join(&conversion.plugin_name)); |
| 5126 | assert!( |
| 5127 | receipt["spec"] |
| 5128 | .as_str() |
| 5129 | .is_some_and(|spec| spec.starts_with("dsh:")), |
| 5130 | "{receipt}" |
| 5131 | ); |
| 5132 | |
| 5133 | let dsh_dual_npm = f.config.workspace.join("dsh-dual-npm"); |
| 5134 | copy_dir_tree(&dsh_template_dir("decoration"), &dsh_dual_npm); |
| 5135 | let (npm_conv, _) = codewhale_plugins::install::preview_dsh(&dsh_dual_npm).unwrap(); |
| 5136 | let mut npm_sibling = serde_json::Map::new(); |
| 5137 | npm_sibling.insert( |
| 5138 | "$schema".to_string(), |
| 5139 | Value::String(codewhale_plugins::agent_plugin::PLUGIN_SCHEMA_URL.to_string()), |
| 5140 | ); |
| 5141 | npm_sibling.insert( |
| 5142 | "name".to_string(), |
| 5143 | Value::String(npm_conv.plugin_name.clone()), |
| 5144 | ); |
| 5145 | if let Some(version) = &npm_conv.source_version { |
| 5146 | npm_sibling.insert("version".to_string(), Value::String(version.clone())); |
| 5147 | } |
| 5148 | fs::write( |
| 5149 | dsh_dual_npm.join("plugin.json"), |
| 5150 | serde_json::to_string_pretty(&Value::Object(npm_sibling)).unwrap(), |
| 5151 | ) |
| 5152 | .unwrap(); |
| 5153 | let mut pkg_json: Value = |
| 5154 | serde_json::from_str(&fs::read_to_string(dsh_dual_npm.join("package.json")).unwrap()) |
| 5155 | .unwrap(); |
| 5156 | pkg_json["dependencies"] = json!({"zod": "^4.0.0"}); |
| 5157 | fs::write( |
| 5158 | dsh_dual_npm.join("package.json"), |
| 5159 | serde_json::to_string_pretty(&pkg_json).unwrap(), |
| 5160 | ) |
| 5161 | .unwrap(); |
| 5162 | fs::write( |
| 5163 | dsh_dual_npm.join("index.js"), |
| 5164 | "import { z } from 'zod';\nexport function apply() { return z; }\n", |
| 5165 | ) |
| 5166 | .unwrap(); |
| 5167 | |
| 5168 | f.reload_registry(); |
| 5169 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 5170 | let blocked_ctx = f.context.clone().with_network_policy( |
| 5171 | codewhale_net::network_policy::NetworkPolicyDecider::new( |
| 5172 | codewhale_net::network_policy::NetworkPolicy::default(), |
| 5173 | None, |
| 5174 | ), |
| 5175 | ); |
| 5176 | let npm_res = f |
| 5177 | .call_admitted( |
| 5178 | &blocked_ctx, |
| 5179 | "install", |
| 5180 | json!({"target": dsh_dual_npm.to_string_lossy()}), |
| 5181 | ) |
| 5182 | .await |
| 5183 | .unwrap(); |
| 5184 | assert_eq!(npm_res["application"], "failed", "{npm_res}"); |
| 5185 | assert_eq!(npm_res["changed"], false); |
| 5186 | assert_eq!(npm_res["error"]["code"], "operation-error"); |
| 5187 | assert!( |
| 5188 | npm_res["error"]["diagnostic"] |
| 5189 | .as_str() |
| 5190 | .unwrap() |
| 5191 | .contains("registry.npmjs.org"), |
| 5192 | "{npm_res}" |
| 5193 | ); |
| 5194 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 5195 | } |
| 5196 | |
| 5197 | #[tokio::test(flavor = "current_thread")] |
| 5198 | async fn a_call_admitted_as_a_list_cannot_change_anything() { |
| 5199 | let mut f = PluginsFixture::new(); |
| 5200 | let src = write_skill_bundle(&f.config.workspace, "list-src", "list-plug", "1.0.0"); |
| 5201 | f.reload_registry(); |
| 5202 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 5203 | |
| 5204 | let seeded = f |
| 5205 | .call_admitted( |
| 5206 | &f.context, |
| 5207 | "install", |
| 5208 | json!({"target": src.to_string_lossy()}), |
| 5209 | ) |
| 5210 | .await |
| 5211 | .unwrap(); |
| 5212 | assert_eq!(seeded["application"], "applied"); |
| 5213 | |
| 5214 | let list_input = json!({"action": "list_plugins"}); |
| 5215 | assert!( |
| 5216 | plan_change_async(&f.context, &list_input, &CancellationToken::new()) |
| 5217 | .await |
| 5218 | .is_err() |
| 5219 | ); |
| 5220 | |
| 5221 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 5222 | let ticket = plugin_ticket(&guard).unwrap(); |
| 5223 | let listed = f |
| 5224 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "list", json!({})) |
| 5225 | .await |
| 5226 | .unwrap(); |
| 5227 | assert!(listed["entries"].is_array()); |
| 5228 | |
| 5229 | for (method, input) in [ |
| 5230 | ("install", json!({"target": src.to_string_lossy()})), |
| 5231 | ("disable", json!({"target": "list-plug"})), |
| 5232 | ("enable", json!({"target": "list-plug"})), |
| 5233 | ("remove", json!({"target": "list-plug"})), |
| 5234 | ] { |
| 5235 | let err = f |
| 5236 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, method, input) |
| 5237 | .await; |
| 5238 | assert_eq!( |
| 5239 | refusal(&err), |
| 5240 | (error_code::REFUSED, "refused".into()), |
| 5241 | "{method}" |
| 5242 | ); |
| 5243 | } |
| 5244 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 5245 | } |
| 5246 | |
| 5247 | #[tokio::test(flavor = "current_thread")] |
| 5248 | async fn one_admitted_change_admits_one_act() { |
| 5249 | let mut f = PluginsFixture::new(); |
| 5250 | let src = write_skill_bundle(&f.config.workspace, "once-src", "once-plug", "1.0.0"); |
| 5251 | f.reload_registry(); |
| 5252 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 5253 | |
| 5254 | let install_input = json!({"target": src.to_string_lossy()}); |
| 5255 | let once_ctx = f |
| 5256 | .admit_context( |
| 5257 | &f.context, |
| 5258 | "install", |
| 5259 | &install_input, |
| 5260 | CreatorDecider::Agent(AgentPosture::FullAccess), |
| 5261 | ) |
| 5262 | .await |
| 5263 | .unwrap(); |
| 5264 | |
| 5265 | let g1 = f.begin(&f.creator, HostCohort::Builtin, &once_ctx); |
| 5266 | let t1 = plugin_ticket(&g1).unwrap(); |
| 5267 | let ok = f |
| 5268 | .call_broker( |
| 5269 | &f.creator, |
| 5270 | HostCohort::Builtin, |
| 5271 | &t1, |
| 5272 | "install", |
| 5273 | install_input.clone(), |
| 5274 | ) |
| 5275 | .await |
| 5276 | .unwrap(); |
| 5277 | assert_eq!(ok["application"], "applied"); |
| 5278 | drop(g1); |
| 5279 | |
| 5280 | let g_rm = f.begin(&f.creator, HostCohort::Builtin, &once_ctx); |
| 5281 | let t_rm = plugin_ticket(&g_rm).unwrap(); |
| 5282 | let wrong_action = f |
| 5283 | .call_broker( |
| 5284 | &f.creator, |
| 5285 | HostCohort::Builtin, |
| 5286 | &t_rm, |
| 5287 | "remove", |
| 5288 | json!({"target": "once-plug"}), |
| 5289 | ) |
| 5290 | .await; |
| 5291 | assert_eq!( |
| 5292 | refusal(&wrong_action), |
| 5293 | (error_code::REFUSED, "refused".into()) |
| 5294 | ); |
| 5295 | drop(g_rm); |
| 5296 | |
| 5297 | f.call_admitted(&f.context, "remove", json!({"target": "once-plug"})) |
| 5298 | .await |
| 5299 | .unwrap(); |
| 5300 | |
| 5301 | let g2 = f.begin(&f.creator, HostCohort::Builtin, &once_ctx); |
| 5302 | let t2 = plugin_ticket(&g2).unwrap(); |
| 5303 | let replay = f |
| 5304 | .call_broker( |
| 5305 | &f.creator, |
| 5306 | HostCohort::Builtin, |
| 5307 | &t2, |
| 5308 | "install", |
| 5309 | install_input, |
| 5310 | ) |
| 5311 | .await; |
| 5312 | assert_eq!(refusal(&replay), (error_code::REFUSED, "refused".into())); |
| 5313 | assert!(!f.config.user_plugins_dir.join("once-plug").exists()); |
| 5314 | } |
| 5315 | |
| 5316 | #[tokio::test(flavor = "current_thread")] |
| 5317 | async fn arm_refuses_without_carried_decision() { |
| 5318 | let mut f = PluginsFixture::new(); |
| 5319 | let src = write_skill_bundle(&f.config.workspace, "nod-src", "nod-plug", "1.0.0"); |
| 5320 | f.reload_registry(); |
| 5321 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 5322 | |
| 5323 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 5324 | let ticket = plugin_ticket(&guard).unwrap(); |
| 5325 | |
| 5326 | let list_ok = f |
| 5327 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "list", json!({})) |
| 5328 | .await; |
| 5329 | assert!(list_ok.is_ok()); |
| 5330 | |
| 5331 | for (method, input) in [ |
| 5332 | ("install", json!({"target": src.to_string_lossy()})), |
| 5333 | ("disable", json!({"target": "nod-plug"})), |
| 5334 | ("enable", json!({"target": "nod-plug"})), |
| 5335 | ("remove", json!({"target": "nod-plug"})), |
| 5336 | ] { |
| 5337 | let err = f |
| 5338 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, method, input) |
| 5339 | .await; |
| 5340 | assert_eq!( |
| 5341 | refusal(&err), |
| 5342 | (error_code::REFUSED, "refused".into()), |
| 5343 | "{method}" |
| 5344 | ); |
| 5345 | } |
| 5346 | assert_eq!(f.asked.load(Ordering::SeqCst), 0); |
| 5347 | } |
| 5348 | |
| 5349 | type GateCallLog = Arc<std::sync::Mutex<Vec<(String, Option<String>)>>>; |
| 5350 | |
| 5351 | fn allow_verdict(input: &Value, decision: NestedDecision) -> NestedCallVerdict { |
| 5352 | NestedCallVerdict::Run { |
| 5353 | name: String::new(), |
| 5354 | input: input.clone(), |
| 5355 | supports_parallel: false, |
| 5356 | decision, |
| 5357 | hook_context: None, |
| 5358 | } |
| 5359 | } |
| 5360 | |
| 5361 | fn deny_verdict(message: &str) -> NestedCallVerdict { |
| 5362 | NestedCallVerdict::Refused { |
| 5363 | error: ToolError::permission_denied(message), |
| 5364 | decision: NestedDecision::Denied, |
| 5365 | } |
| 5366 | } |
| 5367 | |
| 5368 | fn install_gate_with_pool( |
| 5369 | f: &mut PluginsFixture, |
| 5370 | mcp_pool: Option<Arc<tokio::sync::Mutex<crate::mcp::McpPool>>>, |
| 5371 | on_call: impl Fn(&Value, &LivePosture) -> NestedCallVerdict + Send + Sync + 'static, |
| 5372 | ) -> GateCallLog { |
| 5373 | let seen = Arc::new(std::sync::Mutex::new(Vec::new())); |
| 5374 | let seen_ref = Arc::clone(&seen); |
| 5375 | let asked_ref = Arc::clone(&f.asked); |
| 5376 | let posture_ref = f.posture.clone(); |
| 5377 | let (tx_event, mut rx_event) = tokio::sync::mpsc::channel(64); |
| 5378 | tokio::spawn(async move { while rx_event.recv().await.is_some() {} }); |
| 5379 | let (gate, mut requests) = |
| 5380 | NestedCallGate::new(mcp_pool, tx_event, std::time::Duration::from_secs(60)); |
| 5381 | tokio::spawn(async move { |
| 5382 | while let Some(request) = requests.recv().await { |
| 5383 | let request = match request { |
| 5384 | crate::tools::codemode::NestedCallRequest::Tool(request) => request, |
| 5385 | crate::tools::codemode::NestedCallRequest::UserQuestion { reply, .. } => { |
| 5386 | let _ = reply.send(Err(ToolError::not_available( |
| 5387 | "fixture has no user question backend", |
| 5388 | ))); |
| 5389 | continue; |
| 5390 | } |
| 5391 | crate::tools::codemode::NestedCallRequest::Checkpoint { reply, .. } => { |
| 5392 | let _ = reply.send(Err(ToolError::not_available( |
| 5393 | "fixture has no session checkpoint backend", |
| 5394 | ))); |
| 5395 | continue; |
| 5396 | } |
| 5397 | }; |
| 5398 | asked_ref.fetch_add(1, Ordering::SeqCst); |
| 5399 | let target = request |
| 5400 | .input |
| 5401 | .get("target") |
| 5402 | .and_then(Value::as_str) |
| 5403 | .map(str::to_string); |
| 5404 | seen_ref |
| 5405 | .lock() |
| 5406 | .unwrap() |
| 5407 | .push((request.name.clone(), target)); |
| 5408 | let mut verdict = on_call(&request.input, &posture_ref); |
| 5409 | if let NestedCallVerdict::Run { |
| 5410 | name: ref mut verdict_name, |
| 5411 | .. |
| 5412 | } = verdict |
| 5413 | && verdict_name.is_empty() |
| 5414 | { |
| 5415 | *verdict_name = request.name.clone(); |
| 5416 | } |
| 5417 | let _ = request.reply.send(verdict); |
| 5418 | } |
| 5419 | }); |
| 5420 | f.gate = gate.for_extension( |
| 5421 | ExtensionCaller { |
| 5422 | origin: "extension:creator".to_string(), |
| 5423 | tool: "creator_tool".to_string(), |
| 5424 | scope: "ext:host:creator@digest".to_string(), |
| 5425 | }, |
| 5426 | BrokerActTool::all().to_vec(), |
| 5427 | ); |
| 5428 | seen |
| 5429 | } |
| 5430 | |
| 5431 | #[derive(Clone)] |
| 5432 | enum McpStubBehavior { |
| 5433 | Ready(Vec<Value>), |
| 5434 | Fail500, |
| 5435 | Hang, |
| 5436 | } |
| 5437 | |
| 5438 | struct McpStubServer { |
| 5439 | addr: std::net::SocketAddr, |
| 5440 | hits: Arc<AtomicUsize>, |
| 5441 | post_hits: Arc<AtomicUsize>, |
| 5442 | init_hits: Arc<AtomicUsize>, |
| 5443 | task: tokio::task::JoinHandle<()>, |
| 5444 | } |
| 5445 | |
| 5446 | impl Drop for McpStubServer { |
| 5447 | fn drop(&mut self) { |
| 5448 | self.task.abort(); |
| 5449 | } |
| 5450 | } |
| 5451 | |
| 5452 | async fn read_stub_http_request(socket: &mut tokio::net::TcpStream) -> Option<String> { |
| 5453 | use tokio::io::AsyncReadExt as _; |
| 5454 | |
| 5455 | let mut request = Vec::new(); |
| 5456 | let mut buf = [0u8; 1024]; |
| 5457 | let header_end = loop { |
| 5458 | let n = socket.read(&mut buf).await.ok()?; |
| 5459 | if n == 0 { |
| 5460 | return None; |
| 5461 | } |
| 5462 | request.extend_from_slice(&buf[..n]); |
| 5463 | if let Some(pos) = request.windows(4).position(|window| window == b"\r\n\r\n") { |
| 5464 | break pos + 4; |
| 5465 | } |
| 5466 | }; |
| 5467 | let headers = String::from_utf8_lossy(&request[..header_end]); |
| 5468 | let content_length = headers |
| 5469 | .lines() |
| 5470 | .find_map(|line| { |
| 5471 | let (name, value) = line.split_once(':')?; |
| 5472 | name.eq_ignore_ascii_case("content-length") |
| 5473 | .then(|| value.trim().parse::<usize>().ok()) |
| 5474 | .flatten() |
| 5475 | }) |
| 5476 | .unwrap_or(0); |
| 5477 | let total_len = header_end + content_length; |
| 5478 | while request.len() < total_len { |
| 5479 | let n = socket.read(&mut buf).await.ok()?; |
| 5480 | if n == 0 { |
| 5481 | return None; |
| 5482 | } |
| 5483 | request.extend_from_slice(&buf[..n]); |
| 5484 | } |
| 5485 | String::from_utf8(request).ok() |
| 5486 | } |
| 5487 | |
| 5488 | async fn write_stub_sse_response(socket: &mut tokio::net::TcpStream, payload: Value) { |
| 5489 | use tokio::io::AsyncWriteExt as _; |
| 5490 | |
| 5491 | let body = format!("event: message\ndata: {payload}\n\n"); |
| 5492 | let response = format!( |
| 5493 | "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\n\r\n{}", |
| 5494 | body.len(), |
| 5495 | body |
| 5496 | ); |
| 5497 | let _ = socket.write_all(response.as_bytes()).await; |
| 5498 | } |
| 5499 | |
| 5500 | impl McpStubServer { |
| 5501 | async fn spawn(behavior: McpStubBehavior) -> Self { |
| 5502 | use tokio::io::AsyncWriteExt as _; |
| 5503 | |
| 5504 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 5505 | let addr = listener.local_addr().unwrap(); |
| 5506 | let hits = Arc::new(AtomicUsize::new(0)); |
| 5507 | let post_hits = Arc::new(AtomicUsize::new(0)); |
| 5508 | let init_hits = Arc::new(AtomicUsize::new(0)); |
| 5509 | let hits_task = Arc::clone(&hits); |
| 5510 | let post_task = Arc::clone(&post_hits); |
| 5511 | let init_task = Arc::clone(&init_hits); |
| 5512 | let task = tokio::spawn(async move { |
| 5513 | loop { |
| 5514 | let Ok((mut socket, _)) = listener.accept().await else { |
| 5515 | break; |
| 5516 | }; |
| 5517 | hits_task.fetch_add(1, Ordering::SeqCst); |
| 5518 | let post_conn = Arc::clone(&post_task); |
| 5519 | let init_conn = Arc::clone(&init_task); |
| 5520 | let behavior_conn = behavior.clone(); |
| 5521 | tokio::spawn(async move { |
| 5522 | match behavior_conn { |
| 5523 | McpStubBehavior::Hang => { |
| 5524 | let _keep_open = socket; |
| 5525 | std::future::pending::<()>().await; |
| 5526 | } |
| 5527 | McpStubBehavior::Fail500 => { |
| 5528 | if let Some(request) = read_stub_http_request(&mut socket).await { |
| 5529 | if request.starts_with("POST ") { |
| 5530 | post_conn.fetch_add(1, Ordering::SeqCst); |
| 5531 | } |
| 5532 | let _ = socket |
| 5533 | .write_all( |
| 5534 | b"HTTP/1.1 500 Internal Server Error\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", |
| 5535 | ) |
| 5536 | .await; |
| 5537 | } |
| 5538 | } |
| 5539 | McpStubBehavior::Ready(tools) => { |
| 5540 | if let Some(request) = read_stub_http_request(&mut socket).await { |
| 5541 | if request.starts_with("POST ") { |
| 5542 | post_conn.fetch_add(1, Ordering::SeqCst); |
| 5543 | } |
| 5544 | if request.starts_with("GET ") { |
| 5545 | let _ = socket |
| 5546 | .write_all( |
| 5547 | b"HTTP/1.1 405 Method Not Allowed\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", |
| 5548 | ) |
| 5549 | .await; |
| 5550 | return; |
| 5551 | } |
| 5552 | let body = request.split("\r\n\r\n").nth(1).unwrap_or(""); |
| 5553 | let Ok(value) = serde_json::from_str::<Value>(body) else { |
| 5554 | return; |
| 5555 | }; |
| 5556 | let method = value["method"].as_str().unwrap_or(""); |
| 5557 | if method == "notifications/initialized" { |
| 5558 | let _ = socket |
| 5559 | .write_all( |
| 5560 | b"HTTP/1.1 202 Accepted\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", |
| 5561 | ) |
| 5562 | .await; |
| 5563 | return; |
| 5564 | } |
| 5565 | let id = value["id"].clone(); |
| 5566 | let result = match method { |
| 5567 | "initialize" => { |
| 5568 | init_conn.fetch_add(1, Ordering::SeqCst); |
| 5569 | json!({ |
| 5570 | "protocolVersion": "2024-11-05", |
| 5571 | "serverInfo": {"name": "stub-mcp", "version": "1.0.0"}, |
| 5572 | "capabilities": {"tools": {}, "resources": {}, "prompts": {}} |
| 5573 | }) |
| 5574 | } |
| 5575 | "tools/list" => json!({ "tools": tools }), |
| 5576 | "resources/list" => json!({"resources": []}), |
| 5577 | "resources/templates/list" => json!({"resourceTemplates": []}), |
| 5578 | "prompts/list" => json!({"prompts": []}), |
| 5579 | other => panic!("unexpected MCP method in stub: {other}"), |
| 5580 | }; |
| 5581 | write_stub_sse_response( |
| 5582 | &mut socket, |
| 5583 | json!({ |
| 5584 | "jsonrpc": "2.0", |
| 5585 | "id": id, |
| 5586 | "result": result |
| 5587 | }), |
| 5588 | ) |
| 5589 | .await; |
| 5590 | } |
| 5591 | } |
| 5592 | } |
| 5593 | }); |
| 5594 | } |
| 5595 | }); |
| 5596 | Self { |
| 5597 | addr, |
| 5598 | hits, |
| 5599 | post_hits, |
| 5600 | init_hits, |
| 5601 | task, |
| 5602 | } |
| 5603 | } |
| 5604 | |
| 5605 | fn url(&self) -> String { |
| 5606 | format!("http://{}/mcp", self.addr) |
| 5607 | } |
| 5608 | |
| 5609 | fn hits(&self) -> usize { |
| 5610 | self.hits.load(Ordering::SeqCst) |
| 5611 | } |
| 5612 | |
| 5613 | fn post_hits(&self) -> usize { |
| 5614 | self.post_hits.load(Ordering::SeqCst) |
| 5615 | } |
| 5616 | |
| 5617 | fn init_hits(&self) -> usize { |
| 5618 | self.init_hits.load(Ordering::SeqCst) |
| 5619 | } |
| 5620 | } |
| 5621 | |
| 5622 | fn dead_loopback_url() -> String { |
| 5623 | let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); |
| 5624 | let port = listener.local_addr().unwrap().port(); |
| 5625 | drop(listener); |
| 5626 | format!("http://127.0.0.1:{port}/mcp") |
| 5627 | } |
| 5628 | |
| 5629 | fn copy_mcp_template_bundle( |
| 5630 | dest: &Path, |
| 5631 | url: &str, |
| 5632 | fail_on_startup_error: Option<bool>, |
| 5633 | row_disabled: bool, |
| 5634 | ) { |
| 5635 | copy_dir_tree(&dsh_template_dir("mcp"), dest); |
| 5636 | let disabled_line = if row_disabled { |
| 5637 | " disabled: true\n" |
| 5638 | } else { |
| 5639 | "" |
| 5640 | }; |
| 5641 | let startup_line = match fail_on_startup_error { |
| 5642 | Some(flag) => format!(" failOnStartupError: {flag}\n"), |
| 5643 | None => String::new(), |
| 5644 | }; |
| 5645 | let patch = format!( |
| 5646 | "- insert:\n - id: demo-mcp\n{disabled_line} name: '@deepseek-ai/dsh-mcp-client'\n config:\n serverName: demo\n transport: streamable-http\n url: {url}\n{startup_line}" |
| 5647 | ); |
| 5648 | fs::write(dest.join("cordis.patch.yml"), patch).unwrap(); |
| 5649 | } |
| 5650 | |
| 5651 | fn fixture_mcp_pool(f: &PluginsFixture) -> Arc<tokio::sync::Mutex<crate::mcp::McpPool>> { |
| 5652 | let mcp_path = f._temp.path().join("global-mcp.json"); |
| 5653 | if !mcp_path.exists() { |
| 5654 | fs::write(&mcp_path, "{}").unwrap(); |
| 5655 | } |
| 5656 | let pool = crate::mcp::McpPool::from_config_path_with_workspace(&mcp_path, &f.config.workspace) |
| 5657 | .unwrap() |
| 5658 | .with_backend(codewhale_config::McpBackend::Rust); |
| 5659 | Arc::new(tokio::sync::Mutex::new(pool)) |
| 5660 | } |
| 5661 | |
| 5662 | #[tokio::test(flavor = "current_thread")] |
| 5663 | async fn plugins_answering_required_dsh_connector_succeeds_and_lists_tools_for_next_message() { |
| 5664 | let _policy = TestPolicyGuard::extension_host(false); |
| 5665 | let mut f = PluginsFixture::new(); |
| 5666 | f.reload_registry(); |
| 5667 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 5668 | let pool = fixture_mcp_pool(&f); |
| 5669 | install_gate_with_pool(&mut f, Some(pool), |input, _| { |
| 5670 | allow_verdict(input, NestedDecision::Auto) |
| 5671 | }); |
| 5672 | |
| 5673 | let server = McpStubServer::spawn(McpStubBehavior::Ready(vec![ |
| 5674 | json!({ |
| 5675 | "name": "read_wiki", |
| 5676 | "description": "Read docs", |
| 5677 | "inputSchema": {"type": "object"} |
| 5678 | }), |
| 5679 | json!({ |
| 5680 | "name": "\x1b[31mhostile\u{202e}_tool_Bearer sk-secret123456", |
| 5681 | "description": "Hostile name", |
| 5682 | "inputSchema": {"type": "object"} |
| 5683 | }), |
| 5684 | ])) |
| 5685 | .await; |
| 5686 | |
| 5687 | let src = f.config.workspace.join("mcp-ok-src"); |
| 5688 | copy_mcp_template_bundle(&src, &server.url(), Some(true), false); |
| 5689 | let input = json!({"target": src.to_string_lossy()}); |
| 5690 | let admitted = f |
| 5691 | .admit_context( |
| 5692 | &f.context, |
| 5693 | "install", |
| 5694 | &input, |
| 5695 | decider_for_posture(&f.posture.read()), |
| 5696 | ) |
| 5697 | .await |
| 5698 | .unwrap(); |
| 5699 | let guard = f.begin(&f.creator, HostCohort::Builtin, &admitted); |
| 5700 | let ticket = plugin_ticket(&guard).unwrap(); |
| 5701 | |
| 5702 | let res = f |
| 5703 | .call_broker(&f.creator, HostCohort::Builtin, &ticket, "install", input) |
| 5704 | .await |
| 5705 | .unwrap(); |
| 5706 | assert_eq!(res["application"], "applied", "{res}"); |
| 5707 | assert_eq!(res["stage"], "enable"); |
| 5708 | assert_eq!(res["changed"], true); |
| 5709 | assert_eq!(res["enabled"], true); |
| 5710 | assert_eq!(res["bundle"], "demo-mcp"); |
| 5711 | assert_eq!(server.init_hits(), 1); |
| 5712 | |
| 5713 | let qualified = crate::mcp::qualified_plugin_server_name("demo-mcp", "demo"); |
| 5714 | let expected_tool = crate::mcp::McpPool::mcp_model_tool_name(&qualified, "read_wiki"); |
| 5715 | let warnings: Vec<&str> = res["warnings"] |
| 5716 | .as_array() |
| 5717 | .unwrap() |
| 5718 | .iter() |
| 5719 | .filter_map(Value::as_str) |
| 5720 | .collect(); |
| 5721 | assert!( |
| 5722 | warnings.iter().any(|w| w.contains(&expected_tool)), |
| 5723 | "expected {expected_tool} in warnings: {warnings:?}" |
| 5724 | ); |
| 5725 | assert!( |
| 5726 | warnings.iter().any(|w| w.contains("next message on")), |
| 5727 | "expected next-message guidance in warnings: {warnings:?}" |
| 5728 | ); |
| 5729 | let joined = warnings.join("\n"); |
| 5730 | assert!(!joined.contains('\x1b'), "{warnings:?}"); |
| 5731 | assert!(!joined.contains('\u{202e}'), "{warnings:?}"); |
| 5732 | assert!(!joined.contains("sk-secret123456"), "{warnings:?}"); |
| 5733 | |
| 5734 | let receipts = guard.seal_receipts().unwrap(); |
| 5735 | let acts = receipts["broker_acts"]["acts"].as_array().unwrap(); |
| 5736 | assert!( |
| 5737 | acts.iter().any(|act| { |
| 5738 | act["service"] == "plugins" |
| 5739 | && act["method"] == "mcp_connect" |
| 5740 | && act["server"] == "demo" |
| 5741 | && act["outcome"] == "connected" |
| 5742 | }), |
| 5743 | "{receipts}" |
| 5744 | ); |
| 5745 | } |
| 5746 | |
| 5747 | #[tokio::test(flavor = "current_thread")] |
| 5748 | async fn plugins_silent_required_dsh_connector_fails_with_connector_defined_on_disk() { |
| 5749 | let mut f = PluginsFixture::new(); |
| 5750 | f.reload_registry(); |
| 5751 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 5752 | let pool = fixture_mcp_pool(&f); |
| 5753 | install_gate_with_pool(&mut f, Some(pool), |input, _| { |
| 5754 | allow_verdict(input, NestedDecision::Auto) |
| 5755 | }); |
| 5756 | |
| 5757 | let server = McpStubServer::spawn(McpStubBehavior::Fail500).await; |
| 5758 | let src = f.config.workspace.join("mcp-fail-src"); |
| 5759 | copy_mcp_template_bundle(&src, &server.url(), Some(true), false); |
| 5760 | let res = f |
| 5761 | .call_admitted( |
| 5762 | &f.context, |
| 5763 | "install", |
| 5764 | json!({"target": src.to_string_lossy()}), |
| 5765 | ) |
| 5766 | .await |
| 5767 | .unwrap(); |
| 5768 | assert_eq!(res["application"], "failed", "{res}"); |
| 5769 | assert_eq!(res["stage"], "enable"); |
| 5770 | assert_eq!(res["changed"], true); |
| 5771 | assert_eq!(res["enabled"], true); |
| 5772 | assert_eq!(res["error"]["code"], "operation-error"); |
| 5773 | assert!( |
| 5774 | res["error"]["diagnostic"] |
| 5775 | .as_str() |
| 5776 | .is_some_and(|d| d.contains("demo")), |
| 5777 | "{res}" |
| 5778 | ); |
| 5779 | |
| 5780 | let fresh = discover_with_config(&f.config); |
| 5781 | let plugin = fresh.get("demo-mcp").expect("connector remains defined"); |
| 5782 | assert!(plugin.enabled); |
| 5783 | assert!(plugin.manifest.mcp_servers.as_ref().unwrap()["demo"].required); |
| 5784 | } |
| 5785 | |
| 5786 | #[tokio::test(flavor = "current_thread")] |
| 5787 | async fn plugins_bundle_without_flag_makes_no_attempt_and_warns_with_prefix() { |
| 5788 | for flag in [Some(false), None] { |
| 5789 | let mut f = PluginsFixture::new(); |
| 5790 | f.reload_registry(); |
| 5791 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 5792 | let pool = fixture_mcp_pool(&f); |
| 5793 | install_gate_with_pool(&mut f, Some(pool), |input, _| { |
| 5794 | allow_verdict(input, NestedDecision::Auto) |
| 5795 | }); |
| 5796 | |
| 5797 | let server = McpStubServer::spawn(McpStubBehavior::Fail500).await; |
| 5798 | let src = f.config.workspace.join("mcp-optional-src"); |
| 5799 | copy_mcp_template_bundle(&src, &server.url(), flag, false); |
| 5800 | let res = f |
| 5801 | .call_admitted( |
| 5802 | &f.context, |
| 5803 | "install", |
| 5804 | json!({"target": src.to_string_lossy()}), |
| 5805 | ) |
| 5806 | .await |
| 5807 | .unwrap(); |
| 5808 | assert_eq!(res["application"], "applied", "{res}"); |
| 5809 | assert_eq!(server.hits(), 0, "optional connector must not connect"); |
| 5810 | |
| 5811 | let qualified = crate::mcp::qualified_plugin_server_name("demo-mcp", "demo"); |
| 5812 | let expected_prefix = format!("mcp_{qualified}_"); |
| 5813 | let warnings: Vec<&str> = res["warnings"] |
| 5814 | .as_array() |
| 5815 | .unwrap() |
| 5816 | .iter() |
| 5817 | .filter_map(Value::as_str) |
| 5818 | .collect(); |
| 5819 | assert!( |
| 5820 | warnings.iter().any(|w| w.contains(&expected_prefix)), |
| 5821 | "expected {expected_prefix} in warnings: {warnings:?}" |
| 5822 | ); |
| 5823 | assert!( |
| 5824 | warnings.iter().any(|w| w.contains("next message on")), |
| 5825 | "{warnings:?}" |
| 5826 | ); |
| 5827 | } |
| 5828 | } |
| 5829 | |
| 5830 | #[tokio::test(flavor = "current_thread")] |
| 5831 | async fn plugins_refused_install_makes_no_attempt() { |
| 5832 | let mut f = PluginsFixture::new(); |
| 5833 | f.reload_registry(); |
| 5834 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 5835 | let pool = fixture_mcp_pool(&f); |
| 5836 | install_gate_with_pool(&mut f, Some(pool), |_, _| deny_verdict("not approved")); |
| 5837 | |
| 5838 | let server = McpStubServer::spawn(McpStubBehavior::Fail500).await; |
| 5839 | let src = f.config.workspace.join("mcp-refused-src"); |
| 5840 | copy_mcp_template_bundle(&src, &server.url(), Some(true), false); |
| 5841 | let guard = f.begin(&f.creator, HostCohort::Builtin, &f.context); |
| 5842 | let ticket = plugin_ticket(&guard).unwrap(); |
| 5843 | |
| 5844 | let res = f |
| 5845 | .call_broker( |
| 5846 | &f.creator, |
| 5847 | HostCohort::Builtin, |
| 5848 | &ticket, |
| 5849 | "install", |
| 5850 | json!({"target": src.to_string_lossy()}), |
| 5851 | ) |
| 5852 | .await; |
| 5853 | assert_eq!(refusal(&res), (error_code::REFUSED, "refused".into())); |
| 5854 | assert_eq!(server.hits(), 0); |
| 5855 | } |
| 5856 | |
| 5857 | #[tokio::test(flavor = "current_thread")] |
| 5858 | async fn plugins_enable_of_required_connector_attempts_live_connection() { |
| 5859 | let mut f = PluginsFixture::new(); |
| 5860 | f.reload_registry(); |
| 5861 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 5862 | let pool = fixture_mcp_pool(&f); |
| 5863 | install_gate_with_pool(&mut f, Some(pool), |input, _| { |
| 5864 | allow_verdict(input, NestedDecision::Auto) |
| 5865 | }); |
| 5866 | |
| 5867 | let server = McpStubServer::spawn(McpStubBehavior::Ready(vec![json!({ |
| 5868 | "name": "ping", |
| 5869 | "description": "Ping tool", |
| 5870 | "inputSchema": {"type": "object"} |
| 5871 | })])) |
| 5872 | .await; |
| 5873 | let src = f.config.workspace.join("mcp-enable-src"); |
| 5874 | copy_mcp_template_bundle(&src, &server.url(), Some(true), false); |
| 5875 | |
| 5876 | let installed_disabled = f |
| 5877 | .call_admitted( |
| 5878 | &f.context, |
| 5879 | "install", |
| 5880 | json!({"target": src.to_string_lossy(), "enabled": false}), |
| 5881 | ) |
| 5882 | .await |
| 5883 | .unwrap(); |
| 5884 | assert_eq!( |
| 5885 | installed_disabled["application"], "applied", |
| 5886 | "{installed_disabled}" |
| 5887 | ); |
| 5888 | assert_eq!(installed_disabled["enabled"], false); |
| 5889 | assert_eq!( |
| 5890 | server.hits(), |
| 5891 | 0, |
| 5892 | "install with enabled: false must not attempt connection" |
| 5893 | ); |
| 5894 | |
| 5895 | let enabled = f |
| 5896 | .call_admitted(&f.context, "enable", json!({"target": "demo-mcp"})) |
| 5897 | .await |
| 5898 | .unwrap(); |
| 5899 | assert_eq!(enabled["application"], "applied", "{enabled}"); |
| 5900 | assert_eq!(enabled["stage"], "enable"); |
| 5901 | assert_eq!(enabled["enabled"], true); |
| 5902 | assert_eq!(server.init_hits(), 1); |
| 5903 | let qualified = crate::mcp::qualified_plugin_server_name("demo-mcp", "demo"); |
| 5904 | let expected_tool = crate::mcp::McpPool::mcp_model_tool_name(&qualified, "ping"); |
| 5905 | let warnings: Vec<&str> = enabled["warnings"] |
| 5906 | .as_array() |
| 5907 | .unwrap() |
| 5908 | .iter() |
| 5909 | .filter_map(Value::as_str) |
| 5910 | .collect(); |
| 5911 | assert!( |
| 5912 | warnings.iter().any(|w| w.contains(&expected_tool)), |
| 5913 | "{warnings:?}" |
| 5914 | ); |
| 5915 | assert!( |
| 5916 | warnings.iter().any(|w| w.contains("next message on")), |
| 5917 | "{warnings:?}" |
| 5918 | ); |
| 5919 | |
| 5920 | let dead_src = f.config.workspace.join("mcp-enable-dead-src"); |
| 5921 | let dead_url = dead_loopback_url(); |
| 5922 | copy_mcp_template_bundle(&dead_src, &dead_url, Some(true), false); |
| 5923 | let pkg = serde_json::json!({ |
| 5924 | "name": "@local/demo-dead", |
| 5925 | "version": "1.0.0", |
| 5926 | "private": true, |
| 5927 | "type": "module", |
| 5928 | "exports": { "./locale/*.json": "./locale/*.json", "./icon": "./icon.svg" }, |
| 5929 | "files": ["cordis.patch.yml", "locale/*.json", "icon.svg"], |
| 5930 | "dsh": { "bundle": { "patch": "./cordis.patch.yml" } } |
| 5931 | }); |
| 5932 | fs::write( |
| 5933 | dead_src.join("package.json"), |
| 5934 | serde_json::to_string_pretty(&pkg).unwrap(), |
| 5935 | ) |
| 5936 | .unwrap(); |
| 5937 | let dead_installed = f |
| 5938 | .call_admitted( |
| 5939 | &f.context, |
| 5940 | "install", |
| 5941 | json!({"target": dead_src.to_string_lossy(), "enabled": false}), |
| 5942 | ) |
| 5943 | .await |
| 5944 | .unwrap(); |
| 5945 | assert_eq!(dead_installed["application"], "applied"); |
| 5946 | let dead_enabled = f |
| 5947 | .call_admitted(&f.context, "enable", json!({"target": "demo-dead"})) |
| 5948 | .await |
| 5949 | .unwrap(); |
| 5950 | assert_eq!(dead_enabled["application"], "failed", "{dead_enabled}"); |
| 5951 | assert_eq!(dead_enabled["stage"], "enable"); |
| 5952 | assert_eq!(dead_enabled["enabled"], true); |
| 5953 | assert_eq!(dead_enabled["error"]["code"], "operation-error"); |
| 5954 | } |
| 5955 | |
| 5956 | #[tokio::test(flavor = "current_thread")] |
| 5957 | async fn plugins_turned_off_row_never_attempts_connection() { |
| 5958 | let mut f = PluginsFixture::new(); |
| 5959 | f.reload_registry(); |
| 5960 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 5961 | let pool = fixture_mcp_pool(&f); |
| 5962 | install_gate_with_pool(&mut f, Some(pool), |input, _| { |
| 5963 | allow_verdict(input, NestedDecision::Auto) |
| 5964 | }); |
| 5965 | |
| 5966 | let server = McpStubServer::spawn(McpStubBehavior::Fail500).await; |
| 5967 | let dsh_src = f.config.workspace.join("mcp-row-off-src"); |
| 5968 | copy_mcp_template_bundle(&dsh_src, &server.url(), Some(true), true); |
| 5969 | |
| 5970 | let dsh_res = f |
| 5971 | .call_admitted( |
| 5972 | &f.context, |
| 5973 | "install", |
| 5974 | json!({"target": dsh_src.to_string_lossy()}), |
| 5975 | ) |
| 5976 | .await |
| 5977 | .unwrap(); |
| 5978 | assert_eq!(dsh_res["application"], "applied", "{dsh_res}"); |
| 5979 | assert_eq!(server.hits(), 0); |
| 5980 | |
| 5981 | let toml_src = write_toml_plugin( |
| 5982 | &f.config.workspace, |
| 5983 | "mcp-toml-off-src", |
| 5984 | &format!( |
| 5985 | "schema_version = 1\n[plugin]\nname = \"toml-off\"\nversion = \"1.0.0\"\n\n[mcp_servers.off]\nurl = \"{}\"\nenabled = false\n\n[capabilities]\nnetwork_hosts = [\"127.0.0.1\"]\n", |
| 5986 | server.url() |
| 5987 | ), |
| 5988 | ); |
| 5989 | let toml_res = f |
| 5990 | .call_admitted( |
| 5991 | &f.context, |
| 5992 | "install", |
| 5993 | json!({"target": toml_src.to_string_lossy()}), |
| 5994 | ) |
| 5995 | .await |
| 5996 | .unwrap(); |
| 5997 | assert_eq!(toml_res["application"], "applied", "{toml_res}"); |
| 5998 | assert_eq!(server.hits(), 0); |
| 5999 | } |
| 6000 | |
| 6001 | #[tokio::test(flavor = "current_thread")] |
| 6002 | async fn plugins_pool_fork_leaves_session_live_connections_untouched() { |
| 6003 | let mut f = PluginsFixture::new(); |
| 6004 | f.reload_registry(); |
| 6005 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 6006 | |
| 6007 | let existing_server = McpStubServer::spawn(McpStubBehavior::Ready(vec![json!({ |
| 6008 | "name": "existing_tool", |
| 6009 | "description": "Existing tool", |
| 6010 | "inputSchema": {"type": "object"} |
| 6011 | })])) |
| 6012 | .await; |
| 6013 | let mcp_path = f._temp.path().join("global-mcp.json"); |
| 6014 | fs::write( |
| 6015 | &mcp_path, |
| 6016 | json!({ |
| 6017 | "servers": { |
| 6018 | "existing": { |
| 6019 | "url": existing_server.url(), |
| 6020 | "connect_timeout": 5 |
| 6021 | } |
| 6022 | } |
| 6023 | }) |
| 6024 | .to_string(), |
| 6025 | ) |
| 6026 | .unwrap(); |
| 6027 | let mut raw_pool = |
| 6028 | crate::mcp::McpPool::from_config_path_with_workspace(&mcp_path, &f.config.workspace) |
| 6029 | .unwrap() |
| 6030 | .with_backend(codewhale_config::McpBackend::Rust); |
| 6031 | assert!( |
| 6032 | raw_pool |
| 6033 | .get_or_connect("existing") |
| 6034 | .await |
| 6035 | .unwrap() |
| 6036 | .is_ready() |
| 6037 | ); |
| 6038 | assert_eq!(existing_server.init_hits(), 1); |
| 6039 | |
| 6040 | let pool = Arc::new(tokio::sync::Mutex::new(raw_pool)); |
| 6041 | install_gate_with_pool(&mut f, Some(Arc::clone(&pool)), |input, _| { |
| 6042 | allow_verdict(input, NestedDecision::Auto) |
| 6043 | }); |
| 6044 | |
| 6045 | let plugin_server = McpStubServer::spawn(McpStubBehavior::Ready(vec![json!({ |
| 6046 | "name": "demo_tool", |
| 6047 | "description": "Demo tool", |
| 6048 | "inputSchema": {"type": "object"} |
| 6049 | })])) |
| 6050 | .await; |
| 6051 | let src = f.config.workspace.join("mcp-fork-src"); |
| 6052 | copy_mcp_template_bundle(&src, &plugin_server.url(), Some(true), false); |
| 6053 | |
| 6054 | let res = f |
| 6055 | .call_admitted( |
| 6056 | &f.context, |
| 6057 | "install", |
| 6058 | json!({"target": src.to_string_lossy()}), |
| 6059 | ) |
| 6060 | .await |
| 6061 | .unwrap(); |
| 6062 | assert_eq!(res["application"], "applied", "{res}"); |
| 6063 | assert_eq!(plugin_server.init_hits(), 1); |
| 6064 | assert_eq!( |
| 6065 | existing_server.init_hits(), |
| 6066 | 1, |
| 6067 | "session live connection must not be re-initialized during fork connect" |
| 6068 | ); |
| 6069 | |
| 6070 | let guard_pool = pool.lock().await; |
| 6071 | let snapshot = guard_pool.manager_snapshot(&mcp_path, false, &std::collections::HashMap::new()); |
| 6072 | let existing_row = snapshot |
| 6073 | .servers |
| 6074 | .iter() |
| 6075 | .find(|row| row.name == "existing") |
| 6076 | .expect("existing session server still present"); |
| 6077 | assert!(existing_row.connected); |
| 6078 | let qualified = crate::mcp::qualified_plugin_server_name("demo-mcp", "demo"); |
| 6079 | assert!( |
| 6080 | !snapshot.servers.iter().any(|row| row.name == qualified), |
| 6081 | "forked plugin pool must not mutate session pool config" |
| 6082 | ); |
| 6083 | } |
| 6084 | |
| 6085 | #[tokio::test(flavor = "current_thread")] |
| 6086 | async fn plugins_attempt_stops_at_the_deadline_and_on_cancel() { |
| 6087 | let hang_deadline = McpStubServer::spawn(McpStubBehavior::Hang).await; |
| 6088 | let deadline_guard = |
| 6089 | super::set_mcp_connect_deadline_for_test(std::time::Duration::from_millis(250)); |
| 6090 | let mut f = PluginsFixture::new(); |
| 6091 | f.reload_registry(); |
| 6092 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 6093 | let pool = fixture_mcp_pool(&f); |
| 6094 | install_gate_with_pool(&mut f, Some(pool), |input, _| { |
| 6095 | allow_verdict(input, NestedDecision::Auto) |
| 6096 | }); |
| 6097 | |
| 6098 | let src = f.config.workspace.join("mcp-deadline-src"); |
| 6099 | copy_mcp_template_bundle(&src, &hang_deadline.url(), Some(true), false); |
| 6100 | |
| 6101 | let deadline_hit_at = Arc::new(std::sync::Mutex::new(None)); |
| 6102 | let deadline_stamp = Arc::clone(&deadline_hit_at); |
| 6103 | let deadline_hits = Arc::clone(&hang_deadline.hits); |
| 6104 | tokio::spawn(async move { |
| 6105 | while deadline_hits.load(Ordering::SeqCst) == 0 { |
| 6106 | tokio::time::sleep(std::time::Duration::from_millis(5)).await; |
| 6107 | } |
| 6108 | *deadline_stamp.lock().unwrap() = Some(std::time::Instant::now()); |
| 6109 | }); |
| 6110 | |
| 6111 | let (deadline_res, deadline_receipts) = f |
| 6112 | .call_admitted_with_receipts( |
| 6113 | &f.context, |
| 6114 | "install", |
| 6115 | json!({"target": src.to_string_lossy()}), |
| 6116 | ) |
| 6117 | .await; |
| 6118 | let deadline_res = deadline_res.unwrap(); |
| 6119 | assert_eq!(deadline_res["application"], "failed", "{deadline_res}"); |
| 6120 | assert_eq!(deadline_res["error"]["code"], "operation-error"); |
| 6121 | let deadline_diag = deadline_res["error"]["diagnostic"].as_str().unwrap_or(""); |
| 6122 | assert!( |
| 6123 | deadline_diag.contains("timed out") || deadline_diag.contains("deadline elapsed"), |
| 6124 | "call must stop at the MCP connect deadline instead of waiting 30s MCP connect timeout: {deadline_res}" |
| 6125 | ); |
| 6126 | assert!( |
| 6127 | !deadline_diag.contains("didn't start within 30s"), |
| 6128 | "{deadline_res}" |
| 6129 | ); |
| 6130 | let deadline_acts = deadline_receipts["broker_acts"]["acts"] |
| 6131 | .as_array() |
| 6132 | .expect("deadline receipts acts"); |
| 6133 | assert!( |
| 6134 | deadline_acts.iter().any(|act| { |
| 6135 | act["service"] == "plugins" |
| 6136 | && act["method"] == "mcp_connect" |
| 6137 | && act["plugin"] == "demo-mcp" |
| 6138 | && act["server"] == "demo" |
| 6139 | && act["outcome"] == "timed_out" |
| 6140 | }), |
| 6141 | "{deadline_receipts}" |
| 6142 | ); |
| 6143 | if let Some(hit_at) = stamped_instant(&deadline_hit_at).await { |
| 6144 | assert!( |
| 6145 | hit_at.elapsed() < std::time::Duration::from_secs(15), |
| 6146 | "hanging connect must stop at the 250ms deadline instead of the 30s MCP connect timeout: {:?}", |
| 6147 | hit_at.elapsed() |
| 6148 | ); |
| 6149 | } |
| 6150 | drop(deadline_guard); |
| 6151 | |
| 6152 | let hang_cancel = McpStubServer::spawn(McpStubBehavior::Hang).await; |
| 6153 | let mut f_cancel = PluginsFixture::new(); |
| 6154 | f_cancel.reload_registry(); |
| 6155 | f_cancel.posture.switch_for_tests(ApprovalMode::Bypass); |
| 6156 | let pool_cancel = fixture_mcp_pool(&f_cancel); |
| 6157 | install_gate_with_pool(&mut f_cancel, Some(pool_cancel), |input, _| { |
| 6158 | allow_verdict(input, NestedDecision::Auto) |
| 6159 | }); |
| 6160 | let cancel_src = f_cancel.config.workspace.join("mcp-cancel-src"); |
| 6161 | copy_mcp_template_bundle(&cancel_src, &hang_cancel.url(), Some(true), false); |
| 6162 | let cancel_admitted = f_cancel |
| 6163 | .admit_context( |
| 6164 | &f_cancel.context, |
| 6165 | "install", |
| 6166 | &json!({"target": cancel_src.to_string_lossy()}), |
| 6167 | decider_for_posture(&f_cancel.posture.read()), |
| 6168 | ) |
| 6169 | .await |
| 6170 | .unwrap(); |
| 6171 | let cancel_guard = f_cancel.begin(&f_cancel.creator, HostCohort::Builtin, &cancel_admitted); |
| 6172 | let cancel_ticket = plugin_ticket(&cancel_guard).unwrap(); |
| 6173 | |
| 6174 | let (cx, _violations, cancel) = HostRequestContext::for_test(101); |
| 6175 | let cancel_trigger = cancel.clone(); |
| 6176 | let cancel_at = Arc::new(std::sync::Mutex::new(None)); |
| 6177 | let cancel_stamp = Arc::clone(&cancel_at); |
| 6178 | let cancel_hits = Arc::clone(&hang_cancel.hits); |
| 6179 | tokio::spawn(async move { |
| 6180 | let wait_deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); |
| 6181 | while cancel_hits.load(Ordering::SeqCst) == 0 { |
| 6182 | assert!( |
| 6183 | std::time::Instant::now() < wait_deadline, |
| 6184 | "hanging MCP server was never contacted before cancel" |
| 6185 | ); |
| 6186 | tokio::time::sleep(std::time::Duration::from_millis(5)).await; |
| 6187 | } |
| 6188 | *cancel_stamp.lock().unwrap() = Some(std::time::Instant::now()); |
| 6189 | cancel_trigger.cancel(); |
| 6190 | }); |
| 6191 | let cancel_err = f_cancel |
| 6192 | .manager |
| 6193 | .shared |
| 6194 | .core_calls |
| 6195 | .serve_broker_in( |
| 6196 | TABLE, |
| 6197 | &f_cancel.manager.shared, |
| 6198 | HostCohort::Builtin, |
| 6199 | 7, |
| 6200 | DshBrokerParams { |
| 6201 | owner: f_cancel.creator.clone(), |
| 6202 | ticket: cancel_ticket, |
| 6203 | service: "plugins".to_string(), |
| 6204 | method: "install".to_string(), |
| 6205 | input: json!({"target": cancel_src.to_string_lossy()}), |
| 6206 | }, |
| 6207 | cx, |
| 6208 | ) |
| 6209 | .await |
| 6210 | .expect_err("cancel must end hanging MCP attempt"); |
| 6211 | assert_eq!(cancel_err.code, error_code::CANCELLED, "{cancel_err:?}"); |
| 6212 | let cancel_at = cancel_at |
| 6213 | .lock() |
| 6214 | .unwrap() |
| 6215 | .expect("cancel watcher must have fired"); |
| 6216 | assert!( |
| 6217 | cancel_at.elapsed() < std::time::Duration::from_secs(15), |
| 6218 | "cancel must end the hanging connect promptly instead of the 30s MCP connect timeout: {:?}", |
| 6219 | cancel_at.elapsed() |
| 6220 | ); |
| 6221 | |
| 6222 | #[cfg(unix)] |
| 6223 | { |
| 6224 | let mut f_stdio_cancel = PluginsFixture::new(); |
| 6225 | f_stdio_cancel.reload_registry(); |
| 6226 | f_stdio_cancel |
| 6227 | .posture |
| 6228 | .switch_for_tests(ApprovalMode::Bypass); |
| 6229 | let pool_stdio_cancel = fixture_mcp_pool(&f_stdio_cancel); |
| 6230 | install_gate_with_pool(&mut f_stdio_cancel, Some(pool_stdio_cancel), |input, _| { |
| 6231 | allow_verdict(input, NestedDecision::Auto) |
| 6232 | }); |
| 6233 | let cx_pid_file = f_stdio_cancel._temp.path().join("stdio-cx-cancel.pid"); |
| 6234 | let cx_src = write_hanging_stdio_plugin( |
| 6235 | &f_stdio_cancel.config.workspace, |
| 6236 | "stdio-cx-cancel-src", |
| 6237 | "stdio-cx-cancel", |
| 6238 | &cx_pid_file, |
| 6239 | ); |
| 6240 | let cx_admitted = f_stdio_cancel |
| 6241 | .admit_context( |
| 6242 | &f_stdio_cancel.context, |
| 6243 | "install", |
| 6244 | &json!({"target": cx_src.to_string_lossy()}), |
| 6245 | decider_for_posture(&f_stdio_cancel.posture.read()), |
| 6246 | ) |
| 6247 | .await |
| 6248 | .unwrap(); |
| 6249 | let cx_guard = |
| 6250 | f_stdio_cancel.begin(&f_stdio_cancel.creator, HostCohort::Builtin, &cx_admitted); |
| 6251 | let cx_ticket = plugin_ticket(&cx_guard).unwrap(); |
| 6252 | let (cx_stdio, _violations_stdio, cx_token) = HostRequestContext::for_test(102); |
| 6253 | let pid_watch = cx_pid_file.clone(); |
| 6254 | let token_trigger = cx_token.clone(); |
| 6255 | let cx_cancel_at = Arc::new(std::sync::Mutex::new(None)); |
| 6256 | let cx_cancel_stamp = Arc::clone(&cx_cancel_at); |
| 6257 | tokio::spawn(async move { |
| 6258 | let wait_deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); |
| 6259 | while !tokio::fs::try_exists(&pid_watch).await.unwrap_or(false) { |
| 6260 | assert!( |
| 6261 | std::time::Instant::now() < wait_deadline, |
| 6262 | "stdio child did not record PID before cancel" |
| 6263 | ); |
| 6264 | tokio::time::sleep(std::time::Duration::from_millis(5)).await; |
| 6265 | } |
| 6266 | *cx_cancel_stamp.lock().unwrap() = Some(std::time::Instant::now()); |
| 6267 | token_trigger.cancel(); |
| 6268 | }); |
| 6269 | let stdio_cx_err = f_stdio_cancel |
| 6270 | .manager |
| 6271 | .shared |
| 6272 | .core_calls |
| 6273 | .serve_broker_in( |
| 6274 | TABLE, |
| 6275 | &f_stdio_cancel.manager.shared, |
| 6276 | HostCohort::Builtin, |
| 6277 | 7, |
| 6278 | DshBrokerParams { |
| 6279 | owner: f_stdio_cancel.creator.clone(), |
| 6280 | ticket: cx_ticket, |
| 6281 | service: "plugins".to_string(), |
| 6282 | method: "install".to_string(), |
| 6283 | input: json!({"target": cx_src.to_string_lossy()}), |
| 6284 | }, |
| 6285 | cx_stdio, |
| 6286 | ) |
| 6287 | .await |
| 6288 | .expect_err("cx.cancel must end hanging stdio MCP attempt"); |
| 6289 | assert_eq!(stdio_cx_err.code, error_code::CANCELLED, "{stdio_cx_err:?}"); |
| 6290 | let cx_cancel_at = cx_cancel_at |
| 6291 | .lock() |
| 6292 | .unwrap() |
| 6293 | .expect("cx cancel watcher must have fired"); |
| 6294 | assert!( |
| 6295 | cx_cancel_at.elapsed() < std::time::Duration::from_secs(15), |
| 6296 | "stdio cx.cancel must finish promptly after the cancel instead of the 30s MCP connect timeout: {:?}", |
| 6297 | cx_cancel_at.elapsed() |
| 6298 | ); |
| 6299 | assert_pid_reaped(&cx_pid_file, "cx.cancel").await; |
| 6300 | |
| 6301 | let mut f_withdraw = PluginsFixture::new(); |
| 6302 | f_withdraw.reload_registry(); |
| 6303 | f_withdraw.posture.switch_for_tests(ApprovalMode::Bypass); |
| 6304 | let pool_withdraw = fixture_mcp_pool(&f_withdraw); |
| 6305 | install_gate_with_pool(&mut f_withdraw, Some(pool_withdraw), |input, _| { |
| 6306 | allow_verdict(input, NestedDecision::Auto) |
| 6307 | }); |
| 6308 | let withdraw_pid_file = f_withdraw._temp.path().join("stdio-withdraw.pid"); |
| 6309 | let withdraw_src = write_hanging_stdio_plugin( |
| 6310 | &f_withdraw.config.workspace, |
| 6311 | "stdio-withdraw-src", |
| 6312 | "stdio-withdraw", |
| 6313 | &withdraw_pid_file, |
| 6314 | ); |
| 6315 | let withdraw_admitted = f_withdraw |
| 6316 | .admit_context( |
| 6317 | &f_withdraw.context, |
| 6318 | "install", |
| 6319 | &json!({"target": withdraw_src.to_string_lossy()}), |
| 6320 | decider_for_posture(&f_withdraw.posture.read()), |
| 6321 | ) |
| 6322 | .await |
| 6323 | .unwrap(); |
| 6324 | let withdraw_guard = |
| 6325 | f_withdraw.begin(&f_withdraw.creator, HostCohort::Builtin, &withdraw_admitted); |
| 6326 | let withdraw_ticket = plugin_ticket(&withdraw_guard).unwrap(); |
| 6327 | let (cx_withdraw, _violations_withdraw, _token_withdraw) = |
| 6328 | HostRequestContext::for_test(103); |
| 6329 | let withdraw_pid_watch = withdraw_pid_file.clone(); |
| 6330 | let withdraw_at = Arc::new(std::sync::Mutex::new(None)); |
| 6331 | let withdraw_stamp = Arc::clone(&withdraw_at); |
| 6332 | tokio::spawn(async move { |
| 6333 | let wait_deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); |
| 6334 | while !tokio::fs::try_exists(&withdraw_pid_watch) |
| 6335 | .await |
| 6336 | .unwrap_or(false) |
| 6337 | { |
| 6338 | assert!( |
| 6339 | std::time::Instant::now() < wait_deadline, |
| 6340 | "stdio child did not record PID before withdraw" |
| 6341 | ); |
| 6342 | tokio::time::sleep(std::time::Duration::from_millis(5)).await; |
| 6343 | } |
| 6344 | *withdraw_stamp.lock().unwrap() = Some(std::time::Instant::now()); |
| 6345 | drop(withdraw_guard); |
| 6346 | }); |
| 6347 | let withdraw_err = f_withdraw |
| 6348 | .manager |
| 6349 | .shared |
| 6350 | .core_calls |
| 6351 | .serve_broker_in( |
| 6352 | TABLE, |
| 6353 | &f_withdraw.manager.shared, |
| 6354 | HostCohort::Builtin, |
| 6355 | 7, |
| 6356 | DshBrokerParams { |
| 6357 | owner: f_withdraw.creator.clone(), |
| 6358 | ticket: withdraw_ticket, |
| 6359 | service: "plugins".to_string(), |
| 6360 | method: "install".to_string(), |
| 6361 | input: json!({"target": withdraw_src.to_string_lossy()}), |
| 6362 | }, |
| 6363 | cx_withdraw, |
| 6364 | ) |
| 6365 | .await |
| 6366 | .expect_err("withdraw cancel must end hanging stdio MCP attempt"); |
| 6367 | assert_eq!(withdraw_err.code, error_code::CANCELLED, "{withdraw_err:?}"); |
| 6368 | assert!( |
| 6369 | withdraw_err.message.contains("invocation ended"), |
| 6370 | "{withdraw_err:?}" |
| 6371 | ); |
| 6372 | let withdraw_at = withdraw_at |
| 6373 | .lock() |
| 6374 | .unwrap() |
| 6375 | .expect("withdraw watcher must have fired"); |
| 6376 | assert!( |
| 6377 | withdraw_at.elapsed() < std::time::Duration::from_secs(15), |
| 6378 | "stdio withdraw must finish promptly after the withdraw instead of the 30s MCP connect timeout: {:?}", |
| 6379 | withdraw_at.elapsed() |
| 6380 | ); |
| 6381 | assert_pid_reaped(&withdraw_pid_file, "withdraw").await; |
| 6382 | } |
| 6383 | } |
| 6384 | |
| 6385 | #[tokio::test(flavor = "current_thread")] |
| 6386 | async fn plugins_required_connector_blocked_by_network_policy_fails_without_card() { |
| 6387 | use codewhale_net::network_policy::{Decision, NetworkPolicy, NetworkPolicyDecider}; |
| 6388 | |
| 6389 | for policy in [ |
| 6390 | NetworkPolicy { |
| 6391 | default: Decision::Deny.into(), |
| 6392 | ..NetworkPolicy::default() |
| 6393 | }, |
| 6394 | NetworkPolicy::default(), |
| 6395 | ] { |
| 6396 | let mut f = PluginsFixture::new(); |
| 6397 | f.reload_registry(); |
| 6398 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 6399 | let mcp_path = f._temp.path().join("global-mcp.json"); |
| 6400 | fs::write(&mcp_path, "{}").unwrap(); |
| 6401 | let pool = |
| 6402 | crate::mcp::McpPool::from_config_path_with_workspace(&mcp_path, &f.config.workspace) |
| 6403 | .unwrap() |
| 6404 | .with_backend(codewhale_config::McpBackend::Rust) |
| 6405 | .with_network_policy(NetworkPolicyDecider::new(policy, None)); |
| 6406 | let gate_calls = install_gate_with_pool( |
| 6407 | &mut f, |
| 6408 | Some(Arc::new(tokio::sync::Mutex::new(pool))), |
| 6409 | |input, _| allow_verdict(input, NestedDecision::Approved), |
| 6410 | ); |
| 6411 | |
| 6412 | let server = McpStubServer::spawn(McpStubBehavior::Fail500).await; |
| 6413 | let src = f.config.workspace.join("mcp-policy-src"); |
| 6414 | copy_mcp_template_bundle(&src, &server.url(), Some(true), false); |
| 6415 | |
| 6416 | let res = f |
| 6417 | .call_admitted( |
| 6418 | &f.context, |
| 6419 | "install", |
| 6420 | json!({"target": src.to_string_lossy()}), |
| 6421 | ) |
| 6422 | .await |
| 6423 | .unwrap(); |
| 6424 | assert_eq!(res["application"], "failed", "{res}"); |
| 6425 | assert_eq!(res["stage"], "enable"); |
| 6426 | assert_eq!(res["changed"], true); |
| 6427 | assert_eq!(res["enabled"], true); |
| 6428 | assert_eq!(res["error"]["code"], "operation-error"); |
| 6429 | let diag = res["error"]["diagnostic"].as_str().unwrap(); |
| 6430 | assert!(diag.contains("127.0.0.1"), "{res}"); |
| 6431 | assert_eq!(server.hits(), 0, "blocked host must never dial or retry"); |
| 6432 | let calls = gate_calls.lock().unwrap(); |
| 6433 | assert!( |
| 6434 | calls.is_empty(), |
| 6435 | "MCP network policy failure must not ask a nested approval card: {calls:?}" |
| 6436 | ); |
| 6437 | } |
| 6438 | } |
| 6439 | |
| 6440 | #[tokio::test(flavor = "current_thread")] |
| 6441 | async fn plugins_multiple_required_connectors_bounded_together_and_report_all_failures() { |
| 6442 | let mut f = PluginsFixture::new(); |
| 6443 | f.reload_registry(); |
| 6444 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 6445 | let pool = fixture_mcp_pool(&f); |
| 6446 | install_gate_with_pool(&mut f, Some(pool), |input, _| { |
| 6447 | allow_verdict(input, NestedDecision::Auto) |
| 6448 | }); |
| 6449 | |
| 6450 | let fail_server = McpStubServer::spawn(McpStubBehavior::Fail500).await; |
| 6451 | let dead_url = dead_loopback_url(); |
| 6452 | let multi_fail_src = write_toml_plugin( |
| 6453 | &f.config.workspace, |
| 6454 | "multi-fail-src", |
| 6455 | &format!( |
| 6456 | "schema_version = 1\n[plugin]\nname = \"multi-fail\"\nversion = \"1.0.0\"\n\n[mcp_servers.alpha]\nurl = \"{dead_url}\"\nrequired = true\n\n[mcp_servers.beta]\nurl = \"{}\"\nrequired = true\n\n[capabilities]\nnetwork_hosts = [\"127.0.0.1\"]\n", |
| 6457 | fail_server.url() |
| 6458 | ), |
| 6459 | ); |
| 6460 | |
| 6461 | let res = f |
| 6462 | .call_admitted( |
| 6463 | &f.context, |
| 6464 | "install", |
| 6465 | json!({"target": multi_fail_src.to_string_lossy()}), |
| 6466 | ) |
| 6467 | .await |
| 6468 | .unwrap(); |
| 6469 | assert_eq!(res["application"], "failed", "{res}"); |
| 6470 | assert_eq!(res["error"]["code"], "operation-error"); |
| 6471 | let diag = res["error"]["diagnostic"].as_str().unwrap(); |
| 6472 | assert!(diag.contains("alpha"), "{diag}"); |
| 6473 | assert!(diag.contains("beta"), "{diag}"); |
| 6474 | assert_eq!(fail_server.post_hits(), 1); |
| 6475 | |
| 6476 | let hang_a = McpStubServer::spawn(McpStubBehavior::Hang).await; |
| 6477 | let hang_b = McpStubServer::spawn(McpStubBehavior::Hang).await; |
| 6478 | let _deadline = super::set_mcp_connect_deadline_for_test(std::time::Duration::from_millis(250)); |
| 6479 | let mut f_bound = PluginsFixture::new(); |
| 6480 | f_bound.reload_registry(); |
| 6481 | f_bound.posture.switch_for_tests(ApprovalMode::Bypass); |
| 6482 | let pool_bound = fixture_mcp_pool(&f_bound); |
| 6483 | install_gate_with_pool(&mut f_bound, Some(pool_bound), |input, _| { |
| 6484 | allow_verdict(input, NestedDecision::Auto) |
| 6485 | }); |
| 6486 | let multi_hang_src = write_toml_plugin( |
| 6487 | &f_bound.config.workspace, |
| 6488 | "multi-hang-src", |
| 6489 | &format!( |
| 6490 | "schema_version = 1\n[plugin]\nname = \"multi-hang\"\nversion = \"1.0.0\"\n\n[mcp_servers.alpha]\nurl = \"{}\"\nrequired = true\n\n[mcp_servers.beta]\nurl = \"{}\"\nrequired = true\n\n[capabilities]\nnetwork_hosts = [\"127.0.0.1\"]\n", |
| 6491 | hang_a.url(), |
| 6492 | hang_b.url() |
| 6493 | ), |
| 6494 | ); |
| 6495 | let bound_hit_at = Arc::new(std::sync::Mutex::new(None)); |
| 6496 | let bound_stamp = Arc::clone(&bound_hit_at); |
| 6497 | let bound_hits_a = Arc::clone(&hang_a.hits); |
| 6498 | let bound_hits_b = Arc::clone(&hang_b.hits); |
| 6499 | tokio::spawn(async move { |
| 6500 | while bound_hits_a.load(Ordering::SeqCst) == 0 && bound_hits_b.load(Ordering::SeqCst) == 0 { |
| 6501 | tokio::time::sleep(std::time::Duration::from_millis(5)).await; |
| 6502 | } |
| 6503 | *bound_stamp.lock().unwrap() = Some(std::time::Instant::now()); |
| 6504 | }); |
| 6505 | let res_bound = f_bound |
| 6506 | .call_admitted( |
| 6507 | &f_bound.context, |
| 6508 | "install", |
| 6509 | json!({"target": multi_hang_src.to_string_lossy()}), |
| 6510 | ) |
| 6511 | .await |
| 6512 | .unwrap(); |
| 6513 | if let Some(hit_at) = stamped_instant(&bound_hit_at).await { |
| 6514 | assert!( |
| 6515 | hit_at.elapsed() < std::time::Duration::from_secs(15), |
| 6516 | "multiple required connectors must share one call deadline instead of one 30s MCP connect timeout each: {:?}", |
| 6517 | hit_at.elapsed() |
| 6518 | ); |
| 6519 | } |
| 6520 | assert_eq!(res_bound["application"], "failed", "{res_bound}"); |
| 6521 | let diag_bound = res_bound["error"]["diagnostic"].as_str().unwrap(); |
| 6522 | assert!(diag_bound.contains("alpha"), "{diag_bound}"); |
| 6523 | assert!(diag_bound.contains("beta"), "{diag_bound}"); |
| 6524 | } |
| 6525 | |
| 6526 | #[tokio::test(flavor = "current_thread")] |
| 6527 | async fn plugins_live_turn_network_policy_overrides_pool_and_ignores_dynamic_servers() { |
| 6528 | use codewhale_net::network_policy::{Decision, NetworkPolicy, NetworkPolicyDecider}; |
| 6529 | |
| 6530 | let dyn_off_server = McpStubServer::spawn(McpStubBehavior::Fail500).await; |
| 6531 | let req_ok_server = McpStubServer::spawn(McpStubBehavior::Ready(vec![json!({ |
| 6532 | "name": "ping", |
| 6533 | "description": "Ping tool", |
| 6534 | "inputSchema": {"type": "object"} |
| 6535 | })])) |
| 6536 | .await; |
| 6537 | let allow_policy = NetworkPolicy { |
| 6538 | default: Decision::Allow.into(), |
| 6539 | allow: vec!["127.0.0.1".to_string()], |
| 6540 | ..NetworkPolicy::default() |
| 6541 | }; |
| 6542 | let deny_policy = NetworkPolicy { |
| 6543 | default: Decision::Deny.into(), |
| 6544 | ..NetworkPolicy::default() |
| 6545 | }; |
| 6546 | |
| 6547 | let mut f_deny = PluginsFixture::new(); |
| 6548 | f_deny.reload_registry(); |
| 6549 | f_deny.posture.switch_for_tests(ApprovalMode::Bypass); |
| 6550 | let mcp_path_deny = f_deny._temp.path().join("global-mcp-deny.json"); |
| 6551 | fs::write(&mcp_path_deny, "{}").unwrap(); |
| 6552 | let pool_deny = crate::mcp::McpPool::from_config_path_with_workspace( |
| 6553 | &mcp_path_deny, |
| 6554 | &f_deny.config.workspace, |
| 6555 | ) |
| 6556 | .unwrap() |
| 6557 | .with_backend(codewhale_config::McpBackend::Rust) |
| 6558 | .with_network_policy(NetworkPolicyDecider::new(allow_policy.clone(), None)); |
| 6559 | let spoof_cfg: codewhale_mcp::config::McpServerConfig = |
| 6560 | serde_json::from_value(json!({ "url": dyn_off_server.url() })).unwrap(); |
| 6561 | pool_deny.dynamic_servers.write().insert( |
| 6562 | crate::mcp::qualified_plugin_server_name("mixed-dyn", "dyn-off"), |
| 6563 | spoof_cfg.clone(), |
| 6564 | ); |
| 6565 | install_gate_with_pool( |
| 6566 | &mut f_deny, |
| 6567 | Some(Arc::new(tokio::sync::Mutex::new(pool_deny))), |
| 6568 | |input, _| allow_verdict(input, NestedDecision::Auto), |
| 6569 | ); |
| 6570 | let src_deny = write_toml_plugin( |
| 6571 | &f_deny.config.workspace, |
| 6572 | "mixed-dyn-deny-src", |
| 6573 | &format!( |
| 6574 | "schema_version = 1\n[plugin]\nname = \"mixed-dyn\"\nversion = \"1.0.0\"\n\n[mcp_servers.dyn-off]\nurl = \"{}\"\nenabled = false\n\n[mcp_servers.req-ok]\nurl = \"{}\"\nrequired = true\n\n[capabilities]\nnetwork_hosts = [\"127.0.0.1\"]\n", |
| 6575 | dyn_off_server.url(), |
| 6576 | req_ok_server.url(), |
| 6577 | ), |
| 6578 | ); |
| 6579 | let deny_ctx = f_deny |
| 6580 | .context |
| 6581 | .clone() |
| 6582 | .with_network_policy(NetworkPolicyDecider::new(deny_policy.clone(), None)); |
| 6583 | let deny_res = f_deny |
| 6584 | .call_admitted( |
| 6585 | &deny_ctx, |
| 6586 | "install", |
| 6587 | json!({"target": src_deny.to_string_lossy()}), |
| 6588 | ) |
| 6589 | .await |
| 6590 | .unwrap(); |
| 6591 | assert_eq!(deny_res["application"], "failed", "{deny_res}"); |
| 6592 | assert_eq!(deny_res["error"]["code"], "operation-error"); |
| 6593 | assert!( |
| 6594 | deny_res["error"]["diagnostic"] |
| 6595 | .as_str() |
| 6596 | .unwrap() |
| 6597 | .contains("127.0.0.1"), |
| 6598 | "{deny_res}" |
| 6599 | ); |
| 6600 | assert_eq!( |
| 6601 | req_ok_server.hits(), |
| 6602 | 0, |
| 6603 | "live turn Deny policy must override stale pool Allow policy" |
| 6604 | ); |
| 6605 | assert_eq!(dyn_off_server.hits(), 0); |
| 6606 | |
| 6607 | let mut f_allow = PluginsFixture::new(); |
| 6608 | f_allow.reload_registry(); |
| 6609 | f_allow.posture.switch_for_tests(ApprovalMode::Bypass); |
| 6610 | let mcp_path_allow = f_allow._temp.path().join("global-mcp-allow.json"); |
| 6611 | fs::write(&mcp_path_allow, "{}").unwrap(); |
| 6612 | let pool_allow = crate::mcp::McpPool::from_config_path_with_workspace( |
| 6613 | &mcp_path_allow, |
| 6614 | &f_allow.config.workspace, |
| 6615 | ) |
| 6616 | .unwrap() |
| 6617 | .with_backend(codewhale_config::McpBackend::Rust) |
| 6618 | .with_network_policy(NetworkPolicyDecider::new(deny_policy, None)); |
| 6619 | pool_allow.dynamic_servers.write().insert( |
| 6620 | crate::mcp::qualified_plugin_server_name("mixed-dyn", "dyn-off"), |
| 6621 | spoof_cfg.clone(), |
| 6622 | ); |
| 6623 | pool_allow.dynamic_servers.write().insert( |
| 6624 | crate::mcp::qualified_plugin_server_name("mixed-dyn", "req-ok"), |
| 6625 | spoof_cfg, |
| 6626 | ); |
| 6627 | install_gate_with_pool( |
| 6628 | &mut f_allow, |
| 6629 | Some(Arc::new(tokio::sync::Mutex::new(pool_allow))), |
| 6630 | |input, _| allow_verdict(input, NestedDecision::Auto), |
| 6631 | ); |
| 6632 | let src_allow = write_toml_plugin( |
| 6633 | &f_allow.config.workspace, |
| 6634 | "mixed-dyn-allow-src", |
| 6635 | &format!( |
| 6636 | "schema_version = 1\n[plugin]\nname = \"mixed-dyn\"\nversion = \"1.0.0\"\n\n[mcp_servers.dyn-off]\nurl = \"{}\"\nenabled = false\n\n[mcp_servers.req-ok]\nurl = \"{}\"\nrequired = true\n\n[capabilities]\nnetwork_hosts = [\"127.0.0.1\"]\n", |
| 6637 | dyn_off_server.url(), |
| 6638 | req_ok_server.url(), |
| 6639 | ), |
| 6640 | ); |
| 6641 | let allow_ctx = f_allow |
| 6642 | .context |
| 6643 | .clone() |
| 6644 | .with_network_policy(NetworkPolicyDecider::new(allow_policy, None)); |
| 6645 | let allow_res = f_allow |
| 6646 | .call_admitted( |
| 6647 | &allow_ctx, |
| 6648 | "install", |
| 6649 | json!({"target": src_allow.to_string_lossy()}), |
| 6650 | ) |
| 6651 | .await |
| 6652 | .unwrap(); |
| 6653 | assert_eq!(allow_res["application"], "applied", "{allow_res}"); |
| 6654 | assert_eq!(allow_res["enabled"], true); |
| 6655 | assert_eq!(req_ok_server.init_hits(), 1); |
| 6656 | assert_eq!( |
| 6657 | dyn_off_server.hits(), |
| 6658 | 0, |
| 6659 | "isolated plugin fork must ignore pre-populated dynamic_servers entries" |
| 6660 | ); |
| 6661 | } |
| 6662 | |
| 6663 | #[cfg(unix)] |
| 6664 | fn write_stdio_script_plugin( |
| 6665 | root: &Path, |
| 6666 | dir_name: &str, |
| 6667 | plugin_name: &str, |
| 6668 | script_name: &str, |
| 6669 | pid_file: &Path, |
| 6670 | script_template: &str, |
| 6671 | ) -> PathBuf { |
| 6672 | use std::os::unix::fs::PermissionsExt; |
| 6673 | |
| 6674 | let src = write_toml_plugin( |
| 6675 | root, |
| 6676 | dir_name, |
| 6677 | &format!( |
| 6678 | "schema_version = 1\n[plugin]\nname = \"{plugin_name}\"\nversion = \"1.0.0\"\n\n[mcp_servers.stdio]\ncommand = \"sh\"\nargs = [\"{script_name}\"]\nrequired = true\n" |
| 6679 | ), |
| 6680 | ); |
| 6681 | let pid_escaped = pid_file.display().to_string().replace('\'', "'\\''"); |
| 6682 | let script_path = src.join(script_name); |
| 6683 | fs::write( |
| 6684 | &script_path, |
| 6685 | script_template.replace("__PID_FILE__", &pid_escaped), |
| 6686 | ) |
| 6687 | .unwrap(); |
| 6688 | fs::set_permissions(&script_path, fs::Permissions::from_mode(0o755)).unwrap(); |
| 6689 | src |
| 6690 | } |
| 6691 | |
| 6692 | #[cfg(unix)] |
| 6693 | fn write_hanging_stdio_plugin( |
| 6694 | root: &Path, |
| 6695 | dir_name: &str, |
| 6696 | plugin_name: &str, |
| 6697 | pid_file: &Path, |
| 6698 | ) -> PathBuf { |
| 6699 | write_stdio_script_plugin( |
| 6700 | root, |
| 6701 | dir_name, |
| 6702 | plugin_name, |
| 6703 | "hang.sh", |
| 6704 | pid_file, |
| 6705 | r##"#!/bin/sh |
| 6706 | pid_file='__PID_FILE__' |
| 6707 | tmp_file="${pid_file}.tmp" |
| 6708 | printf '%s\n' "$$" > "$tmp_file" |
| 6709 | mv "$tmp_file" "$pid_file" |
| 6710 | while IFS= read -r _line; do |
| 6711 | : |
| 6712 | done |
| 6713 | "##, |
| 6714 | ) |
| 6715 | } |
| 6716 | |
| 6717 | async fn stamped_instant( |
| 6718 | stamp: &Arc<std::sync::Mutex<Option<std::time::Instant>>>, |
| 6719 | ) -> Option<std::time::Instant> { |
| 6720 | for _ in 0..200 { |
| 6721 | if let Some(at) = *stamp.lock().unwrap() { |
| 6722 | return Some(at); |
| 6723 | } |
| 6724 | tokio::time::sleep(std::time::Duration::from_millis(5)).await; |
| 6725 | } |
| 6726 | *stamp.lock().unwrap() |
| 6727 | } |
| 6728 | |
| 6729 | fn assert_connector_reverified( |
| 6730 | server: &McpStubServer, |
| 6731 | inits_before: usize, |
| 6732 | receipts: &Value, |
| 6733 | plugin: &str, |
| 6734 | server_name: &str, |
| 6735 | ) { |
| 6736 | let acts = receipts["broker_acts"]["acts"].as_array().unwrap(); |
| 6737 | let mut connected = 0usize; |
| 6738 | let mut failed = 0usize; |
| 6739 | for act in acts { |
| 6740 | if act["method"] == "mcp_connect" && act["plugin"] == plugin && act["server"] == server_name |
| 6741 | { |
| 6742 | match act["outcome"].as_str() { |
| 6743 | Some("connected") => connected += 1, |
| 6744 | Some("failed") => failed += 1, |
| 6745 | _ => {} |
| 6746 | } |
| 6747 | } |
| 6748 | } |
| 6749 | let inits = server.init_hits().saturating_sub(inits_before); |
| 6750 | assert_eq!( |
| 6751 | connected, 1, |
| 6752 | "exactly one successful verification connect for `{server_name}`: {receipts}" |
| 6753 | ); |
| 6754 | assert!( |
| 6755 | (1..=1 + failed).contains(&inits), |
| 6756 | "initialize count {inits} for `{server_name}` must be the successful connect plus at most one per failed attempt ({failed}): {receipts}" |
| 6757 | ); |
| 6758 | } |
| 6759 | |
| 6760 | #[cfg(unix)] |
| 6761 | async fn assert_pid_reaped(pid_file: &Path, context: &str) { |
| 6762 | let pid: u32 = fs::read_to_string(pid_file) |
| 6763 | .unwrap_or_else(|err| panic!("{context}: missing stdio PID file: {err}")) |
| 6764 | .trim() |
| 6765 | .parse() |
| 6766 | .unwrap(); |
| 6767 | let alive = tokio::process::Command::new("kill") |
| 6768 | .args(["-0", &pid.to_string()]) |
| 6769 | .status() |
| 6770 | .await |
| 6771 | .unwrap(); |
| 6772 | assert!( |
| 6773 | !alive.success(), |
| 6774 | "{context}: stdio child {pid} must already be reaped before call returns" |
| 6775 | ); |
| 6776 | } |
| 6777 | |
| 6778 | #[cfg(unix)] |
| 6779 | #[tokio::test(flavor = "current_thread")] |
| 6780 | async fn plugins_required_stdio_connector_reaps_child_before_returning_on_ready_and_timeout() { |
| 6781 | let mut f = PluginsFixture::new(); |
| 6782 | f.reload_registry(); |
| 6783 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 6784 | let pool = fixture_mcp_pool(&f); |
| 6785 | install_gate_with_pool(&mut f, Some(pool), |input, _| { |
| 6786 | allow_verdict(input, NestedDecision::Auto) |
| 6787 | }); |
| 6788 | |
| 6789 | let ready_pid_file = f._temp.path().join("stdio-ready.pid"); |
| 6790 | let ready_src = write_stdio_script_plugin( |
| 6791 | &f.config.workspace, |
| 6792 | "stdio-ready-src", |
| 6793 | "stdio-ready", |
| 6794 | "server.sh", |
| 6795 | &ready_pid_file, |
| 6796 | r##"#!/bin/sh |
| 6797 | pid_file='__PID_FILE__' |
| 6798 | tmp_file="${pid_file}.tmp" |
| 6799 | printf '%s\n' "$$" > "$tmp_file" |
| 6800 | mv "$tmp_file" "$pid_file" |
| 6801 | while IFS= read -r line; do |
| 6802 | id=$(printf '%s\n' "$line" | sed -n 's/.*"id":[[:space:]]*\([^,}]*\).*/\1/p') |
| 6803 | case "$line" in |
| 6804 | *'"method":"initialize"'*) |
| 6805 | printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":"2024-11-05","capabilities":{"tools":{}},"serverInfo":{"name":"stdio-ready","version":"1.0.0"}}}\n' "$id" |
| 6806 | ;; |
| 6807 | *'"method":"notifications/'*) |
| 6808 | ;; |
| 6809 | *'"method":"tools/list"'*) |
| 6810 | printf '{"jsonrpc":"2.0","id":%s,"result":{"tools":[{"name":"ping","description":"Ping tool","inputSchema":{"type":"object"}}]}}\n' "$id" |
| 6811 | ;; |
| 6812 | *'"method":"resources/templates/list"'*) |
| 6813 | printf '{"jsonrpc":"2.0","id":%s,"result":{"resourceTemplates":[]}}\n' "$id" |
| 6814 | ;; |
| 6815 | *'"method":"resources/list"'*) |
| 6816 | printf '{"jsonrpc":"2.0","id":%s,"result":{"resources":[]}}\n' "$id" |
| 6817 | ;; |
| 6818 | *'"method":"prompts/list"'*) |
| 6819 | printf '{"jsonrpc":"2.0","id":%s,"result":{"prompts":[]}}\n' "$id" |
| 6820 | ;; |
| 6821 | esac |
| 6822 | done |
| 6823 | "##, |
| 6824 | ); |
| 6825 | |
| 6826 | let ready_res = f |
| 6827 | .call_admitted( |
| 6828 | &f.context, |
| 6829 | "install", |
| 6830 | json!({"target": ready_src.to_string_lossy()}), |
| 6831 | ) |
| 6832 | .await |
| 6833 | .unwrap(); |
| 6834 | assert_eq!(ready_res["application"], "applied", "{ready_res}"); |
| 6835 | assert_eq!(ready_res["enabled"], true); |
| 6836 | assert_pid_reaped(&ready_pid_file, "ready").await; |
| 6837 | |
| 6838 | let _deadline = super::set_mcp_connect_deadline_for_test(std::time::Duration::from_millis(800)); |
| 6839 | let mut f_hang = PluginsFixture::new(); |
| 6840 | f_hang.reload_registry(); |
| 6841 | f_hang.posture.switch_for_tests(ApprovalMode::Bypass); |
| 6842 | let pool_hang = fixture_mcp_pool(&f_hang); |
| 6843 | install_gate_with_pool(&mut f_hang, Some(pool_hang), |input, _| { |
| 6844 | allow_verdict(input, NestedDecision::Auto) |
| 6845 | }); |
| 6846 | let hang_pid_file = f_hang._temp.path().join("stdio-hang.pid"); |
| 6847 | let hang_src = write_hanging_stdio_plugin( |
| 6848 | &f_hang.config.workspace, |
| 6849 | "stdio-hang-src", |
| 6850 | "stdio-hang", |
| 6851 | &hang_pid_file, |
| 6852 | ); |
| 6853 | |
| 6854 | let hang_pid_at = Arc::new(std::sync::Mutex::new(None)); |
| 6855 | let hang_pid_stamp = Arc::clone(&hang_pid_at); |
| 6856 | let hang_pid_watch = hang_pid_file.clone(); |
| 6857 | tokio::spawn(async move { |
| 6858 | while !tokio::fs::try_exists(&hang_pid_watch) |
| 6859 | .await |
| 6860 | .unwrap_or(false) |
| 6861 | { |
| 6862 | tokio::time::sleep(std::time::Duration::from_millis(5)).await; |
| 6863 | } |
| 6864 | *hang_pid_stamp.lock().unwrap() = Some(std::time::Instant::now()); |
| 6865 | }); |
| 6866 | let hang_res = f_hang |
| 6867 | .call_admitted( |
| 6868 | &f_hang.context, |
| 6869 | "install", |
| 6870 | json!({"target": hang_src.to_string_lossy()}), |
| 6871 | ) |
| 6872 | .await |
| 6873 | .unwrap(); |
| 6874 | assert_eq!(hang_res["application"], "failed", "{hang_res}"); |
| 6875 | assert_eq!(hang_res["error"]["code"], "operation-error"); |
| 6876 | assert_pid_reaped(&hang_pid_file, "timeout").await; |
| 6877 | if let Some(pid_at) = stamped_instant(&hang_pid_at).await { |
| 6878 | assert!( |
| 6879 | pid_at.elapsed() < std::time::Duration::from_secs(15), |
| 6880 | "hanging stdio connect must stop near the deadline instead of the 30s MCP connect timeout: {:?}", |
| 6881 | pid_at.elapsed() |
| 6882 | ); |
| 6883 | } |
| 6884 | } |
| 6885 | |
| 6886 | #[tokio::test(flavor = "current_thread")] |
| 6887 | async fn plugins_mixed_dsh_bundle_qualifies_required_native_mcp_connector() { |
| 6888 | let Some(node) = super::super::test_support::node_for_tests( |
| 6889 | "plugins_mixed_dsh_bundle_qualifies_required_native_mcp_connector", |
| 6890 | ) else { |
| 6891 | return; |
| 6892 | }; |
| 6893 | let _policy = TestPolicyGuard::extension_host(true); |
| 6894 | let mut f = PluginsFixture::new(); |
| 6895 | f.manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions { |
| 6896 | runtime: codewhale_config::extension_host::ExtensionHostRuntime::Node, |
| 6897 | node_override: Some(node), |
| 6898 | root: Some(f._temp.path().join("host-root")), |
| 6899 | ..Default::default() |
| 6900 | })); |
| 6901 | { |
| 6902 | let mut reg = f.manager.shared.registry.lock().unwrap(); |
| 6903 | f.creator = reg |
| 6904 | .begin_owner( |
| 6905 | HostCohort::Builtin, |
| 6906 | "host:creator", |
| 6907 | "creator", |
| 6908 | None, |
| 6909 | "digest", |
| 6910 | ) |
| 6911 | .unwrap(); |
| 6912 | reg.mark_active(&f.creator); |
| 6913 | } |
| 6914 | let _manager = TestManagerGuard::install(Arc::clone(&f.manager)); |
| 6915 | let initial_reg = f.reload_registry(); |
| 6916 | let _engine = f.manager.attach(initial_reg); |
| 6917 | let _ = _engine.set_creator_demand(true); |
| 6918 | |
| 6919 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 6920 | let pool = fixture_mcp_pool(&f); |
| 6921 | install_gate_with_pool(&mut f, Some(pool), |input, _| { |
| 6922 | allow_verdict(input, NestedDecision::Auto) |
| 6923 | }); |
| 6924 | |
| 6925 | let server = McpStubServer::spawn(McpStubBehavior::Ready(vec![json!({ |
| 6926 | "name": "read_mixed", |
| 6927 | "description": "Mixed native/DSH connector tool", |
| 6928 | "inputSchema": {"type": "object"} |
| 6929 | })])) |
| 6930 | .await; |
| 6931 | |
| 6932 | let src = f.config.workspace.join("mixed-ok-src"); |
| 6933 | copy_dir_tree(&dsh_template_dir("decoration"), &src); |
| 6934 | let patch = format!( |
| 6935 | "- insert:\n - id: my-decoration\n name: '@local/my-decoration'\n - id: demo-mcp\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n serverName: demo\n transport: streamable-http\n url: {}\n failOnStartupError: true\n", |
| 6936 | server.url() |
| 6937 | ); |
| 6938 | fs::write(src.join("cordis.patch.yml"), patch).unwrap(); |
| 6939 | |
| 6940 | let inits_before_install = server.init_hits(); |
| 6941 | let (res, receipts_ok) = f |
| 6942 | .call_admitted_with_receipts( |
| 6943 | &f.context, |
| 6944 | "install", |
| 6945 | json!({"target": src.to_string_lossy()}), |
| 6946 | ) |
| 6947 | .await; |
| 6948 | let res = res.unwrap(); |
| 6949 | assert_eq!(res["application"], "applied", "{res}"); |
| 6950 | assert_eq!(res["stage"], "enable"); |
| 6951 | assert_eq!(res["changed"], true); |
| 6952 | assert_eq!(res["enabled"], true); |
| 6953 | assert_eq!(res["bundle"], "my-decoration"); |
| 6954 | assert_connector_reverified( |
| 6955 | &server, |
| 6956 | inits_before_install, |
| 6957 | &receipts_ok, |
| 6958 | "my-decoration", |
| 6959 | "demo", |
| 6960 | ); |
| 6961 | |
| 6962 | let qualified = crate::mcp::qualified_plugin_server_name("my-decoration", "demo"); |
| 6963 | let expected_tool = crate::mcp::McpPool::mcp_model_tool_name(&qualified, "read_mixed"); |
| 6964 | let warnings: Vec<&str> = res["warnings"] |
| 6965 | .as_array() |
| 6966 | .unwrap() |
| 6967 | .iter() |
| 6968 | .filter_map(Value::as_str) |
| 6969 | .collect(); |
| 6970 | assert!( |
| 6971 | warnings.iter().any(|w| w.contains(&expected_tool)), |
| 6972 | "expected {expected_tool} in warnings: {warnings:?}" |
| 6973 | ); |
| 6974 | assert!( |
| 6975 | warnings.iter().any(|w| w.contains("next message on")), |
| 6976 | "expected next-message guidance in warnings: {warnings:?}" |
| 6977 | ); |
| 6978 | |
| 6979 | let inits_before_enable = server.init_hits(); |
| 6980 | let (idempotent, enable_receipts) = f |
| 6981 | .call_admitted_with_receipts(&f.context, "enable", json!({"target": "my-decoration"})) |
| 6982 | .await; |
| 6983 | let idempotent = idempotent.unwrap(); |
| 6984 | assert_eq!(idempotent["application"], "applied", "{idempotent}"); |
| 6985 | assert_eq!(idempotent["stage"], "enable"); |
| 6986 | assert_eq!(idempotent["enabled"], true); |
| 6987 | assert_connector_reverified( |
| 6988 | &server, |
| 6989 | inits_before_enable, |
| 6990 | &enable_receipts, |
| 6991 | "my-decoration", |
| 6992 | "demo", |
| 6993 | ); |
| 6994 | |
| 6995 | let dead_src = f.config.workspace.join("mixed-dead-src"); |
| 6996 | copy_dir_tree(&dsh_template_dir("decoration"), &dead_src); |
| 6997 | let dead_pkg = json!({ |
| 6998 | "name": "@local/my-decoration-dead", |
| 6999 | "version": "1.0.0", |
| 7000 | "private": true, |
| 7001 | "type": "module", |
| 7002 | "exports": { |
| 7003 | ".": "./index.js", |
| 7004 | "./client": "./client.js", |
| 7005 | "./locale/*.json": "./locale/*.json", |
| 7006 | "./icon": "./icon.svg" |
| 7007 | }, |
| 7008 | "files": ["index.js", "client.js", "cordis.patch.yml", "locale/*.json", "icon.svg"], |
| 7009 | "dsh": { |
| 7010 | "bundle": { "patch": "./cordis.patch.yml" }, |
| 7011 | "client": { |
| 7012 | "platform": "web", |
| 7013 | "immediately": true, |
| 7014 | "inject": ["@deepseek-ai/dsh-client-ui-conversation"] |
| 7015 | } |
| 7016 | } |
| 7017 | }); |
| 7018 | fs::write( |
| 7019 | dead_src.join("package.json"), |
| 7020 | serde_json::to_string_pretty(&dead_pkg).unwrap(), |
| 7021 | ) |
| 7022 | .unwrap(); |
| 7023 | let dead_patch = format!( |
| 7024 | "- insert:\n - id: my-decoration-dead\n name: '@local/my-decoration-dead'\n - id: demo-mcp\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n serverName: demo\n transport: streamable-http\n url: {}\n failOnStartupError: true\n", |
| 7025 | dead_loopback_url() |
| 7026 | ); |
| 7027 | fs::write(dead_src.join("cordis.patch.yml"), dead_patch).unwrap(); |
| 7028 | |
| 7029 | let (dead_res, receipts_dead) = f |
| 7030 | .call_admitted_with_receipts( |
| 7031 | &f.context, |
| 7032 | "install", |
| 7033 | json!({"target": dead_src.to_string_lossy()}), |
| 7034 | ) |
| 7035 | .await; |
| 7036 | let dead_res = dead_res.unwrap(); |
| 7037 | assert_eq!(dead_res["application"], "failed", "{dead_res}"); |
| 7038 | assert_eq!(dead_res["stage"], "enable"); |
| 7039 | assert_eq!(dead_res["enabled"], true); |
| 7040 | assert_eq!(dead_res["error"]["code"], "operation-error"); |
| 7041 | |
| 7042 | let acts_ok = receipts_ok["broker_acts"]["acts"].as_array().unwrap(); |
| 7043 | assert!( |
| 7044 | acts_ok.iter().any(|act| { |
| 7045 | act["service"] == "plugins" |
| 7046 | && act["method"] == "mcp_connect" |
| 7047 | && act["plugin"] == "my-decoration" |
| 7048 | && act["server"] == "demo" |
| 7049 | && act["outcome"] == "connected" |
| 7050 | }), |
| 7051 | "{receipts_ok}" |
| 7052 | ); |
| 7053 | let acts_dead = receipts_dead["broker_acts"]["acts"].as_array().unwrap(); |
| 7054 | assert!( |
| 7055 | acts_dead.iter().any(|act| { |
| 7056 | act["service"] == "plugins" |
| 7057 | && act["method"] == "mcp_connect" |
| 7058 | && act["plugin"] == "my-decoration-dead" |
| 7059 | && act["server"] == "demo" |
| 7060 | && act["outcome"] == "failed" |
| 7061 | }), |
| 7062 | "{receipts_dead}" |
| 7063 | ); |
| 7064 | |
| 7065 | f.manager.shutdown().await; |
| 7066 | } |
| 7067 | |
| 7068 | #[tokio::test(flavor = "current_thread")] |
| 7069 | async fn plugins_enable_waits_out_a_host_recycle_during_connector_verification() { |
| 7070 | let Some(node) = super::super::test_support::node_for_tests( |
| 7071 | "plugins_enable_waits_out_a_host_recycle_during_connector_verification", |
| 7072 | ) else { |
| 7073 | return; |
| 7074 | }; |
| 7075 | let _policy = TestPolicyGuard::extension_host(true); |
| 7076 | let mut f = PluginsFixture::new(); |
| 7077 | f.manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions { |
| 7078 | runtime: codewhale_config::extension_host::ExtensionHostRuntime::Node, |
| 7079 | node_override: Some(node), |
| 7080 | root: Some(f._temp.path().join("host-root")), |
| 7081 | ..Default::default() |
| 7082 | })); |
| 7083 | { |
| 7084 | let mut reg = f.manager.shared.registry.lock().unwrap(); |
| 7085 | f.creator = reg |
| 7086 | .begin_owner( |
| 7087 | HostCohort::Builtin, |
| 7088 | "host:creator", |
| 7089 | "creator", |
| 7090 | None, |
| 7091 | "digest", |
| 7092 | ) |
| 7093 | .unwrap(); |
| 7094 | reg.mark_active(&f.creator); |
| 7095 | } |
| 7096 | let _manager = TestManagerGuard::install(Arc::clone(&f.manager)); |
| 7097 | let initial_reg = f.reload_registry(); |
| 7098 | let _engine = f.manager.attach(initial_reg); |
| 7099 | let _ = _engine.set_creator_demand(true); |
| 7100 | |
| 7101 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 7102 | let pool = fixture_mcp_pool(&f); |
| 7103 | install_gate_with_pool(&mut f, Some(pool), |input, _| { |
| 7104 | allow_verdict(input, NestedDecision::Auto) |
| 7105 | }); |
| 7106 | |
| 7107 | let server = McpStubServer::spawn(McpStubBehavior::Ready(vec![json!({ |
| 7108 | "name": "read_mixed", |
| 7109 | "description": "Mixed native/DSH connector tool", |
| 7110 | "inputSchema": {"type": "object"} |
| 7111 | })])) |
| 7112 | .await; |
| 7113 | |
| 7114 | let src = f.config.workspace.join("mixed-recycle-src"); |
| 7115 | copy_dir_tree(&dsh_template_dir("decoration"), &src); |
| 7116 | let patch = format!( |
| 7117 | "- insert:\n - id: my-decoration\n name: '@local/my-decoration'\n - id: demo-mcp\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n serverName: demo\n transport: streamable-http\n url: {}\n failOnStartupError: true\n", |
| 7118 | server.url() |
| 7119 | ); |
| 7120 | fs::write(src.join("cordis.patch.yml"), patch).unwrap(); |
| 7121 | |
| 7122 | let inits_before_install = server.init_hits(); |
| 7123 | let (res, install_receipts) = f |
| 7124 | .call_admitted_with_receipts( |
| 7125 | &f.context, |
| 7126 | "install", |
| 7127 | json!({"target": src.to_string_lossy()}), |
| 7128 | ) |
| 7129 | .await; |
| 7130 | let res = res.unwrap(); |
| 7131 | assert_eq!(res["application"], "applied", "{res}"); |
| 7132 | assert_connector_reverified( |
| 7133 | &server, |
| 7134 | inits_before_install, |
| 7135 | &install_receipts, |
| 7136 | "my-decoration", |
| 7137 | "demo", |
| 7138 | ); |
| 7139 | |
| 7140 | let spawns_before = f.manager.spawn_attempts(); |
| 7141 | let plugin_id = discover_with_config(&f.config) |
| 7142 | .get("my-decoration") |
| 7143 | .unwrap() |
| 7144 | .id |
| 7145 | .as_str() |
| 7146 | .to_string(); |
| 7147 | let cohort = f |
| 7148 | .manager |
| 7149 | .owner_report(&plugin_id) |
| 7150 | .and_then(|report| report.cohort) |
| 7151 | .expect("installed plugin owner must report its host cohort"); |
| 7152 | let manager_for_hook = Arc::clone(&f.manager); |
| 7153 | let hook_outcome = Arc::new(std::sync::Mutex::new( |
| 7154 | "pre-connect hook did not fire".to_string(), |
| 7155 | )); |
| 7156 | let outcome_hook = Arc::clone(&hook_outcome); |
| 7157 | super::set_pre_connect_hook_for_test(Box::new(move || { |
| 7158 | let outcome = match manager_for_hook.shared.ready_host(&cohort) { |
| 7159 | Ok(host) => format!( |
| 7160 | "terminate_if_idle={}", |
| 7161 | host.terminate_if_idle("test host recycle") |
| 7162 | ), |
| 7163 | Err(status) => format!("ready_host={status}"), |
| 7164 | }; |
| 7165 | *outcome_hook.lock().unwrap() = outcome; |
| 7166 | })); |
| 7167 | |
| 7168 | let inits_before_enable = server.init_hits(); |
| 7169 | let (enable, enable_receipts) = f |
| 7170 | .call_admitted_with_receipts(&f.context, "enable", json!({"target": "my-decoration"})) |
| 7171 | .await; |
| 7172 | let enable = enable.unwrap(); |
| 7173 | let outcome = hook_outcome.lock().unwrap().clone(); |
| 7174 | assert_eq!( |
| 7175 | outcome, "terminate_if_idle=true", |
| 7176 | "pre-connect hook must retire the plugin host" |
| 7177 | ); |
| 7178 | assert_eq!(enable["application"], "applied", "{enable}"); |
| 7179 | assert_eq!(enable["enabled"], true, "{enable}"); |
| 7180 | assert_connector_reverified( |
| 7181 | &server, |
| 7182 | inits_before_enable, |
| 7183 | &enable_receipts, |
| 7184 | "my-decoration", |
| 7185 | "demo", |
| 7186 | ); |
| 7187 | assert!( |
| 7188 | f.manager.spawn_attempts() > spawns_before, |
| 7189 | "the plugin host must have restarted during verification" |
| 7190 | ); |
| 7191 | |
| 7192 | f.manager.shutdown().await; |
| 7193 | } |
| 7194 | |
| 7195 | #[tokio::test(flavor = "current_thread")] |
| 7196 | async fn native_only_install_and_enable_with_extension_host_off_names_switch() { |
| 7197 | let _policy = TestPolicyGuard::extension_host(false); |
| 7198 | let mut f = PluginsFixture::new(); |
| 7199 | f.reload_registry(); |
| 7200 | f.posture.switch_for_tests(ApprovalMode::Bypass); |
| 7201 | |
| 7202 | let install_src = |
| 7203 | write_native_bundle(&f.config.workspace, "native-off-src", "native-off", "1.0.0"); |
| 7204 | let install_res = f |
| 7205 | .call_admitted( |
| 7206 | &f.context, |
| 7207 | "install", |
| 7208 | json!({"target": install_src.to_string_lossy()}), |
| 7209 | ) |
| 7210 | .await |
| 7211 | .unwrap(); |
| 7212 | assert_eq!(install_res["application"], "failed", "{install_res}"); |
| 7213 | assert_eq!(install_res["stage"], "enable", "{install_res}"); |
| 7214 | assert_eq!(install_res["changed"], true, "{install_res}"); |
| 7215 | assert_eq!(install_res["enabled"], false, "{install_res}"); |
| 7216 | assert_eq!( |
| 7217 | install_res["error"]["diagnostic"], |
| 7218 | "the plugin host is switched off in this process, so native plugin code did not start", |
| 7219 | "{install_res}" |
| 7220 | ); |
| 7221 | |
| 7222 | let toggle_src = write_native_bundle( |
| 7223 | &f.config.workspace, |
| 7224 | "native-toggle-src", |
| 7225 | "native-toggle", |
| 7226 | "1.0.0", |
| 7227 | ); |
| 7228 | let disabled_install = f |
| 7229 | .call_admitted( |
| 7230 | &f.context, |
| 7231 | "install", |
| 7232 | json!({"target": toggle_src.to_string_lossy(), "enabled": false}), |
| 7233 | ) |
| 7234 | .await |
| 7235 | .unwrap(); |
| 7236 | assert_eq!( |
| 7237 | disabled_install["application"], "applied", |
| 7238 | "{disabled_install}" |
| 7239 | ); |
| 7240 | assert_eq!(disabled_install["enabled"], false, "{disabled_install}"); |
| 7241 | |
| 7242 | f.reload_registry(); |
| 7243 | let enable_res = f |
| 7244 | .call_admitted(&f.context, "enable", json!({"target": "native-toggle"})) |
| 7245 | .await |
| 7246 | .unwrap(); |
| 7247 | assert_eq!(enable_res["application"], "failed", "{enable_res}"); |
| 7248 | assert_eq!(enable_res["stage"], "enable", "{enable_res}"); |
| 7249 | assert_eq!(enable_res["changed"], false, "{enable_res}"); |
| 7250 | assert_eq!(enable_res["enabled"], false, "{enable_res}"); |
| 7251 | assert_eq!( |
| 7252 | enable_res["error"]["diagnostic"], |
| 7253 | "the plugin host is switched off in this process, so native plugin code did not start", |
| 7254 | "{enable_res}" |
| 7255 | ); |
| 7256 | |
| 7257 | f.manager.shutdown().await; |
| 7258 | } |
| 7259 |