This commit is contained in:
Mateusz Gruszczyński committed 2026-10-19 14:05:13 +02:00
1 parent 28e39f7ce4
commit b57beb83c7
34 files changed
+1037 -314

No files matched your search

+52 -25
View File
@@ -1,15 +1,14 @@
use super::{
config::CompiledCacheMatcher,
filesystem::{DirectoryEntry, Opened},
htaccess,
CompiledService,
htaccess, CompiledService,
};
use axum::{body::Body, response::Response};
use http::{
header::{
ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_ENCODING,
CONTENT_LENGTH, CONTENT_RANGE, CONTENT_TYPE, ETAG, IF_MODIFIED_SINCE, IF_NONE_MATCH,
IF_RANGE, LAST_MODIFIED, LOCATION, RANGE, VARY,
ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_ENCODING, CONTENT_LENGTH,
CONTENT_RANGE, CONTENT_TYPE, ETAG, IF_MODIFIED_SINCE, IF_NONE_MATCH, IF_RANGE,
LAST_MODIFIED, LOCATION, RANGE, VARY,
},
HeaderMap, HeaderValue, Method, StatusCode, Uri,
};
@@ -21,13 +20,37 @@ use std::{
use tokio::io::{AsyncReadExt, AsyncSeekExt};
use tokio_util::io::ReaderStream;
pub(super) fn status_response(status: StatusCode, message: &'static str) -> Response {
let mut response = Response::new(Body::from(message));
pub(super) fn status_response(status: StatusCode, detail: &'static str) -> Response {
// Keep internal diagnostics in server logs, not in public HTTP bodies.
if status.is_server_error() {
tracing::warn!(
status = status.as_u16(),
detail = detail.trim_end(),
"Web Server error"
);
}
let message = format!(
"{} {}\n",
status.as_u16(),
status.canonical_reason().unwrap_or("Error")
);
let mut response = Response::new(Body::from(message.clone()));
*response.status_mut() = status;
response.headers_mut().insert(
CONTENT_TYPE,
HeaderValue::from_static("text/plain; charset=utf-8"),
);
response.headers_mut().insert(
CONTENT_LENGTH,
HeaderValue::from_str(&message.len().to_string()).unwrap(),
);
response
.headers_mut()
.insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
response.headers_mut().insert(
"x-content-type-options",
HeaderValue::from_static("nosniff"),
);
response
}
@@ -60,15 +83,20 @@ pub(super) fn builtin_error_response(status: StatusCode, method: &Method) -> Res
pub(super) fn io_response(error: &io::Error) -> Response {
#[cfg(unix)]
if matches!(error.raw_os_error(), Some(libc::ELOOP)) {
return status_response(StatusCode::FORBIDDEN, "RustProxy: Web Server path is not allowed\n");
return status_response(
StatusCode::FORBIDDEN,
"RustProxy: Web Server path is not allowed\n",
);
}
match error.kind() {
io::ErrorKind::NotFound | io::ErrorKind::NotADirectory => {
status_response(StatusCode::NOT_FOUND, "RustProxy: Web Server resource not found\n")
}
io::ErrorKind::PermissionDenied | io::ErrorKind::InvalidInput => {
status_response(StatusCode::FORBIDDEN, "RustProxy: Web Server path is not allowed\n")
}
io::ErrorKind::NotFound | io::ErrorKind::NotADirectory => status_response(
StatusCode::NOT_FOUND,
"RustProxy: Web Server resource not found\n",
),
io::ErrorKind::PermissionDenied | io::ErrorKind::InvalidInput => status_response(
StatusCode::FORBIDDEN,
"RustProxy: Web Server path is not allowed\n",
),
_ => status_response(
StatusCode::INTERNAL_SERVER_ERROR,
"RustProxy: Web Server filesystem error\n",
@@ -172,10 +200,7 @@ fn cache_control_for(
.and_then(|value| value.to_str())
.unwrap_or("")
.to_ascii_lowercase();
let mime = content_type
.to_str()
.unwrap_or("")
.to_ascii_lowercase();
let mime = content_type.to_str().unwrap_or("").to_ascii_lowercase();
for rule in &service.cache_rules {
let matches = match &rule.matcher {
CompiledCacheMatcher::Extension(value) => extension == *value,
@@ -216,8 +241,14 @@ fn add_download_header(response: &mut Response, service: &CompiledService, path:
if !download_extension(service, path) {
return;
}
let filename = path.file_name().and_then(|value| value.to_str()).unwrap_or("download");
let value = format!("attachment; filename*=UTF-8''{}", percent_encode_segment(filename));
let filename = path
.file_name()
.and_then(|value| value.to_str())
.unwrap_or("download");
let value = format!(
"attachment; filename*=UTF-8''{}",
percent_encode_segment(filename)
);
if let Ok(value) = HeaderValue::from_str(&value) {
response.headers_mut().insert(CONTENT_DISPOSITION, value);
}
@@ -372,11 +403,7 @@ fn if_range_allows(headers: &HeaderMap, etag: Option<&str>, modified: Option<Sys
.is_some_and(|date| modified <= date)
}
fn add_validators(
response: &mut Response,
etag: Option<&str>,
modified: Option<SystemTime>,
) {
fn add_validators(response: &mut Response, etag: Option<&str>, modified: Option<SystemTime>) {
if let Some(etag) = etag.and_then(|value| HeaderValue::from_str(value).ok()) {
response.headers_mut().insert(ETAG, etag);
}
+18 -14
View File
@@ -347,20 +347,19 @@ async fn serve_inner(
}
let root = FilesystemRoot::for_service(service);
let components_for_list = components.clone();
let mut entries = match tokio::task::spawn_blocking(move || {
list_directory_sync(&root, &components_for_list)
})
.await
{
Ok(Ok(entries)) => entries,
Ok(Err(error)) => return io_response(&error),
Err(_) => {
return status_response(
StatusCode::INTERNAL_SERVER_ERROR,
"RustProxy: Web Server directory task failed\n",
)
}
};
let mut entries =
match tokio::task::spawn_blocking(move || list_directory_sync(&root, &components_for_list))
.await
{
Ok(Ok(entries)) => entries,
Ok(Err(error)) => return io_response(&error),
Err(_) => {
return status_response(
StatusCode::INTERNAL_SERVER_ERROR,
"RustProxy: Web Server directory task failed\n",
)
}
};
// Filtering in place avoids a second Vec allocation for large directories
// while retaining exactly the same visibility and hardening checks.
entries.retain(|entry| {
@@ -419,6 +418,11 @@ pub async fn serve(
crate::web_server::metrics::HeadersInFlight::new(&service.web_metrics.in_flight_headers);
let request_method = method.clone();
let mut response = serve_inner(service, method, headers, uri, path, body, context).await;
// HEAD carries the same metadata/status as GET, but no response body,
// including the generic filesystem and rewrite error paths.
if request_method == Method::HEAD {
*response.body_mut() = Body::empty();
}
add_service_headers(&mut response, service);
htaccess::apply_response(service.htaccess.as_ref(), &mut response, path);
strip_unnecessary_headers(&mut response, service);
+114 -12
View File
@@ -118,6 +118,28 @@ async fn missing_files_and_disabled_directory_listing_return_normal_errors() {
)
.await;
assert_eq!(missing.status(), StatusCode::NOT_FOUND);
assert_eq!(missing.headers()[CACHE_CONTROL], "no-store");
assert_eq!(missing.headers()[CONTENT_TYPE], "text/plain; charset=utf-8");
assert_eq!(
missing.into_body().collect().await.unwrap().to_bytes(),
"404 Not Found\n"
);
let missing_head = serve_request(
&service,
&request(Method::HEAD, "/missing.txt"),
"/missing.txt",
)
.await;
assert_eq!(missing_head.status(), StatusCode::NOT_FOUND);
assert_eq!(missing_head.headers()[CONTENT_LENGTH], "14");
assert!(missing_head
.into_body()
.collect()
.await
.unwrap()
.to_bytes()
.is_empty());
let directory = serve_request(&service, &request(Method::GET, "/empty/"), "/empty/").await;
assert_eq!(directory.status(), StatusCode::FORBIDDEN);
@@ -149,6 +171,40 @@ async fn missing_files_and_disabled_directory_listing_return_normal_errors() {
.await;
assert_eq!(method.status(), StatusCode::METHOD_NOT_ALLOWED);
assert_eq!(method.headers()[ALLOW], "GET, HEAD");
assert_eq!(
method.into_body().collect().await.unwrap().to_bytes(),
"405 Method Not Allowed\n"
);
}
#[tokio::test]
async fn internal_filesystem_diagnostics_never_appear_in_public_error_responses() {
use std::io::ErrorKind;
for (kind, expected_status, expected_text) in [
(
ErrorKind::NotFound,
StatusCode::NOT_FOUND,
"404 Not Found\n",
),
(
ErrorKind::PermissionDenied,
StatusCode::FORBIDDEN,
"403 Forbidden\n",
),
(
ErrorKind::Other,
StatusCode::INTERNAL_SERVER_ERROR,
"500 Internal Server Error\n",
),
] {
let error = std::io::Error::from(kind);
let response = super::response::io_response(&error);
assert_eq!(response.status(), expected_status);
assert_eq!(response.headers()[CACHE_CONTROL], "no-store");
let body = response.into_body().collect().await.unwrap().to_bytes();
assert_eq!(body.as_ref(), expected_text.as_bytes());
assert!(!body.starts_with(b"RustProxy:"));
}
}
#[tokio::test]
@@ -2238,41 +2294,87 @@ async fn sendfile_auto_without_tcp_bridge_preserves_full_head_range_and_validato
document_root: tmp.path().to_path_buf(),
sendfile: SendfileMode::Auto,
..Default::default()
}.compile().unwrap();
}
.compile()
.unwrap();
let get = serve_request(&service, &request(Method::GET, "/large.bin"), "/large.bin").await;
assert_eq!(get.status(), StatusCode::OK);
assert_eq!(get.headers()[CONTENT_LENGTH].to_str().unwrap(), original.len().to_string());
assert_eq!(
get.headers()[CONTENT_LENGTH].to_str().unwrap(),
original.len().to_string()
);
// No transport adapter here. Even if a candidate extension was produced,
// its fallback Body must still stream the exact original representation.
let etag = get.headers()[ETAG].clone();
assert_eq!(get.into_body().collect().await.unwrap().to_bytes().to_vec(), original);
assert_eq!(
get.into_body().collect().await.unwrap().to_bytes().to_vec(),
original
);
let head = serve_request(&service, &request(Method::HEAD, "/large.bin"), "/large.bin").await;
assert_eq!(head.status(), StatusCode::OK);
assert_eq!(head.headers()[CONTENT_LENGTH].to_str().unwrap(), original.len().to_string());
assert!(head.into_body().collect().await.unwrap().to_bytes().is_empty());
assert_eq!(
head.headers()[CONTENT_LENGTH].to_str().unwrap(),
original.len().to_string()
);
assert!(head
.into_body()
.collect()
.await
.unwrap()
.to_bytes()
.is_empty());
let mut range = request(Method::GET, "/large.bin");
range.headers_mut().insert(RANGE, HeaderValue::from_static("bytes=100-199"));
range
.headers_mut()
.insert(RANGE, HeaderValue::from_static("bytes=100-199"));
let ranged = serve_request(&service, &range, "/large.bin").await;
assert_eq!(ranged.status(), StatusCode::PARTIAL_CONTENT);
assert_eq!(ranged.headers()[CONTENT_RANGE].to_str().unwrap(), format!("bytes 100-199/{}", original.len()));
assert_eq!(ranged.into_body().collect().await.unwrap().to_bytes().to_vec(), original[100..200]);
assert_eq!(
ranged.headers()[CONTENT_RANGE].to_str().unwrap(),
format!("bytes 100-199/{}", original.len())
);
assert_eq!(
ranged
.into_body()
.collect()
.await
.unwrap()
.to_bytes()
.to_vec(),
original[100..200]
);
let mut conditional = request(Method::GET, "/large.bin");
conditional.headers_mut().insert(IF_NONE_MATCH, etag);
let unchanged = serve_request(&service, &conditional, "/large.bin").await;
assert_eq!(unchanged.status(), StatusCode::NOT_MODIFIED);
assert!(unchanged.into_body().collect().await.unwrap().to_bytes().is_empty());
assert!(unchanged
.into_body()
.collect()
.await
.unwrap()
.to_bytes()
.is_empty());
}
#[test]
fn sendfile_mode_is_backward_compatible_and_rejects_unknown_values() {
assert_eq!(SendfileMode::default(), SendfileMode::Off);
assert_eq!(serde_json::from_str::<SendfileMode>("\"auto\"").unwrap(), SendfileMode::Auto);
assert_eq!(serde_json::from_str::<SendfileMode>("\"off\"").unwrap(), SendfileMode::Off);
assert_eq!(
serde_json::from_str::<SendfileMode>("\"auto\"").unwrap(),
SendfileMode::Auto
);
assert_eq!(
serde_json::from_str::<SendfileMode>("\"off\"").unwrap(),
SendfileMode::Off
);
assert!(serde_json::from_str::<SendfileMode>("\"unsafe\"").is_err());
let legacy = serde_json::json!({"id":"legacy", "name":"Legacy", "document_root":"/tmp"});
assert_eq!(serde_json::from_value::<Service>(legacy).unwrap().sendfile, SendfileMode::Off);
assert_eq!(
serde_json::from_value::<Service>(legacy).unwrap().sendfile,
SendfileMode::Off
);
}