Skip to main content

adk_code/embedded_python/
os_access.rs

1//! Host-granted OS access policy for the Monty executors.
2//!
3//! Monty surfaces every operating-system effect a script attempts — filesystem
4//! reads/writes, `os.getenv`/`os.environ`, and `date.today()`/`datetime.now()` —
5//! as an `OsCall` the host must resolve. The drive loop services these calls
6//! **in place**, bounded by the policy described here, and resumes the
7//! interpreter immediately: OS calls never pause a request and are never
8//! surfaced as host functions.
9//!
10//! [`OsAccess`] is that policy:
11//!
12//! - **Filesystem.** Only the directories explicitly granted with
13//!   [`MontyExecutorBuilder::allow_path`](crate::MontyExecutorBuilder::allow_path)
14//!   are reachable, each as read-only or read-write. A script reaches them
15//!   through `pathlib.Path` against the *virtual* mount path. Monty's
16//!   [`MountTable`] enforces the boundary (canonicalization + symlink-escape
17//!   detection), so a script can never touch a host path outside a mount. Any
18//!   access outside every mount raises `PermissionError` (existence checks
19//!   return `False`, matching CPython).
20//! - **Environment.** `os.getenv(name)` and `os.environ` read the explicit
21//!   string map granted at construction. The map is empty by default, so the
22//!   process environment (and any secrets in it) is never exposed.
23//! - **Clock.** `date.today()` and `datetime.now()` read the host clock only
24//!   when [`MontyExecutorBuilder::system_clock`](crate::MontyExecutorBuilder::system_clock)
25//!   was granted, and otherwise raise.
26//!
27//! Network and subprocess access have no Monty OS-call surface at all, so they
28//! remain unavailable regardless of policy.
29//!
30//! # Grants vs. per-request policy
31//!
32//! The builder's grants are the host-authored trust boundary — the *maximum*
33//! access any script can have. The per-request
34//! [`SandboxPolicy`](crate::SandboxPolicy) may only **narrow** within it: see
35//! [`OsAccess::narrowed`]. A request whose policy exceeds the grants is
36//! rejected fail-closed before any code runs.
37
38use 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/// Access mode for a path made available to a script.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum PathAccess {
54    /// Reads succeed; writes raise `PermissionError`.
55    ReadOnly,
56    /// Reads and writes both succeed against the real host directory.
57    ReadWrite,
58}
59
60impl PathAccess {
61    /// Human-readable label for prompts (`"read-only"` / `"read-write"`).
62    #[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    /// The corresponding [`MountMode`] for Monty's mount table.
71    #[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
80/// Whether every `/`-separated segment of an absolute virtual path is a
81/// normal component — non-empty, not `.`, not `..`. The check is
82/// string-level on purpose: Monty's mount table matches virtual paths as
83/// string prefixes, and `Path::components` would silently normalize away the
84/// very forms (`.`, `//`, trailing `/`) that break that matching.
85fn has_only_normal_segments(path: &str) -> bool {
86    path.split('/').skip(1).all(|segment| !segment.is_empty() && segment != "." && segment != "..")
87}
88
89/// Validate mount virtual paths at `build_*()` time.
90///
91/// Monty's mount table matches virtual paths as normalized string prefixes,
92/// so a non-normalized registration (relative, trailing slash, `.` or `..`
93/// components) would pass policy narrowing yet never match at runtime —
94/// every access would raise `PermissionError` instead of failing the build.
95/// Duplicate virtual paths are ambiguous and also rejected.
96pub(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/// One host directory mounted at a virtual path, with an access mode.
125#[derive(Debug, Clone, PartialEq, Eq)]
126pub(crate) struct MountSpec {
127    /// The absolute virtual path a script uses (e.g. `/data`).
128    pub(crate) virtual_path: String,
129    /// The real host directory backing it.
130    pub(crate) host_path: PathBuf,
131    /// Whether the script may write through this mount.
132    pub(crate) access: PathAccess,
133}
134
135/// The OS-access policy the drive loop enforces while advancing a script.
136///
137/// The default is fully sandboxed: no mounts, an empty environment, and no
138/// clock. `PartialEq` supports the REPL policy-consistency check — a session's
139/// effective policy must not vary between calls.
140#[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    /// Narrow these grants by a per-request [`SandboxPolicy`], producing the
149    /// effective policy for one call.
150    ///
151    /// - `FilesystemPolicy::None` / `EnvironmentPolicy::None` grant nothing
152    ///   this call, regardless of what the executor could offer.
153    /// - Requested paths and variables must be covered by the grants. A grant
154    ///   covers its entire directory subtree, so a request for a granted mount
155    ///   *or any subdirectory of one* succeeds — the effective mount is the
156    ///   requested path, backed by the corresponding host subdirectory. The
157    ///   effective access is the weaker of the granted and requested modes
158    ///   only when the request itself asks for read-only.
159    /// - `NetworkPolicy` is not consulted: Monty has no network surface, so
160    ///   every call runs with less network access than any request allows.
161    /// - `working_directory` is rejected — the executors have no working
162    ///   directory; scripts address files through the granted mount paths.
163    /// - A `FilesystemPolicy::Paths` request naming the same root more than
164    ///   once (in either list) is contradictory and rejected — Monty's mount
165    ///   table would resolve the duplicate by insertion order, not by the
166    ///   weaker access.
167    ///
168    /// # Errors
169    ///
170    /// Returns [`ExecutionError::UnsupportedPolicy`] naming the excess path or
171    /// variable when the request exceeds the grants (fail-closed, before any
172    /// code runs).
173    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    /// Find the granted mount covering `root` at the requested access level.
230    ///
231    /// A grant covers its whole subtree: requesting a subdirectory of a
232    /// granted mount yields an effective mount at the requested virtual path,
233    /// backed by the matching host subdirectory. Nested grants resolve to the
234    /// most specific one.
235    fn narrowed_mount(
236        &self,
237        root: &PathBuf,
238        requested: PathAccess,
239    ) -> Result<MountSpec, ExecutionError> {
240        // Reject non-normalized requests before prefix matching: a `..`
241        // component would survive `starts_with` and remap the host path
242        // outside the granted directory, and `.` / empty / trailing-slash
243        // components produce a virtual path Monty's string-prefix mount
244        // matching never hits.
245        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        // A subdirectory request: back the requested virtual path with the
280        // corresponding host subdirectory.
281        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    /// Assemble a fresh [`MountTable`] for one drive segment.
293    ///
294    /// A table is built per segment rather than shared, so concurrent runs of
295    /// the same executor never contend on mount state.
296    ///
297    /// # Errors
298    ///
299    /// Returns [`ExecutionError::InternalError`] if a configured host path does
300    /// not exist or is not a directory — a host misconfiguration, not a script
301    /// error.
302    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    /// Resolve a single OS call against this policy, producing the value (or
318    /// exception) to resume the interpreter with.
319    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
328/// Service one Monty OS call against a host-authored policy: an explicit
329/// environment map, a clock grant, and a [`MountTable`] for filesystem
330/// operations.
331///
332/// This is the shared servicing kernel used by every Monty integration in the
333/// workspace (the executors here and `adk-codeact-monty`'s `MontyRuntime`):
334///
335/// - `os.getenv(name)` / `os.environ` read `environ` only — the host process
336///   environment is never consulted;
337/// - `date.today()` / `datetime.now()` read the host clock when `system_clock`
338///   is `true`, and otherwise raise a catchable `OSError`;
339/// - everything else is a filesystem operation routed through `mounts`. When
340///   no mount covers the path, existence checks return `False` (CPython
341///   semantics) and any other access raises `PermissionError`.
342///
343/// The call is consumed: [`MountTable::handle_os_call`] moves a covered
344/// write's payload into the backend without a copy, and hands the call back
345/// ([`MountCallOutcome::NotHandled`]) when no mount covers it so the fallback
346/// can render it.
347pub 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        // Clock not granted: raise a catchable OSError explaining why.
359        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        // Everything else is a filesystem operation routed through the
368        // mount table.
369        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            // No mount covers this path. Existence checks report `False`
373            // (CPython semantics); anything else is a permission error.
374            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
382/// Look up an environment variable, falling back to the call's `default`
383/// (which Monty already projected to a [`MontyObject`]) when it is unset.
384fn 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
391/// Project the whole environment to a `dict[str, str]` for `os.environ`.
392fn 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
400/// Service `date.today()` from the host's local clock.
401fn 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
410/// Service `datetime.now(tz=...)` from the host clock.
411///
412/// `tz` is `None` for a naive local datetime, or a fixed-offset
413/// [`MontyTimeZone`] for an aware one.
414fn 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
437/// Build a [`MontyDateTime`] from a chrono naive datetime and optional offset.
438fn 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        // chrono represents leap seconds as nanosecond() >= 10^9; clamp so
451        // the microsecond field stays within MontyDateTime's valid range.
452        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        // A read-write grant narrows to the requested read-only access.
518        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        // `starts_with` is component-wise: /data-x must not match grant /data.
656        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        // /out is granted read-write, so both narrowings would individually
684        // succeed — the duplicate itself must be the rejection.
685        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        // The same root twice within one list is equally contradictory.
702        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}