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