1use std::collections::HashSet;
2use std::path::{Component, Path, PathBuf};
3
4use crate::error::{AgentLoopError, Result};
5use crate::mount_fs::WORKSPACE_MOUNT;
6
7pub const PRIMARY_WORKSPACE_ROOT_NAME: &str = "workspace";
8pub const ADDITIONAL_ROOTS_MOUNT: &str = "/workspace/roots";
9
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct WorkspaceRoot {
12 pub name: String,
13 pub path: PathBuf,
14}
15
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub struct WorkspaceRootSet {
18 pub primary: WorkspaceRoot,
19 pub additional: Vec<WorkspaceRoot>,
20}
21
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub struct ResolvedPath {
24 pub root_name: String,
25 pub relative: RelPath,
26}
27
28#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
29pub struct RelPath(String);
30
31impl RelPath {
32 pub fn as_relative(&self) -> &str {
33 &self.0
34 }
35
36 pub fn to_session_path(&self) -> String {
37 if self.0.is_empty() {
38 "/".to_string()
39 } else {
40 format!("/{}", self.0)
41 }
42 }
43
44 fn from_path(relative: &Path) -> Result<Self> {
45 let mut segments = Vec::new();
46 for component in relative.components() {
47 match component {
48 Component::CurDir => {}
49 Component::Normal(segment) => {
50 let segment = segment.to_str().ok_or_else(|| {
51 AgentLoopError::tool(format!(
52 "non-UTF-8 path component: {}",
53 relative.display()
54 ))
55 })?;
56 segments.push(segment.to_string());
57 }
58 Component::ParentDir => {
59 return Err(AgentLoopError::tool(format!(
60 "path traversal rejected: {}",
61 relative.display()
62 )));
63 }
64 Component::RootDir | Component::Prefix(_) => {
65 return Err(AgentLoopError::tool(format!(
66 "absolute path component rejected: {}",
67 relative.display()
68 )));
69 }
70 }
71 }
72 Ok(Self(segments.join("/")))
73 }
74
75 fn from_str(input: &str) -> Result<Self> {
76 let mut segments = Vec::new();
77 for part in input.split('/') {
78 match part {
79 "" | "." => {}
80 ".." => {
81 return Err(AgentLoopError::tool(format!(
82 "path traversal rejected: {input}"
83 )));
84 }
85 segment => segments.push(segment.to_string()),
86 }
87 }
88 Ok(Self(segments.join("/")))
89 }
90}
91
92impl WorkspaceRootSet {
93 pub fn from_primary(path: impl Into<PathBuf>) -> Result<Self> {
94 Self::new(path, Vec::<(String, PathBuf)>::new())
95 }
96
97 pub fn new<I, P>(primary: impl Into<PathBuf>, additional: I) -> Result<Self>
98 where
99 I: IntoIterator<Item = (String, P)>,
100 P: Into<PathBuf>,
101 {
102 let primary = WorkspaceRoot {
103 name: PRIMARY_WORKSPACE_ROOT_NAME.to_string(),
104 path: canonicalize_root(primary.into())?,
105 };
106 let mut additional_roots = Vec::new();
107 let mut names = HashSet::new();
108 for (name, path) in additional {
109 validate_additional_name(&name)?;
110 if !names.insert(name.clone()) {
111 return Err(AgentLoopError::config(format!(
112 "duplicate workspace root name: {name}"
113 )));
114 }
115 additional_roots.push(WorkspaceRoot {
116 name,
117 path: canonicalize_root(path.into())?,
118 });
119 }
120
121 let root_set = Self {
122 primary,
123 additional: additional_roots,
124 };
125 root_set.reject_overlaps()?;
126 Ok(root_set)
127 }
128
129 pub fn parse_vfs_path(&self, input: &str) -> Result<ResolvedPath> {
130 let trimmed = input.trim();
131 let candidate = Path::new(trimmed);
132 if candidate.is_absolute() && !trimmed.starts_with("/workspace") {
133 if let Some((root, relative)) = self.resolve_host_path(candidate)? {
134 return Ok(ResolvedPath {
135 root_name: root.name.clone(),
136 relative,
137 });
138 }
139 return Err(AgentLoopError::tool(format!(
140 "host path is outside registered workspace roots: {trimmed}"
141 )));
142 }
143
144 let session = if trimmed == WORKSPACE_MOUNT || trimmed == "workspace" {
145 "/".to_string()
146 } else if let Some(rest) = trimmed.strip_prefix("/workspace/") {
147 format!("/{rest}")
148 } else if trimmed.starts_with('/') {
149 trimmed.to_string()
150 } else {
151 format!("/{trimmed}")
152 };
153
154 if session == "/" || !session.starts_with("/roots/") {
155 return Ok(ResolvedPath {
156 root_name: self.primary.name.clone(),
157 relative: RelPath::from_str(&session)?,
158 });
159 }
160
161 let rest = session.strip_prefix("/roots/").unwrap_or_default();
162 let (name, relative) = rest.split_once('/').unwrap_or((rest, ""));
163 let root = self
164 .additional
165 .iter()
166 .find(|root| root.name == name)
167 .ok_or_else(|| AgentLoopError::tool(format!("unknown workspace root: {name}")))?;
168 Ok(ResolvedPath {
169 root_name: root.name.clone(),
170 relative: RelPath::from_str(relative)?,
171 })
172 }
173
174 pub fn parse_host_scope(&self, root: &str, relative: Option<&str>) -> Result<PathBuf> {
175 let workspace_root = self.root_by_name(root)?;
176 let rel = RelPath::from_str(relative.unwrap_or(""))?;
177 let candidate = if rel.as_relative().is_empty() {
178 workspace_root.path.clone()
179 } else {
180 workspace_root.path.join(rel.as_relative())
181 };
182 let resolved = canonicalize_existing_or_parent(&candidate)?;
183 if resolved != workspace_root.path && !resolved.starts_with(&workspace_root.path) {
184 return Err(AgentLoopError::tool(format!(
185 "path escapes workspace root: {}",
186 candidate.display()
187 )));
188 }
189 Ok(resolved)
190 }
191
192 pub fn primary_host_root(&self) -> &Path {
193 &self.primary.path
194 }
195
196 pub fn set_primary_host_root(&mut self, path: PathBuf) -> Result<()> {
197 self.primary.path = canonicalize_root(path)?;
198 self.reject_overlaps()
199 }
200
201 pub fn spawn_cwd(&self) -> Result<PathBuf> {
202 canonicalize_root(self.primary.path.clone())
203 }
204
205 pub fn contains_host_path(&self, path: &Path) -> bool {
206 let Ok(canonical) = canonicalize_existing_or_parent(path) else {
207 return false;
208 };
209 self.all_roots()
210 .any(|root| canonical == root.path || canonical.starts_with(&root.path))
211 }
212
213 pub fn additional_mount_point(root_name: &str) -> String {
214 format!("{ADDITIONAL_ROOTS_MOUNT}/{root_name}")
215 }
216
217 fn all_roots(&self) -> impl Iterator<Item = &WorkspaceRoot> {
218 std::iter::once(&self.primary).chain(self.additional.iter())
219 }
220
221 fn root_by_name(&self, name: &str) -> Result<&WorkspaceRoot> {
222 if name == self.primary.name {
223 return Ok(&self.primary);
224 }
225 self.additional
226 .iter()
227 .find(|root| root.name == name)
228 .ok_or_else(|| AgentLoopError::tool(format!("unknown workspace root: {name}")))
229 }
230
231 fn resolve_host_path(&self, path: &Path) -> Result<Option<(&WorkspaceRoot, RelPath)>> {
232 let canonical = canonicalize_existing_or_parent(path)?;
233 for root in self.all_roots() {
234 if let Ok(relative) = canonical.strip_prefix(&root.path) {
235 return Ok(Some((root, RelPath::from_path(relative)?)));
236 }
237 }
238 Ok(None)
239 }
240
241 fn reject_overlaps(&self) -> Result<()> {
242 let roots: Vec<&WorkspaceRoot> = self.all_roots().collect();
243 for (idx, left) in roots.iter().enumerate() {
244 for right in roots.iter().skip(idx + 1) {
245 if left.path == right.path
246 || left.path.starts_with(&right.path)
247 || right.path.starts_with(&left.path)
248 {
249 return Err(AgentLoopError::config(format!(
250 "workspace roots must not overlap: {} ({}) and {} ({})",
251 left.name,
252 left.path.display(),
253 right.name,
254 right.path.display()
255 )));
256 }
257 }
258 }
259 Ok(())
260 }
261}
262
263fn validate_additional_name(name: &str) -> Result<()> {
264 if name.is_empty()
265 || name == "."
266 || name == ".."
267 || name == PRIMARY_WORKSPACE_ROOT_NAME
268 || name == "roots"
269 || name.contains('/')
270 || name.contains('\\')
271 {
272 return Err(AgentLoopError::config(format!(
273 "invalid workspace root name: {name}"
274 )));
275 }
276 Ok(())
277}
278
279fn canonicalize_root(root: PathBuf) -> Result<PathBuf> {
280 let canonical = std::fs::canonicalize(&root).map_err(|e| {
281 AgentLoopError::config(format!(
282 "failed to canonicalize workspace root {}: {e}",
283 root.display()
284 ))
285 })?;
286 if !canonical.is_dir() {
287 return Err(AgentLoopError::config(format!(
288 "workspace root is not a directory: {}",
289 canonical.display()
290 )));
291 }
292 Ok(canonical)
293}
294
295fn canonicalize_existing_or_parent(path: &Path) -> Result<PathBuf> {
296 match std::fs::canonicalize(path) {
297 Ok(path) => Ok(path),
298 Err(_) => {
299 let parent = path.parent().ok_or_else(|| {
300 AgentLoopError::tool(format!("path has no parent: {}", path.display()))
301 })?;
302 let canonical_parent = std::fs::canonicalize(parent).map_err(|e| {
303 AgentLoopError::tool(format!(
304 "failed to canonicalize parent {}: {e}",
305 parent.display()
306 ))
307 })?;
308 let name = path.file_name().ok_or_else(|| {
309 AgentLoopError::tool(format!("path has no file name: {}", path.display()))
310 })?;
311 Ok(canonical_parent.join(name))
312 }
313 }
314}
315
316#[cfg(test)]
317mod tests {
318 use super::*;
319 use tempfile::TempDir;
320
321 fn roots() -> (WorkspaceRootSet, TempDir, TempDir) {
322 let primary = TempDir::new().unwrap();
323 let backend = TempDir::new().unwrap();
324 let set = WorkspaceRootSet::new(
325 primary.path(),
326 [("backend".to_string(), backend.path().to_path_buf())],
327 )
328 .unwrap();
329 (set, primary, backend)
330 }
331
332 #[test]
333 fn canonicalizes_and_rejects_overlapping_roots() {
334 let primary = TempDir::new().unwrap();
335 let nested = primary.path().join("nested");
336 std::fs::create_dir(&nested).unwrap();
337
338 let err =
339 WorkspaceRootSet::new(primary.path(), [("nested".to_string(), nested)]).unwrap_err();
340 assert!(err.to_string().contains("must not overlap"));
341 }
342
343 #[test]
344 fn rejects_duplicate_names() {
345 let primary = TempDir::new().unwrap();
346 let a = TempDir::new().unwrap();
347 let b = TempDir::new().unwrap();
348
349 let err = WorkspaceRootSet::new(
350 primary.path(),
351 [
352 ("backend".to_string(), a.path().to_path_buf()),
353 ("backend".to_string(), b.path().to_path_buf()),
354 ],
355 )
356 .unwrap_err();
357 assert!(err.to_string().contains("duplicate workspace root name"));
358 }
359
360 #[test]
361 fn parses_primary_aliases_and_rejects_traversal() {
362 let (set, _primary, _backend) = roots();
363
364 assert_eq!(
365 set.parse_vfs_path("/workspace/src/lib.rs").unwrap(),
366 ResolvedPath {
367 root_name: "workspace".to_string(),
368 relative: RelPath("src/lib.rs".to_string())
369 }
370 );
371 assert_eq!(
372 set.parse_vfs_path("workspace").unwrap().relative,
373 RelPath::default()
374 );
375 assert!(set.parse_vfs_path("../outside").is_err());
376 }
377
378 #[test]
379 fn parses_additional_root_mounts_only() {
380 let (set, _primary, _backend) = roots();
381
382 assert_eq!(
383 set.parse_vfs_path("/workspace/roots/backend/src/lib.rs")
384 .unwrap(),
385 ResolvedPath {
386 root_name: "backend".to_string(),
387 relative: RelPath("src/lib.rs".to_string())
388 }
389 );
390 assert!(set.parse_vfs_path("/workspace/roots/missing/file").is_err());
391 }
392
393 #[test]
394 fn repoints_primary_without_touching_additional() {
395 let (mut set, _primary, backend) = roots();
396 let next = TempDir::new().unwrap();
397 set.set_primary_host_root(next.path().to_path_buf())
398 .unwrap();
399
400 assert_eq!(
401 set.spawn_cwd().unwrap(),
402 std::fs::canonicalize(next.path()).unwrap()
403 );
404 assert_eq!(
405 set.parse_host_scope("backend", Some("Cargo.toml")).unwrap(),
406 std::fs::canonicalize(backend.path())
407 .unwrap()
408 .join("Cargo.toml")
409 );
410 }
411
412 #[cfg(unix)]
413 #[test]
414 fn host_scope_rejects_symlink_escape() {
415 let primary = TempDir::new().unwrap();
416 let outside = TempDir::new().unwrap();
417 std::os::unix::fs::symlink(outside.path(), primary.path().join("outside-link")).unwrap();
418 let set = WorkspaceRootSet::from_primary(primary.path()).unwrap();
419
420 let err = set
421 .parse_host_scope("workspace", Some("outside-link/secret.txt"))
422 .unwrap_err();
423
424 assert!(err.to_string().contains("path escapes workspace root"));
425 }
426}