oxinav-core 0.3.0

Core logic for OxiNav: file operations, pane state, archives and viewing, with no UI dependency
Documentation
//! Archive support: recognising a supported format and keeping extraction
//! inside its destination.
//!
//! Both decisions are pure functions over paths so they can be exercised
//! without an archive on disk; the decoding itself lives behind the
//! `Filesystem` trait.

use std::path::{Component, Path, PathBuf};

/// An archive format the viewer can extract.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArchiveFormat {
    Zip,
    Tar,
    TarGz,
}

impl ArchiveFormat {
    /// How the format is named in messages.
    pub const fn label(self) -> &'static str {
        match self {
            Self::Zip => "zip",
            Self::Tar => "tar",
            Self::TarGz => "tar.gz",
        }
    }
}

/// Recognise `path`'s archive format by name, or `None` when it is not one we
/// extract.
///
/// Named rather than sniffed: the user picked this entry from a listing, so
/// the extension is the thing they are going on, and a mismatch is better
/// reported than silently worked around.
pub fn detect_format(path: &Path) -> Option<ArchiveFormat> {
    let name = path.file_name()?.to_string_lossy().to_lowercase();

    // Ordered longest-first: `.tar.gz` must win over `.gz`.
    if name.ends_with(".tar.gz") || name.ends_with(".tgz") {
        Some(ArchiveFormat::TarGz)
    } else if name.ends_with(".tar") {
        Some(ArchiveFormat::Tar)
    } else if name.ends_with(".zip") {
        Some(ArchiveFormat::Zip)
    } else {
        None
    }
}

/// Where an archive entry should land, relative to the destination.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EntryTarget {
    /// Write it here, relative to the destination directory.
    Within(PathBuf),
    /// The archive's own root (`.` or `./`). GNU tar emits one as the first
    /// entry of `tar -C dir .`; it names the destination itself and carries
    /// nothing to write, so it is skipped rather than refused.
    ArchiveRoot,
    /// Points outside the destination and must not be written.
    Escaping,
}

/// Decide where an archive entry may be written.
///
/// Archive entries are attacker-controlled: an entry named `../../.bashrc` or
/// `/etc/passwd` would otherwise write clean outside the destination
/// directory (the "zip slip" bug). Anything absolute, rooted, or reaching
/// upwards is refused outright rather than clamped, so a hostile archive
/// fails loudly instead of extracting somewhere unexpected.
pub fn classify_entry_path(raw: &Path) -> EntryTarget {
    let mut safe = PathBuf::new();

    for component in raw.components() {
        match component {
            Component::Normal(part) => safe.push(part),
            // `.` contributes nothing but is harmless.
            Component::CurDir => {}
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
                return EntryTarget::Escaping
            }
        }
    }

    if safe.as_os_str().is_empty() {
        return EntryTarget::ArchiveRoot;
    }
    EntryTarget::Within(safe)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn detects_each_supported_format() {
        assert_eq!(
            detect_format(Path::new("/a/x.zip")),
            Some(ArchiveFormat::Zip)
        );
        assert_eq!(
            detect_format(Path::new("/a/x.tar")),
            Some(ArchiveFormat::Tar)
        );
        assert_eq!(
            detect_format(Path::new("/a/x.tar.gz")),
            Some(ArchiveFormat::TarGz)
        );
        assert_eq!(
            detect_format(Path::new("/a/x.tgz")),
            Some(ArchiveFormat::TarGz)
        );
    }

    #[test]
    fn tar_gz_wins_over_tar() {
        // `.tar.gz` also ends with neither `.tar` nor `.gz` alone; the
        // longest-match ordering is what keeps it from decoding as plain tar.
        assert_eq!(
            detect_format(Path::new("bundle.tar.gz")),
            Some(ArchiveFormat::TarGz)
        );
    }

    #[test]
    fn detection_ignores_case() {
        assert_eq!(detect_format(Path::new("X.ZIP")), Some(ArchiveFormat::Zip));
        assert_eq!(
            detect_format(Path::new("X.Tar.GZ")),
            Some(ArchiveFormat::TarGz)
        );
    }

    #[test]
    fn unsupported_names_are_not_archives() {
        assert_eq!(detect_format(Path::new("notes.txt")), None);
        assert_eq!(detect_format(Path::new("archive.rar")), None);
        // A bare `.gz` is not a tar we can walk.
        assert_eq!(detect_format(Path::new("blob.gz")), None);
        assert_eq!(detect_format(Path::new("noextension")), None);
    }

    #[test]
    fn ordinary_entry_paths_are_kept_relative() {
        assert_eq!(
            classify_entry_path(Path::new("src/main.rs")),
            EntryTarget::Within(PathBuf::from("src/main.rs"))
        );
        assert_eq!(
            classify_entry_path(Path::new("./src/./main.rs")),
            EntryTarget::Within(PathBuf::from("src/main.rs"))
        );
    }

    #[test]
    fn the_archive_root_entry_is_not_an_escape() {
        // `tar -C dir .` makes `./` its first entry. Refusing it would abort
        // extraction of an entirely ordinary archive on entry one.
        assert_eq!(
            classify_entry_path(Path::new("./")),
            EntryTarget::ArchiveRoot
        );
        assert_eq!(
            classify_entry_path(Path::new(".")),
            EntryTarget::ArchiveRoot
        );
        assert_eq!(classify_entry_path(Path::new("")), EntryTarget::ArchiveRoot);
    }

    #[test]
    fn entries_escaping_upwards_are_refused() {
        assert_eq!(
            classify_entry_path(Path::new("../evil")),
            EntryTarget::Escaping
        );
        assert_eq!(
            classify_entry_path(Path::new("a/../../evil")),
            EntryTarget::Escaping
        );
        assert_eq!(
            classify_entry_path(Path::new("a/b/../c")),
            EntryTarget::Escaping
        );
    }

    #[test]
    fn absolute_entries_are_refused() {
        assert_eq!(
            classify_entry_path(Path::new("/etc/passwd")),
            EntryTarget::Escaping
        );
        assert_eq!(classify_entry_path(Path::new("/")), EntryTarget::Escaping);
    }
}