返回 CodeWhale
shell_dispatcher.rs
根目录 / crates / sandbox / src / shell_dispatcher.rs
1 //! Shell abstraction layer for Codewhale.
2 //!
3 //! Detects the user's shell at startup and provides a single entry point for
4 //! all command execution. Codewhale never calls `Command::new("cmd")` (or
5 //! `"sh"`, `"pwsh"`, ...) directly — it asks the [`ShellDispatcher`] to build
6 //! a correctly configured [`std::process::Command`].
7 //!
8 //! ## Responsibilities
9 //!
10 //! 1. **Shell detection** — find the user's actual shell (PowerShell, pwsh,
11 //! bash via WSL / Git Bash, cmd.exe fallback on Windows, /bin/sh on Unix).
12 //! On Windows, prefer PowerShell 7 (`pwsh`) over Windows PowerShell 5.1.
13 //! 2. **Quoting correctness** — each shell's argument-passing convention is
14 //! respected so quoted strings survive the spawn boundary intact.
15 //! 3. **PowerShell safety** — non-interactive flags, temporary `.ps1` files
16 //! for multiline scripts, explicit native `$LASTEXITCODE` capture, and a
17 //! process-scoped execution-policy bypass so a machine whose local policy
18 //! is `Restricted`/`AllSigned` does not refuse the tool's own temp script
19 //! (issue #6745).
20 //!
21 //! ## Known limitations
22 //!
23 //! - A Group Policy execution policy (`Get-ExecutionPolicy -List` rows
24 //! `MachinePolicy`/`UserPolicy`) outranks the process scope, so on such a
25 //! machine multiline commands (the temp `-File` form) are still refused and
26 //! PowerShell's own refusal is returned as the command's error. This is
27 //! deliberate: the dispatcher does not re-send the script through
28 //! `-EncodedCommand` to get around an administrator-enforced policy.
29 //! - The process scope covers the whole child: scripts that a command itself
30 //! invokes run under the same bypass. The shell tool's approval and sandbox
31 //! policy, not the execution policy, is what gates what may run.
32 //! 4. **Terminal state** — foreground shell execution saves and restores
33 //! crossterm raw-mode so the TUI input pipeline is not broken after a
34 //! child process exits (issue #1690).
35
36 use std::fs::OpenOptions;
37 use std::io::Write;
38 #[cfg(windows)]
39 use std::os::windows::process::CommandExt;
40 use std::path::Path;
41 use std::process::Command;
42 use std::sync::Mutex;
43
44 static LOG_MUTEX: Mutex<()> = Mutex::new(());
45
46 // ---------------------------------------------------------------------------
47 // Shell kind
48 // ---------------------------------------------------------------------------
49
50 /// The concrete shell that the dispatcher will use.
51 #[derive(Debug, Clone, PartialEq, Eq)]
52 pub enum ShellKind {
53 /// PowerShell 7+ (`pwsh.exe`).
54 Pwsh,
55 /// Windows PowerShell 5.1 (`powershell.exe`).
56 WindowsPowerShell,
57 /// Command Prompt (`cmd.exe`).
58 Cmd,
59 /// Unix `/bin/sh` fallback.
60 Sh,
61 /// Bash — detected via `$SHELL` on WSL/Git Bash, or constructed explicitly.
62 Bash,
63 /// The exact shell executable selected by Unix `$SHELL`.
64 Custom { binary: String, flag: String },
65 }
66
67 impl ShellKind {
68 /// Binary name for the shell. Appends `.exe` on Windows where needed.
69 pub fn binary(&self) -> &str {
70 match self {
71 #[cfg(windows)]
72 ShellKind::Pwsh => "pwsh.exe",
73 #[cfg(not(windows))]
74 ShellKind::Pwsh => "pwsh",
75
76 #[cfg(windows)]
77 ShellKind::WindowsPowerShell => "powershell.exe",
78 #[cfg(not(windows))]
79 ShellKind::WindowsPowerShell => "powershell",
80
81 #[cfg(windows)]
82 ShellKind::Cmd => "cmd.exe",
83 #[cfg(not(windows))]
84 ShellKind::Cmd => "cmd",
85
86 #[cfg(windows)]
87 ShellKind::Sh => "sh",
88 #[cfg(not(windows))]
89 ShellKind::Sh => "/bin/sh",
90 ShellKind::Bash => "bash",
91 ShellKind::Custom { binary, .. } => binary,
92 }
93 }
94
95 /// Flag that tells the shell to execute the following argument as a
96 /// command string.
97 pub fn command_flag(&self) -> &str {
98 match self {
99 ShellKind::Pwsh | ShellKind::WindowsPowerShell => "-NoProfile",
100 ShellKind::Cmd => "/C",
101 ShellKind::Sh | ShellKind::Bash => "-c",
102 ShellKind::Custom { flag, .. } => flag,
103 }
104 }
105
106 /// Whether this shell needs an extra `-Command` flag after the profile
107 /// flag (PowerShell-specific). Only exercised by shell-flag unit tests.
108 #[cfg(test)]
109 pub fn needs_command_flag(&self) -> bool {
110 matches!(self, ShellKind::Pwsh | ShellKind::WindowsPowerShell)
111 }
112
113 /// Returns true when this is a PowerShell-family shell.
114 pub fn is_powershell(&self) -> bool {
115 match self {
116 ShellKind::Pwsh | ShellKind::WindowsPowerShell => true,
117 ShellKind::Custom { binary, .. } => Path::new(binary)
118 .file_name()
119 .and_then(|name| name.to_str())
120 .is_some_and(|name| {
121 let name = name.to_ascii_lowercase();
122 name.contains("pwsh") || name.contains("powershell")
123 }),
124 ShellKind::Cmd | ShellKind::Sh | ShellKind::Bash => false,
125 }
126 }
127
128 pub fn is_zsh(&self) -> bool {
129 matches!(self, ShellKind::Custom { binary, .. } if Path::new(binary)
130 .file_stem()
131 .and_then(|name| name.to_str())
132 .is_some_and(|name| name.eq_ignore_ascii_case("zsh")))
133 }
134 }
135
136 /// Multiline, nested-quote, or non-ASCII PowerShell scripts are safer as a
137 /// temporary `-File` script than as a single `-Command` string.
138 fn powershell_prefers_script_file(shell_command: &str) -> bool {
139 shell_command.contains('\n')
140 || shell_command.contains('\r')
141 || !shell_command.is_ascii()
142 || shell_command.matches('"').count() >= 4
143 || shell_command.contains("'''")
144 || shell_command.contains("@'")
145 || shell_command.contains("@\"")
146 }
147
148 /// Flags shared by every PowerShell invocation this dispatcher builds.
149 ///
150 /// `-ExecutionPolicy Bypass` matters for the temp `.ps1` form: script files are
151 /// subject to the execution policy (the Windows client default is
152 /// `Restricted`), so without it a stock or hardened machine refuses a script
153 /// this tool wrote itself before a single statement runs. The parameter only
154 /// sets the *process* scope — no administrator rights, no persisted change, the
155 /// user's own shells are untouched — and it is applied to both forms so a
156 /// command behaves the same whether it travels as `-Command` or `-File`.
157 /// Group Policy scopes still take precedence; see the module's known
158 /// limitations.
159 ///
160 /// `CODEWHALE_POWERSHELL_EXECUTION_POLICY=inherit` omits the flag so the
161 /// machine/user policy applies instead (#6745). Unset, `bypass`, or any other
162 /// value keeps the default.
163 fn powershell_base_args() -> Vec<String> {
164 powershell_base_args_for_policy(
165 std::env::var(POWERSHELL_EXECUTION_POLICY_ENV)
166 .ok()
167 .as_deref(),
168 )
169 }
170
171 /// Environment variable that opts out of the process-scope policy bypass.
172 const POWERSHELL_EXECUTION_POLICY_ENV: &str = "CODEWHALE_POWERSHELL_EXECUTION_POLICY";
173
174 /// [`powershell_base_args`] with the opt-out value passed in, so the decision
175 /// is testable without touching the process environment.
176 fn powershell_base_args_for_policy(setting: Option<&str>) -> Vec<String> {
177 let mut args = vec![
178 "-NoLogo".to_string(),
179 "-NoProfile".to_string(),
180 "-NonInteractive".to_string(),
181 ];
182 if !setting.is_some_and(|value| value.trim().eq_ignore_ascii_case("inherit")) {
183 args.push("-ExecutionPolicy".to_string());
184 args.push("Bypass".to_string());
185 }
186 args
187 }
188
189 /// Wrap a model/user PowerShell command so native program failures surface
190 /// through `$LASTEXITCODE` without using `Invoke-Expression`.
191 fn powershell_exit_aware_command(shell_command: &str) -> String {
192 // Keep simple expressions as-is; only wrap when the payload looks like it
193 // may invoke a native executable (contains a path or known separators).
194 if shell_command.trim().is_empty() {
195 return shell_command.to_string();
196 }
197 // The exit-code check goes on its own line: a trailing unquoted `#`
198 // comment in the payload would otherwise swallow a `;`-joined check to
199 // end-of-line and silently report success for failing native commands.
200 // `-Command` accepts embedded newlines inside one argv string.
201 format!(
202 "$ErrorActionPreference = 'Continue'; {shell_command}\nif ($null -ne $LASTEXITCODE -and $LASTEXITCODE -ne 0) {{ exit $LASTEXITCODE }}"
203 )
204 }
205
206 /// Tail appended to every temp `-File` script: capture the native exit code,
207 /// remove the script itself (PowerShell reads the whole file before running,
208 /// so self-deletion is safe), then propagate the exit code.
209 const TEMP_PS1_TAIL: &str = concat!(
210 "$__codewhaleExit = if ($null -ne $LASTEXITCODE) { $LASTEXITCODE } else { 0 }\n",
211 "Remove-Item -LiteralPath $MyInvocation.MyCommand.Path -Force ",
212 "-ErrorAction SilentlyContinue\n",
213 "if ($__codewhaleExit -ne 0) { exit $__codewhaleExit }\n",
214 );
215
216 fn write_temp_ps1(shell_command: &str) -> std::io::Result<String> {
217 let dir = std::env::temp_dir();
218 sweep_stale_temp_ps1(&dir);
219 // Unguessable name: another user of the shared temporary directory cannot
220 // predict it, and `write_temp_ps1_at` still refuses anything already there.
221 let name = format!(
222 "codewhale-shell-{}-{}.ps1",
223 std::process::id(),
224 uuid::Uuid::new_v4().simple()
225 );
226 write_temp_ps1_at(&dir.join(name), shell_command)
227 }
228
229 /// Create `path` exclusively, owner-only on Unix, and write the script into it.
230 fn write_temp_ps1_at(path: &std::path::Path, shell_command: &str) -> std::io::Result<String> {
231 use std::io::Write;
232 // Create-new: never write the script through a file or link that someone
233 // else placed at this name in the shared temporary directory.
234 let mut options = std::fs::OpenOptions::new();
235 options.write(true).create_new(true);
236 #[cfg(unix)]
237 {
238 use std::os::unix::fs::OpenOptionsExt;
239 options.mode(0o600);
240 }
241 let mut file = options.open(path)?;
242 // UTF-8 with BOM helps Windows PowerShell 5.1 decode non-ASCII scripts.
243 file.write_all(&[0xEF, 0xBB, 0xBF])?;
244 file.write_all(shell_command.as_bytes())?;
245 if !shell_command.ends_with('\n') {
246 file.write_all(b"\n")?;
247 }
248 // Native exit-code propagation plus self-cleanup for the script form.
249 file.write_all(TEMP_PS1_TAIL.as_bytes())?;
250 Ok(path.to_string_lossy().into_owned())
251 }
252
253 /// Best-effort removal of leftover `codewhale-shell-*.ps1` scripts (for
254 /// example after a killed process, which skips the in-script self-delete).
255 /// Only files older than one hour are touched so a concurrently starting
256 /// invocation is never raced.
257 fn sweep_stale_temp_ps1(dir: &std::path::Path) {
258 const STALE_AFTER: std::time::Duration = std::time::Duration::from_secs(60 * 60);
259 let Ok(entries) = std::fs::read_dir(dir) else {
260 return;
261 };
262 for entry in entries.flatten() {
263 let name = entry.file_name();
264 let Some(name) = name.to_str() else {
265 continue;
266 };
267 if !name.starts_with("codewhale-shell-") || !name.ends_with(".ps1") {
268 continue;
269 }
270 let stale = entry
271 .metadata()
272 .and_then(|meta| meta.modified())
273 .ok()
274 .and_then(|modified| modified.elapsed().ok())
275 .is_some_and(|age| age > STALE_AFTER);
276 if stale {
277 let _ = std::fs::remove_file(entry.path());
278 }
279 }
280 }
281
282 // ---------------------------------------------------------------------------
283 // Dispatcher
284 // ---------------------------------------------------------------------------
285
286 /// Central shell abstraction. Created once at startup via
287 /// [`ShellDispatcher::detect`] and then used everywhere a command needs to
288 /// be spawned.
289 #[derive(Debug, Clone)]
290 pub struct ShellDispatcher {
291 kind: ShellKind,
292 }
293
294 impl ShellDispatcher {
295 /// Detect the user's shell from the environment.
296 ///
297 /// ## Detection order (Windows)
298 ///
299 /// 1. `$env:SHELL` — WSL interop or Git Bash often set this.
300 /// 2. `pwsh.exe` found on `PATH` — PowerShell 7+.
301 /// 3. `powershell.exe` found on `PATH` — Windows PowerShell 5.1.
302 /// 4. `cmd.exe` — always available, last resort.
303 ///
304 /// ## Detection order (Unix)
305 ///
306 /// 1. `$SHELL` — preserve its actual executable via `Custom`; bare names
307 /// are resolved against the current `PATH` once at detection time.
308 /// 2. `/bin/sh` fallback.
309 pub fn detect() -> Self {
310 let kind = Self::detect_shell();
311 Self::log_startup(&kind);
312 ShellDispatcher { kind }
313 }
314
315 /// Log a shell execution line when `SHELL_DISPATCHER_LOG` is set.
316 pub fn log_exec(command: &str) {
317 if let Ok(path) = std::env::var("SHELL_DISPATCHER_LOG") {
318 let _ = Self::append_log_static(&path, command);
319 }
320 }
321
322 fn log_startup(kind: &ShellKind) {
323 let _lock = LOG_MUTEX.lock();
324 if let Ok(path) = std::env::var("SHELL_DISPATCHER_LOG") {
325 let init_line = format!(
326 "--- ShellDispatcher log started pid={} ---\n",
327 std::process::id()
328 );
329 let _ = Self::append_log(&path, &init_line);
330 let detect_line = format!("[{}] detect: {kind:?}\n", now_iso());
331 let _ = Self::append_log(&path, &detect_line);
332 }
333 }
334
335 fn append_log(path: &str, line: &str) -> std::io::Result<()> {
336 let mut file = OpenOptions::new()
337 .create(true)
338 .append(true)
339 .open(Path::new(path))?;
340 file.write_all(line.as_bytes())?;
341 file.flush()
342 }
343
344 fn append_log_static(path: &str, command: &str) -> std::io::Result<()> {
345 // Resolve kind outside the lock — `global_dispatcher()` may trigger
346 // `detect()` which calls `log_startup()` which also acquires the mutex.
347 let kind = global_dispatcher().kind();
348 let _lock = LOG_MUTEX.lock();
349 let line = format!("[{}] exec via {kind:?}: {command}\n", now_iso());
350 Self::append_log(path, &line)
351 }
352
353 /// The detected shell kind.
354 pub fn kind(&self) -> &ShellKind {
355 &self.kind
356 }
357
358 // -- Public builders --------------------------------------------------
359
360 /// Build a `std::process::Command` for the given shell command string.
361 pub fn build_command(&self, shell_command: &str) -> Command {
362 let (program, args) = self.build_command_parts(shell_command);
363 let mut cmd = Command::new(program);
364 if matches!(self.kind, ShellKind::Cmd) {
365 #[cfg(windows)]
366 {
367 // Preserve quotes for `cmd /C <payload>` (issue #1691).
368 if args.len() == 2 && args[0].eq_ignore_ascii_case("/C") {
369 cmd.raw_arg(&args[0]);
370 cmd.raw_arg(&args[1]);
371 return cmd;
372 }
373 }
374 }
375 cmd.args(args);
376 cmd
377 }
378
379 /// Build the program + args tuple. Useful when the caller needs to
380 /// inspect or modify the args before passing them to `Command`.
381 pub fn build_command_parts(&self, shell_command: &str) -> (String, Vec<String>) {
382 let program = self.kind.binary().to_string();
383 if self.kind.is_powershell() {
384 let mut args = powershell_base_args();
385 if powershell_prefers_script_file(shell_command) {
386 // Complex multiline / heavily quoted scripts: write a temp
387 // .ps1 and invoke with -File so quoting stays structured.
388 match write_temp_ps1(shell_command) {
389 Ok(path) => {
390 args.push("-File".to_string());
391 args.push(path);
392 return (program, args);
393 }
394 Err(_) => {
395 // Fall through to -Command if the temp file cannot be
396 // created; execution still proceeds.
397 }
398 }
399 }
400 args.push("-Command".to_string());
401 args.push(powershell_exit_aware_command(shell_command));
402 return (program, args);
403 }
404 let args = if matches!(self.kind, ShellKind::Cmd) {
405 vec!["/C".to_string(), shell_command.to_string()]
406 } else if self.kind.is_zsh() {
407 Vec::from(
408 [
409 "+o",
410 "nomatch",
411 "+o",
412 "equals",
413 self.kind.command_flag(),
414 shell_command,
415 ]
416 .map(str::to_string),
417 )
418 } else {
419 vec![
420 self.kind.command_flag().to_string(),
421 shell_command.to_string(),
422 ]
423 };
424 (program, args)
425 }
426
427 /// Build a `Command` from separate program + args (bypasses the shell).
428 /// Used when the caller already has a resolved executable and argument
429 /// vector — e.g. `ExecEnv` from the sandbox.
430 #[cfg(test)]
431 pub fn build_direct(&self, program: &str, args: &[String]) -> Command {
432 let mut cmd = Command::new(program);
433 cmd.args(args);
434 cmd
435 }
436
437 /// Execute a foreground command with raw-mode save/restore.
438 ///
439 /// A scope guard ensures raw mode is restored even if the command fails
440 /// to spawn or returns early (review feedback, issue #1690).
441 pub fn run_foreground(
442 &self,
443 shell_command: &str,
444 cwd: &std::path::Path,
445 ) -> Result<String, anyhow::Error> {
446 use anyhow::Context;
447
448 // Log the execution
449 {
450 let _lock = LOG_MUTEX.lock();
451 if let Ok(path) = std::env::var("SHELL_DISPATCHER_LOG") {
452 let kind = self.kind();
453 let line = format!("[{}] exec via {kind:?}: {shell_command}\n", now_iso());
454 let _ = Self::append_log(&path, &line);
455 }
456 }
457
458 // Leave raw mode; the guard restores it only if it was already enabled.
459 let _raw_mode = codewhale_runtime::host_terminal::suspend_raw_mode();
460
461 let mut cmd = self.build_command(shell_command);
462 cmd.current_dir(cwd);
463
464 let output = cmd
465 .output()
466 .with_context(|| format!("failed to execute shell command: {shell_command}"))?;
467
468 if !output.status.success() {
469 let stderr = String::from_utf8_lossy(&output.stderr);
470 anyhow::bail!(
471 "shell command failed (status={}): {}",
472 output.status,
473 stderr.trim()
474 );
475 }
476
477 let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
478 Ok(stdout)
479 }
480
481 // -- Detection --------------------------------------------------------
482
483 fn detect_shell() -> ShellKind {
484 #[cfg(any(test, feature = "test-support"))]
485 {
486 // Non-blocking on purpose. This runs inside the `LazyLock`
487 // initializer in `global_dispatcher()`, and a test that holds the
488 // env barrier can reach `global_dispatcher()` while another thread
489 // is initializing it — blocking here inverts the two locks and
490 // wedges the whole test binary with no libtest timeout to end it.
491 // `$SHELL` is the only variable read, and the two tests that set it
492 // set it to a fixed value, so an unsynchronized read is safe.
493 codewhale_runtime::test_support::with_test_env_lock_if_uncontended(
494 Self::detect_shell_unlocked,
495 )
496 }
497 #[cfg(not(any(test, feature = "test-support")))]
498 {
499 Self::detect_shell_unlocked()
500 }
501 }
502
503 fn detect_shell_unlocked() -> ShellKind {
504 #[cfg(windows)]
505 {
506 // 1. $env:SHELL — WSL interop or Git Bash often set this.
507 if let Ok(shell) = std::env::var("SHELL") {
508 let lower = shell.to_lowercase();
509 if lower.contains("bash") {
510 return ShellKind::Bash;
511 }
512 if lower.contains("pwsh") {
513 return ShellKind::Pwsh;
514 }
515 if lower.contains("powershell") {
516 return ShellKind::WindowsPowerShell;
517 }
518 }
519
520 if Self::find_exe("pwsh.exe") {
521 return ShellKind::Pwsh;
522 }
523 if Self::find_exe("powershell.exe") {
524 return ShellKind::WindowsPowerShell;
525 }
526 ShellKind::Cmd
527 }
528
529 #[cfg(not(windows))]
530 {
531 if let Ok(shell) = std::env::var("SHELL")
532 && let Some(kind) = Self::unix_shell_kind(&shell)
533 {
534 return kind;
535 }
536
537 ShellKind::Sh
538 }
539 }
540
541 #[cfg(not(windows))]
542 fn unix_shell_kind(shell: &str) -> Option<ShellKind> {
543 let shell = shell.trim();
544 if shell.is_empty() {
545 return None;
546 }
547 let path = Path::new(shell);
548 let binary = if path.is_absolute() || path.components().count() > 1 {
549 shell.to_string()
550 } else {
551 std::env::var_os("PATH")
552 .and_then(|path| {
553 std::env::split_paths(&path)
554 .map(|dir| dir.join(shell))
555 .find(|candidate| candidate.is_file())
556 })
557 .map_or_else(
558 || shell.to_string(),
559 |path| path.to_string_lossy().into_owned(),
560 )
561 };
562 Some(ShellKind::Custom {
563 binary,
564 flag: "-c".to_string(),
565 })
566 }
567
568 /// Check PATH first, then fall back to well-known install directories.
569 #[cfg(windows)]
570 fn find_exe(name: &str) -> bool {
571 if Self::binary_on_path(name) {
572 return true;
573 }
574 // Well-known install locations (order by preference).
575 let known_dirs: &[&str] = &[
576 r"C:\Program Files\PowerShell\7",
577 r"C:\Windows\System32\WindowsPowerShell\v1.0",
578 ];
579 known_dirs
580 .iter()
581 .any(|dir| std::path::Path::new(dir).join(name).is_file())
582 }
583
584 #[cfg(windows)]
585 fn binary_on_path(name: &str) -> bool {
586 std::env::var_os("PATH")
587 .map(|path| {
588 std::env::split_paths(&path).any(|dir| {
589 let candidate = dir.join(name);
590 candidate.is_file()
591 })
592 })
593 .unwrap_or(false)
594 }
595 }
596
597 // -- Helpers ---------------------------------------------------------------
598
599 fn now_iso() -> String {
600 chrono::Utc::now()
601 .format("%Y-%m-%dT%H:%M:%S%.3f")
602 .to_string()
603 }
604
605 /// Global dispatcher instance, detected once at startup.
606 ///
607 /// Any code path that needs to spawn a shell command can use
608 /// `global_dispatcher()` instead of threading the dispatcher through
609 /// every function signature.
610 pub fn global_dispatcher() -> &'static ShellDispatcher {
611 use std::sync::LazyLock;
612 static DISPATCHER: LazyLock<ShellDispatcher> = LazyLock::new(ShellDispatcher::detect);
613 &DISPATCHER
614 }
615
616 // ---------------------------------------------------------------------------
617 // Tests
618 // ---------------------------------------------------------------------------
619
620 #[cfg(test)]
621 mod tests {
622 use super::*;
623
624 #[test]
625 fn shell_kind_binary_names() {
626 #[cfg(windows)]
627 {
628 assert_eq!(ShellKind::Pwsh.binary(), "pwsh.exe");
629 assert_eq!(ShellKind::WindowsPowerShell.binary(), "powershell.exe");
630 assert_eq!(ShellKind::Cmd.binary(), "cmd.exe");
631 }
632 #[cfg(not(windows))]
633 {
634 assert_eq!(ShellKind::Pwsh.binary(), "pwsh");
635 assert_eq!(ShellKind::WindowsPowerShell.binary(), "powershell");
636 assert_eq!(ShellKind::Cmd.binary(), "cmd");
637 }
638 #[cfg(windows)]
639 assert_eq!(ShellKind::Sh.binary(), "sh");
640 #[cfg(not(windows))]
641 assert_eq!(ShellKind::Sh.binary(), "/bin/sh");
642 assert_eq!(ShellKind::Bash.binary(), "bash");
643 }
644
645 #[cfg(not(windows))]
646 #[test]
647 fn unix_shell_detection_preserves_absolute_executable_paths() {
648 let bash = ShellDispatcher::unix_shell_kind("/bin/bash").expect("bash shell");
649 assert_eq!(
650 bash,
651 ShellKind::Custom {
652 binary: "/bin/bash".to_string(),
653 flag: "-c".to_string(),
654 }
655 );
656
657 let pwsh =
658 ShellDispatcher::unix_shell_kind("/opt/homebrew/bin/pwsh").expect("PowerShell path");
659 assert!(pwsh.is_powershell());
660 assert_eq!(pwsh.binary(), "/opt/homebrew/bin/pwsh");
661
662 let dispatcher = ShellDispatcher {
663 kind: ShellDispatcher::unix_shell_kind("/bin/sh").expect("POSIX shell"),
664 };
665 let mut command = dispatcher.build_command("printf path-independent");
666 command.env_clear();
667 let output = command.output().expect("absolute shell must not need PATH");
668 assert!(output.status.success(), "{output:?}");
669 assert_eq!(output.stdout, b"path-independent");
670 }
671
672 #[test]
673 fn detect_returns_some_shell() {
674 let dispatcher = global_dispatcher();
675 let _kind = dispatcher.kind();
676 }
677
678 #[test]
679 fn powershell_build_command_includes_no_profile_and_command_flags() {
680 let dispatcher = ShellDispatcher {
681 kind: ShellKind::Pwsh,
682 };
683 let cmd = dispatcher.build_command("echo hello");
684 let args: Vec<&str> = cmd.get_args().map(|a| a.to_str().unwrap()).collect();
685 assert!(args.contains(&"-NoLogo"));
686 assert!(args.contains(&"-NoProfile"));
687 assert!(args.contains(&"-NonInteractive"));
688 assert!(args.contains(&"-Command"));
689 assert!(
690 args.iter().any(|a| a.contains("echo hello")),
691 "command payload missing: {args:?}"
692 );
693 assert!(
694 args.iter().any(|a| a.contains("$LASTEXITCODE")),
695 "native exit-code capture missing: {args:?}"
696 );
697 }
698
699 #[test]
700 fn powershell_multiline_uses_temp_file_invocation() {
701 let dispatcher = ShellDispatcher {
702 kind: ShellKind::Pwsh,
703 };
704 let script = "Write-Output 'line1'\nWrite-Output 'line2'";
705 let (program, args) = dispatcher.build_command_parts(script);
706 assert!(program.contains("pwsh"));
707 assert!(args.iter().any(|a| a == "-File"), "{args:?}");
708 let path = args
709 .iter()
710 .find(|a| a.ends_with(".ps1"))
711 .unwrap_or_else(|| panic!("expected temp .ps1 path: {args:?}"));
712 // The script must clean up after itself and still propagate the
713 // native exit code — self-delete before the exit line, so a nonzero
714 // exit cannot skip the removal.
715 let contents = std::fs::read_to_string(path).expect("read temp script");
716 let remove_at = contents
717 .find("Remove-Item -LiteralPath $MyInvocation.MyCommand.Path")
718 .expect("self-delete line present");
719 let exit_at = contents
720 .find("if ($__codewhaleExit -ne 0) { exit $__codewhaleExit }")
721 .expect("exit propagation present");
722 assert!(remove_at < exit_at, "self-delete must precede exit");
723 // Cleanup temp script created by the builder (the test never runs it).
724 let _ = std::fs::remove_file(path);
725 }
726
727 /// #6745: both PowerShell forms carry a process-scoped policy bypass, and
728 /// it precedes `-File`/`-Command` — PowerShell hands every argument after
729 /// `-File` to the script, so a later `-ExecutionPolicy` would be ignored.
730 #[test]
731 fn powershell_forms_bypass_execution_policy_at_process_scope() {
732 let dispatcher = ShellDispatcher {
733 kind: ShellKind::WindowsPowerShell,
734 };
735 for script in ["Write-Output 'one'", "Write-Output 'a'\nWrite-Output 'b'"] {
736 let (_, args) = dispatcher.build_command_parts(script);
737 let policy = args
738 .iter()
739 .position(|a| a == "-ExecutionPolicy")
740 .unwrap_or_else(|| panic!("process-scope policy missing: {args:?}"));
741 assert_eq!(args[policy + 1], "Bypass", "{args:?}");
742 let payload_flag = args
743 .iter()
744 .position(|a| a == "-File" || a == "-Command")
745 .expect("payload flag");
746 assert!(policy < payload_flag, "{args:?}");
747 if args[payload_flag] == "-File" {
748 let _ = std::fs::remove_file(&args[payload_flag + 1]);
749 }
750 }
751 }
752
753 /// #6745: `inherit` is the only value that drops the process-scope bypass;
754 /// unset, `bypass`, and anything unrecognised keep it. Tested on the pure
755 /// decision so no test mutates the process environment.
756 #[test]
757 fn powershell_execution_policy_opt_out_only_honours_inherit() {
758 let bypass = |args: &[String]| {
759 args.iter()
760 .position(|a| a == "-ExecutionPolicy")
761 .map(|index| args[index + 1].clone())
762 };
763 for setting in [
764 None,
765 Some("bypass"),
766 Some("Bypass"),
767 Some(""),
768 Some("restricted"),
769 ] {
770 let args = powershell_base_args_for_policy(setting);
771 assert_eq!(bypass(&args).as_deref(), Some("Bypass"), "{setting:?}");
772 assert!(args.contains(&"-NonInteractive".to_string()), "{setting:?}");
773 }
774 for setting in ["inherit", "INHERIT", " inherit "] {
775 let args = powershell_base_args_for_policy(Some(setting));
776 assert_eq!(bypass(&args), None, "{setting:?}: {args:?}");
777 assert_eq!(args, ["-NoLogo", "-NoProfile", "-NonInteractive"]);
778 }
779 }
780
781 #[test]
782 fn powershell_trailing_comment_cannot_swallow_exit_capture() {
783 // An unquoted `#` in a single-line payload comments to end-of-line;
784 // the appended $LASTEXITCODE check must live on its own line so a
785 // failing native command can never silently report success.
786 let dispatcher = ShellDispatcher {
787 kind: ShellKind::Pwsh,
788 };
789 let (_, args) = dispatcher.build_command_parts("git log --oneline -5 # recent");
790 let payload = args.last().expect("command payload");
791 assert!(payload.contains("# recent"), "{payload}");
792 assert!(
793 payload.contains("\nif ($null -ne $LASTEXITCODE"),
794 "exit-code capture must start on a fresh line: {payload}"
795 );
796 }
797
798 /// The temporary script is created exclusively: a file or link already at
799 /// the name is refused and left exactly as it was, and a fresh script is
800 /// owner-only.
801 #[test]
802 fn temp_ps1_script_is_created_exclusively_and_privately() {
803 let dir = tempfile::tempdir().expect("tempdir");
804
805 let taken = dir.path().join("codewhale-shell-taken.ps1");
806 std::fs::write(&taken, "original").expect("pre-existing file");
807 let error = write_temp_ps1_at(&taken, "Write-Output 'x'")
808 .expect_err("an existing file must be refused");
809 assert_eq!(error.kind(), std::io::ErrorKind::AlreadyExists);
810 assert_eq!(std::fs::read_to_string(&taken).unwrap(), "original");
811
812 #[cfg(unix)]
813 {
814 use std::os::unix::fs::{PermissionsExt, symlink};
815 let victim = dir.path().join("victim.txt");
816 let linked = dir.path().join("codewhale-shell-linked.ps1");
817 symlink(&victim, &linked).expect("plant dangling link");
818 assert!(write_temp_ps1_at(&linked, "Write-Output 'x'").is_err());
819 assert!(
820 !victim.exists(),
821 "a planted link must not be written through"
822 );
823
824 let fresh = dir.path().join("codewhale-shell-fresh.ps1");
825 write_temp_ps1_at(&fresh, "Write-Output 'x'").expect("fresh script");
826 let mode = std::fs::metadata(&fresh).unwrap().permissions().mode();
827 assert_eq!(mode & 0o777, 0o600);
828 }
829
830 let fresh = dir.path().join("codewhale-shell-content.ps1");
831 let written = write_temp_ps1_at(&fresh, "Write-Output 'x'").expect("script");
832 assert_eq!(written, fresh.to_string_lossy());
833 let bytes = std::fs::read(&fresh).unwrap();
834 assert_eq!(&bytes[..3], &[0xEF, 0xBB, 0xBF]);
835 let text = String::from_utf8(bytes[3..].to_vec()).unwrap();
836 assert!(text.starts_with("Write-Output 'x'\n"), "{text}");
837 assert!(text.ends_with(TEMP_PS1_TAIL), "{text}");
838
839 // Two scripts from the public entry point never collide.
840 let first = write_temp_ps1("1").expect("first");
841 let second = write_temp_ps1("2").expect("second");
842 assert_ne!(first, second);
843 let _ = std::fs::remove_file(first);
844 let _ = std::fs::remove_file(second);
845 }
846
847 #[test]
848 fn stale_temp_ps1_scripts_are_swept() {
849 let dir = std::env::temp_dir();
850 let stale = dir.join("codewhale-shell-0-stale-test.ps1");
851 std::fs::write(&stale, "Write-Output 'stale'\n").expect("write stale script");
852 // Backdate the file beyond the sweep horizon.
853 let old = std::time::SystemTime::now() - std::time::Duration::from_secs(2 * 60 * 60);
854 let file = std::fs::File::options()
855 .append(true)
856 .open(&stale)
857 .expect("open stale script");
858 file.set_modified(old).expect("backdate stale script");
859 drop(file);
860
861 sweep_stale_temp_ps1(&dir);
862 assert!(!stale.exists(), "stale script should be removed");
863 }
864
865 #[test]
866 fn cmd_build_command_uses_c_flag() {
867 let dispatcher = ShellDispatcher {
868 kind: ShellKind::Cmd,
869 };
870 let cmd = dispatcher.build_command("echo hello");
871 let args: Vec<&str> = cmd.get_args().map(|a| a.to_str().unwrap()).collect();
872 assert!(args.contains(&"/C"));
873 assert!(args.contains(&"echo hello"));
874 }
875
876 #[test]
877 fn sh_build_command_uses_dash_c() {
878 let dispatcher = ShellDispatcher {
879 kind: ShellKind::Sh,
880 };
881 let cmd = dispatcher.build_command("echo hello");
882 let args: Vec<&str> = cmd.get_args().map(|a| a.to_str().unwrap()).collect();
883 assert!(args.contains(&"-c"));
884 assert!(args.contains(&"echo hello"));
885 }
886
887 #[cfg(test)]
888 #[test]
889 fn build_direct_preserves_args() {
890 let dispatcher = ShellDispatcher {
891 kind: ShellKind::Cmd,
892 };
893 let args = vec!["-m".to_string(), "commit message".to_string()];
894 let cmd = dispatcher.build_direct("git", &args);
895 let cmd_args: Vec<&str> = cmd.get_args().map(|a| a.to_str().unwrap()).collect();
896 assert_eq!(cmd_args, vec!["-m", "commit message"]);
897 }
898
899 #[cfg(test)]
900 #[test]
901 fn powershell_flags_are_correct() {
902 assert!(ShellKind::Pwsh.needs_command_flag());
903 assert!(ShellKind::WindowsPowerShell.needs_command_flag());
904 assert!(!ShellKind::Cmd.needs_command_flag());
905 assert!(!ShellKind::Sh.needs_command_flag());
906 assert!(!ShellKind::Bash.needs_command_flag());
907 }
908
909 #[cfg(test)]
910 #[test]
911 fn is_powershell_detects_both_variants() {
912 assert!(ShellKind::Pwsh.is_powershell());
913 assert!(ShellKind::WindowsPowerShell.is_powershell());
914 assert!(!ShellKind::Cmd.is_powershell());
915 assert!(!ShellKind::Sh.is_powershell());
916 assert!(!ShellKind::Bash.is_powershell());
917 }
918
919 #[cfg(test)]
920 #[test]
921 fn build_command_quotes_spaces_for_cmd() {
922 let dispatcher = ShellDispatcher {
923 kind: ShellKind::Cmd,
924 };
925 let cmd = dispatcher.build_command("git commit -m \"msg with spaces\"");
926 let args: Vec<&str> = cmd.get_args().map(|a| a.to_str().unwrap()).collect();
927 assert_eq!(args.len(), 2);
928 assert_eq!(args[0], "/C");
929 assert!(args[1].contains("msg with spaces"));
930 assert!(args[1].starts_with("git "));
931 }
932
933 #[cfg(test)]
934 #[test]
935 fn build_command_quotes_spaces_for_pwsh() {
936 let dispatcher = ShellDispatcher {
937 kind: ShellKind::Pwsh,
938 };
939 let cmd = dispatcher.build_command("git commit -m \"msg with spaces\"");
940 let args: Vec<&str> = cmd.get_args().map(|a| a.to_str().unwrap()).collect();
941 assert!(args.contains(&"-NoLogo"));
942 assert!(args.contains(&"-NoProfile"));
943 assert!(args.contains(&"-NonInteractive"));
944 assert!(args.contains(&"-Command"));
945 assert!(
946 args.iter().any(|a| a.contains("msg with spaces")),
947 "quoted payload missing: {args:?}"
948 );
949 }
950
951 #[cfg(test)]
952 #[test]
953 fn build_direct_handles_empty_args() {
954 let dispatcher = ShellDispatcher {
955 kind: ShellKind::Sh,
956 };
957 let cmd = dispatcher.build_direct("echo", &[]);
958 let args: Vec<&str> = cmd.get_args().map(|a| a.to_str().unwrap()).collect();
959 assert!(args.is_empty());
960 }
961
962 #[cfg(windows)]
963 #[test]
964 fn find_exe_finds_cmd_on_path() {
965 // cmd.exe is always on PATH on Windows.
966 assert!(ShellDispatcher::find_exe("cmd.exe"));
967 }
968
969 #[cfg(windows)]
970 #[test]
971 fn find_exe_rejects_nonexistent_binary() {
972 assert!(!ShellDispatcher::find_exe("nonexistent_xyz_12345.exe"));
973 }
974
975 #[cfg(windows)]
976 #[test]
977 fn find_exe_falls_back_to_known_dirs() {
978 // Verify the known-dirs fallback path actually exists on this system.
979 let ps_path = r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
980 if std::path::Path::new(ps_path).is_file() {
981 // The fallback directory exists — find_exe should locate it.
982 assert!(ShellDispatcher::find_exe("powershell.exe"));
983 } else {
984 eprintln!("Skipping: {ps_path} not present on this system");
985 }
986 }
987
988 #[test]
989 fn custom_shell_uses_provided_binary_and_flag() {
990 let kind = ShellKind::Custom {
991 binary: "/bin/zsh".to_string(),
992 flag: "-c".to_string(),
993 };
994 assert_eq!(kind.binary(), "/bin/zsh");
995 assert_eq!(kind.command_flag(), "-c");
996 }
997 }
998
998 lines RUST