glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Serving static files.

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

use bytes::Bytes;
use http::{Method, StatusCode, header};
use percent_encoding::percent_decode_str;

use crate::context::Context;
use crate::handler::BoxFuture;
use crate::middleware::{Middleware, Next};
use crate::response::Response;

/// Serves files from a directory, falling through to the router when no
/// file matches. Responses carry an `ETag`, so browsers revalidate cheaply.
///
/// ```no_run
/// # use glacier::App;
/// use glacier::files::Static;
///
/// App::new().middleware(Static::new("public"));
/// ```
///
/// `glacier::static_files!("public")` does the same in debug builds, and in
/// release builds serves copies compiled into the binary, so a deploy is
/// one file.
pub struct Static {
    source: Source,
    prefix: String,
}

enum Source {
    Dir(PathBuf),
    Embedded(&'static [EmbeddedFile]),
}

/// A file compiled into the binary by `glacier::static_files!`.
#[derive(Debug)]
pub struct EmbeddedFile {
    /// Relative to the folder, with `/` separators: `css/app.css`.
    pub path: &'static str,
    pub bytes: &'static [u8],
    /// A quoted hash of the contents.
    pub etag: &'static str,
}

impl Static {
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            source: Source::Dir(root.into()),
            prefix: "/".into(),
        }
    }

    /// Serves files compiled into the binary; see `glacier::static_files!`.
    pub fn embedded(files: &'static [EmbeddedFile]) -> Self {
        Self {
            source: Source::Embedded(files),
            prefix: "/".into(),
        }
    }

    /// Only serves URLs under `prefix`, e.g. `/assets`.
    pub fn at(mut self, prefix: &str) -> Self {
        self.prefix = format!("/{}", prefix.trim_matches('/'));
        self
    }

    /// The requested file's path relative to the root, if the URL is under
    /// the prefix and names a plain path.
    fn relative(&self, path: &str) -> Option<PathBuf> {
        let rest = path.strip_prefix(&self.prefix)?;
        // `/assets` must not match `/assetsfoo`.
        if !(self.prefix == "/" || rest.is_empty() || rest.starts_with('/')) {
            return None;
        }
        let decoded = percent_decode_str(rest).decode_utf8().ok()?;
        let relative = Path::new(decoded.trim_start_matches('/'));
        // Only plain names: no `..`, no absolute paths, no drive prefixes.
        if relative
            .components()
            .any(|c| !matches!(c, Component::Normal(_)))
        {
            return None;
        }
        Some(relative.to_path_buf())
    }

    #[cfg(test)]
    fn resolve(&self, path: &str) -> Option<PathBuf> {
        match &self.source {
            Source::Dir(root) => self.relative(path).map(|r| root.join(r)),
            Source::Embedded(_) => None,
        }
    }
}

impl Middleware for Static {
    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
        let relative = matches!(*ctx.method(), Method::GET | Method::HEAD)
            .then(|| self.relative(ctx.path()))
            .flatten();
        let Some(relative) = relative else {
            return Box::pin(next.run(ctx));
        };
        match &self.source {
            Source::Dir(root) => {
                let file = root.join(relative);
                Box::pin(async move {
                    match serve_file(&file, &ctx).await {
                        Some(res) => res,
                        None => next.run(ctx).await,
                    }
                })
            }
            Source::Embedded(files) => {
                let wanted = relative.to_string_lossy().replace('\\', "/");
                match files.iter().find(|f| f.path == wanted) {
                    Some(file) => {
                        let res = respond(&ctx, file.etag, Path::new(file.path), || {
                            Bytes::from_static(file.bytes)
                        });
                        Box::pin(async move { res })
                    }
                    None => Box::pin(next.run(ctx)),
                }
            }
        }
    }
}

async fn serve_file(path: &Path, ctx: &Context) -> Option<Response> {
    let meta = tokio::fs::metadata(path).await.ok()?;
    if !meta.is_file() {
        return None;
    }
    let modified = meta
        .modified()
        .ok()
        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
        .map_or(0, |d| d.as_secs());
    let etag = format!("\"{:x}-{:x}\"", meta.len(), modified);
    if ctx.header(header::IF_NONE_MATCH) == Some(etag.as_str()) {
        return Some(not_modified(&etag));
    }
    let body = tokio::fs::read(path).await.ok()?;
    Some(respond(ctx, &etag, path, || Bytes::from(body)))
}

fn not_modified(etag: &str) -> Response {
    Response::new(StatusCode::NOT_MODIFIED).with_header(header::ETAG, etag.to_owned())
}

/// The file's response, or `304 Not Modified` when the browser has it.
fn respond(ctx: &Context, etag: &str, path: &Path, body: impl FnOnce() -> Bytes) -> Response {
    if ctx.header(header::IF_NONE_MATCH) == Some(etag) {
        return not_modified(etag);
    }
    Response::new(StatusCode::OK)
        .with_body_bytes(body())
        .with_header(header::CONTENT_TYPE, content_type(path))
        .with_header(header::ETAG, etag.to_owned())
        .with_header(header::CACHE_CONTROL, "public, max-age=0, must-revalidate")
}

fn content_type(path: &Path) -> &'static str {
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .map(str::to_ascii_lowercase);
    match ext.as_deref() {
        Some("html" | "htm") => "text/html; charset=utf-8",
        Some("css") => "text/css; charset=utf-8",
        Some("js" | "mjs") => "text/javascript; charset=utf-8",
        Some("json" | "map") => "application/json",
        Some("txt") => "text/plain; charset=utf-8",
        Some("svg") => "image/svg+xml",
        Some("png") => "image/png",
        Some("jpg" | "jpeg") => "image/jpeg",
        Some("gif") => "image/gif",
        Some("webp") => "image/webp",
        Some("avif") => "image/avif",
        Some("ico") => "image/x-icon",
        Some("woff") => "font/woff",
        Some("woff2") => "font/woff2",
        Some("wasm") => "application/wasm",
        Some("pdf") => "application/pdf",
        Some("xml") => "application/xml",
        _ => "application/octet-stream",
    }
}

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

    #[test]
    fn resolves_only_safe_paths_under_prefix() {
        let root = Static::new("public");
        assert_eq!(
            root.resolve("/app.css"),
            Some(PathBuf::from("public/app.css"))
        );
        assert_eq!(root.resolve("/../secret"), None);
        assert_eq!(root.resolve("/a/%2e%2e/%2e%2e/secret"), None);
        assert_eq!(root.resolve("/a/..%2f..%2fsecret"), None);

        let assets = Static::new("public").at("/assets/");
        assert_eq!(
            assets.resolve("/assets/js/app.js"),
            Some(PathBuf::from("public/js/app.js"))
        );
        assert_eq!(assets.resolve("/assetsfoo"), None);
        assert_eq!(assets.resolve("/other/app.js"), None);
    }
}