返回 CodeWhale
execution_envelope.rs
根目录 / crates / engine / src / tools / execution_envelope.rs
1 //! The one place that decides whether a delegated child may make a call that
2 //! **executes**, **mutates**, or **reaches the network**.
3 //!
4 //! Before this module the answer was spread across three hand-maintained name
5 //! lists ([`codewhale_agent_contract::role::RAW_SHELL_DENYLIST`] and its siblings) plus a
6 //! role posture that keyed on `ShellPolicy::Full`. That shape had a structural
7 //! hole: a name list can only deny the execution primitives someone remembered
8 //! to write down, and `shell = "full"` was being read as "may run arbitrary
9 //! code" by every tool whose approval requirement is `Required`. So a member
10 //! saved as read-only-with-checks (`write = false`, `shell = "full"` — the
11 //! `tester`/`verifier` preset, and any `custom` member shaped like it) lost
12 //! `Bash` and kept:
13 //!
14 //! - `tasks{action:"gate_run"}` — runs an operator-supplied command line;
15 //! - `automation{action:"run"}` / `{action:"create"}` — executes or schedules a
16 //! stored automation, with its own cwd and prompt;
17 //! - `start_mcp_server` — spawns a process and opens a socket;
18 //! - every repository plugin tool, which is a shell command by definition;
19 //!
20 //! each of which mutates the workspace and reaches the network exactly as well
21 //! as the shell that was just removed, while the receipt said `write=false`.
22 //!
23 //! ## What is enforced
24 //!
25 //! The classification is derived, never listed: it comes from the tool's own
26 //! [`ToolCapability`] set and from `is_read_only_for` applied to the **actual
27 //! input**, after [`canonical_action_alias`] has resolved the family/action
28 //! pair. That is what makes it cover tools this file has never heard of —
29 //! plugins, runtime MCP servers, and anything registered later.
30 //!
31 //! | call classification | requires |
32 //! |---|---|
33 //! | read-only for this input | nothing |
34 //! | built-in verification (default or test-selection) | shell authority |
35 //! | `ExecutesCode` | write **and** shell authority |
36 //! | `WritesFiles` | write authority |
37 //! | `Network` | network authority |
38 //!
39 //! `ExecutesCode` requires *write* authority because an arbitrary program is an
40 //! arbitrary mutation primitive; requiring shell authority as well keeps the
41 //! existing posture rule from being weakened. Two carve-outs are deliberate and
42 //! are the "bounded positives" this module must not break:
43 //!
44 //! - **`agent`** declares `ExecutesCode` (it runs a child model loop), but
45 //! delegation is governed by the depth budget and by the fact that the child
46 //! inherits this same envelope. Denying it here would stop a read-only member
47 //! from fanning out read-only work, which is a capability, not an escape.
48 //! - **Bounded verification** — `run_tests` / `run_verifiers` / `Run` — is the
49 //! whole purpose of a read-only verifier, and the shipped `verifier` role is
50 //! exactly `write = false, shell = "full"`. Classifying it by tool name would
51 //! either take the role's job away or hand it a program launcher, so the
52 //! bound is read off the concrete call by [`classify_verification`]:
53 //! argument-free and pure test *selection* both cost shell authority (each
54 //! forks a process, which `analyst`/`scout` were never granted), and
55 //! anything that can name a program is held to the raw-shell bar. Every
56 //! consumer of that contract — the catalog filter, the dispatch guard, and
57 //! `reject_unbounded_verification` in [`crate::tools::subagent`] — reads this
58 //! one classifier rather than re-deriving it.
59
60 use serde_json::Value;
61
62 use crate::tools::spec::{ApprovalRequirement, ToolCapability, ToolSpec};
63 use codewhale_agent_contract::worker_profile::ShellGrant;
64 use codewhale_execpolicy::canonical_action::canonical_action_alias;
65
66 /// The execution authority a child actually holds, read off the runtime posture
67 /// rather than off a label.
68 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
69 pub struct ExecutionEnvelope {
70 /// May mutate the workspace.
71 pub write: bool,
72 /// May be handed a model-visible network tool.
73 pub network: bool,
74 /// May run arbitrary commands (raw shell posture).
75 pub shell: bool,
76 }
77
78 impl ExecutionEnvelope {
79 /// The widest envelope: used by callers that impose no narrowing at all.
80 ///
81 /// Currently reached only from this module's tests — the production
82 /// callers all derive an envelope from a real authority rather than
83 /// starting from the widest one. Kept because it is the identity element
84 /// [`Self::narrow`] is defined against, and removing it would leave that
85 /// invariant untestable.
86 pub const UNRESTRICTED: Self = Self {
87 write: true,
88 network: true,
89 shell: true,
90 };
91
92 /// Whether this envelope narrows anything, i.e. whether enforcement can
93 /// ever refuse a call.
94 #[must_use]
95 pub const fn is_unrestricted(self) -> bool {
96 self.write && self.network && self.shell
97 }
98
99 /// Intersect with another envelope. Used wherever a child envelope is
100 /// derived from a parent one: every field takes the more restrictive side,
101 /// so a descendant can never widen an ancestor.
102 ///
103 /// Exercised by this module's tests today; the grandchild-derivation path
104 /// that consumes it in production lands with the ratification UI.
105 #[must_use]
106 pub const fn narrow(self, other: Self) -> Self {
107 Self {
108 write: self.write && other.write,
109 network: self.network && other.network,
110 shell: self.shell && other.shell,
111 }
112 }
113 }
114
115 /// Tool names whose execution is governed by a different, stricter mechanism
116 /// and which therefore must not be judged by capability alone.
117 ///
118 /// Only `agent` qualifies, and the reason is specific: its `ExecutesCode`
119 /// capability describes running a child *model loop*, not a child *program*,
120 /// and that loop runs under a narrowed copy of this same envelope. See the
121 /// module docs.
122 fn is_delegation_tool(canonical: &str) -> bool {
123 canonical == "agent"
124 }
125
126 /// Cargo/test-harness flags a bounded verification call may carry.
127 ///
128 /// An allowlist, not a denylist, and that is the whole of its security value.
129 /// The flags that turn `cargo test` into an arbitrary-program launcher —
130 /// `--config` (which can set `target.runner`), `--manifest-path`,
131 /// `--target-dir`, `--target` — are dangerous precisely because nobody thinks
132 /// to write them down. A denylist would have to enumerate them; this list has
133 /// to enumerate the harmless ones, and an unknown flag is refused by default.
134 ///
135 /// Everything here either selects *which* of the workspace's own tests run or
136 /// changes how their output is reported.
137 const BOUNDED_TEST_FLAGS: &[&str] = &[
138 "--all",
139 "--all-features",
140 "--all-targets",
141 "--benches",
142 "--bin",
143 "--bins",
144 "--color",
145 "--doc",
146 "--example",
147 "--examples",
148 "--exact",
149 "--features",
150 "--ignored",
151 "--include-ignored",
152 "--jobs",
153 "--lib",
154 "--no-default-features",
155 "--no-fail-fast",
156 "--nocapture",
157 "--package",
158 "--quiet",
159 "--release",
160 "--show-output",
161 "--skip",
162 "--test",
163 "--test-threads",
164 "--tests",
165 "--verbose",
166 "--workspace",
167 "-j",
168 "-p",
169 "-q",
170 ];
171
172 /// How tightly one call to the built-in verification surface is bounded.
173 ///
174 /// This is the typed policy the whole verification contract keys on. It exists
175 /// because "bounded" is not a property of the *tool* — `run_tests` is both the
176 /// verifier's entire job and, with the wrong `args`, a way to point cargo at
177 /// another manifest — so the question has to be asked of the concrete call and
178 /// answered in one place that catalog and dispatch both read.
179 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
180 pub enum VerificationBound {
181 /// No operator input at all: the workspace's own configured checks.
182 Default,
183 /// Operator-supplied arguments that only *select* among the workspace's own
184 /// tests. No shell metacharacters, no separators, no unknown flags — see
185 /// [`is_bounded_test_argv`].
186 Filter,
187 /// Names a program to run, or a flag that can redirect what runs. This is
188 /// arbitrary code execution wearing a verification tool's name.
189 Unbounded,
190 }
191
192 /// Classify a call to the built-in verification surface, or `None` if the call
193 /// is not one.
194 #[must_use]
195 pub fn classify_verification(canonical: &str, input: &Value) -> Option<VerificationBound> {
196 match canonical {
197 "run_tests" => Some(match input.get("args") {
198 None | Some(Value::Null) => VerificationBound::Default,
199 Some(Value::String(args)) if args.trim().is_empty() => VerificationBound::Default,
200 Some(Value::String(args)) if is_bounded_test_argv(args) => VerificationBound::Filter,
201 // A wrongly-typed value fails closed and lets the tool's own schema
202 // error explain the shape.
203 Some(_) => VerificationBound::Unbounded,
204 }),
205 "run_verifiers" => Some(VerificationBound::Default),
206 _ => None,
207 }
208 }
209
210 /// Whether a `run_tests` argv is a pure test *selection*.
211 ///
212 /// Every token must be either an allowlisted flag (optionally `flag=value`) or
213 /// a bare filter, and every value must survive [`is_bounded_argv_value`], whose
214 /// character set contains no separator, no glob, and no shell metacharacter. So
215 /// `-p tui exact_fleet` passes, and `--manifest-path ../evil/Cargo.toml`,
216 /// `--config target.runner="sh -c ..."`, `$(id)`, `a; rm -rf .` and `../..` do
217 /// not.
218 #[must_use]
219 fn is_bounded_test_argv(args: &str) -> bool {
220 args.split_whitespace().all(|arg| {
221 // The cargo/harness separator carries nothing itself.
222 if arg == "--" {
223 return true;
224 }
225 if arg.starts_with('-') {
226 let (flag, value) = arg.split_once('=').unwrap_or((arg, ""));
227 return BOUNDED_TEST_FLAGS.contains(&flag) && is_bounded_argv_value(value);
228 }
229 is_bounded_argv_value(arg)
230 })
231 }
232
233 /// The character set a bounded argv token may draw from.
234 ///
235 /// Deliberately expressed as what is *allowed*: alphanumerics plus the four
236 /// characters a Rust test path needs (`_`, `-`, `.`, `:`). No `/`, `\`, `~`,
237 /// `*`, `$`, backtick, quote, or redirection — so a path, a glob, a traversal,
238 /// and every shell expansion are all excluded by construction rather than by a
239 /// list of things to fear.
240 #[must_use]
241 fn is_bounded_argv_value(value: &str) -> bool {
242 value
243 .chars()
244 .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | '.' | ':'))
245 }
246
247 /// How one concrete call is classified, for both enforcement and diagnostics.
248 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
249 pub enum CallClass {
250 /// Read-only for this input.
251 Bounded,
252 /// Built-in verification in its default, argument-free form, or narrowed to
253 /// a test *selection*. Needs shell authority — either one starts a process —
254 /// but not write authority, because running the workspace's own checks is
255 /// what a read-only verifier is for.
256 ///
257 /// The argument-free form is deliberately **not** free. It carries no
258 /// operator argument, so nothing about *what* runs is in doubt — but it
259 /// still forks cargo and every configured verifier command, and a member
260 /// saved as `analyst` (`shell = "none"`) or `scout` was given no authority
261 /// to start a process at all. Treating "bounded" as "costless" is what let a
262 /// shell-less posture launch the test suite while its ceiling said it could
263 /// not run anything. The typed `verifier`/`tester` preset keeps this
264 /// capability because its ceiling grants `shell = "full"`; that is the whole
265 /// difference between the two roles.
266 VerificationFilter,
267 /// Built-in verification carrying an operator command line. Held to the
268 /// same bar as raw shell, with its own wording.
269 UnboundedVerification,
270 /// Bounded remote-ref fetch (`Git{action: fetch}`): fixed argv against a
271 /// configured remote, updating only remote-tracking refs. Needs shell
272 /// authority (it forks git) and network (it reaches the remote) — but
273 /// not write authority, because fetching what is under review is what a
274 /// read-only verifier is for. Shape errors (unknown remote, malformed
275 /// refspec) surface from the tool, not the envelope.
276 BoundedFetch,
277 /// Runs a program or a child process.
278 Executes,
279 /// Mutates the filesystem.
280 Mutates,
281 /// Reaches the network.
282 Reaches,
283 }
284
285 /// Classify one call from the tool's real capabilities plus this input.
286 ///
287 /// `ExecutesCode` outranks the others because it subsumes them: a call that can
288 /// run a program can write and can reach out, whatever else it declares.
289 #[must_use]
290 pub fn classify_call(name: &str, input: &Value, spec: &dyn ToolSpec) -> CallClass {
291 let canonical = canonical_action_alias(name, input);
292 if is_delegation_tool(canonical) {
293 return CallClass::Bounded;
294 }
295 // The verification surface answers for itself, before the generic rules, so
296 // an unbounded form can never be swallowed by a read-only claim and a
297 // bounded one can never be judged on the tool's name alone.
298 match classify_verification(canonical, input) {
299 // Default and Filter land on the same class: both start a process, and
300 // the only thing that separates them is whether an operator argument
301 // narrowed *which* tests run. Neither is available to a posture with no
302 // shell authority.
303 Some(VerificationBound::Default | VerificationBound::Filter) => {
304 return CallClass::VerificationFilter;
305 }
306 Some(VerificationBound::Unbounded) => return CallClass::UnboundedVerification,
307 None => {}
308 }
309 // The bounded fetch answers for itself next, for the same reason: a
310 // `git fetch <remote>` updates only remote-tracking refs through fixed
311 // argv, so it needs a process (shell) and a remote (network) — but not
312 // workspace write authority. Classed before the generic rules so a
313 // malformed fetch can never be swallowed by the family's read-only
314 // default and a bounded one is never judged as opaque execution.
315 if canonical == "git_fetch" {
316 return CallClass::BoundedFetch;
317 }
318 if spec.is_read_only_for(input) {
319 return CallClass::Bounded;
320 }
321 let capabilities = spec.capabilities();
322 if capabilities.contains(&ToolCapability::ExecutesCode) {
323 CallClass::Executes
324 } else if capabilities.contains(&ToolCapability::WritesFiles) {
325 CallClass::Mutates
326 } else if capabilities.contains(&ToolCapability::Network) {
327 CallClass::Reaches
328 } else {
329 // Fail closed on an under-declared tool. A call that is not read-only
330 // for this input and names no positive capability, yet still asks for
331 // approval, is a tool describing its *consequence* without describing
332 // its *mechanism* — `AutomationTool` was exactly this shape and its
333 // `run` action executes a stored automation. Treating the approval
334 // requirement as the floor means a tool has to be positively read-only
335 // to escape the envelope, rather than merely quiet about itself.
336 //
337 // The two approval levels map to different classes on purpose.
338 // `Required` is the level shell and code execution sit at, so it earns
339 // `Executes`. `Suggest` is the file-mutation level, and mapping it to
340 // `Executes` would additionally demand *shell* authority from a
341 // write-capable child that has none — an over-block with no security
342 // value, since the write requirement is the one that bites.
343 match spec.approval_requirement_for(input) {
344 ApprovalRequirement::Required => CallClass::Executes,
345 ApprovalRequirement::Suggest => CallClass::Mutates,
346 ApprovalRequirement::Auto => CallClass::Bounded,
347 }
348 }
349 }
350
351 /// Refuse a call that falls outside `envelope`.
352 ///
353 /// Returns the operator-facing refusal text, which names the posture rather
354 /// than the tool, so the refusal reads as a contract instead of a malfunction.
355 ///
356 /// `proven_read_only` (#5426/#5438) carries bounded read-only shell evidence
357 /// — the exact `agent_readonly_bash_input` predicate `BashTool::execute`
358 /// enforces under `ShellPolicy::ReadOnly` — so the call classifies as
359 /// [`CallClass::Bounded`]: the same class `classify_call` assigns when the
360 /// spec itself reports the input read-only. Two invariants: the admission
361 /// can never outrun the execute-time refusal (same predicate both sides),
362 /// and the parent's parallel auto-approve classifier is untouched —
363 /// `spec.is_read_only_for` still answers the deliberately tighter
364 /// `is_parallel_readonly_command` for every other consumer.
365 pub fn enforce_execution_envelope(
366 name: &str,
367 input: &Value,
368 spec: &dyn ToolSpec,
369 envelope: ExecutionEnvelope,
370 proven_read_only: bool,
371 ) -> Result<(), String> {
372 if envelope.is_unrestricted() {
373 return Ok(());
374 }
375 if proven_read_only {
376 // Classified Bounded: no capability the call can exercise escapes
377 // the envelope. Network-reaching shape is still rejected separately
378 // by the child's network gate, and the execute path re-verifies the
379 // same predicate before running anything.
380 return Ok(());
381 }
382 match classify_call(name, input, spec) {
383 CallClass::Bounded => Ok(()),
384 CallClass::VerificationFilter => {
385 if envelope.shell {
386 Ok(())
387 } else {
388 Err(format!(
389 "[execution_envelope.verification.shell_denied] Tool {name} starts a test or verifier process, and this agent has no shell \
390 authority under its clamped permission ceiling. That holds for the default, \
391 argument-free form too: running the workspace's own checks still forks a \
392 process, which a `shell = \"none\"` posture was never granted. Use a member \
393 whose saved ceiling grants `shell = \"full\"` (the `verifier`/`tester` \
394 preset), or report findings without running the checks yourself."
395 ))
396 }
397 }
398 CallClass::UnboundedVerification => {
399 if envelope.write && envelope.shell {
400 Ok(())
401 } else {
402 Err(format!(
403 "[execution_envelope.verification.unbounded] Tool {name} was called with operator-supplied arguments that can \
404 name a program or redirect what runs, which is arbitrary execution however \
405 it is spelled. This agent runs read-only under its clamped permission \
406 ceiling. The default verification gates, and test-selection arguments \
407 (filters, `-p`, `--lib`, `--exact`), remain available to a member whose \
408 ceiling grants shell authority."
409 ))
410 }
411 }
412 CallClass::BoundedFetch => {
413 if !envelope.shell {
414 return Err(format!(
415 "[execution_envelope.fetch.shell_denied] Tool {name} fetches remote refs, which starts a git process and updates remote-tracking refs, and this agent has no shell \
416 authority under its clamped permission ceiling. Use a member whose saved \
417 ceiling grants `shell = \"full\"` (the `verifier`/`tester` preset), or report \
418 findings without fetching the remote yourself."
419 ));
420 }
421 if !envelope.network {
422 return Err(format!(
423 "[execution_envelope.fetch.network_denied] Tool {name} fetches remote refs, which reaches the network, and this agent runs with no network \
424 capability under its clamped permission ceiling."
425 ));
426 }
427 Ok(())
428 }
429 CallClass::Executes => {
430 if !envelope.write {
431 return Err(format!(
432 "[execution_envelope.executes.write_denied] Tool {name} runs a program or a child process, which mutates the workspace \
433 just as directly as a file write. This agent runs read-only under its \
434 clamped permission ceiling, so arbitrary execution is refused however it is \
435 spelled — shell, verification gate, automation, plugin, or MCP server. The \
436 built-in verification gates (Run/run_tests/run_verifiers in their default \
437 form) are still available."
438 ));
439 }
440 if !envelope.shell {
441 return Err(format!(
442 "[execution_envelope.executes.shell_denied] Tool {name} runs a program or a child process, and this agent has no shell \
443 authority under its clamped permission ceiling. Use a member whose saved \
444 ceiling grants `shell = \"full\"`."
445 ));
446 }
447 Ok(())
448 }
449 CallClass::Mutates => {
450 if envelope.write {
451 Ok(())
452 } else {
453 Err(format!(
454 "[execution_envelope.mutates.write_denied] Tool {name} mutates state and this agent runs read-only under its clamped \
455 permission ceiling."
456 ))
457 }
458 }
459 CallClass::Reaches => {
460 if envelope.network {
461 Ok(())
462 } else {
463 Err(format!(
464 "[execution_envelope.network.denied] Tool {name} reaches the network and this agent runs with no network \
465 capability (`network_tool = false`) under its clamped permission ceiling."
466 ))
467 }
468 }
469 }
470 }
471
472 pub fn tool_call_denied(rules: Option<&[String]>, name: &str, input: &Value) -> bool {
473 tool_call_denied_for(rules, name, input, false)
474 }
475
476 pub fn tool_call_denied_for(
477 rules: Option<&[String]>,
478 name: &str,
479 input: &Value,
480 holds_bounded_verification: bool,
481 ) -> bool {
482 let action = canonical_action_alias(name, input);
483 codewhale_execpolicy::tool_rules::tool_denied(rules, name)
484 || codewhale_execpolicy::tool_rules::tool_denied(rules, action)
485 || (action == "rlm_open"
486 && input
487 .get("url")
488 .and_then(Value::as_str)
489 .is_some_and(|url| !url.trim().is_empty())
490 && codewhale_execpolicy::tool_rules::tool_denied(rules, "fetch_url"))
491 || (starts_workspace_execution(name, action, input, holds_bounded_verification)
492 && rules.is_some_and(|rules| {
493 codewhale_execpolicy::tool_rules::tool_matches_any_rule(rules, "Bash")
494 }))
495 }
496
497 fn starts_workspace_execution(
498 name: &str,
499 action: &str,
500 input: &Value,
501 holds_bounded_verification: bool,
502 ) -> bool {
503 match classify_verification(action, input) {
504 Some(VerificationBound::Unbounded) => true,
505 Some(VerificationBound::Default | VerificationBound::Filter) => !holds_bounded_verification,
506 None => {
507 (name.eq_ignore_ascii_case("send_later")
508 && input.get("action").and_then(Value::as_str) == Some("schedule"))
509 || (name.eq_ignore_ascii_case("workflow")
510 && input
511 .pointer("/args/evaluator")
512 .is_some_and(|value| !value.is_null()))
513 || (name.eq_ignore_ascii_case("workflow")
514 && input.get("verify").and_then(Value::as_bool) == Some(true)
515 && !holds_bounded_verification)
516 }
517 }
518 }
519
520 #[must_use]
521 pub fn holds_bounded_verification(context: &crate::tools::spec::ToolContext) -> bool {
522 context
523 .child_host
524 .as_ref()
525 .is_some_and(|child| child.grant.shell == ShellGrant::Verify)
526 || context.tool_authority.as_deref().is_some_and(|authority| {
527 authority.verification == crate::tools::spec::ToolVerificationAuthority::Bounded
528 })
529 }
530
531 /// Repeat the command ceiling at native dispatch and direct delegation sinks.
532 /// The existing child evidence exception is limited to the canonical lowercase
533 /// tool, a child-owned context, and the same strict read-only grammar enforced
534 /// by Bash itself. It never admits a session, stdin, or background command.
535 pub fn enforce_tool_denial(
536 context: &crate::tools::spec::ToolContext,
537 name: &str,
538 input: &Value,
539 ) -> Result<(), crate::tools::spec::ToolError> {
540 let bounded_child_read = name == "bash"
541 && context.owner_agent_id.is_some()
542 && context.shell_policy == codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly
543 && crate::tools::shell::agent_readonly_bash_input(input);
544 if !bounded_child_read
545 && tool_call_denied_for(
546 Some(&context.disallowed_tools),
547 name,
548 input,
549 holds_bounded_verification(context),
550 )
551 {
552 return Err(crate::tools::spec::ToolError::permission_denied(format!(
553 "Tool '{name}' or its execution dependency is in the disallowed-tools list"
554 )));
555 }
556 Ok(())
557 }
558
559 #[cfg(test)]
560 mod tests {
561 use super::*;
562 use serde_json::json;
563
564 const READ_ONLY: ExecutionEnvelope = ExecutionEnvelope {
565 write: false,
566 network: false,
567 shell: true,
568 };
569
570 /// A stand-in for any tool the registry may hold, including ones this file
571 /// has never heard of. The point of the guard is that it needs nothing but
572 /// the trait.
573 struct FakeTool {
574 name: &'static str,
575 capabilities: Vec<ToolCapability>,
576 read_only_action: Option<&'static str>,
577 }
578
579 #[async_trait::async_trait]
580 impl ToolSpec for FakeTool {
581 fn name(&self) -> &str {
582 self.name
583 }
584 fn description(&self) -> &str {
585 "fake"
586 }
587 fn input_schema(&self) -> Value {
588 json!({})
589 }
590 fn capabilities(&self) -> Vec<ToolCapability> {
591 self.capabilities.clone()
592 }
593 fn is_read_only_for(&self, input: &Value) -> bool {
594 match self.read_only_action {
595 Some(action) => input.get("action").and_then(Value::as_str) == Some(action),
596 None => false,
597 }
598 }
599 async fn execute(
600 &self,
601 _input: Value,
602 _context: &crate::tools::spec::ToolContext,
603 ) -> Result<crate::tools::spec::ToolResult, crate::tools::spec::ToolError> {
604 unreachable!("classification never executes")
605 }
606 }
607
608 fn executes(name: &'static str, read_only_action: Option<&'static str>) -> FakeTool {
609 FakeTool {
610 name,
611 capabilities: vec![ToolCapability::ExecutesCode],
612 read_only_action,
613 }
614 }
615
616 /// The blocker this module exists for: a read-only member that kept
617 /// `shell = "full"` so it could run checks must not regain arbitrary
618 /// execution through a tool the raw-shell name list never mentioned.
619 #[test]
620 fn execution_primitives_spelled_as_bookkeeping_are_refused_read_only() {
621 for (name, input) in [
622 (
623 "tasks",
624 json!({"action": "gate_run", "command": "rm -rf src"}),
625 ),
626 ("automation", json!({"action": "run", "id": "a1"})),
627 (
628 "automation",
629 json!({"action": "create", "name": "x", "prompt": "exfiltrate"}),
630 ),
631 ("start_mcp_server", json!({"command": "node", "args": []})),
632 ("plugin_deploy", json!({})),
633 ] {
634 let spec = executes(name, Some("list"));
635 let error = enforce_execution_envelope(name, &input, &spec, READ_ONLY, false)
636 .expect_err("read-only member must not execute programs");
637 assert!(error.contains("read-only"), "{name}: {error}");
638 }
639 }
640
641 /// The `analyst`/`scout` posture: tools, but no shell authority at all.
642 const NO_SHELL: ExecutionEnvelope = ExecutionEnvelope {
643 write: false,
644 network: false,
645 shell: false,
646 };
647
648 /// A member whose ceiling grants no shell must not start a process, and the
649 /// argument-free verification gates are no exception: running the
650 /// workspace's own checks still forks cargo and every configured verifier.
651 /// "Bounded" bounds *what* runs, not *whether* something runs.
652 #[test]
653 fn a_shell_less_posture_cannot_start_a_verification_process() {
654 let verifier = executes("run_verifiers", None);
655 let error =
656 enforce_execution_envelope("run_verifiers", &json!({}), &verifier, NO_SHELL, false)
657 .expect_err("an analyst was granted no authority to start a process");
658 assert!(error.contains("shell authority"), "{error}");
659
660 let tests = executes("run_tests", None);
661 for input in [json!({}), json!({"args": " "}), json!({"args": "-p tui"})] {
662 enforce_execution_envelope("run_tests", &input, &tests, NO_SHELL, false)
663 .expect_err("the default test gate still forks a process");
664 }
665
666 // The unbounded form was already refused and stays refused, with its own
667 // wording — the two failures must not collapse into one.
668 let error = enforce_execution_envelope(
669 "run_tests",
670 &json!({"args": "--manifest-path ../evil/Cargo.toml"}),
671 &tests,
672 NO_SHELL,
673 false,
674 )
675 .expect_err("redirecting arguments are refused first");
676 assert!(error.contains("arbitrary execution"), "{error}");
677 }
678
679 /// Bounded fetch costs shell plus network, never workspace write: the
680 /// shipped `verifier`/`tester` ceiling (`write = false, shell = "full"`,
681 /// network) keeps it, while a shell-less or network-less posture loses
682 /// it with a naming-its-cause refusal (#6298).
683 #[test]
684 fn bounded_fetch_costs_shell_plus_network_never_write() {
685 let fetch = executes("Git", None);
686 let input = json!({"action": "fetch", "remote": "origin"});
687 assert_eq!(
688 classify_call("Git", &input, &fetch),
689 CallClass::BoundedFetch
690 );
691
692 let verifier = ExecutionEnvelope {
693 write: false,
694 network: true,
695 shell: true,
696 };
697 enforce_execution_envelope("Git", &input, &fetch, verifier, false)
698 .expect("write=false shell=full with network keeps fetch");
699
700 let error = enforce_execution_envelope("Git", &input, &fetch, NO_SHELL, false)
701 .expect_err("a shell-less posture cannot fetch");
702 assert!(error.contains("shell authority"), "{error}");
703
704 let no_network = ExecutionEnvelope {
705 write: false,
706 network: false,
707 shell: true,
708 };
709 let error = enforce_execution_envelope("Git", &input, &fetch, no_network, false)
710 .expect_err("a network-less posture cannot fetch");
711 assert!(error.contains("network"), "{error}");
712 }
713
714 /// `cwd` scopes *where* the workspace's own checks run; it cannot name a
715 /// program or redirect what runs, so the Default/Filter bound — and the
716 /// shell authority it costs — is unchanged by it.
717 #[test]
718 fn run_cwd_does_not_change_the_verification_bound() {
719 assert_eq!(
720 classify_verification("run_tests", &json!({"cwd": "crates/tui"})),
721 Some(VerificationBound::Default)
722 );
723 assert_eq!(
724 classify_verification("run_tests", &json!({"args": "-p tui", "cwd": "crates/tui"})),
725 Some(VerificationBound::Filter)
726 );
727 assert_eq!(
728 classify_verification("run_verifiers", &json!({"cwd": "crates/tui"})),
729 Some(VerificationBound::Default)
730 );
731 }
732
733 /// The other side of the same rule: the shipped `verifier`/`tester` preset
734 /// is `write = false, shell = "full"`, and that is exactly the ceiling that
735 /// keeps the verification surface. The typed role, not the tool name, is
736 /// what separates it from `analyst`.
737 #[test]
738 fn a_verifier_ceiling_keeps_the_verification_surface() {
739 let tests = executes("run_tests", None);
740 for input in [json!({}), json!({"args": "-p tui exact_fleet"})] {
741 enforce_execution_envelope("run_tests", &input, &tests, READ_ONLY, false)
742 .expect("a verifier ceiling grants shell authority, which is its whole job");
743 }
744 }
745
746 /// Catalog and dispatch read the same classifier, so a call the dispatch
747 /// guard would refuse is never advertised. Asserting on `classify_call`
748 /// directly is what pins that they cannot drift apart.
749 #[test]
750 fn the_default_and_filter_forms_classify_identically() {
751 let tests = executes("run_tests", None);
752 assert_eq!(
753 classify_call("run_tests", &json!({}), &tests),
754 CallClass::VerificationFilter
755 );
756 assert_eq!(
757 classify_call("run_tests", &json!({"args": "-p tui"}), &tests),
758 CallClass::VerificationFilter
759 );
760 assert_eq!(
761 classify_call(
762 "run_tests",
763 &json!({"args": "--manifest-path ../x"}),
764 &tests
765 ),
766 CallClass::UnboundedVerification
767 );
768 }
769
770 /// …and the bounded positives it must not break.
771 #[test]
772 fn bounded_read_only_and_verification_calls_survive() {
773 let tasks = executes("tasks", Some("list"));
774 enforce_execution_envelope(
775 "tasks",
776 &json!({"action": "list"}),
777 &tasks,
778 READ_ONLY,
779 false,
780 )
781 .expect("durable task bookkeeping is read-only");
782
783 let verifier = executes("run_verifiers", None);
784 enforce_execution_envelope("run_verifiers", &json!({}), &verifier, READ_ONLY, false)
785 .expect("the default verification gate is what a verifier is for");
786 let tests = executes("run_tests", None);
787 for input in [json!({}), json!({"args": " "})] {
788 enforce_execution_envelope("run_tests", &input, &tests, READ_ONLY, false)
789 .expect("the default test gate is bounded");
790 }
791
792 // Delegation stays available: a read-only member may still fan out
793 // read-only children, which inherit this same envelope.
794 let agent = executes("agent", None);
795 enforce_execution_envelope(
796 "agent",
797 &json!({"prompt": "read"}),
798 &agent,
799 READ_ONLY,
800 false,
801 )
802 .expect("delegation is governed by depth, not by write authority");
803 }
804
805 /// The shipped `verifier` role is `write = false, shell = "full"`, and its
806 /// documented job is running the suite. A test *selection* must survive, or
807 /// the envelope has taken a shipped role's purpose away.
808 #[test]
809 fn a_read_only_shell_capable_role_keeps_test_selection_arguments() {
810 let tests = executes("run_tests", None);
811 for args in [
812 "-p codewhale-tui",
813 "--lib fleet::exact",
814 "exact_fleet_workflow --exact",
815 "--package tui --test-threads=1 --nocapture",
816 "--workspace --all-features -- --skip slow_case",
817 ] {
818 enforce_execution_envelope(
819 "run_tests",
820 &json!({"args": args}),
821 &tests,
822 READ_ONLY,
823 false,
824 )
825 .unwrap_or_else(|error| panic!("`{args}` selects tests and must run: {error}"));
826 }
827 }
828
829 /// …and *every* form is refused for the stricter read-only roles, which
830 /// hold no shell authority at all.
831 ///
832 /// Both the selection form and the argument-free default are refused,
833 /// because both fork a process: running the workspace's own configured
834 /// checks is still starting a program, and a `shell = "none"` posture was
835 /// never granted that. Admitting the default form would make "no shell" a
836 /// label rather than a ceiling.
837 #[test]
838 fn a_shell_less_read_only_role_cannot_start_a_verification_process_at_all() {
839 const NO_SHELL: ExecutionEnvelope = ExecutionEnvelope {
840 write: false,
841 network: false,
842 shell: false,
843 };
844 let tests = executes("run_tests", None);
845 for input in [json!({"args": "-p tui"}), json!({})] {
846 let error = enforce_execution_envelope("run_tests", &input, &tests, NO_SHELL, false)
847 .expect_err("a planner/scout/consultant has no shell authority");
848 assert!(error.contains("shell"), "{input}: {error}");
849 }
850 }
851
852 /// The escape hatch stays shut: a selection is a selection, and anything
853 /// that can name a program or redirect what runs is raw shell.
854 #[test]
855 fn operator_command_lines_are_refused_however_they_are_spelled() {
856 let tests = executes("run_tests", None);
857 for args in [
858 "--manifest-path ../evil/Cargo.toml",
859 "--config target.runner=sh",
860 "--target-dir /tmp/out",
861 "$(id)",
862 "a; rm -rf .",
863 "--lib | tee /tmp/x",
864 "../../etc/passwd",
865 "tests/*",
866 "--features tui/evil",
867 "`whoami`",
868 ] {
869 let error = enforce_execution_envelope(
870 "run_tests",
871 &json!({"args": args}),
872 &tests,
873 READ_ONLY,
874 false,
875 )
876 .expect_err("`{args}` is not a test selection");
877 assert!(error.contains("read-only"), "{args}: {error}");
878 }
879 }
880
881 #[test]
882 fn write_and_network_capabilities_are_gated_independently() {
883 let writer = FakeTool {
884 name: "pandoc_convert",
885 capabilities: vec![ToolCapability::WritesFiles],
886 read_only_action: None,
887 };
888 assert!(
889 enforce_execution_envelope("pandoc_convert", &json!({}), &writer, READ_ONLY, false)
890 .is_err()
891 );
892
893 let reacher = FakeTool {
894 name: "mcp__remote__query",
895 capabilities: vec![ToolCapability::Network],
896 read_only_action: None,
897 };
898 assert!(
899 enforce_execution_envelope(
900 "mcp__remote__query",
901 &json!({}),
902 &reacher,
903 READ_ONLY,
904 false
905 )
906 .is_err()
907 );
908 assert!(
909 enforce_execution_envelope(
910 "mcp__remote__query",
911 &json!({}),
912 &reacher,
913 ExecutionEnvelope {
914 network: true,
915 ..READ_ONLY
916 },
917 false
918 )
919 .is_ok()
920 );
921 }
922
923 /// An unrestricted envelope must be a true no-op, so nothing here can
924 /// change behavior for an ordinary write-capable child.
925 #[test]
926 fn an_unrestricted_envelope_refuses_nothing() {
927 let spec = executes("tasks", None);
928 enforce_execution_envelope(
929 "tasks",
930 &json!({"action": "gate_run", "command": "cargo test"}),
931 &spec,
932 ExecutionEnvelope::UNRESTRICTED,
933 false,
934 )
935 .expect("a write-capable, shell-capable child keeps its gates");
936 }
937
938 #[test]
939 fn narrowing_never_widens() {
940 let parent = ExecutionEnvelope {
941 write: false,
942 network: true,
943 shell: true,
944 };
945 let child = ExecutionEnvelope {
946 write: true,
947 network: false,
948 shell: true,
949 };
950 let narrowed = parent.narrow(child);
951 assert!(!narrowed.write, "a child cannot regain the parent's writes");
952 assert!(!narrowed.network, "a child cannot regain its own denial");
953 assert!(narrowed.shell);
954 }
955 }
956
956 lines RUST