mini-static 0.31.2

A secure, async static file server with streaming, traversal protection, and connection limits.
Documentation
use std::fs::{File, Metadata};
use std::path::{Path, PathBuf};

use crate::error::StaticError;

/// A request path resolved all the way to an opened file.
///
/// Holding the open handle is the point: containment was verified on this exact fd (see
/// [`real_path_of`]), so serving from it — rather than re-opening by path — leaves no
/// gap between the check and the bytes.
pub(crate) struct ResolvedFile {
    pub(crate) file: File,
    pub(crate) metadata: Metadata,
    pub(crate) path: PathBuf,
}

/// The real, symlink-resolved path of an already-open file, from the kernel.
///
/// This is `canonicalize()` inverted: instead of resolving a path and hoping the later
/// `open` lands on the same file, open first and ask what was opened. macOS answers via
/// `fcntl(F_GETPATH)`; Linux via the fd's `/proc` symlink. Measured at ~38% cheaper than
/// the canonicalize-then-open sequence it replaces — and immune to the path being
/// swapped between check and use, because there is no "between".
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn real_path_of(file: &File) -> std::io::Result<PathBuf> {
    use std::os::fd::AsRawFd;
    use std::os::unix::ffi::OsStrExt;

    let mut buf = [0u8; libc::PATH_MAX as usize];
    // SAFETY: `buf` is PATH_MAX bytes and F_GETPATH writes at most PATH_MAX including
    // the NUL terminator; the fd is valid for the lifetime of `file`.
    let rc = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETPATH, buf.as_mut_ptr()) };
    if rc != 0 {
        return Err(std::io::Error::last_os_error());
    }
    let len = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
    Ok(PathBuf::from(std::ffi::OsStr::from_bytes(&buf[..len])))
}

#[cfg(target_os = "linux")]
fn real_path_of(file: &File) -> std::io::Result<PathBuf> {
    use std::os::fd::AsRawFd;
    std::fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd()))
}

/// Check that a canonicalized path stays within the server root.
///
/// Calls `canonicalize()` on the joined path and verifies the result starts with
/// `root_canon`, catching symlink escapes and traversal attempts that sneak through
/// segment-based checks.
///
/// # Arguments
///
/// * `root_canon` - The server root in canonical form.
/// * `joined` - A path that may need canonicalizing (e.g., the result of `root.join(...)`).
///
/// # Returns
///
/// - `Ok(PathBuf)` if the canonicalized path stays within root.
/// - `Err(StaticError::NotFound)` if the path doesn't exist or can't be canonicalized.
/// - `Err(StaticError::Traversal)` if the canonicalized path escapes root.
// On fd-verified platforms (macOS/iOS/Linux) only the portability fallback calls this,
// so it reads as dead there — it is the other platforms' security boundary, not debris.
#[cfg_attr(
    any(target_os = "macos", target_os = "ios", target_os = "linux"),
    allow(dead_code)
)]
pub(crate) fn canonicalize_within_root(
    root_canon: &Path,
    joined: &Path,
) -> Result<PathBuf, StaticError> {
    let canon = joined
        .canonicalize()
        .map_err(|_| StaticError::NotFound(joined.display().to_string()))?;

    if canon.starts_with(root_canon) {
        Ok(canon)
    } else {
        Err(StaticError::Traversal(joined.display().to_string()))
    }
}

/// Resolve a request path under a pre-canonicalized root.
///
/// This function assumes `root_canon` is already in canonical form — `root_canon` should be
/// the output of `root.canonicalize()` called once at server startup. Per-request resolution
/// only canonicalizes the joined path, not the root.
///
/// # Path Traversal Protection
///
/// Segment-based traversal check rejects only path segments exactly equal to `..`.
/// This allows filenames containing `..` as a substring (e.g., `jquery..min.js`) while
/// blocking traversal attempts like `../../etc/passwd`.
///
/// # Directory Handling
///
/// If the resolved path is a directory, automatically serves `index.html` from that directory
/// if it exists and doesn't escape the root.
///
/// # Symlinks
///
/// Symlinks are followed during canonicalization. After following symlinks, the final
/// canonical path must stay within the server root.
///
/// # Arguments
///
/// * `root_canon` - The server root in canonical form (should be output of `canonicalize()`).
/// * `request_path` - The HTTP request path (e.g., `/path/to/file.html`).
///
/// # Returns
///
/// - `Ok(PathBuf)` if the path resolves to a file within root.
/// - `Err(StaticError::NotFound)` if the path doesn't exist.
/// - `Err(StaticError::Traversal)` if the path attempts to escape the root.
pub fn resolve_with_canonical_root(
    root_canon: &Path,
    request_path: &str,
) -> Result<PathBuf, StaticError> {
    resolve_with_policy(root_canon, request_path, HiddenFiles::Deny)
}

/// Whether dot-prefixed request-path segments may be served.
///
/// The default is [`HiddenFiles::Deny`]: a served root is frequently a build output
/// directory, a repository working copy, or a folder someone dropped a `.env` into, and
/// serving `.git/config` or `.env` to anyone who guesses the name is a credential leak
/// that no traversal check catches — the files are legitimately *inside* the root.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HiddenFiles {
    /// Dot-prefixed segments answer as a miss.
    Deny,
    /// Dot-prefixed segments resolve like any other name.
    Serve,
}

/// The one dot-prefixed prefix served under [`HiddenFiles::Deny`]: `/.well-known/` is
/// where the web puts things that are *meant* to be fetched — ACME challenges for
/// certificate issuance, `security.txt`, app-site association files. Denying it would
/// break certificate renewal on any site served by this crate.
const WELL_KNOWN: &str = ".well-known";

/// Whether any segment of `decoded` is a hidden name, honoring the `.well-known`
/// exception.
///
/// Scope is deliberately the *request path* only, never the served root's own
/// filesystem path — a root that itself lives under a dot-directory
/// (`~/.config/site/public`) must keep working, since the operator chose that location
/// and no request can address it.
///
/// A segment of exactly `.` is a same-directory reference (`/./index.html`), not a
/// hidden name, so it is exempt. `..` never reaches here — the traversal check rejects
/// it first.
fn has_hidden_segment(decoded: &str) -> bool {
    decoded
        .trim_start_matches('/')
        .split('/')
        .enumerate()
        .any(|(index, segment)| {
            let is_well_known_root = index == 0 && segment == WELL_KNOWN;
            segment.starts_with('.') && segment != "." && !is_well_known_root
        })
}

/// [`resolve_with_canonical_root`] with an explicit hidden-file policy.
pub(crate) fn resolve_with_policy(
    root_canon: &Path,
    request_path: &str,
    hidden: HiddenFiles,
) -> Result<PathBuf, StaticError> {
    if request_path.contains('\0') {
        return Err(StaticError::Traversal(request_path.to_string()));
    }

    let decoded = decode_request_path(request_path);

    // Segment-based traversal check: reject only path segments exactly equal to ".."
    for segment in decoded.split('/') {
        if segment == ".." {
            return Err(StaticError::Traversal(request_path.to_string()));
        }
    }

    // `NotFound`, not a distinct error: a hidden file that exists and one that doesn't
    // must be indistinguishable, or the response becomes an oracle for what the root
    // contains — the same reasoning that collapses traversal into the miss message.
    if hidden == HiddenFiles::Deny && has_hidden_segment(&decoded) {
        return Err(StaticError::NotFound(request_path.to_string()));
    }

    let stripped = decoded.trim_start_matches('/');
    let joined = root_canon.join(stripped);

    open_verified(root_canon, &joined, request_path).map(|resolved| resolved.path)
}

/// Open `joined` and prove, on the opened fd, that it lies under `root_canon`.
///
/// A directory retries with `index.html` appended — verified on its *own* fd, never
/// trusted transitively from the directory's.
///
/// Every open failure collapses to `NotFound`: differentiating errno (permission vs
/// absent vs vanished) would hand back the existence oracle the 404 path works to deny.
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "linux"))]
fn open_verified(
    root_canon: &Path,
    joined: &Path,
    request_path: &str,
) -> Result<ResolvedFile, StaticError> {
    let file = File::open(joined).map_err(|_| StaticError::NotFound(request_path.to_string()))?;
    let real = real_path_of(&file).map_err(|_| StaticError::NotFound(request_path.to_string()))?;
    if !real.starts_with(root_canon) {
        return Err(StaticError::Traversal(request_path.to_string()));
    }
    let metadata = file
        .metadata()
        .map_err(|_| StaticError::NotFound(request_path.to_string()))?;

    if metadata.is_dir() {
        return open_verified(root_canon, &real.join("index.html"), request_path);
    }

    Ok(ResolvedFile {
        file,
        metadata,
        path: real,
    })
}

/// Portability fallback: the canonicalize-then-open sequence this crate used through
/// 0.30.x, for platforms without a way to read an fd's real path. Slower and it
/// re-admits the check-to-open window; the property tests exercise whichever variant
/// the platform compiles.
#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))]
fn open_verified(
    root_canon: &Path,
    joined: &Path,
    request_path: &str,
) -> Result<ResolvedFile, StaticError> {
    let canon = canonicalize_within_root(root_canon, joined)?;
    let target = if canon.is_dir() {
        let index = canon.join("index.html");
        canonicalize_within_root(root_canon, &index)?;
        index
    } else {
        canon
    };
    let file = File::open(&target).map_err(|_| StaticError::NotFound(request_path.to_string()))?;
    let metadata = file
        .metadata()
        .map_err(|_| StaticError::NotFound(request_path.to_string()))?;
    Ok(ResolvedFile {
        file,
        metadata,
        path: target,
    })
}

/// [`resolve_with_policy`], but yielding the opened, containment-verified file rather
/// than a path to reopen. `Server::handle_request` serves from this handle directly.
pub(crate) fn open_with_policy(
    root_canon: &Path,
    request_path: &str,
    hidden: HiddenFiles,
) -> Result<ResolvedFile, StaticError> {
    if request_path.contains('\0') {
        return Err(StaticError::Traversal(request_path.to_string()));
    }
    let decoded = decode_request_path(request_path);
    for segment in decoded.split('/') {
        if segment == ".." {
            return Err(StaticError::Traversal(request_path.to_string()));
        }
    }
    if hidden == HiddenFiles::Deny && has_hidden_segment(&decoded) {
        return Err(StaticError::NotFound(request_path.to_string()));
    }
    let stripped = decoded.trim_start_matches('/');
    open_verified(root_canon, &root_canon.join(stripped), request_path)
}

/// Percent-decode a request path to UTF-8, falling back to the raw string if decoding
/// produces invalid UTF-8.
///
/// This function decodes percent-encoded characters in the path (e.g., `%2F` → `/`),
/// allowing clients to request files with non-ASCII characters in their names.
/// If the decoded bytes are not valid UTF-8, the original path is returned unchanged.
pub(crate) fn decode_request_path(request_path: &str) -> String {
    percent_encoding::percent_decode_str(request_path)
        .decode_utf8()
        .map(|s| s.to_string())
        .unwrap_or_else(|_| request_path.to_string())
}

/// Resolve a request path under a root directory, canonicalizing the root first.
///
/// This is a convenience wrapper around `resolve_with_canonical_root()` that canonicalizes
/// the root on every call. For production use where the root is fixed at startup, prefer
/// `Server::new()` which canonicalizes the root once and reuses it for all requests.
///
/// # Arguments
///
/// * `root` - The server root directory (need not be pre-canonicalized).
/// * `request_path` - The HTTP request path (e.g., `/path/to/file.html`).
///
/// # Returns
///
/// - `Ok(PathBuf)` if the path resolves to a file within root.
/// - `Err(StaticError)` if the path is invalid, missing, or attempts traversal.
/// - `Err(StaticError::Io)` if canonicalizing the root fails.
pub fn resolve(root: &Path, request_path: &str) -> Result<PathBuf, StaticError> {
    let root_canon = root.canonicalize().map_err(StaticError::Io)?;
    resolve_with_canonical_root(&root_canon, request_path)
}