Skip to main content

aither_sandbox/
container.rs

1//! Typed container runtime specifications shared by host integrations.
2//!
3//! This module defines type-safe container image, mount, and launch specs so
4//! application code can construct container requests without relying on
5//! positional arguments or ad-hoc string conventions.
6
7use std::path::{Component, Path, PathBuf};
8
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11use typed_path::{Utf8UnixPath, Utf8UnixPathBuf};
12
13/// An absolute POSIX path inside a container.
14///
15/// Container paths are joined with `/` whatever the host platform is, so a
16/// host [`Path`] can never stand in for one.
17#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
18#[serde(try_from = "String", into = "String")]
19#[schemars(with = "String")]
20pub struct ContainerPath(Utf8UnixPathBuf);
21
22/// A string that is not an absolute POSIX path.
23#[derive(Debug, thiserror::Error)]
24#[error("container path must be absolute: {0}")]
25pub struct RelativeContainerPath(pub String);
26
27impl ContainerPath {
28    /// The container's filesystem root, `/`.
29    #[must_use]
30    pub fn root() -> Self {
31        Self(Utf8UnixPathBuf::from("/"))
32    }
33
34    /// Parses an absolute POSIX path.
35    ///
36    /// # Errors
37    /// Returns [`RelativeContainerPath`] when `path` does not start at `/`.
38    pub fn new(path: impl Into<String>) -> Result<Self, RelativeContainerPath> {
39        let path = Utf8UnixPathBuf::from(path.into());
40        if path.is_absolute() {
41            Ok(Self(path))
42        } else {
43            Err(RelativeContainerPath(path.into_string()))
44        }
45    }
46
47    /// Appends `path` with POSIX separators; an absolute `path` replaces this one,
48    /// so the result is always absolute.
49    #[must_use]
50    pub fn join(&self, path: impl AsRef<str>) -> Self {
51        Self(self.0.join(path.as_ref()))
52    }
53
54    /// The containing directory, or `None` at the root.
55    #[must_use]
56    pub fn parent(&self) -> Option<Self> {
57        self.0.parent().map(|parent| Self(parent.to_path_buf()))
58    }
59
60    /// The path as POSIX text.
61    #[must_use]
62    pub fn as_str(&self) -> &str {
63        self.0.as_str()
64    }
65
66    /// The path as a POSIX path.
67    #[must_use]
68    pub fn as_unix_path(&self) -> &Utf8UnixPath {
69        &self.0
70    }
71}
72
73impl std::fmt::Display for ContainerPath {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        f.write_str(self.as_str())
76    }
77}
78
79impl TryFrom<String> for ContainerPath {
80    type Error = RelativeContainerPath;
81
82    fn try_from(path: String) -> Result<Self, Self::Error> {
83        Self::new(path)
84    }
85}
86
87impl From<ContainerPath> for String {
88    fn from(path: ContainerPath) -> Self {
89        path.0.into_string()
90    }
91}
92
93/// Supported Docker-compatible runtime kinds.
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
95#[serde(rename_all = "lowercase")]
96pub enum ContainerRuntimeKind {
97    /// `OrbStack`, a macOS-native Docker-compatible runtime.
98    OrbStack,
99    /// Podman, the daemonless Docker-compatible runtime.
100    Podman,
101    /// Docker Engine itself.
102    Docker,
103}
104
105impl std::fmt::Display for ContainerRuntimeKind {
106    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107        match self {
108            Self::OrbStack => write!(f, "OrbStack"),
109            Self::Podman => write!(f, "Podman"),
110            Self::Docker => write!(f, "Docker"),
111        }
112    }
113}
114
115/// Runtime selection order.
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
117pub struct RuntimePreference {
118    /// Runtimes to try, most preferred first.
119    pub order: Vec<ContainerRuntimeKind>,
120}
121
122impl Default for RuntimePreference {
123    fn default() -> Self {
124        Self {
125            order: vec![
126                ContainerRuntimeKind::OrbStack,
127                ContainerRuntimeKind::Podman,
128                ContainerRuntimeKind::Docker,
129            ],
130        }
131    }
132}
133
134/// Filesystem mount access policy.
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
136#[serde(rename_all = "snake_case")]
137pub enum MountAccess {
138    /// The container may read the mount but not write to it.
139    ReadOnly,
140    /// The container may read and write the mount.
141    ReadWrite,
142}
143
144impl MountAccess {
145    /// Whether this policy forbids writes.
146    #[must_use]
147    pub const fn read_only(self) -> bool {
148        matches!(self, Self::ReadOnly)
149    }
150}
151
152/// A host path mounted into a container path.
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
154pub struct MountSpec {
155    /// Path on the host to expose.
156    pub host_path: PathBuf,
157    /// Path inside the container where it appears.
158    pub container_path: ContainerPath,
159    /// Whether the container may write to it.
160    pub access: MountAccess,
161}
162
163/// Declarative host/container root pair used to create validated child mounts.
164#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
165pub struct MountRoot {
166    /// Base directory on the host.
167    pub host_root: PathBuf,
168    /// Directory the host root maps to inside the container.
169    pub container_root: ContainerPath,
170}
171
172/// Mount-root composition error.
173#[derive(Debug, thiserror::Error)]
174pub enum MountRootError {
175    /// The relative path was empty, which would mount the root itself.
176    #[error("relative path must not be empty")]
177    /// Relative path was empty.
178    EmptyRelativePath,
179    /// An absolute path was given where a path relative to the root was expected.
180    #[error("relative path must not be absolute: {0}")]
181    /// Relative path was absolute.
182    AbsoluteRelativePath(PathBuf),
183    /// The path contained `..`, which would escape the mount root.
184    #[error("relative path must not contain parent traversal: {0}")]
185    /// Relative path contained parent traversal.
186    ParentTraversal(PathBuf),
187    /// A component is not UTF-8, so it has no container path spelling.
188    #[error("relative path must be valid UTF-8: {0}")]
189    /// Relative path contained a non-UTF-8 component.
190    NonUtf8(PathBuf),
191    /// A container path that is not beneath the mount's container root.
192    #[error("{path} is not beneath the mounted container directory {root}")]
193    OutsideContainerRoot {
194        /// The container path.
195        path: String,
196        /// The mount root's container directory.
197        root: String,
198    },
199    /// A host path that is not beneath the mount root.
200    #[error("{} is not beneath the mount root {}", .path.display(), .root.display())]
201    OutsideRoot {
202        /// The host path.
203        path: PathBuf,
204        /// The mount root's host directory.
205        root: PathBuf,
206    },
207}
208
209impl MountRoot {
210    /// Pairs a host directory with the container path it maps to.
211    #[must_use]
212    pub fn new(host_root: impl Into<PathBuf>, container_root: ContainerPath) -> Self {
213        Self {
214            host_root: host_root.into(),
215            container_root,
216        }
217    }
218
219    /// Derives a mount for a path beneath this root.
220    ///
221    /// # Errors
222    ///
223    /// Returns [`MountRootError`] if `relative` is empty, absolute, or contains
224    /// a `..` component — any of which would place the mount outside the root —
225    /// or if a component is not UTF-8.
226    pub fn child(
227        &self,
228        relative: impl AsRef<Path>,
229        access: MountAccess,
230    ) -> Result<MountSpec, MountRootError> {
231        let relative = relative.as_ref();
232        let container_path = Self::container_child(&self.container_root, relative)?;
233        let host_path = self.host_root.join(relative);
234        Ok(match access {
235            MountAccess::ReadOnly => MountSpec::read_only(host_path, container_path),
236            MountAccess::ReadWrite => MountSpec::read_write(host_path, container_path),
237        })
238    }
239
240    /// Where the host path `host`, the root itself or a path beneath it,
241    /// appears inside the container.
242    ///
243    /// # Errors
244    ///
245    /// Returns [`MountRootError::OutsideRoot`] if `host` is not beneath the
246    /// root, and the conditions of [`Self::child`] for what lies beneath it.
247    pub fn container_path(&self, host: &Path) -> Result<ContainerPath, MountRootError> {
248        let relative =
249            host.strip_prefix(&self.host_root)
250                .map_err(|_| MountRootError::OutsideRoot {
251                    path: host.to_path_buf(),
252                    root: self.host_root.clone(),
253                })?;
254        if relative.as_os_str().is_empty() {
255            return Ok(self.container_root.clone());
256        }
257        Self::container_child(&self.container_root, relative)
258    }
259
260    /// Where the container path `container`, the container root itself or a
261    /// path beneath it, lies on the host.
262    ///
263    /// # Errors
264    ///
265    /// Returns [`MountRootError::OutsideContainerRoot`] if `container` is not
266    /// beneath the container root, and [`MountRootError::ParentTraversal`] if
267    /// what lies beneath it contains `..`.
268    pub fn host_path(&self, container: &ContainerPath) -> Result<PathBuf, MountRootError> {
269        let relative = container
270            .as_unix_path()
271            .strip_prefix(self.container_root.as_unix_path())
272            .map_err(|_| MountRootError::OutsideContainerRoot {
273                path: container.to_string(),
274                root: self.container_root.to_string(),
275            })?;
276        let mut host = self.host_root.clone();
277        for name in relative
278            .as_str()
279            .split('/')
280            .filter(|name| !name.is_empty() && *name != ".")
281        {
282            if name == ".." {
283                return Err(MountRootError::ParentTraversal(PathBuf::from(
284                    container.as_str(),
285                )));
286            }
287            host.push(name);
288        }
289        Ok(host)
290    }
291
292    /// Derives a read-only mount beneath this root.
293    ///
294    /// # Errors
295    ///
296    /// Same conditions as [`Self::child`].
297    pub fn read_only_child(&self, relative: impl AsRef<Path>) -> Result<MountSpec, MountRootError> {
298        self.child(relative, MountAccess::ReadOnly)
299    }
300
301    /// Derives a writable mount beneath this root.
302    ///
303    /// # Errors
304    ///
305    /// Same conditions as [`Self::child`].
306    pub fn read_write_child(
307        &self,
308        relative: impl AsRef<Path>,
309    ) -> Result<MountSpec, MountRootError> {
310        self.child(relative, MountAccess::ReadWrite)
311    }
312
313    /// Joins the host-relative `path` onto `root` one component at a time, so
314    /// the container side uses POSIX separators whatever the host spells.
315    fn container_child(root: &ContainerPath, path: &Path) -> Result<ContainerPath, MountRootError> {
316        let mut container_path = root.clone();
317        let mut named = false;
318        for component in path.components() {
319            match component {
320                Component::Normal(name) => {
321                    let name = name
322                        .to_str()
323                        .ok_or_else(|| MountRootError::NonUtf8(path.to_path_buf()))?;
324                    container_path = container_path.join(name);
325                    named = true;
326                }
327                Component::CurDir => {}
328                Component::ParentDir => {
329                    return Err(MountRootError::ParentTraversal(path.to_path_buf()));
330                }
331                Component::RootDir | Component::Prefix(_) => {
332                    return Err(MountRootError::AbsoluteRelativePath(path.to_path_buf()));
333                }
334            }
335        }
336        if named {
337            Ok(container_path)
338        } else {
339            Err(MountRootError::EmptyRelativePath)
340        }
341    }
342}
343
344impl MountSpec {
345    /// Mounts a host path into the container without write access.
346    #[must_use]
347    pub fn read_only(host_path: impl Into<PathBuf>, container_path: ContainerPath) -> Self {
348        Self {
349            host_path: host_path.into(),
350            container_path,
351            access: MountAccess::ReadOnly,
352        }
353    }
354
355    /// Mounts a host path into the container with write access.
356    #[must_use]
357    pub fn read_write(host_path: impl Into<PathBuf>, container_path: ContainerPath) -> Self {
358        Self {
359            host_path: host_path.into(),
360            container_path,
361            access: MountAccess::ReadWrite,
362        }
363    }
364}
365
366/// Image build specification.
367#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
368pub struct ContainerImageSpec {
369    /// Tag to apply to the built image.
370    pub tag: String,
371    /// Directory used as the build context.
372    pub context_dir: PathBuf,
373    /// Dockerfile to build, if not the default one in the context directory.
374    #[serde(default, skip_serializing_if = "Option::is_none")]
375    pub dockerfile: Option<PathBuf>,
376}
377
378impl ContainerImageSpec {
379    /// Describes an image built from `context_dir` and tagged `tag`.
380    #[must_use]
381    pub fn new(tag: impl Into<String>, context_dir: impl Into<PathBuf>) -> Self {
382        Self {
383            tag: tag.into(),
384            context_dir: context_dir.into(),
385            dockerfile: None,
386        }
387    }
388
389    /// Builds from a specific Dockerfile rather than the context default.
390    #[must_use]
391    pub fn with_dockerfile(mut self, dockerfile: impl Into<PathBuf>) -> Self {
392        self.dockerfile = Some(dockerfile.into());
393        self
394    }
395}
396
397/// Container launch specification.
398#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
399pub struct ContainerLaunchSpec {
400    /// Name to give the running container.
401    pub name: String,
402    /// Image to run.
403    pub image: String,
404    /// Directory the container treats as its workspace.
405    pub workspace: PathBuf,
406    /// Additional host paths to expose.
407    #[serde(default)]
408    pub mounts: Vec<MountSpec>,
409    /// Environment entries, each formatted as `KEY=value`.
410    #[serde(default)]
411    pub env: Vec<String>,
412}
413
414impl ContainerLaunchSpec {
415    /// Describes a container to launch from `image` in `workspace`.
416    #[must_use]
417    pub fn new(
418        name: impl Into<String>,
419        image: impl Into<String>,
420        workspace: impl Into<PathBuf>,
421    ) -> Self {
422        Self {
423            name: name.into(),
424            image: image.into(),
425            workspace: workspace.into(),
426            mounts: Vec::new(),
427            env: Vec::new(),
428        }
429    }
430
431    /// Exposes an additional host path inside the container.
432    #[must_use]
433    pub fn with_mount(mut self, mount: MountSpec) -> Self {
434        self.mounts.push(mount);
435        self
436    }
437
438    /// Adds an environment entry, formatted as `KEY=value`.
439    #[must_use]
440    pub fn with_env(mut self, value: impl Into<String>) -> Self {
441        self.env.push(value.into());
442        self
443    }
444}
445
446#[cfg(test)]
447mod tests {
448    use super::{ContainerPath, MountRoot, MountRootError, MountSpec};
449
450    fn container_path(path: &str) -> ContainerPath {
451        ContainerPath::new(path).expect("test container paths are absolute")
452    }
453
454    #[test]
455    fn mount_root_maps_relative_path() {
456        let root = MountRoot::new("/host/.may", container_path("/root/.may"));
457        let mount = root
458            .read_only_child("skills")
459            .expect("relative child mount should be valid");
460        assert_eq!(
461            mount.host_path,
462            std::path::PathBuf::from("/host/.may/skills")
463        );
464        assert_eq!(mount.container_path.as_str(), "/root/.may/skills");
465    }
466
467    #[test]
468    fn mount_root_joins_nested_children_with_posix_separators() {
469        let root = MountRoot::new("/host/.may", container_path("/root/.may"));
470        let relative = std::path::Path::new("skills").join("python");
471        let mount = root
472            .read_write_child(relative)
473            .expect("nested child mount should be valid");
474        assert_eq!(mount.container_path.as_str(), "/root/.may/skills/python");
475    }
476
477    #[test]
478    fn mount_root_rejects_parent_traversal() {
479        let root = MountRoot::new("/host/.may", container_path("/root/.may"));
480        let error = root
481            .read_write_child("../secrets")
482            .expect_err("parent traversal must fail");
483        assert!(matches!(error, MountRootError::ParentTraversal(_)));
484    }
485
486    #[test]
487    fn mount_root_rejects_empty_and_rooted_children() {
488        let root = MountRoot::new("/host/.may", container_path("/root/.may"));
489        assert!(matches!(
490            root.read_only_child("."),
491            Err(MountRootError::EmptyRelativePath)
492        ));
493        assert!(matches!(
494            root.read_only_child("/etc"),
495            Err(MountRootError::AbsoluteRelativePath(_))
496        ));
497    }
498
499    #[test]
500    fn container_paths_are_absolute_posix_paths() {
501        assert!(ContainerPath::new("opt/aither").is_err());
502        let path = ContainerPath::root().join("opt").join("aither/tools");
503        assert_eq!(path.as_str(), "/opt/aither/tools");
504        assert_eq!(path.parent().unwrap().as_str(), "/opt/aither");
505        assert_eq!(path.join("/etc").as_str(), "/etc");
506    }
507
508    #[test]
509    fn mount_spec_serializes_container_path_as_text_and_rejects_relative() {
510        let mount = MountSpec::read_only("/host/tools", container_path("/opt/aither/tools/key"));
511        let json = serde_json::to_value(&mount).unwrap();
512        assert_eq!(json["container_path"], "/opt/aither/tools/key");
513        assert_eq!(serde_json::from_value::<MountSpec>(json).unwrap(), mount);
514        let relative = serde_json::json!({
515            "host_path": "/host/tools",
516            "container_path": "opt/aither/tools",
517            "access": "read_only",
518        });
519        assert!(serde_json::from_value::<MountSpec>(relative).is_err());
520    }
521}