1use crate::executor::{CommandCategory, CommandExecutor, CommandInvocation, CommandOutput, ShellKind};
2use crate::policy::CommandPolicy;
3use anyhow::{Context, Result, anyhow, bail};
4use path_clean::PathClean;
5use shell_escape::escape;
6use std::fs;
7use std::path::{Path, PathBuf};
8use vtcode_commons::{WorkspacePaths, canonicalize};
9
10pub struct BashRunner<E, P> {
11 executor: E,
12 policy: P,
13 workspace_root: PathBuf,
14 working_dir: PathBuf,
15 shell_kind: ShellKind,
16}
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub struct RmOptions {
25 pub recursive: bool,
27 pub force: bool,
29}
30
31impl<E, P> BashRunner<E, P>
32where
33 E: CommandExecutor,
34 P: CommandPolicy,
35{
36 pub fn new(workspace_root: PathBuf, executor: E, policy: P) -> Result<Self> {
37 if !workspace_root.exists() {
38 bail!("workspace root `{}` does not exist", workspace_root.display());
39 }
40
41 let canonical_root = canonicalize(&workspace_root)
42 .with_context(|| format!("failed to canonicalize `{}`", workspace_root.display()))?;
43
44 Ok(Self {
45 executor,
46 policy,
47 workspace_root: canonical_root.clone(),
48 working_dir: canonical_root,
49 shell_kind: default_shell_kind(),
50 })
51 }
52
53 pub fn from_workspace_paths<W>(paths: &W, executor: E, policy: P) -> Result<Self>
54 where
55 W: WorkspacePaths,
56 {
57 Self::new(paths.workspace_root().to_path_buf(), executor, policy)
58 }
59
60 pub fn workspace_root(&self) -> &Path {
61 &self.workspace_root
62 }
63
64 fn working_dir(&self) -> &Path {
65 &self.working_dir
66 }
67
68 pub fn shell_kind(&self) -> ShellKind {
69 self.shell_kind
70 }
71
72 fn resolve_canonical_path(&self, path: &Path) -> Result<PathBuf> {
74 canonicalize(path).with_context(|| format!("failed to canonicalize `{}`", path.display()))
75 }
76
77 pub fn cd(&mut self, path: &str) -> Result<()> {
78 let candidate = self.resolve_path(path)?;
79 if !candidate.exists() {
80 bail!("directory `{}` does not exist", candidate.display());
81 }
82 if !candidate.is_dir() {
83 bail!("path `{}` is not a directory", candidate.display());
84 }
85
86 let canonical = self.resolve_canonical_path(&candidate)?;
87
88 self.ensure_within_workspace(&canonical)?;
89
90 let invocation = CommandInvocation::new(
91 self.shell_kind,
92 format!("cd {}", format_path(self.shell_kind, &canonical)),
93 CommandCategory::ChangeDirectory,
94 canonical.clone(),
95 )
96 .with_paths(vec![canonical.clone()]);
97
98 self.policy.check(&invocation)?;
99 self.working_dir = canonical;
100 Ok(())
101 }
102
103 pub fn ls(&self, path: Option<&str>, show_hidden: bool) -> Result<String> {
104 let target = path
105 .map(|p| self.resolve_existing_path(p))
106 .transpose()?
107 .unwrap_or_else(|| self.working_dir.clone());
108
109 let command = match self.shell_kind {
110 ShellKind::Unix => ShellCommand::new(ShellKind::Unix)
111 .verb("ls")
112 .flag(if show_hidden { "la" } else { "l" })
113 .value(format_path(ShellKind::Unix, &target))
114 .build(),
115 ShellKind::Windows => ShellCommand::new(ShellKind::Windows)
116 .verb("Get-ChildItem")
117 .flag_if(show_hidden, "Force")
118 .named("LiteralPath", format_path(ShellKind::Windows, &target))
119 .build(),
120 };
121
122 let invocation =
123 CommandInvocation::new(self.shell_kind, command, CommandCategory::ListDirectory, self.working_dir.clone())
124 .with_paths(vec![target])
125 .with_show_hidden(show_hidden);
126
127 let output = self.expect_success(invocation)?;
128 Ok(output.stdout)
129 }
130
131 pub fn pwd(&self) -> Result<String> {
132 let command = match self.shell_kind {
133 ShellKind::Unix => ShellCommand::new(ShellKind::Unix).verb("pwd").build(),
134 ShellKind::Windows => ShellCommand::new(ShellKind::Windows).verb("Get-Location").build(),
135 };
136 let invocation =
137 CommandInvocation::new(self.shell_kind, command, CommandCategory::PrintDirectory, self.working_dir.clone());
138 self.policy.check(&invocation)?;
139 Ok(self.working_dir.to_string_lossy().into_owned())
140 }
141
142 pub fn mkdir(&self, path: &str, parents: bool) -> Result<()> {
143 let target = self.resolve_path(path)?;
144 self.ensure_mutation_target_within_workspace(&target)?;
145
146 let command = match self.shell_kind {
147 ShellKind::Unix => ShellCommand::new(ShellKind::Unix)
148 .verb("mkdir")
149 .flag_if(parents, "p")
150 .value(format_path(ShellKind::Unix, &target))
151 .build(),
152 ShellKind::Windows => {
153 let target = format_path(ShellKind::Windows, &target);
154 let validate = if parents {
155 ""
156 } else {
157 "if ([System.IO.Directory]::Exists($p)) { throw 'Directory already exists' }; if (-not [System.IO.Directory]::Exists([System.IO.Path]::GetDirectoryName($p))) { throw 'Parent directory does not exist' }; "
158 };
159 format!("$p = {target}; {validate}[void][System.IO.Directory]::CreateDirectory($p)")
160 }
161 };
162
163 let invocation = CommandInvocation::new(
164 self.shell_kind,
165 command,
166 CommandCategory::CreateDirectory,
167 self.working_dir.clone(),
168 )
169 .with_paths(vec![target])
170 .with_create_parents(parents);
171
172 self.expect_success(invocation).map(|_| ())
173 }
174
175 pub fn rm(&self, path: &str, recursive: bool, force: bool) -> Result<()> {
176 self.rm_with_options(path, RmOptions { recursive, force })
177 }
178
179 pub fn rm_with_options(&self, path: &str, options: RmOptions) -> Result<()> {
181 let target = self.resolve_path(path)?;
182 let target_canonical = if target.exists() {
187 Some(self.resolve_canonical_path(&target)?)
188 } else {
189 None
190 };
191 if let Some(canonical) = &target_canonical {
192 self.ensure_not_workspace_root(canonical)?;
193 }
194 self.ensure_mutation_target_within_workspace(&target)?;
195
196 let command = match self.shell_kind {
197 ShellKind::Unix => ShellCommand::new(ShellKind::Unix)
198 .verb("rm")
199 .flag_if(options.recursive, "r")
200 .flag_if(options.force, "f")
201 .value(format_path(ShellKind::Unix, &target))
202 .build(),
203 ShellKind::Windows => ShellCommand::new(ShellKind::Windows)
204 .verb("Remove-Item")
205 .flag_if(options.recursive, "Recurse")
206 .flag_if(options.force, "Force")
207 .named("LiteralPath", format_path(ShellKind::Windows, &target))
208 .build(),
209 };
210
211 let invocation =
212 CommandInvocation::new(self.shell_kind, command, CommandCategory::Remove, self.working_dir.clone())
213 .with_paths(vec![target])
214 .with_recursive(options.recursive);
215
216 self.expect_success(invocation).map(|_| ())
217 }
218
219 pub fn cp(&self, source: &str, dest: &str, recursive: bool) -> Result<()> {
220 let source_path = self.resolve_existing_path(source)?;
221 let dest_path = self.resolve_path(dest)?;
222 self.ensure_mutation_target_within_workspace(&dest_path)?;
223
224 let command = match self.shell_kind {
225 ShellKind::Unix => ShellCommand::new(ShellKind::Unix)
226 .verb("cp")
227 .flag_if(recursive, "r")
228 .value(format_path(ShellKind::Unix, &source_path))
229 .value(format_path(ShellKind::Unix, &dest_path))
230 .build(),
231 ShellKind::Windows => ShellCommand::new(ShellKind::Windows)
232 .verb("Copy-Item")
233 .named("LiteralPath", format_path(ShellKind::Windows, &source_path))
234 .named("Destination", format_path(ShellKind::Windows, &dest_path))
235 .flag_if(recursive, "Recurse")
236 .build(),
237 };
238
239 let invocation =
240 CommandInvocation::new(self.shell_kind, command, CommandCategory::Copy, self.working_dir.clone())
241 .with_paths(vec![source_path, dest_path])
242 .with_recursive(recursive);
243
244 self.expect_success(invocation).map(|_| ())
245 }
246
247 pub fn mv(&self, source: &str, dest: &str) -> Result<()> {
248 let source_path = self.resolve_existing_path(source)?;
249 let dest_path = self.resolve_path(dest)?;
250 self.ensure_mutation_target_within_workspace(&dest_path)?;
251
252 let command = match self.shell_kind {
253 ShellKind::Unix => ShellCommand::new(ShellKind::Unix)
254 .verb("mv")
255 .value(format_path(ShellKind::Unix, &source_path))
256 .value(format_path(ShellKind::Unix, &dest_path))
257 .build(),
258 ShellKind::Windows => ShellCommand::new(ShellKind::Windows)
259 .verb("Move-Item")
260 .named("LiteralPath", format_path(ShellKind::Windows, &source_path))
261 .named("Destination", format_path(ShellKind::Windows, &dest_path))
262 .build(),
263 };
264
265 let invocation =
266 CommandInvocation::new(self.shell_kind, command, CommandCategory::Move, self.working_dir.clone())
267 .with_paths(vec![source_path, dest_path]);
268
269 self.expect_success(invocation).map(|_| ())
270 }
271
272 pub fn grep(&self, pattern: &str, path: Option<&str>, recursive: bool) -> Result<String> {
273 let target = path
274 .map(|p| self.resolve_existing_path(p))
275 .transpose()?
276 .unwrap_or_else(|| self.working_dir.clone());
277
278 let command = match self.shell_kind {
279 ShellKind::Unix => ShellCommand::new(ShellKind::Unix)
280 .verb("grep")
281 .flag("n")
282 .flag_if(recursive, "r")
283 .value(format_pattern(ShellKind::Unix, pattern))
284 .value(format_path(ShellKind::Unix, &target))
285 .build(),
286 ShellKind::Windows if recursive => format!(
287 "Get-ChildItem -LiteralPath {} -File -Recurse | Select-String -Pattern {} -SimpleMatch",
288 format_path(ShellKind::Windows, &target),
289 format_pattern(ShellKind::Windows, pattern)
290 ),
291 ShellKind::Windows => ShellCommand::new(ShellKind::Windows)
292 .verb("Select-String")
293 .named("Pattern", format_pattern(ShellKind::Windows, pattern))
294 .named("LiteralPath", format_path(ShellKind::Windows, &target))
295 .value("-SimpleMatch")
296 .build(),
297 };
298
299 let invocation =
300 CommandInvocation::new(self.shell_kind, command, CommandCategory::Search, self.working_dir.clone())
301 .with_paths(vec![target]);
302
303 let output = self.execute_invocation(invocation)?;
304 if output.status.success() {
305 return Ok(output.stdout);
306 }
307
308 if output.stdout.trim().is_empty() && output.stderr.trim().is_empty() {
309 Ok(String::new())
310 } else {
311 Err(anyhow!(
312 "search command failed: {}",
313 if output.stderr.trim().is_empty() {
314 output.stdout
315 } else {
316 output.stderr
317 }
318 ))
319 }
320 }
321
322 fn execute_invocation(&self, invocation: CommandInvocation) -> Result<CommandOutput> {
323 self.policy.check(&invocation)?;
324 self.executor.execute(&invocation)
325 }
326
327 fn expect_success(&self, invocation: CommandInvocation) -> Result<CommandOutput> {
328 let output = self.execute_invocation(invocation.clone())?;
329 if output.status.success() {
330 Ok(output)
331 } else {
332 Err(anyhow!(
333 "command `{}` failed: {}",
334 invocation.command,
335 if output.stderr.trim().is_empty() {
336 output.stdout
337 } else {
338 output.stderr
339 }
340 ))
341 }
342 }
343
344 fn resolve_existing_path(&self, raw: &str) -> Result<PathBuf> {
345 let path = self.resolve_path(raw)?;
346 if !path.exists() {
347 bail!("path `{}` does not exist", path.display());
348 }
349
350 let canonical = self.resolve_canonical_path(&path)?;
351
352 self.ensure_within_workspace(&canonical)?;
353 Ok(canonical)
354 }
355
356 fn resolve_path(&self, raw: &str) -> Result<PathBuf> {
357 if raw.trim().is_empty() {
362 bail!("path must not be empty");
363 }
364 let candidate = Path::new(raw);
365 let joined = if candidate.is_absolute() {
366 candidate.to_path_buf()
367 } else {
368 self.working_dir.join(candidate)
369 };
370 Ok(joined.clean())
371 }
372
373 fn ensure_mutation_target_within_workspace(&self, candidate: &Path) -> Result<()> {
374 if let Ok(metadata) = fs::symlink_metadata(candidate)
375 && metadata.file_type().is_symlink()
376 {
377 let canonical = self.resolve_canonical_path(candidate)?;
378 return self.ensure_within_workspace(&canonical);
379 }
380
381 if candidate.exists() {
382 let canonical = self.resolve_canonical_path(candidate)?;
383 self.ensure_within_workspace(&canonical)
384 } else {
385 let parent = self.canonicalize_existing_parent(candidate)?;
386 self.ensure_within_workspace(&parent)
387 }
388 }
389
390 fn ensure_not_workspace_root(&self, canonical_candidate: &Path) -> Result<()> {
396 if canonical_candidate == self.workspace_root {
397 bail!("refusing to operate on the workspace root itself (`{}`)", canonical_candidate.display());
398 }
399 Ok(())
400 }
401
402 fn canonicalize_existing_parent(&self, candidate: &Path) -> Result<PathBuf> {
403 let mut current = candidate.parent();
404 while let Some(path) = current {
405 if path.exists() {
406 return self.resolve_canonical_path(path);
407 }
408 current = path.parent();
409 }
410
411 Ok(self.working_dir.clone())
412 }
413
414 fn ensure_within_workspace(&self, candidate: &Path) -> Result<()> {
415 vtcode_commons::paths::ensure_path_within_workspace(candidate, &self.workspace_root).map_err(|error| {
418 error.context(format!(
419 "path `{}` escapes workspace root `{}`",
420 candidate.display(),
421 self.workspace_root.display()
422 ))
423 })?;
424 Ok(())
425 }
426}
427
428fn default_shell_kind() -> ShellKind {
429 if cfg!(windows) {
430 ShellKind::Windows
431 } else {
432 ShellKind::Unix
433 }
434}
435
436fn join_command(parts: Vec<String>) -> String {
437 parts.into_iter().filter(|part| !part.is_empty()).collect::<Vec<_>>().join(" ")
438}
439
440fn format_path(shell: ShellKind, path: &Path) -> String {
441 match shell {
442 ShellKind::Unix => escape(path.to_string_lossy()).into_owned(),
443 ShellKind::Windows => powershell_data(&path.to_string_lossy()),
444 }
445}
446
447fn format_pattern(shell: ShellKind, pattern: &str) -> String {
448 match shell {
449 ShellKind::Unix => escape(pattern.into()).into_owned(),
450 ShellKind::Windows => powershell_data(pattern),
451 }
452}
453
454fn powershell_data(value: &str) -> String {
457 let bytes = value.as_bytes().iter().map(u8::to_string).collect::<Vec<_>>().join(",");
458 format!("([System.Text.Encoding]::UTF8.GetString([byte[]]@({bytes})))")
459}
460
461struct ShellCommand {
467 shell: ShellKind,
468 parts: Vec<String>,
469}
470
471impl ShellCommand {
472 fn new(shell: ShellKind) -> Self {
473 Self { shell, parts: Vec::new() }
474 }
475
476 fn verb(mut self, name: &str) -> Self {
478 self.parts.push(name.to_string());
479 self
480 }
481
482 fn flag(mut self, name: &str) -> Self {
484 self.parts.push(format!("-{name}"));
485 self
486 }
487
488 fn flag_if(mut self, condition: bool, name: &str) -> Self {
490 if condition {
491 self.parts.push(format!("-{name}"));
492 }
493 self
494 }
495
496 fn named(mut self, name: &str, value: impl Into<String>) -> Self {
500 let v = value.into();
501 let token = match self.shell {
502 ShellKind::Unix => v,
503 ShellKind::Windows => format!("-{name} {v}"),
504 };
505 self.parts.push(token);
506 self
507 }
508
509 fn value(mut self, value: impl Into<String>) -> Self {
511 self.parts.push(value.into());
512 self
513 }
514
515 fn build(self) -> String {
516 join_command(self.parts)
517 }
518}
519
520#[cfg(test)]
521mod tests {
522 use super::*;
523 use crate::executor::{CommandInvocation, CommandOutput, CommandStatus};
524 use crate::policy::AllowAllPolicy;
525 use assert_fs::TempDir;
526 use std::sync::{Arc, Mutex};
527
528 #[derive(Clone, Default)]
529 struct RecordingExecutor {
530 invocations: Arc<Mutex<Vec<CommandInvocation>>>,
531 }
532
533 impl CommandExecutor for RecordingExecutor {
534 fn execute(&self, invocation: &CommandInvocation) -> Result<CommandOutput> {
535 self.invocations
536 .lock()
537 .map_err(|e| anyhow!("executor lock poisoned: {e}"))?
538 .push(invocation.clone());
539 Ok(CommandOutput {
540 status: CommandStatus::new(true, Some(0)),
541 stdout: String::new(),
542 stderr: String::new(),
543 })
544 }
545 }
546
547 #[test]
548 fn powershell_arguments_are_data_and_paths_are_literal() -> Result<()> {
549 let dir = TempDir::new()?;
550 let source = "item[1]’ ; Write-Output INJECTED #.txt";
551 fs::write(dir.path().join(source), "content")?;
552 let executor = RecordingExecutor::default();
553 let mut runner = BashRunner::new(dir.path().to_path_buf(), executor.clone(), AllowAllPolicy)?;
554 runner.shell_kind = ShellKind::Windows;
555 runner.ls(Some(source), false)?;
556 runner.cp(source, "copy[2].txt", false)?;
557 runner.mv(source, "move[2].txt")?;
558 runner.rm(source, false, false)?;
559 runner.mkdir("new[3]", true)?;
560 runner.grep("a’ ; Write-Output INJECTED #", Some(source), false)?;
561 runner.grep("needle", Some(source), true)?;
562
563 let invocations = executor.invocations.lock().expect("invocations");
564 assert_eq!(invocations.len(), 7);
565 for invocation in invocations.iter() {
566 assert!(!invocation.command.contains("INJECTED"), "{}", invocation.command);
567 }
568 for index in [0, 1, 2, 3, 5, 6] {
569 assert!(invocations[index].command.contains("-LiteralPath"), "{}", invocations[index].command);
570 }
571 assert!(invocations[4].command.contains("[System.IO.Directory]::CreateDirectory($p)"));
572 assert!(invocations[4].create_parents);
573 assert!(invocations[6].command.contains("-File -Recurse | Select-String"));
574 assert_eq!(powershell_data("A’'"), "([System.Text.Encoding]::UTF8.GetString([byte[]]@(65,226,128,153,39)))");
575 Ok(())
576 }
577
578 #[cfg(feature = "pure-rust")]
579 #[test]
580 fn powershell_mkdir_parent_option_reaches_pure_rust_executor() -> Result<()> {
581 let dir = TempDir::new()?;
582 let mut runner =
583 BashRunner::new(dir.path().to_path_buf(), crate::executor::PureRustCommandExecutor, AllowAllPolicy)?;
584 runner.shell_kind = ShellKind::Windows;
585 assert!(runner.mkdir("missing/child", false).is_err());
586 runner.mkdir("missing/child", true)?;
587 assert!(dir.path().join("missing/child").is_dir());
588 Ok(())
589 }
590
591 #[cfg(all(feature = "pure-rust", unix))]
592 #[test]
593 fn recursive_copy_rejects_escaping_symlinks_on_both_sides() -> Result<()> {
594 use std::os::unix::fs::symlink;
595
596 let dir = TempDir::new()?;
597 let outside = TempDir::new()?;
598 let secret = outside.path().join("secret.txt");
599 fs::write(&secret, "classified")?;
600 let victim = outside.path().join("victim.txt");
601 fs::write(&victim, "untouched")?;
602
603 let source = dir.path().join("source");
604 fs::create_dir_all(source.join("real"))?;
605 fs::write(source.join("real").join("file.txt"), "data")?;
606 symlink(&secret, source.join("escape"))?;
607
608 let runner =
609 BashRunner::new(dir.path().to_path_buf(), crate::executor::PureRustCommandExecutor, AllowAllPolicy)?;
610 let error = runner.cp("source", "copy", true).expect_err("escaping source link must fail");
611 assert!(format!("{error:#}").contains("escaping"), "{error:#}");
612 assert!(!dir.path().join("copy").join("escape").exists());
613
614 fs::remove_file(source.join("escape"))?;
616 symlink(source.join("real").join("file.txt"), source.join("inner"))?;
617 runner.cp("source", "copy", true)?;
618 assert_eq!(fs::read_to_string(dir.path().join("copy").join("inner"))?, "data");
619
620 let dest = dir.path().join("planted");
623 fs::create_dir_all(&dest)?;
624 symlink(&victim, dest.join("inner"))?;
625 symlink(outside.path(), dest.join("real"))?;
626 let error = runner
627 .cp("source", "planted", true)
628 .expect_err("escaping destination link must fail");
629 assert!(format!("{error:#}").contains("escaping"), "{error:#}");
630 assert_eq!(fs::read_to_string(&victim)?, "untouched");
631 assert!(!outside.path().join("file.txt").exists());
632 Ok(())
633 }
634
635 #[test]
636 fn cd_updates_working_directory() -> Result<()> {
637 let dir = TempDir::new()?;
638 let nested = dir.path().join("nested");
639 fs::create_dir(&nested)?;
640 let runner = BashRunner::new(dir.path().to_path_buf(), RecordingExecutor::default(), AllowAllPolicy);
641 let mut runner = runner?;
642 runner.cd("nested")?;
643 let expected = canonicalize(&nested)?;
645 assert_eq!(runner.working_dir(), expected);
646 Ok(())
647 }
648
649 #[test]
650 fn rm_rejects_empty_path_instead_of_targeting_workspace_root() -> Result<()> {
651 let dir = TempDir::new()?;
652 let executor = RecordingExecutor::default();
653 let runner = BashRunner::new(dir.path().to_path_buf(), executor.clone(), AllowAllPolicy)?;
654
655 for empty in ["", " ", "."] {
656 let result = runner.rm(empty, true, true);
657 assert!(result.is_err(), "rm({empty:?}) must be rejected");
658 }
659 assert!(
660 executor.invocations.lock().expect("invocations lock").is_empty(),
661 "no command must be built for empty paths"
662 );
663 Ok(())
664 }
665
666 #[test]
667 fn rm_with_options_matches_positional_rm() -> Result<()> {
668 let dir = TempDir::new()?;
669 let executor = RecordingExecutor::default();
670 let runner = BashRunner::new(dir.path().to_path_buf(), executor.clone(), AllowAllPolicy)?;
671 let target = dir.path().join("named.txt");
672 fs::write(&target, "named")?;
673 runner.rm("named.txt", true, true)?;
675 runner.rm_with_options("named.txt", RmOptions { recursive: true, force: true })?;
676 runner.rm_with_options("named.txt", RmOptions::default())?;
677 let invocations = executor.invocations.lock().expect("invocations lock");
678 assert_eq!(invocations.len(), 3);
679 assert_eq!(invocations[0].command, invocations[1].command);
680 let (recursive_flag, force_flag) = match runner.shell_kind() {
681 ShellKind::Unix => ("-r", "-f"),
682 ShellKind::Windows => ("-Recurse", "-Force"),
683 };
684 assert!(
685 invocations[0].command.contains(recursive_flag),
686 "recursive flag missing: {}",
687 invocations[0].command
688 );
689 assert!(invocations[0].command.contains(force_flag), "force flag missing: {}", invocations[0].command);
690 assert!(!invocations[2].command.contains(recursive_flag));
691 assert!(!invocations[2].command.contains(force_flag));
692 Ok(())
693 }
694
695 #[test]
696 fn rm_rejects_workspace_root_via_parent_traversal_and_absolute_alias() -> Result<()> {
697 let dir = TempDir::new()?;
698 let executor = RecordingExecutor::default();
699 let runner = BashRunner::new(dir.path().to_path_buf(), executor.clone(), AllowAllPolicy)?;
700 let mut runner = runner;
701 let canonical_root = runner.working_dir().to_path_buf();
702
703 fs::create_dir_all(runner.working_dir().join("sub"))?;
705 runner.cd("sub")?;
706 assert!(runner.rm("..", true, true).is_err(), "rm('..') from sub must be rejected");
707 let alias = dir.path().to_path_buf();
709 if alias != canonical_root {
710 assert!(
711 runner.rm(&alias.to_string_lossy(), true, true).is_err(),
712 "rm via non-canonical absolute alias must be rejected"
713 );
714 }
715 assert!(
717 runner.rm(&canonical_root.to_string_lossy(), true, true).is_err(),
718 "rm on the canonical root must be rejected"
719 );
720 let link = runner.working_dir().join("root-link");
722 #[cfg(unix)]
723 std::os::unix::fs::symlink(&canonical_root, &link).expect("create root symlink");
724 #[cfg(unix)]
725 assert!(
726 runner.rm(&link.to_string_lossy(), true, true).is_err(),
727 "rm through a symlink to the root must be rejected"
728 );
729 #[cfg(not(unix))]
730 let _ = &link;
731 assert!(
732 executor.invocations.lock().expect("invocations lock").is_empty(),
733 "no command must be built for root targets"
734 );
735 Ok(())
736 }
737
738 #[test]
739 fn mkdir_records_invocation() -> Result<()> {
740 let dir = TempDir::new()?;
741 let executor = RecordingExecutor::default();
742 let runner = BashRunner::new(dir.path().to_path_buf(), executor.clone(), AllowAllPolicy);
743 runner?.mkdir("new_dir", true)?;
744 let invocations = executor
745 .invocations
746 .lock()
747 .map_err(|e| anyhow!("executor lock poisoned: {e}"))?;
748 assert_eq!(invocations.len(), 1);
749 assert_eq!(invocations[0].category, CommandCategory::CreateDirectory);
750 Ok(())
751 }
752 #[cfg(unix)]
753 #[test]
754 fn symlink_retargeting_cannot_reuse_an_earlier_authorization() -> Result<()> {
755 let root = TempDir::new()?;
756 let outside = TempDir::new()?;
757 let inside = root.path().join("inside");
758 fs::create_dir(&inside)?;
759 let link = root.path().join("link");
760 std::os::unix::fs::symlink(&inside, &link)?;
761 let executor = RecordingExecutor::default();
762 let runner = BashRunner::new(root.path().to_path_buf(), executor.clone(), AllowAllPolicy)?;
763 runner.ls(Some("link"), false)?;
764 fs::remove_file(&link)?;
765 std::os::unix::fs::symlink(outside.path(), &link)?;
766 assert!(runner.ls(Some("link"), false).is_err());
767 assert!(runner.mkdir("link/new-directory", false).is_err());
768 assert_eq!(executor.invocations.lock().expect("invocations lock").len(), 1);
769 Ok(())
770 }
771
772 #[cfg(unix)]
773 #[test]
774 fn shell_command_keeps_metacharacters_inside_a_single_literal_argument() -> Result<()> {
775 let root = TempDir::new()?;
776 let executor = RecordingExecutor::default();
777 let runner = BashRunner::new(root.path().to_path_buf(), executor.clone(), AllowAllPolicy)?;
778 let filename = "literal;$(echo injected)'file";
779 runner.mkdir(filename, false)?;
780 let invocations = executor.invocations.lock().expect("invocations lock");
781 let command = &invocations[0].command;
782 let output = std::process::Command::new("sh").arg("-c").arg(command).output()?;
783 assert!(output.status.success());
784 assert!(runner.workspace_root().join(filename).is_dir());
785 Ok(())
786 }
787}