1use std::collections::HashMap;
19use std::path::{Component, Path, PathBuf};
20use std::sync::{Mutex, OnceLock};
21use std::time::{Duration, Instant};
22
23use crate::backend::obj::{Block, MetaMapType};
24use crate::backend::rpc_types::{FsLinkFileCheck, FsLinkFileReq};
25
26use super::AppState;
27
28const WINDOW: Duration = Duration::from_secs(10);
29const PER_AUTHOR: u32 = 120;
30const OVERALL: u32 = 600;
31
32const FOUND: &str = "found";
33const MISSING: &str = "missing";
34const OUTSIDE: &str = "outside";
35const LIMITED: &str = "limited";
36
37const NOT_FOUND_WORDS: &str = "Not found.";
38const OUTSIDE_WORDS: &str = "Outside this agent's folders.";
39const FOLDER_WORDS: &str = "That is a folder, not a file.";
40const LIMITED_WORDS: &str = "Too many files were checked at once. Hover it again in a moment.";
41
42fn answer(state: &str, reason: &str) -> FsLinkFileCheck {
43 FsLinkFileCheck { state: state.to_string(), reason: reason.to_string(), resolved: String::new() }
44}
45
46#[derive(Default)]
48struct Counts {
49 since: Option<Instant>,
50 by_author: HashMap<String, u32>,
51 overall: u32,
52}
53
54impl Counts {
55 fn allow(&mut self, author: &str, now: Instant) -> bool {
56 if self.since.is_none_or(|since| now.duration_since(since) >= WINDOW) {
57 *self = Counts { since: Some(now), ..Counts::default() };
58 }
59 let mine = self.by_author.entry(author.to_string()).or_default();
60 if *mine >= PER_AUTHOR || self.overall >= OVERALL {
61 return false;
62 }
63 *mine += 1;
64 self.overall += 1;
65 true
66 }
67}
68
69fn counts() -> &'static Mutex<Counts> {
70 static COUNTS: OnceLock<Mutex<Counts>> = OnceLock::new();
71 COUNTS.get_or_init(Mutex::default)
72}
73
74fn collapse(path: &Path) -> Option<PathBuf> {
76 let mut out = PathBuf::new();
77 for part in path.components() {
78 match part {
79 Component::ParentDir => {
80 if !out.pop() {
81 return None;
82 }
83 }
84 Component::CurDir => {}
85 other => out.push(other.as_os_str()),
86 }
87 }
88 Some(out)
89}
90
91const MAX_HOPS: usize = 16;
93
94fn leads_to(path: &Path) -> Option<PathBuf> {
97 let mut rest: Vec<PathBuf> = vec![path.to_path_buf()];
99 let mut here = PathBuf::new();
100 let mut hops = 0;
101 while let Some(next_path) = rest.pop() {
102 let parts: Vec<Component> = next_path.components().collect();
103 for (index, part) in parts.iter().enumerate() {
104 match part {
105 Component::CurDir => {}
106 Component::ParentDir => {
107 here.pop();
108 }
109 Component::RootDir | Component::Prefix(_) => here.push(part.as_os_str()),
110 Component::Normal(name) => {
111 let next = here.join(name);
112 let target = std::fs::symlink_metadata(&next)
113 .ok()
114 .filter(|meta| meta.file_type().is_symlink())
115 .and_then(|_| std::fs::read_link(&next).ok());
116 let Some(target) = target else {
117 here = next;
118 continue;
119 };
120 hops += 1;
121 if hops > MAX_HOPS {
122 return None;
123 }
124 rest.push(parts[index + 1..].iter().collect());
126 rest.push(target);
127 break;
128 }
129 }
130 }
131 }
132 Some(here)
133}
134
135pub(crate) fn dangling_link_leaves(path: &Path, inside: &[&Path]) -> bool {
140 leads_to(path).map_or(true, |at| !inside.iter().any(|root| at.starts_with(root)))
141}
142
143fn check_in_folder(cwd: &str, asked: &str) -> FsLinkFileCheck {
145 let cwd = crate::backend::base::expand_home_dir_safe(cwd).to_string_lossy().into_owned();
147 let cwd = cwd.as_str();
148 let asked = asked.trim();
149 if asked.is_empty() || asked.contains('\0') || asked.starts_with('~') || asked.starts_with("\\\\") || asked.starts_with("//") || cwd.trim().is_empty() {
150 return answer(OUTSIDE, OUTSIDE_WORDS);
151 }
152 let Ok(root) = crate::server::browser_uploads::canonical(Path::new(cwd)) else { return answer(OUTSIDE, OUTSIDE_WORDS) };
153 let written = Path::new(asked);
154 let candidate = if written.is_absolute() { written.to_path_buf() } else { Path::new(cwd).join(written) };
155 let lexically_inside = collapse(&candidate).is_some_and(|c| c.starts_with(Path::new(cwd)) || c.starts_with(&root));
157 match crate::server::browser_uploads::canonical(&candidate) {
158 Ok(file) if file.starts_with(&root) => {
159 if file.is_file() {
160 FsLinkFileCheck { resolved: file.to_string_lossy().into_owned(), ..answer(FOUND, "") }
161 } else {
162 answer(MISSING, FOLDER_WORDS)
163 }
164 }
165 Ok(_) => answer(OUTSIDE, OUTSIDE_WORDS),
167 Err(_) if dangling_link_leaves(&candidate, &[Path::new(cwd), &root]) => answer(OUTSIDE, OUTSIDE_WORDS),
169 Err(_) if lexically_inside => answer(MISSING, NOT_FOUND_WORDS),
170 Err(_) => answer(OUTSIDE, OUTSIDE_WORDS),
172 }
173}
174
175fn check_in_container(meta: &MetaMapType, asked: &str) -> FsLinkFileCheck {
177 match crate::server::agent_media_files::resolve(meta, asked) {
178 Ok(found) if found.file.is_file() => answer(FOUND, ""),
179 Ok(_) => answer(MISSING, FOLDER_WORDS),
180 Err(why) if why.contains("doesn't exist") || why.contains("can't be read") => answer(MISSING, NOT_FOUND_WORDS),
181 Err(_) => answer(OUTSIDE, OUTSIDE_WORDS),
182 }
183}
184
185pub(crate) async fn fs_link_file_check(state: &AppState, req: FsLinkFileReq) -> Result<FsLinkFileCheck, String> {
187 let allowed = counts().lock().map_or(true, |mut c| c.allow(&req.block_id, Instant::now()));
188 if !allowed {
189 return Ok(answer(LIMITED, LIMITED_WORDS));
190 }
191 let Some(block) = state.mstore.get::<Block>(&req.block_id).ok().flatten() else {
192 return Ok(answer(OUTSIDE, OUTSIDE_WORDS));
193 };
194 let container = crate::backend::runtime_adapter::RuntimeKind::of_block_meta(&block.meta).is_container();
195 let path = req.path;
196 tokio::task::spawn_blocking(move || {
197 if container {
198 check_in_container(&block.meta, &path)
199 } else {
200 check_in_folder(&crate::backend::obj::meta_get_string(&block.meta, "cmd:cwd", ""), &path)
201 }
202 })
203 .await
204 .map_err(|e| format!("filesystem task failed: {e}"))
205}
206
207#[cfg(test)]
208mod tests {
209 use super::*;
210
211 fn folder() -> tempfile::TempDir {
212 let dir = tempfile::tempdir().unwrap();
213 std::fs::create_dir(dir.path().join("work")).unwrap();
214 std::fs::create_dir(dir.path().join("work").join("notes")).unwrap();
215 std::fs::write(dir.path().join("work").join("notes").join("plan.md"), "x").unwrap();
216 std::fs::write(dir.path().join("secret.txt"), "x").unwrap();
217 dir
218 }
219
220 fn check(dir: &tempfile::TempDir, asked: &str) -> (String, String) {
221 let cwd = dir.path().join("work");
222 let got = check_in_folder(&cwd.to_string_lossy(), asked);
223 (got.state, got.reason)
224 }
225
226 #[test]
227 fn a_file_in_the_folder_is_found_by_a_relative_or_an_absolute_path() {
228 let dir = folder();
229 assert_eq!(check(&dir, "notes/plan.md").0, FOUND);
230 let found = check_in_folder(&dir.path().join("work").to_string_lossy(), "notes/plan.md");
231 assert!(found.resolved.ends_with("plan.md"), "a found host file says where it is for the window to open");
232 assert!(check_in_folder(&dir.path().join("work").to_string_lossy(), "notes/none.md").resolved.is_empty());
233 assert_eq!(check(&dir, "./notes/../notes/plan.md").0, FOUND);
234 let absolute = dir.path().join("work").join("notes").join("plan.md");
235 assert_eq!(check(&dir, &absolute.to_string_lossy()).0, FOUND);
236 }
237
238 #[test]
239 fn a_missing_file_in_the_folder_is_missing_and_a_folder_is_not_a_file() {
240 let dir = folder();
241 assert_eq!(check(&dir, "notes/none.md"), (MISSING.to_string(), NOT_FOUND_WORDS.to_string()));
242 assert_eq!(check(&dir, "notes"), (MISSING.to_string(), FOLDER_WORDS.to_string()));
243 }
244
245 #[test]
246 fn a_dot_dot_escape_comes_back_outside_whether_or_not_the_target_exists() {
247 let dir = folder();
248 for asked in ["../secret.txt", "../nothing-here.txt", "notes/../../secret.txt", "../../../../etc/hosts"] {
249 assert_eq!(check(&dir, asked), (OUTSIDE.to_string(), OUTSIDE_WORDS.to_string()), "{asked}");
250 }
251 }
252
253 #[test]
254 fn an_absolute_path_elsewhere_and_a_home_or_network_path_are_outside() {
255 let dir = folder();
256 let elsewhere = dir.path().join("secret.txt");
257 assert_eq!(check(&dir, &elsewhere.to_string_lossy()).0, OUTSIDE);
258 for asked in ["~/notes.md", "//host/share/a.md", "\\\\host\\share\\a.md", "", "a\0b.md"] {
259 assert_eq!(check(&dir, asked).0, OUTSIDE, "{asked:?}");
260 }
261 }
262
263 #[cfg(unix)]
264 #[test]
265 fn a_link_inside_the_folder_that_leads_out_comes_back_outside() {
266 let dir = folder();
267 let work = dir.path().join("work");
268 std::os::unix::fs::symlink(dir.path().join("secret.txt"), work.join("shortcut.txt")).unwrap();
269 std::os::unix::fs::symlink(dir.path(), work.join("up")).unwrap();
270 assert_eq!(check(&dir, "shortcut.txt"), (OUTSIDE.to_string(), OUTSIDE_WORDS.to_string()));
271 assert_eq!(check(&dir, "up/secret.txt").0, OUTSIDE);
272 }
273
274 #[cfg(unix)]
275 #[test]
276 fn a_link_that_leaves_the_folder_answers_outside_whether_or_not_its_target_is_there() {
277 let dir = folder();
278 let work = dir.path().join("work");
279 let link = |name: &str, to: &std::path::Path| std::os::unix::fs::symlink(to, work.join(name)).unwrap();
280 link("gone.txt", &dir.path().join("not-there.txt"));
281 link("gone-dir", &dir.path().join("not-there-dir"));
282 link("present.txt", &dir.path().join("secret.txt"));
283 link("relative", std::path::Path::new("../not-there.txt"));
284 link("chain-b", &dir.path().join("not-there.txt"));
285 link("chain-a", &work.join("chain-b"));
286 link("up", dir.path());
287 link("through-up", &work.join("up").join("nothing.txt"));
289 link("through-up-to-a-file", &work.join("up").join("secret.txt"));
290 std::fs::create_dir_all(work.join("x").join("y")).unwrap();
292 link("x/y/dirlink", &work);
293 std::os::unix::fs::symlink("../probe", work.join("d")).unwrap();
294 assert_eq!(check(&dir, "x/y/dirlink/d"), (OUTSIDE.to_string(), OUTSIDE_WORDS.to_string()));
295 std::os::unix::fs::symlink("up/../probe", work.join("dotdot")).unwrap();
297 assert_eq!(check(&dir, "dotdot"), (OUTSIDE.to_string(), OUTSIDE_WORDS.to_string()));
298 for asked in ["through-up", "through-up-to-a-file"] {
299 assert_eq!(check(&dir, asked), (OUTSIDE.to_string(), OUTSIDE_WORDS.to_string()), "{asked}");
300 }
301 for asked in ["gone.txt", "gone-dir/a.md", "gone-dir", "present.txt", "relative", "chain-a", "gone-dir/../plan.md", "up/nothing.txt", "up/secret.txt", "up/nothing/deeper.txt"] {
302 assert_eq!(check(&dir, asked), (OUTSIDE.to_string(), OUTSIDE_WORDS.to_string()), "{asked}");
303 }
304 }
305
306 #[cfg(unix)]
307 #[test]
308 fn a_link_inside_the_folder_whose_target_is_not_there_is_missing() {
309 let dir = folder();
310 let work = dir.path().join("work");
311 std::os::unix::fs::symlink(work.join("notes").join("later.md"), work.join("soon.md")).unwrap();
312 std::os::unix::fs::symlink("notes/later.md", work.join("soon-relative.md")).unwrap();
313 assert_eq!(check(&dir, "soon.md"), (MISSING.to_string(), NOT_FOUND_WORDS.to_string()));
314 assert_eq!(check(&dir, "soon-relative.md"), (MISSING.to_string(), NOT_FOUND_WORDS.to_string()));
315 std::os::unix::fs::symlink(work.join("notes"), work.join("inside-dir")).unwrap();
317 assert_eq!(check(&dir, "inside-dir/later.md"), (MISSING.to_string(), NOT_FOUND_WORDS.to_string()));
318 assert_eq!(check(&dir, "inside-dir/plan.md").0, FOUND);
319 }
320
321 #[cfg(unix)]
322 #[test]
323 fn a_folder_reached_through_a_link_above_it_answers_missing_for_a_file_that_is_not_there() {
324 let dir = folder();
325 let door = dir.path().join("door");
326 std::os::unix::fs::symlink(dir.path(), &door).unwrap();
327 let cwd = door.join("work").to_string_lossy().into_owned();
328 let state = |asked: &str| check_in_folder(&cwd, asked).state;
329 assert_eq!(state("notes/none.md"), MISSING);
330 assert_eq!(state("notes/plan.md"), FOUND);
331 assert_eq!(state("../secret.txt"), OUTSIDE);
332 std::os::unix::fs::symlink(dir.path(), dir.path().join("work").join("up")).unwrap();
334 assert_eq!(state("up/nothing.txt"), OUTSIDE);
335 }
336
337 #[test]
338 fn a_container_agents_bare_name_and_relative_path_are_found_in_its_workspace() {
339 let dir = folder();
340 let mut meta = MetaMapType::new();
341 meta.insert("agentMode".to_string(), serde_json::json!("container"));
342 meta.insert("cmd:cwd".to_string(), serde_json::json!(dir.path().join("work").to_string_lossy()));
343 std::fs::write(dir.path().join("work").join("findings.md"), "x").unwrap();
344 for asked in ["findings.md", "./findings.md", "notes/plan.md", "/workspace/notes/plan.md"] {
345 assert_eq!(check_in_container(&meta, asked).state, FOUND, "{asked}");
346 }
347 assert_eq!(check_in_container(&meta, "notes/none.md").state, MISSING);
348 assert_eq!(check_in_container(&meta, "../secret.txt").state, OUTSIDE);
349 }
350
351 #[test]
352 fn no_answer_names_a_host_path() {
353 let dir = folder();
354 let host = dir.path().to_string_lossy().to_string();
355 for asked in ["notes/plan.md", "notes/none.md", "../secret.txt", "notes"] {
356 let (state, reason) = check(&dir, asked);
357 assert!(!reason.contains(&host) && !state.contains(&host), "{asked}");
358 }
359 }
360
361 #[test]
362 fn a_working_folder_stored_with_a_home_prefix_is_the_folder_it_names() {
363 let got = check_in_folder("~/", "wren-no-such-file-for-this-test.md");
365 assert_eq!((got.state.as_str(), got.reason.as_str()), (MISSING, NOT_FOUND_WORDS));
366 assert_eq!(check_in_folder("~/", "../wren-no-such-file-for-this-test.md").state, OUTSIDE, "a path leaving the folder is still outside");
367 assert_eq!(check_in_folder("~user/x", "a.md").state, OUTSIDE, "another user's home is not a folder this pane has");
368 }
369
370 #[test]
371 fn a_pane_with_no_working_folder_checks_nothing() {
372 assert_eq!(check_in_folder("", "a.md").state, OUTSIDE);
373 }
374
375 #[test]
376 fn the_checks_are_limited_per_author_and_overall() {
377 let mut counts = Counts::default();
378 let now = Instant::now();
379 assert!((0..PER_AUTHOR).all(|_| counts.allow("a", now)));
380 assert!(!counts.allow("a", now), "the author's share is used up");
381 assert!(counts.allow("b", now), "another author is not held up by it");
382 assert!(counts.allow("a", now + WINDOW), "a new window starts afresh");
383 let mut counts = Counts::default();
384 let allowed = (0..OVERALL + 10).filter(|i| counts.allow(&format!("author-{i}"), now)).count();
385 assert_eq!(allowed, OVERALL as usize);
386 }
387}