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#[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 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#[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 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 let owned = writer.take()?;
117 command.stderr(Stdio::from(owned));
118 None
119 }
120 };
121
122 let stdin_stream: Option<SharedInput> = match stdin {
123 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 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 #[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 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 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 #[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 #[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 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 #[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 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 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 #[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 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 #[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 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 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 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 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 #[test]
691 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
692 fn apply_ctx_clears_host_env() {
693 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 #[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 #[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 #[test]
752 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
753 fn apply_ctx_systemroot_check_follows_platform() {
754 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 #[test]
780 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
781 fn apply_ctx_accepts_windows_casing_variants() {
782 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 #[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 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}