1use std::sync::{Arc, Mutex};
2
3#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
4use std::process::Command as ProcessCommand;
5#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
6use std::process::Stdio;
7
8use oxdock_diagnostics::DiagnosticResult;
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::diagnostics as proc_diag;
17use crate::shell::{batch_shell, direct_cmd, shell_cmd};
18
19#[derive(Clone, Default)]
21#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
22pub struct ShellProcessManager;
23
24impl ProcessManager for ShellProcessManager {
25 type Handle = ChildHandle;
26
27 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
28 fn run_command(
29 &mut self,
30 ctx: &CommandContext,
31 script: &str,
32 options: CommandOptions,
33 ) -> DiagnosticResult<CommandResult<Self::Handle>> {
34 if std::env::var_os(PROCESS_DEBUG_ENV_VAR).is_some() {
35 eprintln!("oxbook run_command: {script}");
36 }
37 let mut command = shell_cmd(script);
38 let program = batch_shell();
39 apply_ctx(&mut command, ctx, &program, true)?;
43 let CommandOptions {
44 mode,
45 stdin,
46 stdout,
47 stderr,
48 } = options;
49 run_prepared(&mut command, mode, stdin, stdout, stderr)
50 }
51
52 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
53 fn run_argv(
54 &mut self,
55 ctx: &CommandContext,
56 argv: &[String],
57 options: CommandOptions,
58 ) -> DiagnosticResult<CommandResult<Self::Handle>> {
59 if std::env::var_os(PROCESS_DEBUG_ENV_VAR).is_some() {
60 eprintln!("oxbook run_argv: {argv:?}");
61 }
62 let mut command = direct_cmd(argv)?;
63 let program = argv.first().map(String::as_str).unwrap_or_default();
64 apply_ctx(&mut command, ctx, program, false)?;
65 let CommandOptions {
66 mode,
67 stdin,
68 stdout,
69 stderr,
70 } = options;
71 run_prepared(&mut command, mode, stdin, stdout, stderr)
72 }
73}
74
75#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
80fn run_prepared(
81 command: &mut ProcessCommand,
82 mode: CommandMode,
83 stdin: CommandStdin,
84 stdout: CommandStdout,
85 stderr: CommandStderr,
86) -> DiagnosticResult<CommandResult<ChildHandle>> {
87 let (stdout_stream, capture_buf) = match stdout {
88 CommandStdout::Inherit => (None, None),
89 CommandStdout::Stream(stream) => (Some(stream), None),
90 CommandStdout::Capture => {
91 if matches!(mode, CommandMode::Background) {
92 return Err(proc_diag::run_bg_capture_unsupported());
93 }
94 let buf = Arc::new(Mutex::new(Vec::new()));
95 let writer: SharedOutput = buf.clone();
96 (Some(writer), Some(buf))
97 }
98 #[cfg(not(miri))]
99 CommandStdout::OsPipe(writer) => {
100 let owned = writer.take()?;
104 command.stdout(Stdio::from(owned));
105 (None, None)
106 }
107 };
108
109 let stderr_stream = match stderr {
110 CommandStderr::Inherit => None,
111 CommandStderr::Stream(stream) => Some(stream),
112 #[cfg(not(miri))]
113 CommandStderr::OsPipe(writer) => {
114 let owned = writer.take()?;
116 command.stderr(Stdio::from(owned));
117 None
118 }
119 };
120
121 let stdin_stream: Option<SharedInput> = match stdin {
122 CommandStdin::Null => {
124 command.stdin(Stdio::null());
125 None
126 }
127 CommandStdin::Inherit => None,
128 CommandStdin::Stream(reader) => Some(reader),
129 #[cfg(not(miri))]
130 CommandStdin::OsPipe(reader) => {
131 let owned = reader.take()?;
133 command.stdin(Stdio::from(owned));
134 None
135 }
136 };
137 match mode {
138 CommandMode::Foreground => {
139 let mut handle =
140 spawn_child_with_streams(command, stdin_stream, stdout_stream, stderr_stream)?;
141 let status = handle
142 .wait()
143 .map_err(|err| proc_diag::run_wait_failed(&*command, &err))?;
144 if !status.success() {
145 return Err(proc_diag::run_command_failed(&*command, &status));
146 }
147 if let Some(buf) = capture_buf {
148 let mut guard = buf
149 .lock()
150 .map_err(|_| proc_diag::run_capture_lock_poisoned())?;
151 return Ok(CommandResult::Captured(std::mem::take(&mut *guard)));
152 }
153 Ok(CommandResult::Completed)
154 }
155 CommandMode::Background => {
156 #[cfg(unix)]
162 {
163 use std::os::unix::process::CommandExt;
164 command.process_group(0);
165 }
166 let handle =
167 spawn_child_with_streams(command, stdin_stream, stdout_stream, stderr_stream)?;
168 Ok(CommandResult::Background(handle))
169 }
170 }
171}
172
173#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
174fn apply_ctx(
175 command: &mut ProcessCommand,
176 ctx: &CommandContext,
177 program: &str,
178 require_path: bool,
179) -> DiagnosticResult<()> {
180 let cwd_path: std::borrow::Cow<std::path::Path> = match ctx.cwd() {
196 PolicyPath::Guarded(p) => oxdock_fs::command_path(p),
197 PolicyPath::Unguarded(p) => std::borrow::Cow::Borrowed(p.as_path()),
198 };
199 command.current_dir(cwd_path);
200 let staged = ctx.envs().as_ref().clone();
205 crate::env_policy::check_spawn_anchors(program, &staged, require_path)?;
206 command.env_clear();
207 command.envs(&staged);
208 Ok(())
209}
210
211#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
212fn spawn_child_with_streams(
213 cmd: &mut ProcessCommand,
214 stdin: Option<SharedInput>,
215 stdout: Option<SharedOutput>,
216 stderr: Option<SharedOutput>,
217) -> DiagnosticResult<ChildHandle> {
218 if stdin.is_some() {
219 cmd.stdin(Stdio::piped());
220 }
221 if stdout.is_some() {
222 cmd.stdout(Stdio::piped());
223 }
224 if stderr.is_some() {
225 cmd.stderr(Stdio::piped());
226 }
227
228 let mut child = cmd
229 .spawn()
230 .map_err(|e| proc_diag::spawn_failed(&*cmd, &e))?;
231 let mut io_threads = Vec::new();
232 let mut stdin_thread = None;
233
234 if let Some(stdin_stream) = stdin
235 && let Some(mut child_stdin) = child.stdin.take()
236 {
237 let thread = std::thread::spawn(move || {
238 if let Ok(mut guard) = stdin_stream.lock() {
239 let _ = std::io::copy(&mut *guard, &mut child_stdin);
240 }
241 });
242 stdin_thread = Some(thread);
243 }
244
245 if let Some(stdout_stream) = stdout
246 && let Some(mut child_stdout) = child.stdout.take()
247 {
248 let stream_clone = stdout_stream.clone();
249 let thread = std::thread::spawn(move || {
250 let mut buf = [0u8; 1024];
251 loop {
252 match std::io::Read::read(&mut child_stdout, &mut buf) {
253 Ok(0) => break,
254 Ok(n) => {
255 if let Ok(mut guard) = stream_clone.lock() {
256 if std::io::Write::write_all(&mut *guard, &buf[..n]).is_err() {
257 break;
258 }
259 let _ = std::io::Write::flush(&mut *guard);
260 }
261 }
262 Err(_) => break,
263 }
264 }
265 });
266 io_threads.push(thread);
267 }
268
269 if let Some(stderr_stream) = stderr
270 && let Some(mut child_stderr) = child.stderr.take()
271 {
272 let stream_clone = stderr_stream.clone();
273 let thread = std::thread::spawn(move || {
274 let mut buf = [0u8; 1024];
275 loop {
276 match std::io::Read::read(&mut child_stderr, &mut buf) {
277 Ok(0) => break,
278 Ok(n) => {
279 if let Ok(mut guard) = stream_clone.lock() {
280 if std::io::Write::write_all(&mut *guard, &buf[..n]).is_err() {
281 break;
282 }
283 let _ = std::io::Write::flush(&mut *guard);
284 }
285 }
286 Err(_) => break,
287 }
288 }
289 });
290 io_threads.push(thread);
291 }
292
293 ChildHandle::new(child, stdin_thread, io_threads)
294}
295
296#[cfg(test)]
297mod tests {
298 use super::*;
299 use oxdock_fs::GuardedPath;
300 use oxdock_fs::env as oxdock_env;
301 use std::collections::HashMap;
302
303 fn make_ctx_from_map(
304 map: HashMap<String, String>,
305 ) -> (oxdock_fs::GuardedTempDir, CommandContext) {
306 let temp = GuardedPath::tempdir().expect("tempdir");
307 let guard = temp.as_guarded_path().clone();
308 let cwd: PolicyPath = guard.clone().into();
309 let scratch = oxdock_fs::reserve_cargo_scratch().expect("scratch");
310 let ctx = CommandContext::from_map(&cwd, &map, &scratch, &guard, &guard);
311 (temp, ctx)
312 }
313
314 #[cfg(windows)]
322 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
323 fn with_windows_anchor(mut map: HashMap<String, String>) -> HashMap<String, String> {
324 if !crate::env_policy::has_var(&map, oxdock_env::os::windows::SYSTEM_ROOT)
325 && let Ok(root) = std::env::var(oxdock_env::os::windows::SYSTEM_ROOT)
326 {
327 map.insert(oxdock_env::os::windows::SYSTEM_ROOT.to_string(), root);
328 }
329 map
330 }
331
332 fn make_ctx(envs: &[(&str, &str)]) -> (oxdock_fs::GuardedTempDir, CommandContext) {
333 let map: HashMap<String, String> = envs
334 .iter()
335 .map(|(key, value)| (key.to_string(), value.to_string()))
336 .collect();
337 #[cfg(windows)]
338 let map = with_windows_anchor(map);
339 make_ctx_from_map(map)
340 }
341
342 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
347 fn host_exec_env() -> HashMap<String, String> {
348 let mut map = HashMap::new();
349 if let Ok(path) = std::env::var(oxdock_env::os::PATH) {
350 map.insert(oxdock_env::os::PATH.to_string(), path);
351 }
352 #[allow(clippy::disallowed_macros)]
353 if cfg!(windows) {
354 for key in [
355 oxdock_env::os::windows::SYSTEM_ROOT,
356 oxdock_env::os::windows::PATHEXT,
357 oxdock_env::os::windows::COMSPEC,
358 oxdock_env::os::windows::TEMP,
359 oxdock_env::os::windows::TMP,
360 ] {
361 if let Ok(value) = std::env::var(key) {
362 map.insert(key.to_string(), value);
363 }
364 }
365 }
366 map
367 }
368
369 fn make_ctx_with_host_exec(
370 extra: &[(&str, &str)],
371 ) -> (oxdock_fs::GuardedTempDir, CommandContext) {
372 let temp = GuardedPath::tempdir().expect("tempdir");
373 let guard = temp.as_guarded_path().clone();
374 let cwd: PolicyPath = guard.clone().into();
375 let mut map = host_exec_env();
376 for (key, value) in extra {
377 map.insert(key.to_string(), value.to_string());
378 }
379 let scratch = oxdock_fs::reserve_cargo_scratch().expect("scratch");
380 let ctx = CommandContext::from_map(&cwd, &map, &scratch, &guard, &guard);
381 (temp, ctx)
382 }
383
384 #[test]
385 fn background_capture_stdout_bails_without_spawning() {
386 let (_temp, ctx) = make_ctx_with_host_exec(&[(oxdock_env::os::PATH, "test-path")]);
392 let mut pm = ShellProcessManager;
393 let options = CommandOptions {
394 mode: CommandMode::Background,
395 stdout: CommandStdout::Capture,
396 ..Default::default()
397 };
398 let err = match pm.run_command(&ctx, "echo hi", options) {
399 Err(err) => err,
400 Ok(_) => panic!("background capture must bail"),
401 };
402 assert!(
403 err.to_string().contains("cannot capture stdout"),
404 "unexpected error: {err}"
405 );
406 }
407
408 #[cfg_attr(
409 miri,
410 ignore = "spawns processes; Miri does not support process execution"
411 )]
412 #[test]
413 fn foreground_capture_returns_child_stdout_bytes() {
414 let (_temp, ctx) = make_ctx_with_host_exec(&[]);
415 let mut pm = ShellProcessManager;
416 let options = CommandOptions {
417 stdout: CommandStdout::Capture,
418 ..Default::default()
419 };
420 match pm
421 .run_command(&ctx, "echo hello-capture", options)
422 .expect("run")
423 {
424 CommandResult::Captured(bytes) => {
425 let out = String::from_utf8_lossy(&bytes);
426 assert!(out.contains("hello-capture"), "captured: {out}");
427 }
428 CommandResult::Completed => panic!("expected Captured, got Completed"),
429 CommandResult::Background(_) => panic!("expected Captured, got Background"),
430 }
431 }
432
433 #[cfg_attr(
434 miri,
435 ignore = "spawns processes; Miri does not support process execution"
436 )]
437 #[test]
438 fn run_argv_spawns_directly_without_shell() {
439 #[allow(clippy::disallowed_macros)]
446 #[cfg(unix)]
447 let home = std::env::var(oxdock_env::os::unix::HOME).unwrap_or_default();
448 #[allow(clippy::disallowed_macros)]
449 #[cfg(windows)]
450 let home = std::env::var(oxdock_env::os::windows::USERPROFILE).unwrap_or_default();
451 #[allow(clippy::disallowed_macros)]
452 #[cfg(unix)]
453 let home_key = oxdock_env::os::unix::HOME;
454 #[allow(clippy::disallowed_macros)]
455 #[cfg(windows)]
456 let home_key = oxdock_env::os::windows::USERPROFILE;
457 let (_temp, ctx) = make_ctx_with_host_exec(&[(home_key, home.as_str())]);
458 let mut pm = ShellProcessManager;
459 let options = CommandOptions {
460 stdout: CommandStdout::Capture,
461 ..Default::default()
462 };
463 let argv = vec!["cargo".to_string(), "--version".to_string()];
467 match pm.run_argv(&ctx, &argv, options).expect("run_argv") {
468 CommandResult::Captured(bytes) => {
469 let out = String::from_utf8_lossy(&bytes);
470 assert!(out.contains("cargo"), "captured: {out}");
471 }
472 CommandResult::Completed => panic!("expected Captured, got Completed"),
473 CommandResult::Background(_) => panic!("expected Captured, got Background"),
474 }
475 }
476
477 #[test]
478 fn run_argv_rejects_empty_argv_without_spawning() {
479 let (_temp, ctx) = make_ctx_with_host_exec(&[]);
480 let mut pm = ShellProcessManager;
481 let err = match pm.run_argv(&ctx, &[], CommandOptions::foreground()) {
482 Err(err) => err,
483 Ok(_) => panic!("empty argv must bail"),
484 };
485 assert!(
486 err.to_string().contains("at least one argument"),
487 "unexpected error: {err}"
488 );
489 }
490
491 fn large_output_script() -> &'static str {
492 #[cfg(windows)]
493 {
494 "for /l %i in (1,1,20000) do @echo 0123456789abcdef"
495 }
496 #[cfg(not(windows))]
497 {
498 "i=0; while [ $i -lt 20000 ]; do echo 0123456789abcdef; i=$((i+1)); done"
499 }
500 }
501
502 #[cfg_attr(
503 miri,
504 ignore = "spawns processes; Miri does not support process execution"
505 )]
506 #[test]
507 fn streams_large_stdout_through_shared_output_without_deadlock() {
508 let (_temp, ctx) = make_ctx_with_host_exec(&[]);
509 let mut pm = ShellProcessManager;
510 let buffer = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
511 let options = CommandOptions {
512 stdout: CommandStdout::Stream(buffer.clone()),
513 ..Default::default()
514 };
515 pm.run_command(&ctx, large_output_script(), options)
516 .expect("run");
517 let bytes = buffer.lock().expect("buffer lock").len();
518 assert!(bytes >= 300_000, "streamed only {bytes} bytes");
521 }
522
523 #[cfg_attr(
524 miri,
525 ignore = "spawns processes; Miri does not support process execution"
526 )]
527 #[test]
528 fn foreground_stdin_is_piped_through_copy_thread() {
529 let (_temp, ctx) = make_ctx_with_host_exec(&[]);
530 let mut pm = ShellProcessManager;
531 #[cfg(windows)]
533 let input: &[u8] = b"b\r\na\r\n";
534 #[cfg(not(windows))]
535 let input: &[u8] = b"b\na\n";
536 let payload: SharedInput =
537 std::sync::Arc::new(std::sync::Mutex::new(std::io::Cursor::new(input.to_vec())));
538 let options = CommandOptions {
539 stdin: CommandStdin::Stream(payload),
540 stdout: CommandStdout::Capture,
541 ..Default::default()
542 };
543 match pm.run_command(&ctx, "sort", options).expect("run") {
545 CommandResult::Captured(bytes) => {
546 assert!(bytes.starts_with(b"a"), "sorted output: {:?}", bytes);
547 assert!(windows_compatible_contains(&bytes, b"b"));
548 }
549 CommandResult::Completed => panic!("expected Captured, got Completed"),
550 CommandResult::Background(_) => panic!("expected Captured, got Background"),
551 }
552 }
553
554 fn windows_compatible_contains(haystack: &[u8], needle: &[u8]) -> bool {
555 haystack.windows(needle.len()).any(|w| w == needle)
556 }
557
558 #[cfg(not(miri))]
562 #[test]
563 fn os_pipe_streams_producer_to_consumer_with_eof() {
564 use crate::contract::{BackgroundHandle, create_os_pipe};
565
566 let (_temp, ctx) = make_ctx_with_host_exec(&[]);
567 let (reader, writer) = create_os_pipe().expect("os pipe");
568 let mut pm = ShellProcessManager;
569
570 let producer = match pm
571 .run_command(
572 &ctx,
573 "echo hello-os-pipe",
574 CommandOptions {
575 mode: CommandMode::Background,
576 stdout: CommandStdout::OsPipe(writer),
577 ..Default::default()
578 },
579 )
580 .expect("spawn producer")
581 {
582 CommandResult::Background(handle) => handle,
583 _ => panic!("expected background producer handle"),
584 };
585
586 let options = CommandOptions {
587 stdin: CommandStdin::OsPipe(reader),
588 stdout: CommandStdout::Capture,
589 ..Default::default()
590 };
591 let captured = match pm.run_command(&ctx, "sort", options).expect("run consumer") {
593 CommandResult::Captured(bytes) => bytes,
594 _ => panic!("expected captured consumer output"),
595 };
596 assert!(
597 windows_compatible_contains(&captured, b"hello-os-pipe"),
598 "piped output: {:?}",
599 String::from_utf8_lossy(&captured)
600 );
601
602 let mut producer = producer;
603 let status = producer.wait().expect("wait producer");
604 assert!(status.success(), "producer failed: {status:?}");
605
606 let (spent_reader, spent_writer) = create_os_pipe().expect("os pipe");
608 spent_reader.take().expect("first reader take");
609 assert!(
610 spent_reader.take().is_err(),
611 "reader take must be single use"
612 );
613 spent_writer.take().expect("first writer take");
614 assert!(
615 spent_writer.take().is_err(),
616 "writer take must be single use"
617 );
618 }
619
620 #[test]
621 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
622 fn apply_ctx_stages_map_verbatim() {
623 let (_temp, ctx) = make_ctx(&[
630 (oxdock_env::cargo::TARGET_DIR, "custom-target"),
631 ("FOO", "bar"),
632 (oxdock_env::os::PATH, "test-path"),
633 ]);
634 let mut cmd = ProcessCommand::new("prog");
635 apply_ctx(&mut cmd, &ctx, "prog", false).expect("apply with explicit PATH");
636 let envs: HashMap<String, String> = cmd
637 .get_envs()
638 .map(|(k, v)| {
639 (
640 k.to_string_lossy().into_owned(),
641 v.map(|value| value.to_string_lossy().into_owned())
642 .unwrap_or_default(),
643 )
644 })
645 .collect();
646 assert_eq!(
647 envs.get(oxdock_env::cargo::TARGET_DIR).map(String::as_str),
648 Some("custom-target")
649 );
650 assert_eq!(envs.get("FOO").map(String::as_str), Some("bar"));
651
652 let (_temp, ctx) = make_ctx(&[(oxdock_env::os::PATH, "test-path")]);
654 let mut cmd = ProcessCommand::new("prog");
655 apply_ctx(&mut cmd, &ctx, "prog", false).expect("apply with explicit PATH");
656 let envs: HashMap<String, String> = cmd
657 .get_envs()
658 .map(|(k, v)| {
659 (
660 k.to_string_lossy().into_owned(),
661 v.map(|value| value.to_string_lossy().into_owned())
662 .unwrap_or_default(),
663 )
664 })
665 .collect();
666 assert!(
667 !envs.contains_key(oxdock_env::cargo::TARGET_DIR),
668 "unstaged names must stay out: {envs:?}"
669 );
670 }
671
672 #[test]
673 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
674 fn apply_ctx_sets_working_directory_from_guarded_cwd() {
675 let (_temp, ctx) = make_ctx(&[(oxdock_env::os::PATH, "test-path")]);
676 let mut cmd = ProcessCommand::new("prog");
677 apply_ctx(&mut cmd, &ctx, "prog", false).expect("apply with explicit PATH");
678 let expected = oxdock_fs::command_path(match ctx.cwd() {
679 PolicyPath::Guarded(guarded) => guarded,
680 PolicyPath::Unguarded(_) => panic!("expected guarded cwd"),
681 });
682 assert_eq!(cmd.get_current_dir(), Some(expected.as_ref()));
683 }
684
685 #[test]
688 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
689 fn apply_ctx_clears_host_env() {
690 let _probe_guard = crate::TestEnvGuard::set("OXDOCK_CLOSED_ENV_PROBE", "leaked");
692 let (_temp, ctx) = make_ctx(&[(oxdock_env::os::PATH, "test-path"), ("DECLARED", "yes")]);
693 let mut cmd = ProcessCommand::new("prog");
694 apply_ctx(&mut cmd, &ctx, "prog", false).expect("apply with explicit PATH");
695 let envs: HashMap<String, String> = cmd
696 .get_envs()
697 .map(|(k, v)| {
698 (
699 k.to_string_lossy().into_owned(),
700 v.map(|value| value.to_string_lossy().into_owned())
701 .unwrap_or_default(),
702 )
703 })
704 .collect();
705 assert!(
706 !envs.contains_key("OXDOCK_CLOSED_ENV_PROBE"),
707 "host env must not reach children: {envs:?}"
708 );
709 assert_eq!(envs.get("DECLARED").map(String::as_str), Some("yes"));
710 assert_eq!(
711 envs.get(oxdock_env::os::PATH).map(String::as_str),
712 Some("test-path")
713 );
714 }
715
716 #[test]
721 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
722 fn apply_ctx_bails_for_bare_program_without_path() {
723 let (_temp, ctx) = make_ctx(&[("FOO", "bar")]);
724 let mut cmd = ProcessCommand::new("prog");
725 let err = apply_ctx(&mut cmd, &ctx, "prog", false).expect_err("PATH anchor must trip");
726 assert!(
727 err.to_string().contains("INHERIT_ENV [PATH]"),
728 "unexpected error: {err}"
729 );
730 }
731
732 #[test]
735 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
736 fn apply_ctx_skips_path_check_for_pathed_program() {
737 let (_temp, ctx) = make_ctx(&[("FOO", "bar")]);
738 let mut unix_cmd = ProcessCommand::new("/bin/prog");
739 apply_ctx(&mut unix_cmd, &ctx, "/bin/prog", false).expect("absolute path needs no PATH");
740 let mut rel_cmd = ProcessCommand::new("sub/prog");
741 apply_ctx(&mut rel_cmd, &ctx, "sub/prog", false).expect("relative path needs no PATH");
742 }
743
744 #[test]
749 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
750 fn apply_ctx_systemroot_check_follows_platform() {
751 let map: HashMap<String, String> = [(oxdock_env::os::PATH, "test-path")]
755 .iter()
756 .map(|(key, value)| (key.to_string(), value.to_string()))
757 .collect();
758 let (_temp, ctx) = make_ctx_from_map(map);
759 let mut cmd = ProcessCommand::new("prog");
760 #[allow(clippy::disallowed_macros)]
761 if cfg!(windows) {
762 let err =
763 apply_ctx(&mut cmd, &ctx, "prog", false).expect_err("SystemRoot anchor must trip");
764 assert!(
765 err.to_string().contains("SystemRoot"),
766 "unexpected error: {err}"
767 );
768 } else {
769 apply_ctx(&mut cmd, &ctx, "prog", false).expect("no anchor beyond PATH on unix");
770 }
771 }
772
773 #[test]
777 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
778 fn apply_ctx_accepts_windows_casing_variants() {
779 let (_temp, ctx) = make_ctx(&[("Path", "test-path")]);
783 let mut cmd = ProcessCommand::new("prog");
784 #[allow(clippy::disallowed_macros)]
785 if cfg!(windows) {
786 apply_ctx(&mut cmd, &ctx, "prog", false).expect("cased PATH satisfies the anchor");
787 let envs: HashMap<String, String> = cmd
788 .get_envs()
789 .map(|(k, v)| {
790 (
791 k.to_string_lossy().into_owned(),
792 v.map(|value| value.to_string_lossy().into_owned())
793 .unwrap_or_default(),
794 )
795 })
796 .collect();
797 assert_eq!(envs.get("Path").map(String::as_str), Some("test-path"));
798 } else {
799 let err = apply_ctx(&mut cmd, &ctx, "prog", false)
800 .expect_err("cased PATH is not PATH on unix");
801 assert!(
802 err.to_string().contains("INHERIT_ENV [PATH]"),
803 "unexpected error: {err}"
804 );
805 }
806 }
807
808 #[cfg_attr(miri, ignore = "spawns a real child process, unsupported under Miri")]
811 #[test]
812 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
813 fn spawned_child_does_not_see_host_env() {
814 let _probe_guard = crate::TestEnvGuard::set("OXDOCK_CLOSED_ENV_PROBE", "leaked");
816 let (_temp, ctx) = make_ctx_with_host_exec(&[("OXDOCK_CHILD_MARKER", "here")]);
817 let mut pm = ShellProcessManager;
818 #[cfg(windows)]
819 let script = "if defined OXDOCK_CLOSED_ENV_PROBE (echo PROBE-SEEN) else (echo PROBE-CLEAN)& echo MARKER-%OXDOCK_CHILD_MARKER%";
820 #[cfg(not(windows))]
821 let script = "echo \"probe=${OXDOCK_CLOSED_ENV_PROBE:-unset} marker=${OXDOCK_CHILD_MARKER:-missing}\"";
822 let options = CommandOptions {
823 stdout: CommandStdout::Capture,
824 ..Default::default()
825 };
826 let out = match pm.run_command(&ctx, script, options).expect("run") {
827 CommandResult::Captured(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
828 CommandResult::Completed => panic!("expected Captured, got Completed"),
829 CommandResult::Background(_) => panic!("expected Captured, got Background"),
830 };
831 #[cfg(windows)]
832 {
833 assert!(out.contains("PROBE-CLEAN"), "child saw host env: {out}");
834 assert!(
835 out.contains("MARKER-here"),
836 "child missed script env: {out}"
837 );
838 }
839 #[cfg(not(windows))]
840 {
841 assert!(out.contains("probe=unset"), "child saw host env: {out}");
842 assert!(
843 out.contains("marker=here"),
844 "child missed script env: {out}"
845 );
846 }
847 }
848}