1use shell_words;
2use std::path::Path;
3
4pub use crate::semantics::{PermissionMode, RiskLevel};
5
6pub fn split_by_operators(cmd: &str) -> Vec<(String, Option<String>)> {
11 let mut segments = Vec::new();
12 let mut current = String::new();
13 let mut chars = cmd.chars().peekable();
14 let mut in_single_quote = false;
15 let mut in_double_quote = false;
16 let mut escape_next = false;
17
18 while let Some(ch) = chars.next() {
19 if escape_next {
20 current.push(ch);
21 escape_next = false;
22 continue;
23 }
24 if ch == '\\' && !in_single_quote {
25 escape_next = true;
26 current.push(ch);
27 continue;
28 }
29 if ch == '\'' && !in_double_quote {
30 in_single_quote = !in_single_quote;
31 current.push(ch);
32 continue;
33 }
34 if ch == '"' && !in_single_quote {
35 in_double_quote = !in_double_quote;
36 current.push(ch);
37 continue;
38 }
39
40 if !in_single_quote && !in_double_quote {
41 if ch == '&' && chars.peek() == Some(&'&') {
42 chars.next();
43 segments.push((current.trim().to_string(), Some("&&".to_string())));
44 current.clear();
45 continue;
46 }
47 if ch == '|' && chars.peek() == Some(&'|') {
48 chars.next();
49 segments.push((current.trim().to_string(), Some("||".to_string())));
50 current.clear();
51 continue;
52 }
53 if ch == '|' && chars.peek() == Some(&'&') {
54 chars.next();
55 segments.push((current.trim().to_string(), Some("|&".to_string())));
56 current.clear();
57 continue;
58 }
59 if matches!(ch, '|' | ';' | '\n') {
60 segments.push((current.trim().to_string(), Some(ch.to_string())));
61 current.clear();
62 continue;
63 }
64 if ch == '&'
65 && !current.ends_with('>')
66 && !current.ends_with('<')
67 && chars.peek() != Some(&'>')
68 {
69 segments.push((current.trim().to_string(), Some(ch.to_string())));
70 current.clear();
71 continue;
72 }
73 }
74 current.push(ch);
75 }
76
77 let final_segment = current.trim();
78 if !final_segment.is_empty() {
79 segments.push((final_segment.to_string(), None));
80 }
81 segments
82}
83
84#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct ShellInvocation {
90 pub program: String,
91 pub arguments: Vec<String>,
92}
93
94const MAX_SHELL_INVOCATION_DEPTH: usize = 8;
95
96fn heredoc_specs(line: &str) -> Vec<(String, bool)> {
97 let bytes = line.as_bytes();
98 let mut specs = Vec::new();
99 let mut index = 0;
100 let mut quote = None;
101 let mut escaped = false;
102 while index < bytes.len() {
103 let byte = bytes[index];
104 if escaped {
105 escaped = false;
106 index += 1;
107 continue;
108 }
109 if byte == b'\\' && quote != Some(b'\'') {
110 escaped = true;
111 index += 1;
112 continue;
113 }
114 if matches!(byte, b'\'' | b'"') {
115 if quote == Some(byte) {
116 quote = None;
117 } else if quote.is_none() {
118 quote = Some(byte);
119 }
120 index += 1;
121 continue;
122 }
123 if quote.is_some()
124 || byte != b'<'
125 || bytes.get(index + 1) != Some(&b'<')
126 || bytes.get(index + 2) == Some(&b'<')
127 {
128 index += 1;
129 continue;
130 }
131
132 index += 2;
133 let strip_tabs = bytes.get(index) == Some(&b'-');
134 if strip_tabs {
135 index += 1;
136 }
137 while bytes.get(index).is_some_and(u8::is_ascii_whitespace) {
138 index += 1;
139 }
140 let mut delimiter = Vec::new();
141 let mut delimiter_quote = None;
142 while let Some(¤t) = bytes.get(index) {
143 if delimiter_quote.is_none()
144 && (current.is_ascii_whitespace() || matches!(current, b';' | b'|' | b'&' | b'<'))
145 {
146 break;
147 }
148 if current == b'\\'
149 && delimiter_quote != Some(b'\'')
150 && let Some(&literal) = bytes.get(index + 1)
151 {
152 delimiter.push(literal);
153 index += 2;
154 continue;
155 }
156 if matches!(current, b'\'' | b'"') {
157 if delimiter_quote == Some(current) {
158 delimiter_quote = None;
159 index += 1;
160 continue;
161 }
162 if delimiter_quote.is_none() {
163 delimiter_quote = Some(current);
164 index += 1;
165 continue;
166 }
167 }
168 delimiter.push(current);
169 index += 1;
170 }
171 if !delimiter.is_empty() {
172 specs.push((String::from_utf8_lossy(&delimiter).into_owned(), strip_tabs));
173 }
174 }
175 specs
176}
177
178fn command_without_heredoc_bodies(command: &str) -> String {
183 use std::collections::VecDeque;
184
185 let mut pending = VecDeque::new();
186 let mut projected = String::with_capacity(command.len());
187 for line in command.split_inclusive('\n') {
188 let content = line.trim_end_matches(['\r', '\n']);
189 if let Some((delimiter, strip_tabs)) = pending.front() {
190 let candidate = if *strip_tabs {
191 content.trim_start_matches('\t')
192 } else {
193 content
194 };
195 if candidate == delimiter {
196 pending.pop_front();
197 }
198 if line.ends_with('\n') {
199 projected.push('\n');
200 }
201 continue;
202 }
203
204 projected.push_str(line);
205 pending.extend(heredoc_specs(content));
206 }
207 projected
208}
209
210fn is_environment_assignment(token: &str) -> bool {
211 let Some((name, _)) = token.split_once('=') else {
212 return false;
213 };
214 !name.is_empty()
215 && name.chars().enumerate().all(|(index, ch)| {
216 ch == '_' || ch.is_ascii_alphanumeric() && (index > 0 || !ch.is_ascii_digit())
217 })
218}
219
220fn executable_basename(program: &str) -> &str {
221 Path::new(program)
222 .file_name()
223 .and_then(|name| name.to_str())
224 .unwrap_or(program)
225}
226
227fn command_start(tokens: &[String]) -> Option<usize> {
228 let mut index = 0;
229 while tokens
230 .get(index)
231 .is_some_and(|token| is_environment_assignment(token))
232 {
233 index += 1;
234 }
235 while tokens
236 .get(index)
237 .is_some_and(|token| matches!(executable_basename(token), "command" | "builtin"))
238 {
239 index += 1;
240 }
241 if tokens
242 .get(index)
243 .is_some_and(|token| executable_basename(token) == "env")
244 {
245 index += 1;
246 while let Some(token) = tokens.get(index) {
247 if token == "--" {
248 index += 1;
249 break;
250 }
251 if is_environment_assignment(token) {
252 index += 1;
253 continue;
254 }
255 if matches!(
256 token.as_str(),
257 "-u" | "--unset" | "-C" | "--chdir" | "-S" | "--split-string"
258 ) {
259 index = index.saturating_add(2);
260 continue;
261 }
262 if token.starts_with('-') {
263 index += 1;
264 continue;
265 }
266 break;
267 }
268 }
269 while tokens
270 .get(index)
271 .is_some_and(|token| matches!(executable_basename(token), "command" | "builtin"))
272 {
273 index += 1;
274 }
275 (index < tokens.len()).then_some(index)
276}
277
278fn shell_script_operand(arguments: &[String]) -> Option<&str> {
279 arguments.iter().enumerate().find_map(|(index, argument)| {
280 let command_flag = argument == "--command"
281 || argument
282 .strip_prefix('-')
283 .filter(|flags| !flags.starts_with('-'))
284 .is_some_and(|flags| flags.contains('c'));
285 command_flag
286 .then(|| arguments.get(index + 1).map(String::as_str))
287 .flatten()
288 })
289}
290
291fn collect_shell_invocations(command: &str, depth: usize, output: &mut Vec<ShellInvocation>) {
292 if depth > MAX_SHELL_INVOCATION_DEPTH {
293 return;
294 }
295 for (segment, _) in split_by_operators(&command_without_heredoc_bodies(command)) {
296 if segment.is_empty() {
297 continue;
298 }
299 let Ok(tokens) = shell_words::split(&segment) else {
300 continue;
301 };
302 let Some(program_index) = command_start(&tokens) else {
303 continue;
304 };
305 let invocation = ShellInvocation {
306 program: tokens[program_index].clone(),
307 arguments: tokens[program_index + 1..].to_vec(),
308 };
309 let program_name = executable_basename(&invocation.program);
310 let nested_script = if matches!(program_name, "sh" | "bash" | "dash" | "ksh" | "zsh") {
311 shell_script_operand(&invocation.arguments).map(str::to_string)
312 } else if program_name == "trap" {
313 invocation
314 .arguments
315 .first()
316 .filter(|body| !body.starts_with('-'))
317 .cloned()
318 } else {
319 None
320 };
321 if !output.contains(&invocation) {
322 output.push(invocation);
323 }
324 if let Some(script) = nested_script {
325 collect_shell_invocations(&script, depth + 1, output);
326 }
327 }
328}
329
330pub fn structural_shell_invocations(command: &str) -> Vec<ShellInvocation> {
335 let mut invocations = Vec::new();
336 collect_shell_invocations(command, 0, &mut invocations);
337 invocations
338}
339
340pub fn approval_floor_reason(command: &str) -> Option<String> {
344 for (segment, _) in split_by_operators(command) {
345 let parts = shell_words::split(&segment).ok()?;
346 for arg in parts.iter().skip(1) {
347 if let Some(sensitive) = aidaemon_policies::credential_path_segment(arg) {
348 return Some(format!(
349 "Command explicitly accesses protected credential path segment: {sensitive}"
350 ));
351 }
352 }
353 }
354 None
355}
356
357pub fn persistence_floor_reason(
365 command: &str,
366 working_dir: Option<&str>,
367 extra: &[String],
368) -> Option<String> {
369 let base = working_dir
370 .map(str::trim)
371 .filter(|dir| std::path::Path::new(dir).is_absolute());
372 let resolve = |word: &str| -> Option<std::path::PathBuf> {
373 let word = word.trim_start_matches(['>', '<', '&', '|']).trim();
374 let word = word
375 .split_once('=')
376 .filter(|(key, _)| key.starts_with('-'))
377 .map_or(word, |(_, value)| value);
378 if word.is_empty() || word.starts_with('-') {
379 return None;
380 }
381 let expanded = shellexpand::tilde(word).into_owned();
382 let path = std::path::PathBuf::from(&expanded);
383 if path.is_absolute() {
384 Some(path)
385 } else {
386 base.map(|base| std::path::Path::new(base).join(&expanded))
387 }
388 };
389 let names = |word: &str| {
391 [word, word.rsplit(['>', '<']).next().unwrap_or(word)]
392 .iter()
393 .filter_map(|word| resolve(word))
394 .any(|path| crate::path_class::is_persistence_path(&path, &[]))
395 };
396 if let Some(path) = extra.iter().find(|path| names(path)) {
397 return Some(format!(
398 "Writes {path}, which runs or is loaded automatically later (persists beyond the task)."
399 ));
400 }
401 if crate::command_effects::command_effects(command).observation_only {
402 return None;
403 }
404 for (segment, _) in split_by_operators(command) {
405 let Ok(parts) = shell_words::split(&segment) else {
406 continue;
407 };
408 if let Some(word) = parts.iter().skip(1).find(|word| names(word)) {
409 return Some(format!(
410 "Command names {word}, which runs or is loaded automatically later (persists beyond the task)."
411 ));
412 }
413 }
414 None
415}
416
417#[cfg(test)]
418mod tests {
419 use super::*;
420
421 #[test]
422 fn a_change_naming_a_persistence_path_asks() {
423 for command in [
424 "echo 'export X=1' >> ~/.zshrc",
425 "echo x>>~/.bashrc",
426 "cp agent.plist ~/Library/LaunchAgents/",
427 "tee /srv/app/.git/hooks/pre-commit < hook",
428 "ln -sf /tmp/x ~/.aidaemon/AGENTS.md",
429 ] {
430 assert!(
431 persistence_floor_reason(command, None, &[]).is_some(),
432 "{command}"
433 );
434 }
435 assert!(
436 persistence_floor_reason("cp hook .git/hooks/pre-push", Some("/srv/app"), &[])
437 .is_some()
438 );
439 assert!(
440 persistence_floor_reason(
441 "make install",
442 None,
443 &["/home/synthetic/.config/systemd/user".to_string()]
444 )
445 .is_some()
446 );
447 for command in ["cat ~/.zshrc", "cargo build", "cp a b", "echo hi > out.txt"] {
448 assert!(
449 persistence_floor_reason(command, Some("/srv/app"), &[]).is_none(),
450 "{command}"
451 );
452 }
453 }
454
455 #[test]
456 fn operator_split_respects_quotes() {
457 assert_eq!(split_by_operators("echo 'a | b' && cargo test").len(), 2);
458 assert_eq!(split_by_operators("grep 'x; y' file").len(), 1);
459 }
460
461 #[test]
462 fn nested_shell_invocations_are_parsed_from_combined_command_flags() {
463 let invocations = structural_shell_invocations(
464 "/bin/sh -lc 'trap '\"'\"'rm -rf -- \"$root\"'\"'\"' EXIT; /opt/homebrew/bin/python3 -m venv \"$root/.venv\"'",
465 );
466 assert!(invocations.iter().any(|invocation| {
467 invocation.program == "/bin/sh"
468 && invocation.arguments.first().is_some_and(|arg| arg == "-lc")
469 }));
470 assert!(invocations.iter().any(|invocation| {
471 invocation.program == "/opt/homebrew/bin/python3"
472 && invocation
473 .arguments
474 .starts_with(&["-m".to_string(), "venv".to_string()])
475 }));
476 }
477
478 #[test]
479 fn environment_wrappers_preserve_the_executed_program_identity() {
480 let invocations = structural_shell_invocations(
481 "MODE=test /usr/bin/env -u TOKEN PATH=/usr/bin command /usr/bin/false",
482 );
483 assert_eq!(
484 invocations,
485 [ShellInvocation {
486 program: "/usr/bin/false".to_string(),
487 arguments: Vec::new(),
488 }]
489 );
490 }
491
492 #[test]
493 fn projection_preserves_redirections_and_pipe_stderr_operators() {
494 assert_eq!(
495 split_by_operators("first 2>&1 & second &>output |& third"),
496 [
497 ("first 2>&1".to_string(), Some("&".to_string())),
498 ("second &>output".to_string(), Some("|&".to_string())),
499 ("third".to_string(), None),
500 ]
501 );
502 }
503
504 #[test]
505 fn heredoc_payload_is_not_projected_as_executable_source() {
506 let invocations = structural_shell_invocations(
507 "python3 <<'PY'\ntarget = Path(root) / 'fabricated'\narchive.write(target)\nPY\n/usr/bin/false",
508 );
509 assert_eq!(
510 invocations,
511 [
512 ShellInvocation {
513 program: "python3".to_string(),
514 arguments: vec!["<<PY".to_string()],
515 },
516 ShellInvocation {
517 program: "/usr/bin/false".to_string(),
518 arguments: Vec::new(),
519 },
520 ]
521 );
522 }
523
524 #[test]
525 fn approval_floor_is_limited_to_explicit_sensitive_paths() {
526 assert!(approval_floor_reason("cat ~/.ssh/id_ed25519").is_some());
527 assert!(approval_floor_reason("source .env.local").is_some());
528 assert!(approval_floor_reason("cat .env.example").is_none());
529 assert!(approval_floor_reason("echo $(date)").is_none());
530 assert!(approval_floor_reason("python3 script.py").is_none());
531 assert!(approval_floor_reason("cat password_reset.txt").is_none());
532 }
533}