use super::{PathValidator, SecurityConfig};
use crate::error::{Error, Result};
use crate::http::{Request, Response};
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
pub struct SecureStaticFileServer {
validator: PathValidator,
_enable_directory_listing: bool,
cache_max_age: u32,
}
impl SecureStaticFileServer {
pub fn new(base_directory: impl AsRef<Path>, config: &SecurityConfig) -> Result<Self> {
let validator = PathValidator::new(base_directory, config)?;
Ok(Self {
validator,
_enable_directory_listing: false, cache_max_age: 3600, })
}
pub async fn serve_file(&self, request_path: &str) -> Result<Response> {
let file_path = self.validator.validate_path(request_path)?;
if !self.validator.is_safe_file(&file_path)? {
return Err(Error::template("File cannot be served safely".to_string()));
}
let content = tokio::fs::read(&file_path)
.await
.map_err(|e| Error::template(format!("Failed to read file: {}", e)))?;
let mime_type = self.detect_mime_type(&file_path);
let metadata = std::fs::metadata(&file_path)
.map_err(|e| Error::template(format!("Failed to read file metadata: {}", e)))?;
let last_modified = metadata
.modified()
.unwrap_or(SystemTime::UNIX_EPOCH)
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let mut response = Response::ok();
response = response.with_header("Content-Type", mime_type);
response = response.with_header("X-Content-Type-Options", "nosniff");
response = response.with_header("X-Frame-Options", "DENY");
response = response.with_header(
"Cache-Control",
&format!("public, max-age={}", self.cache_max_age),
);
response = response.with_header("Last-Modified", &Self::format_http_date(last_modified));
response = response.with_header("Content-Length", &content.len().to_string());
if self.should_force_download(&file_path) {
let filename = file_path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("download");
response = response.with_header(
"Content-Disposition",
&format!("attachment; filename=\"{}\"", filename),
);
}
Ok(response.with_body(content))
}
fn should_force_download(&self, path: &Path) -> bool {
if let Some(extension) = path.extension().and_then(|s| s.to_str()) {
let ext = extension.to_lowercase();
matches!(
ext.as_str(),
"pdf"
| "doc"
| "docx"
| "xls"
| "xlsx"
| "ppt"
| "pptx"
| "zip"
| "rar"
| "7z"
| "tar"
| "gz"
| "exe"
| "dmg"
)
} else {
true }
}
fn detect_mime_type(&self, path: &Path) -> &'static str {
if let Some(extension) = path.extension().and_then(|s| s.to_str()) {
match extension.to_lowercase().as_str() {
"html" | "htm" => "text/html; charset=utf-8",
"css" => "text/css; charset=utf-8",
"js" => "application/javascript; charset=utf-8",
"json" => "application/json; charset=utf-8",
"txt" => "text/plain; charset=utf-8",
"xml" => "application/xml; charset=utf-8",
"md" => "text/markdown; charset=utf-8",
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"svg" => "image/svg+xml",
"ico" => "image/x-icon",
"webp" => "image/webp",
"woff" => "font/woff",
"woff2" => "font/woff2",
"ttf" => "font/ttf",
"eot" => "application/vnd.ms-fontobject",
"pdf" => "application/pdf",
"doc" => "application/msword",
"docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"xls" => "application/vnd.ms-excel",
"xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"zip" => "application/zip",
"rar" => "application/x-rar-compressed",
"7z" => "application/x-7z-compressed",
"tar" => "application/x-tar",
"gz" => "application/gzip",
_ => "application/octet-stream",
}
} else {
"application/octet-stream"
}
}
fn format_http_date(timestamp: u64) -> String {
crate::utils::http_date::format_http_date(timestamp)
}
pub fn handle_conditional_request(
&self,
request: &Request,
file_path: &Path,
) -> Result<Option<Response>> {
if let Some(if_modified_since_header) = request.headers.get("if-modified-since") {
let metadata = std::fs::metadata(file_path)
.map_err(|e| Error::template(format!("Failed to read file metadata: {}", e)))?;
let last_modified = metadata
.modified()
.unwrap_or(SystemTime::UNIX_EPOCH)
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
if let Some(if_modified_timestamp) = Self::parse_http_date(if_modified_since_header) {
if last_modified <= if_modified_timestamp {
return Ok(Some(Response::not_modified()));
}
}
}
Ok(None)
}
fn parse_http_date(date_str: &str) -> Option<u64> {
crate::utils::http_date::parse_http_date(date_str)
}
}
pub struct StaticFileMiddleware {
server: SecureStaticFileServer,
url_prefix: String,
}
impl StaticFileMiddleware {
pub fn new(
base_directory: impl AsRef<Path>,
url_prefix: &str,
config: &SecurityConfig,
) -> Result<Self> {
let server = SecureStaticFileServer::new(base_directory, config)?;
Ok(Self {
server,
url_prefix: url_prefix.trim_end_matches('/').to_string(),
})
}
pub fn should_handle(&self, request_path: &str) -> bool {
if self.url_prefix.is_empty() {
return true;
}
request_path.starts_with(&self.url_prefix)
&& request_path.len() > self.url_prefix.len()
&& request_path.chars().nth(self.url_prefix.len()) == Some('/')
}
pub async fn handle_request(&self, request_path: &str) -> Result<Response> {
let file_path = if self.url_prefix.is_empty() {
request_path.to_string()
} else {
request_path
.strip_prefix(&self.url_prefix)
.unwrap_or(request_path)
.to_string()
};
self.server.serve_file(&file_path).await
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
use std::fs;
use tempfile::TempDir;
#[test]
fn test_secure_static_file_server() {
let temp_dir = TempDir::new().unwrap();
let base_path = temp_dir.path();
fs::write(
base_path.join("test.html"),
"<html><body>Test</body></html>",
)
.unwrap();
fs::write(base_path.join("style.css"), "body { color: red; }").unwrap();
let config = SecurityConfig::default();
let server = SecureStaticFileServer::new(base_path, &config).unwrap();
assert_eq!(
server.detect_mime_type(&base_path.join("test.html")),
"text/html; charset=utf-8"
);
assert_eq!(
server.detect_mime_type(&base_path.join("style.css")),
"text/css; charset=utf-8"
);
assert_eq!(
server.detect_mime_type(&base_path.join("unknown.xyz")),
"application/octet-stream"
);
}
#[test]
fn test_static_file_middleware() {
let temp_dir = TempDir::new().unwrap();
let base_path = temp_dir.path();
fs::write(base_path.join("app.js"), "console.log('test');").unwrap();
let config = SecurityConfig::default();
let middleware = StaticFileMiddleware::new(base_path, "/static", &config).unwrap();
assert!(middleware.should_handle("/static/app.js"));
assert!(!middleware.should_handle("/api/data"));
assert!(!middleware.should_handle("/static"));
}
#[tokio::test]
async fn test_path_traversal_prevention() {
let temp_dir = TempDir::new().unwrap();
let base_path = temp_dir.path();
fs::write(base_path.join("safe.txt"), "safe content").unwrap();
let config = SecurityConfig::default();
let server = SecureStaticFileServer::new(base_path, &config).unwrap();
assert!(server.serve_file("../../../etc/passwd").await.is_err());
assert!(server
.serve_file("..\\..\\windows\\system32\\config\\sam")
.await
.is_err());
assert!(server
.serve_file("safe.txt/../../../etc/passwd")
.await
.is_err());
assert!(server.serve_file("safe.txt").await.is_ok());
}
#[test]
fn test_http_date_formatting() {
let dt_1994 = chrono::Utc
.with_ymd_and_hms(1994, 11, 6, 8, 49, 37)
.unwrap();
let timestamp_1994 = dt_1994.timestamp() as u64;
let formatted = SecureStaticFileServer::format_http_date(timestamp_1994);
assert_eq!(formatted, "Sun, 06 Nov 1994 08:49:37 GMT");
let formatted_epoch = SecureStaticFileServer::format_http_date(0);
assert_eq!(formatted_epoch, "Thu, 01 Jan 1970 00:00:00 GMT");
let dt_leap = chrono::Utc.with_ymd_and_hms(2000, 2, 29, 12, 0, 0).unwrap();
let leap_year_timestamp = dt_leap.timestamp() as u64;
let formatted_leap = SecureStaticFileServer::format_http_date(leap_year_timestamp);
assert_eq!(formatted_leap, "Tue, 29 Feb 2000 12:00:00 GMT");
let dt_recent = chrono::Utc
.with_ymd_and_hms(2023, 12, 25, 15, 30, 45)
.unwrap();
let recent_timestamp = dt_recent.timestamp() as u64;
let formatted_recent = SecureStaticFileServer::format_http_date(recent_timestamp);
assert_eq!(formatted_recent, "Mon, 25 Dec 2023 15:30:45 GMT");
}
#[test]
fn test_http_date_parsing() {
let expected_dt = chrono::Utc
.with_ymd_and_hms(1994, 11, 6, 8, 49, 37)
.unwrap();
let expected_timestamp = expected_dt.timestamp() as u64;
let rfc7231_date = "Sun, 06 Nov 1994 08:49:37 GMT";
let parsed_rfc7231 = SecureStaticFileServer::parse_http_date(rfc7231_date);
assert_eq!(parsed_rfc7231, Some(expected_timestamp));
let rfc850_date = "Sunday, 06-Nov-94 08:49:37 GMT";
let parsed_rfc850 = SecureStaticFileServer::parse_http_date(rfc850_date);
assert_eq!(parsed_rfc850, Some(expected_timestamp));
let asctime_date = "Sun Nov 6 08:49:37 1994";
let parsed_asctime = SecureStaticFileServer::parse_http_date(asctime_date);
assert_eq!(parsed_asctime, Some(expected_timestamp));
let epoch_date = "Thu, 01 Jan 1970 00:00:00 GMT";
let parsed_epoch = SecureStaticFileServer::parse_http_date(epoch_date);
assert_eq!(parsed_epoch, Some(0));
assert_eq!(
SecureStaticFileServer::parse_http_date("invalid date"),
None
);
assert_eq!(SecureStaticFileServer::parse_http_date(""), None);
assert_eq!(
SecureStaticFileServer::parse_http_date("Not a date at all"),
None
);
let pre_epoch_date = "Wed, 31 Dec 1969 23:59:59 GMT";
assert_eq!(
SecureStaticFileServer::parse_http_date(pre_epoch_date),
None
);
}
#[test]
fn test_http_date_roundtrip() {
let test_datetimes = [
chrono::Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).unwrap(), chrono::Utc
.with_ymd_and_hms(1994, 11, 6, 8, 49, 37)
.unwrap(), chrono::Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap(), chrono::Utc.with_ymd_and_hms(2020, 1, 1, 0, 0, 0).unwrap(), chrono::Utc
.with_ymd_and_hms(2023, 12, 25, 15, 30, 45)
.unwrap(), ];
for dt in &test_datetimes {
let timestamp = dt.timestamp() as u64;
let formatted = SecureStaticFileServer::format_http_date(timestamp);
let parsed = SecureStaticFileServer::parse_http_date(&formatted);
assert_eq!(
parsed,
Some(timestamp),
"Roundtrip failed for timestamp {}: formatted='{}', parsed={:?}",
timestamp,
formatted,
parsed
);
}
}
#[test]
fn test_http_date_edge_cases() {
let leap_years = [
(
"Sat, 29 Feb 1992 12:00:00 GMT",
chrono::Utc.with_ymd_and_hms(1992, 2, 29, 12, 0, 0).unwrap(),
),
(
"Tue, 29 Feb 2000 12:00:00 GMT",
chrono::Utc.with_ymd_and_hms(2000, 2, 29, 12, 0, 0).unwrap(),
),
(
"Mon, 29 Feb 2016 12:00:00 GMT",
chrono::Utc.with_ymd_and_hms(2016, 2, 29, 12, 0, 0).unwrap(),
),
];
for (date_str, expected_dt) in &leap_years {
let expected_timestamp = expected_dt.timestamp() as u64;
let parsed = SecureStaticFileServer::parse_http_date(date_str);
assert_eq!(
parsed,
Some(expected_timestamp),
"Failed to parse leap year date: {}",
date_str
);
let formatted = SecureStaticFileServer::format_http_date(expected_timestamp);
assert_eq!(
&formatted, date_str,
"Formatting mismatch for timestamp {}",
expected_timestamp
);
}
let dt_1999 = chrono::Utc
.with_ymd_and_hms(1999, 12, 31, 23, 59, 59)
.unwrap();
let formatted_1999 = SecureStaticFileServer::format_http_date(dt_1999.timestamp() as u64);
assert_eq!(formatted_1999, "Fri, 31 Dec 1999 23:59:59 GMT");
let dt_2000 = chrono::Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap();
let formatted_2000 = SecureStaticFileServer::format_http_date(dt_2000.timestamp() as u64);
assert_eq!(formatted_2000, "Sat, 01 Jan 2000 00:00:00 GMT");
}
}