Skip to main content

agentmux_srv/server/
container_workspace.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A container agent's `/workspace` as a folder of the host.
5//!
6//! A container agent's machine is its container, whose `/workspace` is a folder of the host. A route
7//! that takes a path from it (`widgets/install`) names the folder as the agent sees it, and srv maps
8//! that to the host's, after resolving symlinks, and refuses anything outside: a host path outside the
9//! workspace would reach the user's `~/.ssh` or `~/.aws`.
10
11use std::path::{Path, PathBuf};
12
13use crate::server::AppState;
14
15/// Where the container's `/workspace` is on the host: the block's `cmd:cwd`, as the agent was started in it.
16pub(crate) fn workspace_of(state: &AppState, block_id: &str) -> Option<PathBuf> {
17    let block = state.mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten()?;
18    let cwd = crate::backend::obj::meta_get_string(&block.meta, "cmd:cwd", "");
19    if cwd.trim().is_empty() {
20        return None;
21    }
22    let expanded = crate::backend::blockcontroller::core::expand_home_dir(&cwd);
23    Some(std::path::absolute(&expanded).unwrap_or_else(|_| PathBuf::from(expanded)))
24}
25
26/// `raw` as a path on the host, inside `workspace`. `/workspace/...` is the container's name for it;
27/// a relative path is relative to it; a host path is accepted if it is inside it. Symlinks are resolved first.
28pub(crate) fn inside(workspace: &Path, raw: &str) -> Result<String, String> {
29    let raw = raw.trim();
30    let joined = host_spelling(workspace, raw);
31    let root = crate::server::browser_uploads::canonical(workspace).map_err(|e| format!("the agent's workspace can't be read: {e}"))?;
32    let real = crate::server::browser_uploads::canonical(&joined).map_err(|_| format!("no such file or folder: {raw}"))?;
33    if real.starts_with(&root) {
34        Ok(real.to_string_lossy().into_owned())
35    } else {
36        Err(format!("{raw} is outside this agent's workspace. A container agent can use only files in /workspace: copy the file there first."))
37    }
38}
39
40/// `raw` as the host spells it, with nothing resolved yet: `/workspace/...` and a relative path lie
41/// under `workspace`, and a host path stands as given.
42fn host_spelling(workspace: &Path, raw: &str) -> PathBuf {
43    match raw.strip_prefix("/workspace") {
44        Some("") => workspace.to_path_buf(),
45        Some(rest) if rest.starts_with('/') => workspace.join(rest.trim_start_matches('/')),
46        _ if Path::new(raw).is_absolute() => PathBuf::from(raw),
47        _ => workspace.join(raw),
48    }
49}
50
51/// The entry `raw` names, itself: a link is not followed, because a rename acts on the name in its
52/// folder. The folder is resolved (links included) and must lie inside `workspace`. Returns the entry
53/// on the host, and the container's name for its folder (`/workspace/...`).
54///
55/// The folder is checked now and renamed in a moment later, as every route that takes a workspace
56/// path does: the entry handed on is spelled through the resolved folder, with no link left in it.
57pub(crate) fn entry_inside(workspace: &Path, raw: &str) -> Result<(PathBuf, String), String> {
58    let raw = raw.trim();
59    let joined = host_spelling(workspace, raw);
60    let outside =
61        || format!("{raw} is outside this agent's workspace. A container agent can rename only what is in /workspace: move the file there first.");
62    // No name of its own (`/workspace/a/..`): not an entry of a folder.
63    let (Some(folder), Some(name)) = (joined.parent(), joined.file_name()) else {
64        return Err(outside());
65    };
66    let root = crate::server::browser_uploads::canonical(workspace).map_err(|e| format!("the agent's workspace can't be read: {e}"))?;
67    let folder = crate::server::browser_uploads::canonical(folder).map_err(|_| format!("no such file or folder: {raw}"))?;
68    // The workspace folder itself has its folder outside, so it is refused here too.
69    let Ok(below) = folder.strip_prefix(&root) else {
70        return Err(outside());
71    };
72    let entry = folder.join(name);
73    if entry.symlink_metadata().is_err() {
74        return Err(format!("no such file or folder: {raw}"));
75    }
76    let mut named = String::from("/workspace");
77    for part in below.components() {
78        named.push('/');
79        named.push_str(&part.as_os_str().to_string_lossy());
80    }
81    Ok((entry, named))
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    fn workspace() -> (PathBuf, PathBuf) {
89        let root = std::env::temp_dir().join(format!("agentmux-cws-{}-{}", std::process::id(), uuid::Uuid::new_v4().simple()));
90        let ws = root.join("ws");
91        std::fs::create_dir_all(ws.join("src")).unwrap();
92        std::fs::write(ws.join("src/main.rs"), "fn main() {}").unwrap();
93        std::fs::write(root.join("secret.txt"), "outside").unwrap();
94        (root, ws)
95    }
96
97    #[test]
98    fn the_containers_name_for_its_workspace_is_the_hosts_folder() {
99        let (root, ws) = workspace();
100        let want = crate::server::browser_uploads::canonical(&ws.join("src/main.rs")).unwrap().to_string_lossy().into_owned();
101        for given in ["/workspace/src/main.rs", "src/main.rs", &ws.join("src/main.rs").to_string_lossy()] {
102            assert_eq!(inside(&ws, given).as_deref(), Ok(want.as_str()), "{given}");
103        }
104        let _ = std::fs::remove_dir_all(root);
105    }
106
107    #[test]
108    fn a_path_outside_the_workspace_is_refused_however_it_is_written() {
109        let (root, ws) = workspace();
110        let outside = root.join("secret.txt");
111        for given in [
112            "/workspace/../secret.txt".to_string(),
113            "../secret.txt".to_string(),
114            outside.to_string_lossy().into_owned(),
115            "/etc/passwd".to_string(),
116            "/workspacefoo".to_string(),
117            "~/.ssh/id_rsa".to_string(),
118        ] {
119            let err = inside(&ws, &given).expect_err(&given);
120            assert!(err.contains("outside this agent's workspace") || err.contains("no such file"), "{given}: {err}");
121        }
122        // A symlink inside the workspace that points out is outside.
123        #[cfg(unix)]
124        {
125            std::os::unix::fs::symlink(&outside, ws.join("link.txt")).unwrap();
126            assert!(inside(&ws, "/workspace/link.txt").unwrap_err().contains("outside this agent's workspace"));
127        }
128        let _ = std::fs::remove_dir_all(root);
129    }
130
131    #[test]
132    fn an_entry_is_named_in_its_resolved_folder_and_the_container_names_that_folder() {
133        let (root, ws) = workspace();
134        let real = crate::server::browser_uploads::canonical(&ws).unwrap();
135        for given in ["/workspace/src/main.rs", "src/main.rs", &ws.join("src/main.rs").to_string_lossy()] {
136            assert_eq!(entry_inside(&ws, given), Ok((real.join("src").join("main.rs"), "/workspace/src".to_string())), "{given}");
137        }
138        // A folder is an entry too; one at the top is in /workspace.
139        assert_eq!(entry_inside(&ws, "/workspace/src"), Ok((real.join("src"), "/workspace".to_string())));
140        assert!(entry_inside(&ws, "/workspace/src/gone.rs").unwrap_err().contains("no such file"));
141        for given in ["/workspace", "/workspace/..", "/workspace/src/..", "../secret.txt", "/workspace/../secret.txt"] {
142            let err = entry_inside(&ws, given).expect_err(given);
143            assert!(err.contains("outside this agent's workspace"), "{given}: {err}");
144        }
145        let _ = std::fs::remove_dir_all(root);
146    }
147}