Skip to main content

artifactize_tools/platform/
files.rs

1//! Shared safe file access: pinned no-follow opens and directory listings.
2
3use std::{
4    ffi::{OsStr, OsString},
5    fs::File,
6    io,
7    path::{Component, Path, PathBuf},
8};
9
10pub use artifactize_foundation::platform::files::*;
11
12/// Native lexical equality: Windows accepts either separator; Unix does not.
13pub(crate) fn paths_equal(first: &Path, second: &Path) -> bool {
14    first == second
15}
16
17/// Whether a native path is absolute on this system.
18pub fn is_absolute(path: &std::path::Path) -> bool {
19    path.is_absolute()
20}
21
22/// The logical form of `path` below `root`: an absolute native path is taken relative to
23/// `root` (`None` outside it), a relative one is already logical.
24pub fn logical_below(root: &Path, path: &Path) -> Option<String> {
25    if path.is_absolute() {
26        logical_from_native(&relative_below(root, path)?)
27    } else {
28        logical_from_native(path)
29    }
30}
31
32/// `path` below `root`: the part after the matching ancestor. Compare opened
33/// directory identities when the spelling differs, without rewriting child names.
34pub(crate) fn relative_below(root: &Path, path: &Path) -> Option<PathBuf> {
35    if let Ok(relative) = path.strip_prefix(root) {
36        return Some(relative.to_path_buf());
37    }
38    let ancestor = path
39        .ancestors()
40        .find(|ancestor| artifactize_foundation::platform::paths::paths_equal(ancestor, root))?;
41    path.strip_prefix(ancestor).ok().map(Path::to_path_buf)
42}
43
44pub(crate) fn parent(path: &Path) -> Option<&Path> {
45    path.parent()
46}
47
48/// Convert a native relative path into logical components; roots, traversal and non-UTF-8
49/// names are refused rather than guessing at the host's separator or prefix rules.
50pub fn logical_from_native(path: &std::path::Path) -> Option<String> {
51    scoped_relative(path).ok()
52}
53
54/// The native name can be represented as one logical component, with no reinterpretation.
55pub(crate) fn logical_entry_name(name: &OsStr) -> Option<&str> {
56    let text = name.to_str()?;
57    (!matches!(text, "" | "." | "..")
58        && !text
59            .bytes()
60            .any(|byte| byte.is_ascii_control() || matches!(byte, b'/' | b'\\' | b':')))
61    .then_some(text)
62}
63
64/// Validate native relative paths before traversing them. In particular, Windows prefixes
65/// and root-only paths can replace a join's base without being absolute.
66pub(crate) fn relative_names(path: &Path) -> io::Result<Vec<&OsStr>> {
67    let invalid = || {
68        io::Error::new(
69            io::ErrorKind::InvalidInput,
70            "Artifact path must be relative to its declared root and use logical names.",
71        )
72    };
73    let text = path.to_str().ok_or_else(invalid)?;
74    if text
75        .split(|character| character == '/' || cfg!(windows) && character == '\\')
76        .any(|part| matches!(part, "." | ".."))
77    {
78        return Err(invalid());
79    }
80    path.components()
81        .map(|component| match component {
82            Component::Normal(name) if logical_entry_name(name).is_some() => Ok(name),
83            _ => Err(invalid()),
84        })
85        .collect()
86}
87
88pub fn scoped_relative(path: &Path) -> io::Result<String> {
89    relative_names(path).map(relative_text)
90}
91
92/// A command-line path relative to the working folder as logical text: `.` (or only `.`
93/// components) is the folder itself, empty; otherwise its validated names joined by `/`.
94pub(crate) fn relative_text_of(path: &Path) -> io::Result<String> {
95    if path
96        .components()
97        .all(|component| matches!(component, std::path::Component::CurDir))
98    {
99        return Ok(String::new());
100    }
101    relative_names(path).map(relative_text)
102}
103
104/// Render entry names already validated by `relative_names` as a logical slash path.
105pub(crate) fn relative_text<'a>(names: impl IntoIterator<Item = &'a OsStr>) -> String {
106    names
107        .into_iter()
108        .map(|name| name.to_str().expect("validated logical name"))
109        .collect::<Vec<_>>()
110        .join("/")
111}
112
113/// Decode a persisted slash path into a native path and its validated entry names.
114pub(crate) fn parse_target_path(text: &str) -> io::Result<(PathBuf, Vec<OsString>)> {
115    // Empty and dot both denote the project root in saved targets.
116    if matches!(text, "" | ".") {
117        return Ok((PathBuf::new(), Vec::new()));
118    }
119    let names = text
120        .split('/')
121        .map(|name| {
122            logical_entry_name(OsStr::new(name))
123                .map(OsString::from)
124                .ok_or_else(|| {
125                    io::Error::new(
126                        io::ErrorKind::InvalidInput,
127                        "Invalid slash path for an Artifact target.",
128                    )
129                })
130        })
131        .collect::<io::Result<Vec<_>>>()?;
132    Ok((names.iter().collect(), names))
133}
134
135/// Determine aliasing by looking up the reserved spelling in the same pinned directory.
136/// This uses that directory's filesystem comparison (including Unicode and short names),
137/// rather than a guessed case policy or a string fold shared by unlike filesystems.
138pub(crate) fn same_entry_name(parent: &File, actual: &OsStr, reserved: &OsStr) -> io::Result<bool> {
139    if actual == reserved {
140        return Ok(true);
141    }
142    let Some(name) = EntryName::new(reserved) else {
143        return Ok(false);
144    };
145    match open_entry(parent, &name) {
146        // Two exact entries can be distinct directory names for the same inode.
147        Ok(alias) => {
148            Ok(!exact_name(parent, &alias, reserved)? && exact_name(parent, &alias, actual)?)
149        }
150        Err(error)
151            if is_link_refusal(&error)
152                || matches!(
153                    error.kind(),
154                    io::ErrorKind::NotFound
155                        | io::ErrorKind::PermissionDenied
156                        | io::ErrorKind::InvalidInput
157                ) =>
158        {
159            Ok(false)
160        }
161        Err(error) => Err(error),
162    }
163}
164
165/// Keep declaration inputs bounded at the existing 1024 UTF-16-unit wire limit.
166const MAX_DECLARATION_PATH_UNITS: usize = 1024;
167
168/// The declaration-path grammar is portable even on a host that permits these names.
169pub fn declaration_path(value: &str) -> Result<(), String> {
170    let drive_rooted = value
171        .as_bytes()
172        .first()
173        .is_some_and(u8::is_ascii_alphabetic)
174        && value.as_bytes().get(1) == Some(&b':')
175        && value.as_bytes().get(2) == Some(&b'/');
176    if value.encode_utf16().count() > MAX_DECLARATION_PATH_UNITS
177        || drive_rooted
178        || value
179            .bytes()
180            .any(|byte| byte.is_ascii_control() || byte == b'\\')
181        || value
182            .split('/')
183            .any(|part| part.is_empty() || part == "." || part == "..")
184    {
185        return Err("Execution input must be a safe project-relative path.".into());
186    }
187    Ok(())
188}
189
190#[cfg(test)]
191mod tests;