|
| 1 | +// Credit: Ben Ajaero |
| 2 | + |
| 3 | +use std::path::{Path, PathBuf}; |
| 4 | + |
| 5 | +use http::Method; |
| 6 | + |
| 7 | +use crate::middleware::{middleware, Middleware, Next}; |
| 8 | +use crate::request::Request; |
| 9 | +use crate::response::{Response, StatusCode}; |
| 10 | + |
| 11 | +pub fn static_files(root: impl Into<PathBuf>) -> Middleware { |
| 12 | + let root = root.into(); |
| 13 | + middleware(move |req: Request, next: Next| { |
| 14 | + let root = root.clone(); |
| 15 | + async move { |
| 16 | + if req.method() != Method::GET { |
| 17 | + return next.run(req).await; |
| 18 | + } |
| 19 | + |
| 20 | + let path = match sanitize_path(req.path()) { |
| 21 | + Some(path) => path, |
| 22 | + None => { |
| 23 | + return Response::new(StatusCode::BAD_REQUEST, "Bad Request", "text/plain"); |
| 24 | + } |
| 25 | + }; |
| 26 | + |
| 27 | + let candidate = root.join(path); |
| 28 | + match tokio::fs::read(&candidate).await { |
| 29 | + Ok(contents) => Response::new(StatusCode::OK, contents, content_type_for_path(&candidate)), |
| 30 | + Err(_) => next.run(req).await, |
| 31 | + } |
| 32 | + } |
| 33 | + }) |
| 34 | +} |
| 35 | + |
| 36 | +fn sanitize_path(path: &str) -> Option<PathBuf> { |
| 37 | + let trimmed = path.trim_start_matches('/'); |
| 38 | + if trimmed.contains("..") { |
| 39 | + return None; |
| 40 | + } |
| 41 | + |
| 42 | + let normalized = if trimmed.is_empty() { |
| 43 | + PathBuf::from("index.html") |
| 44 | + } else { |
| 45 | + PathBuf::from(trimmed) |
| 46 | + }; |
| 47 | + |
| 48 | + Some(normalized) |
| 49 | +} |
| 50 | + |
| 51 | +fn content_type_for_path(path: &Path) -> &'static str { |
| 52 | + match path.extension().and_then(|ext| ext.to_str()).unwrap_or("") { |
| 53 | + "html" | "htm" => "text/html; charset=utf-8", |
| 54 | + "css" => "text/css; charset=utf-8", |
| 55 | + "js" => "application/javascript", |
| 56 | + "json" => "application/json", |
| 57 | + "png" => "image/png", |
| 58 | + "jpg" | "jpeg" => "image/jpeg", |
| 59 | + "txt" => "text/plain; charset=utf-8", |
| 60 | + _ => "application/octet-stream", |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +#[cfg(test)] |
| 65 | +mod tests { |
| 66 | + use super::{content_type_for_path, sanitize_path}; |
| 67 | + use std::path::Path; |
| 68 | + |
| 69 | + #[test] |
| 70 | + fn sanitize_rejects_parent() { |
| 71 | + assert!(sanitize_path("/../secret").is_none()); |
| 72 | + } |
| 73 | + |
| 74 | + #[test] |
| 75 | + fn sanitize_defaults_index() { |
| 76 | + let path = sanitize_path("/").expect("path"); |
| 77 | + assert_eq!(path.to_string_lossy(), "index.html"); |
| 78 | + } |
| 79 | + |
| 80 | + #[test] |
| 81 | + fn content_type_defaults_binary() { |
| 82 | + assert_eq!(content_type_for_path(Path::new("/tmp/file.bin")), "application/octet-stream"); |
| 83 | + } |
| 84 | +} |
0 commit comments