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    Graph,
148}
149
150/// Access data computed by the caller, without declarations, evals, or owner commands.
151#[derive(Debug, Clone)]
152pub struct Artifact {
153    pub path: PathBuf,
154    pub kind: ArtifactKind,
155    pub name: String,
156    /// Logical path prefix to the child Artifact that owns it.
157    pub children: BTreeMap<ChildPrefix, ArtifactId>,
158    /// Mount alias to the mounted Artifact.
159    pub mounts: BTreeMap<MountAlias, ArtifactId>,
160}
161
162impl Artifact {
163    pub fn folder(&self) -> &Path {
164        match self.kind {
165            ArtifactKind::Folder | ArtifactKind::Graph => &self.path,
166            ArtifactKind::File => self.path.parent().unwrap_or(Path::new("")),
167        }
168    }
169
170    pub fn file_name(&self) -> Option<&str> {
171        (self.kind == ArtifactKind::File)
172            .then(|| self.path.file_name().and_then(|name| name.to_str()))
173            .flatten()
174    }
175}
176
177#[derive(Debug, Clone, PartialEq, Eq)]
178pub struct ScopedPath {
179    pub artifact_id: ArtifactId,
180    pub path: String,
181}
182
183#[derive(Debug)]
184pub struct Scope {
185    pub artifacts: BTreeMap<ArtifactId, Artifact>,
186}
187
188impl Scope {
189    /// Pure logical resolution. Each mount or child hop consumes path components.
190    pub fn resolve_path(
191        &self,
192        artifact_id: &ArtifactId,
193        path: &str,
194    ) -> Result<ScopedPath, ScopeError> {
195        logical_path(path)?;
196        let mut current = artifact_id;
197        let mut remaining = path;
198        loop {
199            let artifact = self
200                .artifacts
201                .get(current)
202                .ok_or_else(|| ScopeError(format!("Artifact is outside this review: {current}")))?;
203            if remaining.is_empty() {
204                break;
205            }
206            let (first, rest) = remaining.split_once('/').unwrap_or((remaining, ""));
207            if let Some(target) = artifact.mounts.get(first) {
208                current = target;
209                remaining = rest;
210                continue;
211            }
212            if let Some((prefix, target)) = artifact.children.iter().find(|(prefix, _)| {
213                remaining == prefix.as_str()
214                    || remaining
215                        .strip_prefix(prefix.as_str())
216                        .is_some_and(|rest| rest.starts_with('/'))
217            }) {
218                current = target;
219                remaining = remaining[prefix.len()..].strip_prefix('/').unwrap_or("");
220                continue;
221            }
222            break;
223        }
224        let artifact = &self.artifacts[current];
225        file_input(artifact, remaining)?;
226        Ok(ScopedPath {
227            artifact_id: current.clone(),
228            path: remaining.to_owned(),
229        })
230    }
231
232    /// Existing file or directory, without traversing links even inside the owner.
233    pub fn resolve_input(
234        &self,
235        root: &Path,
236        artifact_id: &ArtifactId,
237        path: &str,
238    ) -> Result<PathBuf, ScopeError> {
239        let location = self.resolve_path(artifact_id, path)?;
240        let artifact = &self.artifacts[&location.artifact_id];
241        let owner = scoped_path(root, artifact.folder())?;
242        let path = if location.path.is_empty() {
243            artifact.file_name().unwrap_or("")
244        } else {
245            &location.path
246        };
247        let resolved = scoped_path(&owner, Path::new(path))?;
248        let file =
249            open_input(root, artifact, path).map_err(|error| ScopeError(error.to_string()))?;
250        let regular = file
251            .metadata()
252            .map_err(|error| ScopeError(error.to_string()))?
253            .is_file();
254        if artifact.file_name().is_some() && !regular {
255            return Err(ScopeError(
256                "File Artifact target must remain a regular file.".into(),
257            ));
258        }
259        Ok(resolved)
260    }
261}
262
263/// Why a scoped open failed. A missing entry stays distinct, so a caller that knows the
264/// logical path the user asked for can name it.
265#[derive(Debug, Error)]
266pub enum OpenError {
267    #[error("No such file or directory.")]
268    NotFound,
269    /// A component is a link, which scoped access never follows.
270    #[error("Cannot open Artifact input without symlink traversal.")]
271    Link,
272    #[error(transparent)]
273    Refused(#[from] ScopeError),
274}
275
276/// Open each component relative to its pinned parent, so replacement cannot redirect a read
277/// through a link.
278pub fn open_input(root: &Path, artifact: &Artifact, path: &str) -> Result<File, OpenError> {
279    if !platform::is_absolute(root) || platform::is_absolute(&artifact.path) {
280        return Err(
281            ScopeError("Artifact roots must be absolute and owner paths relative.".into()).into(),
282        );
283    }
284    logical_path(path)?;
285    file_input(artifact, path)?;
286    let owner = open_scoped(&root.join(artifact.folder()), "")?;
287    // Keep the owner pinned between checking its namespace and opening each component.
288    // Check the parent of each reserved component: a nested APFS mount can have a different
289    // case policy from its owner volume. Exact-name checks additionally reject OS aliases.
290    let components: Vec<_> = path.split('/').filter(|part| !part.is_empty()).collect();
291    let mut file = owner;
292    for (depth, component) in components.iter().enumerate() {
293        let mount = depth == 0
294            && artifact
295                .mounts
296                .keys()
297                .any(|alias| alias.eq_ignore_ascii_case(component));
298        let child = artifact.children.keys().any(|prefix| {
299            let prefix: Vec<_> = prefix.split('/').collect();
300            prefix.len() == depth + 1
301                && prefix
302                    .iter()
303                    .zip(&components)
304                    .all(|(left, right)| left.eq_ignore_ascii_case(right))
305        });
306        if (mount || child)
307            && !platform::case_sensitive(&file).map_err(|error| ScopeError(error.to_string()))?
308        {
309            return Err(ScopeError(
310                "Physical input conflicts with a child or logical mount name.".into(),
311            )
312            .into());
313        }
314        file = open_child(&file, std::ffi::OsStr::new(component))?;
315    }
316    if artifact.file_name().is_some()
317        && !path.is_empty()
318        && !file
319            .metadata()
320            .map_err(|e| ScopeError(e.to_string()))?
321            .is_file()
322    {
323        return Err(ScopeError("File Artifact target must remain a regular file.".into()).into());
324    }
325    Ok(file)
326}
327
328/// A file Artifact exposes a virtual root containing only its target and mounts.
329fn file_input(artifact: &Artifact, path: &str) -> Result<(), ScopeError> {
330    if let Some(target) = artifact.file_name()
331        && !path.is_empty()
332        && path != target
333    {
334        return Err(ScopeError(format!(
335            "File Artifact {} exposes only its target {target} and mounts.",
336            artifact.name
337        )));
338    }
339    Ok(())
340}
341
342/// Open a relative path below an absolute root without following any symlink components.
343pub fn open_scoped(root: &Path, path: &str) -> Result<File, OpenError> {
344    logical_path(path)?;
345    if !platform::is_absolute(root) {
346        return Err(ScopeError("Scoped roots must be absolute.".into()).into());
347    }
348    let (filesystem_root, names) = platform::split_root(root)
349        .ok_or_else(|| ScopeError("Artifact path must not traverse parent directories.".into()))?;
350    let mut directory =
351        platform::open_directory(filesystem_root).map_err(|e| ScopeError(e.to_string()))?;
352    // Host-selected roots may use system aliases, such as short names. Logical components
353    // below that trusted root must use exact entry spellings. Both walks stay
354    // descriptor-relative and refuse links in every component.
355    let components = names.into_iter().map(|name| (name, false)).chain(
356        path.split('/')
357            .filter(|part| !part.is_empty())
358            .map(|part| (std::ffi::OsStr::new(part), true)),
359    );
360    for (name, exact) in components {
361        directory = match name {
362            name if name != ".." && name != "." => open_named(&directory, name, exact)?,
363            _ => {
364                return Err(ScopeError(
365                    "Artifact path must not traverse parent directories.".into(),
366                )
367                .into());
368            }
369        };
370    }
371    Ok(directory)
372}
373
374/// Open one entry of a pinned directory without following a symlink.
375pub fn open_child(directory: &File, name: &std::ffi::OsStr) -> Result<File, OpenError> {
376    open_named(directory, name, true)
377}
378
379fn open_named(directory: &File, name: &std::ffi::OsStr, exact: bool) -> Result<File, OpenError> {
380    let entry_name = platform::EntryName::new(name)
381        .ok_or_else(|| ScopeError("Invalid Artifact path.".into()))?;
382    let file = platform::open_entry(directory, &entry_name).map_err(|error| {
383        if error.kind() == io::ErrorKind::NotFound {
384            OpenError::NotFound
385        } else if platform::is_link_refusal(&error) {
386            OpenError::Link
387        } else {
388            ScopeError(format!("Cannot open Artifact input: {error}")).into()
389        }
390    })?;
391    if exact && !platform::exact_name(&file, name).map_err(|error| ScopeError(error.to_string()))? {
392        return Err(
393            ScopeError("Artifact path must use the exact directory entry name.".into()).into(),
394        );
395    }
396    let metadata = file.metadata().map_err(|e| ScopeError(e.to_string()))?;
397    if !metadata.is_file() && !metadata.is_dir() {
398        return Err(
399            ScopeError("Artifact input must be a regular file or directory.".into()).into(),
400        );
401    }
402    Ok(file)
403}
404
405pub fn logical_path(path: &str) -> Result<(), ScopeError> {
406    if path.encode_utf16().count() > MAX_PATH_UNITS
407        || path
408            .bytes()
409            .any(|byte| byte.is_ascii_control() || matches!(byte, b'\\' | b':'))
410        || (!path.is_empty()
411            && path
412                .split('/')
413                .any(|part| part.is_empty() || part == "." || part == ".."))
414    {
415        return Err(ScopeError(
416            "Artifact path must be a safe relative logical path.".into(),
417        ));
418    }
419    Ok(())
420}
421
422/// The logical form of a native relative path: its components joined with `/`, whatever
423/// separator the platform uses. `None` when a component is not UTF-8 or not a plain name.
424pub fn logical_from_native(path: &Path) -> Option<String> {
425    platform::logical_from_native(path)
426}
427
428/// Resolve a physical input below a canonical root. No component may be a symlink.
429pub fn scoped_path(root: &Path, path: &Path) -> Result<PathBuf, ScopeError> {
430    let relative =
431        platform::scoped_relative(path).map_err(|error| ScopeError(error.to_string()))?;
432    // The pinned, no-follow walk decides: it refuses links, special files and spellings
433    // other than the directory entry's own, so the returned path names what it opened.
434    match open_scoped(root, &relative) {
435        Ok(_) => Ok(relative
436            .split('/')
437            .filter(|part| !part.is_empty())
438            .fold(root.to_owned(), |path, part| path.join(part))),
439        Err(OpenError::NotFound) => Err(ScopeError(format!(
440            "Artifact input does not exist: {relative}"
441        ))),
442        Err(OpenError::Link) => Err(ScopeError("Artifact symlinks are not supported.".into())),
443        Err(OpenError::Refused(error)) => Err(error),
444    }
445}