1use std::path::{Path, PathBuf};
20
21use crate::backend::container::mounts::writable::{writable_binds, WritableBind};
22use crate::backend::obj::{Block, MetaMapType};
23use crate::backend::work_facts::paths::{normalize_path, relative_to};
24use crate::server::AppState;
25
26pub(crate) const OUTSIDE: &str = "This file isn't in a folder the agent shares with its container, so it isn't shown from the agent's message. Only the agent's own folders can be shown there.";
28
29pub(crate) const LEADS_OUT: &str = "This file is in the agent's folder and leads out of it: a link the agent made points elsewhere. Nothing outside the agent's folder is shown from its message.";
31
32const NO_FOLDER: &str = "This agent shares no folder with its container, so there is nothing to show from its message.";
34
35#[derive(Debug, PartialEq, Eq)]
37pub(crate) struct Found {
38 pub root: PathBuf,
40 pub file: PathBuf,
42 pub of: String,
44}
45
46pub(crate) fn pane_meta(state: &AppState, block_id: &str) -> Option<MetaMapType> {
50 let block = state.mstore.get::<Block>(block_id).ok().flatten()?;
51 crate::backend::runtime_adapter::RuntimeKind::of_block_meta(&block.meta).is_container().then_some(block.meta)
52}
53
54fn collapse(path: &str) -> Option<String> {
56 let text = path.trim().replace('\\', "/");
58 let (root, rest) = match text.strip_prefix('/') {
59 Some(rest) => ("/", rest),
60 None => match text.split_once('/') {
62 Some((drive, rest)) if drive.ends_with(':') => (&text[..drive.len() + 1], rest),
63 _ => return None,
64 },
65 };
66 let mut kept: Vec<&str> = Vec::new();
67 for part in rest.split('/') {
68 match part {
69 "" | "." => {}
70 ".." => {
71 kept.pop()?;
72 }
73 other => kept.push(other),
74 }
75 }
76 Some(format!("{root}{}", kept.join("/")))
77}
78
79fn within(bind: &WritableBind, lexical: &str) -> Option<(usize, String)> {
83 let target = bind.target.trim_end_matches('/');
84 if let Some(rest) = lexical.strip_prefix(target).filter(|rest| rest.is_empty() || rest.starts_with('/')) {
85 return Some((target.len(), rest.trim_start_matches('/').to_string()));
86 }
87 let host = normalize_path(&bind.host.to_string_lossy());
88 relative_to(lexical, &host).map(|rest| (host.len(), rest))
89}
90
91fn is_relative(path: &str) -> bool {
93 let text = path.replace('\\', "/");
94 !text.starts_with('/') && !text.split_once('/').is_some_and(|(drive, _)| drive.ends_with(':'))
95}
96
97pub(crate) fn resolve(meta: &MetaMapType, asked: &str) -> Result<Found, String> {
99 let binds = writable_binds(meta, None);
100 if binds.is_empty() {
101 return Err(NO_FOLDER.to_string());
102 }
103 let asked = asked.trim();
104 if asked.is_empty() || asked.starts_with('~') || asked.starts_with("\\\\") || asked.starts_with("//") {
106 return Err(OUTSIDE.to_string());
107 }
108 let from_workspace = format!("{}/{asked}", crate::backend::container::CONTAINER_WORKSPACE_DIR.trim_end_matches('/'));
110 let asked = if is_relative(asked) { from_workspace.as_str() } else { asked };
111 let lexical = collapse(asked).ok_or_else(|| OUTSIDE.to_string())?;
112 let (bind, rest) = binds
113 .iter()
114 .filter_map(|bind| within(bind, &lexical).map(|(len, rest)| (len, bind, rest)))
115 .max_by_key(|(len, ..)| *len)
116 .map(|(_, bind, rest)| (bind, rest))
117 .ok_or_else(|| OUTSIDE.to_string())?;
118 let canonical = crate::server::browser_uploads::canonical;
119 let root = canonical(&bind.host).map_err(|_| "The agent's folder can't be read right now.".to_string())?;
120 let spelled = if rest.is_empty() { bind.host.clone() } else { bind.host.join(&rest) };
121 let Ok(file) = canonical(&spelled) else {
122 if crate::server::link_file_check::dangling_link_leaves(&spelled, &[&bind.host, &root]) {
124 return Err(LEADS_OUT.to_string());
125 }
126 return Err("That file doesn't exist.".to_string());
127 };
128 if !file.starts_with(&root) {
129 return Err(LEADS_OUT.to_string());
130 }
131 let target = bind.target.trim_end_matches('/');
132 let of = if rest.is_empty() { bind.target.clone() } else { format!("{target}/{rest}") };
133 Ok(Found { root, file, of })
134}
135
136pub(crate) fn open(meta: &MetaMapType, asked: &str) -> Result<(std::fs::File, Found), String> {
138 let found = resolve(meta, asked)?;
139 let file = crate::backend::workspace_copy::open_beneath(&found.root, &found.file)?;
140 Ok((file, found))
141}
142
143#[cfg(test)]
144mod tests {
145 use super::*;
146
147 struct Fixture {
150 _tmp: tempfile::TempDir,
151 ws: PathBuf,
152 private: PathBuf,
153 meta: MetaMapType,
154 }
155
156 fn fixture() -> Fixture {
157 let tmp = tempfile::tempdir().unwrap();
158 let ws = tmp.path().join("ws");
159 let private = tmp.path().join("private");
160 std::fs::create_dir_all(ws.join("img")).unwrap();
161 std::fs::create_dir_all(&private).unwrap();
162 std::fs::write(ws.join("img").join("a.png"), "the agent's picture").unwrap();
163 std::fs::write(private.join("photo.png"), "the person's photo").unwrap();
164 let mut meta = MetaMapType::new();
165 meta.insert("agentMode".to_string(), serde_json::json!("container"));
166 meta.insert(crate::backend::blockcontroller::META_KEY_CMD_CWD.to_string(), serde_json::json!(ws.to_string_lossy()));
167 Fixture { _tmp: tmp, ws, private, meta }
168 }
169
170 fn read(opened: Result<(std::fs::File, Found), String>) -> String {
171 use std::io::Read as _;
172 let mut text = String::new();
173 opened.unwrap().0.read_to_string(&mut text).unwrap();
174 text
175 }
176
177 fn swap_for_a_link(at: &Path, to: &Path) -> bool {
179 std::fs::remove_dir_all(at).unwrap();
180 #[cfg(unix)]
181 return std::os::unix::fs::symlink(to, at).is_ok();
182 #[cfg(windows)]
183 return std::process::Command::new("cmd")
184 .args(["/C", "mklink", "/J", &at.to_string_lossy(), &to.to_string_lossy()])
185 .output()
186 .map(|o| o.status.success())
187 .unwrap_or(false);
188 }
189
190 #[test]
191 fn a_path_in_the_container_is_read_from_the_folder_the_container_shares() {
192 let f = fixture();
193 assert_eq!(read(open(&f.meta, "/workspace/img/a.png")), "the agent's picture");
194 let found = resolve(&f.meta, "/workspace/img/a.png").unwrap();
195 assert_eq!(found.of, "/workspace/img/a.png");
196 }
197
198 #[test]
199 fn a_path_of_the_shared_folder_on_the_host_is_read_too_which_is_how_a_relative_path_arrives() {
200 let f = fixture();
201 let relative = format!("{}/img/a.png", f.ws.to_string_lossy());
203 assert_eq!(read(open(&f.meta, &relative)), "the agent's picture");
204 assert_eq!(read(open(&f.meta, &format!("{}/img/../img/a.png", f.ws.to_string_lossy()))), "the agent's picture");
205 }
206
207 #[test]
208 fn a_path_that_exists_on_the_host_but_is_not_in_the_agents_folders_is_refused() {
209 let f = fixture();
210 let photo = f.private.join("photo.png");
211 assert_eq!(resolve(&f.meta, &photo.to_string_lossy()).unwrap_err(), OUTSIDE);
212 assert_eq!(resolve(&f.meta, "/workspace/../private/photo.png").unwrap_err(), OUTSIDE);
213 assert_eq!(resolve(&f.meta, "/etc/hostname").unwrap_err(), OUTSIDE);
215 assert_eq!(resolve(&f.meta, "/workspaces/img/a.png").unwrap_err(), OUTSIDE, "a folder that only starts with the same letters is not inside it");
216 assert_eq!(resolve(&f.meta, "/Workspace/img/a.png").unwrap_err(), OUTSIDE, "a container's paths are case-sensitive");
217 }
218
219 #[test]
220 fn home_unc_drive_and_dot_dot_paths_are_refused() {
221 let f = fixture();
222 for asked in ["~/img/a.png", "~", "//server/share/a.png", "\\\\server\\share\\a.png", "C:/Users/me/photo.png", "C:\\Users\\me\\photo.png", "/../x.png", "", " "] {
223 assert_eq!(resolve(&f.meta, asked).unwrap_err(), OUTSIDE, "{asked:?}");
224 }
225 }
226
227 #[test]
228 fn a_link_in_the_folder_that_leads_out_is_refused_whether_it_is_a_file_or_a_folder_on_the_way() {
229 let f = fixture();
230 if swap_for_a_link(&f.ws.join("img"), &f.private) {
231 assert_eq!(resolve(&f.meta, "/workspace/img/photo.png").unwrap_err(), LEADS_OUT);
233 let host = format!("{}/img/photo.png", f.ws.to_string_lossy());
234 assert_eq!(resolve(&f.meta, &host).unwrap_err(), LEADS_OUT);
235 }
236 }
237
238 #[cfg(unix)]
239 #[test]
240 fn a_file_link_out_of_the_folder_is_refused_and_an_inside_link_is_read() {
241 let f = fixture();
242 std::os::unix::fs::symlink(f.private.join("photo.png"), f.ws.join("out.png")).unwrap();
243 std::os::unix::fs::symlink(f.ws.join("img").join("a.png"), f.ws.join("in.png")).unwrap();
244 assert_eq!(resolve(&f.meta, "/workspace/out.png").unwrap_err(), LEADS_OUT);
245 assert_eq!(read(open(&f.meta, "/workspace/in.png")), "the agent's picture");
246 }
247
248 #[cfg(unix)]
249 #[test]
250 fn a_link_out_of_the_folder_is_refused_alike_whether_or_not_its_target_is_there() {
251 let f = fixture();
252 std::os::unix::fs::symlink(f.private.join("not-there.png"), f.ws.join("gone.png")).unwrap();
253 std::os::unix::fs::symlink(f.private.join("not-there-dir"), f.ws.join("gone-dir")).unwrap();
254 std::os::unix::fs::symlink(f.ws.join("img").join("later.png"), f.ws.join("soon.png")).unwrap();
255 assert_eq!(resolve(&f.meta, "/workspace/gone.png").unwrap_err(), LEADS_OUT);
256 assert_eq!(resolve(&f.meta, "/workspace/gone-dir/a.png").unwrap_err(), LEADS_OUT);
257 std::os::unix::fs::symlink(&f.private, f.ws.join("up")).unwrap();
259 assert_eq!(resolve(&f.meta, "/workspace/up/nothing.png").unwrap_err(), LEADS_OUT);
260 assert_eq!(resolve(&f.meta, "/workspace/up/photo.png").unwrap_err(), LEADS_OUT);
261 std::os::unix::fs::symlink(f.ws.join("up").join("nothing.png"), f.ws.join("via-up.png")).unwrap();
263 std::os::unix::fs::symlink(f.ws.join("up").join("photo.png"), f.ws.join("via-up-file.png")).unwrap();
264 std::fs::create_dir_all(f.ws.join("x").join("y")).unwrap();
265 std::os::unix::fs::symlink(&f.ws, f.ws.join("x").join("y").join("dirlink")).unwrap();
266 std::os::unix::fs::symlink("../probe.png", f.ws.join("d.png")).unwrap();
267 assert_eq!(resolve(&f.meta, "/workspace/x/y/dirlink/d.png").unwrap_err(), LEADS_OUT);
268 std::os::unix::fs::symlink("up/../probe.png", f.ws.join("dotdot.png")).unwrap();
269 assert_eq!(resolve(&f.meta, "/workspace/dotdot.png").unwrap_err(), LEADS_OUT);
270 assert_eq!(resolve(&f.meta, "/workspace/via-up.png").unwrap_err(), LEADS_OUT);
271 assert_eq!(resolve(&f.meta, "/workspace/via-up-file.png").unwrap_err(), LEADS_OUT);
272 let host = format!("{}/gone.png", f.ws.to_string_lossy());
273 assert_eq!(resolve(&f.meta, &host).unwrap_err(), LEADS_OUT);
274 assert_eq!(resolve(&f.meta, "/workspace/soon.png").unwrap_err(), "That file doesn't exist.");
276 }
277
278 #[test]
279 fn a_name_with_no_folder_is_read_from_the_workspace() {
280 let f = fixture();
281 assert_eq!(resolve(&f.meta, "img/a.png").unwrap().of, "/workspace/img/a.png");
282 assert_eq!(read(open(&f.meta, "img/a.png")), "the agent's picture");
283 assert_eq!(resolve(&f.meta, "img/none.png").unwrap_err(), "That file doesn't exist.");
284 assert_eq!(resolve(&f.meta, "../a.png").unwrap_err(), OUTSIDE);
285 }
286
287 #[cfg(unix)]
288 #[test]
289 fn a_folder_reached_through_a_link_above_it_says_a_missing_file_is_not_there() {
290 let mut f = fixture();
291 let door = f._tmp.path().join("door");
292 std::os::unix::fs::symlink(f._tmp.path(), &door).unwrap();
293 f.meta.insert(crate::backend::blockcontroller::META_KEY_CMD_CWD.to_string(), serde_json::json!(door.join("ws").to_string_lossy()));
294 assert_eq!(resolve(&f.meta, "/workspace/img/none.png").unwrap_err(), "That file doesn't exist.");
295 assert_eq!(read(open(&f.meta, "/workspace/img/a.png")), "the agent's picture");
296 std::os::unix::fs::symlink(&f.private, f.ws.join("up")).unwrap();
297 assert_eq!(resolve(&f.meta, "/workspace/up/nothing.png").unwrap_err(), LEADS_OUT);
298 }
299
300 #[test]
301 fn a_link_swapped_in_after_the_path_was_found_is_not_followed() {
302 let f = fixture();
303 let found = resolve(&f.meta, "/workspace/img/a.png").unwrap();
304 std::fs::write(f.private.join("a.png"), "the person's file").unwrap();
306 if swap_for_a_link(&f.ws.join("img"), &f.private) {
307 assert!(crate::backend::workspace_copy::open_beneath(&found.root, &found.file).is_err());
309 }
310 }
311
312 #[test]
313 fn an_agent_with_no_shared_folder_has_nothing_to_show() {
314 let mut meta = MetaMapType::new();
315 meta.insert("agentMode".to_string(), serde_json::json!("container"));
316 assert_eq!(resolve(&meta, "/workspace/a.png").unwrap_err(), NO_FOLDER);
317 assert_eq!(resolve(&MetaMapType::new(), "/workspace/a.png").unwrap_err(), NO_FOLDER);
319 }
320
321 #[test]
322 fn only_the_workspace_and_the_volumes_the_person_declared_can_be_shown_never_the_folders_the_app_binds_itself() {
323 let f = fixture();
324 let shared = f.private.to_string_lossy().replace('\\', "/");
325 let volumes = format!("[\"{shared}:/data\",\"{shared}:/docs:ro\",\"cache:/cache\"]");
326 let mut meta = f.meta.clone();
327 meta.insert("agent:container_volumes".to_string(), serde_json::json!(volumes));
328 let targets: Vec<String> = writable_binds(&meta, None).into_iter().map(|b| b.target).collect();
329 assert_eq!(targets, ["/workspace", "/data"], "a read-only volume and a named volume are not folders of the host to show");
330 for app_owned in ["/root/.claude/projects/-workspace/memory/m.md", "/root/.claude/.credentials.json", "/root/.aws/credentials", "/docs/photo.png", "/cache/x"] {
333 assert_eq!(resolve(&meta, app_owned).unwrap_err(), OUTSIDE, "{app_owned}");
334 }
335 }
336
337 #[test]
338 fn a_file_that_is_not_there_says_so() {
339 let f = fixture();
340 assert_eq!(resolve(&f.meta, "/workspace/img/missing.png").unwrap_err(), "That file doesn't exist.");
341 }
342
343 #[test]
344 fn collapse_takes_dots_out_and_refuses_to_leave_the_root() {
345 assert_eq!(collapse("/a/./b//c/../d").as_deref(), Some("/a/b/d"));
346 assert_eq!(collapse("C:\\a\\b\\..\\c").as_deref(), Some("C:/a/c"));
347 assert_eq!(collapse("/c/x/../y").as_deref(), Some("/c/y"));
348 assert_eq!(collapse("/a/../..").as_deref(), None);
349 assert_eq!(collapse("relative/path").as_deref(), None);
350 }
351
352 #[test]
353 fn the_deepest_of_two_folders_holds_a_path_that_both_do() {
354 let f = fixture();
355 let mut meta = f.meta.clone();
356 let inner = f.ws.join("img");
357 meta.insert("agent:container_volumes".to_string(), serde_json::json!(format!("[\"{}:/workspace/pictures\"]", inner.to_string_lossy().replace('\\', "/"))));
358 let found = resolve(&meta, "/workspace/pictures/a.png").unwrap();
359 assert_eq!(found.of, "/workspace/pictures/a.png");
360 assert_eq!(read(open(&meta, "/workspace/pictures/a.png")), "the agent's picture");
361 }
362}