This commit is contained in:
Mateusz Gruszczyński committed 2026-10-08 23:36:27 +02:00
1 parent 68678e98be
commit b3bc56cd42
16 files changed
+230 -54

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.0.3",
"info": {
"title": "RustProxy Administration API",
"version": "0.29.2",
"version": "0.29.3",
"description": "Administration API for the active panel origin. Sign in through the panel; the same-origin HttpOnly cookie authenticates all private operations. Mutations also require the exact Origin, X-RustProxy-Request: 1 and a session-bound X-CSRF-Token. Loopback HTTP is the default; Settings can enable HTTPS before using a non-loopback administration bind. This document contains no live configuration or credentials. Object schemas marked extensible are summaries: full configuration validation is authoritative in Rust."
},
"servers": [
+28
View File
@@ -8,6 +8,11 @@ struct InternalFallbackRoute {
#[derive(Clone)]
struct FinalRouteContext(crate::config::CompiledRoute);
/// The named location has already produced the terminal HTTP response.
/// In particular, do not replace its 404 HTML with a global/vhost error page.
#[derive(Clone, Copy)]
struct ErrorFallbackResponse;
#[derive(Clone)]
struct ErrorFallbackRequest {
method: Method,
@@ -88,6 +93,21 @@ async fn prepare_error_fallback_body(request: &mut Request, enabled: bool) -> Re
return Ok(ErrorFallbackBody::Replayable(Bytes::new()));
}
let Some(length) = request.body().size_hint().exact() else {
// HTTP/2 and HTTP/3 frequently expose an *empty* GET/HEAD body as a
// stream with no exact size hint. Refusing to inspect that stream
// silently disables the configured 404 fallback. Only peek for safe
// bodyless methods; an actual payload is replayed back into the
// original request and is never discarded or forwarded twice.
if request.method() == Method::GET || request.method() == Method::HEAD {
return match empty_for_cache(request).await {
Ok(true) => Ok(ErrorFallbackBody::Replayable(Bytes::new())),
Ok(false) => Ok(ErrorFallbackBody::Unavailable),
Err(_) => Err(error(
StatusCode::BAD_REQUEST,
"RustProxy: invalid or incomplete request body\n",
)),
};
}
return Ok(ErrorFallbackBody::Unavailable);
};
if length > MAX_ERROR_FALLBACK_REPLAY_BODY_BYTES {
@@ -131,6 +151,13 @@ async fn execute_error_fallback(
.select_internal_on(host, &frontend.id, &fallback.target, local.0, tls)
.cloned()
else {
tracing::warn!(
vhost = %frontend.id,
route = %route.id,
target = %fallback.target,
status = status.as_u16(),
"error fallback target could not be resolved on this frontend"
);
return None;
};
let ErrorFallbackBody::Replayable(body) = body else {
@@ -148,6 +175,7 @@ async fn execute_error_fallback(
},
);
let mut response = Box::pin(forward_request(state, peer, local, request)).await;
response.extensions_mut().insert(ErrorFallbackResponse);
if response.extensions().get::<FinalRouteContext>().is_none() {
response.extensions_mut().insert(FinalRouteContext(target));
}
+103
View File
@@ -307,3 +307,106 @@ fn upstream_uri_preserves_nested_url_query_without_rejecting_valid_separators()
let uri = upstream_uri(backend, suffix).unwrap();
assert_eq!(uri.path_and_query().unwrap().as_str(), suffix);
}
#[tokio::test]
async fn error_fallback_replays_empty_unknown_length_h2_h3_get_and_head() {
use bytes::Bytes;
for version in [Version::HTTP_2, Version::HTTP_3] {
for method in [Method::GET, Method::HEAD] {
let stream = futures_util::stream::empty::<Result<Bytes, std::io::Error>>();
let mut request = Request::builder()
.version(version)
.method(method.clone())
.uri("https://www.example.test/missing?query=1")
.body(Body::from_stream(stream))
.unwrap();
assert_eq!(request.body().size_hint().exact(), None);
let result = match prepare_error_fallback_body(&mut request, true).await {
Ok(result) => result,
Err(response) => panic!("unexpected status {}", response.status()),
};
assert!(
matches!(result, ErrorFallbackBody::Replayable(ref bytes) if bytes.is_empty()),
"an empty {method:?} request over {version:?} should allow fallback"
);
assert!(request.body().is_end_stream());
assert_eq!(request.uri().path_and_query().unwrap().as_str(), "/missing?query=1");
}
}
}
#[tokio::test]
async fn error_fallback_preserves_unknown_length_get_payload_without_replaying_it() {
use bytes::Bytes;
let stream = futures_util::stream::iter([Ok::<_, std::io::Error>(
Bytes::from_static(b"unexpected-payload"),
)]);
let mut request = Request::builder()
.method(Method::GET)
.version(Version::HTTP_3)
.uri("https://www.example.test/missing")
.body(Body::from_stream(stream))
.unwrap();
let result = match prepare_error_fallback_body(&mut request, true).await {
Ok(result) => result,
Err(response) => panic!("unexpected status {}", response.status()),
};
assert!(matches!(result, ErrorFallbackBody::Unavailable));
assert_eq!(
request.into_body().collect().await.unwrap().to_bytes(),
Bytes::from_static(b"unexpected-payload")
);
}
#[tokio::test]
async fn error_fallback_does_not_poll_unknown_length_post_payload() {
use bytes::Bytes;
let stream = futures_util::stream::pending::<Result<Bytes, std::io::Error>>();
let mut request = Request::builder()
.method(Method::POST)
.version(Version::HTTP_2)
.uri("https://www.example.test/form")
.body(Body::from_stream(stream))
.unwrap();
let result = match prepare_error_fallback_body(&mut request, true).await {
Ok(result) => result,
Err(response) => panic!("unexpected status {}", response.status()),
};
assert!(matches!(result, ErrorFallbackBody::Unavailable));
}
#[tokio::test]
async fn fallback_terminal_404_html_takes_precedence_over_builtin_error_page() {
use bytes::Bytes;
let mut response = Response::builder()
.status(StatusCode::NOT_FOUND)
.header("content-type", "text/html; charset=utf-8")
.body(Body::from("<html><title>ReactPHP 404</title></html>"))
.unwrap();
response.extensions_mut().insert(ErrorFallbackResponse);
let configured_page = crate::pages::Page {
kind: crate::pages::Kind::Builtin,
status: Some(404),
html: String::new(),
};
if should_replace_error_page(&response, false) {
crate::pages::replace_error(&mut response, &configured_page);
}
assert_eq!(response.status(), StatusCode::NOT_FOUND);
assert_eq!(
response.into_body().collect().await.unwrap().to_bytes(),
Bytes::from_static(b"<html><title>ReactPHP 404</title></html>")
);
// A normal response with no fallback is still eligible for the configured
// global/vhost error-page replacement.
let response = Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::empty())
.unwrap();
assert!(should_replace_error_page(&response, false));
}
+10 -6
View File
@@ -11,6 +11,15 @@ fn request_id_hash(sequence: u64) -> String {
format!("{:x}", hash.finalize())
}
fn should_replace_error_page(response: &Response, minimal_welcome: bool) -> bool {
!minimal_welcome
&& response.extensions().get::<ErrorFallbackResponse>().is_none()
&& response
.extensions()
.get::<crate::tinyauth::AuthenticationFailure>()
.is_none()
}
async fn observe(State(state): State<Arc<App>>, mut request: Request, next: Next) -> Response {
let snapshot = state.config.load_full();
let (frontend_context, route_context) = response_context(&snapshot, &request);
@@ -205,12 +214,7 @@ async fn observe(State(state): State<Arc<App>>, mut request: Request, next: Next
.as_ref()
.and_then(|f| f.pages.errors.get(&code))
.or_else(|| snapshot.envelope.config.pages.errors.get(&code));
if !minimal_welcome
&& response
.extensions()
.get::<crate::tinyauth::AuthenticationFailure>()
.is_none()
{
if should_replace_error_page(&response, minimal_welcome) {
if let Some(page) = custom_error {
crate::pages::replace_error(&mut response, page);
}