1use std::collections::HashMap;
10use std::path::{Path, PathBuf};
11
12
13pub(crate) const MAX_UPLOAD_FILES: usize = 10;
15
16pub(crate) use crate::backend::spawn_env::workspaces::{
17 agent_workspace, container_workspace, record_container_workspace, record_launch_workspace,
18};
19
20pub(crate) const CONTAINER_WORKSPACE: &str = "/workspace";
22
23pub(crate) fn map_container_paths(host_dir: &Path, paths: &[String]) -> Result<Vec<String>, String> {
30 paths
31 .iter()
32 .map(|p| {
33 let raw = p.trim();
34 let outside = || {
35 format!("{p} is outside {CONTAINER_WORKSPACE}; a container agent can upload only files in its own workspace: copy the file there first")
36 };
37 let rest = match raw.strip_prefix(CONTAINER_WORKSPACE) {
38 Some("") => "",
39 Some(r) if r.starts_with('/') => r.trim_start_matches('/'),
40 _ if raw.starts_with('/') || raw.starts_with('\\') || raw.contains(':') => return Err(outside()),
41 _ => raw,
42 };
43 if Path::new(rest).components().any(|c| matches!(c, std::path::Component::ParentDir)) {
44 return Err(outside());
45 }
46 Ok(host_dir.join(rest).to_string_lossy().into_owned())
47 })
48 .collect()
49}
50
51fn container_view(error: String) -> String {
55 match error.split_once(" is outside your workspace") {
56 Some((path, _)) => format!("no such file: {path}"),
57 None => error,
58 }
59}
60
61pub(crate) async fn files_for_agent(own: &str, paths: Vec<String>) -> Result<Vec<serde_json::Value>, (axum::http::StatusCode, String)> {
68 use axum::http::StatusCode;
69 let host = agent_workspace(own);
70 let in_container = host.is_none();
71 let Some(workspace) = host.or_else(|| container_workspace(own)) else {
72 return Err((
73 StatusCode::FORBIDDEN,
74 "uploads come only from an agent's own workspace, and this agent has none (no launch directory)".to_string(),
75 ));
76 };
77 let requested = if in_container { map_container_paths(&workspace, &paths).map_err(|e| (StatusCode::FORBIDDEN, e))? } else { paths };
78 let host_dir = workspace.to_string_lossy().into_owned();
79 let read = tokio::task::spawn_blocking(move || {
80 use base64::Engine as _;
81 let checked = check_upload_paths(&workspace, &requested)?;
82 let files = read_upload_files(&workspace, &checked)?;
83 Ok::<_, String>(
84 files
85 .iter()
86 .map(|f| {
87 serde_json::json!({
88 "name": f.name,
89 "type": f.mime,
90 "data": base64::engine::general_purpose::STANDARD.encode(&f.bytes),
91 })
92 })
93 .collect::<Vec<serde_json::Value>>(),
94 )
95 })
96 .await;
97 match read {
98 Ok(Ok(files)) => Ok(files),
99 Ok(Err(e)) if in_container => {
100 let real = canonical(Path::new(&host_dir)).map(|p| p.to_string_lossy().into_owned()).ok();
101 let e = [Some(host_dir), real].into_iter().flatten().fold(e, |e, h| e.replace(&h, CONTAINER_WORKSPACE));
102 Err((StatusCode::FORBIDDEN, container_view(e)))
103 }
104 Ok(Err(e)) => Err((StatusCode::FORBIDDEN, e)),
105 Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, format!("reading the files failed: {e}"))),
106 }
107}
108
109pub(crate) fn canonical(p: &Path) -> std::io::Result<PathBuf> {
112 let c = std::fs::canonicalize(p)?;
113 let s = c.to_string_lossy();
114 Ok(match s.strip_prefix(r"\\?\") {
115 Some(rest) if !rest.starts_with("UNC\\") => PathBuf::from(rest),
116 _ => c,
117 })
118}
119
120pub(crate) fn check_upload_paths(workspace: &Path, paths: &[String]) -> Result<Vec<String>, String> {
124 if paths.is_empty() {
125 return Err("no files given".to_string());
126 }
127 if paths.len() > MAX_UPLOAD_FILES {
128 return Err(format!("at most {MAX_UPLOAD_FILES} files per upload"));
129 }
130 let ws = canonical(workspace)
131 .map_err(|e| format!("your workspace {} can't be read: {e}", workspace.display()))?;
132 let mut out = Vec::with_capacity(paths.len());
133 for p in paths {
134 let raw = Path::new(p.trim());
135 let joined = if raw.is_absolute() { raw.to_path_buf() } else { workspace.join(raw) };
136 let c = canonical(&joined).map_err(|_| format!("no such file: {p}"))?;
137 if !c.starts_with(&ws) {
138 return Err(format!(
139 "{p} is outside your workspace ({}); an agent can upload only files in its own workspace: copy the file there first",
140 ws.display()
141 ));
142 }
143 if !c.is_file() {
144 return Err(format!("{p} is not a file"));
145 }
146 out.push(c.to_string_lossy().into_owned());
147 }
148 Ok(out)
149}
150
151pub(crate) const MAX_UPLOAD_BYTES: u64 = 25 * 1024 * 1024;
154
155pub(crate) struct UploadFile {
158 pub name: String,
159 pub mime: &'static str,
160 pub bytes: Vec<u8>,
161}
162
163pub(crate) fn read_upload_files(workspace: &Path, checked: &[String]) -> Result<Vec<UploadFile>, String> {
169 use std::io::Read;
170 let ws = canonical(workspace).map_err(|e| format!("your workspace {} can't be read: {e}", workspace.display()))?;
171 let mut total: u64 = 0;
172 let mut out = Vec::with_capacity(checked.len());
173 for p in checked {
174 let file = std::fs::File::open(p).map_err(|_| format!("no such file: {p}"))?;
175 let real = handle_path(&file).map_err(|e| format!("can't tell where {p} is ({e}), so it isn't uploaded"))?;
176 if !real.starts_with(&ws) {
177 return Err(format!("{p} is outside your workspace ({})", ws.display()));
178 }
179 let meta = file.metadata().map_err(|e| format!("{p}: {e}"))?;
180 if !meta.is_file() {
181 return Err(format!("{p} is not a file"));
182 }
183 total += meta.len();
184 if total > MAX_UPLOAD_BYTES {
185 return Err(format!(
186 "uploads are limited to {} MB in all; for bigger files, ask the user to pick them (Browser's handoff action)",
187 MAX_UPLOAD_BYTES / (1024 * 1024)
188 ));
189 }
190 let mut bytes = Vec::with_capacity(meta.len() as usize);
191 file.take(MAX_UPLOAD_BYTES + 1).read_to_end(&mut bytes).map_err(|e| format!("{p}: {e}"))?;
192 if bytes.len() as u64 != meta.len() {
193 return Err(format!("{p} changed while it was being read; try again"));
194 }
195 let name = real.file_name().and_then(|n| n.to_str()).unwrap_or("file").to_string();
196 out.push(UploadFile { mime: mime_for(&name), name, bytes });
197 }
198 Ok(out)
199}
200
201#[cfg(windows)]
204fn handle_path(file: &std::fs::File) -> std::io::Result<PathBuf> {
205 use std::os::windows::ffi::OsStringExt;
206 use std::os::windows::io::AsRawHandle;
207 use windows_sys::Win32::Storage::FileSystem::{GetFinalPathNameByHandleW, FILE_NAME_NORMALIZED, VOLUME_NAME_DOS};
208 let mut buf = vec![0u16; 1024];
209 loop {
210 let n = unsafe {
211 GetFinalPathNameByHandleW(
212 file.as_raw_handle() as _,
213 buf.as_mut_ptr(),
214 buf.len() as u32,
215 FILE_NAME_NORMALIZED | VOLUME_NAME_DOS,
216 )
217 } as usize;
218 if n == 0 {
219 return Err(std::io::Error::last_os_error());
220 }
221 if n < buf.len() {
222 let p = PathBuf::from(std::ffi::OsString::from_wide(&buf[..n]));
223 let s = p.to_string_lossy();
224 return Ok(match s.strip_prefix(r"\\?\") {
225 Some(rest) if !rest.starts_with("UNC\\") => PathBuf::from(rest),
226 _ => p,
227 });
228 }
229 buf.resize(n + 1, 0);
230 }
231}
232
233#[cfg(target_os = "linux")]
234fn handle_path(file: &std::fs::File) -> std::io::Result<PathBuf> {
235 use std::os::fd::AsRawFd;
236 std::fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd()))
237}
238
239#[cfg(target_os = "macos")]
240fn handle_path(file: &std::fs::File) -> std::io::Result<PathBuf> {
241 use std::os::fd::AsRawFd;
242 use std::os::unix::ffi::OsStrExt;
243 let mut buf = vec![0u8; libc::PATH_MAX as usize];
244 if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETPATH, buf.as_mut_ptr()) } == -1 {
245 return Err(std::io::Error::last_os_error());
246 }
247 let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
248 Ok(PathBuf::from(std::ffi::OsStr::from_bytes(&buf[..end])))
249}
250
251#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
252fn handle_path(_file: &std::fs::File) -> std::io::Result<PathBuf> {
253 Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "not supported on this platform"))
254}
255
256fn mime_for(name: &str) -> &'static str {
261 let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();
262 match ext.as_str() {
263 "txt" | "log" => "text/plain",
264 "md" => "text/markdown",
265 "csv" => "text/csv",
266 "tsv" => "text/tab-separated-values",
267 "htm" | "html" => "text/html",
268 "css" => "text/css",
269 "js" | "mjs" => "text/javascript",
270 "rtf" => "application/rtf",
271 "json" => "application/json",
272 "xml" => "text/xml",
273 "pdf" => "application/pdf",
274 "zip" => "application/zip",
275 "gz" | "tgz" => "application/gzip",
276 "tar" => "application/x-tar",
277 "7z" => "application/x-7z-compressed",
278 "rar" => "application/vnd.rar",
279 "png" => "image/png",
280 "jpg" | "jpeg" => "image/jpeg",
281 "gif" => "image/gif",
282 "webp" => "image/webp",
283 "bmp" => "image/bmp",
284 "ico" => "image/x-icon",
285 "tif" | "tiff" => "image/tiff",
286 "heic" => "image/heic",
287 "avif" => "image/avif",
288 "svg" => "image/svg+xml",
289 "mp4" | "m4v" => "video/mp4",
290 "mov" => "video/quicktime",
291 "webm" => "video/webm",
292 "avi" => "video/x-msvideo",
293 "mkv" => "video/x-matroska",
294 "mpeg" | "mpg" => "video/mpeg",
295 "mp3" => "audio/mpeg",
296 "m4a" => "audio/mp4",
297 "wav" => "audio/wav",
298 "ogg" => "audio/ogg",
299 "flac" => "audio/flac",
300 "doc" => "application/msword",
301 "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
302 "xls" => "application/vnd.ms-excel",
303 "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
304 "ppt" => "application/vnd.ms-powerpoint",
305 "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
306 "odt" => "application/vnd.oasis.opendocument.text",
307 "ods" => "application/vnd.oasis.opendocument.spreadsheet",
308 "odp" => "application/vnd.oasis.opendocument.presentation",
309 "exe" | "dll" => "application/x-msdownload",
310 "msi" => "application/x-msi",
311 "apk" => "application/vnd.android.package-archive",
312 _ => "",
313 }
314}
315
316#[cfg(test)]
317mod tests {
318 use super::*;
319 use crate::backend::obj::MetaMapType;
320 use serde_json::json;
321
322 fn ws() -> (tempfile::TempDir, PathBuf) {
323 let dir = tempfile::tempdir().unwrap();
324 let ws = dir.path().join("agent-ws");
325 std::fs::create_dir_all(ws.join("sub")).unwrap();
326 std::fs::write(ws.join("report.txt"), "x").unwrap();
327 std::fs::write(ws.join("sub").join("a.bin"), "y").unwrap();
328 std::fs::write(dir.path().join("secret.txt"), "z").unwrap();
329 (dir, ws)
330 }
331
332 #[test]
333 fn a_container_agents_workspace_paths_map_to_the_host_folder_and_stay_inside_it() {
334 let (_d, ws) = ws();
335 let mapped = map_container_paths(&ws, &["/workspace/report.txt".into(), "sub/a.bin".into(), "/workspace/sub/a.bin".into()]).unwrap();
336 let checked = check_upload_paths(&ws, &mapped).unwrap();
337 let ws_real = canonical(&ws).unwrap();
338 assert_eq!(checked[0], ws_real.join("report.txt").to_string_lossy());
339 assert_eq!(checked[1], ws_real.join("sub").join("a.bin").to_string_lossy());
340 assert_eq!(checked[2], checked[1], "absolute and relative name the same file");
341 for outside in ["/etc/passwd", "/home/agent/x.txt", "/workspaces/x", "C:/Users/me/x.txt"] {
343 let why = map_container_paths(&ws, &[outside.into()]).unwrap_err();
344 assert!(why.contains("outside /workspace"), "{outside}: {why}");
345 }
346 for climb in ["/workspace/../secret.txt", "../secret.txt", "sub/../../secret.txt", "/workspace/sub/../../x"] {
348 let why = map_container_paths(&ws, &[climb.into()]).unwrap_err();
349 assert!(why.contains("outside /workspace"), "{climb}: {why}");
350 }
351 }
352
353 #[test]
354 fn a_container_agent_cant_tell_a_missing_file_from_one_outside_its_workspace() {
355 let outside = "link.txt is outside your workspace (/work/agent); an agent can upload only files in its own workspace: copy the file there first";
356 assert_eq!(container_view(outside.into()), "no such file: link.txt");
357 assert_eq!(container_view("no such file: gone.txt".into()), "no such file: gone.txt");
358 assert_eq!(container_view("at most 10 files per upload".into()), "at most 10 files per upload");
359 }
360
361 #[test]
362 fn the_container_workspace_is_recorded_per_block_and_forgotten_without_a_folder() {
363 record_container_workspace("ws-test-container", Some("/some/work"));
364 assert_eq!(container_workspace("ws-test-container"), Some(PathBuf::from("/some/work")));
365 record_container_workspace("ws-test-container", None);
366 assert_eq!(container_workspace("ws-test-container"), None);
367 record_container_workspace("ws-test-container", Some(" "));
368 assert_eq!(container_workspace("ws-test-container"), None);
369 }
370
371 #[test]
372 fn files_inside_the_workspace_are_allowed_absolute_or_relative() {
373 let (_d, ws) = ws();
374 let got = check_upload_paths(&ws, &["report.txt".into(), ws.join("sub").join("a.bin").to_string_lossy().into_owned()]).unwrap();
375 assert_eq!(got.len(), 2);
376 assert!(got[0].ends_with("report.txt") && !got[0].starts_with(r"\\?\"), "{got:?}");
377 }
378
379 #[test]
380 fn a_file_outside_the_workspace_is_refused_including_through_dotdot() {
381 let (d, ws) = ws();
382 let e = check_upload_paths(&ws, &[d.path().join("secret.txt").to_string_lossy().into_owned()]).unwrap_err();
383 assert!(e.contains("outside your workspace"), "{e}");
384 let e = check_upload_paths(&ws, &["../secret.txt".into()]).unwrap_err();
385 assert!(e.contains("outside your workspace"), "{e}");
386 }
387
388 #[test]
389 fn missing_files_directories_and_too_many_are_refused() {
390 let (_d, ws) = ws();
391 assert!(check_upload_paths(&ws, &["nope.txt".into()]).unwrap_err().contains("no such file"));
392 assert!(check_upload_paths(&ws, &["sub".into()]).unwrap_err().contains("not a file"));
393 assert!(check_upload_paths(&ws, &[]).is_err());
394 let many: Vec<String> = (0..11).map(|_| "report.txt".to_string()).collect();
395 assert!(check_upload_paths(&ws, &many).unwrap_err().contains("at most"));
396 }
397
398 #[test]
399 fn the_workspace_is_what_srv_launched_the_agent_in() {
400 let spawn = |pairs: &[(&str, &str)]| {
403 let mut m = MetaMapType::new();
404 for (k, v) in pairs {
405 m.insert(k.to_string(), json!(v));
406 }
407 let mut env = HashMap::new();
408 crate::backend::spawn_env::block_identity::carry_agent_workdir_env(&mut env, &m);
409 env
410 };
411 record_launch_workspace("ws-test-a", &spawn(&[("cmd:cwd", "C:/work/agent")]));
412 assert!(agent_workspace("ws-test-a").is_some());
413 record_launch_workspace("ws-test-a", &spawn(&[("cmd:cwd", "C:/work/agent"), ("agentMode", "container")]));
414 assert_eq!(agent_workspace("ws-test-a"), None);
415 assert_eq!(agent_workspace("ws-test-never-launched"), None);
416 }
417
418 #[test]
419 fn checked_files_are_read_from_the_handle_with_a_content_type() {
420 let (_d, ws) = ws();
421 let checked = check_upload_paths(&ws, &["report.txt".into(), "sub/a.bin".into()]).unwrap();
422 let files = read_upload_files(&ws, &checked).unwrap();
423 assert_eq!(files[0].name, "report.txt");
424 assert_eq!(files[0].bytes, b"x");
425 assert_eq!(files[0].mime, "text/plain");
426 assert_eq!(files[1].mime, "");
428 assert_eq!(mime_for("Deck.PPTX"), "application/vnd.openxmlformats-officedocument.presentationml.presentation");
429 assert_eq!(mime_for("clip.mov"), "video/quicktime");
430 }
431
432 #[test]
433 fn the_handle_check_refuses_a_file_outside_the_workspace_on_its_own() {
434 let (d, ws) = ws();
438 let outside = d.path().join("secret.txt").to_string_lossy().into_owned();
439 let e = read_upload_files(&ws, &[outside]).err().expect("refused");
440 assert!(e.contains("outside your workspace"), "{e}");
441 }
442
443 #[cfg(unix)]
444 #[test]
445 fn a_link_swapped_in_after_the_check_is_caught_by_the_handle() {
446 let (d, ws) = ws();
447 let checked = check_upload_paths(&ws, &["report.txt".into()]).unwrap();
448 std::fs::remove_file(ws.join("report.txt")).unwrap();
449 std::os::unix::fs::symlink(d.path().join("secret.txt"), ws.join("report.txt")).unwrap();
450 let e = read_upload_files(&ws, &checked).err().expect("refused");
451 assert!(e.contains("outside your workspace"), "{e}");
452 }
453
454 #[test]
455 fn uploads_over_the_size_limit_are_refused() {
456 let (_d, ws) = ws();
457 let big = ws.join("big.bin");
458 let f = std::fs::File::create(&big).unwrap();
459 f.set_len(MAX_UPLOAD_BYTES + 1).unwrap();
460 let checked = check_upload_paths(&ws, &["big.bin".into()]).unwrap();
461 let e = read_upload_files(&ws, &checked).err().expect("refused");
462 assert!(e.contains("limited to"), "{e}");
463 }
464}