返回 CodeWhale
approval_cache.rs
根目录 / crates / engine / src / tools / approval_cache.rs
1 //! Approval fingerprint keys (§5.A).
2 //!
3 //! Instead of caching by tool name alone (which would let an approved
4 //! `exec_shell "cat foo"` silently pass `exec_shell "rm -rf /"`), the
5 //! approval flow uses a **call fingerprint** — a digest of the tool name
6 //! and the semantically‑relevant portion of its arguments.
7 //!
8 //! ## Two fingerprint shapes
9 //!
10 //! There are two key flavours, used for opposite sides of the decision:
11 //!
12 //! * [`build_approval_key`] — an **exact** digest of the full arguments.
13 //! Used to scope *denials* so that denying one call (e.g. `rm -rf /tmp/x`)
14 //! does not also suppress a later, different call to the same tool (#1617).
15 //!
16 //! | Tool | Exact key |
17 //! |---------------|------------------------------------------|
18 //! | file writes | `file:<tool_name>:<hash of args>` |
19 //! | shell tools | `shell:<tool_name>:<hash of args>` |
20 //! | `fetch_url` | `net:<hostname>` |
21 //! | everything else| `tool:<tool_name>:<hash of input>` |
22 //!
23 //! * [`build_approval_grouping_key`] — a **lossy / arity-aware** digest.
24 //! Used to scope *approvals* so that approving `cargo build` for the
25 //! session also covers `cargo build --release` (the v0.8.37 behaviour).
26 //!
27 //! | Tool | Grouping key |
28 //! |---------------|------------------------------------------|
29 //! | `apply_patch` | `patch:<hash of file paths>` |
30 //! | shell tools | `shell:<command family>` for a simple, known command; `shell:cmd:<full normalized command>` otherwise |
31 //! | shell interact / wait | `shell:<tool_name>:<hash of args>` |
32 //! | `fetch_url` | `net:<hostname>` |
33 //! | Computer Use consent / `app_script` | `cu:<tool_name>:<hash of input>` |
34 //! | other MCP tools| `mcp:<tool_name>` (the reviewed kind) |
35 //! | everything else| `tool:<tool_name>:<hash of input>` |
36 //!
37 //! ## Computer Use calls that need a human (K1 / K2)
38 //!
39 //! [`computer_use_user_gate`] names the Computer Use calls whose approval must
40 //! come from a person: granting or revoking per-app consent (which includes the
41 //! shared-pointer `scope: "foreground"` decision) and `app_script`, an
42 //! unsandboxed osascript. Those calls are never covered by the MCP kind grant:
43 //! their session grant is the exact call, so allowing app X never allows app Y
44 //! and approving one script never approves a changed one. Engine preparation
45 //! also refuses them in any posture that cannot open a human approval card,
46 //! and refuses a `run_actions` batch that carries one as a step
47 //! ([`computer_use_batch_hidden_gate`]).
48 //!
49 //! Known limits of this stopgap: the calls are matched by MCP tool-name suffix
50 //! (`_consent`, `_consent_allow`, `_consent_revoke`, `_app_script`), so a
51 //! different MCP server exposing a tool with one of those names is gated the
52 //! same way (fail closed). Consent, script and computer registration/spawn
53 //! calls force an exact human card. Only its human decision can be attested
54 //! to the reviewed built-in plugin; grants and autonomous modes cannot mint it.
55 use std::fmt::Write as _;
56
57 use serde_json::Value;
58 use sha2::{Digest, Sha256};
59
60 use codewhale_execpolicy::command_safety::{canonical_prefix_is_leading, classify_command};
61
62 /// The fingerprint of a tool call — stable enough to match repeated
63 /// calls but specific enough to avoid privilege confusion.
64 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
65 pub struct ApprovalKey(pub String);
66
67 /// Build the approval‑cache key for a tool call.
68 ///
69 /// The key incorporates the tool name and a canonical digest of the
70 /// arguments so that denying one call suppresses exact retries, not later
71 /// invocations of the same tool with different parameters.
72 #[must_use]
73 pub fn build_approval_key(tool_name: &str, input: &serde_json::Value) -> ApprovalKey {
74 let tool_name =
75 codewhale_execpolicy::canonical_action::canonical_action_alias(tool_name, input);
76 let fingerprint = match tool_name {
77 "apply_patch" | "write_file" | "edit_file" | "fim_edit" => {
78 format!("file:{tool_name}:{}", hash_json_value(input))
79 }
80 "exec_shell"
81 | "task_shell_start"
82 | "exec_shell_wait"
83 | "exec_shell_interact"
84 | "exec_wait"
85 | "exec_interact" => exact_shell_call_key(tool_name, input),
86 "fetch_url" | "web.fetch" | "web_fetch" => {
87 let host = parse_host(input);
88 format!("net:{host}")
89 }
90 _ => format!("tool:{tool_name}:{}", hash_json_value(input)),
91 };
92 ApprovalKey(fingerprint)
93 }
94
95 /// Build the **grouping** approval key for a tool call.
96 ///
97 /// Unlike [`build_approval_key`], this collapses argument variants of the
98 /// same command family onto one key (the v0.8.37 behaviour) so that an
99 /// "approve for session" decision covers later invocations that differ only
100 /// by flags. Denials must keep using the exact [`build_approval_key`].
101 #[must_use]
102 pub fn build_approval_grouping_key(tool_name: &str, input: &serde_json::Value) -> ApprovalKey {
103 let tool_name =
104 codewhale_execpolicy::canonical_action::canonical_action_alias(tool_name, input);
105 let fingerprint = match tool_name {
106 "apply_patch" => {
107 let paths_hash = hash_patch_paths(input);
108 format!("patch:{paths_hash}")
109 }
110 "exec_shell" | "task_shell_start" if shell_call_carries_stdin(input) => {
111 exact_shell_call_key(tool_name, input)
112 }
113 "exec_shell" | "task_shell_start" => shell_command_grant_scope(input),
114 // Interact and wait calls carry no command, only input for a live
115 // session. Keying them on the (empty) command prefix gave every one
116 // of them the same grant; a grant covers the exact call only.
117 "exec_shell_wait" | "exec_shell_interact" | "exec_wait" | "exec_interact" => {
118 format!("shell:{tool_name}:{}", hash_json_value(input))
119 }
120 "fetch_url" | "web.fetch" | "web_fetch" => {
121 let host = parse_host(input);
122 format!("net:{host}")
123 }
124 // MCP tools are reviewed as kinds: a trusted plugin bundle's MCP
125 // tools were human-reviewed at trust time, so the session grant the
126 // approval card offers (`2` — "approves for the session") is the
127 // reviewed kind, `mcp:<tool>`. Hashing the full params here would
128 // make every exact-argument variant its own family and silently
129 // narrow the granted kind into a one-call grant (the regression the
130 // plugin e2e acceptance catches). Shell keeps its command-family
131 // key (R2); this arm never widens shell or file tools.
132 //
133 // Computer Use consent and `app_script` are the exception (K1/K2):
134 // a kind grant there would let one approval cover every app or every
135 // script, so their session grant is the exact call.
136 name if computer_use_user_gate(name, input).is_some() => {
137 format!("cu:{name}:{}", hash_json_value(input))
138 }
139 name if crate::mcp::McpPool::is_mcp_tool(name) => format!("mcp:{name}"),
140 // E1: a session grant for web browsing covers the argument class the
141 // person approved (search, open, …), not the one exact query.
142 "web.run" => format!("web:{tool_name}:{}", web_run_action_class(input)),
143 "web_search" => format!("web:{tool_name}"),
144 _ => format!("tool:{tool_name}:{}", hash_json_value(input)),
145 };
146 ApprovalKey(fingerprint)
147 }
148
149 /// Prefix on approval keys minted for human-confirmed `plugin_manager` changes.
150 pub const CREATOR_HUMAN_APPROVAL_KEY_PREFIX: &str = "creator-human:";
151
152 /// Whether a Rust-minted approval key bypasses Full Access's policy-hold auto-denial
153 /// so a person still answers on the approval card.
154 #[must_use]
155 pub fn forces_full_access_prompt_for_key(approval_key: &str) -> bool {
156 approval_key.starts_with("extcall:ext:")
157 || approval_key.starts_with(CREATOR_HUMAN_APPROVAL_KEY_PREFIX)
158 || approval_key.starts_with(crate::tools::web::consent::CONSENT_APPROVAL_KEY_PREFIX)
159 }
160
161 /// Exact and grouping keys for one call, as the engine puts them on an
162 /// approval request. A tool with an [`approval_scope`] (extension tools) is
163 /// keyed `<scope>:<tool_name>:<hash of input>` for both, so its grants are
164 /// bound to the reviewed plugin build and never widened to a family; every
165 /// other tool keeps [`build_approval_key`] / [`build_approval_grouping_key`].
166 /// The registry's captured owning agent prefixes both keys with `agent:<id>:`,
167 /// so its grants and denials never cover a parent or sibling's call.
168 ///
169 /// [`approval_scope`]: crate::tools::spec::ToolSpec::approval_scope
170 #[must_use]
171 pub fn approval_keys_for_call(
172 registry: Option<&crate::tools::ToolRegistry>,
173 tool_name: &str,
174 input: &serde_json::Value,
175 ) -> (ApprovalKey, ApprovalKey) {
176 let tool = registry.and_then(|registry| registry.get(tool_name));
177 let creator_changing = tool.as_deref().is_some_and(|spec| {
178 crate::extension_host::creator_policy::is_creator_changing_spec_call(spec, input)
179 });
180 let scope = tool.and_then(|tool| tool.approval_scope());
181 let keys = match scope {
182 Some(scope) if creator_changing => {
183 let key = ApprovalKey(format!(
184 "{CREATOR_HUMAN_APPROVAL_KEY_PREFIX}{scope}:{tool_name}:{}",
185 hash_json_value(input)
186 ));
187 (key.clone(), key)
188 }
189 Some(scope) => {
190 let key = ApprovalKey(format!("{scope}:{tool_name}:{}", hash_json_value(input)));
191 (key.clone(), key)
192 }
193 None if creator_changing => {
194 let key = ApprovalKey(format!(
195 "{CREATOR_HUMAN_APPROVAL_KEY_PREFIX}{tool_name}:{}",
196 hash_json_value(input)
197 ));
198 (key.clone(), key)
199 }
200 None => (
201 build_approval_key(tool_name, input),
202 build_approval_grouping_key(tool_name, input),
203 ),
204 };
205 if let Some(owner) = registry.and_then(|registry| registry.context().owner_agent_id.as_deref())
206 {
207 let scoped = |key: ApprovalKey| ApprovalKey(format!("agent:{owner}:{}", key.0));
208 (scoped(keys.0), scoped(keys.1))
209 } else {
210 keys
211 }
212 }
213
214 /// [`approval_keys_for_call`] for a call an extension made through `core/call`
215 /// (`scope` is the extension plugin build's [`approval_scope`]): both keys are
216 /// prefixed `extcall:<scope>:`, so a session grant or a denial recorded for the
217 /// model's call of a tool never matches the extension's call of it, and the
218 /// reverse, and neither crosses to another plugin build.
219 ///
220 /// [`approval_scope`]: crate::tools::spec::ToolSpec::approval_scope
221 #[must_use]
222 pub fn extension_origin_approval_keys(
223 scope: &str,
224 registry: Option<&crate::tools::ToolRegistry>,
225 tool_name: &str,
226 input: &serde_json::Value,
227 ) -> (ApprovalKey, ApprovalKey) {
228 let (exact, grouping) = approval_keys_for_call(registry, tool_name, input);
229 let scoped = |key: ApprovalKey| ApprovalKey(format!("extcall:{scope}:{}", key.0));
230 (scoped(exact), scoped(grouping))
231 }
232
233 /// The sorted `web.run` action kinds present in `input`, e.g. `open+search_query`.
234 fn web_run_action_class(input: &Value) -> String {
235 const ACTIONS: [&str; 6] = [
236 "click",
237 "find",
238 "image_query",
239 "open",
240 "screenshot",
241 "search_query",
242 ];
243 let present: Vec<String> = ACTIONS
244 .into_iter()
245 .filter(|action| input.get(*action).is_some_and(|value| !value.is_null()))
246 .map(|action| {
247 if action == "open" {
248 format!("open({})", web_run_open_targets(input))
249 } else {
250 action.to_string()
251 }
252 })
253 .collect();
254 if present.is_empty() {
255 "none".to_string()
256 } else {
257 present.join("+")
258 }
259 }
260
261 /// The sorted target set of a `web.run` `open`: the host of each raw URL, or
262 /// `ref` for a result reference. `open` fetches any raw URL it is given, and a
263 /// URL can carry local data out in its path or query, so an "open" grant
264 /// covers the hosts the person approved — as `fetch_url` grants do — never
265 /// every host.
266 fn web_run_open_targets(input: &Value) -> String {
267 let mut targets: Vec<String> = input
268 .get("open")
269 .and_then(Value::as_array)
270 .into_iter()
271 .flatten()
272 .map(|item| {
273 let ref_id = item.get("ref_id").and_then(Value::as_str).unwrap_or("");
274 if ref_id.starts_with("http://") || ref_id.starts_with("https://") {
275 reqwest::Url::parse(ref_id)
276 .ok()
277 .and_then(|url| url.host_str().map(str::to_ascii_lowercase))
278 .unwrap_or_else(|| format!("url:{}", hash_json_value(item)))
279 } else {
280 "ref".to_string()
281 }
282 })
283 .collect();
284 targets.sort_unstable();
285 targets.dedup();
286 targets.join(",")
287 }
288
289 /// A Computer Use call whose approval must come from a person (K1 / K2).
290 #[derive(Debug, Clone, PartialEq, Eq)]
291 pub enum ComputerUseUserGate {
292 /// A consent ledger write that widens what the model may do: `allow`, or
293 /// `revoke` (which can clear a persisted deny).
294 Consent {
295 action: &'static str,
296 app: Option<String>,
297 bundle_id: Option<String>,
298 scope: &'static str,
299 remember: bool,
300 /// An `allow` carrying a plugin `confirm` token: the person is
301 /// confirming an irreversible action (pay, buy, send, transfer,
302 /// delete) the plugin paused on, not consenting to an app.
303 confirm: bool,
304 },
305 /// `app_script`: arbitrary AppleScript/JXA through osascript.
306 AppScript {
307 language: &'static str,
308 script_sha256: String,
309 first_line: String,
310 /// Non-empty lines in the script, so the card can say how much is
311 /// not shown by `first_line`.
312 line_count: usize,
313 },
314 /// Registering or spawning a computer the plugin will then drive (and,
315 /// for ssh, push an agent to).
316 Computer {
317 action: &'static str,
318 transport: Option<String>,
319 /// `user@host:port` for ssh, the target or image otherwise.
320 destination: Option<String>,
321 },
322 }
323
324 /// Classify an MCP tool call as a Computer Use call that needs a human
325 /// decision. See the module docs for the matching rule and its limits.
326 #[must_use]
327 pub fn computer_use_user_gate(tool_name: &str, input: &Value) -> Option<ComputerUseUserGate> {
328 if !tool_name.starts_with("mcp_") {
329 return None;
330 }
331 let text = |key: &str| {
332 input
333 .get(key)
334 .and_then(Value::as_str)
335 .map(str::trim)
336 .filter(|value| !value.is_empty())
337 .map(str::to_string)
338 };
339 let computer_action = if tool_name.ends_with("_computer_register") {
340 Some("register")
341 } else if tool_name.ends_with("_computer_spawn") {
342 Some("spawn")
343 } else if tool_name.ends_with("_computer") {
344 match input.get("action").and_then(Value::as_str) {
345 Some("register") => Some("register"),
346 Some("spawn") => Some("spawn"),
347 _ => None,
348 }
349 } else {
350 None
351 };
352 if let Some(action) = computer_action {
353 let host = text("host");
354 let destination = match host {
355 Some(host) => {
356 let user = text("user")
357 .map(|user| format!("{user}@"))
358 .unwrap_or_default();
359 let port = input
360 .get("port")
361 .and_then(Value::as_u64)
362 .map(|port| format!(":{port}"))
363 .unwrap_or_default();
364 Some(format!("{user}{host}{port}"))
365 }
366 None => text("target").or_else(|| text("image")),
367 };
368 return Some(ComputerUseUserGate::Computer {
369 action,
370 transport: text("transport"),
371 destination,
372 });
373 }
374 let action = if tool_name.ends_with("_consent_allow") {
375 "allow"
376 } else if tool_name.ends_with("_consent_revoke") {
377 "revoke"
378 } else if tool_name.ends_with("_consent") {
379 match input.get("action").and_then(Value::as_str) {
380 Some("allow") => "allow",
381 Some("revoke") => "revoke",
382 // `status` reads; `deny` only narrows what the model may do.
383 _ => return None,
384 }
385 } else if tool_name.ends_with("_app_script") {
386 let script = input.get("script").and_then(Value::as_str).unwrap_or("");
387 let language = match input.get("language").and_then(Value::as_str) {
388 Some("javascript") => "JXA",
389 _ => "AppleScript",
390 };
391 let digest = Sha256::digest(script.as_bytes());
392 let mut script_sha256 = String::with_capacity(64);
393 for byte in digest {
394 write!(&mut script_sha256, "{byte:02x}").expect("writing to String cannot fail");
395 }
396 let first_line = script
397 .lines()
398 .map(str::trim)
399 .find(|line| !line.is_empty())
400 .unwrap_or("")
401 .chars()
402 .take(120)
403 .collect();
404 let line_count = script
405 .lines()
406 .filter(|line| !line.trim().is_empty())
407 .count();
408 return Some(ComputerUseUserGate::AppScript {
409 language,
410 script_sha256,
411 first_line,
412 line_count,
413 });
414 } else {
415 return None;
416 };
417 let pid = input
418 .get("pid")
419 .and_then(Value::as_i64)
420 .map(|pid| format!("pid:{pid}"));
421 Some(ComputerUseUserGate::Consent {
422 action,
423 app: text("app").or_else(|| text("name")).or(pid),
424 bundle_id: text("bundle_id"),
425 scope: if input.get("scope").and_then(Value::as_str) == Some("foreground") {
426 "foreground"
427 } else {
428 "app"
429 },
430 remember: input.get("remember").and_then(Value::as_bool) == Some(true),
431 confirm: action == "allow" && text("confirm").is_some(),
432 })
433 }
434
435 /// Whether this call exists only to carry a person's own answer: Computer Use
436 /// consent, a consent revoke, or an app script. A posture may supply an
437 /// allowance, but it can never supply an answer.
438 #[must_use]
439 pub fn computer_use_human_decision_tool(tool_name: &str) -> bool {
440 tool_name.starts_with("mcp_")
441 && [
442 "_consent",
443 "_consent_allow",
444 "_consent_revoke",
445 "_app_script",
446 ]
447 .iter()
448 .any(|suffix| tool_name.ends_with(suffix))
449 }
450
451 /// The inner tool of the first `run_actions` step that would need a human
452 /// decision (K1 / K2). Computer Use `run_actions` accepts any plugin tool name
453 /// as a step — including the unlisted `consent_allow` / `consent_revoke` and
454 /// `app_script` — so a batch would otherwise carry a consent grant or a
455 /// script past the per-call card. Engine preparation refuses such a batch.
456 #[must_use]
457 pub fn computer_use_batch_hidden_gate(tool_name: &str, input: &Value) -> Option<String> {
458 if !tool_name.starts_with("mcp_") || !tool_name.ends_with("_run_actions") {
459 return None;
460 }
461 input
462 .get("steps")
463 .and_then(Value::as_array)?
464 .iter()
465 .find_map(|step| {
466 let inner = step.get("tool").and_then(Value::as_str)?;
467 let arguments = step
468 .get("arguments")
469 .or_else(|| step.get("args"))
470 .unwrap_or(&Value::Null);
471 computer_use_user_gate(&format!("mcp_{inner}"), arguments).map(|_| inner.to_string())
472 })
473 }
474
475 fn exact_shell_call_key(tool_name: &str, input: &serde_json::Value) -> String {
476 let mut execution_input = input.clone();
477 if let Some(fields) = execution_input.as_object_mut() {
478 fields.remove("description");
479 }
480 format!("shell:{tool_name}:{}", hash_json_value(&execution_input))
481 }
482
483 fn shell_call_carries_stdin(input: &serde_json::Value) -> bool {
484 ["stdin", "input", "data"]
485 .iter()
486 .any(|key| input.get(*key).is_some_and(|value| !value.is_null()))
487 }
488
489 /// The session-grant scope for a shell command.
490 ///
491 /// A simple command whose family is in the arity dictionary keeps the
492 /// family grant, so approving `git status` also covers `git status -s`
493 /// without covering `git push`. Everything else fails closed to the full
494 /// normalized command:
495 ///
496 /// * compound commands (`;`, `&&`, `|`, redirects, substitutions, `$VAR`):
497 /// a grant for `cd` must not extend to whatever is chained after it;
498 /// * wrappers and interpreters (`bash -c`, `env`, `sudo`, `xargs`,
499 /// `python -c`, `docker run`, …): the first word says nothing about what
500 /// runs;
501 /// * commands the dictionary does not know, which used to collapse to their
502 /// first word, so one approval covered every use of that program.
503 fn shell_command_grant_scope(input: &serde_json::Value) -> String {
504 let cmd = input.get("command").and_then(|v| v.as_str()).unwrap_or("");
505 let tokens: Vec<&str> = cmd.split_whitespace().collect();
506 if tokens.is_empty() {
507 return "shell:<empty>".to_string();
508 }
509 if !shell_command_is_compound(cmd)
510 && !shell_command_is_wrapper(&tokens)
511 && !shell_command_has_code_option(&tokens)
512 {
513 let family = classify_command(&tokens);
514 // Options wedged before a subcommand (`git -c k=v status`), a chain,
515 // or code that runs nested or resolves only at run time also keep
516 // the grant to this exact command (#6675).
517 let expansion = codewhale_execpolicy::shell_expand::expand_command(cmd);
518 if command_family_is_known(&family)
519 && !family_arguments_are_config(&family)
520 && !family_arguments_are_code(&family)
521 && !expansion.dynamic
522 && !expansion.nested
523 && expansion.commands.len() == 1
524 && canonical_prefix_is_leading(&tokens, &family)
525 {
526 return format!("shell:{family}");
527 }
528 }
529 format!("shell:cmd:{}", normalize_shell_command(cmd))
530 }
531
532 /// Whether any option could change what a known command runs, reads or
533 /// writes. The family ignores flags, so a family grant is kept only when
534 /// every option is on [`INERT_OPTIONS`]; anything else keys the grant on the
535 /// full command.
536 ///
537 /// An allow-list, not a deny-list: options take values in too many spellings
538 /// (`-C../x`, `-f/tmp/x`, `--output out.patch`, `-x "cmd"`, `-exec ./x`,
539 /// `-O<cmd>`) for a list of dangerous ones to be complete.
540 fn shell_command_has_code_option(tokens: &[&str]) -> bool {
541 tokens.iter().skip(1).any(|token| {
542 token.contains('=') || (token.starts_with('-') && !INERT_OPTIONS.contains(token))
543 })
544 }
545
546 /// Value-free options that only change how much a command prints or which of
547 /// its own outputs it builds, never what it runs or where it writes.
548 const INERT_OPTIONS: &[&str] = &[
549 "-h",
550 "--help",
551 "-V",
552 "--version",
553 "-v",
554 "-vv",
555 "--verbose",
556 "-q",
557 "--quiet",
558 "-s",
559 "--short",
560 "--porcelain",
561 "--oneline",
562 "--stat",
563 "--name-only",
564 "--name-status",
565 "--cached",
566 "--staged",
567 "--no-color",
568 "--release",
569 "-p",
570 "--package",
571 "--workspace",
572 "--all-targets",
573 "--all-features",
574 "--lib",
575 "--bins",
576 "--tests",
577 "--locked",
578 "--frozen",
579 "--offline",
580 "--no-fail-fast",
581 "--dry-run",
582 ];
583
584 /// Families whose positional arguments beyond the family are themselves what
585 /// runs or gets installed (`go run <file>`, `git bisect run <cmd>`,
586 /// `make <target>`, `npm install <pkg>`), so one grant would cover any of
587 /// them.
588 fn family_arguments_are_code(family: &str) -> bool {
589 const FAMILIES: &[&str] = &[
590 "make",
591 "go run",
592 "go install",
593 "go get",
594 "go generate",
595 "deno run",
596 "bun run",
597 "cargo run",
598 "cargo install",
599 "cargo add",
600 "git bisect",
601 "git submodule",
602 "npm install",
603 "yarn add",
604 "pnpm add",
605 "bun add",
606 "pip install",
607 "pip3 install",
608 "docker compose run",
609 "docker compose exec",
610 "docker container run",
611 "docker container exec",
612 ];
613 FAMILIES.contains(&family)
614 }
615
616 /// Families whose arguments are settings, so one grant would cover every
617 /// setting (`git config user.name x` covering `git config core.fsmonitor`).
618 fn family_arguments_are_config(family: &str) -> bool {
619 matches!(family.split(' ').nth(1), Some("config" | "set" | "remote"))
620 }
621
622 /// Whether the dictionary recognised `family`, rather than falling back to
623 /// the bare first word.
624 fn command_family_is_known(family: &str) -> bool {
625 use codewhale_execpolicy::command_safety::COMMAND_ARITY;
626 COMMAND_ARITY
627 .iter()
628 .any(|(key, _)| family == *key || family.starts_with(&format!("{key} ")))
629 }
630
631 /// Any shell syntax that chains, redirects, substitutes, or expands.
632 fn shell_command_is_compound(cmd: &str) -> bool {
633 cmd.contains(|c: char| {
634 matches!(
635 c,
636 ';' | '&' | '|' | '<' | '>' | '`' | '$' | '(' | ')' | '{' | '}' | '\n' | '\r'
637 )
638 })
639 }
640
641 /// Commands whose first word runs something else the grant cannot see.
642 fn shell_command_is_wrapper(tokens: &[&str]) -> bool {
643 const WRAPPERS: &[&str] = &[
644 "bash",
645 "sh",
646 "zsh",
647 "dash",
648 "ksh",
649 "fish",
650 "csh",
651 "tcsh",
652 "env",
653 "sudo",
654 "doas",
655 "su",
656 "xargs",
657 "nohup",
658 "time",
659 "timeout",
660 "nice",
661 "ionice",
662 "exec",
663 "eval",
664 "command",
665 "builtin",
666 "stdbuf",
667 "script",
668 "watch",
669 "parallel",
670 "chroot",
671 "nsenter",
672 "unshare",
673 "setsid",
674 "caffeinate",
675 "strace",
676 "ltrace",
677 "gdb",
678 "lldb",
679 "osascript",
680 "pwsh",
681 "powershell",
682 "cmd",
683 "npx",
684 "pnpx",
685 "bunx",
686 "uvx",
687 "node",
688 "perl",
689 "ruby",
690 "php",
691 "python",
692 "python2",
693 "python3",
694 "find",
695 "ssh",
696 ];
697 const RUNNERS: &[&str] = &[
698 "docker run",
699 "docker exec",
700 "kubectl exec",
701 "npm exec",
702 "pnpm exec",
703 "pnpm dlx",
704 "yarn dlx",
705 "uv run",
706 "poetry run",
707 ];
708 let first = tokens[0];
709 // `FOO=1 cmd`: an environment assignment can change what `cmd` does.
710 if first.contains('=') {
711 return true;
712 }
713 let program = first.rsplit('/').next().unwrap_or(first);
714 if WRAPPERS.contains(&program) {
715 return true;
716 }
717 let lead = tokens
718 .iter()
719 .take(2)
720 .map(|token| token.rsplit('/').next().unwrap_or(token))
721 .collect::<Vec<_>>()
722 .join(" ");
723 RUNNERS.contains(&lead.as_str())
724 }
725
726 /// Collapse insignificant whitespace. Quoted text keeps its exact spacing:
727 /// `echo "a b"` and `echo "a b"` are different commands.
728 fn normalize_shell_command(cmd: &str) -> String {
729 if cmd.contains(['"', '\'', '\\']) {
730 cmd.trim().to_string()
731 } else {
732 cmd.split_whitespace().collect::<Vec<_>>().join(" ")
733 }
734 }
735
736 /// Hash the sorted set of file paths referenced by a patch input.
737 ///
738 /// The paths come from [`preflight_apply_patch`] — the same resolver the
739 /// executor, the permission path (`core/engine.rs`) and auto-review already
740 /// use — rather than from a second, weaker parser. That matters because this
741 /// string *is* the scope of an "approve for the session" grant: two patches
742 /// share a grant exactly when they share this key.
743 ///
744 /// The previous implementation read only `+++ b/` headers and the
745 /// `replace`/`changes` array, so it saw no paths at all for the documented
746 /// `apply_patch{path, patch}` override, for `--no-prefix` diffs, or for
747 /// delete-only diffs — and collapsed all of them to one shared constant.
748 /// Approving any one of those pre-approved every later one, to any file
749 /// (#6247).
750 ///
751 /// An input the resolver cannot parse gets a digest of the input itself, not
752 /// a shared constant: an unparseable patch is its own family and matches
753 /// nothing but a byte-identical repeat.
754 fn hash_patch_paths(input: &serde_json::Value) -> String {
755 use std::collections::hash_map::DefaultHasher;
756 use std::hash::{Hash, Hasher};
757
758 let Ok(preflight) = codewhale_tools::patch_preflight::preflight_apply_patch(input) else {
759 return format!("unparsed_{}", hash_json_value(input));
760 };
761
762 let mut paths: Vec<&str> = preflight.touched_files.iter().map(String::as_str).collect();
763
764 paths.sort_unstable();
765 paths.dedup();
766
767 if paths.is_empty() {
768 // The resolver parsed the input but found no target. Fail closed for
769 // the same reason as the error arm above: a shared key here is a
770 // shared grant.
771 return format!("no_target_{}", hash_json_value(input));
772 }
773
774 let mut hasher = DefaultHasher::new();
775 for path in &paths {
776 path.hash(&mut hasher);
777 }
778 format!("{:x}", hasher.finish())
779 }
780
781 /// Parse the host portion from a URL input.
782 fn parse_host(input: &serde_json::Value) -> String {
783 let url = input.get("url").and_then(|v| v.as_str()).unwrap_or("");
784
785 if let Ok(parsed) = reqwest::Url::parse(url) {
786 parsed.host_str().unwrap_or(url).to_string()
787 } else {
788 url.to_string()
789 }
790 }
791
792 fn hash_json_value(value: &Value) -> String {
793 let mut canonical = String::new();
794 push_canonical_json(value, &mut canonical);
795
796 let digest = Sha256::digest(canonical.as_bytes());
797 let mut short = String::with_capacity(16);
798 for byte in &digest[..8] {
799 write!(&mut short, "{byte:02x}").expect("writing to String cannot fail");
800 }
801 short
802 }
803
804 /// Maximum nesting depth the canonical serializer descends. Aligned with
805 /// serde_json's own parse limit so parsed input never truncates; anything
806 /// deeper emits a fixed marker, keeping keys deterministic.
807 const MAX_CANONICAL_JSON_DEPTH: usize = 128;
808
809 fn push_canonical_json(value: &Value, out: &mut String) {
810 push_canonical_json_at(value, out, 0)
811 }
812
813 fn push_canonical_json_at(value: &Value, out: &mut String, depth: usize) {
814 if depth > MAX_CANONICAL_JSON_DEPTH {
815 out.push_str("maxdepth");
816 return;
817 }
818 match value {
819 Value::Null => out.push_str("null"),
820 Value::Bool(value) => {
821 out.push_str("bool:");
822 out.push_str(if *value { "true" } else { "false" });
823 }
824 Value::Number(value) => {
825 out.push_str("number:");
826 // Avoid allocating via value.to_string().
827 if let Some(n) = value.as_f64() {
828 let _ = write!(out, "{n}");
829 } else if let Some(n) = value.as_i64() {
830 let _ = write!(out, "{n}");
831 } else if let Some(n) = value.as_u64() {
832 let _ = write!(out, "{n}");
833 } else {
834 out.push_str(&value.to_string());
835 }
836 }
837 Value::String(value) => {
838 out.push_str("string:");
839 // Emit JSON-encoded string without an intermediate allocation.
840 out.push('"');
841 for ch in value.chars() {
842 match ch {
843 '"' => out.push_str("\\\""),
844 '\\' => out.push_str("\\\\"),
845 '\n' => out.push_str("\\n"),
846 '\r' => out.push_str("\\r"),
847 '\t' => out.push_str("\\t"),
848 c if c.is_control() => {
849 let _ = write!(out, "\\u{:04x}", c as u32);
850 }
851 c => out.push(c),
852 }
853 }
854 out.push('"');
855 }
856 Value::Array(items) => {
857 out.push('[');
858 for (index, item) in items.iter().enumerate() {
859 if index > 0 {
860 out.push(',');
861 }
862 push_canonical_json_at(item, out, depth + 1);
863 }
864 out.push(']');
865 }
866 Value::Object(map) => {
867 let mut entries = map.iter().collect::<Vec<_>>();
868 entries.sort_by_key(|(key, _)| *key);
869
870 out.push('{');
871 for (index, (key, value)) in entries.into_iter().enumerate() {
872 if index > 0 {
873 out.push(',');
874 }
875 let encoded_key =
876 serde_json::to_string(key).expect("serializing an object key cannot fail");
877 out.push_str(&encoded_key);
878 out.push(':');
879 push_canonical_json_at(value, out, depth + 1);
880 }
881 out.push('}');
882 }
883 }
884 }
885
886 #[cfg(test)]
887 mod tests {
888 use super::*;
889 use serde_json::json;
890
891 #[test]
892 fn different_commands_different_keys() {
893 let key_a = build_approval_key("exec_shell", &json!({"command": "ls"}));
894 let key_b = build_approval_key("exec_shell", &json!({"command": "rm -rf /tmp"}));
895 assert_ne!(key_a, key_b);
896 }
897
898 #[test]
899 fn same_command_same_key() {
900 let key_a = build_approval_key("exec_shell", &json!({"command": "cargo build --release"}));
901 let key_b = build_approval_key("exec_shell", &json!({"command": "cargo build --release"}));
902 assert_eq!(key_a, key_b);
903 }
904
905 #[test]
906 fn pathological_nesting_yields_a_stable_key() {
907 let mut value = Value::String("leaf".to_string());
908 for _ in 0..150 {
909 let mut map = serde_json::Map::new();
910 map.insert("t".to_string(), value);
911 value = Value::Object(map);
912 }
913 let key_a = build_approval_key("exec_shell", &value);
914 let key_b = build_approval_key("exec_shell", &value);
915 assert_eq!(key_a, key_b, "truncated keys must stay deterministic");
916 }
917
918 #[test]
919 fn shell_keys_include_full_command_arguments() {
920 let key_a = build_approval_key("exec_shell", &json!({"command": "cargo build"}));
921 let key_b = build_approval_key("exec_shell", &json!({"command": "cargo build --release"}));
922 assert_ne!(key_a, key_b);
923 }
924
925 #[test]
926 fn grouping_key_collapses_shell_flag_variants() {
927 let key_a = build_approval_grouping_key("exec_shell", &json!({"command": "cargo build"}));
928 let key_b =
929 build_approval_grouping_key("exec_shell", &json!({"command": "cargo build --release"}));
930 assert_eq!(
931 key_a, key_b,
932 "approving a command family must cover later flag variants"
933 );
934 }
935
936 #[test]
937 fn shell_grants_fail_closed_on_compound_wrapper_and_unknown_commands() {
938 let key = |cmd: &str| build_approval_grouping_key("exec_shell", &json!({"command": cmd}));
939 // Compound: a grant for `cd` never covers what is chained after it.
940 assert_ne!(key("cd src"), key("cd src && make clean"));
941 assert_ne!(key("cargo build"), key("cargo build; make install"));
942 assert_ne!(key("cargo build"), key("cargo build > out.log"));
943 assert_ne!(key("git status"), key("git status $(pwd)"));
944 // Wrappers and interpreters are keyed by the whole command.
945 assert_ne!(key("bash build.sh"), key("bash -c 'make clean'"));
946 assert_ne!(key("python3 script.py"), key("python3 -c 'import os'"));
947 assert_ne!(key("env FOO=1 make"), key("env FOO=1 make clean"));
948 assert_ne!(key("FOO=1 make"), key("FOO=1 make install"));
949 assert_ne!(
950 key("docker run alpine ls"),
951 key("docker run alpine touch x")
952 );
953 assert_ne!(key("/usr/bin/sudo ls"), key("/usr/bin/sudo make install"));
954 // Unknown commands no longer collapse to their first word.
955 assert_ne!(key("rm tmp/x"), key("rm -r build"));
956 assert_ne!(key("cat README.md"), key("cat notes/other.txt"));
957 // The full-command key still matches an exact repeat, modulo
958 // insignificant whitespace, but not a quoted-spacing change.
959 assert_eq!(key("cd src && make"), key(" cd src && make "));
960 assert_ne!(key("echo \"a b\""), key("echo \"a b\""));
961 assert!(key("rm -r build").0.starts_with("shell:cmd:"));
962 // Options and config arguments that can run code key the full
963 // command, though the family ignores flags.
964 assert_ne!(key("git status"), key("git -ccore.fsmonitor=./hook status"));
965 assert_ne!(key("git status"), key("git -C ../other status"));
966 assert_ne!(
967 key("cargo build"),
968 key("cargo build --config build.rustc-wrapper=./x")
969 );
970 assert_ne!(key("git diff"), key("git diff --output=out.patch"));
971 assert_ne!(key("make"), key("make -f /tmp/x"));
972 assert_ne!(
973 key("git config user.name x"),
974 key("git config core.fsmonitor ./x.sh")
975 );
976 // A known, simple command keeps its family grant.
977 assert_eq!(key("git status"), key("git status --porcelain"));
978 assert_ne!(key("git status"), key("git push"));
979 }
980
981 #[test]
982 fn shell_family_grants_survive_only_inert_options() {
983 let key = |cmd: &str| build_approval_grouping_key("exec_shell", &json!({"command": cmd}));
984 // Options with an attached or separate value, and single-dash long
985 // options, key the full command.
986 for (granted, other) in [
987 ("git status", "git -C../other status"),
988 ("make", "make -f/tmp/x"),
989 ("git diff", "git diff --output out.patch"),
990 ("git rebase HEAD~1", "git rebase -x \"touch x\" HEAD~1"),
991 ("go test ./...", "go test -exec ./x ./..."),
992 ("go build ./...", "go build -toolexec ./x ./..."),
993 ("git clone ./repo", "git clone -u \"cmd\" ./repo"),
994 ("git grep pat", "git grep -Ocmd pat"),
995 ("git log", "git log --git-dir x"),
996 ("cargo test", "cargo test -- --nocapture"),
997 ] {
998 assert_ne!(key(granted), key(other), "{other}");
999 assert!(key(other).0.starts_with("shell:cmd:"), "{other}");
1000 }
1001 // Every option once listed as able to run code still keys the full
1002 // command.
1003 for option in [
1004 "-c",
1005 "-C",
1006 "--config",
1007 "--exec",
1008 "--exec-path",
1009 "--script-shell",
1010 "-f",
1011 "--file",
1012 "--makefile",
1013 "-e",
1014 "--eval",
1015 "--require",
1016 "--upload-pack",
1017 "--receive-pack",
1018 "--manifest-path",
1019 ] {
1020 assert!(!INERT_OPTIONS.contains(&option), "{option}");
1021 }
1022 // Families whose arguments are the code that runs or is installed
1023 // key the full command.
1024 for (granted, other) in [
1025 ("go run ./cmd/tool", "go run /tmp/other.go"),
1026 ("deno run main.ts", "deno run https://host/x.ts"),
1027 ("cargo run", "cargo run --bin other"),
1028 ("git bisect start", "git bisect run ./x"),
1029 ("git submodule update", "git submodule foreach ./x"),
1030 ("make build", "make clean"),
1031 ("npm install", "npm install left-pad"),
1032 ("pip install requests", "pip install other"),
1033 ("cargo install ripgrep", "cargo install other"),
1034 ] {
1035 assert_ne!(key(granted), key(other), "{other}");
1036 }
1037 // Inert options keep the family grant.
1038 assert_eq!(key("cargo build"), key("cargo build --release --locked"));
1039 assert_eq!(key("git status"), key("git status -s"));
1040 assert_eq!(key("git diff"), key("git diff --stat --cached"));
1041 }
1042
1043 #[test]
1044 fn shell_interact_grants_are_per_exact_call() {
1045 for tool in [
1046 "exec_shell_interact",
1047 "exec_interact",
1048 "exec_shell_wait",
1049 "exec_wait",
1050 ] {
1051 let a = build_approval_grouping_key(tool, &json!({"task_id": "t1", "input": "y\n"}));
1052 let b = build_approval_grouping_key(tool, &json!({"task_id": "t1", "input": "n\n"}));
1053 let c = build_approval_grouping_key(tool, &json!({"task_id": "t2", "input": "y\n"}));
1054 assert_ne!(a, b, "{tool}: different input must not share a grant");
1055 assert_ne!(a, c, "{tool}: a different session must not share a grant");
1056 assert_eq!(
1057 a,
1058 build_approval_grouping_key(tool, &json!({"task_id": "t1", "input": "y\n"}))
1059 );
1060 }
1061 }
1062
1063 #[test]
1064 fn shell_run_grant_does_not_cover_a_different_stdin() {
1065 for tool in ["Bash", "bash", "exec_shell", "task_shell_start"] {
1066 let plain = json!({"command": "python3 -"});
1067 let hello = json!({"command": "python3 -", "stdin": "print(1)"});
1068 let other = json!({"command": "python3 -", "stdin": "print(2)"});
1069 let granted = build_approval_grouping_key(tool, &plain);
1070 let with_stdin = build_approval_grouping_key(tool, &hello);
1071 assert_ne!(granted, with_stdin, "{tool}: stdin is part of what runs");
1072 assert_ne!(
1073 with_stdin,
1074 build_approval_grouping_key(tool, &other),
1075 "{tool}: different stdin must not share a grant"
1076 );
1077 assert_eq!(
1078 with_stdin,
1079 build_approval_grouping_key(tool, &hello),
1080 "{tool}: the same call keeps its grant"
1081 );
1082 for alias in ["input", "data"] {
1083 let aliased = json!({"command": "python3 -", alias: "print(2)"});
1084 assert_ne!(
1085 granted,
1086 build_approval_grouping_key(tool, &aliased),
1087 "{tool}: `{alias}` carries stdin too"
1088 );
1089 assert_ne!(
1090 with_stdin,
1091 build_approval_grouping_key(tool, &aliased),
1092 "{tool}: `{alias}` input is not the `stdin` input of another call"
1093 );
1094 }
1095 assert_eq!(
1096 granted,
1097 build_approval_grouping_key(tool, &json!({"command": "python3 -", "stdin": null})),
1098 "{tool}: a null stdin is no stdin"
1099 );
1100 }
1101 let family_plain = build_approval_grouping_key("Bash", &json!({"command": "git status"}));
1102 let family_stdin =
1103 build_approval_grouping_key("Bash", &json!({"command": "git status", "stdin": "x"}));
1104 assert_ne!(family_plain, family_stdin);
1105 }
1106
1107 #[test]
1108 fn grouping_key_grants_mcp_tools_as_reviewed_kinds() {
1109 // A session grant for a reviewed plugin MCP tool is the kind
1110 // (`mcp:<tool>`), not the exact arguments: the plugin e2e acceptance
1111 // approves the echo kind once and later variants of the same reviewed
1112 // tool must not re-prompt. R2's shell command-family scoping is
1113 // untouched — this is the MCP arm only.
1114 let key_a = build_approval_grouping_key(
1115 "mcp_plugin-4-demo-local_echo",
1116 &json!({"text": "acceptance", "hang": false}),
1117 );
1118 let key_b = build_approval_grouping_key(
1119 "mcp_plugin-4-demo-local_echo",
1120 &json!({"text": "acceptance", "hang": true}),
1121 );
1122 assert_eq!(
1123 key_a, key_b,
1124 "a reviewed MCP kind grant covers argument variants of that tool"
1125 );
1126 let key_c = build_approval_grouping_key("mcp_plugin-4-demo-local_kick", &json!({"x": 1}));
1127 assert_ne!(key_a, key_c, "a different MCP tool is a different kind");
1128 // The exact-call key stays per-arguments so denials still suppress
1129 // only exact retries.
1130 let exact_a = build_approval_key(
1131 "mcp_plugin-4-demo-local_echo",
1132 &json!({"text": "acceptance", "hang": false}),
1133 );
1134 let exact_b = build_approval_key(
1135 "mcp_plugin-4-demo-local_echo",
1136 &json!({"text": "acceptance", "hang": true}),
1137 );
1138 assert_ne!(exact_a, exact_b, "denial keys remain argument-exact");
1139 }
1140
1141 /// K1: one session grant for Computer Use consent must not cover a
1142 /// consent request for a different app, a different scope, or a
1143 /// persisted (`remember`) variant — the MCP kind grant is not used here.
1144 #[test]
1145 fn computer_use_consent_grants_are_per_exact_call_not_per_kind() {
1146 let tool = "mcp_plugin-12-computer-use-computer_consent";
1147 let safari = build_approval_grouping_key(
1148 tool,
1149 &json!({"action": "allow", "app": "Safari", "bundle_id": "com.apple.Safari"}),
1150 );
1151 let terminal = build_approval_grouping_key(
1152 tool,
1153 &json!({"action": "allow", "app": "Terminal", "bundle_id": "com.apple.Terminal"}),
1154 );
1155 let foreground =
1156 build_approval_grouping_key(tool, &json!({"action": "allow", "scope": "foreground"}));
1157 let persisted = build_approval_grouping_key(
1158 tool,
1159 &json!({"action": "allow", "app": "Safari", "bundle_id": "com.apple.Safari", "remember": true}),
1160 );
1161 assert_ne!(safari, terminal, "allowing app X must never allow app Y");
1162 assert_ne!(safari, foreground);
1163 assert_ne!(safari, persisted);
1164 assert!(safari.0.starts_with("cu:"), "{safari:?}");
1165 for name in [
1166 "mcp_codewhale-cu_consent_allow",
1167 "mcp_codewhale-cu_consent_revoke",
1168 ] {
1169 let a = build_approval_grouping_key(name, &json!({"app": "Safari"}));
1170 let b = build_approval_grouping_key(name, &json!({"app": "Terminal"}));
1171 assert_ne!(a, b, "{name}");
1172 }
1173 // Reads and self-narrowing decisions keep the ordinary kind grant.
1174 assert_eq!(
1175 build_approval_grouping_key(tool, &json!({"action": "status"})).0,
1176 format!("mcp:{tool}")
1177 );
1178 assert!(
1179 computer_use_user_gate(tool, &json!({"action": "deny", "app": "Safari"})).is_none()
1180 );
1181 assert!(computer_use_user_gate("mcp_codewhale-cu_consent_status", &json!({})).is_none());
1182 assert!(computer_use_user_gate("consent_allow", &json!({"app": "Safari"})).is_none());
1183 }
1184
1185 /// K2: an `app_script` session grant is the exact script; a changed
1186 /// script is a new approval.
1187 #[test]
1188 fn app_script_grants_are_per_exact_script() {
1189 let tool = "mcp_plugin-12-computer-use-computer_app_script";
1190 let a = build_approval_grouping_key(
1191 tool,
1192 &json!({"script": "tell application \"Finder\" to get name of front window"}),
1193 );
1194 let same = build_approval_grouping_key(
1195 tool,
1196 &json!({"script": "tell application \"Finder\" to get name of front window"}),
1197 );
1198 let changed =
1199 build_approval_grouping_key(tool, &json!({"script": "do shell script \"id\""}));
1200 assert_eq!(a, same);
1201 assert_ne!(a, changed, "a changed script must prompt again");
1202 let Some(ComputerUseUserGate::AppScript {
1203 language,
1204 script_sha256,
1205 first_line,
1206 line_count,
1207 }) = computer_use_user_gate(
1208 tool,
1209 &json!({"script": "\n ObjC.import('Foundation')\nrest", "language": "javascript"}),
1210 )
1211 else {
1212 panic!("app_script must be gated");
1213 };
1214 assert_eq!(language, "JXA");
1215 assert_eq!(script_sha256.len(), 64);
1216 assert_eq!(first_line, "ObjC.import('Foundation')");
1217 assert_eq!(line_count, 2);
1218 }
1219
1220 #[test]
1221 fn grouping_key_still_separates_distinct_commands() {
1222 let key_a = build_approval_grouping_key("exec_shell", &json!({"command": "git status"}));
1223 let key_b = build_approval_grouping_key("exec_shell", &json!({"command": "git push"}));
1224 assert_ne!(key_a, key_b);
1225 }
1226
1227 #[test]
1228 fn grouping_key_does_not_cover_interposed_options_chains_or_nested_code() {
1229 let key =
1230 |command: &str| build_approval_grouping_key("exec_shell", &json!({"command": command}));
1231 let granted = key("git status");
1232 assert_eq!(granted, key("git status -s"));
1233 for command in [
1234 "git --git-dir=/tmp/e/.git status",
1235 "git --exec-path=/x status",
1236 "git status $(touch p)",
1237 "git status && rm x",
1238 ] {
1239 assert_ne!(granted, key(command), "{command}");
1240 }
1241 // Such a command still matches an identical repeat, and only that.
1242 assert_eq!(key("git status && ls"), key("git status && ls"));
1243 assert_ne!(key("git status && ls"), key("git status && pwd"));
1244 }
1245
1246 /// #6247. The `path` override is the documented way to patch without
1247 /// diff headers (`apply_patch.rs` tells the model "Ensure the patch
1248 /// includes ---/+++ headers or provide `path`"), and a bare hunk has no
1249 /// `+++` line at all. Before the fix both of these produced the constant
1250 /// `patch:no_files`, so one session grant covered every later one.
1251 #[test]
1252 fn grouping_key_scopes_a_path_override_to_its_own_file() {
1253 let hunk = "@@ -1 +1 @@\n-old\n+new\n";
1254 let benign = build_approval_grouping_key(
1255 "apply_patch",
1256 &json!({"path": ".env.example", "patch": hunk}),
1257 );
1258 let sensitive = build_approval_grouping_key(
1259 "apply_patch",
1260 &json!({"path": ".codewhale/settings.json", "patch": hunk}),
1261 );
1262 assert_ne!(
1263 benign, sensitive,
1264 "approving a patch to one file must never cover a patch to another"
1265 );
1266 assert!(
1267 !format!("{benign:?}").contains("no_files"),
1268 "a resolvable target must never collapse to the shared constant"
1269 );
1270 }
1271
1272 /// The executor's `normalize_diff_path` accepts a prefix-less header, so
1273 /// the fingerprint must too — otherwise a `--no-prefix` diff is a second
1274 /// route to the shared key.
1275 #[test]
1276 fn grouping_key_reads_prefix_less_diff_headers() {
1277 let prefixed = build_approval_grouping_key(
1278 "apply_patch",
1279 &json!({"patch": "--- a/src/auth.rs\n+++ b/src/auth.rs\n@@ -1 +1 @@\n-a\n+b\n"}),
1280 );
1281 let bare = build_approval_grouping_key(
1282 "apply_patch",
1283 &json!({"patch": "--- src/auth.rs\n+++ src/auth.rs\n@@ -1 +1 @@\n-a\n+b\n"}),
1284 );
1285 assert_eq!(
1286 prefixed, bare,
1287 "the same target written two legal ways is one approval family"
1288 );
1289 let other = build_approval_grouping_key(
1290 "apply_patch",
1291 &json!({"patch": "--- src/billing.rs\n+++ src/billing.rs\n@@ -1 +1 @@\n-a\n+b\n"}),
1292 );
1293 assert_ne!(bare, other, "different targets are different families");
1294 }
1295
1296 /// Fail closed: an input the resolver cannot parse is its own family, not
1297 /// a member of a shared one. Two different unparseable inputs must not
1298 /// share a grant.
1299 #[test]
1300 fn grouping_key_fails_closed_on_an_unresolvable_patch() {
1301 let a = build_approval_grouping_key("apply_patch", &json!({"patch": "not a diff at all"}));
1302 let b = build_approval_grouping_key("apply_patch", &json!({"patch": "also not a diff"}));
1303 assert_ne!(a, b, "unparseable inputs must not share an approval family");
1304 for key in [&a, &b] {
1305 let rendered = format!("{key:?}");
1306 assert!(
1307 !rendered.contains("no_files"),
1308 "the shared constant must not survive anywhere: {rendered}"
1309 );
1310 }
1311 }
1312
1313 #[test]
1314 fn grouping_key_collapses_patch_body_for_same_path() {
1315 let key_a = build_approval_grouping_key(
1316 "apply_patch",
1317 &json!({"replace": [{"path": "a.rs", "content": "x"}]}),
1318 );
1319 let key_b = build_approval_grouping_key(
1320 "apply_patch",
1321 &json!({"replace": [{"path": "a.rs", "content": "y"}]}),
1322 );
1323 assert_eq!(
1324 key_a, key_b,
1325 "approving a patch family must cover later edits to the same path"
1326 );
1327 }
1328
1329 #[test]
1330 fn grouping_key_treats_replace_and_legacy_changes_as_the_same_path_set() {
1331 let canonical = build_approval_grouping_key(
1332 "apply_patch",
1333 &json!({"replace": [{"path": "a.rs", "content": "new"}]}),
1334 );
1335 let legacy = build_approval_grouping_key(
1336 "apply_patch",
1337 &json!({"changes": [{"path": "a.rs", "content": "new"}]}),
1338 );
1339
1340 assert_eq!(canonical, legacy);
1341 }
1342
1343 #[test]
1344 fn denial_key_stays_exact_while_grouping_key_collapses() {
1345 let exact_a = build_approval_key("exec_shell", &json!({"command": "cargo build"}));
1346 let exact_b =
1347 build_approval_key("exec_shell", &json!({"command": "cargo build --release"}));
1348 assert_ne!(exact_a, exact_b, "denials must remain exact-call scoped");
1349
1350 let group_a = build_approval_grouping_key("exec_shell", &json!({"command": "cargo build"}));
1351 let group_b =
1352 build_approval_grouping_key("exec_shell", &json!({"command": "cargo build --release"}));
1353 assert_eq!(group_a, group_b, "approvals must group by command family");
1354 }
1355
1356 #[test]
1357 fn patch_keys_differ_by_path() {
1358 let key_a = build_approval_key(
1359 "apply_patch",
1360 &json!({"replace": [{"path": "a.rs", "content": "x"}]}),
1361 );
1362 let key_b = build_approval_key(
1363 "apply_patch",
1364 &json!({"replace": [{"path": "b.rs", "content": "x"}]}),
1365 );
1366 assert_ne!(key_a, key_b);
1367 }
1368
1369 #[test]
1370 fn patch_keys_differ_by_body_for_same_path() {
1371 let key_a = build_approval_key(
1372 "apply_patch",
1373 &json!({"replace": [{"path": "a.rs", "content": "x"}]}),
1374 );
1375 let key_b = build_approval_key(
1376 "apply_patch",
1377 &json!({"replace": [{"path": "a.rs", "content": "y"}]}),
1378 );
1379 assert_ne!(key_a, key_b);
1380 }
1381
1382 #[test]
1383 fn net_keys_differ_by_host() {
1384 let key_a = build_approval_key("fetch_url", &json!({"url": "https://example.com"}));
1385 let key_b = build_approval_key("fetch_url", &json!({"url": "https://other.org"}));
1386 assert_ne!(key_a, key_b);
1387 }
1388
1389 #[test]
1390 fn generic_tool_keys_include_arguments() {
1391 let key_a = build_approval_key("read_file", &json!({"path": "a.txt"}));
1392 let key_b = build_approval_key("read_file", &json!({"path": "b.txt"}));
1393 assert_ne!(key_a, key_b);
1394 assert!(key_a.0.starts_with("tool:read_file:"));
1395 }
1396
1397 #[test]
1398 fn generic_tool_same_arguments_reuse_key() {
1399 let input = json!({"path": "a.txt"});
1400 let key_a = build_approval_key("edit_file", &input);
1401 let key_b = build_approval_key("edit_file", &input);
1402 assert_eq!(key_a, key_b);
1403 }
1404
1405 #[test]
1406 fn input_hash_is_stable_across_object_key_order() {
1407 let key_a = build_approval_key("write_file", &json!({"path": "a.txt", "content": "x"}));
1408 let key_b = build_approval_key("write_file", &json!({"content": "x", "path": "a.txt"}));
1409 assert_eq!(key_a, key_b);
1410 }
1411
1412 #[test]
1413 fn lowercase_primitives_share_legacy_approval_keys() {
1414 let shell = json!({"command": "cargo test"});
1415 assert_eq!(
1416 build_approval_key("bash", &shell),
1417 build_approval_key("exec_shell", &shell)
1418 );
1419 let write = json!({"path": "a.txt", "content": "x"});
1420 assert_eq!(
1421 build_approval_key("write", &write),
1422 build_approval_key("write_file", &write)
1423 );
1424 let edit = json!({
1425 "path": "a.txt",
1426 "edits": [{"oldText": "x", "newText": "y"}]
1427 });
1428 assert_eq!(
1429 build_approval_key("edit", &edit),
1430 build_approval_key("edit_file", &edit)
1431 );
1432 }
1433
1434 #[test]
1435 fn canonical_json_omits_trailing_commas() {
1436 let mut canonical = String::new();
1437 push_canonical_json(&json!({"b": [true, false], "a": {"x": 1}}), &mut canonical);
1438
1439 assert_eq!(
1440 canonical,
1441 r#"{"a":{"x":number:1},"b":[bool:true,bool:false]}"#
1442 );
1443 assert!(!canonical.contains(",]"));
1444 assert!(!canonical.contains(",}"));
1445 }
1446
1447 #[test]
1448 fn web_run_session_grant_covers_its_argument_class_only() {
1449 let search = |q: &str| json!({"search_query": [{"q": q}]});
1450 assert_eq!(
1451 build_approval_grouping_key("web.run", &search("espresso")),
1452 build_approval_grouping_key("web.run", &search("grinders")),
1453 "approving one search covers later searches"
1454 );
1455 assert_ne!(
1456 build_approval_grouping_key("web.run", &search("espresso")),
1457 build_approval_grouping_key(
1458 "web.run",
1459 &json!({"open": [{"ref_id": "https://x.test"}]})
1460 ),
1461 "a search grant never covers opening a page"
1462 );
1463 let open = |url: &str| json!({"open": [{"ref_id": url}]});
1464 assert_eq!(
1465 build_approval_grouping_key("web.run", &open("https://docs.rs/a")),
1466 build_approval_grouping_key("web.run", &open("https://DOCS.rs/b?x=1")),
1467 "an open grant covers later pages on the approved host"
1468 );
1469 assert_ne!(
1470 build_approval_grouping_key("web.run", &open("https://docs.rs/a")),
1471 build_approval_grouping_key("web.run", &open("https://evil.test/?q=secret")),
1472 "an open grant never covers another host"
1473 );
1474 assert_ne!(
1475 build_approval_grouping_key("web.run", &open("turn0search0")),
1476 build_approval_grouping_key("web.run", &open("https://evil.test/")),
1477 "a result-reference open grant never covers a raw URL"
1478 );
1479 assert_ne!(
1480 build_approval_key("web.run", &search("espresso")),
1481 build_approval_key("web.run", &search("grinders")),
1482 "denials stay exact-call scoped"
1483 );
1484 }
1485 #[test]
1486 fn computer_register_and_spawn_need_a_human_card() {
1487 for (tool, input) in [
1488 (
1489 "mcp_codewhale-cu_computer_register",
1490 json!({"computer": "box", "transport": "ssh", "host": "box.example", "user": "me", "port": 2222}),
1491 ),
1492 (
1493 "mcp_codewhale-cu_computer",
1494 json!({"action": "register", "id": "box", "transport": "ssh", "host": "box.example"}),
1495 ),
1496 (
1497 "mcp_codewhale-cu_computer_spawn",
1498 json!({"image": "desktop"}),
1499 ),
1500 (
1501 "mcp_codewhale-cu_computer",
1502 json!({"action": "spawn", "id": "d"}),
1503 ),
1504 ] {
1505 assert!(
1506 matches!(
1507 computer_use_user_gate(tool, &input),
1508 Some(ComputerUseUserGate::Computer { .. })
1509 ),
1510 "{tool} {input}"
1511 );
1512 }
1513 assert_eq!(
1514 computer_use_user_gate(
1515 "mcp_codewhale-cu_computer_register",
1516 &json!({"transport": "ssh", "host": "box.example", "user": "me", "port": 2222}),
1517 ),
1518 Some(ComputerUseUserGate::Computer {
1519 action: "register",
1520 transport: Some("ssh".to_string()),
1521 destination: Some("me@box.example:2222".to_string()),
1522 })
1523 );
1524 for (tool, input) in [
1525 ("mcp_codewhale-cu_computer", json!({"action": "list"})),
1526 (
1527 "mcp_codewhale-cu_computer",
1528 json!({"action": "switch", "id": "box"}),
1529 ),
1530 (
1531 "mcp_codewhale-cu_computer_switch",
1532 json!({"computer": "box"}),
1533 ),
1534 ] {
1535 assert_eq!(computer_use_user_gate(tool, &input), None, "{tool}");
1536 }
1537 assert_eq!(
1538 computer_use_batch_hidden_gate(
1539 "mcp_codewhale-cu_run_actions",
1540 &json!({"steps": [{"tool": "codewhale-cu_computer_register", "arguments": {"host": "x"}}]}),
1541 )
1542 .as_deref(),
1543 Some("codewhale-cu_computer_register")
1544 );
1545 }
1546 }
1547
1547 lines RUST