Skip to main content

artifactize_tools/
scope.rs

1//! Logical scope data and path resolution independent of project configuration.
2
3use std::{
4    borrow::Borrow,
5    collections::BTreeMap,
6    fmt,
7    fs::File,
8    io,
9    path::{Path, PathBuf},
10};
11
12use serde::{Deserialize, Serialize};
13use thiserror::Error;
14
15use crate::files as platform;
16
17/// Bound logical tool paths in UTF-16 units, matching JSON Schema string limits
18/// across supported clients without tying scoped paths to an OS-specific PATH_MAX.
19pub const MAX_PATH_UNITS: usize = 4096;
20
21/// Bound Artifact IDs like artifactize's Artifact names, so they stay short in tool output.
22pub const MAX_ARTIFACT_ID_BYTES: usize = 64;
23
24#[derive(Debug, Error)]
25#[error("{0}")]
26pub struct ScopeError(pub String);
27
28/// An Artifact's ID: `[A-Za-z0-9][A-Za-z0-9_-]{0,63}`, so it can never smuggle a path
29/// separator, a dot component, or control text into a scope key or a tool result.
30#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
31#[serde(transparent)]
32pub struct ArtifactId(String);
33
34impl ArtifactId {
35    pub fn new(value: impl Into<String>) -> Result<Self, ScopeError> {
36        let value = value.into();
37        let valid = value.len() <= MAX_ARTIFACT_ID_BYTES
38            && value
39                .bytes()
40                .next()
41                .is_some_and(|first| first.is_ascii_alphanumeric())
42            && value
43                .bytes()
44                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'));
45        if valid {
46            Ok(Self(value))
47        } else {
48            Err(ScopeError(format!(
49                "Artifact ID must match [A-Za-z0-9][A-Za-z0-9_-]{{0,63}}: {value:?}"
50            )))
51        }
52    }
53
54    pub fn as_str(&self) -> &str {
55        &self.0
56    }
57}
58
59/// Lets scope maps be looked up by a borrowed name; the derived order matches `str`'s.
60impl Borrow<str> for ArtifactId {
61    fn borrow(&self) -> &str {
62        &self.0
63    }
64}
65
66impl fmt::Display for ArtifactId {
67    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
68        formatter.write_str(&self.0)
69    }
70}
71
72impl PartialEq<str> for ArtifactId {
73    fn eq(&self, other: &str) -> bool {
74        self.0 == other
75    }
76}
77
78impl PartialEq<&str> for ArtifactId {
79    fn eq(&self, other: &&str) -> bool {
80        self.0 == *other
81    }
82}
83
84impl PartialEq<String> for ArtifactId {
85    fn eq(&self, other: &String) -> bool {
86        self.0 == *other
87    }
88}
89
90/// A safe relative logical path below an Artifact: `/`-separated plain names, such as a
91/// child Artifact's folder prefix. It holds no empty, `.` or `..` component.
92macro_rules! logical_name {
93    ($name:ident, $what:literal, $valid:expr) => {
94        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
95        #[serde(transparent)]
96        pub struct $name(String);
97
98        impl $name {
99            pub fn new(value: impl Into<String>) -> Result<Self, ScopeError> {
100                let value = value.into();
101                if !value.is_empty() && logical_path(&value).is_ok() && ($valid)(&value) {
102                    Ok(Self(value))
103                } else {
104                    Err(ScopeError(format!(
105                        concat!("Invalid ", $what, ": {:?}"),
106                        value
107                    )))
108                }
109            }
110
111            pub fn as_str(&self) -> &str {
112                &self.0
113            }
114        }
115
116        impl Borrow<str> for $name {
117            fn borrow(&self) -> &str {
118                &self.0
119            }
120        }
121
122        impl std::ops::Deref for $name {
123            type Target = str;
124            fn deref(&self) -> &str {
125                &self.0
126            }
127        }
128
129        impl fmt::Display for $name {
130            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
131                formatter.write_str(&self.0)
132            }
133        }
134    };
135}
136
137logical_name!(ChildPrefix, "child folder prefix", |_: &str| true);
138// A mount alias is one name: the first component of the paths it serves.
139logical_name!(MountAlias, "mount alias", |value: &str| !value
140    .contains('/'));
141
142#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
143#[serde(rename_all = "camelCase")]
144pub enum ArtifactKind {
145    Folder,
146    File,
147}
148
149/// Access data computed by the caller, without declarations, evals, or owner commands.
150#[derive(Debug, Clone)]
151pub struct Artifact {
152    pub path: PathBuf,
153    pub kind: ArtifactKind,
154    pub name: String,
155    /// Logical path prefix to the child Artifact that owns it.
156    pub children: BTreeMap<ChildPrefix, ArtifactId>,
157    /// Mount alias to the mounted Artifact.
158    pub mounts: BTreeMap<MountAlias, ArtifactId>,
159}
160
161impl Artifact {
162    pub fn folder(&self) -> &Path {
163        match self.kind {
164            ArtifactKind::Folder => &self.path,
165            ArtifactKind::File => self.path.parent().unwrap_or(Path::new("")),
166        }
167    }
168
169    pub fn file_name(&self) -> Option<&str> {
170        (self.kind == ArtifactKind::File)
171            .then(|| self.path.file_name().and_then(|name| name.to_str()))
172            .flatten()
173    }
174}
175
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct ScopedPath {
178    pub artifact_id: ArtifactId,
179    pub path: String,
180}
181
182#[derive(Debug)]
183pub struct Scope {
184    pub artifacts: BTreeMap<ArtifactId, Artifact>,
185}
186
187impl Scope {
188    /// Pure logical resolution. Each mount or child hop consumes path components.
189    pub fn resolve_path(
190        &self,
191        artifact_id: &ArtifactId,
192        path: &str,
193    ) -> Result<ScopedPath, ScopeError> {
194        logical_path(path)?;
195        let mut current = artifact_id;
196        let mut remaining = path;
197        loop {
198            let artifact = self
199                .artifacts
200                .get(current)
201                .ok_or_else(|| ScopeError(format!("Artifact is outside this review: {current}")))?;
202            if remaining.is_empty() {
203                break;
204            }
205            let (first, rest) = remaining.split_once('/').unwrap_or((remaining, ""));
206            if let Some(target) = artifact.mounts.get(first) {
207                current = target;
208                remaining = rest;
209                continue;
210            }
211            if let Some((prefix, target)) = artifact.children.iter().find(|(prefix, _)| {
212                remaining == prefix.as_str()
213                    || remaining
214                        .strip_prefix(prefix.as_str())
215                        .is_some_and(|rest| rest.starts_with('/'))
216            }) {
217                current = target;
218                remaining = remaining[prefix.len()..].strip_prefix('/').unwrap_or("");
219                continue;
220            }
221            break;
222        }
223        let artifact = &self.artifacts[current];
224        file_input(artifact, remaining)?;
225        Ok(ScopedPath {
226            artifact_id: current.clone(),
227            path: remaining.to_owned(),
228        })
229    }
230
231    /// Existing file or directory, without traversing links even inside the owner.
232    pub fn resolve_input(
233        &self,
234        root: &Path,
235        artifact_id: &ArtifactId,
236        path: &str,
237    ) -> Result<PathBuf, ScopeError> {
238        let location = self.resolve_path(artifact_id, path)?;
239        let artifact = &self.artifacts[&location.artifact_id];
240        let owner = scoped_path(root, artifact.folder())?;
241        let path = if location.path.is_empty() {
242            artifact.file_name().unwrap_or("")
243        } else {
244            &location.path
245        };
246        let resolved = scoped_path(&owner, Path::new(path))?;
247        let file =
248            open_input(root, artifact, path).map_err(|error| ScopeError(error.to_string()))?;
249        let regular = file
250            .metadata()
251            .map_err(|error| ScopeError(error.to_string()))?
252            .is_file();
253        if artifact.file_name().is_some() && !regular {
254            return Err(ScopeError(
255                "File Artifact target must remain a regular file.".into(),
256            ));
257        }
258        Ok(resolved)
259    }
260}
261
262/// Why a scoped open failed. A missing entry stays distinct, so a caller that knows the
263/// logical path the user asked for can name it.
264#[derive(Debug, Error)]
265pub enum OpenError {
266    #[error("No such file or directory.")]
267    NotFound,
268    /// A component is a link, which scoped access never follows.
269    #[error("Cannot open Artifact input without symlink traversal.")]
270    Link,
271    #[error(transparent)]
272    Refused(#[from] ScopeError),
273}
274
275/// Open each component relative to its pinned parent, so replacement cannot redirect a read
276/// through a link.
277pub fn open_input(root: &Path, artifact: &Artifact, path: &str) -> Result<File, OpenError> {
278    if !platform::is_absolute(root) || platform::is_absolute(&artifact.path) {
279        return Err(
280            ScopeError("Artifact roots must be absolute and owner paths relative.".into()).into(),
281        );
282    }
283    logical_path(path)?;
284    file_input(artifact, path)?;
285    let owner = open_scoped(&root.join(artifact.folder()), "")?;
286    // Keep the owner pinned between checking its namespace and opening each component.
287    // Check the parent of each reserved component: a nested APFS mount can have a different
288    // case policy from its owner volume. Exact-name checks additionally reject OS aliases.
289    let components: Vec<_> = path.split('/').filter(|part| !part.is_empty()).collect();
290    let mut file = owner;
291    for (depth, component) in components.iter().enumerate() {
292        let mount = depth == 0
293            && artifact
294                .mounts
295                .keys()
296                .any(|alias| alias.eq_ignore_ascii_case(component));
297        let child = artifact.children.keys().any(|prefix| {
298            let prefix: Vec<_> = prefix.split('/').collect();
299            prefix.len() == depth + 1
300                && prefix
301                    .iter()
302                    .zip(&components)
303                    .all(|(left, right)| left.eq_ignore_ascii_case(right))
304        });
305        if (mount || child)
306            && !platform::case_sensitive(&file).map_err(|error| ScopeError(error.to_string()))?
307        {
308            return Err(ScopeError(
309                "Physical input conflicts with a child or logical mount name.".into(),
310            )
311            .into());
312        }
313        file = open_child(&file, std::ffi::OsStr::new(component))?;
314    }
315    if artifact.file_name().is_some()
316        && !path.is_empty()
317        && !file
318            .metadata()
319            .map_err(|e| ScopeError(e.to_string()))?
320            .is_file()
321    {
322        return Err(ScopeError("File Artifact target must remain a regular file.".into()).into());
323    }
324    Ok(file)
325}
326
327/// A file Artifact exposes a virtual root containing only its target and mounts.
328fn file_input(artifact: &Artifact, path: &str) -> Result<(), ScopeError> {
329    if let Some(target) = artifact.file_name()
330        && !path.is_empty()
331        && path != target
332    {
333        return Err(ScopeError(format!(
334            "File Artifact {} exposes only its target {target} and mounts.",
335            artifact.name
336        )));
337    }
338    Ok(())
339}
340
341/// Open a relative path below an absolute root without following any symlink components.
342pub fn open_scoped(root: &Path, path: &str) -> Result<File, OpenError> {
343    logical_path(path)?;
344    if !platform::is_absolute(root) {
345        return Err(ScopeError("Scoped roots must be absolute.".into()).into());
346    }
347    let (filesystem_root, names) = platform::split_root(root)
348        .ok_or_else(|| ScopeError("Artifact path must not traverse parent directories.".into()))?;
349    let mut directory =
350        platform::open_directory(filesystem_root).map_err(|e| ScopeError(e.to_string()))?;
351    // Host-selected roots may use system aliases, such as short names. Logical components
352    // below that trusted root must use exact entry spellings. Both walks stay
353    // descriptor-relative and refuse links in every component.
354    let components = names.into_iter().map(|name| (name, false)).chain(
355        path.split('/')
356            .filter(|part| !part.is_empty())
357            .map(|part| (std::ffi::OsStr::new(part), true)),
358    );
359    for (name, exact) in components {
360        directory = match name {
361            name if name != ".." && name != "." => open_named(&directory, name, exact)?,
362            _ => {
363                return Err(ScopeError(
364                    "Artifact path must not traverse parent directories.".into(),
365                )
366                .into());
367            }
368        };
369    }
370    Ok(directory)
371}
372
373/// Open one entry of a pinned directory without following a symlink.
374pub fn open_child(directory: &File, name: &std::ffi::OsStr) -> Result<File, OpenError> {
375    open_named(directory, name, true)
376}
377
378fn open_named(directory: &File, name: &std::ffi::OsStr, exact: bool) -> Result<File, OpenError> {
379    let entry_name = platform::EntryName::new(name)
380        .ok_or_else(|| ScopeError("Invalid Artifact path.".into()))?;
381    let file = platform::open_entry(directory, &entry_name).map_err(|error| {
382        if error.kind() == io::ErrorKind::NotFound {
383            OpenError::NotFound
384        } else if platform::is_link_refusal(&error) {
385            OpenError::Link
386        } else {
387            ScopeError(format!("Cannot open Artifact input: {error}")).into()
388        }
389    })?;
390    if exact && !platform::exact_name(&file, name).map_err(|error| ScopeError(error.to_string()))? {
391        return Err(
392            ScopeError("Artifact path must use the exact directory entry name.".into()).into(),
393        );
394    }
395    let metadata = file.metadata().map_err(|e| ScopeError(e.to_string()))?;
396    if !metadata.is_file() && !metadata.is_dir() {
397        return Err(
398            ScopeError("Artifact input must be a regular file or directory.".into()).into(),
399        );
400    }
401    Ok(file)
402}
403
404pub fn logical_path(path: &str) -> Result<(), ScopeError> {
405    if path.encode_utf16().count() > MAX_PATH_UNITS
406        || path
407            .bytes()
408            .any(|byte| byte.is_ascii_control() || matches!(byte, b'\\' | b':'))
409        || (!path.is_empty()
410            && path
411                .split('/')
412                .any(|part| part.is_empty() || part == "." || part == ".."))
413    {
414        return Err(ScopeError(
415            "Artifact path must be a safe relative logical path.".into(),
416        ));
417    }
418    Ok(())
419}
420
421/// The logical form of a native relative path: its components joined with `/`, whatever
422/// separator the platform uses. `None` when a component is not UTF-8 or not a plain name.
423pub fn logical_from_native(path: &Path) -> Option<String> {
424    platform::logical_from_native(path)
425}
426
427/// Resolve a physical input below a canonical root. No component may be a symlink.
428pub fn scoped_path(root: &Path, path: &Path) -> Result<PathBuf, ScopeError> {
429    let relative =
430        platform::scoped_relative(path).map_err(|error| ScopeError(error.to_string()))?;
431    // The pinned, no-follow walk decides: it refuses links, special files and spellings
432    // other than the directory entry's own, so the returned path names what it opened.
433    match open_scoped(root, &relative) {
434        Ok(_) => Ok(relative
435            .split('/')
436            .filter(|part| !part.is_empty())
437            .fold(root.to_owned(), |path, part| path.join(part))),
438        Err(OpenError::NotFound) => Err(ScopeError(format!(
439            "Artifact input does not exist: {relative}"
440        ))),
441        Err(OpenError::Link) => Err(ScopeError("Artifact symlinks are not supported.".into())),
442        Err(OpenError::Refused(error)) => Err(error),
443    }
444}