1pub mod content_sniff;
16pub mod direct;
17pub mod policy;
18
19#[cfg(target_os = "linux")]
20mod linux_jail;
21
22#[cfg(windows)]
23mod windows_job;
24
25pub use content_sniff::{Suspicion, SuspicionKind, sniff_lifecycle};
26pub use policy::{AllowDecision, BuildPolicy, BuildPolicyError, pattern_matches};
27
28use aube_manifest::PackageJson;
29use std::collections::hash_map::DefaultHasher;
30use std::hash::{Hash, Hasher};
31use std::path::{Path, PathBuf};
32use tokio::io::{AsyncBufReadExt, AsyncReadExt};
33
34const MAX_SCRIPT_OUTPUT_RECORD_BYTES: usize = 64 * 1024;
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum ScriptOutputStream {
38 Stdout,
39 Stderr,
40}
41
42pub trait ScriptOutputReporter: Send + Sync + 'static {
43 fn report(&self, stream: ScriptOutputStream, line: String);
44}
45
46pub const CLI_EXE_ENV: &str = "AUBE_CLI_EXE";
52
53#[derive(Debug, Clone, Default)]
55pub struct ScriptSettings {
56 pub node_options: Option<String>,
57 pub script_shell: Option<PathBuf>,
58 pub unsafe_perm: Option<bool>,
59 pub shell_emulator: bool,
60 pub node_bin_dir: Option<PathBuf>,
63 pub node_program: Option<PathBuf>,
67 pub node_execpath: Option<PathBuf>,
71 pub extra_env: Vec<(std::ffi::OsString, std::ffi::OsString)>,
77 pub command: Option<String>,
82 pub node_gyp_js: Option<PathBuf>,
89 pub http_proxy: Option<String>,
98 pub https_proxy: Option<String>,
99 pub no_proxy: Option<String>,
100}
101
102#[derive(Debug, Clone)]
104pub struct ScriptJail {
105 pub package_dir: PathBuf,
106 pub env: Vec<String>,
107 pub read_paths: Vec<PathBuf>,
108 pub write_paths: Vec<PathBuf>,
109 pub network: bool,
110}
111
112impl ScriptJail {
113 pub fn new(package_dir: impl Into<PathBuf>) -> Self {
114 Self {
115 package_dir: package_dir.into(),
116 env: Vec::new(),
117 read_paths: Vec::new(),
118 write_paths: Vec::new(),
119 network: false,
120 }
121 }
122
123 pub fn with_env(mut self, env: impl IntoIterator<Item = String>) -> Self {
124 self.env = env.into_iter().collect();
125 self
126 }
127
128 pub fn with_read_paths(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
129 self.read_paths = paths.into_iter().collect();
130 self
131 }
132
133 pub fn with_write_paths(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
134 self.write_paths = paths.into_iter().collect();
135 self
136 }
137
138 pub fn with_network(mut self, network: bool) -> Self {
139 self.network = network;
140 self
141 }
142}
143
144pub struct ScriptJailHomeCleanup {
145 path: PathBuf,
146}
147
148impl ScriptJailHomeCleanup {
149 pub fn new(jail: &ScriptJail) -> Self {
150 Self {
151 path: jail_home(&jail.package_dir),
152 }
153 }
154}
155
156impl Drop for ScriptJailHomeCleanup {
157 fn drop(&mut self) {
158 if self.path.exists()
159 && let Err(err) = std::fs::remove_dir_all(&self.path)
160 {
161 tracing::debug!("failed to clean jail HOME {}: {err}", self.path.display());
162 }
163 }
164}
165
166#[derive(Clone, Default)]
167struct ScriptSettingsState {
168 settings: ScriptSettings,
169 node_bin_dir_precedes_project_bins: bool,
170 output_reporter: Option<std::sync::Arc<dyn ScriptOutputReporter>>,
171 pm_execpath: Option<PathBuf>,
174}
175
176static SCRIPT_SETTINGS: std::sync::OnceLock<std::sync::RwLock<ScriptSettingsState>> =
177 std::sync::OnceLock::new();
178
179type ScriptSettingsSlot = std::sync::Arc<std::sync::RwLock<ScriptSettingsState>>;
180
181tokio::task_local! {
182 static INSTALL_SCRIPT_SETTINGS: ScriptSettingsSlot;
183}
184
185pub async fn scope<F: std::future::Future>(future: F) -> F::Output {
187 INSTALL_SCRIPT_SETTINGS
188 .scope(
189 std::sync::Arc::new(std::sync::RwLock::new(ScriptSettingsState::default())),
190 future,
191 )
192 .await
193}
194
195pub fn scope_current<F: std::future::Future>(
197 future: F,
198) -> impl std::future::Future<Output = F::Output> {
199 let settings = INSTALL_SCRIPT_SETTINGS.try_with(std::sync::Arc::clone).ok();
200 async move {
201 match settings {
202 Some(settings) => INSTALL_SCRIPT_SETTINGS.scope(settings, future).await,
203 None => future.await,
204 }
205 }
206}
207
208fn script_settings_lock() -> &'static std::sync::RwLock<ScriptSettingsState> {
209 SCRIPT_SETTINGS.get_or_init(|| std::sync::RwLock::new(ScriptSettingsState::default()))
210}
211
212pub fn set_script_settings(settings: ScriptSettings) {
215 set_script_settings_with_path_order(settings, false);
216}
217
218#[doc(hidden)]
222pub fn set_script_settings_with_path_order(
223 settings: ScriptSettings,
224 node_bin_dir_precedes_project_bins: bool,
225) {
226 if INSTALL_SCRIPT_SETTINGS
227 .try_with(|slot| match slot.write() {
228 Ok(mut guard) => {
229 guard.settings = settings.clone();
230 guard.node_bin_dir_precedes_project_bins = node_bin_dir_precedes_project_bins;
231 }
232 Err(poisoned) => {
233 let mut guard = poisoned.into_inner();
234 guard.settings = settings.clone();
235 guard.node_bin_dir_precedes_project_bins = node_bin_dir_precedes_project_bins;
236 }
237 })
238 .is_ok()
239 {
240 return;
241 }
242 match script_settings_lock().write() {
243 Ok(mut guard) => {
244 guard.settings = settings;
245 guard.node_bin_dir_precedes_project_bins = node_bin_dir_precedes_project_bins;
246 }
247 Err(poisoned) => {
248 let mut guard = poisoned.into_inner();
249 guard.settings = settings;
250 guard.node_bin_dir_precedes_project_bins = node_bin_dir_precedes_project_bins;
251 }
252 }
253}
254
255pub fn set_output_reporter(reporter: Option<std::sync::Arc<dyn ScriptOutputReporter>>) {
258 if INSTALL_SCRIPT_SETTINGS
259 .try_with(|slot| match slot.write() {
260 Ok(mut guard) => guard.output_reporter = reporter.clone(),
261 Err(poisoned) => poisoned.into_inner().output_reporter = reporter.clone(),
262 })
263 .is_ok()
264 {
265 return;
266 }
267 match script_settings_lock().write() {
268 Ok(mut guard) => guard.output_reporter = reporter,
269 Err(poisoned) => poisoned.into_inner().output_reporter = reporter,
270 }
271}
272
273pub fn set_pm_execpath(path: Option<PathBuf>) {
282 if INSTALL_SCRIPT_SETTINGS
283 .try_with(|slot| match slot.write() {
284 Ok(mut guard) => guard.pm_execpath = path.clone(),
285 Err(poisoned) => poisoned.into_inner().pm_execpath = path.clone(),
286 })
287 .is_ok()
288 {
289 return;
290 }
291 match script_settings_lock().write() {
292 Ok(mut guard) => guard.pm_execpath = path,
293 Err(poisoned) => poisoned.into_inner().pm_execpath = path,
294 }
295}
296
297fn script_settings_state() -> ScriptSettingsState {
298 if let Ok(state) = INSTALL_SCRIPT_SETTINGS.try_with(|slot| match slot.read() {
299 Ok(guard) => guard.clone(),
300 Err(poisoned) => poisoned.into_inner().clone(),
301 }) {
302 return state;
303 }
304 match script_settings_lock().read() {
305 Ok(guard) => guard.clone(),
306 Err(poisoned) => poisoned.into_inner().clone(),
307 }
308}
309
310fn script_settings() -> ScriptSettings {
311 script_settings_state().settings
312}
313
314#[cfg(test)]
315mod scoped_settings_tests {
316 use super::*;
317
318 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
319 async fn install_script_settings_are_isolated_and_propagated() {
320 let barrier = std::sync::Arc::new(tokio::sync::Barrier::new(2));
321 let first_barrier = std::sync::Arc::clone(&barrier);
322 let second_barrier = std::sync::Arc::clone(&barrier);
323
324 let first = scope(async move {
325 set_script_settings_with_path_order(
326 ScriptSettings {
327 command: Some("first".to_string()),
328 ..ScriptSettings::default()
329 },
330 true,
331 );
332 first_barrier.wait().await;
333 tokio::spawn(scope_current(async {
334 let state = script_settings_state();
335 (
336 state.settings.command,
337 state.node_bin_dir_precedes_project_bins,
338 )
339 }))
340 .await
341 .unwrap()
342 });
343 let second = scope(async move {
344 set_script_settings(ScriptSettings {
345 command: Some("second".to_string()),
346 ..ScriptSettings::default()
347 });
348 second_barrier.wait().await;
349 tokio::spawn(scope_current(async {
350 let state = script_settings_state();
351 (
352 state.settings.command,
353 state.node_bin_dir_precedes_project_bins,
354 )
355 }))
356 .await
357 .unwrap()
358 });
359
360 let (first, second) = tokio::join!(first, second);
361 assert_eq!(first.0.as_deref(), Some("first"));
362 assert!(first.1);
363 assert_eq!(second.0.as_deref(), Some("second"));
364 assert!(!second.1);
365 }
366}
367
368pub fn prepend_path(bin_dir: &Path) -> std::ffi::OsString {
371 prepend_paths(std::slice::from_ref(&bin_dir.to_path_buf()))
372}
373
374pub fn prepend_paths(bin_dirs: &[PathBuf]) -> std::ffi::OsString {
376 let path = std::env::var_os("PATH").unwrap_or_default();
377 let mut entries: Vec<PathBuf> = bin_dirs.to_vec();
378 entries.extend(std::env::split_paths(&path));
379 std::env::join_paths(entries).unwrap_or(path)
380}
381
382pub fn order_path_entries(
386 mut project_bins: Vec<PathBuf>,
387 runtime_bin: Option<&Path>,
388 runtime_precedes_project_bins: bool,
389) -> Vec<PathBuf> {
390 let Some(runtime_bin) = runtime_bin else {
391 return project_bins;
392 };
393 if runtime_precedes_project_bins {
394 project_bins.insert(0, runtime_bin.to_path_buf());
395 } else {
396 project_bins.push(runtime_bin.to_path_buf());
397 }
398 project_bins
399}
400
401#[cfg(test)]
402mod path_entry_tests {
403 use super::*;
404
405 #[test]
406 fn wrapper_runtime_leads_project_bins() {
407 let runtime = Path::new("/shim");
408 let project = PathBuf::from("/project/node_modules/.bin");
409 assert_eq!(
410 order_path_entries(vec![project.clone()], Some(runtime), true),
411 vec![runtime.to_path_buf(), project]
412 );
413 }
414
415 #[test]
416 fn selector_runtime_follows_project_bins() {
417 let runtime = Path::new("/opt/node/bin");
418 let project = PathBuf::from("/project/node_modules/.bin");
419 assert_eq!(
420 order_path_entries(vec![project.clone()], Some(runtime), false),
421 vec![project, runtime.to_path_buf()]
422 );
423 }
424}
425
426pub fn spawn_shell(script_cmd: &str) -> tokio::process::Command {
445 let settings = script_settings();
446 spawn_shell_with_settings(script_cmd, &settings)
447}
448
449pub fn spawn_program<I, S>(program: &Path, arg0: &str, args: I) -> tokio::process::Command
464where
465 I: IntoIterator<Item = S>,
466 S: AsRef<std::ffi::OsStr>,
467{
468 let settings = script_settings();
469 let mut cmd = tokio::process::Command::new(program);
470 #[cfg(unix)]
471 {
472 use std::os::unix::process::CommandExt;
473 cmd.as_std_mut().arg0(arg0);
474 }
475 #[cfg(not(unix))]
476 let _ = arg0;
477 cmd.args(args);
478 apply_script_settings_env(&mut cmd, &settings);
479 cmd.kill_on_drop(true);
480 cmd
481}
482
483fn spawn_shell_with_settings(
484 script_cmd: &str,
485 settings: &ScriptSettings,
486) -> tokio::process::Command {
487 #[cfg(unix)]
488 let mut cmd = {
489 let mut cmd = tokio::process::Command::new(
490 settings
491 .script_shell
492 .as_deref()
493 .unwrap_or_else(|| Path::new("sh")),
494 );
495 cmd.arg("-c").arg(script_cmd);
496 cmd
497 };
498 #[cfg(windows)]
499 let mut cmd = {
500 let mut cmd = tokio::process::Command::new(
501 settings
502 .script_shell
503 .as_deref()
504 .unwrap_or_else(|| Path::new("cmd.exe")),
505 );
506 if settings.script_shell.is_some() {
507 cmd.arg("-c").arg(script_cmd);
508 } else {
509 cmd.raw_arg("/d /s /c \"").raw_arg(script_cmd).raw_arg("\"");
514 }
515 cmd
516 };
517 apply_script_settings_env(&mut cmd, settings);
518 cmd.kill_on_drop(true);
527 cmd
528}
529
530#[cfg(target_os = "macos")]
531fn sbpl_escape(s: &str) -> String {
532 s.replace('\\', "\\\\").replace('"', "\\\"")
533}
534
535#[cfg(target_os = "macos")]
536fn push_write_rule(rules: &mut Vec<String>, path: &Path) {
537 let path = sbpl_escape(&path.to_string_lossy());
538 let rule = format!("(allow file-write* (subpath \"{path}\"))");
539 if !rules.iter().any(|existing| existing == &rule) {
540 rules.push(rule);
541 }
542}
543
544#[cfg(target_os = "macos")]
545fn jail_profile(jail: &ScriptJail, home: &Path) -> String {
546 let mut rules = vec![
547 "(version 1)".to_string(),
548 "(allow default)".to_string(),
549 "(allow network* (local unix))".to_string(),
550 "(deny file-write*)".to_string(),
551 ];
552 if !jail.network {
553 rules.insert(2, "(deny network*)".to_string());
554 }
555
556 for path in [
557 Path::new("/tmp"),
558 Path::new("/private/tmp"),
559 Path::new("/dev"),
560 ] {
561 push_write_rule(&mut rules, path);
562 }
563 for path in [&jail.package_dir, home] {
564 push_write_rule(&mut rules, path);
565 }
566 for path in &jail.write_paths {
567 push_write_rule(&mut rules, path);
568 }
569 for path in [&jail.package_dir, home] {
570 if let Ok(canonical) = path.canonicalize() {
571 push_write_rule(&mut rules, &canonical);
572 }
573 }
574 for path in &jail.write_paths {
575 if let Ok(canonical) = path.canonicalize() {
576 push_write_rule(&mut rules, &canonical);
577 }
578 }
579 rules.join("\n")
580}
581
582#[cfg(target_os = "macos")]
583fn spawn_jailed_shell(
584 script_cmd: &str,
585 settings: &ScriptSettings,
586 jail: &ScriptJail,
587 home: &Path,
588) -> tokio::process::Command {
589 let shell = settings
590 .script_shell
591 .as_deref()
592 .unwrap_or_else(|| Path::new("sh"));
593 let profile = jail_profile(jail, home);
594 let mut cmd = tokio::process::Command::new("sandbox-exec");
595 cmd.arg("-p")
596 .arg(profile)
597 .arg("--")
598 .arg(shell)
599 .arg("-c")
600 .arg(script_cmd);
601 apply_script_settings_env(&mut cmd, settings);
602 cmd.kill_on_drop(true);
604 cmd
605}
606
607#[cfg(target_os = "linux")]
608fn spawn_jailed_shell(
609 script_cmd: &str,
610 settings: &ScriptSettings,
611 jail: &ScriptJail,
612 home: &Path,
613) -> tokio::process::Command {
614 let mut cmd = spawn_shell_with_settings(script_cmd, settings);
615 let jail = jail.clone();
616 let home = home.to_path_buf();
617 unsafe {
618 cmd.pre_exec(move || {
619 linux_jail::apply_landlock(&jail, &home).map_err(std::io::Error::other)?;
620 if !jail.network {
621 linux_jail::apply_seccomp_net_filter().map_err(std::io::Error::other)?;
622 }
623 Ok(())
624 });
625 }
626 cmd
627}
628
629#[cfg(not(any(target_os = "linux", target_os = "macos")))]
630fn spawn_jailed_shell(
631 script_cmd: &str,
632 settings: &ScriptSettings,
633 _jail: &ScriptJail,
634 _home: &Path,
635) -> tokio::process::Command {
636 spawn_shell_with_settings(script_cmd, settings)
637}
638
639pub fn shell_quote_arg(arg: &str) -> String {
662 #[cfg(unix)]
663 {
664 let mut out = String::with_capacity(arg.len() + 2);
665 out.push('\'');
666 for ch in arg.chars() {
667 if ch == '\'' {
668 out.push_str("'\\''");
669 } else {
670 out.push(ch);
671 }
672 }
673 out.push('\'');
674 out
675 }
676 #[cfg(windows)]
677 {
678 let mut out = String::with_capacity(arg.len() + 2);
679 out.push('"');
680 let mut backslashes: usize = 0;
681 for ch in arg.chars() {
682 match ch {
683 '\\' => backslashes += 1,
684 '"' => {
685 for _ in 0..backslashes * 2 + 1 {
686 out.push('\\');
687 }
688 out.push('"');
689 backslashes = 0;
690 }
691 '%' => {
702 for _ in 0..backslashes {
703 out.push('\\');
704 }
705 backslashes = 0;
706 out.push_str("%%");
707 }
708 _ => {
709 for _ in 0..backslashes {
710 out.push('\\');
711 }
712 backslashes = 0;
713 out.push(ch);
714 }
715 }
716 }
717 for _ in 0..backslashes * 2 {
718 out.push('\\');
719 }
720 out.push('"');
721 out
722 }
723}
724
725pub fn exit_code_from_status(status: std::process::ExitStatus) -> i32 {
737 if let Some(code) = status.code() {
738 return code;
739 }
740 #[cfg(unix)]
741 {
742 use std::os::unix::process::ExitStatusExt;
743 if let Some(sig) = status.signal() {
744 return 128 + sig;
745 }
746 }
747 1
748}
749
750pub fn aube_user_agent() -> String {
760 format!(
761 "{} {} {}",
762 aube_util::embedder().user_agent,
763 node_platform(),
764 node_arch(),
765 )
766}
767
768fn node_platform() -> &'static str {
769 match std::env::consts::OS {
770 "macos" => "darwin",
771 "windows" => "win32",
772 other => other,
773 }
774}
775
776fn node_arch() -> &'static str {
777 match std::env::consts::ARCH {
784 "x86_64" => "x64",
785 "aarch64" => "arm64",
786 "x86" => "ia32",
787 "powerpc" => "ppc",
788 "powerpc64" => "ppc64",
789 "loongarch64" => "loong64",
790 other => other,
791 }
792}
793
794fn pm_execpath_for(
802 registered: Option<PathBuf>,
803 embedded: bool,
804 aube_exe: Option<PathBuf>,
805) -> Option<PathBuf> {
806 registered.or_else(|| (!embedded).then_some(aube_exe).flatten())
807}
808
809fn apply_script_settings_env(cmd: &mut tokio::process::Command, settings: &ScriptSettings) {
810 cmd.env_remove("AUBE_AUTH_TOKEN");
817 cmd.env("npm_config_user_agent", aube_user_agent());
822 let aube_exe = std::env::current_exe().ok();
840 let pm_execpath = pm_execpath_for(
841 script_settings_state().pm_execpath,
842 aube_util::is_embedded(),
843 aube_exe.clone(),
844 );
845 cmd.env_remove("npm_execpath");
846 if let Some(execpath) = pm_execpath.as_deref() {
847 cmd.env("npm_execpath", execpath);
848 }
849 cmd.env_remove(CLI_EXE_ENV);
857 if let Some(exe) = aube_exe.as_deref() {
858 cmd.env(CLI_EXE_ENV, exe);
859 }
860 let node_execpath = settings
867 .node_execpath
868 .as_deref()
869 .or(settings.node_program.as_deref());
870 if let Some(execpath) = node_execpath {
871 cmd.env("npm_node_execpath", execpath);
872 }
873 if let Some(node) = settings.node_program.as_deref().or(node_execpath) {
874 cmd.env("NODE", node);
875 }
876 if let Some(command) = settings.command.as_deref() {
878 cmd.env("npm_command", command);
879 }
880 if let Some(node_gyp_js) = settings.node_gyp_js.as_deref() {
891 cmd.env("npm_config_node_gyp", node_gyp_js);
892 if let Some(exe) = aube_exe.as_deref() {
893 cmd.env("AUBE_NODE_GYP_EXE", exe);
894 }
895 }
896 if let Some(node_options) = settings.node_options.as_deref() {
897 cmd.env("NODE_OPTIONS", node_options);
898 }
899 if let Some(unsafe_perm) = settings.unsafe_perm {
900 cmd.env(
901 "npm_config_unsafe_perm",
902 if unsafe_perm { "true" } else { "false" },
903 );
904 }
905 if settings.shell_emulator {
906 cmd.env("npm_config_shell_emulator", "true");
907 }
908 if settings.http_proxy.is_some() || settings.https_proxy.is_some() {
923 if let Some(https) = settings.https_proxy.as_deref() {
924 cmd.env("HTTPS_PROXY", https);
925 }
926 if let Some(http) = settings.http_proxy.as_deref() {
927 cmd.env("HTTP_PROXY", http);
928 }
929 if let Some(no_proxy) = settings.no_proxy.as_deref() {
930 cmd.env("NO_PROXY", no_proxy);
931 }
932 cmd.env("NODE_USE_ENV_PROXY", "1");
933 }
934 for (key, value) in &settings.extra_env {
940 cmd.env(key, value);
941 }
942}
943
944pub fn apply_npm_manifest_env(
963 cmd: &mut tokio::process::Command,
964 manifest: &PackageJson,
965 script_dir: &Path,
966 lifecycle_script: &str,
967) {
968 for (key, _) in std::env::vars_os() {
969 if key.to_str().is_some_and(|k| k.starts_with("npm_package_")) {
970 cmd.env_remove(&key);
971 }
972 }
973 cmd.env("npm_lifecycle_script", lifecycle_script);
974 cmd.env("npm_package_json", script_dir.join("package.json"));
975 for (key, value) in manifest.npm_package_env() {
976 cmd.env(key, value);
977 }
978}
979
980fn safe_jail_env_key(key: &str) -> bool {
981 const EXACT: &[&str] = &[
982 "PATH",
983 "HOME",
984 "TERM",
985 "LANG",
986 "LC_ALL",
987 "INIT_CWD",
988 "npm_lifecycle_event",
989 "npm_package_name",
990 "npm_package_version",
991 ];
992 if EXACT.contains(&key) {
993 return true;
994 }
995 let lower = key.to_ascii_lowercase();
996 if lower.contains("token")
997 || lower.contains("auth")
998 || lower.contains("password")
999 || lower.contains("credential")
1000 || lower.contains("secret")
1001 {
1002 return false;
1003 }
1004 key.starts_with("npm_config_")
1005}
1006
1007fn inherit_jail_env_key(key: &str, extra_env: &[String]) -> bool {
1008 (safe_jail_env_key(key) || extra_env.iter().any(|env| env == key))
1009 && !matches!(
1010 key,
1011 "PATH" | "HOME" | "npm_lifecycle_event" | "npm_package_name" | "npm_package_version"
1012 )
1013}
1014
1015fn jail_home(package_dir: &Path) -> PathBuf {
1016 let mut hasher = DefaultHasher::new();
1017 package_dir.hash(&mut hasher);
1018 let hash = hasher.finish();
1019 let name = package_dir
1020 .file_name()
1021 .and_then(|s| s.to_str())
1022 .unwrap_or("package")
1023 .chars()
1024 .map(|c| {
1025 if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') {
1026 c
1027 } else {
1028 '_'
1029 }
1030 })
1031 .collect::<String>();
1032 std::env::temp_dir()
1033 .join("aube-jail")
1034 .join(std::process::id().to_string())
1035 .join(format!("{name}-{hash:016x}"))
1036}
1037
1038fn apply_jail_env(
1039 cmd: &mut tokio::process::Command,
1040 path_env: &std::ffi::OsStr,
1041 home: &Path,
1042 project_root: &Path,
1043 manifest: &PackageJson,
1044 script_name: &str,
1045 extra_env: &[String],
1046) {
1047 cmd.env_clear();
1048 cmd.env("PATH", path_env)
1049 .env("HOME", home)
1050 .env("TMPDIR", home)
1051 .env("TMP", home)
1052 .env("TEMP", home)
1053 .env("AUBE_NODE_GYP_PROJECT_DIR", project_root)
1059 .env("npm_lifecycle_event", script_name);
1060 if std::env::var_os("INIT_CWD").is_none() {
1061 cmd.env("INIT_CWD", project_root);
1062 }
1063 if let Some(ref name) = manifest.name {
1064 cmd.env("npm_package_name", name);
1065 }
1066 if let Some(ref version) = manifest.version {
1067 cmd.env("npm_package_version", version);
1068 }
1069 for (key, val) in std::env::vars_os() {
1070 let Some(key_str) = key.to_str() else {
1071 continue;
1072 };
1073 if inherit_jail_env_key(key_str, extra_env) {
1074 cmd.env(key, val);
1075 }
1076 }
1077}
1078
1079#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1083pub enum LifecycleHook {
1084 PreInstall,
1085 Install,
1086 PostInstall,
1087 Prepare,
1088}
1089
1090impl LifecycleHook {
1091 pub fn script_name(self) -> &'static str {
1092 match self {
1093 Self::PreInstall => "preinstall",
1094 Self::Install => "install",
1095 Self::PostInstall => "postinstall",
1096 Self::Prepare => "prepare",
1097 }
1098 }
1099}
1100
1101pub const DEP_LIFECYCLE_HOOKS: [LifecycleHook; 3] = [
1105 LifecycleHook::PreInstall,
1106 LifecycleHook::Install,
1107 LifecycleHook::PostInstall,
1108];
1109
1110#[cfg(unix)]
1118static SAVED_STDERR_FD: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(-1);
1119
1120#[cfg(unix)]
1125pub fn set_saved_stderr_fd(fd: std::os::fd::RawFd) {
1126 SAVED_STDERR_FD.store(fd, std::sync::atomic::Ordering::SeqCst);
1127}
1128
1129#[cfg(not(unix))]
1134pub fn set_saved_stderr_fd(_fd: i32) {}
1135
1136#[cfg(unix)]
1141pub fn child_stderr() -> std::process::Stdio {
1142 let fd = SAVED_STDERR_FD.load(std::sync::atomic::Ordering::SeqCst);
1143 if fd < 0 {
1144 return std::process::Stdio::inherit();
1145 }
1146 let borrowed = unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) };
1151 match borrowed.try_clone_to_owned() {
1152 Ok(owned) => std::process::Stdio::from(owned),
1153 Err(_) => std::process::Stdio::inherit(),
1154 }
1155}
1156
1157#[cfg(not(unix))]
1158pub fn child_stderr() -> std::process::Stdio {
1159 std::process::Stdio::inherit()
1160}
1161
1162#[cfg(unix)]
1178pub fn write_line_to_real_stderr(line: &str) {
1179 use std::io::Write;
1180 let saved = SAVED_STDERR_FD.load(std::sync::atomic::Ordering::SeqCst);
1181 let fd = if saved >= 0 { saved } else { 2 };
1182 let borrowed = unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) };
1189 let Ok(owned) = borrowed.try_clone_to_owned() else {
1190 return;
1191 };
1192 let mut file = std::fs::File::from(owned);
1193 let mut buf = String::with_capacity(line.len() + 1);
1194 buf.push_str(line);
1195 buf.push('\n');
1196 let _ = file.write_all(buf.as_bytes());
1197}
1198
1199#[cfg(not(unix))]
1200pub fn write_line_to_real_stderr(line: &str) {
1201 eprintln!("{line}");
1202}
1203
1204async fn run_command_killing_descendants(
1240 mut cmd: tokio::process::Command,
1241 script_name: &str,
1242) -> Result<std::process::ExitStatus, Error> {
1243 let output_reporter = script_settings_state().output_reporter;
1244 if output_reporter.is_some() {
1245 cmd.stdout(std::process::Stdio::piped())
1246 .stderr(std::process::Stdio::piped());
1247 }
1248 let mut child = cmd
1249 .spawn()
1250 .map_err(|e| Error::Spawn(script_name.to_string(), e.to_string()))?;
1251 #[cfg(windows)]
1252 let _job = match windows_job::JobObject::new() {
1253 Ok(job) => {
1254 if let Some(handle) = child.raw_handle()
1258 && let Err(err) = job.assign(handle)
1259 {
1260 tracing::warn!(
1267 code = aube_codes::warnings::WARN_AUBE_WINDOWS_JOB_OBJECT_UNAVAILABLE,
1268 "windows: AssignProcessToJobObject failed for `{script_name}` shell ({err}); \
1269 grandchildren may be orphaned if the script is aborted"
1270 );
1271 }
1272 Some(job)
1273 }
1274 Err(err) => {
1275 tracing::warn!(
1276 code = aube_codes::warnings::WARN_AUBE_WINDOWS_JOB_OBJECT_UNAVAILABLE,
1277 "windows: CreateJobObjectW failed for `{script_name}` shell ({err}); \
1278 running without orphan-reaping — grandchildren may leak if aborted"
1279 );
1280 None
1281 }
1282 };
1283 let Some(reporter) = output_reporter else {
1284 return child
1285 .wait()
1286 .await
1287 .map_err(|e| Error::Spawn(script_name.to_string(), e.to_string()));
1288 };
1289 let stdout = child.stdout.take().ok_or_else(|| {
1290 Error::Spawn(
1291 script_name.to_string(),
1292 "failed to capture lifecycle stdout".to_string(),
1293 )
1294 })?;
1295 let stderr = child.stderr.take().ok_or_else(|| {
1296 Error::Spawn(
1297 script_name.to_string(),
1298 "failed to capture lifecycle stderr".to_string(),
1299 )
1300 })?;
1301 let (status, stdout_result, stderr_result) = tokio::join!(
1302 child.wait(),
1303 report_script_output(stdout, ScriptOutputStream::Stdout, reporter.clone()),
1304 report_script_output(stderr, ScriptOutputStream::Stderr, reporter),
1305 );
1306 stdout_result.map_err(|e| Error::Spawn(script_name.to_string(), e.to_string()))?;
1307 stderr_result.map_err(|e| Error::Spawn(script_name.to_string(), e.to_string()))?;
1308 status.map_err(|e| Error::Spawn(script_name.to_string(), e.to_string()))
1309}
1310
1311async fn report_script_output<R: tokio::io::AsyncRead + Unpin>(
1312 reader: R,
1313 stream: ScriptOutputStream,
1314 reporter: std::sync::Arc<dyn ScriptOutputReporter>,
1315) -> std::io::Result<()> {
1316 let mut reader = tokio::io::BufReader::new(reader);
1317 let mut buffer = Vec::new();
1318 let mut continued_record = false;
1319 loop {
1320 buffer.clear();
1321 let mut limited = (&mut reader).take(MAX_SCRIPT_OUTPUT_RECORD_BYTES as u64);
1322 if limited.read_until(b'\n', &mut buffer).await? == 0 {
1323 return Ok(());
1324 }
1325 let record_terminated = buffer.last() == Some(&b'\n');
1326 if record_terminated {
1327 buffer.pop();
1328 if buffer.last() == Some(&b'\r') {
1329 buffer.pop();
1330 }
1331 }
1332 if !(continued_record && record_terminated && buffer.is_empty()) {
1333 reporter.report(stream, String::from_utf8_lossy(&buffer).into_owned());
1334 }
1335 continued_record = !record_terminated;
1336 }
1337}
1338
1339#[cfg(test)]
1340mod script_output_tests {
1341 use super::*;
1342 use tokio::io::AsyncWriteExt;
1343
1344 #[derive(Default)]
1345 struct RecordingReporter(std::sync::Mutex<Vec<String>>);
1346
1347 impl ScriptOutputReporter for RecordingReporter {
1348 fn report(&self, _stream: ScriptOutputStream, line: String) {
1349 self.0.lock().unwrap().push(line);
1350 }
1351 }
1352
1353 #[tokio::test]
1354 async fn unterminated_output_is_reported_in_bounded_chunks() {
1355 let reporter = std::sync::Arc::new(RecordingReporter::default());
1356 let (mut writer, reader) = tokio::io::duplex(1024);
1357 let mut output = vec![b'x'; MAX_SCRIPT_OUTPUT_RECORD_BYTES * 2 + 17];
1358 output.extend_from_slice(b"\nnext\n");
1359 let write = tokio::spawn(async move {
1360 writer.write_all(&output).await.unwrap();
1361 });
1362
1363 report_script_output(reader, ScriptOutputStream::Stdout, reporter.clone())
1364 .await
1365 .unwrap();
1366 write.await.unwrap();
1367
1368 let messages = reporter.0.lock().unwrap();
1369 assert_eq!(
1370 messages.iter().map(String::len).collect::<Vec<_>>(),
1371 [
1372 MAX_SCRIPT_OUTPUT_RECORD_BYTES,
1373 MAX_SCRIPT_OUTPUT_RECORD_BYTES,
1374 17,
1375 4,
1376 ]
1377 );
1378 assert_eq!(messages.last().map(String::as_str), Some("next"));
1379 }
1380}
1381
1382#[allow(clippy::too_many_arguments)]
1400pub async fn run_script(
1401 script_dir: &Path,
1402 project_root: &Path,
1403 modules_dir_name: &str,
1404 manifest: &PackageJson,
1405 script_name: &str,
1406 script_cmd: &str,
1407 extra_bin_dirs: &[&Path],
1408 jail: Option<&ScriptJail>,
1409) -> Result<(), Error> {
1410 let _diag = aube_util::diag::Span::new(aube_util::diag::Category::Script, "run_script")
1415 .with_meta_fn(|| {
1416 let pkg = manifest.name.as_deref().unwrap_or("(root)");
1417 format!(
1418 r#"{{"pkg":{},"script":{}}}"#,
1419 aube_util::diag::jstr(pkg),
1420 aube_util::diag::jstr(script_name)
1421 )
1422 });
1423 let project_bin = project_root.join(modules_dir_name).join(".bin");
1431 let state = script_settings_state();
1432 let settings = &state.settings;
1433 let path = std::env::var_os("PATH").unwrap_or_default();
1434 let mut project_bins: Vec<PathBuf> = Vec::with_capacity(extra_bin_dirs.len() + 1);
1435 for dir in extra_bin_dirs {
1436 project_bins.push(dir.to_path_buf());
1437 }
1438 project_bins.push(project_bin);
1439 let mut entries = order_path_entries(
1440 project_bins,
1441 settings.node_bin_dir.as_deref(),
1442 state.node_bin_dir_precedes_project_bins,
1443 );
1444 entries.extend(std::env::split_paths(&path));
1445 let new_path = std::env::join_paths(entries).unwrap_or(path);
1446 let jail_home = jail.map(|j| jail_home(&j.package_dir));
1447 if let Some(home) = &jail_home {
1448 std::fs::create_dir_all(home)
1449 .map_err(|e| Error::Spawn(script_name.to_string(), e.to_string()))?;
1450 }
1451 let mut cmd = match (jail, jail_home.as_deref()) {
1452 (Some(jail), Some(home)) => spawn_jailed_shell(script_cmd, settings, jail, home),
1453 _ => spawn_shell_with_settings(script_cmd, settings),
1454 };
1455 cmd.current_dir(script_dir)
1456 .stderr(child_stderr())
1457 .env("PATH", &new_path)
1458 .env("npm_lifecycle_event", script_name);
1459
1460 if std::env::var_os("INIT_CWD").is_none() {
1467 cmd.env("INIT_CWD", project_root);
1468 }
1469
1470 if let (Some(jail), Some(home)) = (jail, jail_home.as_deref()) {
1471 apply_jail_env(
1472 &mut cmd,
1473 &new_path,
1474 home,
1475 project_root,
1476 manifest,
1477 script_name,
1478 &jail.env,
1479 );
1480 apply_script_settings_env(&mut cmd, settings);
1481 } else {
1482 cmd.env("AUBE_NODE_GYP_PROJECT_DIR", project_root);
1486 }
1487
1488 apply_npm_manifest_env(&mut cmd, manifest, script_dir, script_cmd);
1492
1493 tracing::debug!("lifecycle: {script_name} → {script_cmd}");
1494 let status = run_command_killing_descendants(cmd, script_name).await?;
1495
1496 if !status.success() {
1497 return Err(Error::NonZeroExit {
1498 script: script_name.to_string(),
1499 code: status.code(),
1500 });
1501 }
1502
1503 Ok(())
1504}
1505
1506pub async fn run_root_hook(
1512 project_dir: &Path,
1513 modules_dir_name: &str,
1514 manifest: &PackageJson,
1515 hook: LifecycleHook,
1516) -> Result<bool, Error> {
1517 run_root_script_by_name(project_dir, modules_dir_name, manifest, hook.script_name()).await
1518}
1519
1520pub async fn run_root_script_by_name(
1527 project_dir: &Path,
1528 modules_dir_name: &str,
1529 manifest: &PackageJson,
1530 name: &str,
1531) -> Result<bool, Error> {
1532 let Some(script_cmd) = manifest.scripts.get(name) else {
1533 return Ok(false);
1534 };
1535 run_script(
1536 project_dir,
1537 project_dir,
1538 modules_dir_name,
1539 manifest,
1540 name,
1541 script_cmd,
1542 &[],
1543 None,
1544 )
1545 .await?;
1546 Ok(true)
1547}
1548
1549pub fn implicit_install_script(
1562 manifest: &PackageJson,
1563 has_binding_gyp: bool,
1564) -> Option<&'static str> {
1565 if !has_binding_gyp {
1566 return None;
1567 }
1568 if manifest
1569 .scripts
1570 .contains_key(LifecycleHook::Install.script_name())
1571 || manifest
1572 .scripts
1573 .contains_key(LifecycleHook::PreInstall.script_name())
1574 {
1575 return None;
1576 }
1577 Some("node-gyp rebuild")
1578}
1579
1580pub fn default_install_script(package_dir: &Path, manifest: &PackageJson) -> Option<&'static str> {
1584 implicit_install_script(manifest, package_dir.join("binding.gyp").is_file())
1585}
1586
1587pub fn has_dep_lifecycle_work(package_dir: &Path, manifest: &PackageJson) -> bool {
1592 if DEP_LIFECYCLE_HOOKS
1593 .iter()
1594 .any(|h| manifest.scripts.contains_key(h.script_name()))
1595 {
1596 return true;
1597 }
1598 default_install_script(package_dir, manifest).is_some()
1599}
1600
1601#[allow(clippy::too_many_arguments)]
1635pub async fn run_dep_hook(
1636 package_dir: &Path,
1637 dep_modules_dir: &Path,
1638 project_root: &Path,
1639 modules_dir_name: &str,
1640 manifest: &PackageJson,
1641 hook: LifecycleHook,
1642 tool_bin_dirs: &[&Path],
1643 jail: Option<&ScriptJail>,
1644) -> Result<bool, Error> {
1645 let name = hook.script_name();
1646 let script_cmd: &str = match manifest.scripts.get(name) {
1647 Some(s) => s.as_str(),
1648 None => match hook {
1649 LifecycleHook::Install => match default_install_script(package_dir, manifest) {
1650 Some(s) => s,
1651 None => return Ok(false),
1652 },
1653 _ => return Ok(false),
1654 },
1655 };
1656 let nested_bin_dir = package_dir.join("node_modules").join(".bin");
1670 let dep_bin_dir = dep_modules_dir.join(".bin");
1671 let mut bin_dirs: Vec<&Path> = Vec::with_capacity(tool_bin_dirs.len() + 2);
1672 if nested_bin_dir != dep_bin_dir {
1673 bin_dirs.push(&nested_bin_dir);
1674 }
1675 bin_dirs.push(&dep_bin_dir);
1676 bin_dirs.extend(tool_bin_dirs.iter().copied());
1677 run_script(
1678 package_dir,
1679 project_root,
1680 modules_dir_name,
1681 manifest,
1682 name,
1683 script_cmd,
1684 &bin_dirs,
1685 jail,
1686 )
1687 .await?;
1688 Ok(true)
1689}
1690
1691#[derive(Debug, thiserror::Error, miette::Diagnostic)]
1692pub enum Error {
1693 #[error("failed to spawn script {0}: {1}")]
1694 #[diagnostic(code(ERR_AUBE_SCRIPT_SPAWN))]
1695 Spawn(String, String),
1696 #[error("script `{script}` exited with code {code:?}")]
1697 #[diagnostic(code(ERR_AUBE_SCRIPT_NON_ZERO_EXIT))]
1698 NonZeroExit { script: String, code: Option<i32> },
1699}
1700
1701#[cfg(test)]
1702mod user_agent_tests {
1703 use super::*;
1704
1705 #[test]
1706 fn user_agent_uses_node_style_platform_and_arch() {
1707 let ua = aube_user_agent();
1708 assert!(ua.starts_with("aube/"), "unexpected prefix: {ua}");
1710 let parts: Vec<&str> = ua.split(' ').collect();
1711 assert_eq!(parts.len(), 3, "expected 3 space-separated fields: {ua}");
1712 let platform = parts[1];
1714 assert!(
1715 matches!(
1716 platform,
1717 "darwin" | "linux" | "win32" | "freebsd" | "openbsd" | "netbsd" | "dragonfly"
1718 ),
1719 "platform `{platform}` should follow Node's `process.platform` vocabulary"
1720 );
1721 let arch = parts[2];
1725 assert!(
1726 matches!(
1727 arch,
1728 "x64"
1729 | "arm64"
1730 | "ia32"
1731 | "arm"
1732 | "ppc"
1733 | "ppc64"
1734 | "loong64"
1735 | "mips"
1736 | "riscv64"
1737 | "s390x"
1738 ),
1739 "arch `{arch}` should follow Node's `process.arch` vocabulary"
1740 );
1741 }
1742}
1743
1744#[cfg(test)]
1745mod spawn_program_tests {
1746 use super::*;
1747
1748 fn env_keys(cmd: &tokio::process::Command) -> Vec<String> {
1749 let mut keys: Vec<String> = cmd
1750 .as_std()
1751 .get_envs()
1752 .map(|(k, _)| k.to_string_lossy().into_owned())
1753 .collect();
1754 keys.sort();
1755 keys
1756 }
1757
1758 #[tokio::test]
1764 async fn spawn_program_stamps_the_same_env_as_spawn_shell() {
1765 let settings = ScriptSettings {
1766 node_options: Some("--max-old-space-size=100".to_string()),
1767 node_program: Some(PathBuf::from("/usr/bin/node")),
1768 node_execpath: Some(PathBuf::from("/usr/bin/node")),
1769 command: Some("run-script".to_string()),
1770 http_proxy: Some("http://proxy.invalid".to_string()),
1771 https_proxy: Some("http://proxy.invalid".to_string()),
1772 ..ScriptSettings::default()
1773 };
1774 scope(async move {
1775 set_script_settings(settings);
1776 let shell = spawn_shell("tool --flag");
1777 let direct = spawn_program(Path::new("/usr/bin/tool"), "tool", ["--flag"]);
1778 assert_eq!(
1779 env_keys(&shell),
1780 env_keys(&direct),
1781 "direct exec must export the same env keys as `sh -c`"
1782 );
1783 })
1784 .await;
1785 }
1786
1787 #[cfg(unix)]
1795 #[tokio::test]
1796 async fn dep_hook_prefers_the_packages_own_nested_bin() {
1797 let nanos = std::time::SystemTime::now()
1800 .duration_since(std::time::UNIX_EPOCH)
1801 .unwrap_or_default()
1802 .as_nanos();
1803 let root = std::env::temp_dir().join(format!("aube-test-nested-bin-{nanos}"));
1804 let root = root.as_path();
1805 let package_dir = root.join("node_modules/requester");
1806 let marker = root.join("which-ran.txt");
1807
1808 for (bin_dir, tag) in [
1811 (root.join("node_modules/.bin"), "sibling"),
1812 (package_dir.join("node_modules/.bin"), "nested"),
1813 ] {
1814 std::fs::create_dir_all(&bin_dir).unwrap();
1815 let tool = bin_dir.join("tool");
1816 std::fs::write(
1817 &tool,
1818 format!("#!/bin/sh\nprintf {tag} > \"{}\"\n", marker.display()),
1819 )
1820 .unwrap();
1821 let mut perms = std::fs::metadata(&tool).unwrap().permissions();
1822 std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o755);
1823 std::fs::set_permissions(&tool, perms).unwrap();
1824 }
1825
1826 let mut scripts = std::collections::BTreeMap::new();
1827 scripts.insert("postinstall".to_string(), "tool".to_string());
1828 let manifest = PackageJson {
1829 name: Some("requester".to_string()),
1830 version: Some("1.0.0".to_string()),
1831 scripts,
1832 ..PackageJson::default()
1833 };
1834
1835 let ran = run_dep_hook(
1836 &package_dir,
1837 &root.join("node_modules"),
1840 root,
1841 "node_modules",
1842 &manifest,
1843 LifecycleHook::PostInstall,
1844 &[],
1845 None,
1846 )
1847 .await
1848 .unwrap();
1849
1850 let which_ran = std::fs::read_to_string(&marker);
1851 let _ = std::fs::remove_dir_all(root);
1852 assert!(ran, "postinstall is defined, so it should have run");
1853 assert_eq!(
1854 which_ran.unwrap(),
1855 "nested",
1856 "the package's own nested `.bin` must win over its siblings'"
1857 );
1858 }
1859
1860 #[cfg(unix)]
1861 #[tokio::test]
1862 async fn spawn_program_runs_the_program_with_its_args() {
1863 let mut cmd = spawn_program(Path::new("/bin/echo"), "echo", ["a b", "$HOME"]);
1864 let out = cmd.output().await.unwrap();
1865 assert!(out.status.success());
1866 assert_eq!(String::from_utf8_lossy(&out.stdout), "a b $HOME\n");
1868 }
1869}
1870
1871#[cfg(test)]
1872mod jail_tests {
1873 use super::*;
1874
1875 #[test]
1876 fn jail_home_uses_full_package_path() {
1877 let a = jail_home(Path::new("/tmp/project/node_modules/@scope-a/native"));
1878 let b = jail_home(Path::new("/tmp/project/node_modules/@scope-b/native"));
1879
1880 assert_ne!(a, b);
1881 assert!(
1882 a.file_name()
1883 .unwrap()
1884 .to_string_lossy()
1885 .starts_with("native-")
1886 );
1887 assert!(
1888 b.file_name()
1889 .unwrap()
1890 .to_string_lossy()
1891 .starts_with("native-")
1892 );
1893 }
1894
1895 #[test]
1896 fn jail_home_cleanup_removes_temp_home() {
1897 let package_dir = std::env::temp_dir()
1898 .join("aube-jail-cleanup-test")
1899 .join(std::process::id().to_string())
1900 .join("node_modules")
1901 .join("native");
1902 let jail = ScriptJail::new(&package_dir);
1903 let home = jail_home(&package_dir);
1904 std::fs::create_dir_all(home.join(".cache")).unwrap();
1905 std::fs::write(home.join(".cache").join("marker"), "x").unwrap();
1906
1907 {
1908 let _cleanup = ScriptJailHomeCleanup::new(&jail);
1909 }
1910
1911 assert!(!home.exists());
1912 }
1913
1914 #[test]
1915 fn parent_env_cannot_override_explicit_jail_metadata() {
1916 for key in [
1917 "PATH",
1918 "HOME",
1919 "npm_lifecycle_event",
1920 "npm_package_name",
1921 "npm_package_version",
1922 ] {
1923 assert!(!inherit_jail_env_key(key, &[]));
1924 }
1925 assert!(inherit_jail_env_key("INIT_CWD", &[]));
1926 assert!(inherit_jail_env_key("npm_config_arch", &[]));
1927 assert!(!inherit_jail_env_key("npm_config__authToken", &[]));
1928 assert!(inherit_jail_env_key(
1929 "SHARP_DIST_BASE_URL",
1930 &["SHARP_DIST_BASE_URL".to_string()]
1931 ));
1932 }
1933
1934 #[test]
1935 fn jail_env_preserves_script_settings_after_clear() {
1936 let mut cmd = tokio::process::Command::new("node");
1937 let manifest = PackageJson {
1938 name: Some("pkg".to_string()),
1939 version: Some("1.2.3".to_string()),
1940 ..Default::default()
1941 };
1942 let settings = ScriptSettings {
1943 node_options: Some("--conditions=aube".to_string()),
1944 unsafe_perm: Some(false),
1945 shell_emulator: true,
1946 ..Default::default()
1947 };
1948
1949 apply_jail_env(
1950 &mut cmd,
1951 std::ffi::OsStr::new("/bin"),
1952 Path::new("/tmp/aube-jail/home"),
1953 Path::new("/tmp/project"),
1954 &manifest,
1955 "postinstall",
1956 &[],
1957 );
1958 apply_script_settings_env(&mut cmd, &settings);
1959
1960 let envs = cmd.as_std().get_envs().collect::<Vec<_>>();
1961 let env = |name: &str| {
1962 envs.iter()
1963 .find(|(key, _)| *key == std::ffi::OsStr::new(name))
1964 .and_then(|(_, val)| *val)
1965 .and_then(|val| val.to_str())
1966 };
1967
1968 assert_eq!(env("NODE_OPTIONS"), Some("--conditions=aube"));
1969 assert_eq!(env("npm_config_unsafe_perm"), Some("false"));
1970 assert_eq!(env("npm_config_shell_emulator"), Some("true"));
1971 assert_eq!(env("AUBE_NODE_GYP_PROJECT_DIR"), Some("/tmp/project"));
1972 assert_eq!(env("npm_lifecycle_event"), Some("postinstall"));
1973 assert_eq!(env("npm_package_name"), Some("pkg"));
1974 assert_eq!(env("npm_package_version"), Some("1.2.3"));
1975 }
1976
1977 #[test]
1978 fn embedder_env_overrides_jailed_node_gyp_project_default() {
1979 let mut cmd = tokio::process::Command::new("node");
1980 let settings = ScriptSettings {
1981 extra_env: vec![(
1982 "AUBE_NODE_GYP_PROJECT_DIR".into(),
1983 "/tmp/embedder-project".into(),
1984 )],
1985 ..Default::default()
1986 };
1987
1988 apply_jail_env(
1989 &mut cmd,
1990 std::ffi::OsStr::new("/bin"),
1991 Path::new("/tmp/aube-jail/home"),
1992 Path::new("/tmp/project"),
1993 &PackageJson::default(),
1994 "postinstall",
1995 &[],
1996 );
1997 apply_script_settings_env(&mut cmd, &settings);
1998
1999 let project_dir = cmd
2000 .as_std()
2001 .get_envs()
2002 .find(|(key, _)| *key == std::ffi::OsStr::new("AUBE_NODE_GYP_PROJECT_DIR"))
2003 .and_then(|(_, value)| value)
2004 .and_then(|value| value.to_str());
2005 assert_eq!(project_dir, Some("/tmp/embedder-project"));
2006 }
2007
2008 fn proxy_env(settings: ScriptSettings) -> impl Fn(&str) -> Option<String> {
2009 let mut cmd = tokio::process::Command::new("node");
2010 apply_script_settings_env(&mut cmd, &settings);
2011 let envs: Vec<_> = cmd
2012 .as_std()
2013 .get_envs()
2014 .map(|(k, v)| {
2015 (
2016 k.to_string_lossy().into_owned(),
2017 v.map(|v| v.to_string_lossy().into_owned()),
2018 )
2019 })
2020 .collect();
2021 move |name: &str| {
2022 envs.iter()
2023 .find(|(k, _)| k == name)
2024 .and_then(|(_, v)| v.clone())
2025 }
2026 }
2027
2028 #[test]
2029 fn proxy_vars_stamped_when_proxy_configured() {
2030 let env = proxy_env(ScriptSettings {
2031 https_proxy: Some("http://proxy.example:8080".to_string()),
2032 http_proxy: Some("http://proxy.example:8080".to_string()),
2033 no_proxy: Some("localhost,127.0.0.1".to_string()),
2034 ..Default::default()
2035 });
2036 assert_eq!(
2037 env("HTTPS_PROXY").as_deref(),
2038 Some("http://proxy.example:8080")
2039 );
2040 assert_eq!(
2041 env("HTTP_PROXY").as_deref(),
2042 Some("http://proxy.example:8080")
2043 );
2044 assert_eq!(env("NO_PROXY").as_deref(), Some("localhost,127.0.0.1"));
2045 assert_eq!(env("NODE_USE_ENV_PROXY").as_deref(), Some("1"));
2048 }
2049
2050 #[test]
2053 fn npm_execpath_defaults_to_the_running_binary() {
2054 let env = proxy_env(ScriptSettings::default());
2055 assert!(!aube_util::is_embedded());
2056 assert_eq!(
2057 env("npm_execpath").map(PathBuf::from),
2058 std::env::current_exe().ok()
2059 );
2060 }
2061
2062 #[tokio::test]
2067 async fn pm_execpath_overrides_the_running_binary() {
2068 scope(async {
2069 set_pm_execpath(Some(PathBuf::from("/cache/aube/tools/pm-exec/aube")));
2070 let env = proxy_env(ScriptSettings::default());
2071 assert_eq!(
2072 env("npm_execpath").as_deref(),
2073 Some("/cache/aube/tools/pm-exec/aube")
2074 );
2075 })
2076 .await;
2077 }
2078
2079 #[test]
2084 fn pm_execpath_resolution_table() {
2085 let exe = Some(PathBuf::from("/usr/bin/aube"));
2086 let shim = Some(PathBuf::from("/cache/aube/tools/pm-exec/aube"));
2087 assert_eq!(pm_execpath_for(None, false, exe.clone()), exe);
2088 assert_eq!(pm_execpath_for(None, true, exe.clone()), None);
2089 assert_eq!(pm_execpath_for(shim.clone(), true, exe.clone()), shim);
2090 assert_eq!(pm_execpath_for(shim.clone(), false, exe), shim);
2091 assert_eq!(pm_execpath_for(None, false, None), None);
2092 }
2093
2094 #[test]
2097 fn cli_exe_is_stamped_for_the_shim() {
2098 let env = proxy_env(ScriptSettings::default());
2099 assert_eq!(
2100 env(CLI_EXE_ENV).map(PathBuf::from),
2101 std::env::current_exe().ok()
2102 );
2103 }
2104
2105 #[test]
2106 fn proxy_block_skipped_when_no_proxy_configured() {
2107 let env = proxy_env(ScriptSettings::default());
2111 assert_eq!(env("HTTPS_PROXY"), None);
2112 assert_eq!(env("HTTP_PROXY"), None);
2113 assert_eq!(env("NO_PROXY"), None);
2114 assert_eq!(env("NODE_USE_ENV_PROXY"), None);
2115 }
2116
2117 #[test]
2118 fn no_proxy_alone_does_not_trigger_passthrough() {
2119 let env = proxy_env(ScriptSettings {
2122 no_proxy: Some("example.com".to_string()),
2123 ..Default::default()
2124 });
2125 assert_eq!(env("NO_PROXY"), None);
2126 assert_eq!(env("NODE_USE_ENV_PROXY"), None);
2127 }
2128
2129 #[test]
2130 fn wrapper_node_and_execpath_are_stamped_distinctly() {
2131 let env = proxy_env(ScriptSettings {
2135 node_program: Some(PathBuf::from("/shim/node")),
2136 node_execpath: Some(PathBuf::from("/real/node-24.4.1/bin/node")),
2137 extra_env: vec![("MYTOOL_WRAPPED".into(), "1".into())],
2138 ..Default::default()
2139 });
2140 assert_eq!(env("NODE").as_deref(), Some("/shim/node"));
2141 assert_eq!(
2142 env("npm_node_execpath").as_deref(),
2143 Some("/real/node-24.4.1/bin/node")
2144 );
2145 assert_eq!(env("MYTOOL_WRAPPED").as_deref(), Some("1"));
2146 }
2147
2148 #[test]
2149 fn node_execpath_falls_back_to_node_program() {
2150 let env = proxy_env(ScriptSettings {
2152 node_program: Some(PathBuf::from("/opt/node/bin/node")),
2153 ..Default::default()
2154 });
2155 assert_eq!(env("NODE").as_deref(), Some("/opt/node/bin/node"));
2156 assert_eq!(
2157 env("npm_node_execpath").as_deref(),
2158 Some("/opt/node/bin/node")
2159 );
2160 }
2161}
2162
2163#[cfg(all(test, windows))]
2164mod windows_quote_tests {
2165 use super::shell_quote_arg;
2166
2167 #[test]
2168 fn windows_path_backslash_not_doubled() {
2169 let q = shell_quote_arg(r"C:\Users\me\file.txt");
2170 assert_eq!(q, "\"C:\\Users\\me\\file.txt\"");
2171 }
2172
2173 #[test]
2174 fn windows_trailing_backslash_doubled_before_close_quote() {
2175 let q = shell_quote_arg(r"C:\path\");
2176 assert_eq!(q, "\"C:\\path\\\\\"");
2177 }
2178
2179 #[test]
2180 fn windows_quote_in_arg_escapes_with_backslash() {
2181 assert_eq!(shell_quote_arg(r#"a"b"#), "\"a\\\"b\"");
2182 assert_eq!(shell_quote_arg(r#"a\"b"#), "\"a\\\\\\\"b\"");
2183 assert_eq!(shell_quote_arg(r#"a\\"b"#), "\"a\\\\\\\\\\\"b\"");
2184 }
2185}
2186
2187#[cfg(all(test, windows))]
2194mod windows_job_object_tests {
2195 use super::*;
2196 use std::time::{Duration, Instant};
2197 use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE};
2198 use windows_sys::Win32::System::Threading::{
2199 GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
2200 };
2201
2202 fn is_process_alive(pid: u32) -> bool {
2203 unsafe {
2207 let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
2208 if handle.is_null() {
2209 return false;
2210 }
2211 let mut code: u32 = 0;
2212 let ok = GetExitCodeProcess(handle, &mut code);
2213 CloseHandle(handle);
2214 ok != 0 && code == STILL_ACTIVE as u32
2215 }
2216 }
2217
2218 async fn wait_until<F: Fn() -> bool>(check: F, timeout: Duration) -> bool {
2219 let start = Instant::now();
2220 while !check() {
2221 if start.elapsed() > timeout {
2222 return false;
2223 }
2224 tokio::time::sleep(Duration::from_millis(75)).await;
2225 }
2226 true
2227 }
2228
2229 #[tokio::test]
2230 async fn aborting_script_kills_grandchildren() {
2231 let nanos = std::time::SystemTime::now()
2235 .duration_since(std::time::UNIX_EPOCH)
2236 .unwrap_or_default()
2237 .as_nanos();
2238 let pid_file = std::env::temp_dir().join(format!("aube-test-grandchild-{nanos}.pid"));
2239 let script = format!(
2248 "start /b powershell -NoProfile -WindowStyle Hidden -Command \
2249 \"$pid | Out-File -Encoding ascii -FilePath '{}'; Start-Sleep 60\" \
2250 & ping -n 10 127.0.0.1 >nul",
2251 pid_file.display()
2252 );
2253 let cmd = spawn_shell_with_settings(&script, &ScriptSettings::default());
2254 let task = tokio::spawn(async move {
2255 let _ = run_command_killing_descendants(cmd, "test-grandchild").await;
2256 });
2257
2258 let appeared = wait_until(
2259 || {
2260 std::fs::read_to_string(&pid_file)
2261 .ok()
2262 .and_then(|pid| pid.trim().parse::<u32>().ok())
2263 .is_some()
2264 },
2265 Duration::from_secs(20),
2266 )
2267 .await;
2268 assert!(appeared, "grandchild never wrote pid file at {pid_file:?}");
2269 let pid: u32 = std::fs::read_to_string(&pid_file)
2270 .expect("read pid file")
2271 .trim()
2272 .parse()
2273 .expect("pid file was parseable before reading");
2274 assert!(
2275 is_process_alive(pid),
2276 "grandchild pid {pid} not alive immediately after writing pid file"
2277 );
2278
2279 task.abort();
2284 let _ = task.await;
2285
2286 let reaped = wait_until(|| !is_process_alive(pid), Duration::from_secs(10)).await;
2287 let _ = std::fs::remove_file(&pid_file);
2288 assert!(
2289 reaped,
2290 "grandchild pid {pid} survived parent abort — job object did not kill the tree"
2291 );
2292 }
2293}