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#[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 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#[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 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 let owned = writer.take()?;
115 command.stderr(Stdio::from(owned));
116 None
117 }
118 };
119
120 let stdin_stream: Option<SharedInput> = match stdin {
121 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 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 #[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 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 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 #[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 #[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(&[(oxdock_env::os::PATH, "test-path")]);
391 let mut pm = ShellProcessManager;
392 let options = CommandOptions {
393 mode: CommandMode::Background,
394 stdout: CommandStdout::Capture,
395 ..Default::default()
396 };
397 let err = match pm.run_command(&ctx, "echo hi", options) {
398 Err(err) => err,
399 Ok(_) => panic!("background capture must bail"),
400 };
401 assert!(
402 err.to_string().contains("cannot capture stdout"),
403 "unexpected error: {err}"
404 );
405 }
406
407 #[cfg_attr(
408 miri,
409 ignore = "spawns processes; Miri does not support process execution"
410 )]
411 #[test]
412 fn foreground_capture_returns_child_stdout_bytes() {
413 let (_temp, ctx) = make_ctx_with_host_exec(&[]);
414 let mut pm = ShellProcessManager;
415 let options = CommandOptions {
416 stdout: CommandStdout::Capture,
417 ..Default::default()
418 };
419 match pm
420 .run_command(&ctx, "echo hello-capture", options)
421 .expect("run")
422 {
423 CommandResult::Captured(bytes) => {
424 let out = String::from_utf8_lossy(&bytes);
425 assert!(out.contains("hello-capture"), "captured: {out}");
426 }
427 CommandResult::Completed => panic!("expected Captured, got Completed"),
428 CommandResult::Background(_) => panic!("expected Captured, got Background"),
429 }
430 }
431
432 #[cfg_attr(
433 miri,
434 ignore = "spawns processes; Miri does not support process execution"
435 )]
436 #[test]
437 fn run_argv_spawns_directly_without_shell() {
438 #[allow(clippy::disallowed_macros)]
445 #[cfg(unix)]
446 let home = std::env::var(oxdock_env::os::unix::HOME).unwrap_or_default();
447 #[allow(clippy::disallowed_macros)]
448 #[cfg(windows)]
449 let home = std::env::var(oxdock_env::os::windows::USERPROFILE).unwrap_or_default();
450 #[allow(clippy::disallowed_macros)]
451 #[cfg(unix)]
452 let home_key = oxdock_env::os::unix::HOME;
453 #[allow(clippy::disallowed_macros)]
454 #[cfg(windows)]
455 let home_key = oxdock_env::os::windows::USERPROFILE;
456 let (_temp, ctx) = make_ctx_with_host_exec(&[(home_key, home.as_str())]);
457 let mut pm = ShellProcessManager;
458 let options = CommandOptions {
459 stdout: CommandStdout::Capture,
460 ..Default::default()
461 };
462 let argv = vec!["cargo".to_string(), "--version".to_string()];
466 match pm.run_argv(&ctx, &argv, options).expect("run_argv") {
467 CommandResult::Captured(bytes) => {
468 let out = String::from_utf8_lossy(&bytes);
469 assert!(out.contains("cargo"), "captured: {out}");
470 }
471 CommandResult::Completed => panic!("expected Captured, got Completed"),
472 CommandResult::Background(_) => panic!("expected Captured, got Background"),
473 }
474 }
475
476 #[test]
477 fn run_argv_rejects_empty_argv_without_spawning() {
478 let (_temp, ctx) = make_ctx_with_host_exec(&[]);
479 let mut pm = ShellProcessManager;
480 let err = match pm.run_argv(&ctx, &[], CommandOptions::foreground()) {
481 Err(err) => err,
482 Ok(_) => panic!("empty argv must bail"),
483 };
484 assert!(
485 err.to_string().contains("at least one argument"),
486 "unexpected error: {err}"
487 );
488 }
489
490 fn large_output_script() -> &'static str {
491 #[cfg(windows)]
492 {
493 "for /l %i in (1,1,20000) do @echo 0123456789abcdef"
494 }
495 #[cfg(not(windows))]
496 {
497 "i=0; while [ $i -lt 20000 ]; do echo 0123456789abcdef; i=$((i+1)); done"
498 }
499 }
500
501 #[cfg_attr(
502 miri,
503 ignore = "spawns processes; Miri does not support process execution"
504 )]
505 #[test]
506 fn streams_large_stdout_through_shared_output_without_deadlock() {
507 let (_temp, ctx) = make_ctx_with_host_exec(&[]);
508 let mut pm = ShellProcessManager;
509 let buffer = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
510 let options = CommandOptions {
511 stdout: CommandStdout::Stream(buffer.clone()),
512 ..Default::default()
513 };
514 pm.run_command(&ctx, large_output_script(), options)
515 .expect("run");
516 let bytes = buffer.lock().expect("buffer lock").len();
517 assert!(bytes >= 300_000, "streamed only {bytes} bytes");
520 }
521
522 #[cfg_attr(
523 miri,
524 ignore = "spawns processes; Miri does not support process execution"
525 )]
526 #[test]
527 fn foreground_stdin_is_piped_through_copy_thread() {
528 let (_temp, ctx) = make_ctx_with_host_exec(&[]);
529 let mut pm = ShellProcessManager;
530 #[cfg(windows)]
532 let input: &[u8] = b"b\r\na\r\n";
533 #[cfg(not(windows))]
534 let input: &[u8] = b"b\na\n";
535 let payload: SharedInput =
536 std::sync::Arc::new(std::sync::Mutex::new(std::io::Cursor::new(input.to_vec())));
537 let options = CommandOptions {
538 stdin: CommandStdin::Stream(payload),
539 stdout: CommandStdout::Capture,
540 ..Default::default()
541 };
542 match pm.run_command(&ctx, "sort", options).expect("run") {
544 CommandResult::Captured(bytes) => {
545 assert!(bytes.starts_with(b"a"), "sorted output: {:?}", bytes);
546 assert!(windows_compatible_contains(&bytes, b"b"));
547 }
548 CommandResult::Completed => panic!("expected Captured, got Completed"),
549 CommandResult::Background(_) => panic!("expected Captured, got Background"),
550 }
551 }
552
553 fn windows_compatible_contains(haystack: &[u8], needle: &[u8]) -> bool {
554 haystack.windows(needle.len()).any(|w| w == needle)
555 }
556
557 #[cfg(not(miri))]
561 #[test]
562 fn os_pipe_streams_producer_to_consumer_with_eof() {
563 use crate::contract::{BackgroundHandle, create_os_pipe};
564
565 let (_temp, ctx) = make_ctx_with_host_exec(&[]);
566 let (reader, writer) = create_os_pipe().expect("os pipe");
567 let mut pm = ShellProcessManager;
568
569 let producer = match pm
570 .run_command(
571 &ctx,
572 "echo hello-os-pipe",
573 CommandOptions {
574 mode: CommandMode::Background,
575 stdout: CommandStdout::OsPipe(writer),
576 ..Default::default()
577 },
578 )
579 .expect("spawn producer")
580 {
581 CommandResult::Background(handle) => handle,
582 _ => panic!("expected background producer handle"),
583 };
584
585 let options = CommandOptions {
586 stdin: CommandStdin::OsPipe(reader),
587 stdout: CommandStdout::Capture,
588 ..Default::default()
589 };
590 let captured = match pm.run_command(&ctx, "sort", options).expect("run consumer") {
592 CommandResult::Captured(bytes) => bytes,
593 _ => panic!("expected captured consumer output"),
594 };
595 assert!(
596 windows_compatible_contains(&captured, b"hello-os-pipe"),
597 "piped output: {:?}",
598 String::from_utf8_lossy(&captured)
599 );
600
601 let mut producer = producer;
602 let status = producer.wait().expect("wait producer");
603 assert!(status.success(), "producer failed: {status:?}");
604
605 let (spent_reader, spent_writer) = create_os_pipe().expect("os pipe");
607 spent_reader.take().expect("first reader take");
608 assert!(
609 spent_reader.take().is_err(),
610 "reader take must be single use"
611 );
612 spent_writer.take().expect("first writer take");
613 assert!(
614 spent_writer.take().is_err(),
615 "writer take must be single use"
616 );
617 }
618
619 #[test]
620 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
621 fn apply_ctx_stages_map_verbatim() {
622 let (_temp, ctx) = make_ctx(&[
629 (oxdock_env::cargo::TARGET_DIR, "custom-target"),
630 ("FOO", "bar"),
631 (oxdock_env::os::PATH, "test-path"),
632 ]);
633 let mut cmd = ProcessCommand::new("prog");
634 apply_ctx(&mut cmd, &ctx, "prog", false).expect("apply with explicit PATH");
635 let envs: HashMap<String, String> = cmd
636 .get_envs()
637 .map(|(k, v)| {
638 (
639 k.to_string_lossy().into_owned(),
640 v.map(|value| value.to_string_lossy().into_owned())
641 .unwrap_or_default(),
642 )
643 })
644 .collect();
645 assert_eq!(
646 envs.get(oxdock_env::cargo::TARGET_DIR).map(String::as_str),
647 Some("custom-target")
648 );
649 assert_eq!(envs.get("FOO").map(String::as_str), Some("bar"));
650
651 let (_temp, ctx) = make_ctx(&[(oxdock_env::os::PATH, "test-path")]);
653 let mut cmd = ProcessCommand::new("prog");
654 apply_ctx(&mut cmd, &ctx, "prog", false).expect("apply with explicit PATH");
655 let envs: HashMap<String, String> = cmd
656 .get_envs()
657 .map(|(k, v)| {
658 (
659 k.to_string_lossy().into_owned(),
660 v.map(|value| value.to_string_lossy().into_owned())
661 .unwrap_or_default(),
662 )
663 })
664 .collect();
665 assert!(
666 !envs.contains_key(oxdock_env::cargo::TARGET_DIR),
667 "unstaged names must stay out: {envs:?}"
668 );
669 }
670
671 #[test]
672 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
673 fn apply_ctx_sets_working_directory_from_guarded_cwd() {
674 let (_temp, ctx) = make_ctx(&[(oxdock_env::os::PATH, "test-path")]);
675 let mut cmd = ProcessCommand::new("prog");
676 apply_ctx(&mut cmd, &ctx, "prog", false).expect("apply with explicit PATH");
677 let expected = oxdock_fs::command_path(match ctx.cwd() {
678 PolicyPath::Guarded(guarded) => guarded,
679 PolicyPath::Unguarded(_) => panic!("expected guarded cwd"),
680 });
681 assert_eq!(cmd.get_current_dir(), Some(expected.as_ref()));
682 }
683
684 #[test]
687 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
688 fn apply_ctx_clears_host_env() {
689 let _probe_guard = crate::TestEnvGuard::set("OXDOCK_CLOSED_ENV_PROBE", "leaked");
691 let (_temp, ctx) = make_ctx(&[(oxdock_env::os::PATH, "test-path"), ("DECLARED", "yes")]);
692 let mut cmd = ProcessCommand::new("prog");
693 apply_ctx(&mut cmd, &ctx, "prog", false).expect("apply with explicit PATH");
694 let envs: HashMap<String, String> = cmd
695 .get_envs()
696 .map(|(k, v)| {
697 (
698 k.to_string_lossy().into_owned(),
699 v.map(|value| value.to_string_lossy().into_owned())
700 .unwrap_or_default(),
701 )
702 })
703 .collect();
704 assert!(
705 !envs.contains_key("OXDOCK_CLOSED_ENV_PROBE"),
706 "host env must not reach children: {envs:?}"
707 );
708 assert_eq!(envs.get("DECLARED").map(String::as_str), Some("yes"));
709 assert_eq!(
710 envs.get(oxdock_env::os::PATH).map(String::as_str),
711 Some("test-path")
712 );
713 }
714
715 #[test]
720 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
721 fn apply_ctx_bails_for_bare_program_without_path() {
722 let (_temp, ctx) = make_ctx(&[("FOO", "bar")]);
723 let mut cmd = ProcessCommand::new("prog");
724 let err = apply_ctx(&mut cmd, &ctx, "prog", false).expect_err("PATH anchor must trip");
725 assert!(
726 err.to_string().contains("INHERIT_ENV [PATH]"),
727 "unexpected error: {err}"
728 );
729 }
730
731 #[test]
734 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
735 fn apply_ctx_skips_path_check_for_pathed_program() {
736 let (_temp, ctx) = make_ctx(&[("FOO", "bar")]);
737 let mut unix_cmd = ProcessCommand::new("/bin/prog");
738 apply_ctx(&mut unix_cmd, &ctx, "/bin/prog", false).expect("absolute path needs no PATH");
739 let mut rel_cmd = ProcessCommand::new("sub/prog");
740 apply_ctx(&mut rel_cmd, &ctx, "sub/prog", false).expect("relative path needs no PATH");
741 }
742
743 #[test]
748 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
749 fn apply_ctx_systemroot_check_follows_platform() {
750 let map: HashMap<String, String> = [(oxdock_env::os::PATH, "test-path")]
754 .iter()
755 .map(|(key, value)| (key.to_string(), value.to_string()))
756 .collect();
757 let (_temp, ctx) = make_ctx_from_map(map);
758 let mut cmd = ProcessCommand::new("prog");
759 #[allow(clippy::disallowed_macros)]
760 if cfg!(windows) {
761 let err =
762 apply_ctx(&mut cmd, &ctx, "prog", false).expect_err("SystemRoot anchor must trip");
763 assert!(
764 err.to_string().contains("SystemRoot"),
765 "unexpected error: {err}"
766 );
767 } else {
768 apply_ctx(&mut cmd, &ctx, "prog", false).expect("no anchor beyond PATH on unix");
769 }
770 }
771
772 #[test]
776 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
777 fn apply_ctx_accepts_windows_casing_variants() {
778 let (_temp, ctx) = make_ctx(&[("Path", "test-path")]);
782 let mut cmd = ProcessCommand::new("prog");
783 #[allow(clippy::disallowed_macros)]
784 if cfg!(windows) {
785 apply_ctx(&mut cmd, &ctx, "prog", false).expect("cased PATH satisfies the anchor");
786 let envs: HashMap<String, String> = cmd
787 .get_envs()
788 .map(|(k, v)| {
789 (
790 k.to_string_lossy().into_owned(),
791 v.map(|value| value.to_string_lossy().into_owned())
792 .unwrap_or_default(),
793 )
794 })
795 .collect();
796 assert_eq!(envs.get("Path").map(String::as_str), Some("test-path"));
797 } else {
798 let err = apply_ctx(&mut cmd, &ctx, "prog", false)
799 .expect_err("cased PATH is not PATH on unix");
800 assert!(
801 err.to_string().contains("INHERIT_ENV [PATH]"),
802 "unexpected error: {err}"
803 );
804 }
805 }
806
807 #[cfg_attr(miri, ignore = "spawns a real child process, unsupported under Miri")]
810 #[test]
811 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
812 fn spawned_child_does_not_see_host_env() {
813 let _probe_guard = crate::TestEnvGuard::set("OXDOCK_CLOSED_ENV_PROBE", "leaked");
815 let (_temp, ctx) = make_ctx_with_host_exec(&[("OXDOCK_CHILD_MARKER", "here")]);
816 let mut pm = ShellProcessManager;
817 #[cfg(windows)]
818 let script = "if defined OXDOCK_CLOSED_ENV_PROBE (echo PROBE-SEEN) else (echo PROBE-CLEAN)& echo MARKER-%OXDOCK_CHILD_MARKER%";
819 #[cfg(not(windows))]
820 let script = "echo \"probe=${OXDOCK_CLOSED_ENV_PROBE:-unset} marker=${OXDOCK_CHILD_MARKER:-missing}\"";
821 let options = CommandOptions {
822 stdout: CommandStdout::Capture,
823 ..Default::default()
824 };
825 let out = match pm.run_command(&ctx, script, options).expect("run") {
826 CommandResult::Captured(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
827 CommandResult::Completed => panic!("expected Captured, got Completed"),
828 CommandResult::Background(_) => panic!("expected Captured, got Background"),
829 };
830 #[cfg(windows)]
831 {
832 assert!(out.contains("PROBE-CLEAN"), "child saw host env: {out}");
833 assert!(
834 out.contains("MARKER-here"),
835 "child missed script env: {out}"
836 );
837 }
838 #[cfg(not(windows))]
839 {
840 assert!(out.contains("probe=unset"), "child saw host env: {out}");
841 assert!(
842 out.contains("marker=here"),
843 "child missed script env: {out}"
844 );
845 }
846 }
847}