Skip to main content

tapid_runner/execution/
request.rs

1//! Validated execution requests, runtime identity, and platform argument/environment limits.
2
3use 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    // SAFETY: `file` keeps a valid owned handle alive for the call and `information` points to
17    // writable storage of the exact structure required by `GetFileInformationByHandle`.
18    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    // SAFETY: a successful API call initialized the complete output structure.
29    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/// Canonical trusted Node executable with its native file identity captured at construction.
36#[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 &current != 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/// Platform-neutral, validated request passed to a private execution backend.
136///
137/// Search paths remain private adapter input: external callers can add them only through the
138/// checked builder and cannot replace validated paths after construction.
139///
140/// ```compile_fail
141/// use tapid_runner::ExecutionRequest;
142/// let request = ExecutionRequest::builder("node")
143///     .executable_search_path("/runtime/bin")
144///     .build()
145///     .unwrap();
146/// let _ = request.executable_search_paths();
147/// ```
148#[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) working_directory: Option<PathBuf>,
161    pub(super) policy: SandboxPolicy,
162    pub(super) environment: BTreeMap<OsString, OsString>,
163}
164
165impl ExecutionRequest {
166    pub fn builder(program: impl Into<OsString>) -> ExecutionRequestBuilder {
167        ExecutionRequestBuilder {
168            program: program.into(),
169            arguments: Vec::new(),
170            executable_search_paths: Vec::new(),
171            trusted_node_runtime: None,
172            windows_verbatim_arguments: false,
173            allow_process_memory_stats: false,
174            project_root: PathBuf::from("."),
175            working_directory: None,
176            policy: SandboxPolicy::default(),
177            environment: BTreeMap::new(),
178        }
179    }
180
181    pub fn program(&self) -> &OsStr {
182        &self.program
183    }
184    pub fn arguments(&self) -> &[OsString] {
185        &self.arguments
186    }
187    /// Whether a Windows adapter must pass arguments without MSVCRT re-quoting.
188    pub fn uses_windows_verbatim_arguments(&self) -> bool {
189        self.windows_verbatim_arguments
190    }
191    /// Ordered executable search directories for private platform adapters.
192    pub(super) fn executable_search_paths(&self) -> &[PathBuf] {
193        &self.executable_search_paths
194    }
195    #[cfg(all(test, unix))]
196    pub(super) fn trusted_node_runtime(&self) -> &Path {
197        self.trusted_node_runtime
198            .as_ref()
199            .expect("trusted Node runtime was requested")
200            .path
201            .as_path()
202    }
203    pub(super) fn validate_trusted_node_runtime(&self) -> Result<(), ExecutionError> {
204        #[cfg(target_os = "macos")]
205        if let Some(binding) = &self.reserved_node {
206            return binding.validate();
207        }
208        if let Some(runtime) = &self.trusted_node_runtime {
209            runtime.validate(&self.executable_search_paths)?;
210        }
211        Ok(())
212    }
213    pub fn project_root(&self) -> &Path {
214        &self.project_root
215    }
216    /// Directory used as the child process working directory, confined beneath `project_root`.
217    pub fn working_directory(&self) -> &Path {
218        self.working_directory
219            .as_deref()
220            .unwrap_or(&self.project_root)
221    }
222    pub fn policy(&self) -> &SandboxPolicy {
223        &self.policy
224    }
225
226    /// Whether the caller explicitly requested process-memory statistics through isolated procfs.
227    pub fn allow_process_memory_stats(&self) -> bool {
228        self.allow_process_memory_stats
229    }
230
231    #[cfg(target_os = "linux")]
232    pub(crate) fn private_launcher_executable(&self) -> Option<&Path> {
233        self.launcher
234            .as_ref()
235            .and_then(|launcher| launcher.executable.as_deref())
236    }
237
238    /// Explicit caller-provided environment.
239    ///
240    /// This does not expose the mandatory adapter-owned `PATH`. Private adapters receive the
241    /// explicit entries plus `PATH` serialized from the ordered executable-search directories;
242    /// an empty directory list produces an explicitly empty `PATH`.
243    pub fn environment(&self) -> &BTreeMap<OsString, OsString> {
244        &self.environment
245    }
246
247    /// Complete adapter-owned child environment, including a controlled `PATH` entry.
248    pub(super) fn child_environment(&self) -> BTreeMap<OsString, OsString> {
249        let mut environment = self.environment.clone();
250        let path = join_executable_search_paths(&self.executable_search_paths)
251            .expect("validated executable search paths must remain joinable");
252        environment.insert(OsString::from("PATH"), path);
253        environment
254    }
255
256    pub(super) fn validate_windows_verbatim_boundary(&self) -> Result<(), ExecutionError> {
257        if !self.windows_verbatim_arguments {
258            return Ok(());
259        }
260        let is_cmd = Path::new(&self.program)
261            .file_name()
262            .and_then(OsStr::to_str)
263            .is_some_and(|name| {
264                name.eq_ignore_ascii_case("cmd") || name.eq_ignore_ascii_case("cmd.exe")
265            });
266        if !is_cmd
267            || self.arguments.len() != 4
268            || self.arguments[0] != OsStr::new("/D")
269            || self.arguments[1] != OsStr::new("/S")
270            || self.arguments[2] != OsStr::new("/C")
271        {
272            return Err(invalid_request(
273                "Windows verbatim arguments require cmd.exe /D /S /C plus one command payload",
274            ));
275        }
276        let payload = self.arguments[3].to_str().ok_or_else(|| {
277            invalid_request("Windows verbatim command payload must be valid Unicode")
278        })?;
279        if payload.contains(['\r', '\n']) {
280            return Err(invalid_request(
281                "Windows verbatim command payload cannot contain CR or LF",
282            ));
283        }
284        Ok(())
285    }
286
287    pub(super) fn validate(&self) -> Result<(), ExecutionError> {
288        self.validate_windows_verbatim_boundary()?;
289        #[cfg(not(target_os = "linux"))]
290        if self.allow_process_memory_stats {
291            return Err(invalid_request(
292                "process memory statistics opt-in is supported only by Linux containment backends",
293            ));
294        }
295        #[cfg(target_os = "linux")]
296        if self.allow_process_memory_stats
297            && (self.policy.mode() != SandboxMode::Required
298                || !matches!(
299                    self.policy.assurance(),
300                    AssuranceLevel::Restricted | AssuranceLevel::ManagedTree
301                ))
302        {
303            return Err(invalid_request(
304                "process memory statistics opt-in requires required sandbox mode and Linux Restricted or ManagedTree assurance",
305            ));
306        }
307        #[cfg(target_os = "linux")]
308        if self.allow_process_memory_stats && self.private_launcher_executable().is_none() {
309            return Err(invalid_request(
310                "process memory statistics opt-in requires early private-launcher initialization",
311            ));
312        }
313        let program_units =
314            validate_os_value("execution program", &self.program, MAX_PROGRAM_UNITS)?;
315        if self.program.is_empty() {
316            return Err(invalid_request("execution program must not be empty"));
317        }
318        if self.arguments.len() > MAX_ARGUMENT_COUNT {
319            return Err(invalid_request(format!(
320                "execution request exceeds {MAX_ARGUMENT_COUNT} arguments"
321            )));
322        }
323        #[cfg(windows)]
324        let mut argument_units = Vec::with_capacity(self.arguments.len());
325        #[cfg(not(windows))]
326        let mut argv_units = program_units.saturating_add(1);
327        for argument in &self.arguments {
328            let units = validate_os_value("execution argument", argument, MAX_ARGUMENT_UNITS)?;
329            #[cfg(windows)]
330            argument_units.push(units);
331            #[cfg(not(windows))]
332            {
333                argv_units = argv_units.saturating_add(units).saturating_add(1);
334            }
335        }
336        #[cfg(windows)]
337        {
338            validate_windows_command_line_units(program_units, argument_units.iter().copied())?;
339            use std::os::windows::ffi::OsStrExt;
340            let program = self.program.encode_wide().collect::<Vec<_>>();
341            let arguments = self
342                .arguments
343                .iter()
344                .map(|argument| argument.encode_wide().collect::<Vec<_>>())
345                .collect::<Vec<_>>();
346            serialize_windows_command_line_units(
347                &program,
348                &arguments,
349                self.windows_verbatim_arguments,
350            )?;
351        }
352        #[cfg(not(windows))]
353        if argv_units > MAX_ARGV_UNITS {
354            return Err(invalid_request(format!(
355                "execution argv exceeds {MAX_ARGV_UNITS} bytes/code units"
356            )));
357        }
358        validate_os_value(
359            "project root",
360            self.project_root.as_os_str(),
361            MAX_PROJECT_ROOT_UNITS,
362        )?;
363        if self.project_root.as_os_str().is_empty() {
364            return Err(invalid_request("project root must not be empty"));
365        }
366        if let Some(working_directory) = &self.working_directory {
367            validate_os_value(
368                "working directory",
369                working_directory.as_os_str(),
370                MAX_PROJECT_ROOT_UNITS,
371            )?;
372            if working_directory.as_os_str().is_empty() {
373                return Err(invalid_request("working directory must not be empty"));
374            }
375            let canonical_root = canonical_path(&self.project_root, "project root")?;
376            let canonical_working_directory =
377                canonical_path(working_directory, "working directory")?;
378            if canonical_root != self.project_root
379                || canonical_working_directory != *working_directory
380                || !canonical_working_directory.starts_with(&canonical_root)
381                || !canonical_working_directory.is_dir()
382            {
383                return Err(invalid_request(
384                    "working directory must be canonical, existing, and contained beneath project root",
385                ));
386            }
387        }
388        let executable_search_path =
389            validate_executable_search_paths(&self.executable_search_paths)?;
390        self.validate_trusted_node_runtime()?;
391        // The complete block always contains PATH=<joined paths>\0 followed by the block's final
392        // terminator. An empty path list therefore still contributes `PATH=\0\0`.
393        let mut environment_units = 1usize
394            .checked_add(os_units(OsStr::new("PATH")))
395            .and_then(|units| units.checked_add(os_units(&executable_search_path)))
396            .and_then(|units| units.checked_add(2))
397            .ok_or_else(environment_block_too_large)?;
398        if environment_units > MAX_ENVIRONMENT_BLOCK_UNITS {
399            return Err(environment_block_too_large());
400        }
401        for (name, value) in &self.environment {
402            let Some(name) = name.to_str() else {
403                return Err(invalid_request(
404                    "environment variable names must be valid UTF-8",
405                ));
406            };
407            if name.eq_ignore_ascii_case("PATH") {
408                return Err(invalid_request(
409                    "caller-controlled PATH is forbidden; containment backends own executable search paths",
410                ));
411            }
412            if validate_environment_name(name).is_err() {
413                return Err(invalid_request(format!(
414                    "invalid environment variable name: {name:?}"
415                )));
416            }
417            let name_units = os_units(name.as_ref());
418            let value_units = validate_os_value(
419                "environment variable value",
420                value,
421                MAX_ENVIRONMENT_VALUE_UNITS,
422            )?;
423            environment_units = environment_units
424                .checked_add(name_units)
425                .and_then(|units| units.checked_add(value_units))
426                .and_then(|units| units.checked_add(2))
427                .ok_or_else(environment_block_too_large)?;
428            if environment_units > MAX_ENVIRONMENT_BLOCK_UNITS {
429                return Err(environment_block_too_large());
430            }
431            if !self
432                .policy
433                .environment()
434                .iter()
435                .any(|allowed| allowed == name)
436            {
437                return Err(invalid_request(format!(
438                    "environment variable is not allowlisted by policy: {name}"
439                )));
440            }
441        }
442        #[cfg(windows)]
443        windows_environment_block_units(&self.child_environment())?;
444        Ok(())
445    }
446}
447
448/// Builder for an [`ExecutionRequest`].
449#[derive(Clone, Debug)]
450pub struct ExecutionRequestBuilder {
451    program: OsString,
452    arguments: Vec<OsString>,
453    executable_search_paths: Vec<PathBuf>,
454    trusted_node_runtime: Option<PathBuf>,
455    windows_verbatim_arguments: bool,
456    allow_process_memory_stats: bool,
457    project_root: PathBuf,
458    working_directory: Option<PathBuf>,
459    policy: SandboxPolicy,
460    environment: BTreeMap<OsString, OsString>,
461}
462
463impl ExecutionRequestBuilder {
464    pub fn arg(mut self, argument: impl Into<OsString>) -> Self {
465        self.arguments.push(argument.into());
466        self
467    }
468
469    pub fn args<I, S>(mut self, arguments: I) -> Self
470    where
471        I: IntoIterator<Item = S>,
472        S: Into<OsString>,
473    {
474        self.arguments.extend(arguments.into_iter().map(Into::into));
475        self
476    }
477
478    /// Adds one executable search directory after existing entries.
479    ///
480    /// [`Self::build`] rejects entries that the target platform's [`std::env::join_paths`] cannot
481    /// serialize, exact duplicates, and requests whose complete child environment (including the
482    /// resulting mandatory `PATH`) exceeds [`MAX_ENVIRONMENT_BLOCK_UNITS`].
483    pub fn executable_search_path(mut self, path: impl Into<PathBuf>) -> Self {
484        self.executable_search_paths.push(path.into());
485        self
486    }
487
488    /// Binds the exact canonical Node executable to the first child PATH directory.
489    pub fn trusted_node_runtime(mut self, path: impl Into<PathBuf>) -> Self {
490        self.trusted_node_runtime = Some(path.into());
491        self
492    }
493
494    /// Requires the Windows adapter to use `CommandExt::raw_arg` or an equivalent verbatim seam.
495    pub fn windows_verbatim_arguments(mut self, enabled: bool) -> Self {
496        self.windows_verbatim_arguments = enabled;
497        self
498    }
499
500    /// Enables read-only procfs access inside a private PID/mount namespace for this process and its descendants.
501    pub fn allow_process_memory_stats(mut self, enabled: bool) -> Self {
502        self.allow_process_memory_stats = enabled;
503        self
504    }
505
506    /// Adds ordered executable search directories without consulting ambient `PATH`.
507    ///
508    /// [`Self::build`] validates every entry's representation and size before duplicate checks,
509    /// then applies the target platform's exact [`std::env::join_paths`] serialization rules.
510    pub fn executable_search_paths<I, P>(mut self, paths: I) -> Self
511    where
512        I: IntoIterator<Item = P>,
513        P: Into<PathBuf>,
514    {
515        self.executable_search_paths
516            .extend(paths.into_iter().map(Into::into));
517        self
518    }
519
520    pub fn project_root(mut self, project_root: impl Into<PathBuf>) -> Self {
521        self.project_root = project_root.into();
522        self
523    }
524
525    /// Sets the child process working directory, which must resolve inside `project_root`.
526    pub fn working_directory(mut self, working_directory: impl Into<PathBuf>) -> Self {
527        self.working_directory = Some(working_directory.into());
528        self
529    }
530
531    pub fn policy(mut self, policy: SandboxPolicy) -> Self {
532        self.policy = policy;
533        self
534    }
535
536    /// Adds one explicit child environment value.
537    pub fn env(mut self, name: impl Into<OsString>, value: impl Into<OsString>) -> Self {
538        self.environment.insert(name.into(), value.into());
539        self
540    }
541
542    /// Adds explicit child environment values without reading the ambient environment.
543    pub fn envs<I, K, V>(mut self, environment: I) -> Self
544    where
545        I: IntoIterator<Item = (K, V)>,
546        K: Into<OsString>,
547        V: Into<OsString>,
548    {
549        self.environment.extend(
550            environment
551                .into_iter()
552                .map(|(name, value)| (name.into(), value.into())),
553        );
554        self
555    }
556
557    pub fn build(self) -> Result<ExecutionRequest, ExecutionError> {
558        let working_directory = self
559            .working_directory
560            .as_ref()
561            .map(|working_directory| {
562                let project_root = fs::canonicalize(&self.project_root)
563                    .map_err(|error| path_error("project root", &self.project_root, error))?;
564                if !project_root.is_dir() {
565                    return Err(invalid_request(
566                        "project root must be an existing directory",
567                    ));
568                }
569                let working_path = if working_directory.is_absolute() {
570                    working_directory.clone()
571                } else {
572                    project_root.join(working_directory)
573                };
574                let working_directory = fs::canonicalize(&working_path)
575                    .map_err(|error| path_error("working directory", &working_path, error))?;
576                if !working_directory.is_dir() || !working_directory.starts_with(&project_root) {
577                    return Err(invalid_request(
578                        "working directory must be an existing directory beneath project root",
579                    ));
580                }
581                Ok(working_directory)
582            })
583            .transpose()?;
584        let trusted_node_runtime = self
585            .trusted_node_runtime
586            .as_deref()
587            .map(TrustedNodeRuntime::checked)
588            .transpose()?;
589        let request = ExecutionRequest {
590            #[cfg(target_os = "macos")]
591            reserved_node: None,
592            launcher: crate::LAUNCHER.get().cloned(),
593            program: self.program,
594            arguments: self.arguments,
595            executable_search_paths: self.executable_search_paths,
596            trusted_node_runtime,
597            windows_verbatim_arguments: self.windows_verbatim_arguments,
598            allow_process_memory_stats: self.allow_process_memory_stats,
599            project_root: self.project_root,
600            working_directory,
601            policy: self.policy,
602            environment: self.environment,
603        };
604        request.validate()?;
605        Ok(request)
606    }
607}
608
609pub(super) fn validate_executable_search_paths(
610    paths: &[PathBuf],
611) -> Result<OsString, ExecutionError> {
612    if paths.len() > MAX_EXECUTABLE_SEARCH_PATH_COUNT {
613        return Err(invalid_request(format!(
614            "execution request exceeds {MAX_EXECUTABLE_SEARCH_PATH_COUNT} executable search directories"
615        )));
616    }
617
618    // Bound and validate every value before any duplicate comparison. This keeps comparisons over
619    // attacker-controlled native strings bounded even when an earlier value is repeated.
620    for path in paths {
621        validate_os_value(
622            "executable search directory",
623            path.as_os_str(),
624            MAX_EXECUTABLE_SEARCH_PATH_UNITS,
625        )?;
626    }
627
628    let joined = join_executable_search_paths(paths)?;
629    let total_units = os_units(&joined)
630        .checked_add(1)
631        .ok_or_else(executable_search_path_too_large)?;
632    if total_units > MAX_EXECUTABLE_SEARCH_PATHS_UNITS {
633        return Err(executable_search_path_too_large());
634    }
635
636    let mut seen = BTreeSet::new();
637    for path in paths {
638        if !seen.insert(path.as_os_str()) {
639            return Err(invalid_request(format!(
640                "duplicate executable search directory: {}",
641                path.display()
642            )));
643        }
644    }
645    Ok(joined)
646}
647
648pub(super) fn join_executable_search_paths(paths: &[PathBuf]) -> Result<OsString, ExecutionError> {
649    let paths = {
650        #[cfg(windows)]
651        {
652            use std::os::windows::ffi::{OsStrExt, OsStringExt};
653            paths
654                .iter()
655                .map(|path| {
656                    let units = path.as_os_str().encode_wide().collect::<Vec<_>>();
657                    PathBuf::from(OsString::from_wide(&windows_environment_path_units(&units)))
658                })
659                .collect::<Vec<_>>()
660        }
661        #[cfg(not(windows))]
662        {
663            paths.to_vec()
664        }
665    };
666    std::env::join_paths(paths).map_err(|error| {
667        invalid_request(format!(
668            "executable search directory cannot be joined into PATH: {error}"
669        ))
670    })
671}
672
673fn executable_search_path_too_large() -> ExecutionError {
674    invalid_request(format!(
675        "executable search path exceeds {MAX_EXECUTABLE_SEARCH_PATHS_UNITS} bytes/code units"
676    ))
677}
678
679fn environment_block_too_large() -> ExecutionError {
680    invalid_request(format!(
681        "execution environment exceeds {MAX_ENVIRONMENT_BLOCK_UNITS} bytes/code units"
682    ))
683}
684
685fn invalid_request(message: impl Into<String>) -> ExecutionError {
686    ExecutionError::new(ExecutionErrorCategory::InvalidRequest, message)
687}
688
689#[cfg(any(windows, test))]
690pub(super) fn serialize_windows_command_line_units(
691    program: &[u16],
692    arguments: &[Vec<u16>],
693    verbatim_last: bool,
694) -> Result<Vec<u16>, ExecutionError> {
695    if program.is_empty() || program.contains(&0) || arguments.iter().any(|arg| arg.contains(&0)) {
696        return Err(invalid_request(
697            "Windows command line contains an empty program or embedded NUL",
698        ));
699    }
700    if verbatim_last && arguments.is_empty() {
701        return Err(invalid_request(
702            "Windows verbatim command line requires a final command payload",
703        ));
704    }
705
706    fn quote(argument: &[u16], output: &mut Vec<u16>) {
707        let slash = u16::from(b'\\');
708        let quote = u16::from(b'"');
709        output.push(quote);
710        let mut backslashes = 0usize;
711        for &unit in argument {
712            if unit == slash {
713                backslashes += 1;
714            } else if unit == quote {
715                output.extend(std::iter::repeat_n(slash, backslashes * 2 + 1));
716                output.push(quote);
717                backslashes = 0;
718            } else {
719                output.extend(std::iter::repeat_n(slash, backslashes));
720                output.push(unit);
721                backslashes = 0;
722            }
723        }
724        output.extend(std::iter::repeat_n(slash, backslashes * 2));
725        output.push(quote);
726    }
727
728    let mut command_line = Vec::new();
729    quote(program, &mut command_line);
730    for argument in arguments {
731        command_line.push(u16::from(b' '));
732        if verbatim_last {
733            // The checked verbatim boundary permits only /D /S /C and one
734            // command payload. cmd.exe parses its own command line: quoting
735            // these switches changes how it finds and strips payload quotes.
736            command_line.extend_from_slice(argument);
737        } else {
738            quote(argument, &mut command_line);
739        }
740    }
741    command_line.push(0);
742    if command_line.len() > MAX_ARGV_UNITS {
743        return Err(invalid_request(format!(
744            "serialized Windows command line exceeds {MAX_ARGV_UNITS} UTF-16 code units"
745        )));
746    }
747    Ok(command_line)
748}
749
750/// Returns a conservative upper bound rather than the exact Windows command-line serialization.
751/// The program and every argument are assumed to need surrounding quotes, and every input code
752/// unit is budgeted to double under worst-case quote/backslash escaping. Separators and the
753/// mandatory terminating NUL are counted separately.
754#[cfg(any(windows, test))]
755pub(super) fn windows_command_line_units_upper_bound(
756    program_units: usize,
757    argument_units: impl IntoIterator<Item = usize>,
758) -> Option<usize> {
759    let mut units = program_units
760        .checked_mul(2)?
761        .checked_add(2)?
762        .checked_add(1)?;
763    for argument_units in argument_units {
764        units = units
765            .checked_add(1)?
766            .checked_add(argument_units.checked_mul(2)?.checked_add(2)?)?;
767    }
768    Some(units)
769}
770
771#[cfg(any(windows, test))]
772pub(super) fn validate_windows_command_line_units(
773    program_units: usize,
774    argument_units: impl IntoIterator<Item = usize>,
775) -> Result<(), ExecutionError> {
776    if windows_command_line_units_upper_bound(program_units, argument_units)
777        .is_none_or(|units| units > MAX_ARGV_UNITS)
778    {
779        return Err(invalid_request(format!(
780            "execution argv may exceed {MAX_ARGV_UNITS} UTF-16 code units after Windows command-line serialization"
781        )));
782    }
783    Ok(())
784}
785
786#[cfg(any(windows, test))]
787pub(super) fn windows_environment_block_units(
788    environment: &BTreeMap<OsString, OsString>,
789) -> Result<Vec<u16>, ExecutionError> {
790    let mut entries = Vec::with_capacity(environment.len());
791    for (name, value) in environment {
792        let name = name.to_str().ok_or_else(|| {
793            invalid_request("Windows environment variable names must be valid UTF-8")
794        })?;
795        validate_environment_name(name).map_err(|error| invalid_request(error.to_string()))?;
796        let name_units = name.encode_utf16().collect::<Vec<_>>();
797        let value_units = {
798            #[cfg(windows)]
799            {
800                use std::os::windows::ffi::OsStrExt;
801                value.encode_wide().collect::<Vec<_>>()
802            }
803            #[cfg(not(windows))]
804            {
805                value.to_string_lossy().encode_utf16().collect::<Vec<_>>()
806            }
807        };
808        entries.push((name_units, value_units));
809    }
810    #[cfg(windows)]
811    {
812        use std::os::windows::ffi::OsStrExt;
813        let local_app_data = std::env::var_os("LOCALAPPDATA").ok_or_else(|| {
814            ExecutionError::new(
815                ExecutionErrorCategory::UnsupportedContainment,
816                "Windows AppContainer launch requires the runner's LOCALAPPDATA environment variable",
817            )
818        })?;
819        let system_root = std::env::var_os("SystemRoot").ok_or_else(|| {
820            ExecutionError::new(
821                ExecutionErrorCategory::UnsupportedContainment,
822                "Windows AppContainer launch requires the runner's SystemRoot environment variable",
823            )
824        })?;
825        let local_app_data_units = local_app_data.encode_wide().collect::<Vec<_>>();
826        let system_root_units = system_root.encode_wide().collect::<Vec<_>>();
827        entries = windows_appcontainer_environment_entries(
828            entries,
829            &local_app_data_units,
830            &system_root_units,
831        );
832    }
833    assemble_windows_environment_block(entries)
834}
835
836#[cfg(any(windows, test))]
837pub(super) fn windows_appcontainer_environment_entries(
838    mut entries: Vec<(Vec<u16>, Vec<u16>)>,
839    host_local_app_data: &[u16],
840    host_system_root: &[u16],
841) -> Vec<(Vec<u16>, Vec<u16>)> {
842    for (name, value) in [
843        ("LOCALAPPDATA", host_local_app_data),
844        ("SYSTEMROOT", host_system_root),
845    ] {
846        let required_name = name.encode_utf16().collect::<Vec<_>>();
847        entries
848            .retain(|(candidate, _)| !windows_environment_names_equal(candidate, &required_name));
849        entries.push((required_name, value.to_vec()));
850    }
851    entries
852}
853
854#[cfg(any(windows, test))]
855fn windows_environment_names_equal(left: &[u16], right: &[u16]) -> bool {
856    fn fold_ascii_case(unit: u16) -> u16 {
857        if (u16::from(b'A')..=u16::from(b'Z')).contains(&unit) {
858            unit + u16::from(b'a' - b'A')
859        } else {
860            unit
861        }
862    }
863    left.len() == right.len()
864        && left
865            .iter()
866            .zip(right)
867            .all(|(&left, &right)| fold_ascii_case(left) == fold_ascii_case(right))
868}
869
870#[cfg(any(windows, test))]
871pub(super) fn assemble_windows_environment_block(
872    mut entries: Vec<(Vec<u16>, Vec<u16>)>,
873) -> Result<Vec<u16>, ExecutionError> {
874    fn fold_ascii_case(unit: u16) -> u16 {
875        if (u16::from(b'A')..=u16::from(b'Z')).contains(&unit) {
876            unit + u16::from(b'a' - b'A')
877        } else {
878            unit
879        }
880    }
881    fn compare_names(left: &[u16], right: &[u16]) -> std::cmp::Ordering {
882        left.iter()
883            .map(|unit| fold_ascii_case(*unit))
884            .cmp(right.iter().map(|unit| fold_ascii_case(*unit)))
885    }
886
887    for (name, value) in &entries {
888        if name.is_empty()
889            || name
890                .iter()
891                .any(|unit| *unit == 0 || *unit == u16::from(b'='))
892        {
893            return Err(invalid_request("invalid Windows environment variable name"));
894        }
895        if value.contains(&0) {
896            return Err(invalid_request(
897                "Windows environment value contains an embedded NUL",
898            ));
899        }
900    }
901    entries.sort_by(|left, right| compare_names(&left.0, &right.0));
902    if entries
903        .windows(2)
904        .any(|pair| compare_names(&pair[0].0, &pair[1].0).is_eq())
905    {
906        return Err(invalid_request(
907            "Windows environment contains case-insensitive duplicate names",
908        ));
909    }
910    let mut units: usize = if entries.is_empty() { 2 } else { 1 };
911    for (name, value) in &entries {
912        units = units
913            .checked_add(name.len())
914            .and_then(|count| count.checked_add(1))
915            .and_then(|count| count.checked_add(value.len()))
916            .and_then(|count| count.checked_add(1))
917            .ok_or_else(environment_block_too_large)?;
918    }
919    if units > MAX_ENVIRONMENT_BLOCK_UNITS {
920        return Err(environment_block_too_large());
921    }
922    if entries.is_empty() {
923        return Ok(vec![0, 0]);
924    }
925
926    let mut block = Vec::with_capacity(units);
927    for (name, value) in entries {
928        block.extend(name);
929        block.push(u16::from(b'='));
930        block.extend(value);
931        block.push(0);
932    }
933    block.push(0);
934    Ok(block)
935}
936
937/// Mirrors `std::env::join_paths` on Windows so its separator quoting remains host-testable.
938#[cfg(test)]
939pub(super) fn join_windows_path_units<'a>(
940    paths: impl IntoIterator<Item = &'a [u16]>,
941) -> Result<Vec<u16>, ()> {
942    const SEPARATOR: u16 = b';' as u16;
943    const QUOTE: u16 = b'"' as u16;
944    let mut joined = Vec::new();
945    for (index, path) in paths.into_iter().enumerate() {
946        if index != 0 {
947            joined.push(SEPARATOR);
948        }
949        if path.contains(&QUOTE) {
950            return Err(());
951        }
952        if path.contains(&SEPARATOR) {
953            joined.push(QUOTE);
954            joined.extend_from_slice(path);
955            joined.push(QUOTE);
956        } else {
957            joined.extend_from_slice(path);
958        }
959    }
960    Ok(joined)
961}
962
963#[cfg(any(windows, test))]
964pub(super) fn windows_environment_path_units(path: &[u16]) -> Vec<u16> {
965    const EXTENDED_PREFIX: [u16; 4] = [92, 92, 63, 92];
966    const EXTENDED_UNC_PREFIX: [u16; 8] = [92, 92, 63, 92, 85, 78, 67, 92];
967    if path.starts_with(&EXTENDED_UNC_PREFIX) {
968        let mut ordinary = vec![92, 92];
969        ordinary.extend_from_slice(&path[EXTENDED_UNC_PREFIX.len()..]);
970        ordinary
971    } else if path.starts_with(&EXTENDED_PREFIX) {
972        path[EXTENDED_PREFIX.len()..].to_vec()
973    } else {
974        path.to_vec()
975    }
976}
977
978#[cfg(any(windows, test))]
979pub(super) fn windows_path_units_semantically_equal(left: &[u16], right: &[u16]) -> bool {
980    fn fold_ascii_case(unit: u16) -> u16 {
981        if unit >= u16::from(b'A') && unit <= u16::from(b'Z') {
982            unit + u16::from(b'a' - b'A')
983        } else {
984            unit
985        }
986    }
987
988    left.len() == right.len()
989        && left
990            .iter()
991            .zip(right)
992            .all(|(&left, &right)| fold_ascii_case(left) == fold_ascii_case(right))
993}
994
995fn validate_os_value(kind: &str, value: &OsStr, maximum: usize) -> Result<usize, ExecutionError> {
996    validate_platform_representation(kind, value)?;
997    let units = os_units(value);
998    if os_contains_nul(value) {
999        return Err(invalid_request(format!("{kind} contains an embedded NUL")));
1000    }
1001    if units > maximum {
1002        return Err(invalid_request(format!(
1003            "{kind} exceeds {maximum} bytes/code units"
1004        )));
1005    }
1006    Ok(units)
1007}
1008
1009#[cfg(any(unix, windows))]
1010fn validate_platform_representation(_kind: &str, _value: &OsStr) -> Result<(), ExecutionError> {
1011    Ok(())
1012}
1013
1014#[cfg(not(any(unix, windows)))]
1015fn validate_platform_representation(kind: &str, value: &OsStr) -> Result<(), ExecutionError> {
1016    if value.to_str().is_none() {
1017        return Err(invalid_request(format!(
1018            "{kind} cannot be represented on this platform"
1019        )));
1020    }
1021    Ok(())
1022}
1023
1024#[cfg(unix)]
1025pub(super) fn os_units(value: &OsStr) -> usize {
1026    use std::os::unix::ffi::OsStrExt;
1027    value.as_bytes().len()
1028}
1029
1030#[cfg(unix)]
1031fn os_contains_nul(value: &OsStr) -> bool {
1032    use std::os::unix::ffi::OsStrExt;
1033    value.as_bytes().contains(&0)
1034}
1035
1036#[cfg(windows)]
1037pub(super) fn os_units(value: &OsStr) -> usize {
1038    use std::os::windows::ffi::OsStrExt;
1039    value.encode_wide().count()
1040}
1041
1042#[cfg(windows)]
1043fn os_contains_nul(value: &OsStr) -> bool {
1044    use std::os::windows::ffi::OsStrExt;
1045    value.encode_wide().any(|unit| unit == 0)
1046}
1047
1048#[cfg(not(any(unix, windows)))]
1049pub(super) fn os_units(value: &OsStr) -> usize {
1050    value.to_string_lossy().len()
1051}
1052
1053#[cfg(not(any(unix, windows)))]
1054fn os_contains_nul(value: &OsStr) -> bool {
1055    value.to_string_lossy().contains('\0')
1056}