use std::{
borrow::Cow,
convert::Infallible,
future::Future,
io,
path::{Path, PathBuf},
pin::Pin,
sync::Arc,
task::{Context, Poll},
time::Duration,
};
use axum::{
body::Body,
http::{HeaderMap, HeaderValue, Method, Request, StatusCode, header},
response::{IntoResponse, Response},
};
use percent_encoding::percent_decode_str;
use thiserror::Error;
use tower::Service;
use tower_http::services::{ServeDir, ServeFile};
use crate::result::{ClassifyError, ErrorCode, ErrorKind};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StaticAssetCache {
#[default]
Revalidate,
Immutable {
max_age: Duration,
},
}
impl StaticAssetCache {
#[expect(
clippy::expect_used,
reason = "fixed ASCII and decimal digits form a valid header"
)]
fn header_value(self) -> Result<HeaderValue, StaticSiteError> {
match self {
Self::Revalidate => Ok(HeaderValue::from_static("no-cache")),
Self::Immutable { max_age } => {
if max_age.is_zero() || max_age.subsec_nanos() != 0 {
return Err(StaticSiteError::InvalidCacheDuration);
}
Ok(HeaderValue::try_from(format!(
"public, max-age={}, immutable",
max_age.as_secs()
))
.expect("fixed ASCII cache directive"))
}
}
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum StaticSiteError {
#[error("SPA fallback requires an entry configured with with_entry")]
MissingEntry,
#[error("invalid static site path {path:?}: {reason}")]
InvalidPath {
path: PathBuf,
reason: &'static str,
},
#[error("static site paths overlap: {first:?} and {second:?}")]
OverlappingPaths {
first: String,
second: String,
},
#[error("immutable asset max_age must be a positive whole number of seconds")]
InvalidCacheDuration,
#[error("cannot access static site path {path:?}: {source}")]
Io {
path: PathBuf,
#[source]
source: io::Error,
},
}
impl ClassifyError for StaticSiteError {
fn error_kind(&self) -> ErrorKind {
match self {
Self::Io { .. } => ErrorKind::Dependency,
_ => ErrorKind::Validation,
}
}
fn error_code(&self) -> ErrorCode {
ErrorCode::internal(match self {
Self::MissingEntry => "static_site_missing_entry",
Self::InvalidPath { .. } => "static_site_invalid_path",
Self::OverlappingPaths { .. } => "static_site_overlapping_paths",
Self::InvalidCacheDuration => "static_site_invalid_cache_duration",
Self::Io { .. } => "static_site_io_failed",
})
}
}
#[derive(Clone, Debug)]
#[must_use]
pub struct StaticSite {
root: PathBuf,
entry: Option<PathBuf>,
spa_fallback: bool,
precompressed_br: bool,
precompressed_gzip: bool,
assets: Vec<(String, StaticAssetCache)>,
reserved: Vec<String>,
}
impl StaticSite {
pub fn new(root: impl Into<PathBuf>) -> Self {
Self {
root: root.into(),
entry: None,
spa_fallback: false,
precompressed_br: false,
precompressed_gzip: false,
assets: Vec::new(),
reserved: Vec::new(),
}
}
pub fn with_entry(mut self, entry: impl Into<PathBuf>) -> Self {
self.entry = Some(entry.into());
self
}
pub fn with_spa_fallback(mut self, enabled: bool) -> Self {
self.spa_fallback = enabled;
self
}
pub fn with_precompressed_br(mut self, enabled: bool) -> Self {
self.precompressed_br = enabled;
self
}
pub fn with_precompressed_gzip(mut self, enabled: bool) -> Self {
self.precompressed_gzip = enabled;
self
}
pub fn with_assets(mut self, prefix: impl Into<String>, cache: StaticAssetCache) -> Self {
self.assets.push((prefix.into(), cache));
self
}
pub fn with_reserved_path(mut self, prefix: impl Into<String>) -> Self {
self.reserved.push(prefix.into());
self
}
pub async fn build(self) -> Result<StaticSiteService, StaticSiteError> {
if self.spa_fallback && self.entry.is_none() {
return Err(StaticSiteError::MissingEntry);
}
let prefixes: Vec<_> = self
.reserved
.iter()
.chain(self.assets.iter().map(|(path, _)| path))
.collect();
for (index, prefix) in prefixes.iter().enumerate() {
if !valid_literal_path(prefix) || prefix.as_str() == "/" || prefix.ends_with('/') {
return Err(invalid_path(
prefix.as_str(),
"expected a non-root literal URL prefix without a trailing slash",
));
}
for other in &prefixes[..index] {
if matches_prefix(prefix, other) || matches_prefix(other, prefix) {
return Err(StaticSiteError::OverlappingPaths {
first: (*other).clone(),
second: (*prefix).clone(),
});
}
}
}
let entry = if let Some(entry) = &self.entry {
let Some(relative) = entry.to_str() else {
return Err(invalid_path(entry, "entry must be a UTF-8 relative path"));
};
let url = format!("/{relative}");
if !valid_literal_path(&url) || url == "/" || url.ends_with('/') {
return Err(invalid_path(
entry,
"entry must be a relative file path without empty or dot segments",
));
}
if let Some(prefix) = prefixes.iter().find(|prefix| matches_prefix(&url, prefix)) {
return Err(StaticSiteError::OverlappingPaths {
first: (*prefix).clone(),
second: url,
});
}
Some((entry, url))
} else {
None
};
let assets = self
.assets
.into_iter()
.map(|(path, cache)| Ok((path, cache.header_value()?)))
.collect::<Result<_, StaticSiteError>>()?;
let root = tokio::fs::canonicalize(&self.root)
.await
.map_err(|source| io_error(&self.root, source))?;
drop(
tokio::fs::read_dir(&root)
.await
.map_err(|source| io_error(&root, source))?,
);
let entry = if let Some((relative, url)) = entry {
let path = root.join(relative);
if !tokio::fs::metadata(&path)
.await
.map_err(|source| io_error(&path, source))?
.is_file()
{
return Err(invalid_path(&path, "entry must be a regular file"));
}
drop(
tokio::fs::File::open(&path)
.await
.map_err(|source| io_error(&path, source))?,
);
let mut file = ServeFile::new_with_mime(&path, &mime::TEXT_HTML_UTF_8);
if self.precompressed_br {
file = file.precompressed_br();
}
if self.precompressed_gzip {
file = file.precompressed_gzip();
}
Some(Entry {
file,
path,
url,
spa_fallback: self.spa_fallback,
})
} else {
None
};
let mut files = ServeDir::new(&root)
.append_index_html_on_directories(false)
.redirect_to_trailing_slash(false);
if self.precompressed_br {
files = files.precompressed_br();
}
if self.precompressed_gzip {
files = files.precompressed_gzip();
}
Ok(StaticSiteService {
inner: Arc::new(Site {
files,
root,
entry,
assets,
reserved: self.reserved,
}),
})
}
}
#[derive(Clone, Debug)]
pub struct StaticSiteService {
inner: Arc<Site>,
}
#[derive(Debug)]
struct Site {
root: PathBuf,
files: ServeDir,
entry: Option<Entry>,
assets: Vec<(String, HeaderValue)>,
reserved: Vec<String>,
}
#[derive(Debug)]
struct Entry {
path: PathBuf,
url: String,
file: ServeFile,
spa_fallback: bool,
}
impl Service<Request<Body>> for StaticSiteService {
type Response = Response;
type Error = Infallible;
type Future = Pin<Box<dyn Future<Output = Result<Response, Infallible>> + Send>>;
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, request: Request<Body>) -> Self::Future {
let site = Arc::clone(&self.inner);
Box::pin(async move { Ok(site.serve(request.map(|_| ())).await) })
}
}
impl Site {
async fn serve(&self, mut request: Request<()>) -> Response {
let Some(path) = decoded_path(request.uri().path()) else {
return error_response(StatusCode::NOT_FOUND);
};
if self
.reserved
.iter()
.any(|prefix| matches_prefix(&path, prefix))
{
return error_response(StatusCode::NOT_FOUND);
}
if request.method() != Method::GET && request.method() != Method::HEAD {
let mut response = error_response(StatusCode::METHOD_NOT_ALLOWED);
response
.headers_mut()
.insert(header::ALLOW, HeaderValue::from_static("GET, HEAD"));
return response;
}
let direct_entry = self
.entry
.as_ref()
.filter(|entry| path == "/" || path == entry.url);
let cache = self
.assets
.iter()
.find(|(prefix, _)| matches_prefix(&path, prefix))
.map(|(_, cache)| cache);
let fallback_entry = self
.entry
.as_ref()
.filter(|entry| entry.spa_fallback && cache.is_none());
let path = path.into_owned();
if request.method() == Method::HEAD || request.headers().contains_key(header::IF_RANGE) {
request.headers_mut().remove(header::RANGE);
}
if request.headers().contains_key(header::IF_MATCH) {
let mut values = request.headers().get_all(header::IF_MATCH).iter();
let wildcard = values
.next()
.is_some_and(|value| value.as_bytes().trim_ascii() == b"*")
&& values.next().is_none();
request.headers_mut().insert(
header::IF_MATCH,
HeaderValue::from_static(if wildcard { "*" } else { "W/\"\"" }),
);
}
normalize_if_none_match(request.headers_mut());
if let Some(entry) = direct_entry {
return entry.serve(request, false).await;
}
let fallback = fallback_entry.filter(|_| explicitly_accepts_html(request.headers()));
let result = self.files.clone().try_call(request.clone()).await;
let response = match (result, fallback) {
(Err(error), Some(entry)) if error.kind() == io::ErrorKind::NotFound => {
return entry.serve(request, true).await;
}
(Ok(response), Some(entry)) if response.status() == StatusCode::NOT_FOUND => {
match tokio::fs::metadata(self.root.join(&path[1..])).await {
Ok(metadata) if metadata.is_dir() => {
return entry.serve(request, true).await;
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {
return entry.serve(request, true).await;
}
Err(error) => file_error(error),
Ok(_) => response.map(Body::new),
}
}
(Ok(response), _) => response.map(Body::new),
(Err(error), _) => file_error(error),
};
finish_response(response, cache, fallback_entry.is_some())
}
}
#[expect(
clippy::expect_used,
reason = "commas preserve the validity of existing header values"
)]
fn normalize_if_none_match(headers: &mut HeaderMap) {
let values = headers.get_all(header::IF_NONE_MATCH);
if values.iter().count() > 1 {
let combined = values
.iter()
.map(HeaderValue::as_bytes)
.collect::<Vec<_>>()
.join(b", ".as_slice());
headers.insert(
header::IF_NONE_MATCH,
HeaderValue::from_bytes(&combined).expect("valid header values joined with commas"),
);
} else if values
.iter()
.next()
.is_some_and(|value| value.as_bytes().trim_ascii() == b"*")
{
headers.insert(header::IF_NONE_MATCH, HeaderValue::from_static("*"));
}
}
impl Entry {
async fn serve(&self, request: Request<()>, vary: bool) -> Response {
let result = async {
if !tokio::fs::metadata(&self.path).await?.is_file() {
return Err(io::Error::other("static site entry is not a regular file"));
}
self.file.clone().try_call(request).await
}
.await;
let response = match result {
Ok(response) => response.map(Body::new),
Err(error) => {
tracing::error!(%error, "static site entry is unavailable");
error_response(StatusCode::INTERNAL_SERVER_ERROR)
}
};
finish_response(response, None, vary)
}
}
fn finish_response(mut response: Response, cache: Option<&HeaderValue>, vary: bool) -> Response {
let value = if response.status().is_success() || response.status() == StatusCode::NOT_MODIFIED {
cache
.cloned()
.unwrap_or_else(|| HeaderValue::from_static("no-cache"))
} else {
HeaderValue::from_static("no-store")
};
response.headers_mut().insert(header::CACHE_CONTROL, value);
if response.status() == StatusCode::PARTIAL_CONTENT {
response.headers_mut().remove(header::ETAG);
} else if let Some(etag) = response.headers_mut().get_mut(header::ETAG)
&& !etag.as_bytes().starts_with(b"W/")
{
*etag = weak_etag(etag);
}
response.headers_mut().insert(
header::VARY,
HeaderValue::from_static(if vary {
"Accept, Accept-Encoding"
} else {
"Accept-Encoding"
}),
);
response
}
#[expect(
clippy::expect_used,
reason = "ASCII prefix preserves a validated header value"
)]
fn weak_etag(etag: &HeaderValue) -> HeaderValue {
let mut bytes = Vec::with_capacity(etag.as_bytes().len() + 2);
bytes.extend_from_slice(b"W/");
bytes.extend_from_slice(etag.as_bytes());
HeaderValue::from_bytes(&bytes).expect("ASCII prefix followed by a valid header value")
}
fn error_response(status: StatusCode) -> Response {
finish_response(status.into_response(), None, false)
}
fn file_error(error: io::Error) -> Response {
match error.kind() {
io::ErrorKind::NotFound
| io::ErrorKind::NotADirectory
| io::ErrorKind::PermissionDenied => error_response(StatusCode::NOT_FOUND),
_ => {
tracing::error!(%error, "static site file could not be served");
error_response(StatusCode::INTERNAL_SERVER_ERROR)
}
}
}
fn matches_prefix(path: &str, prefix: &str) -> bool {
path == prefix
|| path
.strip_prefix(prefix)
.is_some_and(|rest| rest.starts_with('/'))
}
fn valid_literal_path(path: &str) -> bool {
!path.contains(['%', '?', '#']) && valid_decoded_path(path)
}
fn decoded_path(path: &str) -> Option<Cow<'_, str>> {
for (index, byte) in path.bytes().enumerate() {
if byte == b'%'
&& !path
.as_bytes()
.get(index + 1..index + 3)
.is_some_and(|hex| hex.iter().all(u8::is_ascii_hexdigit))
{
return None;
}
}
let decoded = percent_decode_str(path).decode_utf8().ok()?;
valid_decoded_path(&decoded).then_some(decoded)
}
fn valid_decoded_path(path: &str) -> bool {
path.starts_with('/')
&& !path.contains("//")
&& !path.chars().any(|ch| ch == '\\' || ch.is_control())
&& !path.split('/').any(|segment| {
matches!(segment, "." | "..")
|| (cfg!(windows) && (segment.contains(':') || segment.ends_with(['.', ' '])))
})
}
fn explicitly_accepts_html(headers: &HeaderMap) -> bool {
headers
.get_all(header::ACCEPT)
.iter()
.filter_map(|value| value.to_str().ok())
.flat_map(super::media_ranges)
.filter_map(|value| value.trim().parse::<mime::Mime>().ok())
.filter_map(|range| {
if range.essence_str() != "text/html" {
return None;
}
let mut quality = None;
let mut parameters = 0;
for (name, value) in range.params() {
if name == "q" {
if quality.is_some() {
return None;
}
quality = Some(super::parse_quality(value.as_str()).unwrap_or(0));
} else if quality.is_none() {
if !(name == mime::CHARSET && value == mime::UTF_8) || parameters != 0 {
return None;
}
parameters += 1;
}
}
Some((parameters, quality.unwrap_or(1000)))
})
.max()
.is_some_and(|(_, quality)| quality > 0)
}
fn invalid_path(path: impl Into<PathBuf>, reason: &'static str) -> StaticSiteError {
StaticSiteError::InvalidPath {
path: path.into(),
reason,
}
}
fn io_error(path: &Path, source: io::Error) -> StaticSiteError {
StaticSiteError::Io {
path: path.to_owned(),
source,
}
}