mini-static 0.32.0

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(segments: &[String]) -> bool {
    segments.iter().enumerate().any(|(index, segment)| {
        let is_well_known_root = index == 0 && segment == WELL_KNOWN;
        segment.starts_with('.') && segment != "." && !is_well_known_root
    })
}

/// Decode a request path into its segments — this crate's only interpretation of what a
/// path *is*.
///
/// **Splitting happens before decoding**, per RFC 3986 §3.3: `/` separates segments and a
/// percent-encoded `%2F` is an ordinary character *inside* one. Decoding the whole path
/// first — which this crate did through 0.31.x — promotes `%2F` into a separator, so
/// `/admin%2Fconfig` reaches `admin/config` on disk. Containment still held, but any
/// router or middleware in front of this server correctly reads that request as a single
/// segment matching no route, so the file was served while the route guarding it was
/// never consulted. See `tests/encoded_separator.rs`.
///
/// A segment that still contains a separator after decoding is refused rather than
/// re-split — the same answer Apache gives by default (`AllowEncodedSlashes Off`).
/// Backslash is refused on every platform, not just Windows where it separates: a server
/// whose test suite runs on one OS should not behave differently on another, and a file
/// with a backslash in its name is not worth the divergence.
pub(crate) fn decode_segments(request_path: &str) -> Result<Vec<String>, StaticError> {
    let refuse = || StaticError::Traversal(request_path.to_string());

    if request_path.contains('\0') {
        return Err(refuse());
    }

    let mut segments = Vec::new();
    for raw in request_path.split('/') {
        if raw.is_empty() {
            continue;
        }
        // Invalid UTF-8 falls back to the raw segment, which then matches only a file
        // literally named that — the behaviour this crate has always had.
        let decoded = percent_encoding::percent_decode_str(raw)
            .decode_utf8()
            .map(|decoded| decoded.into_owned())
            .unwrap_or_else(|_| raw.to_string());

        // `%00` survives the raw check above and only fails much later, inside the
        // syscall; refused here so the reason is the path rather than an open error.
        if decoded.contains('/') || decoded.contains('\\') || decoded.contains('\0') {
            return Err(refuse());
        }
        if decoded == ".." {
            return Err(refuse());
        }
        segments.push(decoded);
    }
    Ok(segments)
}

/// Join decoded segments onto the root one at a time.
///
/// One at a time because `Path::join` re-reads a separator inside its argument; feeding
/// it a pre-joined string would undo the work `decode_segments` just did.
fn join_segments(root_canon: &Path, segments: &[String]) -> PathBuf {
    segments
        .iter()
        .fold(root_canon.to_path_buf(), |path, segment| path.join(segment))
}

/// [`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> {
    open_with_policy(root_canon, request_path, hidden).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> {
    let segments = decode_segments(request_path)?;

    // `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(&segments) {
        return Err(StaticError::NotFound(request_path.to_string()));
    }

    open_verified(root_canon, &join_segments(root_canon, &segments), request_path)
}

/// 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)
}