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
10mod text;
11use text::native_path_text;
12pub use text::path_from_text;
13
14#[cfg(unix)]
15mod unix;
16#[cfg(windows)]
17mod windows;
18
19#[cfg(unix)]
20pub use unix::{
21    EntryName, canonicalize, case_sensitive, entry_kind, exact_name, is_link_refusal,
22    open_directory, open_entry, open_no_follow, open_nonblocking, read_dir, verified_path,
23};
24#[cfg(windows)]
25pub use windows::{
26    EntryName, canonicalize, case_sensitive, entry_kind, exact_name, is_link_refusal,
27    open_directory, open_entry, open_no_follow, open_nonblocking, read_dir, verified_path,
28};
29
30/// Native lexical equality: Windows accepts either separator; Unix does not.
31pub(crate) fn paths_equal(first: &Path, second: &Path) -> bool {
32    first == second
33}
34
35/// Whether a native path is absolute on this system.
36pub fn is_absolute(path: &std::path::Path) -> bool {
37    path.is_absolute()
38}
39
40/// The logical form of `path` below `root`: an absolute native path is taken relative to
41/// `root` (`None` outside it), a relative one is already logical.
42pub fn logical_below(root: &Path, path: &Path) -> Option<String> {
43    if path.is_absolute() {
44        logical_from_native(&relative_below(root, path)?)
45    } else {
46        logical_from_native(path)
47    }
48}
49
50/// `path` below `root`: the part after it. On Windows a verbatim (`\\?\`) spelling of either
51/// is compared as its plain one, the spelling path text renders.
52pub(crate) fn relative_below(root: &Path, path: &Path) -> Option<PathBuf> {
53    if let Ok(relative) = path.strip_prefix(root) {
54        return Some(relative.to_path_buf());
55    }
56    #[cfg(windows)]
57    {
58        let plain = |path: &Path| windows::plain(path).unwrap_or_else(|| path.to_path_buf());
59        plain(path)
60            .strip_prefix(plain(root))
61            .ok()
62            .map(Path::to_path_buf)
63    }
64    #[cfg(not(windows))]
65    None
66}
67
68pub(crate) fn parent(path: &Path) -> Option<&Path> {
69    path.parent()
70}
71
72/// The filesystem root of an absolute path (`/`, or a Windows volume or share) and the names
73/// below it, in order. `None` when a component is `.` or `..`.
74pub fn split_root(path: &std::path::Path) -> Option<(&std::path::Path, Vec<&std::ffi::OsStr>)> {
75    use std::path::Component;
76    let root = path.ancestors().last()?;
77    path.components()
78        .filter_map(|component| match component {
79            Component::Prefix(_) | Component::RootDir => None,
80            Component::Normal(name) => Some(Some(name)),
81            Component::CurDir | Component::ParentDir => Some(None),
82        })
83        .collect::<Option<Vec<_>>>()
84        .map(|names| (root, names))
85}
86
87/// The target a link names, read without following it: a symlink's text, or on Windows a
88/// junction's or symbolic link's substitute name.
89pub fn link_target(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
90    std::fs::read_link(path)
91}
92
93/// Whether a name can reach an entry spelled differently, as case-insensitive Windows and
94/// macOS volumes allow; path-returning interfaces then also check the exact spelling.
95pub const ALIASED_NAMES: bool = cfg!(any(windows, target_os = "macos"));
96
97/// The type of a directory entry, read without following it.
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum FileKind {
100    File,
101    Directory,
102    Symlink,
103    /// FIFOs, sockets, devices, and on Windows reparse points that are not links.
104    Other,
105}
106
107/// Read the process's current directory and resolve its native filesystem aliases.
108pub fn current_directory() -> std::io::Result<std::path::PathBuf> {
109    canonicalize(&std::env::current_dir()?)
110}
111
112/// Text shown for a native path or a logical external target, never an I/O conversion.
113pub trait PathText {
114    fn path_text(&self) -> String;
115}
116impl<P: AsRef<std::path::Path> + ?Sized> PathText for P {
117    fn path_text(&self) -> String {
118        native_path_text(self.as_ref())
119    }
120}
121/// Render a path for people and JSON clients; logical external targets stay opaque.
122pub fn path_text<P: PathText + ?Sized>(path: &P) -> String {
123    path.path_text()
124}
125
126/// Convert a native relative path into logical components; roots, traversal and non-UTF-8
127/// names are refused rather than guessing at the host's separator or prefix rules.
128pub fn logical_from_native(path: &std::path::Path) -> Option<String> {
129    scoped_relative(path).ok()
130}
131
132/// The native name can be represented as one logical component, with no reinterpretation.
133pub(crate) fn logical_entry_name(name: &OsStr) -> Option<&str> {
134    let text = name.to_str()?;
135    (!matches!(text, "" | "." | "..")
136        && !text
137            .bytes()
138            .any(|byte| byte.is_ascii_control() || matches!(byte, b'/' | b'\\' | b':')))
139    .then_some(text)
140}
141
142/// Validate native relative paths before traversing them. In particular, Windows prefixes
143/// and root-only paths can replace a join's base without being absolute.
144pub(crate) fn relative_names(path: &Path) -> io::Result<Vec<&OsStr>> {
145    let invalid = || {
146        io::Error::new(
147            io::ErrorKind::InvalidInput,
148            "Artifact path must be relative to its declared root and use logical names.",
149        )
150    };
151    let text = path.to_str().ok_or_else(invalid)?;
152    if text
153        .split(|character| character == '/' || cfg!(windows) && character == '\\')
154        .any(|part| matches!(part, "." | ".."))
155    {
156        return Err(invalid());
157    }
158    path.components()
159        .map(|component| match component {
160            Component::Normal(name) if logical_entry_name(name).is_some() => Ok(name),
161            _ => Err(invalid()),
162        })
163        .collect()
164}
165
166pub fn scoped_relative(path: &Path) -> io::Result<String> {
167    relative_names(path).map(relative_text)
168}
169
170/// A command-line path relative to the working folder as logical text: `.` (or only `.`
171/// components) is the folder itself, empty; otherwise its validated names joined by `/`.
172pub(crate) fn relative_text_of(path: &Path) -> io::Result<String> {
173    if path
174        .components()
175        .all(|component| matches!(component, std::path::Component::CurDir))
176    {
177        return Ok(String::new());
178    }
179    relative_names(path).map(relative_text)
180}
181
182/// Render entry names already validated by `relative_names` as a logical slash path.
183pub(crate) fn relative_text<'a>(names: impl IntoIterator<Item = &'a OsStr>) -> String {
184    names
185        .into_iter()
186        .map(|name| name.to_str().expect("validated logical name"))
187        .collect::<Vec<_>>()
188        .join("/")
189}
190
191/// Decode a persisted slash path into a native path and its validated entry names.
192pub(crate) fn parse_target_path(text: &str) -> io::Result<(PathBuf, Vec<OsString>)> {
193    // Empty and dot both denote the project root in saved targets.
194    if matches!(text, "" | ".") {
195        return Ok((PathBuf::new(), Vec::new()));
196    }
197    let names = text
198        .split('/')
199        .map(|name| {
200            logical_entry_name(OsStr::new(name))
201                .map(OsString::from)
202                .ok_or_else(|| {
203                    io::Error::new(
204                        io::ErrorKind::InvalidInput,
205                        "Invalid slash path for an Artifact target.",
206                    )
207                })
208        })
209        .collect::<io::Result<Vec<_>>>()?;
210    Ok((names.iter().collect(), names))
211}
212
213/// Determine aliasing by looking up the reserved spelling in the same pinned directory.
214/// This uses that directory's filesystem comparison (including Unicode and short names),
215/// rather than a guessed case policy or a string fold shared by unlike filesystems.
216pub(crate) fn same_entry_name(parent: &File, actual: &OsStr, reserved: &OsStr) -> io::Result<bool> {
217    if actual == reserved {
218        return Ok(true);
219    }
220    let Some(name) = EntryName::new(reserved) else {
221        return Ok(false);
222    };
223    match open_entry(parent, &name) {
224        // Two exact entries can be distinct directory names for the same inode.
225        Ok(alias) => {
226            Ok(!exact_name(parent, &alias, reserved)? && exact_name(parent, &alias, actual)?)
227        }
228        Err(error)
229            if is_link_refusal(&error)
230                || matches!(
231                    error.kind(),
232                    io::ErrorKind::NotFound
233                        | io::ErrorKind::PermissionDenied
234                        | io::ErrorKind::InvalidInput
235                ) =>
236        {
237            Ok(false)
238        }
239        Err(error) => Err(error),
240    }
241}
242
243/// Keep declaration inputs bounded at the existing 1024 UTF-16-unit wire limit.
244const MAX_DECLARATION_PATH_UNITS: usize = 1024;
245
246/// The declaration-path grammar is portable even on a host that permits these names.
247pub fn declaration_path(value: &str) -> Result<(), String> {
248    let drive_rooted = value
249        .as_bytes()
250        .first()
251        .is_some_and(u8::is_ascii_alphabetic)
252        && value.as_bytes().get(1) == Some(&b':')
253        && value.as_bytes().get(2) == Some(&b'/');
254    if value.encode_utf16().count() > MAX_DECLARATION_PATH_UNITS
255        || drive_rooted
256        || value
257            .bytes()
258            .any(|byte| byte.is_ascii_control() || byte == b'\\')
259        || value
260            .split('/')
261            .any(|part| part.is_empty() || part == "." || part == "..")
262    {
263        return Err("Execution input must be a safe project-relative path.".into());
264    }
265    Ok(())
266}
267
268#[cfg(test)]
269mod tests {
270    use super::path_text;
271
272    // reason: only Unix allows '\' in file names.
273    #[cfg(unix)]
274    #[test]
275    fn literal_backslash_in_a_file_name_is_not_a_separator() {
276        let root = crate::test_os::tempdir();
277        let path = crate::test_os::file_with_backslash(root.path());
278        assert_eq!(
279            path_text(std::path::Path::new(path.file_name().unwrap())),
280            r"input\name"
281        );
282    }
283
284    // Windows supports prefixes and roots that are not absolute in Rust's Path grammar.
285    #[cfg(windows)]
286    #[test]
287    fn pinned_owners_refuse_drive_relative_and_rooted_paths() {
288        use crate::scope::Target;
289        for path in [r"C:owner", r"\owner"] {
290            assert!(
291                Target::try_from(path)
292                    .unwrap_err()
293                    .to_string()
294                    .contains("relative to its declared root")
295            );
296        }
297    }
298
299    // Only the Windows verbatim namespace preserves trailing dots in a file name.
300    #[cfg(windows)]
301    #[test]
302    fn a_pin_with_a_win32_alias_is_not_returned_as_an_ordinary_path() {
303        use crate::scope::{open_scoped, scoped_path};
304        let root = crate::test_os::tempdir();
305        let root = crate::test_os::trailing_dot_alias(root.path());
306        assert!(open_scoped(&root, "literal.").is_ok());
307        assert!(
308            scoped_path(&root, std::path::Path::new("literal."))
309                .unwrap_err()
310                .to_string()
311                .contains("ordinary Windows path")
312        );
313    }
314
315    // reason: Windows native paths use backslash separators.
316    #[cfg(windows)]
317    #[test]
318    fn native_separators_are_rendered_as_slashes() {
319        assert_eq!(
320            path_text(std::path::Path::new(r"C:\input\name")),
321            "C:/input/name"
322        );
323    }
324
325    // reason: Windows canonical paths can carry verbatim disk and UNC prefixes.
326    #[cfg(windows)]
327    #[test]
328    fn verbatim_paths_render_without_the_native_prefix() {
329        assert_eq!(
330            path_text(std::path::Path::new(r"\\?\C:\input\name")),
331            "C:/input/name"
332        );
333        assert_eq!(
334            path_text(std::path::Path::new(r"\\?\UNC\server\share\input")),
335            "//server/share/input"
336        );
337    }
338}