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