1use std::path::{Component, Path, PathBuf};
8
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11use typed_path::{Utf8UnixPath, Utf8UnixPathBuf};
12
13#[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#[derive(Debug, thiserror::Error)]
24#[error("container path must be absolute: {0}")]
25pub struct RelativeContainerPath(pub String);
26
27impl ContainerPath {
28 #[must_use]
30 pub fn root() -> Self {
31 Self(Utf8UnixPathBuf::from("/"))
32 }
33
34 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 #[must_use]
50 pub fn join(&self, path: impl AsRef<str>) -> Self {
51 Self(self.0.join(path.as_ref()))
52 }
53
54 #[must_use]
56 pub fn parent(&self) -> Option<Self> {
57 self.0.parent().map(|parent| Self(parent.to_path_buf()))
58 }
59
60 #[must_use]
62 pub fn as_str(&self) -> &str {
63 self.0.as_str()
64 }
65
66 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
95#[serde(rename_all = "lowercase")]
96pub enum ContainerRuntimeKind {
97 OrbStack,
99 Podman,
101 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
117pub struct RuntimePreference {
118 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
136#[serde(rename_all = "snake_case")]
137pub enum MountAccess {
138 ReadOnly,
140 ReadWrite,
142}
143
144impl MountAccess {
145 #[must_use]
147 pub const fn read_only(self) -> bool {
148 matches!(self, Self::ReadOnly)
149 }
150}
151
152#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
154pub struct MountSpec {
155 pub host_path: PathBuf,
157 pub container_path: ContainerPath,
159 pub access: MountAccess,
161}
162
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
165pub struct MountRoot {
166 pub host_root: PathBuf,
168 pub container_root: ContainerPath,
170}
171
172#[derive(Debug, thiserror::Error)]
174pub enum MountRootError {
175 #[error("relative path must not be empty")]
177 EmptyRelativePath,
179 #[error("relative path must not be absolute: {0}")]
181 AbsoluteRelativePath(PathBuf),
183 #[error("relative path must not contain parent traversal: {0}")]
185 ParentTraversal(PathBuf),
187 #[error("relative path must be valid UTF-8: {0}")]
189 NonUtf8(PathBuf),
191}
192
193impl MountRoot {
194 #[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 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 pub fn read_only_child(&self, relative: impl AsRef<Path>) -> Result<MountSpec, MountRootError> {
230 self.child(relative, MountAccess::ReadOnly)
231 }
232
233 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 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 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
300pub struct ContainerImageSpec {
301 pub tag: String,
303 pub context_dir: PathBuf,
305 #[serde(default, skip_serializing_if = "Option::is_none")]
307 pub dockerfile: Option<PathBuf>,
308}
309
310impl ContainerImageSpec {
311 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
331pub struct ContainerLaunchSpec {
332 pub name: String,
334 pub image: String,
336 pub workspace: PathBuf,
338 #[serde(default)]
340 pub mounts: Vec<MountSpec>,
341 #[serde(default)]
343 pub env: Vec<String>,
344}
345
346impl ContainerLaunchSpec {
347 #[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 #[must_use]
365 pub fn with_mount(mut self, mount: MountSpec) -> Self {
366 self.mounts.push(mount);
367 self
368 }
369
370 #[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}