Skip to main content

artifactize_tools/scope/
open.rs

1//! Open validated logical inputs through pinned parent directories, never through links.
2
3use std::{
4    ffi::OsStr,
5    fs::File,
6    io,
7    path::{Path, PathBuf},
8};
9use thiserror::Error;
10
11use super::{Artifact, InputPath, Location, MAX_PATH_UNITS, ScopeError, file_input};
12use crate::files as platform;
13
14/// Why a scoped open failed. Missing entries stay distinct so callers can name the input.
15#[derive(Debug, Error)]
16pub enum OpenError {
17    #[error("No such file or directory.")]
18    NotFound,
19    #[error("Cannot open Artifact input without symlink traversal.")]
20    Link,
21    #[error(transparent)]
22    Refused(#[from] ScopeError),
23}
24
25impl Location<'_, '_> {
26    pub(crate) fn open(&self, root: &Path) -> Result<File, OpenError> {
27        open_owned(root, self.artifact, self.path).map(|opened| opened.file)
28    }
29
30    /// The virtual root of a file Artifact names its one file for direct text reads and open.
31    pub(crate) fn direct_path(&self) -> Result<InputPath<&str>, ScopeError> {
32        match self
33            .artifact
34            .file_name()
35            .filter(|_| self.path.as_str().is_empty())
36        {
37            Some(name) => InputPath::parse(name),
38            None => Ok(self.path),
39        }
40    }
41
42    pub(crate) fn open_direct(&self, root: &Path) -> Result<(InputPath<&str>, File), OpenError> {
43        let path = self.direct_path()?;
44        open_owned(root, self.artifact, path).map(|opened| (path, opened.file))
45    }
46
47    pub(crate) fn native_path(&self, root: &Path) -> Result<PathBuf, ScopeError> {
48        let path = self.direct_path()?;
49        native_path(open_owned(root, self.artifact, path), root, path.as_str())
50    }
51}
52
53/// Open each component relative to its pinned parent, so replacement cannot redirect a read
54/// through a link.
55pub fn open_input(root: &Path, artifact: &Artifact, path: &str) -> Result<File, OpenError> {
56    let path = InputPath::parse(path)?;
57    file_input(artifact, path)?;
58    open_owned(root, artifact, path).map(|opened| opened.file)
59}
60
61struct Opened<'a> {
62    file: File,
63    names: Vec<&'a OsStr>,
64}
65
66fn open_owned<'a>(
67    root: &'a Path,
68    artifact: &'a Artifact,
69    path: InputPath<&'a str>,
70) -> Result<Opened<'a>, OpenError> {
71    let owner = artifact
72        .path
73        .folder_names()
74        .ok_or_else(|| ScopeError("Live Artifacts have no filesystem inputs.".into()))?;
75    let mut opened = open_folder(root, owner)?;
76    let mut reserved: Vec<_> = artifact
77        .nested
78        .keys()
79        .map(|prefix| prefix.split('/').peekable())
80        .collect();
81    for name in path.names().map(OsStr::new) {
82        let parent = opened.file;
83        let file = open_child(&parent, name)?;
84        // Compare reserved spellings through this pinned parent, whose filesystem may
85        // apply a different case or normalization policy from the Artifact root.
86        let mut descendants = Vec::new();
87        for mut prefix in reserved {
88            if let Some(candidate) = prefix.next()
89                && platform::same_entry_name(&parent, name, OsStr::new(candidate))
90                    .map_err(io_scope)?
91            {
92                if prefix.peek().is_none() {
93                    return Err(
94                        ScopeError("Physical input conflicts with a child name.".into()).into(),
95                    );
96                }
97                descendants.push(prefix);
98            }
99        }
100        reserved = descendants;
101        opened.file = file;
102        opened.names.push(name);
103    }
104    if artifact.file_name().is_some()
105        && !path.as_str().is_empty()
106        && !opened.file.metadata().map_err(io_scope)?.is_file()
107    {
108        return Err(ScopeError("File Artifact target must remain a regular file.".into()).into());
109    }
110    Ok(opened)
111}
112
113impl Artifact {
114    pub(crate) fn native_folder(&self, root: &Path) -> Result<PathBuf, ScopeError> {
115        // A Live Artifact has no files; its help program can still run from the workspace.
116        let names = self.path.folder_names().unwrap_or_default();
117        native_path(
118            open_folder(root, names),
119            root,
120            &platform::path_text(self.folder()),
121        )
122    }
123}
124
125fn open_folder<'a>(
126    root: &'a Path,
127    names: &'a [std::ffi::OsString],
128) -> Result<Opened<'a>, OpenError> {
129    let mut opened = open_root(root)?;
130    for name in names {
131        opened.descend(name)?;
132    }
133    Ok(opened)
134}
135
136impl<'a> Opened<'a> {
137    fn descend(&mut self, name: &'a OsStr) -> Result<(), OpenError> {
138        self.file = open_child(&self.file, name)?;
139        self.names.push(name);
140        Ok(())
141    }
142}
143
144fn open_root(root: &Path) -> Result<Opened<'_>, OpenError> {
145    if !platform::is_absolute(root) {
146        return Err(ScopeError("Scoped roots must be absolute.".into()).into());
147    }
148    let (filesystem_root, names) = platform::split_root(root)
149        .ok_or_else(|| ScopeError("Artifact path must not traverse parent directories.".into()))?;
150    let mut file = platform::open_directory(filesystem_root).map_err(io_scope)?;
151    // The host-selected root may use system aliases. Exact names are required below it.
152    for name in names {
153        file = open_named(&file, name, false)?;
154    }
155    Ok(Opened {
156        file,
157        names: Vec::new(),
158    })
159}
160
161/// Open a relative path below an absolute root without following any symlink components.
162pub fn open_scoped(root: &Path, path: &str) -> Result<File, OpenError> {
163    let path = InputPath::parse(path)?;
164    walk(root, path.names().map(OsStr::new)).map(|opened| opened.file)
165}
166
167fn walk<'a>(
168    root: &'a Path,
169    names: impl IntoIterator<Item = &'a OsStr>,
170) -> Result<Opened<'a>, OpenError> {
171    let mut opened = open_root(root)?;
172    for name in names {
173        opened.descend(name)?;
174    }
175    Ok(opened)
176}
177
178/// Open one entry of a pinned directory without following a symlink.
179pub fn open_child(directory: &File, name: &OsStr) -> Result<File, OpenError> {
180    open_named(directory, name, true)
181}
182
183fn open_named(directory: &File, name: &OsStr, exact: bool) -> Result<File, OpenError> {
184    let entry_name = platform::EntryName::new(name)
185        .ok_or_else(|| ScopeError("Invalid Artifact path.".into()))?;
186    let file = platform::open_entry(directory, &entry_name).map_err(|error| {
187        if error.kind() == io::ErrorKind::NotFound {
188            OpenError::NotFound
189        } else if platform::is_link_refusal(&error) {
190            OpenError::Link
191        } else {
192            ScopeError(format!("Cannot open Artifact input: {error}")).into()
193        }
194    })?;
195    if exact && !platform::exact_name(directory, &file, name).map_err(io_scope)? {
196        return Err(
197            ScopeError("Artifact path must use the exact directory entry name.".into()).into(),
198        );
199    }
200    let metadata = file.metadata().map_err(io_scope)?;
201    if !metadata.is_file() && !metadata.is_dir() {
202        return Err(
203            ScopeError("Artifact input must be a regular file or directory.".into()).into(),
204        );
205    }
206    Ok(file)
207}
208
209/// Resolve a physical input below a canonical root. No component may be a symlink.
210pub fn scoped_path(root: &Path, path: &Path) -> Result<PathBuf, ScopeError> {
211    let (names, relative) = native_relative(path)?;
212    native_path(walk(root, names), root, &relative)
213}
214
215/// Open a native relative path without a second logical parse.
216pub(crate) fn open_native_scoped(root: &Path, path: &Path) -> Result<File, OpenError> {
217    let (names, _) = native_relative(path)?;
218    walk(root, names).map(|opened| opened.file)
219}
220
221fn native_relative(path: &Path) -> Result<(Vec<&OsStr>, String), ScopeError> {
222    let names = platform::relative_names(path).map_err(io_scope)?;
223    let relative = platform::relative_text(names.iter().copied());
224    if relative.encode_utf16().count() > MAX_PATH_UNITS {
225        return Err(ScopeError(
226            "Artifact path must be a safe relative logical path.".into(),
227        ));
228    }
229    Ok((names, relative))
230}
231
232fn native_path(
233    opened: Result<Opened<'_>, OpenError>,
234    root: &Path,
235    path: &str,
236) -> Result<PathBuf, ScopeError> {
237    match opened {
238        Ok(opened) => platform::verified_path(&opened.file, root, &opened.names).map_err(io_scope),
239        Err(OpenError::NotFound) => {
240            Err(ScopeError(format!("Artifact input does not exist: {path}")))
241        }
242        Err(OpenError::Link) => Err(ScopeError("Artifact symlinks are not supported.".into())),
243        Err(OpenError::Refused(error)) => Err(error),
244    }
245}
246
247fn io_scope(error: io::Error) -> ScopeError {
248    ScopeError(error.to_string())
249}