Skip to main content

tea_coding_tools/
workspace.rs

1use std::fs;
2use std::io::ErrorKind;
3use std::path::{Path, PathBuf};
4
5use crate::path::ValidatedRelativePath;
6use crate::{WorkspacePathError, WorkspacePathErrorCode};
7
8/// Validated authority to resolve tool paths beneath one canonical directory.
9///
10/// Construction resolves symlinks in the supplied host path and requires an
11/// existing directory. Model-supplied paths are never interpreted relative to
12/// the process current directory.
13///
14/// # TOCTOU limits
15///
16/// Path-based host APIs cannot make resolution and a later open or rename one
17/// atomic operation. Callers performing mutations must invoke
18/// [`Self::revalidate_mutation`] immediately before commit. Executors should
19/// additionally prefer descriptor-relative operations where a safe portable
20/// implementation is available. Unix identity checks use device/inode. The
21/// portable stable Windows metadata APIs used here provide a best-effort
22/// fingerprint instead of a file index. This capability fails closed on
23/// detected replacement, but it does not claim to eliminate every filesystem
24/// race.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct WorkspaceRoot {
27    host_path: PathBuf,
28    identity: ObjectIdentity,
29}
30
31impl WorkspaceRoot {
32    /// Constructs a capability from an existing host directory.
33    ///
34    /// # Errors
35    ///
36    /// Returns a stable bounded error if the path is absent, is not a
37    /// directory, or cannot be resolved safely.
38    pub fn new(path: impl AsRef<Path>) -> Result<Self, WorkspacePathError> {
39        let host_path = fs::canonicalize(path.as_ref()).map_err(|error| {
40            if error.kind() == ErrorKind::NotFound {
41                WorkspacePathError::new(WorkspacePathErrorCode::WorkspaceNotFound)
42            } else {
43                WorkspacePathError::new(WorkspacePathErrorCode::FilesystemFailure)
44            }
45        })?;
46        let metadata = fs::metadata(&host_path)
47            .map_err(|_| WorkspacePathError::new(WorkspacePathErrorCode::FilesystemFailure))?;
48        if !metadata.is_dir() {
49            return Err(WorkspacePathError::new(
50                WorkspacePathErrorCode::WorkspaceNotDirectory,
51            ));
52        }
53        Ok(Self {
54            host_path,
55            identity: ObjectIdentity::from_metadata(&metadata),
56        })
57    }
58
59    /// Returns the canonical host directory represented by this capability.
60    #[must_use]
61    pub fn host_path(&self) -> &Path {
62        &self.host_path
63    }
64
65    /// Resolves a model path that must already exist.
66    ///
67    /// The returned display path is normalized and workspace-relative. The
68    /// host path is canonical and has passed a component-wise containment
69    /// check against this capability.
70    ///
71    /// # Errors
72    ///
73    /// Rejects malformed, absolute, traversing, missing, unresolvable, or
74    /// workspace-escaping paths.
75    pub fn resolve_existing(&self, path: &str) -> Result<ResolvedExistingPath, WorkspacePathError> {
76        self.verify_root()?;
77        let relative = ValidatedRelativePath::parse(path)?;
78        let candidate = relative.join_to(&self.host_path);
79        let host_path = fs::canonicalize(&candidate).map_err(|error| {
80            if error.kind() == ErrorKind::NotFound {
81                WorkspacePathError::new(WorkspacePathErrorCode::TargetNotFound)
82            } else {
83                WorkspacePathError::new(WorkspacePathErrorCode::UnresolvableTarget)
84            }
85        })?;
86        self.require_contained(&host_path)?;
87        let metadata = fs::metadata(&host_path)
88            .map_err(|_| WorkspacePathError::new(WorkspacePathErrorCode::UnresolvableTarget))?;
89        Ok(ResolvedExistingPath {
90            display_path: relative.display().to_owned(),
91            host_path,
92            workspace_root: self.host_path.clone(),
93            identity: ObjectIdentity::from_metadata(&metadata),
94        })
95    }
96
97    /// Revalidates an existing target immediately before opening it.
98    ///
99    /// # Errors
100    ///
101    /// Returns `CapabilityMismatch` for a value from another workspace and
102    /// `PathChanged` if resolution or filesystem identity changed.
103    pub fn revalidate_existing(
104        &self,
105        target: &ResolvedExistingPath,
106    ) -> Result<(), WorkspacePathError> {
107        if target.workspace_root != self.host_path {
108            return Err(WorkspacePathError::new(
109                WorkspacePathErrorCode::CapabilityMismatch,
110            ));
111        }
112        let current = self
113            .resolve_existing(target.display_path())
114            .map_err(|error| match error.code() {
115                WorkspacePathErrorCode::TargetNotFound
116                | WorkspacePathErrorCode::UnresolvableTarget => {
117                    WorkspacePathError::new(WorkspacePathErrorCode::PathChanged)
118                }
119                _ => error,
120            })?;
121        if current.host_path != target.host_path || current.identity != target.identity {
122            return Err(WorkspacePathError::new(WorkspacePathErrorCode::PathChanged));
123        }
124        Ok(())
125    }
126
127    /// Verifies that an opened file handle identifies the resolved target.
128    ///
129    /// Call this with metadata obtained from the opened file handle, not by
130    /// looking up its path again. It closes the validation-to-open race for the
131    /// object identity on platforms that expose stable file identifiers.
132    ///
133    /// # Errors
134    ///
135    /// Returns `PathChanged` if the opened object differs from the resolved
136    /// target, or `CapabilityMismatch` for a token from another workspace.
137    pub fn verify_opened_existing(
138        &self,
139        target: &ResolvedExistingPath,
140        metadata: &fs::Metadata,
141    ) -> Result<(), WorkspacePathError> {
142        if target.workspace_root != self.host_path {
143            return Err(WorkspacePathError::new(
144                WorkspacePathErrorCode::CapabilityMismatch,
145            ));
146        }
147        self.verify_root()?;
148        if ObjectIdentity::from_metadata(metadata) != target.identity {
149            return Err(WorkspacePathError::new(WorkspacePathErrorCode::PathChanged));
150        }
151        Ok(())
152    }
153
154    /// Resolves an existing or prospective mutation target.
155    ///
156    /// The workspace root itself is not a valid mutation target. Existing
157    /// targets are canonicalized. For a prospective target, the nearest
158    /// existing ancestor is canonicalized, checked as a directory, and checked
159    /// for workspace containment before unresolved components are appended.
160    ///
161    /// # Errors
162    ///
163    /// Rejects malformed, absolute, traversing, unresolvable, root-targeting,
164    /// non-directory-parent, or workspace-escaping paths.
165    pub fn resolve_mutation(&self, path: &str) -> Result<ResolvedMutationPath, WorkspacePathError> {
166        self.verify_root()?;
167        let relative = ValidatedRelativePath::parse(path)?;
168        if relative.display() == "." {
169            return Err(WorkspacePathError::new(
170                WorkspacePathErrorCode::WorkspaceRootMutation,
171            ));
172        }
173        let candidate = relative.join_to(&self.host_path);
174
175        if let Ok(host_path) = fs::canonicalize(&candidate) {
176            self.require_contained(&host_path)?;
177            let metadata = fs::metadata(&host_path)
178                .map_err(|_| WorkspacePathError::new(WorkspacePathErrorCode::UnresolvableTarget))?;
179            Ok(ResolvedMutationPath {
180                display_path: relative.display().to_owned(),
181                host_path: host_path.clone(),
182                workspace_root: self.host_path.clone(),
183                target_existed: true,
184                anchor_path: host_path,
185                anchor_identity: ObjectIdentity::from_metadata(&metadata),
186            })
187        } else {
188            if fs::symlink_metadata(&candidate).is_ok() {
189                return Err(WorkspacePathError::new(
190                    WorkspacePathErrorCode::UnresolvableTarget,
191                ));
192            }
193            self.resolve_prospective(&relative, &candidate)
194        }
195    }
196
197    /// Revalidates a mutation target immediately before its commit operation.
198    ///
199    /// This detects containment changes, target appearance/disappearance, and
200    /// nearest-existing-ancestor replacement on supported platforms. A caller
201    /// must discard the old value and resolve again after any failure.
202    ///
203    /// # Errors
204    ///
205    /// Returns `CapabilityMismatch` for a value from another workspace and a
206    /// stable path error when the target no longer has the same resolution.
207    pub fn revalidate_mutation(
208        &self,
209        target: &ResolvedMutationPath,
210    ) -> Result<(), WorkspacePathError> {
211        if target.workspace_root != self.host_path {
212            return Err(WorkspacePathError::new(
213                WorkspacePathErrorCode::CapabilityMismatch,
214            ));
215        }
216        let current = self.resolve_mutation(target.display_path())?;
217        if current.host_path != target.host_path
218            || current.target_existed != target.target_existed
219            || current.anchor_path != target.anchor_path
220            || current.anchor_identity != target.anchor_identity
221        {
222            return Err(WorkspacePathError::new(WorkspacePathErrorCode::PathChanged));
223        }
224        Ok(())
225    }
226
227    fn resolve_prospective(
228        &self,
229        relative: &ValidatedRelativePath,
230        candidate: &Path,
231    ) -> Result<ResolvedMutationPath, WorkspacePathError> {
232        let mut ancestor = candidate
233            .parent()
234            .ok_or_else(|| WorkspacePathError::new(WorkspacePathErrorCode::InvalidPath))?;
235        loop {
236            match fs::symlink_metadata(ancestor) {
237                Ok(metadata) => {
238                    let anchor_path = fs::canonicalize(ancestor).map_err(|_| {
239                        WorkspacePathError::new(WorkspacePathErrorCode::UnresolvableTarget)
240                    })?;
241                    self.require_contained(&anchor_path)?;
242                    let followed_metadata = fs::metadata(&anchor_path).map_err(|_| {
243                        WorkspacePathError::new(WorkspacePathErrorCode::UnresolvableTarget)
244                    })?;
245                    if !followed_metadata.is_dir() {
246                        return Err(WorkspacePathError::new(
247                            WorkspacePathErrorCode::ParentNotDirectory,
248                        ));
249                    }
250                    let suffix = candidate.strip_prefix(ancestor).map_err(|_| {
251                        WorkspacePathError::new(WorkspacePathErrorCode::UnresolvableTarget)
252                    })?;
253                    return Ok(ResolvedMutationPath {
254                        display_path: relative.display().to_owned(),
255                        host_path: anchor_path.join(suffix),
256                        workspace_root: self.host_path.clone(),
257                        target_existed: false,
258                        anchor_path,
259                        anchor_identity: ObjectIdentity::from_metadata(&metadata),
260                    });
261                }
262                Err(error) if error.kind() == ErrorKind::NotFound => {
263                    ancestor = ancestor.parent().ok_or_else(|| {
264                        WorkspacePathError::new(WorkspacePathErrorCode::UnresolvableTarget)
265                    })?;
266                }
267                Err(_) => {
268                    return Err(WorkspacePathError::new(
269                        WorkspacePathErrorCode::FilesystemFailure,
270                    ));
271                }
272            }
273        }
274    }
275
276    fn verify_root(&self) -> Result<(), WorkspacePathError> {
277        let current = fs::canonicalize(&self.host_path)
278            .map_err(|_| WorkspacePathError::new(WorkspacePathErrorCode::FilesystemFailure))?;
279        let metadata = fs::metadata(&current)
280            .map_err(|_| WorkspacePathError::new(WorkspacePathErrorCode::FilesystemFailure))?;
281        if current != self.host_path
282            || !metadata.is_dir()
283            || ObjectIdentity::from_metadata(&metadata) != self.identity
284        {
285            return Err(WorkspacePathError::new(WorkspacePathErrorCode::PathChanged));
286        }
287        Ok(())
288    }
289
290    fn require_contained(&self, path: &Path) -> Result<(), WorkspacePathError> {
291        if path.starts_with(&self.host_path) {
292            Ok(())
293        } else {
294            Err(WorkspacePathError::new(
295                WorkspacePathErrorCode::OutsideWorkspace,
296            ))
297        }
298    }
299}
300
301/// Verified existing workspace target.
302#[derive(Debug, Clone, PartialEq, Eq)]
303pub struct ResolvedExistingPath {
304    display_path: String,
305    host_path: PathBuf,
306    workspace_root: PathBuf,
307    identity: ObjectIdentity,
308}
309
310impl ResolvedExistingPath {
311    /// Returns the normalized workspace-relative path safe for model/UI output.
312    #[must_use]
313    pub fn display_path(&self) -> &str {
314        &self.display_path
315    }
316
317    /// Returns the canonical contained host path.
318    #[must_use]
319    pub fn host_path(&self) -> &Path {
320        &self.host_path
321    }
322}
323
324/// Verified existing or prospective workspace mutation target.
325#[derive(Debug, Clone, PartialEq, Eq)]
326pub struct ResolvedMutationPath {
327    display_path: String,
328    host_path: PathBuf,
329    workspace_root: PathBuf,
330    target_existed: bool,
331    anchor_path: PathBuf,
332    anchor_identity: ObjectIdentity,
333}
334
335impl ResolvedMutationPath {
336    /// Returns the normalized workspace-relative path safe for model/UI output.
337    #[must_use]
338    pub fn display_path(&self) -> &str {
339        &self.display_path
340    }
341
342    /// Returns the verified contained host path.
343    ///
344    /// For prospective targets this path is formed by appending unresolved
345    /// components to the canonical nearest existing parent.
346    #[must_use]
347    pub fn host_path(&self) -> &Path {
348        &self.host_path
349    }
350
351    /// Reports whether the final target existed when this value was resolved.
352    #[must_use]
353    pub const fn target_existed_at_resolution(&self) -> bool {
354        self.target_existed
355    }
356}
357
358#[derive(Debug, Clone, PartialEq, Eq)]
359struct ObjectIdentity {
360    #[cfg(unix)]
361    device: u64,
362    #[cfg(unix)]
363    inode: u64,
364    #[cfg(windows)]
365    file_attributes: u32,
366    #[cfg(windows)]
367    creation_time: u64,
368    #[cfg(windows)]
369    last_write_time: u64,
370    #[cfg(windows)]
371    file_size: u64,
372    #[cfg(not(any(unix, windows)))]
373    length: u64,
374    #[cfg(not(any(unix, windows)))]
375    modified: Option<std::time::SystemTime>,
376}
377
378impl ObjectIdentity {
379    fn from_metadata(metadata: &fs::Metadata) -> Self {
380        #[cfg(unix)]
381        {
382            use std::os::unix::fs::MetadataExt;
383            Self {
384                device: metadata.dev(),
385                inode: metadata.ino(),
386            }
387        }
388        #[cfg(windows)]
389        {
390            use std::os::windows::fs::MetadataExt;
391            Self {
392                file_attributes: metadata.file_attributes(),
393                creation_time: metadata.creation_time(),
394                last_write_time: metadata.last_write_time(),
395                file_size: metadata.file_size(),
396            }
397        }
398        #[cfg(not(any(unix, windows)))]
399        {
400            Self {
401                length: metadata.len(),
402                modified: metadata.modified().ok(),
403            }
404        }
405    }
406}