Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / infra / agents / agentd / src / tools.rs

tools.rs281 lines · 10.5 KiBRaw
1//! Command allowlists: which `build` invocations agentd forwards to the
2//! runner, and which `run_shell` commands it rejects.
3//!
4//! Gradle builds in this repo go through `./gradlew :<path>:<task>` or the
5//! `./check <module>` wrapper. Raw build-ish commands (`cargo build`,
6//! `adb`, …) are rejected from `run_shell` with a pointer to `build`.
7
8use std::collections::HashSet;
9
10/// Gradle tasks the `build` tool may run (exact allowlist).
11const ALLOWED_TASKS: &[&str] = &[
12 "compileDevKotlin",
13 "lint",
14 "lintDev",
15 "checkMetadata",
16 "detekt",
17 "metadata",
18];
19
20/// Extra flags allowed after the task list.
21const ALLOWED_FLAGS: &[&str] = &["--console=plain", "--stacktrace", "--info"];
22
23fn is_test_unit_task(task: &str) -> bool {
24 // `test[A-Za-z]*UnitTest`, e.g. `testDebugUnitTest`.
25 let rest = match task.strip_prefix("test") {
26 Some(r) => r,
27 None => return false,
28 };
29 let body = match rest.strip_suffix("UnitTest") {
30 Some(b) => b,
31 None => return false,
32 };
33 body.chars().all(|c| c.is_ascii_alphabetic())
34}
35
36fn is_cargo_build_task(task: &str) -> bool {
37 // `cargoBuild[A-Za-z0-9_]*`, e.g. `cargoBuildNativeDebug`.
38 match task.strip_prefix("cargoBuild") {
39 Some(rest) => {
40 rest.chars()
41 .all(|c| c.is_ascii_alphanumeric() || c == '_')
42 }
43 None => false,
44 }
45}
46
47fn task_allowed(task: &str) -> bool {
48 ALLOWED_TASKS.contains(&task) || is_test_unit_task(task) || is_cargo_build_task(task)
49}
50
51/// Whether a bare Gradle task name passes the allowlist.
52/// `pub(crate)` so `structured.rs` validates structured `build{module, tasks}`
53/// parts against this same allowlist.
54pub(crate) fn build_task_ok(task: &str) -> bool {
55 task_allowed(task)
56}
57
58/// Whether a `test<Variant>UnitTest` task name is allowed.
59/// `pub(crate)` for `structured::run_tests_command`.
60pub(crate) fn test_unit_task_ok(task: &str) -> bool {
61 is_test_unit_task(task)
62}
63
64/// Module dirs the structured `build`/`run_tests`/`check` tools accept.
65/// `pub(crate)` so `structured.rs` validates against the same allowlist.
66pub(crate) fn module_path_ok(path: &str) -> bool {
67 // `[a-z0-9-]+(:[a-z0-9-]+)*`, e.g. `notes`, `games:logicgate`.
68 !path.is_empty()
69 && path
70 .split(':')
71 .all(|seg| !seg.is_empty() && seg.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'))
72}
73
74pub fn build_help() -> &'static str {
75 "Allowed builds: `./gradlew :<module path>:<task> [...] [--console=plain --stacktrace --info]` \
76 where module path matches `[a-z0-9-]+(:[a-z0-9-]+)*` (e.g. `notes`, `games:logicgate`) and task is one of \
77 `compileDevKotlin`, `lint`, `lintDev`, `checkMetadata`, `detekt`, `metadata`, `test*UnitTest`, `cargoBuild*`; \
78 or `./check <module>` (a single module name, not `all`)."
79}
80
81/// Validate a `build` command. Returns the exact command to forward when
82/// allowed, else a helpful rejection naming what is allowed.
83pub fn validate_build_command(cmd: &str) -> Result<String, String> {
84 let cmd = cmd.trim();
85 if cmd.is_empty() {
86 return Err(format!("Empty build command. {}", build_help()));
87 }
88 // No shell metacharacters: one program invocation only.
89 for meta in ["&&", "||", ";", "|", "$(", "`", "$", ">", "<", "\n"] {
90 if cmd.contains(meta) {
91 return Err(format!(
92 "Build commands must be a single invocation (found {meta:?}). {}",
93 build_help()
94 ));
95 }
96 }
97 // `./check <module>` form.
98 if let Some(rest) = cmd.strip_prefix("./check") {
99 let args: Vec<&str> = rest.split_whitespace().collect();
100 if args.len() == 1 && module_path_ok(&args[0].replace('/', ":")) && args[0] != "all" {
101 return Ok(cmd.to_string());
102 }
103 return Err(format!(
104 "`./check` takes exactly one module (e.g. `./check notes`), never `all`. {}",
105 build_help()
106 ));
107 }
108 // `./gradlew :path:task ...` form.
109 let parts: Vec<&str> = cmd.split_whitespace().collect();
110 if parts.len() < 2 || (parts[0] != "./gradlew" && parts[0] != "gradlew") {
111 return Err(format!(
112 "Builds must start with `./gradlew` or be `./check <module>`. {}",
113 build_help()
114 ));
115 }
116 let mut seen_task = false;
117 for arg in &parts[1..] {
118 if let Some(flag) = arg.strip_prefix("--") {
119 let _ = flag;
120 if !ALLOWED_FLAGS.contains(arg) {
121 return Err(format!("Flag {arg:?} is not allowed. {}", build_help()));
122 }
123 continue;
124 }
125 if let Some(target) = arg.strip_prefix(':') {
126 // `:path:task`
127 let mut segs: Vec<&str> = target.split(':').collect();
128 let task = segs.pop().unwrap_or("");
129 let path = segs.join(":");
130 if !module_path_ok(&path) {
131 return Err(format!("Bad module path {path:?}. {}", build_help()));
132 }
133 if !task_allowed(task) {
134 return Err(format!("Task {task:?} is not allowed. {}", build_help()));
135 }
136 seen_task = true;
137 } else {
138 return Err(format!("Unexpected argument {arg:?}. {}", build_help()));
139 }
140 }
141 if !seen_task {
142 return Err(format!("No `:path:task` target found. {}", build_help()));
143 }
144 Ok(cmd.to_string())
145}
146
147/// Patterns rejected from `run_shell` (case-insensitive substring match on
148/// the command): anything that should go through the `build` tool instead,
149/// plus device flashing.
150const SHELL_BLOCKED: &[(&str, &str)] = &[
151 ("gradlew", "Gradle builds must use the `build` tool, not `run_shell`."),
152 ("./check", "Static checks must use the `build` tool (`./check <module>`), not `run_shell`."),
153 ("./install", "Installs are not available to agents; verify with the `build` tool instead."),
154 ("adb", "`adb` is not available to agents; verify with the `build` tool instead."),
155];
156
157fn shell_blocked_cargo(cmd_lower: &str) -> bool {
158 // `cargo (build|test|run|check|clippy)` as a command word.
159 let mut tokens = cmd_lower
160 .split(|c: char| c.is_whitespace() || c == ';' || c == '&' || c == '|' || c == '(')
161 .filter(|t| !t.is_empty());
162 while let Some(tok) = tokens.next() {
163 let tok = tok.trim_matches(|c: char| c == '"' || c == '\'' || c == '(');
164 if tok == "cargo" {
165 if let Some(sub) = tokens.next() {
166 if matches!(sub, "build" | "test" | "run" | "check" | "clippy") {
167 return true;
168 }
169 }
170 }
171 }
172 false
173}
174
175/// Validate a `run_shell` command. `Ok(())` = forward to the runner;
176/// `Err(msg)` = return `msg` to the model as the tool result.
177pub fn validate_shell_command(cmd: &str) -> Result<(), String> {
178 let lower = cmd.to_lowercase();
179 for (pat, msg) in SHELL_BLOCKED {
180 if lower.contains(pat) {
181 return Err(format!("{msg} {}", build_help()));
182 }
183 }
184 if shell_blocked_cargo(&lower) {
185 return Err(format!(
186 "`cargo build/test/run/check/clippy` must use the `build` tool, not `run_shell`. {}",
187 build_help()
188 ));
189 }
190 let _ = HashSet::<u8>::new();
191 Ok(())
192}
193
194/// Best-effort detector for file-mutating `run_shell` commands, used ONLY by
195/// the plan gate (`require_plan && !plan_approved`): when it returns `true`
196/// the command is rejected with the "propose a plan first" message.
197///
198/// This is deliberately conservative and documented as incomplete: a
199/// determined model can mutate the tree through allowed commands (e.g.
200/// `python3 -c "open(...).write(...)"`, `git apply`, `perl -i`). The gate
201/// keeps honest agents on the plan-first path; it is not a sandbox.
202///
203/// Rejected patterns (case-insensitive substring / token match):
204/// * output redirection: `>`, `>>` (also `>|`, `&>`, `2>`);
205/// * `sed -i` / `sed --in-place`;
206/// * `tee` as a command word;
207/// * `mv`, `cp`, `rm`, `touch`, `mkdir`, `ln` as command words;
208/// * `git` write subcommands: `add`, `commit`, `checkout`, `apply`, `mv`,
209/// `rm`, `clean`, `reset`, `restore`, `revert`, `merge`, `rebase`,
210/// `cherry-pick`, `stash`.
211pub fn shell_looks_mutating(cmd: &str) -> bool {
212 // Redirection operators (cheap substring scan; `>` also covers `>>`,
213 // `>|`, `&>`, `2>`).
214 if cmd.contains('>') {
215 return true;
216 }
217 let lower = cmd.to_lowercase();
218 if lower.contains("sed -i") || lower.contains("sed --in-place") {
219 return true;
220 }
221 // Command-word scan: split on shell separators so `echo hi | tee x`
222 // catches `tee` but `guarantee` does not match `tee`.
223 let words: Vec<&str> = lower
224 .split(|c: char| {
225 c.is_whitespace() || matches!(c, ';' | '&' | '|' | '(' | ')' | '<')
226 })
227 .filter(|t| !t.is_empty())
228 .collect();
229 let mut words = words.into_iter().peekable();
230 while let Some(tok) = words.next() {
231 let tok = tok.trim_matches(|c: char| c == '"' || c == '\'' || c == '`');
232 if matches!(
233 tok,
234 "tee" | "mv" | "cp" | "rm" | "touch" | "mkdir" | "ln" | "rmdir" | "unlink"
235 ) {
236 return true;
237 }
238 if tok == "git" {
239 // Skip flags (`-C dir`) to find the subcommand. Note `lower` is
240 // already lowercased, so `-C` arrives as `-c`.
241 let mut sub: Option<String> = None;
242 while let Some(n) = words.peek().map(|s| s.to_string()) {
243 if n.starts_with('-') {
244 words.next();
245 // `-C`/`--git-dir`/`--work-tree` take a value.
246 if n == "-c" || n == "--git-dir" || n == "--work-tree" {
247 words.next();
248 }
249 continue;
250 }
251 sub = Some(n);
252 break;
253 }
254 if let Some(s) = sub.as_deref() {
255 if matches!(
256 s,
257 "add"
258 | "commit"
259 | "checkout"
260 | "switch"
261 | "apply"
262 | "mv"
263 | "rm"
264 | "clean"
265 | "reset"
266 | "restore"
267 | "revert"
268 | "merge"
269 | "rebase"
270 | "cherry-pick"
271 | "cherry"
272 | "stash"
273 | "am"
274 ) {
275 return true;
276 }
277 }
278 }
279 }
280 false
281}