0.34.6_repo_cleanup
This commit is contained in:
1 parent
ce1a90397c
commit
133d2f0f91
273 files changed
+5969
-6926
No files matched your search
@@ -0,0 +1,328 @@
|
||||
use anyhow::{ensure, Result};
|
||||
use axum::{body::Body, response::Response};
|
||||
use http::{HeaderValue, Method, StatusCode};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub const MAX_HTML_BYTES: usize = 32 * 1024;
|
||||
pub const ERROR_CODES: [u16; 11] = [400, 401, 403, 404, 408, 413, 429, 500, 502, 503, 504];
|
||||
pub const BUILTIN_ERROR_CODES: [u16; 12] =
|
||||
[400, 401, 403, 404, 408, 410, 413, 429, 500, 502, 503, 504];
|
||||
|
||||
pub fn builtin_gateway_error(status: StatusCode) -> Option<&'static str> {
|
||||
match status {
|
||||
StatusCode::BAD_REQUEST => Some(include_str!("../admin/web/error_400.html")),
|
||||
StatusCode::UNAUTHORIZED => Some(include_str!("../admin/web/error_401.html")),
|
||||
StatusCode::FORBIDDEN => Some(include_str!("../admin/web/error_403.html")),
|
||||
StatusCode::NOT_FOUND => Some(include_str!("../admin/web/error_404.html")),
|
||||
StatusCode::REQUEST_TIMEOUT => Some(include_str!("../admin/web/error_408.html")),
|
||||
StatusCode::GONE => Some(include_str!("../admin/web/error_410.html")),
|
||||
StatusCode::PAYLOAD_TOO_LARGE => Some(include_str!("../admin/web/error_413.html")),
|
||||
StatusCode::TOO_MANY_REQUESTS => Some(include_str!("../admin/web/error_429.html")),
|
||||
StatusCode::INTERNAL_SERVER_ERROR => Some(include_str!("../admin/web/error_500.html")),
|
||||
StatusCode::BAD_GATEWAY => Some(include_str!("../admin/web/error_502.html")),
|
||||
StatusCode::SERVICE_UNAVAILABLE => Some(include_str!("../admin/web/error_503.html")),
|
||||
StatusCode::GATEWAY_TIMEOUT => Some(include_str!("../admin/web/error_504.html")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub(crate) fn builtin_application_page(status: StatusCode) -> String {
|
||||
if status == StatusCode::OK {
|
||||
return include_str!("../admin/web/status_200.html").to_owned();
|
||||
}
|
||||
if let Some(page) = builtin_gateway_error(status) {
|
||||
return page.to_owned();
|
||||
}
|
||||
let reason = status.canonical_reason().unwrap_or("Response");
|
||||
format!(
|
||||
r#"<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>{code} - {reason} - RustProxy</title>
|
||||
<style>
|
||||
body {{ margin: 12vh auto; padding: 24px; max-width: 620px; background: #131615; color: #e5e9e6; font: 15px/1.6 system-ui, sans-serif }}
|
||||
h1 {{ font-size: 24px; margin: 0 0 8px }}
|
||||
p {{ margin: 0; color: #b9c3bc }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>{code} - {reason}</h1>
|
||||
<p>RustProxy generated this response.</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>"#,
|
||||
code = status.as_u16(),
|
||||
reason = reason
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Kind {
|
||||
#[default]
|
||||
Welcome,
|
||||
Empty,
|
||||
Html,
|
||||
Builtin,
|
||||
}
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Page {
|
||||
pub kind: Kind,
|
||||
pub status: Option<u16>,
|
||||
pub html: String,
|
||||
}
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct GlobalPages {
|
||||
pub errors: BTreeMap<u16, Page>,
|
||||
pub direct_ip: Option<Page>,
|
||||
pub unknown_host: Option<Page>,
|
||||
}
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct VhostPages {
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub intercept_statuses: Vec<u16>,
|
||||
pub response: Option<Page>,
|
||||
pub fallback: Option<Page>,
|
||||
pub errors: BTreeMap<u16, Page>,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct PageServed;
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct OriginProvidedResponse;
|
||||
#[derive(Clone)]
|
||||
pub struct MinimalWelcome;
|
||||
|
||||
impl Page {
|
||||
pub fn validate_local_response(&self) -> Result<()> {
|
||||
ensure!(
|
||||
self.html.len() <= MAX_HTML_BYTES,
|
||||
"custom page HTML exceeds 32 KiB"
|
||||
);
|
||||
if let Some(status) = self.status {
|
||||
ensure!(
|
||||
(200..=599).contains(&status) && StatusCode::from_u16(status).is_ok(),
|
||||
"local response status must be 200..599"
|
||||
);
|
||||
ensure!(
|
||||
!matches!(status, 204 | 205 | 304) || matches!(self.kind, Kind::Empty),
|
||||
"204, 205 and 304 require an empty page"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
!matches!(self.kind, Kind::Html) || !self.html.trim().is_empty(),
|
||||
"HTML page cannot be blank; use empty mode"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
ensure!(
|
||||
self.html.len() <= MAX_HTML_BYTES,
|
||||
"custom page HTML exceeds 32 KiB"
|
||||
);
|
||||
if let Some(status) = self.status {
|
||||
ensure!(
|
||||
matches!(
|
||||
status,
|
||||
200 | 204
|
||||
| 400
|
||||
| 401
|
||||
| 403
|
||||
| 404
|
||||
| 408
|
||||
| 410
|
||||
| 413
|
||||
| 429
|
||||
| 500
|
||||
| 502
|
||||
| 503
|
||||
| 504
|
||||
),
|
||||
"unsupported custom page status"
|
||||
);
|
||||
ensure!(
|
||||
status != 204 || matches!(self.kind, Kind::Empty),
|
||||
"204 requires an empty page"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
!matches!(self.kind, Kind::Html) || !self.html.trim().is_empty(),
|
||||
"HTML page cannot be blank; use empty mode"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn body(&self, status: StatusCode) -> String {
|
||||
match self.kind {
|
||||
Kind::Empty => String::new(),
|
||||
Kind::Html => self.html.clone(),
|
||||
Kind::Welcome => include_str!("../admin/web/demo.html").to_owned(),
|
||||
Kind::Builtin => builtin_application_page(status),
|
||||
}
|
||||
}
|
||||
pub fn render(&self, default_status: StatusCode) -> Response {
|
||||
let status = self
|
||||
.status
|
||||
.and_then(|v| StatusCode::from_u16(v).ok())
|
||||
.unwrap_or(default_status);
|
||||
let bodyless = matches!(
|
||||
status,
|
||||
StatusCode::NO_CONTENT | StatusCode::RESET_CONTENT | StatusCode::NOT_MODIFIED
|
||||
);
|
||||
let body = if bodyless {
|
||||
String::new()
|
||||
} else {
|
||||
self.body(status)
|
||||
};
|
||||
let length = body.len();
|
||||
let mut response = Response::new(Body::from(body));
|
||||
*response.status_mut() = status;
|
||||
let headers = response.headers_mut();
|
||||
headers.insert(
|
||||
"content-type",
|
||||
HeaderValue::from_static(if matches!(self.kind, Kind::Empty) {
|
||||
"text/plain; charset=utf-8"
|
||||
} else {
|
||||
"text/html; charset=utf-8"
|
||||
}),
|
||||
);
|
||||
if !bodyless {
|
||||
if let Ok(value) = HeaderValue::from_str(&length.to_string()) {
|
||||
headers.insert("content-length", value);
|
||||
}
|
||||
}
|
||||
headers.insert("cache-control", HeaderValue::from_static("no-store"));
|
||||
if matches!(self.kind, Kind::Welcome) {
|
||||
response.extensions_mut().insert(MinimalWelcome);
|
||||
} else {
|
||||
headers.insert(
|
||||
"x-content-type-options",
|
||||
HeaderValue::from_static("nosniff"),
|
||||
);
|
||||
}
|
||||
response.extensions_mut().insert(PageServed);
|
||||
response
|
||||
}
|
||||
pub fn serve(&self, method: &Method, default_status: StatusCode) -> Response {
|
||||
if !matches!(*method, Method::GET | Method::HEAD) {
|
||||
let mut response = Response::new(Body::empty());
|
||||
*response.status_mut() = StatusCode::METHOD_NOT_ALLOWED;
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("allow", HeaderValue::from_static("GET, HEAD"));
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("cache-control", HeaderValue::from_static("no-store"));
|
||||
response.extensions_mut().insert(PageServed);
|
||||
return response;
|
||||
}
|
||||
self.render(default_status)
|
||||
}
|
||||
}
|
||||
fn validate_errors(errors: &BTreeMap<u16, Page>) -> Result<()> {
|
||||
ensure!(
|
||||
errors.len() <= ERROR_CODES.len(),
|
||||
"too many custom error pages"
|
||||
);
|
||||
for (code, page) in errors {
|
||||
ensure!(ERROR_CODES.contains(code), "unsupported error page code");
|
||||
page.validate()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
impl GlobalPages {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
validate_errors(&self.errors)?;
|
||||
for page in [&self.direct_ip, &self.unknown_host].into_iter().flatten() {
|
||||
page.validate()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl VhostPages {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
validate_errors(&self.errors)?;
|
||||
ensure!(
|
||||
self.intercept_statuses.len() <= ERROR_CODES.len()
|
||||
&& self
|
||||
.intercept_statuses
|
||||
.iter()
|
||||
.all(|status| ERROR_CODES.contains(status))
|
||||
&& {
|
||||
let distinct: std::collections::HashSet<_> =
|
||||
self.intercept_statuses.iter().collect();
|
||||
distinct.len() == self.intercept_statuses.len()
|
||||
},
|
||||
"intercepted application status codes must be unique supported HTTP error codes"
|
||||
);
|
||||
for page in [&self.response, &self.fallback].into_iter().flatten() {
|
||||
page.validate()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
pub fn replace_error(response: &mut Response, page: &Page) {
|
||||
if response.extensions().get::<PageServed>().is_some() {
|
||||
return;
|
||||
}
|
||||
let mut replacement = page.render(response.status());
|
||||
for name in [
|
||||
"www-authenticate",
|
||||
"proxy-authenticate",
|
||||
"allow",
|
||||
"retry-after",
|
||||
] {
|
||||
for value in response.headers().get_all(name) {
|
||||
replacement.headers_mut().append(name, value.clone());
|
||||
}
|
||||
}
|
||||
*response = replacement;
|
||||
}
|
||||
pub fn intercept_application_error(
|
||||
mut response: Response,
|
||||
vhost_pages: &VhostPages,
|
||||
global_pages: &GlobalPages,
|
||||
) -> Response {
|
||||
let code = response.status().as_u16();
|
||||
if !vhost_pages.intercept_statuses.contains(&code)
|
||||
|| response.extensions().get::<PageServed>().is_some()
|
||||
{
|
||||
return response;
|
||||
}
|
||||
let default_page = Page {
|
||||
kind: Kind::Builtin,
|
||||
status: None,
|
||||
html: String::new(),
|
||||
};
|
||||
let selected = vhost_pages
|
||||
.errors
|
||||
.get(&code)
|
||||
.or_else(|| global_pages.errors.get(&code))
|
||||
.unwrap_or(&default_page);
|
||||
let mut body_only = selected.clone();
|
||||
body_only.status = None;
|
||||
replace_error(&mut response, &body_only);
|
||||
response
|
||||
}
|
||||
|
||||
pub fn literal_ip_authority(value: &str) -> bool {
|
||||
!value.contains('@')
|
||||
&& value
|
||||
.parse::<http::uri::Authority>()
|
||||
.ok()
|
||||
.is_some_and(|authority| {
|
||||
authority
|
||||
.host()
|
||||
.trim_start_matches('[')
|
||||
.trim_end_matches(']')
|
||||
.parse::<std::net::IpAddr>()
|
||||
.is_ok()
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
include!("tests.rs");
|
||||
Reference in new issue
Block a user