Skip to main content

oxdock_process/
shell_manager.rs

1use std::sync::{Arc, Mutex};
2
3use anyhow::{Context, Result, anyhow, bail};
4#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
5use std::process::Command as ProcessCommand;
6#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
7use std::process::Stdio;
8
9use oxdock_fs::PolicyPath;
10
11use crate::child::ChildHandle;
12use crate::contract::{
13    BackgroundHandle, CommandContext, CommandMode, CommandOptions, CommandResult, CommandStderr,
14    CommandStdin, CommandStdout, PROCESS_DEBUG_ENV_VAR, ProcessManager, SharedInput, SharedOutput,
15};
16use crate::shell::{batch_shell, direct_cmd, shell_cmd};
17
18/// Default process manager that shells out using the system shell.
19#[derive(Clone, Default)]
20#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
21pub struct ShellProcessManager;
22
23impl ProcessManager for ShellProcessManager {
24    type Handle = ChildHandle;
25
26    #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
27    fn run_command(
28        &mut self,
29        ctx: &CommandContext,
30        script: &str,
31        options: CommandOptions,
32    ) -> Result<CommandResult<Self::Handle>> {
33        if std::env::var_os(PROCESS_DEBUG_ENV_VAR).is_some() {
34            eprintln!("oxbook run_command: {script}");
35        }
36        let mut command = shell_cmd(script);
37        let program = batch_shell();
38        // Shell form always requires PATH: the shell binary may resolve
39        // without it, but every command inside the script text resolves
40        // through the child's PATH.
41        apply_ctx(&mut command, ctx, &program, true)?;
42        let CommandOptions {
43            mode,
44            stdin,
45            stdout,
46            stderr,
47        } = options;
48        run_prepared(&mut command, mode, stdin, stdout, stderr)
49    }
50
51    #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
52    fn run_argv(
53        &mut self,
54        ctx: &CommandContext,
55        argv: &[String],
56        options: CommandOptions,
57    ) -> Result<CommandResult<Self::Handle>> {
58        if std::env::var_os(PROCESS_DEBUG_ENV_VAR).is_some() {
59            eprintln!("oxbook run_argv: {argv:?}");
60        }
61        let mut command = direct_cmd(argv)?;
62        let program = argv.first().map(String::as_str).unwrap_or_default();
63        apply_ctx(&mut command, ctx, program, false)?;
64        let CommandOptions {
65            mode,
66            stdin,
67            stdout,
68            stderr,
69        } = options;
70        run_prepared(&mut command, mode, stdin, stdout, stderr)
71    }
72}
73
74/// Shared foreground/background runner for an already-configured
75/// `std::process::Command`: stdio mapping, null-stdin isolation,
76/// capture semantics, and non-zero failures behave identically for
77/// shell (`run_command`) and direct-spawn (`run_argv`) paths.
78#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
79fn run_prepared(
80    command: &mut ProcessCommand,
81    mode: CommandMode,
82    stdin: CommandStdin,
83    stdout: CommandStdout,
84    stderr: CommandStderr,
85) -> Result<CommandResult<ChildHandle>> {
86    let (stdout_stream, capture_buf) = match stdout {
87        CommandStdout::Inherit => (None, None),
88        CommandStdout::Stream(stream) => (Some(stream), None),
89        CommandStdout::Capture => {
90            if matches!(mode, CommandMode::Background) {
91                bail!("cannot capture stdout for background command");
92            }
93            let buf = Arc::new(Mutex::new(Vec::new()));
94            let writer: SharedOutput = buf.clone();
95            (Some(writer), Some(buf))
96        }
97        #[cfg(not(miri))]
98        CommandStdout::OsPipe(writer) => {
99            // Move the FD into the child. `take` empties the parent slot,
100            // and `options` drops at the end of this function, so no parent
101            // copy survives to starve the reader of EOF.
102            let owned = writer.take()?;
103            command.stdout(Stdio::from(owned));
104            (None, None)
105        }
106    };
107
108    let stderr_stream = match stderr {
109        CommandStderr::Inherit => None,
110        CommandStderr::Stream(stream) => Some(stream),
111        #[cfg(not(miri))]
112        CommandStderr::OsPipe(writer) => {
113            // Same move and drop discipline as stdout above.
114            let owned = writer.take()?;
115            command.stderr(Stdio::from(owned));
116            None
117        }
118    };
119
120    let stdin_stream: Option<SharedInput> = match stdin {
121        // Do not inherit stdin by default; ensure isolation unless requested.
122        CommandStdin::Null => {
123            command.stdin(Stdio::null());
124            None
125        }
126        CommandStdin::Inherit => None,
127        CommandStdin::Stream(reader) => Some(reader),
128        #[cfg(not(miri))]
129        CommandStdin::OsPipe(reader) => {
130            // Same move and drop discipline as stdout above.
131            let owned = reader.take()?;
132            command.stdin(Stdio::from(owned));
133            None
134        }
135    };
136    let desc = format!("{:?}", command);
137
138    match mode {
139        CommandMode::Foreground => {
140            let mut handle =
141                spawn_child_with_streams(command, stdin_stream, stdout_stream, stderr_stream)?;
142            let status = handle
143                .wait()
144                .with_context(|| format!("failed to run {desc}"))?;
145            if !status.success() {
146                bail!("command {desc} failed with status {}", status);
147            }
148            if let Some(buf) = capture_buf {
149                let mut guard = buf.lock().map_err(|_| anyhow!("capture stdout poisoned"))?;
150                return Ok(CommandResult::Captured(std::mem::take(&mut *guard)));
151            }
152            Ok(CommandResult::Completed)
153        }
154        CommandMode::Background => {
155            // Own process group: teardown signals the whole tree (see
156            // `ChildHandle::kill`), so orphaned grandchildren die with
157            // the direct child instead of holding pipe write ends open
158            // past the kill and stalling pump EOF. Foreground keeps the
159            // parent group so terminal signals still reach children.
160            #[cfg(unix)]
161            {
162                use std::os::unix::process::CommandExt;
163                command.process_group(0);
164            }
165            let handle =
166                spawn_child_with_streams(command, stdin_stream, stdout_stream, stderr_stream)?;
167            Ok(CommandResult::Background(handle))
168        }
169    }
170}
171
172#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
173fn apply_ctx(
174    command: &mut ProcessCommand,
175    ctx: &CommandContext,
176    program: &str,
177    require_path: bool,
178) -> Result<()> {
179    // Use command_path to strip Windows verbatim prefixes (\\?\) before passing to Command.
180    // While Rust's `std::process::Command` handles verbatim paths in current_dir correctly,
181    // environment variables are passed as-is. If we pass a verbatim path in `CARGO_TARGET_DIR`,
182    // tools that don't understand it (or shell scripts echoing it) might misbehave or produce
183    // unexpected output. Normalizing here ensures consistency.
184    //
185    // Why the `\\?\` verbatim prefixes?
186    // On Windows we intentionally keep the canonical verbatim path (e.g. `\\?\C:\\repo`)
187    // inside every `GuardedPath`. This avoids MAX_PATH truncation and prevents subtle
188    // `PathBuf` casing/drive-letter surprises when the guard is later joined, copied,
189    // or passed through `std::fs`. When you need a human-readable path, call
190    // [`command_path`] (native separators, prefix stripped) or [`normalized_path`]
191    // (forward slashes) or use the `Display` impl, which already defers to
192    // `command_path`. Keep the debug view raw so diagnostics can show the exact path
193    // we are guarding.
194    let cwd_path: std::borrow::Cow<std::path::Path> = match ctx.cwd() {
195        PolicyPath::Guarded(p) => oxdock_fs::command_path(p),
196        PolicyPath::Unguarded(p) => std::borrow::Cow::Borrowed(p.as_path()),
197    };
198    command.current_dir(cwd_path);
199    // Closed child env: the script map is the single source of truth
200    // (seeded at session start, uniformly overwritten by ENV). Stage
201    // it verbatim after the shared anchor pre-flight, so the messages
202    // cannot drift per call site.
203    let staged = ctx.envs().as_ref().clone();
204    crate::env_policy::check_spawn_anchors(program, &staged, require_path)?;
205    command.env_clear();
206    command.envs(&staged);
207    Ok(())
208}
209
210#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
211fn spawn_child_with_streams(
212    cmd: &mut ProcessCommand,
213    stdin: Option<SharedInput>,
214    stdout: Option<SharedOutput>,
215    stderr: Option<SharedOutput>,
216) -> Result<ChildHandle> {
217    if stdin.is_some() {
218        cmd.stdin(Stdio::piped());
219    }
220    if stdout.is_some() {
221        cmd.stdout(Stdio::piped());
222    }
223    if stderr.is_some() {
224        cmd.stderr(Stdio::piped());
225    }
226
227    let mut child = cmd
228        .spawn()
229        .with_context(|| format!("failed to spawn {:?}", cmd))?;
230    let mut io_threads = Vec::new();
231    let mut stdin_thread = None;
232
233    if let Some(stdin_stream) = stdin
234        && let Some(mut child_stdin) = child.stdin.take()
235    {
236        let thread = std::thread::spawn(move || {
237            if let Ok(mut guard) = stdin_stream.lock() {
238                let _ = std::io::copy(&mut *guard, &mut child_stdin);
239            }
240        });
241        stdin_thread = Some(thread);
242    }
243
244    if let Some(stdout_stream) = stdout
245        && let Some(mut child_stdout) = child.stdout.take()
246    {
247        let stream_clone = stdout_stream.clone();
248        let thread = std::thread::spawn(move || {
249            let mut buf = [0u8; 1024];
250            loop {
251                match std::io::Read::read(&mut child_stdout, &mut buf) {
252                    Ok(0) => break,
253                    Ok(n) => {
254                        if let Ok(mut guard) = stream_clone.lock() {
255                            if std::io::Write::write_all(&mut *guard, &buf[..n]).is_err() {
256                                break;
257                            }
258                            let _ = std::io::Write::flush(&mut *guard);
259                        }
260                    }
261                    Err(_) => break,
262                }
263            }
264        });
265        io_threads.push(thread);
266    }
267
268    if let Some(stderr_stream) = stderr
269        && let Some(mut child_stderr) = child.stderr.take()
270    {
271        let stream_clone = stderr_stream.clone();
272        let thread = std::thread::spawn(move || {
273            let mut buf = [0u8; 1024];
274            loop {
275                match std::io::Read::read(&mut child_stderr, &mut buf) {
276                    Ok(0) => break,
277                    Ok(n) => {
278                        if let Ok(mut guard) = stream_clone.lock() {
279                            if std::io::Write::write_all(&mut *guard, &buf[..n]).is_err() {
280                                break;
281                            }
282                            let _ = std::io::Write::flush(&mut *guard);
283                        }
284                    }
285                    Err(_) => break,
286                }
287            }
288        });
289        io_threads.push(thread);
290    }
291
292    ChildHandle::new(child, stdin_thread, io_threads)
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use oxdock_fs::GuardedPath;
299    use oxdock_fs::env as oxdock_env;
300    use std::collections::HashMap;
301
302    fn make_ctx_from_map(
303        map: HashMap<String, String>,
304    ) -> (oxdock_fs::GuardedTempDir, CommandContext) {
305        let temp = GuardedPath::tempdir().expect("tempdir");
306        let guard = temp.as_guarded_path().clone();
307        let cwd: PolicyPath = guard.clone().into();
308        let scratch = oxdock_fs::reserve_cargo_scratch().expect("scratch");
309        let ctx = CommandContext::from_map(&cwd, &map, &scratch, &guard, &guard);
310        (temp, ctx)
311    }
312
313    /// Mirror the session seed on Windows: production maps always
314    /// carry the NT loader anchor, so success-path tests stage it
315    /// explicitly here instead of tripping the fail-safe under test.
316    /// Mirror or omit, like the seed: a host lacking the anchor leaves
317    /// it out. The anchor check itself is proven anchorless by
318    /// `apply_ctx_systemroot_check_follows_platform`, which bypasses
319    /// `make_ctx`.
320    #[cfg(windows)]
321    #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
322    fn with_windows_anchor(mut map: HashMap<String, String>) -> HashMap<String, String> {
323        if !crate::env_policy::has_var(&map, oxdock_env::os::windows::SYSTEM_ROOT)
324            && let Ok(root) = std::env::var(oxdock_env::os::windows::SYSTEM_ROOT)
325        {
326            map.insert(oxdock_env::os::windows::SYSTEM_ROOT.to_string(), root);
327        }
328        map
329    }
330
331    fn make_ctx(envs: &[(&str, &str)]) -> (oxdock_fs::GuardedTempDir, CommandContext) {
332        let map: HashMap<String, String> = envs
333            .iter()
334            .map(|(key, value)| (key.to_string(), value.to_string()))
335            .collect();
336        #[cfg(windows)]
337        let map = with_windows_anchor(map);
338        make_ctx_from_map(map)
339    }
340
341    /// Host executable-lookup env for real-spawn tests: closed children
342    /// resolve binaries only through the script env, so tests that spawn
343    /// real tools must route the host lookup path explicitly, exactly
344    /// like workflow legs route `INHERIT_ENV [PATH]`.
345    #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
346    fn host_exec_env() -> HashMap<String, String> {
347        let mut map = HashMap::new();
348        if let Ok(path) = std::env::var(oxdock_env::os::PATH) {
349            map.insert(oxdock_env::os::PATH.to_string(), path);
350        }
351        #[allow(clippy::disallowed_macros)]
352        if cfg!(windows) {
353            for key in [
354                oxdock_env::os::windows::SYSTEM_ROOT,
355                oxdock_env::os::windows::PATHEXT,
356                oxdock_env::os::windows::COMSPEC,
357                oxdock_env::os::windows::TEMP,
358                oxdock_env::os::windows::TMP,
359            ] {
360                if let Ok(value) = std::env::var(key) {
361                    map.insert(key.to_string(), value);
362                }
363            }
364        }
365        map
366    }
367
368    fn make_ctx_with_host_exec(
369        extra: &[(&str, &str)],
370    ) -> (oxdock_fs::GuardedTempDir, CommandContext) {
371        let temp = GuardedPath::tempdir().expect("tempdir");
372        let guard = temp.as_guarded_path().clone();
373        let cwd: PolicyPath = guard.clone().into();
374        let mut map = host_exec_env();
375        for (key, value) in extra {
376            map.insert(key.to_string(), value.to_string());
377        }
378        let scratch = oxdock_fs::reserve_cargo_scratch().expect("scratch");
379        let ctx = CommandContext::from_map(&cwd, &map, &scratch, &guard, &guard);
380        (temp, ctx)
381    }
382
383    #[test]
384    fn background_capture_stdout_bails_without_spawning() {
385        let (_temp, ctx) = make_ctx_with_host_exec(&[]);
386        let mut pm = ShellProcessManager;
387        let options = CommandOptions {
388            mode: CommandMode::Background,
389            stdout: CommandStdout::Capture,
390            ..Default::default()
391        };
392        let err = match pm.run_command(&ctx, "echo hi", options) {
393            Err(err) => err,
394            Ok(_) => panic!("background capture must bail"),
395        };
396        assert!(
397            err.to_string().contains("cannot capture stdout"),
398            "unexpected error: {err}"
399        );
400    }
401
402    #[cfg_attr(
403        miri,
404        ignore = "spawns processes; Miri does not support process execution"
405    )]
406    #[test]
407    fn foreground_capture_returns_child_stdout_bytes() {
408        let (_temp, ctx) = make_ctx_with_host_exec(&[]);
409        let mut pm = ShellProcessManager;
410        let options = CommandOptions {
411            stdout: CommandStdout::Capture,
412            ..Default::default()
413        };
414        match pm
415            .run_command(&ctx, "echo hello-capture", options)
416            .expect("run")
417        {
418            CommandResult::Captured(bytes) => {
419                let out = String::from_utf8_lossy(&bytes);
420                assert!(out.contains("hello-capture"), "captured: {out}");
421            }
422            CommandResult::Completed => panic!("expected Captured, got Completed"),
423            CommandResult::Background(_) => panic!("expected Captured, got Background"),
424        }
425    }
426
427    #[cfg_attr(
428        miri,
429        ignore = "spawns processes; Miri does not support process execution"
430    )]
431    #[test]
432    fn run_argv_spawns_directly_without_shell() {
433        // `cargo` here is a rustup shim: it resolves through the host
434        // PATH the helper bridges, and needs a home for its toolchain
435        // lookup. This helper builds its map by hand instead of going
436        // through the session seed, so it bridges the host home
437        // explicitly; production sessions seed the host home
438        // automatically.
439        #[allow(clippy::disallowed_macros)]
440        #[cfg(unix)]
441        let home = std::env::var(oxdock_env::os::unix::HOME).unwrap_or_default();
442        #[allow(clippy::disallowed_macros)]
443        #[cfg(windows)]
444        let home = std::env::var(oxdock_env::os::windows::USERPROFILE).unwrap_or_default();
445        #[allow(clippy::disallowed_macros)]
446        #[cfg(unix)]
447        let home_key = oxdock_env::os::unix::HOME;
448        #[allow(clippy::disallowed_macros)]
449        #[cfg(windows)]
450        let home_key = oxdock_env::os::windows::USERPROFILE;
451        let (_temp, ctx) = make_ctx_with_host_exec(&[(home_key, home.as_str())]);
452        let mut pm = ShellProcessManager;
453        let options = CommandOptions {
454            stdout: CommandStdout::Capture,
455            ..Default::default()
456        };
457        // `cargo` drives the test suite itself, so it is present on every
458        // platform without relying on shell builtins (`echo` is not a
459        // Windows executable).
460        let argv = vec!["cargo".to_string(), "--version".to_string()];
461        match pm.run_argv(&ctx, &argv, options).expect("run_argv") {
462            CommandResult::Captured(bytes) => {
463                let out = String::from_utf8_lossy(&bytes);
464                assert!(out.contains("cargo"), "captured: {out}");
465            }
466            CommandResult::Completed => panic!("expected Captured, got Completed"),
467            CommandResult::Background(_) => panic!("expected Captured, got Background"),
468        }
469    }
470
471    #[test]
472    fn run_argv_rejects_empty_argv_without_spawning() {
473        let (_temp, ctx) = make_ctx_with_host_exec(&[]);
474        let mut pm = ShellProcessManager;
475        let err = match pm.run_argv(&ctx, &[], CommandOptions::foreground()) {
476            Err(err) => err,
477            Ok(_) => panic!("empty argv must bail"),
478        };
479        assert!(
480            err.to_string().contains("at least one argument"),
481            "unexpected error: {err}"
482        );
483    }
484
485    fn large_output_script() -> &'static str {
486        #[cfg(windows)]
487        {
488            "for /l %i in (1,1,20000) do @echo 0123456789abcdef"
489        }
490        #[cfg(not(windows))]
491        {
492            "i=0; while [ $i -lt 20000 ]; do echo 0123456789abcdef; i=$((i+1)); done"
493        }
494    }
495
496    #[cfg_attr(
497        miri,
498        ignore = "spawns processes; Miri does not support process execution"
499    )]
500    #[test]
501    fn streams_large_stdout_through_shared_output_without_deadlock() {
502        let (_temp, ctx) = make_ctx_with_host_exec(&[]);
503        let mut pm = ShellProcessManager;
504        let buffer = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
505        let options = CommandOptions {
506            stdout: CommandStdout::Stream(buffer.clone()),
507            ..Default::default()
508        };
509        pm.run_command(&ctx, large_output_script(), options)
510            .expect("run");
511        let bytes = buffer.lock().expect("buffer lock").len();
512        // 20000 lines x 17 bytes ~= 340KB, far beyond any OS pipe buffer, so
513        // the reader pump must have iterated continuously.
514        assert!(bytes >= 300_000, "streamed only {bytes} bytes");
515    }
516
517    #[cfg_attr(
518        miri,
519        ignore = "spawns processes; Miri does not support process execution"
520    )]
521    #[test]
522    fn foreground_stdin_is_piped_through_copy_thread() {
523        let (_temp, ctx) = make_ctx_with_host_exec(&[]);
524        let mut pm = ShellProcessManager;
525        // Windows `sort` requires `\r\n` line endings to recognize lines.
526        #[cfg(windows)]
527        let input: &[u8] = b"b\r\na\r\n";
528        #[cfg(not(windows))]
529        let input: &[u8] = b"b\na\n";
530        let payload: SharedInput =
531            std::sync::Arc::new(std::sync::Mutex::new(std::io::Cursor::new(input.to_vec())));
532        let options = CommandOptions {
533            stdin: CommandStdin::Stream(payload),
534            stdout: CommandStdout::Capture,
535            ..Default::default()
536        };
537        // `sort` reads stdin to EOF on both Unix and Windows before printing.
538        match pm.run_command(&ctx, "sort", options).expect("run") {
539            CommandResult::Captured(bytes) => {
540                assert!(bytes.starts_with(b"a"), "sorted output: {:?}", bytes);
541                assert!(windows_compatible_contains(&bytes, b"b"));
542            }
543            CommandResult::Completed => panic!("expected Captured, got Completed"),
544            CommandResult::Background(_) => panic!("expected Captured, got Background"),
545        }
546    }
547
548    fn windows_compatible_contains(haystack: &[u8], needle: &[u8]) -> bool {
549        haystack.windows(needle.len()).any(|w| w == needle)
550    }
551
552    /// Concurrent producer and consumer wired through one kernel pipe. The
553    /// consumer (`sort`) only returns after EOF, which proves the parent
554    /// retained no writer copy after spawning the producer.
555    #[cfg(not(miri))]
556    #[test]
557    fn os_pipe_streams_producer_to_consumer_with_eof() {
558        use crate::contract::{BackgroundHandle, create_os_pipe};
559
560        let (_temp, ctx) = make_ctx_with_host_exec(&[]);
561        let (reader, writer) = create_os_pipe().expect("os pipe");
562        let mut pm = ShellProcessManager;
563
564        let producer = match pm
565            .run_command(
566                &ctx,
567                "echo hello-os-pipe",
568                CommandOptions {
569                    mode: CommandMode::Background,
570                    stdout: CommandStdout::OsPipe(writer),
571                    ..Default::default()
572                },
573            )
574            .expect("spawn producer")
575        {
576            CommandResult::Background(handle) => handle,
577            _ => panic!("expected background producer handle"),
578        };
579
580        let options = CommandOptions {
581            stdin: CommandStdin::OsPipe(reader),
582            stdout: CommandStdout::Capture,
583            ..Default::default()
584        };
585        // `sort` reads stdin to EOF on every platform before printing.
586        let captured = match pm.run_command(&ctx, "sort", options).expect("run consumer") {
587            CommandResult::Captured(bytes) => bytes,
588            _ => panic!("expected captured consumer output"),
589        };
590        assert!(
591            windows_compatible_contains(&captured, b"hello-os-pipe"),
592            "piped output: {:?}",
593            String::from_utf8_lossy(&captured)
594        );
595
596        let mut producer = producer;
597        let status = producer.wait().expect("wait producer");
598        assert!(status.success(), "producer failed: {status:?}");
599
600        // A spent handle cannot be reused for a second spawn.
601        let (spent_reader, spent_writer) = create_os_pipe().expect("os pipe");
602        spent_reader.take().expect("first reader take");
603        assert!(
604            spent_reader.take().is_err(),
605            "reader take must be single use"
606        );
607        spent_writer.take().expect("first writer take");
608        assert!(
609            spent_writer.take().is_err(),
610            "writer take must be single use"
611        );
612    }
613
614    #[test]
615    #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
616    fn apply_ctx_stages_map_verbatim() {
617        // The map is the single source of truth: declared entries stage
618        // exactly as spelled, and nothing is injected. PATH is present
619        // because the closed child env requires it for bare names (on
620        // Windows `make_ctx` additionally stages the seeded NT loader
621        // anchor the fail-safe requires; the anchor itself is proven
622        // anchorless elsewhere).
623        let (_temp, ctx) = make_ctx(&[
624            (oxdock_env::cargo::TARGET_DIR, "custom-target"),
625            ("FOO", "bar"),
626            (oxdock_env::os::PATH, "test-path"),
627        ]);
628        let mut cmd = ProcessCommand::new("prog");
629        apply_ctx(&mut cmd, &ctx, "prog", false).expect("apply with explicit PATH");
630        let envs: HashMap<String, String> = cmd
631            .get_envs()
632            .map(|(k, v)| {
633                (
634                    k.to_string_lossy().into_owned(),
635                    v.map(|value| value.to_string_lossy().into_owned())
636                        .unwrap_or_default(),
637                )
638            })
639            .collect();
640        assert_eq!(
641            envs.get(oxdock_env::cargo::TARGET_DIR).map(String::as_str),
642            Some("custom-target")
643        );
644        assert_eq!(envs.get("FOO").map(String::as_str), Some("bar"));
645
646        // Absent stays absent: no silent CARGO_TARGET_DIR injection.
647        let (_temp, ctx) = make_ctx(&[(oxdock_env::os::PATH, "test-path")]);
648        let mut cmd = ProcessCommand::new("prog");
649        apply_ctx(&mut cmd, &ctx, "prog", false).expect("apply with explicit PATH");
650        let envs: HashMap<String, String> = cmd
651            .get_envs()
652            .map(|(k, v)| {
653                (
654                    k.to_string_lossy().into_owned(),
655                    v.map(|value| value.to_string_lossy().into_owned())
656                        .unwrap_or_default(),
657                )
658            })
659            .collect();
660        assert!(
661            !envs.contains_key(oxdock_env::cargo::TARGET_DIR),
662            "unstaged names must stay out: {envs:?}"
663        );
664    }
665
666    #[test]
667    #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
668    fn apply_ctx_sets_working_directory_from_guarded_cwd() {
669        let (_temp, ctx) = make_ctx(&[(oxdock_env::os::PATH, "test-path")]);
670        let mut cmd = ProcessCommand::new("prog");
671        apply_ctx(&mut cmd, &ctx, "prog", false).expect("apply with explicit PATH");
672        let expected = oxdock_fs::command_path(match ctx.cwd() {
673            PolicyPath::Guarded(guarded) => guarded,
674            PolicyPath::Unguarded(_) => panic!("expected guarded cwd"),
675        });
676        assert_eq!(cmd.get_current_dir(), Some(expected.as_ref()));
677    }
678
679    /// Closed child env: a host variable never routed through the script env
680    /// must not appear in the staged command env, while declared names do.
681    #[test]
682    #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
683    fn apply_ctx_clears_host_env() {
684        // RAII-guarded: a mid-test failure still restores process env.
685        let _probe_guard = crate::TestEnvGuard::set("OXDOCK_CLOSED_ENV_PROBE", "leaked");
686        let (_temp, ctx) = make_ctx(&[(oxdock_env::os::PATH, "test-path"), ("DECLARED", "yes")]);
687        let mut cmd = ProcessCommand::new("prog");
688        apply_ctx(&mut cmd, &ctx, "prog", false).expect("apply with explicit PATH");
689        let envs: HashMap<String, String> = cmd
690            .get_envs()
691            .map(|(k, v)| {
692                (
693                    k.to_string_lossy().into_owned(),
694                    v.map(|value| value.to_string_lossy().into_owned())
695                        .unwrap_or_default(),
696                )
697            })
698            .collect();
699        assert!(
700            !envs.contains_key("OXDOCK_CLOSED_ENV_PROBE"),
701            "host env must not reach children: {envs:?}"
702        );
703        assert_eq!(envs.get("DECLARED").map(String::as_str), Some("yes"));
704        assert_eq!(
705            envs.get(oxdock_env::os::PATH).map(String::as_str),
706            Some("test-path")
707        );
708    }
709
710    /// No baseline injection: a bare program name without a script
711    /// PATH bails naming the `INHERIT_ENV [PATH]` fix, so missing
712    /// seed entries fail loudly instead of resolving through a
713    /// silent default.
714    #[test]
715    #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
716    fn apply_ctx_bails_for_bare_program_without_path() {
717        let (_temp, ctx) = make_ctx(&[("FOO", "bar")]);
718        let mut cmd = ProcessCommand::new("prog");
719        let err = apply_ctx(&mut cmd, &ctx, "prog", false).expect_err("PATH anchor must trip");
720        assert!(
721            err.to_string().contains("INHERIT_ENV [PATH]"),
722            "unexpected error: {err}"
723        );
724    }
725
726    /// Pre-flight skips separator-carrying programs: absolute and relative
727    /// pathed invocations resolve without `PATH` and stay hermetic.
728    #[test]
729    #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
730    fn apply_ctx_skips_path_check_for_pathed_program() {
731        let (_temp, ctx) = make_ctx(&[("FOO", "bar")]);
732        let mut unix_cmd = ProcessCommand::new("/bin/prog");
733        apply_ctx(&mut unix_cmd, &ctx, "/bin/prog", false).expect("absolute path needs no PATH");
734        let mut rel_cmd = ProcessCommand::new("sub/prog");
735        apply_ctx(&mut rel_cmd, &ctx, "sub/prog", false).expect("relative path needs no PATH");
736    }
737
738    /// The NT loader anchor is seeded, never injected: without a
739    /// script `SystemRoot` the anchor check bails on Windows (naming
740    /// the fix); elsewhere there is nothing to check and staging
741    /// still succeeds.
742    #[test]
743    #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
744    fn apply_ctx_systemroot_check_follows_platform() {
745        // Raw map, bypassing `make_ctx` (which mirrors the seeded NT
746        // loader anchor): proves the fail-safe trips on a genuinely
747        // anchorless map instead of passing through helper staging.
748        let map: HashMap<String, String> = [(oxdock_env::os::PATH, "test-path")]
749            .iter()
750            .map(|(key, value)| (key.to_string(), value.to_string()))
751            .collect();
752        let (_temp, ctx) = make_ctx_from_map(map);
753        let mut cmd = ProcessCommand::new("prog");
754        #[allow(clippy::disallowed_macros)]
755        if cfg!(windows) {
756            let err =
757                apply_ctx(&mut cmd, &ctx, "prog", false).expect_err("SystemRoot anchor must trip");
758            assert!(
759                err.to_string().contains("SystemRoot"),
760                "unexpected error: {err}"
761            );
762        } else {
763            apply_ctx(&mut cmd, &ctx, "prog", false).expect("no anchor beyond PATH on unix");
764        }
765    }
766
767    /// Windows casing: `Path` satisfies the case-insensitive anchor
768    /// and stages exactly as spelled. No canonicalization, no drops:
769    /// the map is staged verbatim.
770    #[test]
771    #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
772    fn apply_ctx_accepts_windows_casing_variants() {
773        // Deliberate non-canonical spelling: this test proves the
774        // anchor matches case-insensitively while staging keeps the
775        // script spelling, so the literal stays.
776        let (_temp, ctx) = make_ctx(&[("Path", "test-path")]);
777        let mut cmd = ProcessCommand::new("prog");
778        #[allow(clippy::disallowed_macros)]
779        if cfg!(windows) {
780            apply_ctx(&mut cmd, &ctx, "prog", false).expect("cased PATH satisfies the anchor");
781            let envs: HashMap<String, String> = cmd
782                .get_envs()
783                .map(|(k, v)| {
784                    (
785                        k.to_string_lossy().into_owned(),
786                        v.map(|value| value.to_string_lossy().into_owned())
787                            .unwrap_or_default(),
788                    )
789                })
790                .collect();
791            assert_eq!(envs.get("Path").map(String::as_str), Some("test-path"));
792        } else {
793            let err = apply_ctx(&mut cmd, &ctx, "prog", false)
794                .expect_err("cased PATH is not PATH on unix");
795            assert!(
796                err.to_string().contains("INHERIT_ENV [PATH]"),
797                "unexpected error: {err}"
798            );
799        }
800    }
801
802    /// End-to-end closedness: a real child sees declared vars and cannot see
803    /// a host-only sentinel, proving the boundary past `apply_ctx` staging.
804    #[cfg_attr(miri, ignore = "spawns a real child process, unsupported under Miri")]
805    #[test]
806    #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
807    fn spawned_child_does_not_see_host_env() {
808        // RAII-guarded: a mid-test failure still restores process env.
809        let _probe_guard = crate::TestEnvGuard::set("OXDOCK_CLOSED_ENV_PROBE", "leaked");
810        let (_temp, ctx) = make_ctx_with_host_exec(&[("OXDOCK_CHILD_MARKER", "here")]);
811        let mut pm = ShellProcessManager;
812        #[cfg(windows)]
813        let script = "if defined OXDOCK_CLOSED_ENV_PROBE (echo PROBE-SEEN) else (echo PROBE-CLEAN)& echo MARKER-%OXDOCK_CHILD_MARKER%";
814        #[cfg(not(windows))]
815        let script = "echo \"probe=${OXDOCK_CLOSED_ENV_PROBE:-unset} marker=${OXDOCK_CHILD_MARKER:-missing}\"";
816        let options = CommandOptions {
817            stdout: CommandStdout::Capture,
818            ..Default::default()
819        };
820        let out = match pm.run_command(&ctx, script, options).expect("run") {
821            CommandResult::Captured(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
822            CommandResult::Completed => panic!("expected Captured, got Completed"),
823            CommandResult::Background(_) => panic!("expected Captured, got Background"),
824        };
825        #[cfg(windows)]
826        {
827            assert!(out.contains("PROBE-CLEAN"), "child saw host env: {out}");
828            assert!(
829                out.contains("MARKER-here"),
830                "child missed script env: {out}"
831            );
832        }
833        #[cfg(not(windows))]
834        {
835            assert!(out.contains("probe=unset"), "child saw host env: {out}");
836            assert!(
837                out.contains("marker=here"),
838                "child missed script env: {out}"
839            );
840        }
841    }
842}