返回 CodeWhale
plugin_trust_cli.rs
根目录 / crates / tui / tests / integration / plugin_trust_cli.rs
1 use std::path::Path;
2 use std::process::{Command, Output, Stdio};
3
4 use serde_json::Value;
5 use tempfile::TempDir;
6
7 struct Fixture {
8 home: TempDir,
9 workspace: TempDir,
10 }
11
12 impl Fixture {
13 fn new() -> Self {
14 let home = TempDir::new().expect("home");
15 std::fs::create_dir_all(home.path().join(".codewhale")).expect("config dir");
16 Self {
17 home,
18 workspace: TempDir::new().expect("workspace"),
19 }
20 }
21
22 fn marked(&self) -> [(&'static str, &str); 1] {
23 [(
24 "CODEWHALE_AGENT_PROJECT",
25 self.workspace.path().to_str().expect("utf-8 temp path"),
26 )]
27 }
28
29 fn run_with(&self, args: &[&str], env: &[(&str, &str)]) -> Output {
30 self.run_in(self.workspace.path(), args, env)
31 }
32
33 #[cfg(unix)]
34 fn status_in(&self, workspace: &Path) -> Value {
35 let output = self.run_in(workspace, &["plugins", "status", "demo", "--json"], &[]);
36 assert!(output.status.success(), "{output:?}");
37 let value: Value = serde_json::from_slice(&output.stdout).expect("status json");
38 value["plugins"][0].clone()
39 }
40
41 fn run_in(&self, workspace: &Path, args: &[&str], env: &[(&str, &str)]) -> Output {
42 let mut command = Command::new(crate::binary::codewhale());
43 command.env_clear();
44 for key in [
45 "PATH",
46 "TMPDIR",
47 "TEMP",
48 "TMP",
49 "TERM",
50 "LANG",
51 "LC_ALL",
52 "SystemRoot",
53 "WINDIR",
54 ] {
55 if let Some(value) = std::env::var_os(key) {
56 command.env(key, value);
57 }
58 }
59 command
60 .current_dir(workspace)
61 .arg("--workspace")
62 .arg(workspace)
63 .arg("--no-project-config")
64 .args(args)
65 .env("HOME", self.home.path())
66 .env("USERPROFILE", self.home.path())
67 .envs(env.iter().copied())
68 .env("XDG_CONFIG_HOME", self.home.path().join(".config"))
69 .env(
70 "CODEWHALE_CONFIG_PATH",
71 self.home.path().join(".codewhale").join("config.toml"),
72 )
73 .env("RUST_LOG", "warn")
74 .stdin(Stdio::null())
75 .output()
76 .expect("run codewhale")
77 }
78
79 fn ok(&self, args: &[&str]) -> Output {
80 self.ok_with(args, &[])
81 }
82
83 fn ok_with(&self, args: &[&str], env: &[(&str, &str)]) -> Output {
84 let output = self.run_with(args, env);
85 assert!(
86 output.status.success(),
87 "{args:?} failed\nstdout:\n{}\nstderr:\n{}",
88 String::from_utf8_lossy(&output.stdout),
89 String::from_utf8_lossy(&output.stderr)
90 );
91 output
92 }
93
94 fn refused(&self, args: &[&str], needle: &str) {
95 self.refused_with(args, &[], needle);
96 }
97
98 fn refused_with(&self, args: &[&str], env: &[(&str, &str)], needle: &str) -> String {
99 let output = self.run_with(args, env);
100 let stderr = String::from_utf8_lossy(&output.stderr);
101 assert!(
102 !output.status.success(),
103 "{args:?} must be refused\nstdout:\n{}",
104 String::from_utf8_lossy(&output.stdout)
105 );
106 assert!(
107 stderr.contains(needle),
108 "{args:?}: expected `{needle}` in:\n{stderr}"
109 );
110 stderr.into_owned()
111 }
112
113 fn status(&self) -> Value {
114 let output = self.ok(&["plugins", "status", "demo", "--json"]);
115 let value: Value = serde_json::from_slice(&output.stdout).expect("status json");
116 value["plugins"][0].clone()
117 }
118 }
119
120 fn write_bundle(parent: &Path) -> std::path::PathBuf {
121 let source = parent.join("demo");
122 std::fs::create_dir_all(source.join("skills").join("hello")).unwrap();
123 std::fs::write(
124 source.join("plugin.toml"),
125 "schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n",
126 )
127 .unwrap();
128 std::fs::write(
129 source.join("skills").join("hello").join("SKILL.md"),
130 "---\nname: hello\ndescription: hi\n---\nbody\n",
131 )
132 .unwrap();
133 source
134 }
135
136 fn review(fixture: &Fixture) -> String {
137 let output = fixture.ok(&["plugins", "trust", "demo", "--json"]);
138 let value: Value = serde_json::from_slice(&output.stdout).expect("review json");
139 assert!(
140 value["review"]
141 .as_str()
142 .is_some_and(|review| review.contains("Activation boundary:")),
143 "{value}"
144 );
145 value["bundle_review_token"].as_str().unwrap().to_string()
146 }
147
148 #[test]
149 fn headless_refusals_need_no_terminal_and_change_nothing() {
150 let fixture = Fixture::new();
151 write_bundle(&fixture.home.path().join(".codewhale").join("plugins"));
152 #[cfg(unix)]
153 {
154 use std::os::unix::fs::PermissionsExt;
155 let state_dir = fixture.home.path().join(".codewhale").join("plugins");
156 let mode = |mode| {
157 std::fs::set_permissions(&state_dir, std::fs::Permissions::from_mode(mode)).unwrap()
158 };
159 mode(0o755);
160 let unreadable = fixture.refused_with(&["plugins", "enable", "demo"], &[], "is unknown");
161 assert!(!unreadable.contains("plugins trust"), "{unreadable}");
162 mode(0o700);
163 }
164 assert_ne!(fixture.status()["trust"], "trusted");
165 fixture.refused(
166 &["plugins", "enable", "demo"],
167 if cfg!(unix) { "is not trusted" } else { "demo" },
168 );
169
170 let text = fixture.ok(&["plugins", "trust", "demo"]);
171 let text = String::from_utf8_lossy(&text.stdout);
172 assert!(text.contains("Activation boundary:"), "{text}");
173 assert!(text.contains("does not record that anyone read"), "{text}");
174 let token = review(&fixture);
175 assert!(
176 text.contains(&format!("Bundle review token: {token}")),
177 "{text}"
178 );
179 assert!(
180 text.contains("trusted from the command line with --yes"),
181 "{text}"
182 );
183 let (content, capability) = token.split_once('.').expect("two digests");
184
185 fixture.refused(&["plugins", "trust", "demo", "--yes"], "--review-token");
186 fixture.refused(
187 &["plugins", "trust", "demo", "--review-token", &token],
188 "Trust needs confirmation",
189 );
190 fixture.refused(
191 &[
192 "plugins",
193 "trust",
194 "demo",
195 "--review-token",
196 &format!("{content}.{}", "0".repeat(64)),
197 "--yes",
198 ],
199 "Bundle review token does not match",
200 );
201 fixture.refused(
202 &[
203 "plugins",
204 "trust",
205 "demo",
206 "--review-token",
207 &format!("{}.{capability}", "0".repeat(64)),
208 "--yes",
209 ],
210 "content changed",
211 );
212 fixture.refused_with(
213 &["plugins", "enable", "demo"],
214 &fixture.marked(),
215 if cfg!(unix) { "is not trusted" } else { "demo" },
216 );
217 let marked_review = fixture.ok_with(&["plugins", "trust", "demo"], &fixture.marked());
218 let marked_review = String::from_utf8_lossy(&marked_review.stdout);
219 assert!(
220 marked_review.contains("approved by the agent from a shell command"),
221 "{marked_review}"
222 );
223
224 let plugin = fixture.status();
225 assert_ne!(plugin["trust"], "trusted");
226 assert_eq!(plugin["enabled"], false);
227 }
228
229 #[cfg(unix)]
230 #[test]
231 fn headless_install_review_trust_enable_disable_revoke_journey() {
232 let fixture = Fixture::new();
233 let source = write_bundle(&fixture.workspace.path().join("source"));
234 fixture.ok(&["install", source.to_str().unwrap()]);
235
236 let plugin = fixture.status();
237 assert_eq!(plugin["enabled"], false);
238 assert_ne!(plugin["trust"], "trusted");
239 fixture.refused(&["plugins", "enable", "demo"], "codewhale plugins trust");
240
241 let token = review(&fixture);
242 assert_ne!(
243 fixture.status()["trust"],
244 "trusted",
245 "review alone must not trust"
246 );
247 let trust = [
248 "plugins",
249 "trust",
250 "demo",
251 "--review-token",
252 &token,
253 "--yes",
254 ];
255 fixture.ok(&trust);
256 let plugin = fixture.status();
257 assert_eq!(plugin["trust"], "trusted");
258 assert_eq!(plugin["enabled"], false);
259 assert_eq!(plugin["approved_by"]["kind"], "command_line");
260
261 fixture.refused_with(
262 &["plugins", "enable", "demo"],
263 &fixture.marked(),
264 "approved for every project",
265 );
266 assert_eq!(fixture.status()["enabled"], false);
267 fixture.ok(&["plugins", "enable", "demo"]);
268 let plugin = fixture.status();
269 assert_eq!(plugin["enabled"], true);
270 assert_eq!(plugin["active"], true);
271 assert_eq!(plugin["enabled_by"]["kind"], "command_line");
272
273 fixture.ok(&["plugins", "disable", "demo"]);
274 assert_eq!(fixture.status()["enabled"], false);
275
276 let skill = fixture
277 .home
278 .path()
279 .join(".codewhale/plugins/demo/skills/hello/SKILL.md");
280 std::fs::write(&skill, "---\nname: hello\ndescription: hi\n---\nchanged\n").unwrap();
281 fixture.refused(&trust, "content changed");
282 assert_ne!(fixture.status()["trust"], "trusted");
283
284 let token = review(&fixture);
285 fixture.ok_with(
286 &[
287 "plugins",
288 "trust",
289 "demo",
290 "--review-token",
291 &token,
292 "--yes",
293 ],
294 &fixture.marked(),
295 );
296 let plugin = fixture.status();
297 assert_eq!(plugin["approved_by"]["kind"], "agent");
298 assert_eq!(plugin["approved_by"]["posture"], "command_line");
299 assert_eq!(plugin["outside_reach"], false);
300 fixture.ok_with(&["plugins", "enable", "demo"], &fixture.marked());
301 let plugin = fixture.status();
302 assert_eq!(plugin["active"], true);
303 assert_eq!(plugin["enabled_by"]["kind"], "agent");
304 fixture.ok(&["plugins", "revoke", "demo"]);
305 let plugin = fixture.status();
306 assert_ne!(plugin["trust"], "trusted");
307 assert_eq!(plugin["active"], false);
308 }
309
310 #[cfg(unix)]
311 fn trust_args(token: &str) -> [&str; 6] {
312 ["plugins", "trust", "demo", "--review-token", token, "--yes"]
313 }
314
315 #[cfg(unix)]
316 #[test]
317 fn an_agents_trust_and_enable_reach_only_its_own_project() {
318 let fixture = Fixture::new();
319 let source = write_bundle(&fixture.workspace.path().join("source"));
320 fixture.ok(&["install", source.to_str().unwrap()]);
321 let other = TempDir::new().expect("other project");
322
323 let token = review(&fixture);
324 fixture.ok_with(&trust_args(&token), &fixture.marked());
325 fixture.ok_with(&["plugins", "enable", "demo"], &fixture.marked());
326 let here = fixture.status();
327 assert_eq!(here["approved_by"]["kind"], "agent", "{here}");
328 assert_eq!(here["enabled_by"]["kind"], "agent", "{here}");
329 assert_eq!(here["active"], true, "{here}");
330 let there = fixture.status_in(other.path());
331 assert_eq!(there["outside_reach"], true, "{there}");
332 assert_eq!(there["active"], false, "{there}");
333 }
334
335 #[cfg(unix)]
336 #[test]
337 fn the_agent_trusts_only_a_plugin_it_installed_from_its_project() {
338 let fixture = Fixture::new();
339 let source = write_bundle(&fixture.home.path().join("downloads"));
340 fixture.ok(&["install", source.to_str().unwrap()]);
341 let token = review(&fixture);
342
343 fixture.refused_with(&trust_args(&token), &fixture.marked(), "ask the person");
344 assert_ne!(fixture.status()["trust"], "trusted");
345
346 fixture.ok(&trust_args(&token));
347 assert_eq!(fixture.status()["approved_by"]["kind"], "command_line");
348 }
349
350 #[cfg(target_os = "linux")]
351 #[test]
352 fn a_prompt_answered_in_a_pseudo_terminal_is_the_agents_when_marked() {
353 use std::io::Write;
354
355 let fixture = Fixture::new();
356 let source = write_bundle(&fixture.workspace.path().join("source"));
357 fixture.ok(&["install", source.to_str().unwrap()]);
358 let quoted = |value: &str| format!("'{}'", value.replace('\'', "'\\''"));
359 let answer_in_pty = |env: &[(&str, &str)]| {
360 let line = [
361 quoted(crate::binary::codewhale().to_str().unwrap()),
362 "--workspace".to_string(),
363 quoted(fixture.workspace.path().to_str().unwrap()),
364 "--no-project-config plugins trust demo".to_string(),
365 ]
366 .join(" ");
367 let mut command = Command::new("script");
368 command.env_clear();
369 for key in ["PATH", "TMPDIR", "LANG", "LC_ALL"] {
370 if let Some(value) = std::env::var_os(key) {
371 command.env(key, value);
372 }
373 }
374 let mut child = command
375 .current_dir(fixture.workspace.path())
376 .args(["-qec", line.as_str(), "/dev/null"])
377 .env("TERM", "xterm")
378 .env("HOME", fixture.home.path())
379 .env("XDG_CONFIG_HOME", fixture.home.path().join(".config"))
380 .env(
381 "CODEWHALE_CONFIG_PATH",
382 fixture.home.path().join(".codewhale").join("config.toml"),
383 )
384 .env("RUST_LOG", "warn")
385 .envs(env.iter().copied())
386 .stdin(Stdio::piped())
387 .stdout(Stdio::piped())
388 .stderr(Stdio::piped())
389 .spawn()
390 .expect("script(1) runs");
391 child.stdin.take().unwrap().write_all(b"y\n").unwrap();
392 let output = child.wait_with_output().expect("script(1) finishes");
393 assert!(output.status.success(), "{output:?}");
394 };
395
396 answer_in_pty(&[]);
397 let person = fixture.status();
398 assert_eq!(person["approved_by"]["kind"], "person", "{person}");
399
400 fixture.ok(&["plugins", "revoke", "demo"]);
401 answer_in_pty(&fixture.marked());
402 let agent = fixture.status();
403 assert_eq!(agent["approved_by"]["kind"], "agent", "{agent}");
404 assert_eq!(agent["approved_by"]["posture"], "command_line", "{agent}");
405 }
406
407 #[cfg(unix)]
408 #[tokio::test]
409 async fn a_prompt_answered_through_the_agents_terminal_tools_is_the_agents() {
410 use codewhale_engine::tools::spec::{ToolContext, ToolSpec};
411 use codewhale_engine::tools::terminal_session::{
412 TerminalResetTool, TerminalRunTool, TerminalSendTool, TerminalWaitTool,
413 };
414
415 let fixture = Fixture::new();
416 let source = write_bundle(&fixture.workspace.path().join("source"));
417 fixture.ok(&["install", source.to_str().unwrap()]);
418 let quoted = |value: &Path| format!("'{}'", value.display().to_string().replace('\'', "'\\''"));
419 let home = fixture.home.path();
420 let command = format!(
421 "HOME={} USERPROFILE={} XDG_CONFIG_HOME={} CODEWHALE_CONFIG_PATH={} RUST_LOG=warn {} --workspace {} --no-project-config plugins trust demo",
422 quoted(home),
423 quoted(home),
424 quoted(&home.join(".config")),
425 quoted(&home.join(".codewhale").join("config.toml")),
426 quoted(&crate::binary::codewhale()),
427 quoted(fixture.workspace.path()),
428 );
429 let mut context = ToolContext::new(fixture.workspace.path())
430 .with_elevated_sandbox_policy(codewhale_sandbox::SandboxPolicy::DangerFullAccess);
431 context.auto_approve = true;
432 let session = "plugin-trust-prompt";
433
434 let asked = TerminalRunTool
435 .execute(
436 serde_json::json!({ "command": command, "session": session, "timeout_secs": 5 }),
437 &context,
438 )
439 .await
440 .expect("terminal_run");
441 assert!(asked.content.contains("[y/N]"), "{}", asked.content);
442 TerminalSendTool
443 .execute(
444 serde_json::json!({ "session": session, "text": "y\n", "wait_ms": 500 }),
445 &context,
446 )
447 .await
448 .expect("terminal_send");
449 let done = TerminalWaitTool
450 .execute(
451 serde_json::json!({ "session": session, "timeout_secs": 60 }),
452 &context,
453 )
454 .await
455 .expect("terminal_wait");
456 let _ = TerminalResetTool
457 .execute(serde_json::json!({ "session": session }), &context)
458 .await;
459
460 let plugin = fixture.status();
461 assert_eq!(
462 plugin["approved_by"]["kind"], "agent",
463 "{plugin}\n{}",
464 done.content
465 );
466 assert_eq!(plugin["approved_by"]["posture"], "command_line", "{plugin}");
467 }
468
469 #[cfg(unix)]
470 #[test]
471 fn auto_review_mark_records_auto_review_posture_with_provenance_and_refuses_bad_env() {
472 let fixture = Fixture::new();
473 let source = write_bundle(&fixture.workspace.path().join("source"));
474 fixture.ok(&["install", source.to_str().unwrap()]);
475 let token = review(&fixture);
476 let project = fixture.workspace.path().to_str().expect("utf-8 path");
477
478 let missing_ids = [
479 ("CODEWHALE_AGENT_PROJECT", project),
480 ("CODEWHALE_AGENT_POSTURE", "auto_review"),
481 ("CODEWHALE_AGENT_THREAD_ID", "thread-cli-1"),
482 ];
483 fixture.refused_with(
484 &trust_args(&token),
485 &missing_ids,
486 "thread, turn and tool call",
487 );
488 assert_ne!(fixture.status()["trust"], "trusted");
489
490 let bad_posture = [
491 ("CODEWHALE_AGENT_PROJECT", project),
492 ("CODEWHALE_AGENT_POSTURE", "bogus_mode"),
493 ];
494 fixture.refused_with(
495 &trust_args(&token),
496 &bad_posture,
497 "Unsupported CODEWHALE_AGENT_POSTURE",
498 );
499
500 let auto_review_env = [
501 ("CODEWHALE_AGENT_PROJECT", project),
502 ("CODEWHALE_AGENT_POSTURE", "auto_review"),
503 ("CODEWHALE_AGENT_THREAD_ID", "thread-cli-1"),
504 ("CODEWHALE_AGENT_TURN_ID", "turn-cli-2"),
505 ("CODEWHALE_AGENT_TOOL_CALL_ID", "call-cli-3"),
506 ];
507 fixture.ok_with(&trust_args(&token), &auto_review_env);
508 fixture.ok_with(&["plugins", "enable", "demo"], &auto_review_env);
509
510 let plugin = fixture.status();
511 assert_eq!(plugin["approved_by"]["kind"], "agent", "{plugin}");
512 assert_eq!(plugin["approved_by"]["posture"], "auto_review", "{plugin}");
513 assert_eq!(
514 plugin["approved_by"]["thread_id"], "thread-cli-1",
515 "{plugin}"
516 );
517 assert_eq!(plugin["approved_by"]["turn_id"], "turn-cli-2", "{plugin}");
518 assert_eq!(
519 plugin["approved_by"]["tool_call_id"], "call-cli-3",
520 "{plugin}"
521 );
522 assert_eq!(plugin["enabled_by"]["kind"], "agent", "{plugin}");
523 assert_eq!(plugin["enabled_by"]["posture"], "auto_review", "{plugin}");
524 assert_eq!(
525 plugin["enabled_by"]["thread_id"], "thread-cli-1",
526 "{plugin}"
527 );
528 assert_eq!(plugin["active"], true, "{plugin}");
529
530 let status_out = fixture.ok(&["plugins", "status", "demo"]);
531 let status_text = String::from_utf8_lossy(&status_out.stdout);
532 assert!(
533 status_text.contains("approved by the agent in Auto-Review"),
534 "{status_text}"
535 );
536 }
537
537 lines RUST