use crate::serve::INDEX_FILE;
use axum::extract::Request;
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use http::StatusCode;
use percent_encoding::percent_decode_str;
use std::borrow::Cow;
use std::path::{Component, Path, PathBuf};
const WELL_KNOWN: &str = ".well-known";
#[cfg(windows)]
const SEPARATORS: &[char] = &['/', '\\'];
#[cfg(not(windows))]
const SEPARATORS: &[char] = &['/'];
pub(crate) async fn refuse_paths_outside(root: PathBuf, request: Request, next: Next) -> Response {
if !may_be_served(&root, &on_disk(&root, request.uri().path())) {
return StatusCode::NOT_FOUND.into_response();
}
next.run(request).await
}
pub(crate) async fn refuse_index_pages_outside(
root: PathBuf,
request: Request,
next: Next,
) -> Response {
let path = request.uri().path();
if path.ends_with('/') && !may_be_served(&root, &on_disk(&root, path).join(INDEX_FILE)) {
return StatusCode::NOT_FOUND.into_response();
}
next.run(request).await
}
fn on_disk(root: &Path, path: &str) -> PathBuf {
root.join(decode(path).trim_start_matches(SEPARATORS))
}
pub(crate) fn may_be_served(root: &Path, path: &Path) -> bool {
let Ok(resolved) = path.canonicalize() else {
return true;
};
let Ok(below) = resolved.strip_prefix(root) else {
return false;
};
!below.components().any(|part| match part {
Component::Normal(name) => is_hidden(&name.to_string_lossy()),
_ => false,
})
}
pub(crate) async fn refuse_hidden_files(request: Request, next: Next) -> Response {
if names_a_hidden_file(request.uri().path()) {
return StatusCode::NOT_FOUND.into_response();
}
next.run(request).await
}
pub(crate) fn is_hidden(name: &str) -> bool {
name.starts_with('.') && name != WELL_KNOWN
}
fn names_a_hidden_file(path: &str) -> bool {
decode(path).split(SEPARATORS).any(is_hidden)
}
fn decode(path: &str) -> Cow<'_, str> {
percent_decode_str(path).decode_utf8_lossy()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hidden_addresses_are_refused() {
for path in [
"/.env",
"/.git/config",
"/%2e%65nv",
"/%2Eenv",
"/js/.hidden.js",
"/.well-known/.secret",
] {
assert!(names_a_hidden_file(path), "{path}");
}
}
#[test]
fn an_encoded_separator_does_not_hide_a_hidden_file() {
for path in ["/sub%2f.env", "/sub%2F.env", "/sub%2f.git%2fconfig"] {
assert!(names_a_hidden_file(path), "{path}");
}
}
#[cfg(not(windows))]
#[test]
fn a_backslash_is_an_ordinary_character_in_a_name_here() {
assert!(!names_a_hidden_file("/sub%5c.env"));
}
#[test]
fn ordinary_addresses_are_allowed() {
for path in ["/", "/index.html", "/a.b/c.js", "/.well-known/acme/token"] {
assert!(!names_a_hidden_file(path), "{path}");
}
}
}