agentmux_srv/server/
container_workspace.rs1use std::path::{Path, PathBuf};
12
13use crate::server::AppState;
14
15pub(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
26pub(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
40fn 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
51pub(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 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 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 #[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 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}