Skip to main content

oxdock_process/
shell_manager.rs

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