1use super::*;
4
5#[cfg(windows)]
6fn windows_file_identity(path: &Path) -> Result<(u32, u64), ExecutionError> {
7 use std::mem::MaybeUninit;
8 use std::os::windows::io::AsRawHandle;
9 use windows_sys::Win32::Storage::FileSystem::{
10 BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle,
11 };
12
13 let file =
14 fs::File::open(path).map_err(|error| path_error("trusted Node runtime", path, error))?;
15 let mut information = MaybeUninit::<BY_HANDLE_FILE_INFORMATION>::zeroed();
16 let succeeded = unsafe {
19 GetFileInformationByHandle(file.as_raw_handle() as isize, information.as_mut_ptr())
20 };
21 if succeeded == 0 {
22 return Err(path_error(
23 "trusted Node runtime identity",
24 path,
25 std::io::Error::last_os_error(),
26 ));
27 }
28 let information = unsafe { information.assume_init() };
30 let file_index =
31 (u64::from(information.nFileIndexHigh) << 32) | u64::from(information.nFileIndexLow);
32 Ok((information.dwVolumeSerialNumber, file_index))
33}
34
35#[derive(Clone, Debug, Eq, PartialEq)]
37pub(super) struct TrustedNodeRuntime {
38 pub(super) path: PathBuf,
39 #[cfg(unix)]
40 pub(super) identity: NativeIdentity,
41 #[cfg(windows)]
42 pub(super) volume_serial_number: u32,
43 #[cfg(windows)]
44 pub(super) file_index: u64,
45}
46
47impl TrustedNodeRuntime {
48 pub(super) fn checked(path: &Path) -> Result<Self, ExecutionError> {
49 let canonical = canonical_path(path, "trusted Node runtime")?;
50 if canonical != path || !is_node_executable_name(&canonical) {
51 return Err(invalid_request(
52 "trusted Node runtime must be canonical and named node or node.exe",
53 ));
54 }
55 let metadata = fs::metadata(&canonical)
56 .map_err(|error| path_error("trusted Node runtime", &canonical, error))?;
57 if !metadata.is_file() {
58 return Err(invalid_request(
59 "trusted Node runtime must be a regular file",
60 ));
61 }
62 #[cfg(unix)]
63 {
64 use std::os::unix::fs::{MetadataExt, PermissionsExt};
65 if metadata.permissions().mode() & 0o111 == 0 {
66 return Err(invalid_request("trusted Node runtime must be executable"));
67 }
68 Ok(Self {
69 path: canonical,
70 identity: NativeIdentity {
71 device: metadata.dev(),
72 inode: metadata.ino(),
73 },
74 })
75 }
76 #[cfg(windows)]
77 {
78 let (volume_serial_number, file_index) = windows_file_identity(&canonical)?;
79 Ok(Self {
80 path: canonical,
81 volume_serial_number,
82 file_index,
83 })
84 }
85 #[cfg(not(any(unix, windows)))]
86 Ok(Self { path: canonical })
87 }
88
89 pub(super) fn validate(&self, search_paths: &[PathBuf]) -> Result<(), ExecutionError> {
90 #[cfg(not(target_os = "macos"))]
91 if search_paths
92 .first()
93 .and_then(|directory| fs::canonicalize(directory.join(self.path.file_name()?)).ok())
94 .as_deref()
95 != Some(self.path.as_path())
96 {
97 return Err(invalid_request(
98 "first executable search directory must resolve node to the verified runtime",
99 ));
100 }
101 #[cfg(target_os = "macos")]
102 if !search_paths
103 .iter()
104 .any(|p| Some(p.as_path()) == self.path.parent())
105 {
106 return Err(invalid_request(
107 "search paths must contain the trusted runtime parent",
108 ));
109 }
110 let current = Self::checked(&self.path).map_err(|_| {
111 ExecutionError::new(
112 ExecutionErrorCategory::PolicyViolation,
113 "trusted Node runtime identity changed after request construction",
114 )
115 })?;
116 if ¤t != self {
117 return Err(ExecutionError::new(
118 ExecutionErrorCategory::PolicyViolation,
119 "trusted Node runtime identity changed after request construction",
120 ));
121 }
122 Ok(())
123 }
124}
125
126fn is_node_executable_name(path: &Path) -> bool {
127 path.file_name().is_some_and(|name| {
128 #[cfg(windows)]
129 return name.to_string_lossy().eq_ignore_ascii_case("node.exe");
130 #[cfg(not(windows))]
131 return name == OsStr::new("node");
132 })
133}
134
135#[derive(Clone, Debug, Eq, PartialEq)]
149pub struct ExecutionRequest {
150 #[cfg(target_os = "macos")]
151 pub(super) reserved_node: Option<platform_backend::ReservedNodeBinding>,
152 pub(super) launcher: Option<crate::PrivateLauncher>,
153 pub(super) program: OsString,
154 pub(super) arguments: Vec<OsString>,
155 pub(super) executable_search_paths: Vec<PathBuf>,
156 pub(super) trusted_node_runtime: Option<TrustedNodeRuntime>,
157 pub(super) windows_verbatim_arguments: bool,
158 pub(super) allow_process_memory_stats: bool,
159 pub(super) project_root: PathBuf,
160 pub(super) policy: SandboxPolicy,
161 pub(super) environment: BTreeMap<OsString, OsString>,
162}
163
164impl ExecutionRequest {
165 pub fn builder(program: impl Into<OsString>) -> ExecutionRequestBuilder {
166 ExecutionRequestBuilder {
167 program: program.into(),
168 arguments: Vec::new(),
169 executable_search_paths: Vec::new(),
170 trusted_node_runtime: None,
171 windows_verbatim_arguments: false,
172 allow_process_memory_stats: false,
173 project_root: PathBuf::from("."),
174 policy: SandboxPolicy::default(),
175 environment: BTreeMap::new(),
176 }
177 }
178
179 pub fn program(&self) -> &OsStr {
180 &self.program
181 }
182 pub fn arguments(&self) -> &[OsString] {
183 &self.arguments
184 }
185 pub fn uses_windows_verbatim_arguments(&self) -> bool {
187 self.windows_verbatim_arguments
188 }
189 pub(super) fn executable_search_paths(&self) -> &[PathBuf] {
191 &self.executable_search_paths
192 }
193 #[cfg(all(test, unix))]
194 pub(super) fn trusted_node_runtime(&self) -> &Path {
195 self.trusted_node_runtime
196 .as_ref()
197 .expect("trusted Node runtime was requested")
198 .path
199 .as_path()
200 }
201 pub(super) fn validate_trusted_node_runtime(&self) -> Result<(), ExecutionError> {
202 #[cfg(target_os = "macos")]
203 if let Some(binding) = &self.reserved_node {
204 return binding.validate();
205 }
206 if let Some(runtime) = &self.trusted_node_runtime {
207 runtime.validate(&self.executable_search_paths)?;
208 }
209 Ok(())
210 }
211 pub fn project_root(&self) -> &Path {
212 &self.project_root
213 }
214 pub fn policy(&self) -> &SandboxPolicy {
215 &self.policy
216 }
217
218 pub fn allow_process_memory_stats(&self) -> bool {
220 self.allow_process_memory_stats
221 }
222
223 #[cfg(target_os = "linux")]
224 pub(crate) fn private_launcher_executable(&self) -> Option<&Path> {
225 self.launcher
226 .as_ref()
227 .and_then(|launcher| launcher.executable.as_deref())
228 }
229
230 pub fn environment(&self) -> &BTreeMap<OsString, OsString> {
236 &self.environment
237 }
238
239 pub(super) fn child_environment(&self) -> BTreeMap<OsString, OsString> {
241 let mut environment = self.environment.clone();
242 let path = join_executable_search_paths(&self.executable_search_paths)
243 .expect("validated executable search paths must remain joinable");
244 environment.insert(OsString::from("PATH"), path);
245 environment
246 }
247
248 pub(super) fn validate_windows_verbatim_boundary(&self) -> Result<(), ExecutionError> {
249 if !self.windows_verbatim_arguments {
250 return Ok(());
251 }
252 let is_cmd = Path::new(&self.program)
253 .file_name()
254 .and_then(OsStr::to_str)
255 .is_some_and(|name| {
256 name.eq_ignore_ascii_case("cmd") || name.eq_ignore_ascii_case("cmd.exe")
257 });
258 if !is_cmd
259 || self.arguments.len() != 4
260 || self.arguments[0] != OsStr::new("/D")
261 || self.arguments[1] != OsStr::new("/S")
262 || self.arguments[2] != OsStr::new("/C")
263 {
264 return Err(invalid_request(
265 "Windows verbatim arguments require cmd.exe /D /S /C plus one command payload",
266 ));
267 }
268 let payload = self.arguments[3].to_str().ok_or_else(|| {
269 invalid_request("Windows verbatim command payload must be valid Unicode")
270 })?;
271 if payload.contains(['\r', '\n']) {
272 return Err(invalid_request(
273 "Windows verbatim command payload cannot contain CR or LF",
274 ));
275 }
276 Ok(())
277 }
278
279 pub(super) fn validate(&self) -> Result<(), ExecutionError> {
280 self.validate_windows_verbatim_boundary()?;
281 #[cfg(not(target_os = "linux"))]
282 if self.allow_process_memory_stats {
283 return Err(invalid_request(
284 "process memory statistics opt-in is supported only by the Linux Restricted backend",
285 ));
286 }
287 #[cfg(target_os = "linux")]
288 if self.allow_process_memory_stats
289 && (self.policy.mode() != SandboxMode::Required
290 || self.policy.assurance() != AssuranceLevel::Restricted)
291 {
292 return Err(invalid_request(
293 "process memory statistics opt-in requires required sandbox mode and Linux Restricted assurance",
294 ));
295 }
296 #[cfg(target_os = "linux")]
297 if self.allow_process_memory_stats && self.private_launcher_executable().is_none() {
298 return Err(invalid_request(
299 "process memory statistics opt-in requires early private-launcher initialization",
300 ));
301 }
302 let program_units =
303 validate_os_value("execution program", &self.program, MAX_PROGRAM_UNITS)?;
304 if self.program.is_empty() {
305 return Err(invalid_request("execution program must not be empty"));
306 }
307 if self.arguments.len() > MAX_ARGUMENT_COUNT {
308 return Err(invalid_request(format!(
309 "execution request exceeds {MAX_ARGUMENT_COUNT} arguments"
310 )));
311 }
312 #[cfg(windows)]
313 let mut argument_units = Vec::with_capacity(self.arguments.len());
314 #[cfg(not(windows))]
315 let mut argv_units = program_units.saturating_add(1);
316 for argument in &self.arguments {
317 let units = validate_os_value("execution argument", argument, MAX_ARGUMENT_UNITS)?;
318 #[cfg(windows)]
319 argument_units.push(units);
320 #[cfg(not(windows))]
321 {
322 argv_units = argv_units.saturating_add(units).saturating_add(1);
323 }
324 }
325 #[cfg(windows)]
326 validate_windows_command_line_units(program_units, argument_units.iter().copied())?;
327 #[cfg(not(windows))]
328 if argv_units > MAX_ARGV_UNITS {
329 return Err(invalid_request(format!(
330 "execution argv exceeds {MAX_ARGV_UNITS} bytes/code units"
331 )));
332 }
333 validate_os_value(
334 "project root",
335 self.project_root.as_os_str(),
336 MAX_PROJECT_ROOT_UNITS,
337 )?;
338 if self.project_root.as_os_str().is_empty() {
339 return Err(invalid_request("project root must not be empty"));
340 }
341 let executable_search_path =
342 validate_executable_search_paths(&self.executable_search_paths)?;
343 self.validate_trusted_node_runtime()?;
344 let mut environment_units = 1usize
347 .checked_add(os_units(OsStr::new("PATH")))
348 .and_then(|units| units.checked_add(os_units(&executable_search_path)))
349 .and_then(|units| units.checked_add(2))
350 .ok_or_else(environment_block_too_large)?;
351 if environment_units > MAX_ENVIRONMENT_BLOCK_UNITS {
352 return Err(environment_block_too_large());
353 }
354 for (name, value) in &self.environment {
355 let Some(name) = name.to_str() else {
356 return Err(invalid_request(
357 "environment variable names must be valid UTF-8",
358 ));
359 };
360 if name.eq_ignore_ascii_case("PATH") {
361 return Err(invalid_request(
362 "caller-controlled PATH is forbidden; containment backends own executable search paths",
363 ));
364 }
365 if validate_environment_name(name).is_err() {
366 return Err(invalid_request(format!(
367 "invalid environment variable name: {name:?}"
368 )));
369 }
370 let name_units = os_units(name.as_ref());
371 let value_units = validate_os_value(
372 "environment variable value",
373 value,
374 MAX_ENVIRONMENT_VALUE_UNITS,
375 )?;
376 environment_units = environment_units
377 .checked_add(name_units)
378 .and_then(|units| units.checked_add(value_units))
379 .and_then(|units| units.checked_add(2))
380 .ok_or_else(environment_block_too_large)?;
381 if environment_units > MAX_ENVIRONMENT_BLOCK_UNITS {
382 return Err(environment_block_too_large());
383 }
384 if !self
385 .policy
386 .environment()
387 .iter()
388 .any(|allowed| allowed == name)
389 {
390 return Err(invalid_request(format!(
391 "environment variable is not allowlisted by policy: {name}"
392 )));
393 }
394 }
395 Ok(())
396 }
397}
398
399#[derive(Clone, Debug)]
401pub struct ExecutionRequestBuilder {
402 program: OsString,
403 arguments: Vec<OsString>,
404 executable_search_paths: Vec<PathBuf>,
405 trusted_node_runtime: Option<PathBuf>,
406 windows_verbatim_arguments: bool,
407 allow_process_memory_stats: bool,
408 project_root: PathBuf,
409 policy: SandboxPolicy,
410 environment: BTreeMap<OsString, OsString>,
411}
412
413impl ExecutionRequestBuilder {
414 pub fn arg(mut self, argument: impl Into<OsString>) -> Self {
415 self.arguments.push(argument.into());
416 self
417 }
418
419 pub fn args<I, S>(mut self, arguments: I) -> Self
420 where
421 I: IntoIterator<Item = S>,
422 S: Into<OsString>,
423 {
424 self.arguments.extend(arguments.into_iter().map(Into::into));
425 self
426 }
427
428 pub fn executable_search_path(mut self, path: impl Into<PathBuf>) -> Self {
434 self.executable_search_paths.push(path.into());
435 self
436 }
437
438 pub fn trusted_node_runtime(mut self, path: impl Into<PathBuf>) -> Self {
440 self.trusted_node_runtime = Some(path.into());
441 self
442 }
443
444 pub fn windows_verbatim_arguments(mut self, enabled: bool) -> Self {
446 self.windows_verbatim_arguments = enabled;
447 self
448 }
449
450 pub fn allow_process_memory_stats(mut self, enabled: bool) -> Self {
452 self.allow_process_memory_stats = enabled;
453 self
454 }
455
456 pub fn executable_search_paths<I, P>(mut self, paths: I) -> Self
461 where
462 I: IntoIterator<Item = P>,
463 P: Into<PathBuf>,
464 {
465 self.executable_search_paths
466 .extend(paths.into_iter().map(Into::into));
467 self
468 }
469
470 pub fn project_root(mut self, project_root: impl Into<PathBuf>) -> Self {
471 self.project_root = project_root.into();
472 self
473 }
474
475 pub fn policy(mut self, policy: SandboxPolicy) -> Self {
476 self.policy = policy;
477 self
478 }
479
480 pub fn env(mut self, name: impl Into<OsString>, value: impl Into<OsString>) -> Self {
482 self.environment.insert(name.into(), value.into());
483 self
484 }
485
486 pub fn envs<I, K, V>(mut self, environment: I) -> Self
488 where
489 I: IntoIterator<Item = (K, V)>,
490 K: Into<OsString>,
491 V: Into<OsString>,
492 {
493 self.environment.extend(
494 environment
495 .into_iter()
496 .map(|(name, value)| (name.into(), value.into())),
497 );
498 self
499 }
500
501 pub fn build(self) -> Result<ExecutionRequest, ExecutionError> {
502 let trusted_node_runtime = self
503 .trusted_node_runtime
504 .as_deref()
505 .map(TrustedNodeRuntime::checked)
506 .transpose()?;
507 let request = ExecutionRequest {
508 #[cfg(target_os = "macos")]
509 reserved_node: None,
510 launcher: crate::LAUNCHER.get().cloned(),
511 program: self.program,
512 arguments: self.arguments,
513 executable_search_paths: self.executable_search_paths,
514 trusted_node_runtime,
515 windows_verbatim_arguments: self.windows_verbatim_arguments,
516 allow_process_memory_stats: self.allow_process_memory_stats,
517 project_root: self.project_root,
518 policy: self.policy,
519 environment: self.environment,
520 };
521 request.validate()?;
522 Ok(request)
523 }
524}
525
526pub(super) fn validate_executable_search_paths(
527 paths: &[PathBuf],
528) -> Result<OsString, ExecutionError> {
529 if paths.len() > MAX_EXECUTABLE_SEARCH_PATH_COUNT {
530 return Err(invalid_request(format!(
531 "execution request exceeds {MAX_EXECUTABLE_SEARCH_PATH_COUNT} executable search directories"
532 )));
533 }
534
535 for path in paths {
538 validate_os_value(
539 "executable search directory",
540 path.as_os_str(),
541 MAX_EXECUTABLE_SEARCH_PATH_UNITS,
542 )?;
543 }
544
545 let joined = join_executable_search_paths(paths)?;
546 let total_units = os_units(&joined)
547 .checked_add(1)
548 .ok_or_else(executable_search_path_too_large)?;
549 if total_units > MAX_EXECUTABLE_SEARCH_PATHS_UNITS {
550 return Err(executable_search_path_too_large());
551 }
552
553 let mut seen = BTreeSet::new();
554 for path in paths {
555 if !seen.insert(path.as_os_str()) {
556 return Err(invalid_request(format!(
557 "duplicate executable search directory: {}",
558 path.display()
559 )));
560 }
561 }
562 Ok(joined)
563}
564
565fn join_executable_search_paths(paths: &[PathBuf]) -> Result<OsString, ExecutionError> {
566 std::env::join_paths(paths).map_err(|error| {
567 invalid_request(format!(
568 "executable search directory cannot be joined into PATH: {error}"
569 ))
570 })
571}
572
573fn executable_search_path_too_large() -> ExecutionError {
574 invalid_request(format!(
575 "executable search path exceeds {MAX_EXECUTABLE_SEARCH_PATHS_UNITS} bytes/code units"
576 ))
577}
578
579fn environment_block_too_large() -> ExecutionError {
580 invalid_request(format!(
581 "execution environment exceeds {MAX_ENVIRONMENT_BLOCK_UNITS} bytes/code units"
582 ))
583}
584
585fn invalid_request(message: impl Into<String>) -> ExecutionError {
586 ExecutionError::new(ExecutionErrorCategory::InvalidRequest, message)
587}
588
589#[cfg(any(windows, test))]
594pub(super) fn windows_command_line_units_upper_bound(
595 program_units: usize,
596 argument_units: impl IntoIterator<Item = usize>,
597) -> Option<usize> {
598 let mut units = program_units
599 .checked_mul(2)?
600 .checked_add(2)?
601 .checked_add(1)?;
602 for argument_units in argument_units {
603 units = units
604 .checked_add(1)?
605 .checked_add(argument_units.checked_mul(2)?.checked_add(2)?)?;
606 }
607 Some(units)
608}
609
610#[cfg(any(windows, test))]
611pub(super) fn validate_windows_command_line_units(
612 program_units: usize,
613 argument_units: impl IntoIterator<Item = usize>,
614) -> Result<(), ExecutionError> {
615 if windows_command_line_units_upper_bound(program_units, argument_units)
616 .is_none_or(|units| units > MAX_ARGV_UNITS)
617 {
618 return Err(invalid_request(format!(
619 "execution argv may exceed {MAX_ARGV_UNITS} UTF-16 code units after Windows command-line serialization"
620 )));
621 }
622 Ok(())
623}
624
625#[cfg(test)]
627pub(super) fn join_windows_path_units<'a>(
628 paths: impl IntoIterator<Item = &'a [u16]>,
629) -> Result<Vec<u16>, ()> {
630 const SEPARATOR: u16 = b';' as u16;
631 const QUOTE: u16 = b'"' as u16;
632 let mut joined = Vec::new();
633 for (index, path) in paths.into_iter().enumerate() {
634 if index != 0 {
635 joined.push(SEPARATOR);
636 }
637 if path.contains("E) {
638 return Err(());
639 }
640 if path.contains(&SEPARATOR) {
641 joined.push(QUOTE);
642 joined.extend_from_slice(path);
643 joined.push(QUOTE);
644 } else {
645 joined.extend_from_slice(path);
646 }
647 }
648 Ok(joined)
649}
650
651#[cfg(any(windows, test))]
652pub(super) fn windows_path_units_semantically_equal(left: &[u16], right: &[u16]) -> bool {
653 fn fold_ascii_case(unit: u16) -> u16 {
654 if unit >= u16::from(b'A') && unit <= u16::from(b'Z') {
655 unit + u16::from(b'a' - b'A')
656 } else {
657 unit
658 }
659 }
660
661 left.len() == right.len()
662 && left
663 .iter()
664 .zip(right)
665 .all(|(&left, &right)| fold_ascii_case(left) == fold_ascii_case(right))
666}
667
668fn validate_os_value(kind: &str, value: &OsStr, maximum: usize) -> Result<usize, ExecutionError> {
669 validate_platform_representation(kind, value)?;
670 let units = os_units(value);
671 if os_contains_nul(value) {
672 return Err(invalid_request(format!("{kind} contains an embedded NUL")));
673 }
674 if units > maximum {
675 return Err(invalid_request(format!(
676 "{kind} exceeds {maximum} bytes/code units"
677 )));
678 }
679 Ok(units)
680}
681
682#[cfg(any(unix, windows))]
683fn validate_platform_representation(_kind: &str, _value: &OsStr) -> Result<(), ExecutionError> {
684 Ok(())
685}
686
687#[cfg(not(any(unix, windows)))]
688fn validate_platform_representation(kind: &str, value: &OsStr) -> Result<(), ExecutionError> {
689 if value.to_str().is_none() {
690 return Err(invalid_request(format!(
691 "{kind} cannot be represented on this platform"
692 )));
693 }
694 Ok(())
695}
696
697#[cfg(unix)]
698pub(super) fn os_units(value: &OsStr) -> usize {
699 use std::os::unix::ffi::OsStrExt;
700 value.as_bytes().len()
701}
702
703#[cfg(unix)]
704fn os_contains_nul(value: &OsStr) -> bool {
705 use std::os::unix::ffi::OsStrExt;
706 value.as_bytes().contains(&0)
707}
708
709#[cfg(windows)]
710pub(super) fn os_units(value: &OsStr) -> usize {
711 use std::os::windows::ffi::OsStrExt;
712 value.encode_wide().count()
713}
714
715#[cfg(windows)]
716fn os_contains_nul(value: &OsStr) -> bool {
717 use std::os::windows::ffi::OsStrExt;
718 value.encode_wide().any(|unit| unit == 0)
719}
720
721#[cfg(not(any(unix, windows)))]
722pub(super) fn os_units(value: &OsStr) -> usize {
723 value.to_string_lossy().len()
724}
725
726#[cfg(not(any(unix, windows)))]
727fn os_contains_nul(value: &OsStr) -> bool {
728 value.to_string_lossy().contains('\0')
729}