use std::path::{Component, Path, PathBuf};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use typed_path::{Utf8UnixPath, Utf8UnixPathBuf};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(try_from = "String", into = "String")]
#[schemars(with = "String")]
pub struct ContainerPath(Utf8UnixPathBuf);
#[derive(Debug, thiserror::Error)]
#[error("container path must be absolute: {0}")]
pub struct RelativeContainerPath(pub String);
impl ContainerPath {
#[must_use]
pub fn root() -> Self {
Self(Utf8UnixPathBuf::from("/"))
}
pub fn new(path: impl Into<String>) -> Result<Self, RelativeContainerPath> {
let path = Utf8UnixPathBuf::from(path.into());
if path.is_absolute() {
Ok(Self(path))
} else {
Err(RelativeContainerPath(path.into_string()))
}
}
#[must_use]
pub fn join(&self, path: impl AsRef<str>) -> Self {
Self(self.0.join(path.as_ref()))
}
#[must_use]
pub fn parent(&self) -> Option<Self> {
self.0.parent().map(|parent| Self(parent.to_path_buf()))
}
#[must_use]
pub fn as_str(&self) -> &str {
self.0.as_str()
}
#[must_use]
pub fn as_unix_path(&self) -> &Utf8UnixPath {
&self.0
}
}
impl std::fmt::Display for ContainerPath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl TryFrom<String> for ContainerPath {
type Error = RelativeContainerPath;
fn try_from(path: String) -> Result<Self, Self::Error> {
Self::new(path)
}
}
impl From<ContainerPath> for String {
fn from(path: ContainerPath) -> Self {
path.0.into_string()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum ContainerRuntimeKind {
OrbStack,
Podman,
Docker,
}
impl std::fmt::Display for ContainerRuntimeKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::OrbStack => write!(f, "OrbStack"),
Self::Podman => write!(f, "Podman"),
Self::Docker => write!(f, "Docker"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct RuntimePreference {
pub order: Vec<ContainerRuntimeKind>,
}
impl Default for RuntimePreference {
fn default() -> Self {
Self {
order: vec![
ContainerRuntimeKind::OrbStack,
ContainerRuntimeKind::Podman,
ContainerRuntimeKind::Docker,
],
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum MountAccess {
ReadOnly,
ReadWrite,
}
impl MountAccess {
#[must_use]
pub const fn read_only(self) -> bool {
matches!(self, Self::ReadOnly)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct MountSpec {
pub host_path: PathBuf,
pub container_path: ContainerPath,
pub access: MountAccess,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct MountRoot {
pub host_root: PathBuf,
pub container_root: ContainerPath,
}
#[derive(Debug, thiserror::Error)]
pub enum MountRootError {
#[error("relative path must not be empty")]
EmptyRelativePath,
#[error("relative path must not be absolute: {0}")]
AbsoluteRelativePath(PathBuf),
#[error("relative path must not contain parent traversal: {0}")]
ParentTraversal(PathBuf),
#[error("relative path must be valid UTF-8: {0}")]
NonUtf8(PathBuf),
}
impl MountRoot {
#[must_use]
pub fn new(host_root: impl Into<PathBuf>, container_root: ContainerPath) -> Self {
Self {
host_root: host_root.into(),
container_root,
}
}
pub fn child(
&self,
relative: impl AsRef<Path>,
access: MountAccess,
) -> Result<MountSpec, MountRootError> {
let relative = relative.as_ref();
let container_path = Self::container_child(&self.container_root, relative)?;
let host_path = self.host_root.join(relative);
Ok(match access {
MountAccess::ReadOnly => MountSpec::read_only(host_path, container_path),
MountAccess::ReadWrite => MountSpec::read_write(host_path, container_path),
})
}
pub fn read_only_child(&self, relative: impl AsRef<Path>) -> Result<MountSpec, MountRootError> {
self.child(relative, MountAccess::ReadOnly)
}
pub fn read_write_child(
&self,
relative: impl AsRef<Path>,
) -> Result<MountSpec, MountRootError> {
self.child(relative, MountAccess::ReadWrite)
}
fn container_child(root: &ContainerPath, path: &Path) -> Result<ContainerPath, MountRootError> {
let mut container_path = root.clone();
let mut named = false;
for component in path.components() {
match component {
Component::Normal(name) => {
let name = name
.to_str()
.ok_or_else(|| MountRootError::NonUtf8(path.to_path_buf()))?;
container_path = container_path.join(name);
named = true;
}
Component::CurDir => {}
Component::ParentDir => {
return Err(MountRootError::ParentTraversal(path.to_path_buf()));
}
Component::RootDir | Component::Prefix(_) => {
return Err(MountRootError::AbsoluteRelativePath(path.to_path_buf()));
}
}
}
if named {
Ok(container_path)
} else {
Err(MountRootError::EmptyRelativePath)
}
}
}
impl MountSpec {
#[must_use]
pub fn read_only(host_path: impl Into<PathBuf>, container_path: ContainerPath) -> Self {
Self {
host_path: host_path.into(),
container_path,
access: MountAccess::ReadOnly,
}
}
#[must_use]
pub fn read_write(host_path: impl Into<PathBuf>, container_path: ContainerPath) -> Self {
Self {
host_path: host_path.into(),
container_path,
access: MountAccess::ReadWrite,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ContainerImageSpec {
pub tag: String,
pub context_dir: PathBuf,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dockerfile: Option<PathBuf>,
}
impl ContainerImageSpec {
#[must_use]
pub fn new(tag: impl Into<String>, context_dir: impl Into<PathBuf>) -> Self {
Self {
tag: tag.into(),
context_dir: context_dir.into(),
dockerfile: None,
}
}
#[must_use]
pub fn with_dockerfile(mut self, dockerfile: impl Into<PathBuf>) -> Self {
self.dockerfile = Some(dockerfile.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ContainerLaunchSpec {
pub name: String,
pub image: String,
pub workspace: PathBuf,
#[serde(default)]
pub mounts: Vec<MountSpec>,
#[serde(default)]
pub env: Vec<String>,
}
impl ContainerLaunchSpec {
#[must_use]
pub fn new(
name: impl Into<String>,
image: impl Into<String>,
workspace: impl Into<PathBuf>,
) -> Self {
Self {
name: name.into(),
image: image.into(),
workspace: workspace.into(),
mounts: Vec::new(),
env: Vec::new(),
}
}
#[must_use]
pub fn with_mount(mut self, mount: MountSpec) -> Self {
self.mounts.push(mount);
self
}
#[must_use]
pub fn with_env(mut self, value: impl Into<String>) -> Self {
self.env.push(value.into());
self
}
}
#[cfg(test)]
mod tests {
use super::{ContainerPath, MountRoot, MountRootError, MountSpec};
fn container_path(path: &str) -> ContainerPath {
ContainerPath::new(path).expect("test container paths are absolute")
}
#[test]
fn mount_root_maps_relative_path() {
let root = MountRoot::new("/host/.may", container_path("/root/.may"));
let mount = root
.read_only_child("skills")
.expect("relative child mount should be valid");
assert_eq!(
mount.host_path,
std::path::PathBuf::from("/host/.may/skills")
);
assert_eq!(mount.container_path.as_str(), "/root/.may/skills");
}
#[test]
fn mount_root_joins_nested_children_with_posix_separators() {
let root = MountRoot::new("/host/.may", container_path("/root/.may"));
let relative = std::path::Path::new("skills").join("python");
let mount = root
.read_write_child(relative)
.expect("nested child mount should be valid");
assert_eq!(mount.container_path.as_str(), "/root/.may/skills/python");
}
#[test]
fn mount_root_rejects_parent_traversal() {
let root = MountRoot::new("/host/.may", container_path("/root/.may"));
let error = root
.read_write_child("../secrets")
.expect_err("parent traversal must fail");
assert!(matches!(error, MountRootError::ParentTraversal(_)));
}
#[test]
fn mount_root_rejects_empty_and_rooted_children() {
let root = MountRoot::new("/host/.may", container_path("/root/.may"));
assert!(matches!(
root.read_only_child("."),
Err(MountRootError::EmptyRelativePath)
));
assert!(matches!(
root.read_only_child("/etc"),
Err(MountRootError::AbsoluteRelativePath(_))
));
}
#[test]
fn container_paths_are_absolute_posix_paths() {
assert!(ContainerPath::new("opt/aither").is_err());
let path = ContainerPath::root().join("opt").join("aither/tools");
assert_eq!(path.as_str(), "/opt/aither/tools");
assert_eq!(path.parent().unwrap().as_str(), "/opt/aither");
assert_eq!(path.join("/etc").as_str(), "/etc");
}
#[test]
fn mount_spec_serializes_container_path_as_text_and_rejects_relative() {
let mount = MountSpec::read_only("/host/tools", container_path("/opt/aither/tools/key"));
let json = serde_json::to_value(&mount).unwrap();
assert_eq!(json["container_path"], "/opt/aither/tools/key");
assert_eq!(serde_json::from_value::<MountSpec>(json).unwrap(), mount);
let relative = serde_json::json!({
"host_path": "/host/tools",
"container_path": "opt/aither/tools",
"access": "read_only",
});
assert!(serde_json::from_value::<MountSpec>(relative).is_err());
}
}