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}
192
193impl MountRoot {
194    /// Pairs a host directory with the container path it maps to.
195    #[must_use]
196    pub fn new(host_root: impl Into<PathBuf>, container_root: ContainerPath) -> Self {
197        Self {
198            host_root: host_root.into(),
199            container_root,
200        }
201    }
202
203    /// Derives a mount for a path beneath this root.
204    ///
205    /// # Errors
206    ///
207    /// Returns [`MountRootError`] if `relative` is empty, absolute, or contains
208    /// a `..` component — any of which would place the mount outside the root —
209    /// or if a component is not UTF-8.
210    pub fn child(
211        &self,
212        relative: impl AsRef<Path>,
213        access: MountAccess,
214    ) -> Result<MountSpec, MountRootError> {
215        let relative = relative.as_ref();
216        let container_path = Self::container_child(&self.container_root, relative)?;
217        let host_path = self.host_root.join(relative);
218        Ok(match access {
219            MountAccess::ReadOnly => MountSpec::read_only(host_path, container_path),
220            MountAccess::ReadWrite => MountSpec::read_write(host_path, container_path),
221        })
222    }
223
224    /// Derives a read-only mount beneath this root.
225    ///
226    /// # Errors
227    ///
228    /// Same conditions as [`Self::child`].
229    pub fn read_only_child(&self, relative: impl AsRef<Path>) -> Result<MountSpec, MountRootError> {
230        self.child(relative, MountAccess::ReadOnly)
231    }
232
233    /// Derives a writable mount beneath this root.
234    ///
235    /// # Errors
236    ///
237    /// Same conditions as [`Self::child`].
238    pub fn read_write_child(
239        &self,
240        relative: impl AsRef<Path>,
241    ) -> Result<MountSpec, MountRootError> {
242        self.child(relative, MountAccess::ReadWrite)
243    }
244
245    /// Joins the host-relative `path` onto `root` one component at a time, so
246    /// the container side uses POSIX separators whatever the host spells.
247    fn container_child(root: &ContainerPath, path: &Path) -> Result<ContainerPath, MountRootError> {
248        let mut container_path = root.clone();
249        let mut named = false;
250        for component in path.components() {
251            match component {
252                Component::Normal(name) => {
253                    let name = name
254                        .to_str()
255                        .ok_or_else(|| MountRootError::NonUtf8(path.to_path_buf()))?;
256                    container_path = container_path.join(name);
257                    named = true;
258                }
259                Component::CurDir => {}
260                Component::ParentDir => {
261                    return Err(MountRootError::ParentTraversal(path.to_path_buf()));
262                }
263                Component::RootDir | Component::Prefix(_) => {
264                    return Err(MountRootError::AbsoluteRelativePath(path.to_path_buf()));
265                }
266            }
267        }
268        if named {
269            Ok(container_path)
270        } else {
271            Err(MountRootError::EmptyRelativePath)
272        }
273    }
274}
275
276impl MountSpec {
277    /// Mounts a host path into the container without write access.
278    #[must_use]
279    pub fn read_only(host_path: impl Into<PathBuf>, container_path: ContainerPath) -> Self {
280        Self {
281            host_path: host_path.into(),
282            container_path,
283            access: MountAccess::ReadOnly,
284        }
285    }
286
287    /// Mounts a host path into the container with write access.
288    #[must_use]
289    pub fn read_write(host_path: impl Into<PathBuf>, container_path: ContainerPath) -> Self {
290        Self {
291            host_path: host_path.into(),
292            container_path,
293            access: MountAccess::ReadWrite,
294        }
295    }
296}
297
298/// Image build specification.
299#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
300pub struct ContainerImageSpec {
301    /// Tag to apply to the built image.
302    pub tag: String,
303    /// Directory used as the build context.
304    pub context_dir: PathBuf,
305    /// Dockerfile to build, if not the default one in the context directory.
306    #[serde(default, skip_serializing_if = "Option::is_none")]
307    pub dockerfile: Option<PathBuf>,
308}
309
310impl ContainerImageSpec {
311    /// Describes an image built from `context_dir` and tagged `tag`.
312    #[must_use]
313    pub fn new(tag: impl Into<String>, context_dir: impl Into<PathBuf>) -> Self {
314        Self {
315            tag: tag.into(),
316            context_dir: context_dir.into(),
317            dockerfile: None,
318        }
319    }
320
321    /// Builds from a specific Dockerfile rather than the context default.
322    #[must_use]
323    pub fn with_dockerfile(mut self, dockerfile: impl Into<PathBuf>) -> Self {
324        self.dockerfile = Some(dockerfile.into());
325        self
326    }
327}
328
329/// Container launch specification.
330#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
331pub struct ContainerLaunchSpec {
332    /// Name to give the running container.
333    pub name: String,
334    /// Image to run.
335    pub image: String,
336    /// Directory the container treats as its workspace.
337    pub workspace: PathBuf,
338    /// Additional host paths to expose.
339    #[serde(default)]
340    pub mounts: Vec<MountSpec>,
341    /// Environment entries, each formatted as `KEY=value`.
342    #[serde(default)]
343    pub env: Vec<String>,
344}
345
346impl ContainerLaunchSpec {
347    /// Describes a container to launch from `image` in `workspace`.
348    #[must_use]
349    pub fn new(
350        name: impl Into<String>,
351        image: impl Into<String>,
352        workspace: impl Into<PathBuf>,
353    ) -> Self {
354        Self {
355            name: name.into(),
356            image: image.into(),
357            workspace: workspace.into(),
358            mounts: Vec::new(),
359            env: Vec::new(),
360        }
361    }
362
363    /// Exposes an additional host path inside the container.
364    #[must_use]
365    pub fn with_mount(mut self, mount: MountSpec) -> Self {
366        self.mounts.push(mount);
367        self
368    }
369
370    /// Adds an environment entry, formatted as `KEY=value`.
371    #[must_use]
372    pub fn with_env(mut self, value: impl Into<String>) -> Self {
373        self.env.push(value.into());
374        self
375    }
376}
377
378#[cfg(test)]
379mod tests {
380    use super::{ContainerPath, MountRoot, MountRootError, MountSpec};
381
382    fn container_path(path: &str) -> ContainerPath {
383        ContainerPath::new(path).expect("test container paths are absolute")
384    }
385
386    #[test]
387    fn mount_root_maps_relative_path() {
388        let root = MountRoot::new("/host/.may", container_path("/root/.may"));
389        let mount = root
390            .read_only_child("skills")
391            .expect("relative child mount should be valid");
392        assert_eq!(
393            mount.host_path,
394            std::path::PathBuf::from("/host/.may/skills")
395        );
396        assert_eq!(mount.container_path.as_str(), "/root/.may/skills");
397    }
398
399    #[test]
400    fn mount_root_joins_nested_children_with_posix_separators() {
401        let root = MountRoot::new("/host/.may", container_path("/root/.may"));
402        let relative = std::path::Path::new("skills").join("python");
403        let mount = root
404            .read_write_child(relative)
405            .expect("nested child mount should be valid");
406        assert_eq!(mount.container_path.as_str(), "/root/.may/skills/python");
407    }
408
409    #[test]
410    fn mount_root_rejects_parent_traversal() {
411        let root = MountRoot::new("/host/.may", container_path("/root/.may"));
412        let error = root
413            .read_write_child("../secrets")
414            .expect_err("parent traversal must fail");
415        assert!(matches!(error, MountRootError::ParentTraversal(_)));
416    }
417
418    #[test]
419    fn mount_root_rejects_empty_and_rooted_children() {
420        let root = MountRoot::new("/host/.may", container_path("/root/.may"));
421        assert!(matches!(
422            root.read_only_child("."),
423            Err(MountRootError::EmptyRelativePath)
424        ));
425        assert!(matches!(
426            root.read_only_child("/etc"),
427            Err(MountRootError::AbsoluteRelativePath(_))
428        ));
429    }
430
431    #[test]
432    fn container_paths_are_absolute_posix_paths() {
433        assert!(ContainerPath::new("opt/aither").is_err());
434        let path = ContainerPath::root().join("opt").join("aither/tools");
435        assert_eq!(path.as_str(), "/opt/aither/tools");
436        assert_eq!(path.parent().unwrap().as_str(), "/opt/aither");
437        assert_eq!(path.join("/etc").as_str(), "/etc");
438    }
439
440    #[test]
441    fn mount_spec_serializes_container_path_as_text_and_rejects_relative() {
442        let mount = MountSpec::read_only("/host/tools", container_path("/opt/aither/tools/key"));
443        let json = serde_json::to_value(&mount).unwrap();
444        assert_eq!(json["container_path"], "/opt/aither/tools/key");
445        assert_eq!(serde_json::from_value::<MountSpec>(json).unwrap(), mount);
446        let relative = serde_json::json!({
447            "host_path": "/host/tools",
448            "container_path": "opt/aither/tools",
449            "access": "read_only",
450        });
451        assert!(serde_json::from_value::<MountSpec>(relative).is_err());
452    }
453}