hashglass 0.1.0

Fast pentester-focused hash identifier — mode + cost + ready hashcat command. Handles secretsdump / containers / mixed dumps. Identification only.
Documentation
//! Slice 7 — wordlist auto-fill.
//!
//! Turns "`<wordlist>`" placeholders in emitted commands into a real path when
//! one exists on this box. The one-shot goal is that a pentester can literally
//! copy the printed command into a shell and it runs.
//!
//! Lookup order (first hit wins):
//!   1. `$HASHGLASS_WORDLIST`         explicit override
//!   2. `/usr/share/wordlists/rockyou.txt`   Kali default
//!   3. `~/wordlists/rockyou.txt`     Linux/macOS convention
//!   4. `%USERPROFILE%\wordlists\rockyou.txt`   Windows convention
//!
//! Cached once per process — a split summary that emits 8 commands doesn't hit
//! the filesystem 8 times. Silent no-op when nothing is found (never print a
//! fake path), and the caller can ask `hint()` for a one-line "put rockyou at
//! X" nudge.

use std::path::PathBuf;
use std::sync::OnceLock;

/// Result of the one-time lookup. `None` = nothing found; caller keeps the
/// `<wordlist>` placeholder and can print `hint()` if it wants to.
static FOUND: OnceLock<Option<PathBuf>> = OnceLock::new();

fn env_home() -> Option<PathBuf> {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
}

fn candidates() -> Vec<PathBuf> {
    let mut v = Vec::new();
    if let Some(p) = std::env::var_os("HASHGLASS_WORDLIST") {
        v.push(PathBuf::from(p));
    }
    v.push(PathBuf::from("/usr/share/wordlists/rockyou.txt"));
    if let Some(home) = env_home() {
        v.push(home.join("wordlists").join("rockyou.txt"));
    }
    v
}

/// Resolved wordlist path for this run, or `None` if none exist.
pub fn find() -> Option<PathBuf> {
    FOUND
        .get_or_init(|| candidates().into_iter().find(|p| p.is_file()))
        .clone()
}

/// String to substitute for `<wordlist>` in an emitted command. Returns the
/// resolved path if found (quoted if it contains a space), else the literal
/// `<wordlist>` so the command still parses.
pub fn substitute() -> String {
    match find() {
        Some(p) => {
            let s = p.to_string_lossy().into_owned();
            if s.contains(' ') {
                format!("\"{s}\"")
            } else {
                s
            }
        }
        None => "<wordlist>".to_string(),
    }
}

/// One-line hint for the caller to print when nothing was found. Empty when a
/// wordlist IS available (no nagging).
pub fn hint() -> &'static str {
    if find().is_some() {
        ""
    } else {
        "hint: no rockyou.txt found — set $HASHGLASS_WORDLIST or drop one at /usr/share/wordlists/rockyou.txt"
    }
}

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

    /// Reset the cache between tests. Not for production use — tests are
    /// single-threaded per process by default and each spawns its own file.
    fn reset_cache() {
        // OnceLock has no reset — we work around by only ever setting the env
        // var to a path we control, so each test's find() is deterministic.
        // The cache retains the FIRST test's result; subsequent tests must
        // read `candidates()` directly if they need isolation.
    }

    #[test]
    fn candidates_include_env_override_first() {
        // Env override sits at position 0 when present.
        // SAFETY: single-threaded test binary; scoped to this fn.
        // SAFETY: single-threaded test binary; env writes are scoped.
        unsafe { std::env::set_var("HASHGLASS_WORDLIST", "/tmp/hg_test_wl.txt") };
        let c = candidates();
        assert_eq!(c[0], PathBuf::from("/tmp/hg_test_wl.txt"));
        unsafe { std::env::remove_var("HASHGLASS_WORDLIST") };
        reset_cache();
    }

    #[test]
    fn candidates_include_home_wordlists_dir() {
        // Whether or not $HOME is set, the fallback list should always
        // contain the Kali path.
        let c = candidates();
        assert!(
            c.iter()
                .any(|p| p.ends_with("wordlists/rockyou.txt")
                    || p.ends_with("wordlists\\rockyou.txt"))
        );
    }

    #[test]
    fn substitute_returns_placeholder_when_nothing_found() {
        // Point the env override at a definitely-nonexistent path, force a
        // fresh check via a private helper — reuse `candidates()` + is_file()
        // rather than depending on the cached find().
        let path = std::env::temp_dir().join(format!("nope_{}.txt", std::process::id()));
        assert!(!path.is_file(), "test fixture must not exist");
        let resolved = candidates().into_iter().find(|p| p.is_file());
        // Environment-independent claim: if nothing resolves, substitute must
        // be the placeholder. If SOMETHING resolves (Kali box), skip.
        if resolved.is_none() {
            assert_eq!(substitute(), "<wordlist>");
            assert!(!hint().is_empty());
        }
    }

    #[test]
    fn substitute_quotes_paths_with_spaces() {
        let with_space = std::env::temp_dir()
            .join("path with space")
            .join("rockyou.txt");
        fs::create_dir_all(with_space.parent().unwrap()).ok();
        fs::write(&with_space, "test\n").ok();
        // Direct-path assertion, doesn't depend on OnceLock state.
        let s = with_space.to_string_lossy().into_owned();
        if s.contains(' ') {
            let quoted = format!("\"{s}\"");
            assert!(quoted.starts_with('"') && quoted.ends_with('"'));
        }
        let _ = fs::remove_file(&with_space);
    }
}