1use std::collections::{BTreeMap, BTreeSet};
39use std::path::PathBuf;
40
41use chrono::{Datelike, FixedOffset, Timelike, Utc};
42use monty_fs::{MountCallOutcome, MountMode, MountTable};
43use monty_types::{
44 DictPairs, ExcType, ExtFunctionResult, GetenvArgs, MontyDate, MontyDateTime, MontyException,
45 MontyObject, MontyTimeZone, OsFunctionCall,
46};
47
48use super::host_fn::MontyBuildError;
49use crate::{EnvironmentPolicy, ExecutionError, FilesystemPolicy, SandboxPolicy};
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum PathAccess {
54 ReadOnly,
56 ReadWrite,
58}
59
60impl PathAccess {
61 #[must_use]
63 pub fn label(self) -> &'static str {
64 match self {
65 Self::ReadOnly => "read-only",
66 Self::ReadWrite => "read-write",
67 }
68 }
69
70 #[must_use]
72 pub fn mount_mode(self) -> MountMode {
73 match self {
74 Self::ReadOnly => MountMode::ReadOnly,
75 Self::ReadWrite => MountMode::ReadWrite,
76 }
77 }
78}
79
80fn has_only_normal_segments(path: &str) -> bool {
86 path.split('/').skip(1).all(|segment| !segment.is_empty() && segment != "." && segment != "..")
87}
88
89pub(crate) fn validate_mounts(mounts: &[MountSpec]) -> Result<(), MontyBuildError> {
97 let mut seen = BTreeSet::new();
98 for spec in mounts {
99 let path = &spec.virtual_path;
100 let invalid = |reason: &str| MontyBuildError::InvalidMountPath {
101 path: path.clone(),
102 reason: reason.to_string(),
103 };
104 if !path.starts_with('/') {
105 return Err(invalid("the path must be absolute"));
106 }
107 if path == "/" {
108 return Err(invalid(
109 "mounting the filesystem root is not supported; mount a subdirectory",
110 ));
111 }
112 if !has_only_normal_segments(path) {
113 return Err(invalid(
114 "'.', '..', empty, and trailing-slash path components are not allowed",
115 ));
116 }
117 if !seen.insert(path.as_str()) {
118 return Err(MontyBuildError::DuplicateMountPath(path.clone()));
119 }
120 }
121 Ok(())
122}
123
124#[derive(Debug, Clone, PartialEq, Eq)]
126pub(crate) struct MountSpec {
127 pub(crate) virtual_path: String,
129 pub(crate) host_path: PathBuf,
131 pub(crate) access: PathAccess,
133}
134
135#[derive(Debug, Clone, Default, PartialEq, Eq)]
141pub(crate) struct OsAccess {
142 pub(crate) mounts: Vec<MountSpec>,
143 pub(crate) environ: BTreeMap<String, String>,
144 pub(crate) system_clock: bool,
145}
146
147impl OsAccess {
148 pub(crate) fn narrowed(&self, policy: &SandboxPolicy) -> Result<Self, ExecutionError> {
174 if let Some(dir) = &policy.working_directory {
175 return Err(ExecutionError::UnsupportedPolicy(format!(
176 "working_directory {dir:?} is not supported by the Monty executors; \
177 scripts address files through the granted mount paths"
178 )));
179 }
180 let mounts = match &policy.filesystem {
181 FilesystemPolicy::None => Vec::new(),
182 FilesystemPolicy::WorkspaceReadOnly { root } => {
183 vec![self.narrowed_mount(root, PathAccess::ReadOnly)?]
184 }
185 FilesystemPolicy::WorkspaceReadWrite { root } => {
186 vec![self.narrowed_mount(root, PathAccess::ReadWrite)?]
187 }
188 FilesystemPolicy::Paths { read_only, read_write } => {
189 let mut seen = BTreeSet::new();
190 let mut mounts = Vec::with_capacity(read_only.len() + read_write.len());
191 for (roots, access) in
192 [(read_only, PathAccess::ReadOnly), (read_write, PathAccess::ReadWrite)]
193 {
194 for root in roots {
195 if !seen.insert(root.as_path()) {
196 return Err(ExecutionError::UnsupportedPolicy(format!(
197 "path {root:?} is requested more than once; list each root \
198 exactly once, in either read_only or read_write"
199 )));
200 }
201 mounts.push(self.narrowed_mount(root, access)?);
202 }
203 }
204 mounts
205 }
206 };
207
208 let environ = match &policy.environment {
209 EnvironmentPolicy::None => BTreeMap::new(),
210 EnvironmentPolicy::AllowList(names) => {
211 let mut environ = BTreeMap::new();
212 for name in names {
213 let Some(value) = self.environ.get(name) else {
214 return Err(ExecutionError::UnsupportedPolicy(format!(
215 "environment variable '{name}' is not granted on this executor; \
216 granted variables: {:?}",
217 self.environ.keys().collect::<Vec<_>>()
218 )));
219 };
220 environ.insert(name.clone(), value.clone());
221 }
222 environ
223 }
224 };
225
226 Ok(Self { mounts, environ, system_clock: self.system_clock })
227 }
228
229 fn narrowed_mount(
236 &self,
237 root: &PathBuf,
238 requested: PathAccess,
239 ) -> Result<MountSpec, ExecutionError> {
240 let root_str = root.to_str().filter(|s| s.starts_with('/'));
246 let Some(root_str) = root_str.filter(|s| has_only_normal_segments(s)) else {
247 return Err(ExecutionError::UnsupportedPolicy(format!(
248 "path {root:?} must be a normalized absolute path without '.', '..', empty, \
249 or trailing-slash components"
250 )));
251 };
252 let Some(grant) = self
253 .mounts
254 .iter()
255 .filter(|spec| root.starts_with(&spec.virtual_path))
256 .max_by_key(|spec| spec.virtual_path.len())
257 else {
258 return Err(ExecutionError::UnsupportedPolicy(format!(
259 "path {root:?} is not covered by any grant on this executor; granted mounts \
260 (each covering its subtree): {:?}",
261 self.mounts.iter().map(|m| m.virtual_path.as_str()).collect::<Vec<_>>()
262 )));
263 };
264 if requested == PathAccess::ReadWrite && grant.access == PathAccess::ReadOnly {
265 return Err(ExecutionError::UnsupportedPolicy(format!(
266 "path {root:?} is granted read-only on this executor; \
267 the request asks for read-write access"
268 )));
269 }
270 let relative = root.strip_prefix(&grant.virtual_path).map_err(|_| {
271 ExecutionError::InternalError(format!(
272 "grant '{}' matched {root:?} but is not its prefix",
273 grant.virtual_path
274 ))
275 })?;
276 if relative.as_os_str().is_empty() {
277 return Ok(MountSpec { access: requested, ..grant.clone() });
278 }
279 let host_path = grant.host_path.join(relative);
282 if !host_path.is_dir() {
283 return Err(ExecutionError::UnsupportedPolicy(format!(
284 "path {root:?} is covered by granted mount '{}', but the backing host \
285 directory {host_path:?} does not exist",
286 grant.virtual_path
287 )));
288 }
289 Ok(MountSpec { virtual_path: root_str.to_string(), host_path, access: requested })
290 }
291
292 pub(crate) fn build_mount_table(&self) -> Result<MountTable, ExecutionError> {
303 let mut table = MountTable::new();
304 for spec in &self.mounts {
305 table
306 .mount(&spec.virtual_path, &spec.host_path, spec.access.mount_mode(), None)
307 .map_err(|err| {
308 ExecutionError::InternalError(format!(
309 "failed to mount {:?} at {:?}: {err}",
310 spec.host_path, spec.virtual_path
311 ))
312 })?;
313 }
314 Ok(table)
315 }
316
317 pub(crate) fn resolve(
320 &self,
321 call: OsFunctionCall,
322 mounts: &mut MountTable,
323 ) -> ExtFunctionResult {
324 resolve_os_call(call, &self.environ, self.system_clock, mounts)
325 }
326}
327
328pub fn resolve_os_call(
348 call: OsFunctionCall,
349 environ: &BTreeMap<String, String>,
350 system_clock: bool,
351 mounts: &mut MountTable,
352) -> ExtFunctionResult {
353 match call {
354 OsFunctionCall::Getenv(args) => getenv(environ, args),
355 OsFunctionCall::GetEnviron => get_environ(environ),
356 OsFunctionCall::DateToday if system_clock => date_today(),
357 OsFunctionCall::DateTimeNow(ref tz) if system_clock => datetime_now(tz),
358 call @ (OsFunctionCall::DateToday | OsFunctionCall::DateTimeNow(_)) => {
360 ExtFunctionResult::Error(MontyException::new(
361 ExcType::OSError,
362 Some(format!(
363 "{call:?} is not available: the host clock is not granted by the host policy"
364 )),
365 ))
366 }
367 call => match mounts.handle_os_call(call) {
370 MountCallOutcome::Handled(Ok(value)) => ExtFunctionResult::Return(value),
371 MountCallOutcome::Handled(Err(err)) => ExtFunctionResult::Error(err.into_exception()),
372 MountCallOutcome::NotHandled(call) if call.is_existence_check() => {
375 ExtFunctionResult::Return(MontyObject::Bool(false))
376 }
377 MountCallOutcome::NotHandled(call) => ExtFunctionResult::Error(call.on_no_handler()),
378 },
379 }
380}
381
382fn getenv(environ: &BTreeMap<String, String>, args: GetenvArgs) -> ExtFunctionResult {
385 match environ.get(&args.key) {
386 Some(value) => ExtFunctionResult::Return(MontyObject::String(value.clone())),
387 None => ExtFunctionResult::Return(args.default),
388 }
389}
390
391fn get_environ(environ: &BTreeMap<String, String>) -> ExtFunctionResult {
393 let pairs: Vec<(MontyObject, MontyObject)> = environ
394 .iter()
395 .map(|(key, value)| (MontyObject::String(key.clone()), MontyObject::String(value.clone())))
396 .collect();
397 ExtFunctionResult::Return(MontyObject::Dict(DictPairs::from(pairs)))
398}
399
400fn date_today() -> ExtFunctionResult {
402 let today = chrono::Local::now().date_naive();
403 ExtFunctionResult::Return(MontyObject::Date(MontyDate {
404 year: today.year(),
405 month: today.month() as u8,
406 day: today.day() as u8,
407 }))
408}
409
410fn datetime_now(tz: &Option<MontyTimeZone>) -> ExtFunctionResult {
415 match tz {
416 None => {
417 let now = chrono::Local::now().naive_local();
418 ExtFunctionResult::Return(MontyObject::DateTime(monty_datetime(&now, None, None)))
419 }
420 Some(zone) => {
421 let Some(offset) = FixedOffset::east_opt(zone.offset_seconds) else {
422 return ExtFunctionResult::Error(MontyException::new(
423 ExcType::ValueError,
424 Some(format!("invalid timezone offset: {} seconds", zone.offset_seconds)),
425 ));
426 };
427 let now = Utc::now().with_timezone(&offset).naive_local();
428 ExtFunctionResult::Return(MontyObject::DateTime(monty_datetime(
429 &now,
430 Some(zone.offset_seconds),
431 zone.name.clone(),
432 )))
433 }
434 }
435}
436
437fn monty_datetime(
439 naive: &chrono::NaiveDateTime,
440 offset_seconds: Option<i32>,
441 timezone_name: Option<String>,
442) -> MontyDateTime {
443 MontyDateTime {
444 year: naive.year(),
445 month: naive.month() as u8,
446 day: naive.day() as u8,
447 hour: naive.hour() as u8,
448 minute: naive.minute() as u8,
449 second: naive.second() as u8,
450 microsecond: (naive.nanosecond() / 1_000).min(999_999),
453 offset_seconds,
454 timezone_name,
455 }
456}
457
458#[cfg(test)]
459mod tests {
460 use super::*;
461 use std::time::Duration;
462
463 use crate::NetworkPolicy;
464
465 fn grants() -> OsAccess {
466 OsAccess {
467 mounts: vec![
468 MountSpec {
469 virtual_path: "/data".to_string(),
470 host_path: PathBuf::from("/tmp/data"),
471 access: PathAccess::ReadOnly,
472 },
473 MountSpec {
474 virtual_path: "/out".to_string(),
475 host_path: PathBuf::from("/tmp/out"),
476 access: PathAccess::ReadWrite,
477 },
478 ],
479 environ: BTreeMap::from([("PROJECT".to_string(), "acme".to_string())]),
480 system_clock: true,
481 }
482 }
483
484 fn policy(filesystem: FilesystemPolicy, environment: EnvironmentPolicy) -> SandboxPolicy {
485 SandboxPolicy {
486 network: NetworkPolicy::Disabled,
487 filesystem,
488 environment,
489 timeout: Duration::from_secs(5),
490 max_stdout_bytes: 1024,
491 max_stderr_bytes: 1024,
492 working_directory: None,
493 }
494 }
495
496 #[test]
497 fn none_policies_grant_nothing() {
498 let effective =
499 grants().narrowed(&policy(FilesystemPolicy::None, EnvironmentPolicy::None)).unwrap();
500 assert_eq!(
501 effective,
502 OsAccess { mounts: Vec::new(), environ: BTreeMap::new(), system_clock: true }
503 );
504 }
505
506 #[test]
507 fn request_within_grants_intersects() {
508 let effective = grants()
509 .narrowed(&policy(
510 FilesystemPolicy::Paths {
511 read_only: vec![PathBuf::from("/out")],
512 read_write: vec![],
513 },
514 EnvironmentPolicy::AllowList(vec!["PROJECT".to_string()]),
515 ))
516 .unwrap();
517 assert_eq!(effective.mounts.len(), 1);
519 assert_eq!(effective.mounts[0].access, PathAccess::ReadOnly);
520 assert_eq!(effective.environ.get("PROJECT").map(String::as_str), Some("acme"));
521 }
522
523 #[test]
524 fn ungranted_path_is_rejected_naming_the_excess() {
525 let err = grants()
526 .narrowed(&policy(
527 FilesystemPolicy::WorkspaceReadOnly { root: PathBuf::from("/secret") },
528 EnvironmentPolicy::None,
529 ))
530 .unwrap_err();
531 match err {
532 ExecutionError::UnsupportedPolicy(msg) => assert!(msg.contains("/secret")),
533 other => panic!("expected UnsupportedPolicy, got {other:?}"),
534 }
535 }
536
537 #[test]
538 fn write_request_on_read_only_grant_is_rejected() {
539 let err = grants()
540 .narrowed(&policy(
541 FilesystemPolicy::WorkspaceReadWrite { root: PathBuf::from("/data") },
542 EnvironmentPolicy::None,
543 ))
544 .unwrap_err();
545 match err {
546 ExecutionError::UnsupportedPolicy(msg) => {
547 assert!(msg.contains("/data"));
548 assert!(msg.contains("read-only"));
549 }
550 other => panic!("expected UnsupportedPolicy, got {other:?}"),
551 }
552 }
553
554 #[test]
555 fn ungranted_environment_variable_is_rejected_naming_the_excess() {
556 let err = grants()
557 .narrowed(&policy(
558 FilesystemPolicy::None,
559 EnvironmentPolicy::AllowList(vec!["SECRET".to_string()]),
560 ))
561 .unwrap_err();
562 match err {
563 ExecutionError::UnsupportedPolicy(msg) => assert!(msg.contains("SECRET")),
564 other => panic!("expected UnsupportedPolicy, got {other:?}"),
565 }
566 }
567
568 #[test]
569 fn getenv_returns_granted_value_or_default() {
570 let access = grants();
571 let hit = getenv(
572 &access.environ,
573 GetenvArgs { key: "PROJECT".to_string(), default: MontyObject::None },
574 );
575 assert!(matches!(hit, ExtFunctionResult::Return(MontyObject::String(s)) if s == "acme"));
576 let miss = getenv(
577 &access.environ,
578 GetenvArgs { key: "MISSING".to_string(), default: MontyObject::None },
579 );
580 assert!(matches!(miss, ExtFunctionResult::Return(MontyObject::None)));
581 }
582
583 #[test]
584 fn disabled_clock_raises_os_error() {
585 let access = OsAccess::default();
586 let mut mounts = access.build_mount_table().unwrap();
587 let result = access.resolve(OsFunctionCall::DateToday, &mut mounts);
588 match result {
589 ExtFunctionResult::Error(exc) => assert_eq!(exc.exc_type(), ExcType::OSError),
590 other => panic!("expected an OSError, got {other:?}"),
591 }
592 }
593
594 #[test]
595 fn enabled_clock_returns_a_date() {
596 let access = OsAccess { system_clock: true, ..OsAccess::default() };
597 let mut mounts = access.build_mount_table().unwrap();
598 let result = access.resolve(OsFunctionCall::DateToday, &mut mounts);
599 assert!(matches!(result, ExtFunctionResult::Return(MontyObject::Date(_))));
600 }
601
602 #[test]
603 fn subdirectory_of_a_grant_is_covered_and_remapped() {
604 let dir = tempfile::tempdir().unwrap();
605 std::fs::create_dir(dir.path().join("sub")).unwrap();
606 let access = OsAccess {
607 mounts: vec![MountSpec {
608 virtual_path: "/data".to_string(),
609 host_path: dir.path().to_path_buf(),
610 access: PathAccess::ReadWrite,
611 }],
612 ..OsAccess::default()
613 };
614 let effective = access
615 .narrowed(&policy(
616 FilesystemPolicy::WorkspaceReadOnly { root: PathBuf::from("/data/sub") },
617 EnvironmentPolicy::None,
618 ))
619 .unwrap();
620 assert_eq!(
621 effective.mounts,
622 vec![MountSpec {
623 virtual_path: "/data/sub".to_string(),
624 host_path: dir.path().join("sub"),
625 access: PathAccess::ReadOnly,
626 }]
627 );
628 }
629
630 #[test]
631 fn subdirectory_request_without_backing_directory_is_rejected() {
632 let dir = tempfile::tempdir().unwrap();
633 let access = OsAccess {
634 mounts: vec![MountSpec {
635 virtual_path: "/data".to_string(),
636 host_path: dir.path().to_path_buf(),
637 access: PathAccess::ReadOnly,
638 }],
639 ..OsAccess::default()
640 };
641 let err = access
642 .narrowed(&policy(
643 FilesystemPolicy::WorkspaceReadOnly { root: PathBuf::from("/data/missing") },
644 EnvironmentPolicy::None,
645 ))
646 .unwrap_err();
647 match err {
648 ExecutionError::UnsupportedPolicy(msg) => assert!(msg.contains("does not exist")),
649 other => panic!("expected UnsupportedPolicy, got {other:?}"),
650 }
651 }
652
653 #[test]
654 fn sibling_with_a_shared_name_prefix_is_not_covered() {
655 let err = grants()
657 .narrowed(&policy(
658 FilesystemPolicy::WorkspaceReadOnly { root: PathBuf::from("/data-x") },
659 EnvironmentPolicy::None,
660 ))
661 .unwrap_err();
662 assert!(matches!(err, ExecutionError::UnsupportedPolicy(_)));
663 }
664
665 #[test]
666 fn requested_paths_with_dot_or_dotdot_components_are_rejected() {
667 for bad in ["/data/..", "/data/../out", "/data/./sub", "relative/path"] {
668 let err = grants()
669 .narrowed(&policy(
670 FilesystemPolicy::WorkspaceReadOnly { root: PathBuf::from(bad) },
671 EnvironmentPolicy::None,
672 ))
673 .unwrap_err();
674 assert!(
675 matches!(err, ExecutionError::UnsupportedPolicy(_)),
676 "expected UnsupportedPolicy for {bad:?}, got {err:?}"
677 );
678 }
679 }
680
681 #[test]
682 fn duplicate_roots_across_the_paths_request_are_rejected() {
683 let err = grants()
686 .narrowed(&policy(
687 FilesystemPolicy::Paths {
688 read_only: vec![PathBuf::from("/out")],
689 read_write: vec![PathBuf::from("/out")],
690 },
691 EnvironmentPolicy::None,
692 ))
693 .unwrap_err();
694 match err {
695 ExecutionError::UnsupportedPolicy(msg) => {
696 assert!(msg.contains("more than once"), "message: {msg}");
697 }
698 other => panic!("expected UnsupportedPolicy, got {other:?}"),
699 }
700
701 let err = grants()
703 .narrowed(&policy(
704 FilesystemPolicy::Paths {
705 read_only: vec![PathBuf::from("/data"), PathBuf::from("/data")],
706 read_write: vec![],
707 },
708 EnvironmentPolicy::None,
709 ))
710 .unwrap_err();
711 assert!(matches!(err, ExecutionError::UnsupportedPolicy(_)));
712 }
713
714 #[test]
715 fn working_directory_request_is_rejected() {
716 let mut request = policy(FilesystemPolicy::None, EnvironmentPolicy::None);
717 request.working_directory = Some(PathBuf::from("/work"));
718 let err = grants().narrowed(&request).unwrap_err();
719 match err {
720 ExecutionError::UnsupportedPolicy(msg) => assert!(msg.contains("working_directory")),
721 other => panic!("expected UnsupportedPolicy, got {other:?}"),
722 }
723 }
724
725 #[test]
726 fn get_environ_projects_the_whole_granted_map() {
727 let result = get_environ(&grants().environ);
728 let ExtFunctionResult::Return(MontyObject::Dict(pairs)) = result else {
729 panic!("expected a dict");
730 };
731 let entries: Vec<_> = (&pairs).into_iter().collect();
732 assert_eq!(
733 entries,
734 vec![&(
735 MontyObject::String("PROJECT".to_string()),
736 MontyObject::String("acme".to_string())
737 )]
738 );
739 }
740
741 #[test]
742 fn datetime_now_honors_a_fixed_offset_and_rejects_an_invalid_one() {
743 let valid = datetime_now(&Some(MontyTimeZone {
744 offset_seconds: 3600,
745 name: Some("CET".to_string()),
746 }));
747 match valid {
748 ExtFunctionResult::Return(MontyObject::DateTime(dt)) => {
749 assert_eq!(dt.offset_seconds, Some(3600));
750 assert!(dt.microsecond <= 999_999);
751 }
752 other => panic!("expected a datetime, got {other:?}"),
753 }
754 let invalid = datetime_now(&Some(MontyTimeZone { offset_seconds: 999_999, name: None }));
755 match invalid {
756 ExtFunctionResult::Error(exc) => assert_eq!(exc.exc_type(), ExcType::ValueError),
757 other => panic!("expected a ValueError, got {other:?}"),
758 }
759 }
760
761 #[test]
762 fn validate_mounts_rejects_non_normalized_virtual_paths() {
763 let spec = |virtual_path: &str| MountSpec {
764 virtual_path: virtual_path.to_string(),
765 host_path: PathBuf::from("/tmp/data"),
766 access: PathAccess::ReadOnly,
767 };
768 for bad in ["data", "/", "/data/", "/data//sub", "/data/../out", "/data/./sub"] {
769 let err = validate_mounts(&[spec(bad)]).unwrap_err();
770 assert!(
771 matches!(err, MontyBuildError::InvalidMountPath { .. }),
772 "expected InvalidMountPath for {bad:?}, got {err:?}"
773 );
774 }
775 let err = validate_mounts(&[spec("/data"), spec("/data")]).unwrap_err();
776 assert_eq!(err, MontyBuildError::DuplicateMountPath("/data".to_string()));
777 validate_mounts(&[spec("/data"), spec("/data/nested")]).unwrap();
778 }
779}