artifactize-tools 0.27.1

Portable scoped tools and safe file access for artifactize.
Documentation
//! Shared safe file access: pinned no-follow opens and directory listings.

use std::{
    ffi::{OsStr, OsString},
    fs::File,
    io,
    path::{Component, Path, PathBuf},
};

pub use artifactize_foundation::platform::files::*;

/// Native lexical equality: Windows accepts either separator; Unix does not.
pub(crate) fn paths_equal(first: &Path, second: &Path) -> bool {
    first == second
}

/// Whether a native path is absolute on this system.
pub fn is_absolute(path: &std::path::Path) -> bool {
    path.is_absolute()
}

/// The logical form of `path` below `root`: an absolute native path is taken relative to
/// `root` (`None` outside it), a relative one is already logical.
pub fn logical_below(root: &Path, path: &Path) -> Option<String> {
    if path.is_absolute() {
        logical_from_native(&relative_below(root, path)?)
    } else {
        logical_from_native(path)
    }
}

/// `path` below `root`: the part after the matching ancestor. Compare opened
/// directory identities when the spelling differs, without rewriting child names.
pub(crate) fn relative_below(root: &Path, path: &Path) -> Option<PathBuf> {
    if let Ok(relative) = path.strip_prefix(root) {
        return Some(relative.to_path_buf());
    }
    let ancestor = path
        .ancestors()
        .find(|ancestor| artifactize_foundation::platform::paths::paths_equal(ancestor, root))?;
    path.strip_prefix(ancestor).ok().map(Path::to_path_buf)
}

pub(crate) fn parent(path: &Path) -> Option<&Path> {
    path.parent()
}

/// Convert a native relative path into logical components; roots, traversal and non-UTF-8
/// names are refused rather than guessing at the host's separator or prefix rules.
pub fn logical_from_native(path: &std::path::Path) -> Option<String> {
    scoped_relative(path).ok()
}

/// The native name can be represented as one logical component, with no reinterpretation.
pub(crate) fn logical_entry_name(name: &OsStr) -> Option<&str> {
    let text = name.to_str()?;
    (!matches!(text, "" | "." | "..")
        && !text
            .bytes()
            .any(|byte| byte.is_ascii_control() || matches!(byte, b'/' | b'\\' | b':')))
    .then_some(text)
}

/// Validate native relative paths before traversing them. In particular, Windows prefixes
/// and root-only paths can replace a join's base without being absolute.
pub(crate) fn relative_names(path: &Path) -> io::Result<Vec<&OsStr>> {
    let invalid = || {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            "Artifact path must be relative to its declared root and use logical names.",
        )
    };
    let text = path.to_str().ok_or_else(invalid)?;
    if text
        .split(|character| character == '/' || cfg!(windows) && character == '\\')
        .any(|part| matches!(part, "." | ".."))
    {
        return Err(invalid());
    }
    path.components()
        .map(|component| match component {
            Component::Normal(name) if logical_entry_name(name).is_some() => Ok(name),
            _ => Err(invalid()),
        })
        .collect()
}

pub fn scoped_relative(path: &Path) -> io::Result<String> {
    relative_names(path).map(relative_text)
}

/// A command-line path relative to the working folder as logical text: `.` (or only `.`
/// components) is the folder itself, empty; otherwise its validated names joined by `/`.
pub(crate) fn relative_text_of(path: &Path) -> io::Result<String> {
    if path
        .components()
        .all(|component| matches!(component, std::path::Component::CurDir))
    {
        return Ok(String::new());
    }
    relative_names(path).map(relative_text)
}

/// Render entry names already validated by `relative_names` as a logical slash path.
pub(crate) fn relative_text<'a>(names: impl IntoIterator<Item = &'a OsStr>) -> String {
    names
        .into_iter()
        .map(|name| name.to_str().expect("validated logical name"))
        .collect::<Vec<_>>()
        .join("/")
}

/// Decode a persisted slash path into a native path and its validated entry names.
pub(crate) fn parse_target_path(text: &str) -> io::Result<(PathBuf, Vec<OsString>)> {
    // Empty and dot both denote the project root in saved targets.
    if matches!(text, "" | ".") {
        return Ok((PathBuf::new(), Vec::new()));
    }
    let names = text
        .split('/')
        .map(|name| {
            logical_entry_name(OsStr::new(name))
                .map(OsString::from)
                .ok_or_else(|| {
                    io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "Invalid slash path for an Artifact target.",
                    )
                })
        })
        .collect::<io::Result<Vec<_>>>()?;
    Ok((names.iter().collect(), names))
}

/// Determine aliasing by looking up the reserved spelling in the same pinned directory.
/// This uses that directory's filesystem comparison (including Unicode and short names),
/// rather than a guessed case policy or a string fold shared by unlike filesystems.
pub(crate) fn same_entry_name(parent: &File, actual: &OsStr, reserved: &OsStr) -> io::Result<bool> {
    if actual == reserved {
        return Ok(true);
    }
    let Some(name) = EntryName::new(reserved) else {
        return Ok(false);
    };
    match open_entry(parent, &name) {
        // Two exact entries can be distinct directory names for the same inode.
        Ok(alias) => {
            Ok(!exact_name(parent, &alias, reserved)? && exact_name(parent, &alias, actual)?)
        }
        Err(error)
            if is_link_refusal(&error)
                || matches!(
                    error.kind(),
                    io::ErrorKind::NotFound
                        | io::ErrorKind::PermissionDenied
                        | io::ErrorKind::InvalidInput
                ) =>
        {
            Ok(false)
        }
        Err(error) => Err(error),
    }
}

/// Keep declaration inputs bounded at the existing 1024 UTF-16-unit wire limit.
const MAX_DECLARATION_PATH_UNITS: usize = 1024;

/// The declaration-path grammar is portable even on a host that permits these names.
pub fn declaration_path(value: &str) -> Result<(), String> {
    let drive_rooted = value
        .as_bytes()
        .first()
        .is_some_and(u8::is_ascii_alphabetic)
        && value.as_bytes().get(1) == Some(&b':')
        && value.as_bytes().get(2) == Some(&b'/');
    if value.encode_utf16().count() > MAX_DECLARATION_PATH_UNITS
        || drive_rooted
        || value
            .bytes()
            .any(|byte| byte.is_ascii_control() || byte == b'\\')
        || value
            .split('/')
            .any(|part| part.is_empty() || part == "." || part == "..")
    {
        return Err("Execution input must be a safe project-relative path.".into());
    }
    Ok(())
}

#[cfg(test)]
mod tests;