Skip to main content

tapid_runner/
execution.rs

1mod request;
2#[cfg(target_os = "macos")]
3use request::TrustedNodeRuntime;
4#[cfg(any(windows, test))]
5use request::windows_path_units_semantically_equal;
6pub use request::{ExecutionRequest, ExecutionRequestBuilder};
7#[cfg(test)]
8use request::{
9    assemble_windows_environment_block, join_executable_search_paths,
10    windows_appcontainer_environment_entries, windows_environment_path_units,
11};
12#[cfg(test)]
13use request::{
14    join_windows_path_units, os_units, validate_executable_search_paths,
15    validate_windows_command_line_units, windows_command_line_units_upper_bound,
16};
17#[cfg(any(windows, test))]
18use request::{serialize_windows_command_line_units, windows_environment_block_units};
19
20mod supervision;
21#[cfg(any(target_os = "macos", target_os = "linux", windows, test))]
22use supervision::ExecutionLifecycle;
23use supervision::{
24    ExecutionBackend, OwnedExecutionAttempt, PreparationError, execute_with_backend,
25};
26
27use crate::config::{
28    AssuranceLevel, ExecutionLimits, SandboxMode, SandboxPolicy, validate_environment_name,
29};
30use std::collections::{BTreeMap, BTreeSet};
31use std::ffi::{OsStr, OsString};
32use std::fmt;
33use std::fs;
34use std::path::{Path, PathBuf};
35
36/// Maximum UTF-8 byte length of each backend identity field.
37pub const MAX_BACKEND_IDENTITY_BYTES: usize = 255;
38/// Maximum program length in bytes on Unix or UTF-16 code units on Windows.
39pub const MAX_PROGRAM_UNITS: usize = 4_096;
40/// Maximum number of arguments, excluding the program.
41pub const MAX_ARGUMENT_COUNT: usize = 4_096;
42/// Maximum argument length in bytes on Unix or UTF-16 code units on Windows.
43pub const MAX_ARGUMENT_UNITS: usize = 16_384;
44/// Maximum cumulative argv payload. On Windows this bounds a conservative upper estimate of the
45/// serialized `CreateProcessW` command line, including quoting, separators, and its terminating NUL.
46pub const MAX_ARGV_UNITS: usize = 32_767;
47/// Maximum environment value length in bytes on Unix or UTF-16 code units on Windows.
48pub const MAX_ENVIRONMENT_VALUE_UNITS: usize = 32_767;
49/// Maximum cumulative child environment block, including separators and terminators.
50pub const MAX_ENVIRONMENT_BLOCK_UNITS: usize = 32_767;
51/// Maximum project-root length in bytes on Unix or UTF-16 code units on Windows.
52pub const MAX_PROJECT_ROOT_UNITS: usize = 32_767;
53/// Maximum number of explicit executable search directories.
54pub const MAX_EXECUTABLE_SEARCH_PATH_COUNT: usize = 256;
55/// Maximum length of one executable search directory in native platform units.
56pub const MAX_EXECUTABLE_SEARCH_PATH_UNITS: usize = 4_096;
57/// Maximum serialized executable search path, including separators and its terminating NUL.
58pub const MAX_EXECUTABLE_SEARCH_PATHS_UNITS: usize = 32_767;
59
60/// Identity and lifecycle status of a containment backend.
61#[derive(Clone, Debug, Eq, PartialEq)]
62pub struct BackendIdentity {
63    name: String,
64    version: String,
65    deprecation: Option<String>,
66}
67
68impl BackendIdentity {
69    pub fn new(
70        name: impl Into<String>,
71        version: impl Into<String>,
72        deprecation: Option<String>,
73    ) -> Result<Self, ExecutionError> {
74        let name = name.into();
75        let version = version.into();
76        validate_identity_field("backend name", &name)?;
77        validate_identity_field("backend version", &version)?;
78        if let Some(message) = &deprecation {
79            validate_identity_field("backend deprecation", message)?;
80        }
81        Ok(Self {
82            name,
83            version,
84            deprecation,
85        })
86    }
87
88    pub fn name(&self) -> &str {
89        &self.name
90    }
91
92    pub fn version(&self) -> &str {
93        &self.version
94    }
95
96    pub fn deprecation(&self) -> Option<&str> {
97        self.deprecation.as_deref()
98    }
99}
100
101fn validate_identity_field(kind: &str, value: &str) -> Result<(), ExecutionError> {
102    if value.is_empty()
103        || value.len() > MAX_BACKEND_IDENTITY_BYTES
104        || value.chars().any(char::is_control)
105    {
106        return Err(ExecutionError::new(
107            ExecutionErrorCategory::InvalidRequest,
108            format!(
109                "{kind} must be non-empty, at most {MAX_BACKEND_IDENTITY_BYTES} UTF-8 bytes, and contain no control characters"
110            ),
111        ));
112    }
113    Ok(())
114}
115
116/// Independently reportable containment dimensions.
117#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
118pub struct EnforcementDimensions {
119    filesystem_read: bool,
120    filesystem_write: bool,
121    network: bool,
122    environment_sanitization: bool,
123    descriptor_hygiene: bool,
124    subprocess_restriction: bool,
125    descendant_authority_propagation: bool,
126    descendant_lifecycle: bool,
127    process_tree_membership: bool,
128    complete_cleanup: bool,
129    timeout: bool,
130    output: bool,
131    process_count: bool,
132    memory: bool,
133}
134
135impl EnforcementDimensions {
136    pub const fn none() -> Self {
137        Self {
138            filesystem_read: false,
139            filesystem_write: false,
140            network: false,
141            environment_sanitization: false,
142            descriptor_hygiene: false,
143            subprocess_restriction: false,
144            descendant_authority_propagation: false,
145            descendant_lifecycle: false,
146            process_tree_membership: false,
147            complete_cleanup: false,
148            timeout: false,
149            output: false,
150            process_count: false,
151            memory: false,
152        }
153    }
154
155    pub fn filesystem_read(&self) -> bool {
156        self.filesystem_read
157    }
158    pub fn filesystem_write(&self) -> bool {
159        self.filesystem_write
160    }
161    pub fn network(&self) -> bool {
162        self.network
163    }
164    pub fn environment_sanitization(&self) -> bool {
165        self.environment_sanitization
166    }
167    pub fn descriptor_hygiene(&self) -> bool {
168        self.descriptor_hygiene
169    }
170    pub fn subprocess_restriction(&self) -> bool {
171        self.subprocess_restriction
172    }
173    pub fn descendant_authority_propagation(&self) -> bool {
174        self.descendant_authority_propagation
175    }
176    pub fn descendant_lifecycle(&self) -> bool {
177        self.descendant_lifecycle
178    }
179    pub fn process_tree_membership(&self) -> bool {
180        self.process_tree_membership
181    }
182    pub fn complete_cleanup(&self) -> bool {
183        self.complete_cleanup
184    }
185    pub fn timeout(&self) -> bool {
186        self.timeout
187    }
188    pub fn output(&self) -> bool {
189        self.output
190    }
191    pub fn process_count(&self) -> bool {
192        self.process_count
193    }
194    pub fn memory(&self) -> bool {
195        self.memory
196    }
197    /// Compatibility summary; prefer the individual resource accessors.
198    pub fn resource_limits(&self) -> bool {
199        self.timeout || self.output || self.process_count || self.memory
200    }
201
202    fn requested_by(policy: &SandboxPolicy) -> Self {
203        if policy.mode() == SandboxMode::Disabled {
204            return Self::none();
205        }
206        let limits = policy.limits();
207        let managed_tree = policy.assurance() == AssuranceLevel::ManagedTree;
208        Self {
209            filesystem_read: true,
210            filesystem_write: true,
211            network: true,
212            environment_sanitization: true,
213            descriptor_hygiene: true,
214            subprocess_restriction: !policy.subprocess(),
215            descendant_authority_propagation: true,
216            descendant_lifecycle: managed_tree,
217            process_tree_membership: managed_tree,
218            complete_cleanup: managed_tree,
219            timeout: limits.timeout_seconds().is_some(),
220            output: limits.max_output_bytes().is_some(),
221            process_count: limits.max_processes().is_some(),
222            memory: limits.max_memory_bytes().is_some(),
223        }
224    }
225
226    fn completion_required(requested: &Self) -> Self {
227        Self {
228            descendant_lifecycle: requested.descendant_lifecycle,
229            process_tree_membership: requested.process_tree_membership,
230            complete_cleanup: requested.complete_cleanup,
231            ..Self::none()
232        }
233    }
234
235    #[allow(dead_code)] // Used by checked construction when a platform backend lands.
236    fn contains(&self, required: &Self) -> bool {
237        (!required.filesystem_read || self.filesystem_read)
238            && (!required.filesystem_write || self.filesystem_write)
239            && (!required.network || self.network)
240            && (!required.environment_sanitization || self.environment_sanitization)
241            && (!required.descriptor_hygiene || self.descriptor_hygiene)
242            && (!required.subprocess_restriction || self.subprocess_restriction)
243            && (!required.descendant_authority_propagation || self.descendant_authority_propagation)
244            && (!required.descendant_lifecycle || self.descendant_lifecycle)
245            && (!required.process_tree_membership || self.process_tree_membership)
246            && (!required.complete_cleanup || self.complete_cleanup)
247            && (!required.timeout || self.timeout)
248            && (!required.output || self.output)
249            && (!required.process_count || self.process_count)
250            && (!required.memory || self.memory)
251    }
252}
253
254/// One independently reportable portable enforcement dimension.
255#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
256#[non_exhaustive]
257pub enum EnforcementDimension {
258    FilesystemRead,
259    FilesystemWrite,
260    Network,
261    EnvironmentSanitization,
262    DescriptorHygiene,
263    SubprocessRestriction,
264    DescendantAuthorityPropagation,
265    DescendantLifecycle,
266    ProcessTreeMembership,
267    CompleteCleanup,
268    Timeout,
269    Output,
270    ProcessCount,
271    Memory,
272}
273
274/// The processes to which one dimension applies.
275#[derive(Clone, Copy, Debug, Eq, PartialEq)]
276#[non_exhaustive]
277pub enum EnforcementScope {
278    LaunchProcess,
279    DescendantTree,
280    ManagedTree,
281}
282
283/// Backend-specific evidence for one dimension. Its private fields prevent forgery by callers.
284#[derive(Clone, Debug, Eq, PartialEq)]
285pub struct DimensionEvidence {
286    dimension: EnforcementDimension,
287    scope: EnforcementScope,
288    mechanism: String,
289    limitations: Vec<String>,
290}
291
292impl DimensionEvidence {
293    fn new(
294        dimension: EnforcementDimension,
295        scope: EnforcementScope,
296        mechanism: impl Into<String>,
297        limitations: Vec<String>,
298    ) -> Self {
299        Self {
300            dimension,
301            scope,
302            mechanism: mechanism.into(),
303            limitations,
304        }
305    }
306
307    pub fn dimension(&self) -> EnforcementDimension {
308        self.dimension
309    }
310    pub fn scope(&self) -> EnforcementScope {
311        self.scope
312    }
313    pub fn mechanism(&self) -> &str {
314        &self.mechanism
315    }
316    pub fn limitations(&self) -> &[String] {
317        &self.limitations
318    }
319}
320
321fn evidence_for_dimensions(
322    dimensions: &EnforcementDimensions,
323    mechanism: &str,
324    limitations: &[&str],
325) -> Vec<DimensionEvidence> {
326    let managed = dimensions.process_tree_membership;
327    [
328        (
329            EnforcementDimension::FilesystemRead,
330            dimensions.filesystem_read,
331        ),
332        (
333            EnforcementDimension::FilesystemWrite,
334            dimensions.filesystem_write,
335        ),
336        (EnforcementDimension::Network, dimensions.network),
337        (
338            EnforcementDimension::EnvironmentSanitization,
339            dimensions.environment_sanitization,
340        ),
341        (
342            EnforcementDimension::DescriptorHygiene,
343            dimensions.descriptor_hygiene,
344        ),
345        (
346            EnforcementDimension::SubprocessRestriction,
347            dimensions.subprocess_restriction,
348        ),
349        (
350            EnforcementDimension::DescendantAuthorityPropagation,
351            dimensions.descendant_authority_propagation,
352        ),
353        (
354            EnforcementDimension::DescendantLifecycle,
355            dimensions.descendant_lifecycle,
356        ),
357        (
358            EnforcementDimension::ProcessTreeMembership,
359            dimensions.process_tree_membership,
360        ),
361        (
362            EnforcementDimension::CompleteCleanup,
363            dimensions.complete_cleanup,
364        ),
365        (EnforcementDimension::Timeout, dimensions.timeout),
366        (EnforcementDimension::Output, dimensions.output),
367        (EnforcementDimension::ProcessCount, dimensions.process_count),
368        (EnforcementDimension::Memory, dimensions.memory),
369    ]
370    .into_iter()
371    .filter(|(_, enabled)| *enabled)
372    .map(|(dimension, _)| {
373        let scope = match dimension {
374            EnforcementDimension::EnvironmentSanitization
375            | EnforcementDimension::DescriptorHygiene => EnforcementScope::LaunchProcess,
376            EnforcementDimension::DescendantLifecycle
377            | EnforcementDimension::ProcessTreeMembership
378            | EnforcementDimension::CompleteCleanup => EnforcementScope::ManagedTree,
379            EnforcementDimension::Timeout
380            | EnforcementDimension::Output
381            | EnforcementDimension::ProcessCount
382            | EnforcementDimension::Memory
383                if managed =>
384            {
385                EnforcementScope::ManagedTree
386            }
387            _ => EnforcementScope::DescendantTree,
388        };
389        DimensionEvidence::new(
390            dimension,
391            scope,
392            mechanism,
393            limitations
394                .iter()
395                .map(|value| (*value).to_owned())
396                .collect(),
397        )
398    })
399    .collect()
400}
401
402fn validate_dimension_evidence(
403    dimensions: &EnforcementDimensions,
404    evidence: &[DimensionEvidence],
405) -> Result<(), ExecutionError> {
406    let expected = evidence_for_dimensions(dimensions, "expected", &[]);
407    if evidence.len() != expected.len()
408        || expected.iter().any(|required| {
409            evidence
410                .iter()
411                .filter(|candidate| candidate.dimension == required.dimension)
412                .count()
413                != 1
414                || !evidence.iter().any(|candidate| {
415                    candidate.dimension == required.dimension
416                        && candidate.scope == required.scope
417                        && !candidate.mechanism.is_empty()
418                        && candidate.mechanism.len() <= MAX_BACKEND_IDENTITY_BYTES
419                        && !candidate.mechanism.chars().any(char::is_control)
420                        && candidate.limitations.iter().all(|limitation| {
421                            !limitation.is_empty()
422                                && limitation.len() <= MAX_BACKEND_IDENTITY_BYTES
423                                && !limitation.chars().any(char::is_control)
424                        })
425                })
426        })
427    {
428        return Err(ExecutionError::new(
429            ExecutionErrorCategory::UnsupportedContainment,
430            "backend dimension metadata is incomplete, duplicated, invalid, or has the wrong scope",
431        ));
432    }
433    Ok(())
434}
435
436/// Access associated with one effective filesystem grant.
437#[derive(Clone, Copy, Debug, Eq, PartialEq)]
438pub enum FilesystemAccess {
439    /// Data only, excluding implicit metadata access.
440    ReadData,
441    /// Metadata only, without file contents or directory listings.
442    ReadMetadata,
443    Read,
444    Write,
445}
446
447/// The policy semantics declared for a target.
448#[derive(Clone, Copy, Debug, Eq, PartialEq)]
449pub enum FilesystemGrantKind {
450    /// Only the directory itself, excluding descendants.
451    ExactDirectory,
452    /// An explicit backend-owned character device, with identity revalidation.
453    CharacterDevice,
454    ExactFile,
455    DirectorySubtree,
456}
457
458/// Where an effective grant originated.
459#[derive(Clone, Copy, Debug, Eq, PartialEq)]
460pub enum FilesystemGrantSource {
461    ProjectPolicy,
462    BackendRuntime,
463}
464
465/// Evidence used to bind a grant immediately before native setup.
466#[derive(Clone, Copy, Debug, Eq, PartialEq)]
467pub enum FilesystemBindingMode {
468    /// A held native handle and stable object identity back this grant.
469    NativeObject,
470    /// A freshly re-resolved canonical path backs this grant. This mode assumes a trusted host
471    /// does not concurrently replace path components before native sandbox installation.
472    CanonicalPath,
473}
474
475/// One typed, effective filesystem grant reported by a receipt.
476#[derive(Clone, Debug, Eq, PartialEq)]
477pub struct ResolvedFilesystemGrant {
478    path: PathBuf,
479    access: FilesystemAccess,
480    kind: FilesystemGrantKind,
481    source: FilesystemGrantSource,
482    binding: FilesystemBindingMode,
483}
484
485impl ResolvedFilesystemGrant {
486    pub fn path(&self) -> &Path {
487        &self.path
488    }
489    pub fn access(&self) -> FilesystemAccess {
490        self.access
491    }
492    pub fn kind(&self) -> FilesystemGrantKind {
493        self.kind
494    }
495    pub fn source(&self) -> FilesystemGrantSource {
496        self.source
497    }
498    pub fn binding(&self) -> FilesystemBindingMode {
499        self.binding
500    }
501}
502
503/// Every effective project and backend runtime grant, without collapsing origins or kinds.
504#[derive(Clone, Debug, Eq, PartialEq)]
505pub struct ResolvedFilesystemGrants {
506    grants: Vec<ResolvedFilesystemGrant>,
507}
508
509impl ResolvedFilesystemGrants {
510    pub fn grants(&self) -> &[ResolvedFilesystemGrant] {
511        &self.grants
512    }
513    pub fn read(&self) -> impl Iterator<Item = &ResolvedFilesystemGrant> {
514        self.grants.iter().filter(|grant| {
515            matches!(
516                grant.access,
517                FilesystemAccess::Read
518                    | FilesystemAccess::ReadData
519                    | FilesystemAccess::ReadMetadata
520            )
521        })
522    }
523    pub fn write(&self) -> impl Iterator<Item = &ResolvedFilesystemGrant> {
524        self.grants
525            .iter()
526            .filter(|grant| grant.access == FilesystemAccess::Write)
527    }
528}
529
530#[derive(Clone, Debug, Eq, PartialEq)]
531enum GrantResolution {
532    ExistingCanonical,
533    MissingWriteDirectory {
534        canonical_ancestor: PathBuf,
535        relative_target: PathBuf,
536    },
537    RuntimeCanonical,
538    #[cfg(any(target_os = "macos", target_os = "linux"))]
539    RuntimeDevice {
540        device: u64,
541        inode: u64,
542        rdev: u64,
543    },
544}
545
546#[derive(Clone, Debug, Eq, PartialEq)]
547struct ResolvedGrant {
548    path: PathBuf,
549    access: FilesystemAccess,
550    kind: FilesystemGrantKind,
551    source: FilesystemGrantSource,
552    resolution: GrantResolution,
553}
554
555/// Explicit, typed backend baseline/runtime paths added to project policy.
556#[derive(Clone, Debug, Default, Eq, PartialEq)]
557struct RuntimeFilesystemAdditions {
558    read: Vec<ResolvedGrant>,
559    write: Vec<ResolvedGrant>,
560}
561
562impl RuntimeFilesystemAdditions {
563    #[allow(dead_code)]
564    fn checked(read: Vec<PathBuf>, write: Vec<PathBuf>) -> Result<Self, ExecutionError> {
565        Ok(Self {
566            read: read
567                .into_iter()
568                .map(|path| resolve_runtime_grant(path, FilesystemAccess::Read))
569                .collect::<Result<_, _>>()?,
570            write: write
571                .into_iter()
572                .map(|path| resolve_runtime_grant(path, FilesystemAccess::Write))
573                .collect::<Result<_, _>>()?,
574        })
575    }
576}
577
578#[derive(Clone, Debug, Eq, PartialEq)]
579struct ResolvedSandboxPolicy {
580    assurance: AssuranceLevel,
581    mode: SandboxMode,
582    project_root: PathBuf,
583    read: Vec<ResolvedGrant>,
584    write: Vec<ResolvedGrant>,
585    limits: ExecutionLimits,
586}
587
588#[cfg(unix)]
589#[derive(Clone, Copy, Debug, Eq, PartialEq)]
590struct NativeIdentity {
591    device: u64,
592    inode: u64,
593}
594
595struct BoundFilesystemGrant {
596    receipt: ResolvedFilesystemGrant,
597    held: Option<fs::File>,
598    #[cfg(unix)]
599    native_identity: Option<NativeIdentity>,
600}
601
602struct FilesystemBindings {
603    grants: Vec<BoundFilesystemGrant>,
604}
605
606impl FilesystemBindings {
607    fn canonical_path(policy: &ResolvedSandboxPolicy) -> Result<Self, ExecutionError> {
608        let grants = policy
609            .read
610            .iter()
611            .chain(&policy.write)
612            .map(bind_canonical)
613            .collect::<Result<_, _>>()?;
614        Ok(Self { grants })
615    }
616
617    #[cfg(unix)]
618    #[allow(dead_code)]
619    fn native_objects(policy: &ResolvedSandboxPolicy) -> Result<Self, ExecutionError> {
620        use std::os::unix::fs::MetadataExt;
621        let grants = policy
622            .read
623            .iter()
624            .chain(&policy.write)
625            .map(|grant| {
626                let canonical = canonical_path(&grant.path, "native filesystem binding")?;
627                if canonical != grant.path || !grant_kind_matches(grant, &canonical)? {
628                    return Err(binding_mismatch());
629                }
630                let held = fs::File::open(&canonical).map_err(|error| {
631                    path_error("open native filesystem binding", &canonical, error)
632                })?;
633                let metadata = held.metadata().map_err(|error| {
634                    path_error("inspect native filesystem binding", &canonical, error)
635                })?;
636                Ok(BoundFilesystemGrant {
637                    receipt: grant_receipt(grant, FilesystemBindingMode::NativeObject),
638                    held: Some(held),
639                    native_identity: Some(NativeIdentity {
640                        device: metadata.dev(),
641                        inode: metadata.ino(),
642                    }),
643                })
644            })
645            .collect::<Result<_, ExecutionError>>()?;
646        Ok(Self { grants })
647    }
648
649    fn validate(&self, policy: &ResolvedSandboxPolicy) -> Result<(), ExecutionError> {
650        let expected: Vec<_> = policy.read.iter().chain(&policy.write).collect();
651        if expected.len() != self.grants.len() {
652            return Err(binding_mismatch());
653        }
654        for (expected, bound) in expected.into_iter().zip(&self.grants) {
655            if bound.receipt.path != expected.path
656                || bound.receipt.access != expected.access
657                || bound.receipt.kind != expected.kind
658                || bound.receipt.source != expected.source
659            {
660                return Err(binding_mismatch());
661            }
662            let canonical = canonical_path(&expected.path, "filesystem binding revalidation")?;
663            if canonical != expected.path || !grant_kind_matches(expected, &canonical)? {
664                return Err(binding_mismatch());
665            }
666            match bound.receipt.binding {
667                FilesystemBindingMode::CanonicalPath => {
668                    if bound.held.is_some() {
669                        return Err(binding_mismatch());
670                    }
671                }
672                FilesystemBindingMode::NativeObject => {
673                    #[cfg(unix)]
674                    {
675                        use std::os::unix::fs::MetadataExt;
676                        let held = bound.held.as_ref().ok_or_else(binding_mismatch)?;
677                        let held_metadata = held.metadata().map_err(|error| {
678                            path_error(
679                                "inspect held native filesystem binding",
680                                &expected.path,
681                                error,
682                            )
683                        })?;
684                        let current = fs::metadata(&canonical).map_err(|error| {
685                            path_error(
686                                "inspect current native filesystem binding",
687                                &canonical,
688                                error,
689                            )
690                        })?;
691                        let identity = NativeIdentity {
692                            device: held_metadata.dev(),
693                            inode: held_metadata.ino(),
694                        };
695                        let current_identity = NativeIdentity {
696                            device: current.dev(),
697                            inode: current.ino(),
698                        };
699                        if Some(identity) != bound.native_identity || identity != current_identity {
700                            return Err(binding_mismatch());
701                        }
702                    }
703                    #[cfg(not(unix))]
704                    return Err(ExecutionError::new(
705                        ExecutionErrorCategory::UnsupportedContainment,
706                        "native object identity is unavailable on this adapter scaffold",
707                    ));
708                }
709            }
710        }
711        Ok(())
712    }
713
714    fn receipt(&self) -> ResolvedFilesystemGrants {
715        ResolvedFilesystemGrants {
716            grants: self
717                .grants
718                .iter()
719                .map(|grant| grant.receipt.clone())
720                .collect(),
721        }
722    }
723}
724
725fn bind_canonical(grant: &ResolvedGrant) -> Result<BoundFilesystemGrant, ExecutionError> {
726    let canonical =
727        canonical_path(&grant.path, "canonical filesystem binding").map_err(|error| {
728            if matches!(
729                grant.resolution,
730                GrantResolution::MissingWriteDirectory { .. }
731            ) {
732                ExecutionError::new(
733                    ExecutionErrorCategory::UnsupportedContainment,
734                    format!("backend did not securely materialize missing write subtree: {error}"),
735                )
736            } else {
737                error
738            }
739        })?;
740    if canonical != grant.path || !grant_kind_matches(grant, &canonical)? {
741        return Err(binding_mismatch());
742    }
743    Ok(BoundFilesystemGrant {
744        receipt: grant_receipt(grant, FilesystemBindingMode::CanonicalPath),
745        held: None,
746        #[cfg(unix)]
747        native_identity: None,
748    })
749}
750
751fn grant_receipt(grant: &ResolvedGrant, binding: FilesystemBindingMode) -> ResolvedFilesystemGrant {
752    ResolvedFilesystemGrant {
753        path: grant.path.clone(),
754        access: grant.access,
755        kind: grant.kind,
756        source: grant.source,
757        binding,
758    }
759}
760
761fn binding_mismatch() -> ExecutionError {
762    ExecutionError::new(
763        ExecutionErrorCategory::PolicyViolation,
764        "backend filesystem bindings do not match the exact validated preflight",
765    )
766}
767
768/// Private proof that support, policy, bindings, and limits passed pre-spawn checks.
769struct ValidatedPreflight {
770    support: ContainmentSupport,
771    policy: ResolvedSandboxPolicy,
772    bindings: FilesystemBindings,
773    child_environment: BTreeMap<OsString, OsString>,
774}
775
776impl ResolvedSandboxPolicy {
777    fn validate(&self) -> Result<(), ExecutionError> {
778        for grant in self.read.iter().chain(&self.write) {
779            match &grant.resolution {
780                GrantResolution::ExistingCanonical => {
781                    validate_canonical_path(&grant.path)?;
782                    if !grant.path.starts_with(&self.project_root) {
783                        return Err(grant_confinement_error(&grant.path));
784                    }
785                }
786                GrantResolution::MissingWriteDirectory {
787                    canonical_ancestor,
788                    relative_target,
789                } => {
790                    validate_canonical_path(canonical_ancestor)?;
791                    if grant.access != FilesystemAccess::Write
792                        || grant.kind != FilesystemGrantKind::DirectorySubtree
793                        || !canonical_ancestor.starts_with(&self.project_root)
794                        || relative_target.is_absolute()
795                        || relative_target
796                            .components()
797                            .any(|component| !matches!(component, std::path::Component::Normal(_)))
798                        || canonical_ancestor.join(relative_target) != grant.path
799                    {
800                        return Err(grant_confinement_error(&grant.path));
801                    }
802                }
803                GrantResolution::RuntimeCanonical => validate_canonical_path(&grant.path)?,
804                #[cfg(any(target_os = "macos", target_os = "linux"))]
805                GrantResolution::RuntimeDevice { .. } => {
806                    validate_canonical_path(&grant.path)?;
807                    if !grant_kind_matches(grant, &grant.path)? {
808                        return Err(binding_mismatch());
809                    }
810                }
811            }
812        }
813        Ok(())
814    }
815}
816
817fn validate_canonical_path(path: &Path) -> Result<(), ExecutionError> {
818    if !path.is_absolute() || canonical_path(path, "filesystem grant")? != path {
819        return Err(ExecutionError::new(
820            ExecutionErrorCategory::PolicyViolation,
821            format!(
822                "filesystem grant is not absolute and canonical: {}",
823                path.display()
824            ),
825        ));
826    }
827    Ok(())
828}
829
830fn grant_confinement_error(path: &Path) -> ExecutionError {
831    ExecutionError::new(
832        ExecutionErrorCategory::PolicyViolation,
833        format!(
834            "filesystem grant is neither project-confined nor an approved runtime addition: {}",
835            path.display()
836        ),
837    )
838}
839
840#[derive(Clone, Copy, Debug, Eq, PartialEq)]
841enum SupportAvailability {
842    Supported,
843    Unsupported,
844}
845
846/// The platform backend's dimensioned ability to enforce the requested containment policy.
847///
848/// Callers can inspect this report but cannot manufacture one.
849///
850/// ```
851/// use tapid_runner::ContainmentSupport;
852/// fn inspect(report: &ContainmentSupport) {
853///     let _: bool = report.is_supported();
854///     let _: Option<&str> = report.platform();
855/// }
856/// ```
857///
858/// ```compile_fail
859/// use tapid_runner::{BackendIdentity, ContainmentSupport, EnforcementDimensions};
860/// let none = EnforcementDimensions::none();
861/// let _ = ContainmentSupport::Supported {
862///     backend: BackendIdentity::new("fake", "1", None).unwrap(),
863///     requested: none.clone(), declared: none.clone(), observed: none,
864///     declared_evidence: vec![], observed_evidence: vec![],
865/// };
866/// ```
867#[derive(Clone, Debug, Eq, PartialEq)]
868pub struct ContainmentSupport {
869    availability: SupportAvailability,
870    backend: BackendIdentity,
871    platform: Option<String>,
872    reason: Option<String>,
873    requested: EnforcementDimensions,
874    declared: EnforcementDimensions,
875    observed: EnforcementDimensions,
876    declared_evidence: Vec<DimensionEvidence>,
877    observed_evidence: Vec<DimensionEvidence>,
878}
879
880impl ContainmentSupport {
881    #[allow(dead_code)] // Reserved for a platform backend; tests exercise the contract now.
882    fn supported(
883        backend: BackendIdentity,
884        requested: EnforcementDimensions,
885        declared: EnforcementDimensions,
886        observed: EnforcementDimensions,
887        declared_evidence: Vec<DimensionEvidence>,
888        observed_evidence: Vec<DimensionEvidence>,
889    ) -> Self {
890        Self {
891            availability: SupportAvailability::Supported,
892            backend,
893            platform: Some(std::env::consts::OS.to_owned()),
894            reason: None,
895            requested,
896            declared,
897            observed,
898            declared_evidence,
899            observed_evidence,
900        }
901    }
902
903    fn unsupported(
904        backend: BackendIdentity,
905        platform: impl Into<String>,
906        reason: impl Into<String>,
907        requested: EnforcementDimensions,
908        declared: EnforcementDimensions,
909        observed: EnforcementDimensions,
910    ) -> Self {
911        Self {
912            availability: SupportAvailability::Unsupported,
913            backend,
914            platform: Some(platform.into()),
915            reason: Some(reason.into()),
916            requested,
917            declared,
918            observed,
919            declared_evidence: Vec::new(),
920            observed_evidence: Vec::new(),
921        }
922    }
923
924    pub fn is_supported(&self) -> bool {
925        self.availability == SupportAvailability::Supported
926    }
927
928    /// Platform named by the backend report. The report remains non-forgeable because all fields
929    /// and constructors are private while these accessors make its claims inspectable.
930    pub fn platform(&self) -> Option<&str> {
931        self.platform.as_deref()
932    }
933
934    pub fn backend(&self) -> &BackendIdentity {
935        &self.backend
936    }
937
938    pub fn requested(&self) -> &EnforcementDimensions {
939        &self.requested
940    }
941
942    /// Compatibility summary. Prefer [`Self::declared_evidence`].
943    pub fn declared(&self) -> &EnforcementDimensions {
944        &self.declared
945    }
946
947    /// Compatibility summary. Prefer [`Self::observed_evidence`].
948    pub fn observed(&self) -> &EnforcementDimensions {
949        &self.observed
950    }
951
952    pub fn declared_evidence(&self) -> &[DimensionEvidence] {
953        &self.declared_evidence
954    }
955
956    pub fn observed_evidence(&self) -> &[DimensionEvidence] {
957        &self.observed_evidence
958    }
959
960    /// Compatibility alias for [`Self::declared`].
961    pub fn enforceable(&self) -> &EnforcementDimensions {
962        self.declared()
963    }
964
965    pub fn unsupported_reason(&self) -> Option<&str> {
966        self.reason.as_deref()
967    }
968}
969
970/// Evidence returned by an execution backend about actual enforcement.
971///
972/// Its private fields prevent callers from manufacturing enforcement claims. No receipt is
973/// produced until a backend has performed execution.
974///
975/// ```compile_fail
976/// use tapid_runner::{ContainmentSupport, EnforcementDimensions, EnforcementReceipt,
977///     ExecutionLimits, ResolvedFilesystemGrants};
978/// fn forge(support: ContainmentSupport, enforced: EnforcementDimensions,
979///     resolved_filesystem: ResolvedFilesystemGrants, configured_limits: ExecutionLimits) {
980///     let _ = EnforcementReceipt { support, enforced, resolved_filesystem, configured_limits };
981/// }
982/// ```
983#[derive(Clone, Debug, Eq, PartialEq)]
984pub struct EnforcementReceipt {
985    executable_resolution: Option<ExecutableResolutionEvidence>,
986    assurance: AssuranceLevel,
987    support: ContainmentSupport,
988    enforced: EnforcementDimensions,
989    established_evidence: Vec<DimensionEvidence>,
990    resolved_filesystem: ResolvedFilesystemGrants,
991    configured_limits: ExecutionLimits,
992}
993
994/// Exact Unix bytes for PATH and each entry, preserving non-UTF-8 paths.
995#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
996pub struct ExecutableResolutionEvidence {
997    pub path: Vec<u8>,
998    pub path_order: Vec<Vec<u8>>,
999    pub caller_path_inherited: bool,
1000    pub reserved_node: Option<ReservedExecutableEvidence>,
1001}
1002#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
1003pub struct ReservedExecutableEvidence {
1004    pub command: String,
1005    pub private_path: Vec<u8>,
1006    pub trusted_runtime: Vec<u8>,
1007    pub device: u64,
1008    pub inode: u64,
1009    pub mechanism: String,
1010    pub identity_checks: String,
1011    /// Whether the private binding was removed, not whether descendants were cleaned.
1012    /// macOS retains it when subprocess-enabled targets may have executed.
1013    pub cleanup_observed: bool,
1014    pub limitations: String,
1015}
1016
1017impl EnforcementReceipt {
1018    pub fn executable_resolution(&self) -> Option<&ExecutableResolutionEvidence> {
1019        self.executable_resolution.as_ref()
1020    }
1021
1022    #[allow(dead_code)] // Non-macOS backends cannot produce receipts.
1023    fn checked(
1024        preflight: &ValidatedPreflight,
1025        enforced: EnforcementDimensions,
1026        established_evidence: Vec<DimensionEvidence>,
1027    ) -> Result<Self, ExecutionError> {
1028        let support = &preflight.support;
1029        if !support.is_supported() {
1030            return Err(ExecutionError::new(
1031                ExecutionErrorCategory::UnsupportedContainment,
1032                "cannot issue an enforcement receipt for unsupported containment",
1033            ));
1034        }
1035        let requested = support.requested();
1036        if preflight.policy.mode == SandboxMode::Disabled {
1037            return Err(ExecutionError::new(
1038                ExecutionErrorCategory::PolicyViolation,
1039                "disabled sandbox execution cannot issue an enforcement receipt",
1040            ));
1041        }
1042        if &enforced != requested {
1043            return Err(ExecutionError::new(
1044                ExecutionErrorCategory::PolicyViolation,
1045                "established dimensions do not exactly match the requested restrictions",
1046            ));
1047        }
1048        if !support.declared().contains(requested) || !support.observed().contains(requested) {
1049            return Err(ExecutionError::new(
1050                ExecutionErrorCategory::UnsupportedContainment,
1051                "requested restrictions lack declared or observed backend support",
1052            ));
1053        }
1054        let configured_limits = &preflight.policy.limits;
1055        if requested.timeout != configured_limits.timeout_seconds().is_some()
1056            || requested.output != configured_limits.max_output_bytes().is_some()
1057            || requested.process_count != configured_limits.max_processes().is_some()
1058            || requested.memory != configured_limits.max_memory_bytes().is_some()
1059        {
1060            return Err(ExecutionError::new(
1061                ExecutionErrorCategory::PolicyViolation,
1062                "configured limits do not match requested resource restrictions",
1063            ));
1064        }
1065        validate_dimension_evidence(&enforced, &established_evidence)?;
1066        Ok(Self {
1067            executable_resolution: None,
1068            assurance: preflight.policy.assurance,
1069            support: support.clone(),
1070            enforced,
1071            established_evidence,
1072            resolved_filesystem: preflight.bindings.receipt(),
1073            configured_limits: configured_limits.clone(),
1074        })
1075    }
1076
1077    pub fn assurance(&self) -> AssuranceLevel {
1078        self.assurance
1079    }
1080
1081    pub fn support(&self) -> &ContainmentSupport {
1082        &self.support
1083    }
1084
1085    pub fn backend(&self) -> &BackendIdentity {
1086        self.support.backend()
1087    }
1088
1089    pub fn requested(&self) -> &EnforcementDimensions {
1090        self.support.requested()
1091    }
1092
1093    pub fn declared(&self) -> &EnforcementDimensions {
1094        self.support.declared()
1095    }
1096
1097    pub fn observed(&self) -> &EnforcementDimensions {
1098        self.support.observed()
1099    }
1100
1101    pub fn enforced(&self) -> &EnforcementDimensions {
1102        &self.enforced
1103    }
1104
1105    /// Launch-time evidence that the backend established each reported restriction before spawn.
1106    pub fn established_evidence(&self) -> &[DimensionEvidence] {
1107        &self.established_evidence
1108    }
1109
1110    pub fn resolved_filesystem(&self) -> &ResolvedFilesystemGrants {
1111        &self.resolved_filesystem
1112    }
1113
1114    pub fn configured_limits(&self) -> &ExecutionLimits {
1115        &self.configured_limits
1116    }
1117}
1118
1119/// Confidence that process cleanup was observed at execution completion.
1120///
1121/// ```compile_fail
1122/// use tapid_runner::CleanupConfidence;
1123/// fn exhaustive(value: CleanupConfidence) {
1124///     match value {
1125///         CleanupConfidence::NotGuaranteed => {}
1126///         CleanupConfidence::BestEffortObserved => {}
1127///         CleanupConfidence::KernelOwnedComplete => {}
1128///     }
1129/// }
1130/// ```
1131#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1132#[non_exhaustive]
1133pub enum CleanupConfidence {
1134    /// Cleanup is outside the portable restricted-authority contract.
1135    NotGuaranteed,
1136    /// Cleanup was attempted and observed without complete descendant ownership.
1137    BestEffortObserved,
1138    /// A kernel or VM owned the complete process-tree cleanup boundary.
1139    KernelOwnedComplete,
1140}
1141
1142/// Completion-time evidence, distinct from launch-time enforcement evidence.
1143#[derive(Clone, Debug, Eq, PartialEq)]
1144pub struct CompletionEvidence {
1145    confirmed: EnforcementDimensions,
1146    evidence: Vec<DimensionEvidence>,
1147    cleanup_confidence: CleanupConfidence,
1148}
1149
1150impl CompletionEvidence {
1151    #[allow(dead_code)] // Non-macOS backends cannot produce completion evidence.
1152    fn checked(
1153        preflight: &ValidatedPreflight,
1154        confirmed: EnforcementDimensions,
1155        evidence: Vec<DimensionEvidence>,
1156        cleanup_confidence: CleanupConfidence,
1157    ) -> Result<Self, ExecutionError> {
1158        let required = EnforcementDimensions::completion_required(preflight.support.requested());
1159        if confirmed != required {
1160            return Err(ExecutionError::new(
1161                ExecutionErrorCategory::PolicyViolation,
1162                "completion evidence does not exactly match completion-observable dimensions",
1163            ));
1164        }
1165        validate_dimension_evidence(&confirmed, &evidence)?;
1166        Ok(Self {
1167            evidence,
1168            confirmed,
1169            cleanup_confidence,
1170        })
1171    }
1172
1173    pub fn confirmed(&self) -> &EnforcementDimensions {
1174        &self.confirmed
1175    }
1176
1177    pub fn evidence(&self) -> &[DimensionEvidence] {
1178        &self.evidence
1179    }
1180
1181    pub fn cleanup_confidence(&self) -> CleanupConfidence {
1182        self.cleanup_confidence
1183    }
1184}
1185
1186/// How execution ended after a backend accepted a request.
1187#[derive(Clone, Debug, Eq, PartialEq)]
1188pub enum Termination {
1189    Exited(i32),
1190    Signaled(i32),
1191    TimedOut,
1192    OutputLimitExceeded,
1193    ProcessLimitExceeded,
1194    MemoryLimitExceeded,
1195    Cancelled,
1196}
1197
1198/// Captured execution result paired with an enforcement receipt.
1199///
1200/// Post-spawn validation checked-adds the byte lengths of stdout and stderr; their combined size
1201/// may not exceed the exact preflight `max_output_bytes`. Resource-limit termination variants are
1202/// accepted only when the corresponding limit was present in that exact preflight.
1203///
1204/// ```compile_fail
1205/// use tapid_runner::{EnforcementReceipt, ExecutionOutcome, Termination};
1206/// fn forge(enforcement: EnforcementReceipt) {
1207///     let _ = ExecutionOutcome {
1208///         termination: Termination::Exited(0), stdout: vec![], stderr: vec![], enforcement
1209///     };
1210/// }
1211/// ```
1212#[derive(Clone, Debug, Eq, PartialEq)]
1213pub struct ExecutionOutcome {
1214    termination: Termination,
1215    stdout: Vec<u8>,
1216    stderr: Vec<u8>,
1217    process_memory_stats_hint: bool,
1218    enforcement: EnforcementReceipt,
1219    completion: CompletionEvidence,
1220}
1221
1222impl ExecutionOutcome {
1223    #[allow(dead_code)] // Non-macOS backends cannot produce outcomes.
1224    fn checked(
1225        termination: Termination,
1226        stdout: Vec<u8>,
1227        stderr: Vec<u8>,
1228        enforcement: EnforcementReceipt,
1229        completion: CompletionEvidence,
1230    ) -> Result<Self, ExecutionError> {
1231        if enforcement.enforced() != enforcement.requested() {
1232            return Err(ExecutionError::new(
1233                ExecutionErrorCategory::PolicyViolation,
1234                "execution outcome lacks complete enforcement evidence",
1235            ));
1236        }
1237        let completion_required =
1238            EnforcementDimensions::completion_required(enforcement.requested());
1239        if completion.confirmed() != &completion_required {
1240            return Err(ExecutionError::new(
1241                ExecutionErrorCategory::PolicyViolation,
1242                "execution outcome lacks complete completion evidence",
1243            ));
1244        }
1245        if enforcement.requested().process_tree_membership()
1246            && completion.cleanup_confidence() != CleanupConfidence::KernelOwnedComplete
1247        {
1248            return Err(ExecutionError::new(
1249                ExecutionErrorCategory::PolicyViolation,
1250                "managed-tree execution requires kernel-owned complete cleanup evidence",
1251            ));
1252        }
1253        Ok(Self {
1254            termination,
1255            stdout,
1256            stderr,
1257            process_memory_stats_hint: false,
1258            enforcement,
1259            completion,
1260        })
1261    }
1262
1263    fn validate_for_preflight(&self, preflight: &ValidatedPreflight) -> Result<(), ExecutionError> {
1264        let required = preflight.support.requested();
1265        let receipt = self.enforcement();
1266        if receipt.support() != &preflight.support
1267            || receipt.requested() != required
1268            || receipt.enforced() != required
1269            || !receipt.declared().contains(required)
1270            || !receipt.observed().contains(required)
1271            || receipt.configured_limits() != &preflight.policy.limits
1272            || receipt.resolved_filesystem() != &preflight.bindings.receipt()
1273            || self.completion.confirmed() != &EnforcementDimensions::completion_required(required)
1274        {
1275            return Err(ExecutionError::new(
1276                ExecutionErrorCategory::PolicyViolation,
1277                "execution outcome does not match the exact validated preflight",
1278            ));
1279        }
1280        let captured_bytes = checked_captured_output_bytes(self.stdout.len(), self.stderr.len())?;
1281        if preflight
1282            .policy
1283            .limits
1284            .max_output_bytes()
1285            .is_some_and(|limit| {
1286                u64::try_from(captured_bytes).map_or(true, |captured| captured > limit)
1287            })
1288        {
1289            return Err(ExecutionError::new(
1290                ExecutionErrorCategory::PolicyViolation,
1291                "captured stdout and stderr exceed the exact preflight output limit",
1292            ));
1293        }
1294        if matches!(self.termination, Termination::TimedOut)
1295            && preflight.policy.limits.timeout_seconds().is_none()
1296        {
1297            return Err(ExecutionError::new(
1298                ExecutionErrorCategory::PolicyViolation,
1299                "timeout termination requires an exact preflight timeout limit",
1300            ));
1301        }
1302        if matches!(self.termination, Termination::OutputLimitExceeded)
1303            && preflight.policy.limits.max_output_bytes().is_none()
1304        {
1305            return Err(ExecutionError::new(
1306                ExecutionErrorCategory::PolicyViolation,
1307                "output-limit termination requires an exact preflight output limit",
1308            ));
1309        }
1310        if matches!(self.termination, Termination::ProcessLimitExceeded)
1311            && preflight.policy.limits.max_processes().is_none()
1312        {
1313            return Err(ExecutionError::new(
1314                ExecutionErrorCategory::PolicyViolation,
1315                "process-limit termination requires an exact preflight process limit",
1316            ));
1317        }
1318        if matches!(self.termination, Termination::MemoryLimitExceeded)
1319            && preflight.policy.limits.max_memory_bytes().is_none()
1320        {
1321            return Err(ExecutionError::new(
1322                ExecutionErrorCategory::PolicyViolation,
1323                "memory-limit termination requires an exact preflight memory limit",
1324            ));
1325        }
1326        Ok(())
1327    }
1328
1329    pub fn termination(&self) -> &Termination {
1330        &self.termination
1331    }
1332    pub fn stdout(&self) -> &[u8] {
1333        &self.stdout
1334    }
1335    pub fn stderr(&self) -> &[u8] {
1336        &self.stderr
1337    }
1338    /// Whether stderr matched the known libuv process-memory-stat permission failure.
1339    pub fn process_memory_stats_hint(&self) -> bool {
1340        self.process_memory_stats_hint
1341    }
1342    #[cfg(target_os = "linux")]
1343    pub(crate) fn with_process_memory_stats_hint(mut self, hint: bool) -> Self {
1344        self.process_memory_stats_hint = hint;
1345        self
1346    }
1347    pub fn enforcement(&self) -> &EnforcementReceipt {
1348        &self.enforcement
1349    }
1350    pub fn completion(&self) -> &CompletionEvidence {
1351        &self.completion
1352    }
1353}
1354
1355fn checked_captured_output_bytes(stdout: usize, stderr: usize) -> Result<usize, ExecutionError> {
1356    stdout.checked_add(stderr).ok_or_else(|| {
1357        ExecutionError::new(
1358            ExecutionErrorCategory::PolicyViolation,
1359            "captured stdout and stderr byte count overflowed",
1360        )
1361    })
1362}
1363
1364/// Stable high-level execution failure categories for callers and machine output.
1365#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1366#[non_exhaustive]
1367pub enum ExecutionErrorCategory {
1368    InvalidRequest,
1369    UnsupportedContainment,
1370    PolicyViolation,
1371    Spawn,
1372    Timeout,
1373    OutputLimit,
1374    ProcessLimit,
1375    MemoryLimit,
1376    Internal,
1377}
1378
1379/// An execution failure with a stable category and human-readable context.
1380#[derive(Clone, Debug, Eq, PartialEq)]
1381pub struct ExecutionError {
1382    category: ExecutionErrorCategory,
1383    message: String,
1384    completion: Option<CompletionEvidence>,
1385}
1386
1387impl ExecutionError {
1388    fn new(category: ExecutionErrorCategory, message: impl Into<String>) -> Self {
1389        Self {
1390            category,
1391            message: message.into(),
1392            completion: None,
1393        }
1394    }
1395
1396    fn with_completion(mut self, completion: CompletionEvidence) -> Self {
1397        self.completion = Some(completion);
1398        self
1399    }
1400
1401    pub fn category(&self) -> ExecutionErrorCategory {
1402        self.category
1403    }
1404
1405    /// Checked cleanup disposition for a failure after process creation; absent before spawn.
1406    pub fn completion(&self) -> Option<&CompletionEvidence> {
1407        self.completion.as_ref()
1408    }
1409}
1410
1411impl fmt::Display for ExecutionError {
1412    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1413        f.write_str(&self.message)
1414    }
1415}
1416impl std::error::Error for ExecutionError {}
1417
1418/// Attempts execution through a private platform backend.
1419///
1420/// Experimental macOS Restricted execution requires early private-launcher initialization.
1421/// Unsupported platforms and required dimensions fail before target spawn.
1422pub fn execute(request: &ExecutionRequest) -> Result<ExecutionOutcome, ExecutionError> {
1423    #[cfg(target_os = "macos")]
1424    return platform_backend::execute_reserved(request);
1425    #[cfg(not(target_os = "macos"))]
1426    execute_with_backend(request, &platform_backend::PlatformBackend)
1427}
1428
1429/// Byte identity of the native backend and its documented system toolchain.
1430/// This performs no project execution and does not require cgroup delegation.
1431pub fn dependency_toolchain_identity() -> Result<String, ExecutionError> {
1432    #[cfg(target_os = "linux")]
1433    {
1434        platform_backend::toolchain_identity()
1435    }
1436    #[cfg(not(target_os = "linux"))]
1437    Err(ExecutionError::new(
1438        ExecutionErrorCategory::UnsupportedContainment,
1439        "dependency lifecycle toolchain identity currently requires Linux",
1440    ))
1441}
1442
1443fn resolve_policy(
1444    request: &ExecutionRequest,
1445    additions: RuntimeFilesystemAdditions,
1446) -> Result<ResolvedSandboxPolicy, ExecutionError> {
1447    let project_root = canonical_path(request.project_root(), "project root")?;
1448    let filesystem = request.policy().filesystem();
1449    let mut read = filesystem
1450        .read()
1451        .iter()
1452        .map(|grant| resolve_project_grant(&project_root, grant, FilesystemAccess::Read))
1453        .collect::<Result<Vec<_>, _>>()?;
1454    let mut write = filesystem
1455        .write()
1456        .iter()
1457        .map(|grant| resolve_project_grant(&project_root, grant, FilesystemAccess::Write))
1458        .collect::<Result<Vec<_>, _>>()?;
1459    let executable_search_paths = request
1460        .executable_search_paths()
1461        .iter()
1462        .map(|path| resolve_executable_search_directory(path))
1463        .collect::<Result<Vec<_>, _>>()?;
1464    validate_resolved_executable_search_paths(
1465        request.executable_search_paths(),
1466        &executable_search_paths,
1467    )?;
1468    read.extend(executable_search_paths);
1469    read.extend(additions.read);
1470    write.extend(additions.write);
1471
1472    Ok(ResolvedSandboxPolicy {
1473        assurance: request.policy().assurance(),
1474        mode: request.policy().mode(),
1475        project_root,
1476        read,
1477        write,
1478        limits: request.policy().limits().clone(),
1479    })
1480}
1481
1482fn resolve_project_grant(
1483    project_root: &Path,
1484    configured: &str,
1485    access: FilesystemAccess,
1486) -> Result<ResolvedGrant, ExecutionError> {
1487    let target = project_root.join(configured);
1488    let mut ancestor = target.as_path();
1489    let mut missing = Vec::new();
1490
1491    loop {
1492        match fs::symlink_metadata(ancestor) {
1493            Ok(_) => break,
1494            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
1495                if access == FilesystemAccess::Read {
1496                    return Err(ExecutionError::new(
1497                        ExecutionErrorCategory::PolicyViolation,
1498                        format!("read grant target does not exist: {configured:?}"),
1499                    ));
1500                }
1501                let component = ancestor.file_name().ok_or_else(|| {
1502                    ExecutionError::new(
1503                        ExecutionErrorCategory::PolicyViolation,
1504                        format!("filesystem grant has no existing ancestor: {configured:?}"),
1505                    )
1506                })?;
1507                missing.push(component.to_os_string());
1508                ancestor = ancestor.parent().ok_or_else(|| {
1509                    ExecutionError::new(
1510                        ExecutionErrorCategory::PolicyViolation,
1511                        format!("filesystem grant has no existing ancestor: {configured:?}"),
1512                    )
1513                })?;
1514            }
1515            Err(error) => return Err(path_error("inspect filesystem grant", &target, error)),
1516        }
1517    }
1518
1519    let canonical_ancestor = canonical_path(ancestor, "filesystem grant ancestor")?;
1520    if !canonical_ancestor.starts_with(project_root) {
1521        return Err(ExecutionError::new(
1522            ExecutionErrorCategory::PolicyViolation,
1523            format!("filesystem grant escapes the canonical project root: {configured:?}"),
1524        ));
1525    }
1526    if missing.is_empty() {
1527        return Ok(ResolvedGrant {
1528            kind: filesystem_kind(&canonical_ancestor)?,
1529            path: canonical_ancestor,
1530            access,
1531            source: FilesystemGrantSource::ProjectPolicy,
1532            resolution: GrantResolution::ExistingCanonical,
1533        });
1534    }
1535
1536    missing.reverse();
1537    let relative_target = missing.iter().collect::<PathBuf>();
1538    let path = canonical_ancestor.join(&relative_target);
1539    Ok(ResolvedGrant {
1540        path,
1541        access,
1542        kind: FilesystemGrantKind::DirectorySubtree,
1543        source: FilesystemGrantSource::ProjectPolicy,
1544        resolution: GrantResolution::MissingWriteDirectory {
1545            canonical_ancestor,
1546            relative_target,
1547        },
1548    })
1549}
1550
1551fn resolve_executable_search_directory(path: &Path) -> Result<ResolvedGrant, ExecutionError> {
1552    if !path.is_absolute() {
1553        return Err(ExecutionError::new(
1554            ExecutionErrorCategory::PolicyViolation,
1555            format!(
1556                "executable search directory must be absolute: {}",
1557                path.display()
1558            ),
1559        ));
1560    }
1561    let canonical = canonical_path(path, "executable search directory")?;
1562    let metadata = fs::metadata(&canonical)
1563        .map_err(|error| path_error("executable search directory", &canonical, error))?;
1564    if !metadata.is_dir() {
1565        return Err(ExecutionError::new(
1566            ExecutionErrorCategory::PolicyViolation,
1567            format!(
1568                "executable search path is not a directory: {}",
1569                path.display()
1570            ),
1571        ));
1572    }
1573    Ok(ResolvedGrant {
1574        path: canonical,
1575        access: FilesystemAccess::Read,
1576        kind: FilesystemGrantKind::DirectorySubtree,
1577        source: FilesystemGrantSource::BackendRuntime,
1578        resolution: GrantResolution::RuntimeCanonical,
1579    })
1580}
1581
1582fn validate_resolved_executable_search_paths(
1583    requested: &[PathBuf],
1584    resolved: &[ResolvedGrant],
1585) -> Result<(), ExecutionError> {
1586    for (index, grant) in resolved.iter().enumerate() {
1587        if resolved[..index]
1588            .iter()
1589            .any(|prior| platform_paths_semantically_equal(&prior.path, &grant.path))
1590        {
1591            return Err(ExecutionError::new(
1592                ExecutionErrorCategory::PolicyViolation,
1593                format!(
1594                    "executable search directories resolve to the same platform alias: {}",
1595                    requested[index].display()
1596                ),
1597            ));
1598        }
1599    }
1600
1601    for (requested, resolved) in requested.iter().zip(resolved) {
1602        if requested != &resolved.path {
1603            return Err(ExecutionError::new(
1604                ExecutionErrorCategory::PolicyViolation,
1605                format!(
1606                    "executable search directory must already be canonical: {}",
1607                    requested.display()
1608                ),
1609            ));
1610        }
1611    }
1612    Ok(())
1613}
1614
1615#[cfg(not(windows))]
1616fn platform_paths_semantically_equal(left: &Path, right: &Path) -> bool {
1617    left == right
1618}
1619
1620#[cfg(windows)]
1621fn platform_paths_semantically_equal(left: &Path, right: &Path) -> bool {
1622    use std::os::windows::ffi::OsStrExt;
1623    let left = left.as_os_str().encode_wide().collect::<Vec<_>>();
1624    let right = right.as_os_str().encode_wide().collect::<Vec<_>>();
1625    windows_path_units_semantically_equal(&left, &right)
1626}
1627
1628fn resolve_runtime_grant(
1629    path: PathBuf,
1630    access: FilesystemAccess,
1631) -> Result<ResolvedGrant, ExecutionError> {
1632    if !path.is_absolute() {
1633        return Err(ExecutionError::new(
1634            ExecutionErrorCategory::PolicyViolation,
1635            format!(
1636                "runtime filesystem grant must be absolute: {}",
1637                path.display()
1638            ),
1639        ));
1640    }
1641    let canonical = canonical_path(&path, "runtime filesystem grant")?;
1642    if canonical != path {
1643        return Err(ExecutionError::new(
1644            ExecutionErrorCategory::PolicyViolation,
1645            format!(
1646                "runtime filesystem grant must already be canonical: {}",
1647                path.display()
1648            ),
1649        ));
1650    }
1651    #[cfg(any(target_os = "macos", target_os = "linux"))]
1652    if matches!(
1653        canonical.to_str(),
1654        Some("/dev/null" | "/dev/random" | "/dev/urandom")
1655    ) || (cfg!(target_os = "linux") && canonical == Path::new("/dev/zero"))
1656    {
1657        use std::os::unix::fs::{FileTypeExt, MetadataExt};
1658        let metadata = fs::metadata(&canonical).map_err(|_| binding_mismatch())?;
1659        if !metadata.file_type().is_char_device() {
1660            return Err(binding_mismatch());
1661        }
1662        return Ok(ResolvedGrant {
1663            path: canonical,
1664            access,
1665            kind: FilesystemGrantKind::CharacterDevice,
1666            source: FilesystemGrantSource::BackendRuntime,
1667            resolution: GrantResolution::RuntimeDevice {
1668                device: metadata.dev(),
1669                inode: metadata.ino(),
1670                rdev: metadata.rdev(),
1671            },
1672        });
1673    }
1674    Ok(ResolvedGrant {
1675        kind: filesystem_kind(&canonical)?,
1676        path: canonical,
1677        access,
1678        source: FilesystemGrantSource::BackendRuntime,
1679        resolution: GrantResolution::RuntimeCanonical,
1680    })
1681}
1682
1683fn grant_kind_matches(grant: &ResolvedGrant, path: &Path) -> Result<bool, ExecutionError> {
1684    #[cfg(any(target_os = "macos", target_os = "linux"))]
1685    if let GrantResolution::RuntimeDevice {
1686        device,
1687        inode,
1688        rdev,
1689    } = grant.resolution
1690    {
1691        use std::os::unix::fs::{FileTypeExt, MetadataExt};
1692        let metadata = fs::metadata(path).map_err(|_| binding_mismatch())?;
1693        return Ok(grant.source == FilesystemGrantSource::BackendRuntime
1694            && grant.kind == FilesystemGrantKind::CharacterDevice
1695            && metadata.file_type().is_char_device()
1696            && (metadata.dev(), metadata.ino(), metadata.rdev()) == (device, inode, rdev));
1697    }
1698    let actual = filesystem_kind(path)?;
1699    Ok(actual == grant.kind
1700        || (actual == FilesystemGrantKind::DirectorySubtree
1701            && grant.kind == FilesystemGrantKind::ExactDirectory))
1702}
1703
1704fn filesystem_kind(path: &Path) -> Result<FilesystemGrantKind, ExecutionError> {
1705    let metadata = fs::metadata(path)
1706        .map_err(|error| path_error("inspect filesystem grant kind", path, error))?;
1707    if metadata.is_file() {
1708        Ok(FilesystemGrantKind::ExactFile)
1709    } else if metadata.is_dir() {
1710        Ok(FilesystemGrantKind::DirectorySubtree)
1711    } else {
1712        Err(ExecutionError::new(
1713            ExecutionErrorCategory::PolicyViolation,
1714            format!(
1715                "filesystem grant is neither a regular file nor directory: {}",
1716                path.display()
1717            ),
1718        ))
1719    }
1720}
1721
1722fn canonical_path(path: &Path, kind: &str) -> Result<PathBuf, ExecutionError> {
1723    fs::canonicalize(path).map_err(|error| path_error(kind, path, error))
1724}
1725
1726fn path_error(kind: &str, path: &Path, error: std::io::Error) -> ExecutionError {
1727    ExecutionError::new(
1728        ExecutionErrorCategory::PolicyViolation,
1729        format!("cannot resolve {kind} {}: {error}", path.display()),
1730    )
1731}
1732
1733#[cfg(windows)]
1734#[path = "windows_execution.rs"]
1735mod platform_backend;
1736#[cfg(any(windows, test))]
1737#[path = "windows_cancellation.rs"]
1738mod windows_cancellation;
1739#[cfg(windows)]
1740#[path = "windows_job.rs"]
1741mod windows_job;
1742
1743#[cfg(target_os = "macos")]
1744#[path = "macos_restricted.rs"]
1745mod platform_backend;
1746
1747#[cfg(target_os = "linux")]
1748#[path = "linux_restricted.rs"]
1749mod platform_backend;
1750
1751#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
1752mod platform_backend {
1753    use super::{
1754        BackendIdentity, ContainmentSupport, EnforcementDimensions, ExecutionBackend,
1755        ExecutionError, ExecutionErrorCategory, ExecutionRequest, OwnedExecutionAttempt,
1756        PreparationError, ValidatedPreflight,
1757    };
1758
1759    pub(super) struct PlatformBackend;
1760
1761    impl ExecutionBackend for PlatformBackend {
1762        fn containment_support(&self, request: &ExecutionRequest) -> ContainmentSupport {
1763            containment_support(request)
1764        }
1765
1766        fn prepare<'a>(
1767            &'a self,
1768            _request: &ExecutionRequest,
1769            _preflight: &'a ValidatedPreflight,
1770        ) -> Result<OwnedExecutionAttempt<'a>, PreparationError> {
1771            Err(PreparationError::from(ExecutionError::new(
1772                ExecutionErrorCategory::Internal,
1773                "containment backend reported support but execution is not implemented",
1774            )))
1775        }
1776    }
1777
1778    pub(super) fn containment_support(request: &ExecutionRequest) -> ContainmentSupport {
1779        ContainmentSupport::unsupported(
1780            BackendIdentity::new("tapid-runner/no-backend", env!("CARGO_PKG_VERSION"), None)
1781                .expect("static backend identity must satisfy the checked contract"),
1782            std::env::consts::OS,
1783            "no platform execution backend is implemented",
1784            EnforcementDimensions::requested_by(request.policy()),
1785            EnforcementDimensions::none(),
1786            EnforcementDimensions::none(),
1787        )
1788    }
1789}
1790
1791#[cfg(any(target_os = "macos", target_os = "linux"))]
1792pub(crate) use platform_backend::dispatch_private_launcher;
1793
1794#[cfg(test)]
1795#[path = "execution/tests.rs"]
1796mod tests;