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 #[error("{path} is not beneath the mounted container directory {root}")]
193 OutsideContainerRoot {
194 path: String,
196 root: String,
198 },
199 #[error("{} is not beneath the mount root {}", .path.display(), .root.display())]
201 OutsideRoot {
202 path: PathBuf,
204 root: PathBuf,
206 },
207}
208
209impl MountRoot {
210 #[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 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 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 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 pub fn read_only_child(&self, relative: impl AsRef<Path>) -> Result<MountSpec, MountRootError> {
298 self.child(relative, MountAccess::ReadOnly)
299 }
300
301 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 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 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
368pub struct ContainerImageSpec {
369 pub tag: String,
371 pub context_dir: PathBuf,
373 #[serde(default, skip_serializing_if = "Option::is_none")]
375 pub dockerfile: Option<PathBuf>,
376}
377
378impl ContainerImageSpec {
379 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
399pub struct ContainerLaunchSpec {
400 pub name: String,
402 pub image: String,
404 pub workspace: PathBuf,
406 #[serde(default)]
408 pub mounts: Vec<MountSpec>,
409 #[serde(default)]
411 pub env: Vec<String>,
412}
413
414impl ContainerLaunchSpec {
415 #[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 #[must_use]
433 pub fn with_mount(mut self, mount: MountSpec) -> Self {
434 self.mounts.push(mount);
435 self
436 }
437
438 #[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}