0.34.13_cleaup_code
This commit is contained in:
1 parent
ec46a96a29
commit
5c2e50ec06
87 files changed
+4890
-1338
No files matched your search
@@ -1,7 +1,7 @@
|
||||
use super::htaccess;
|
||||
use super::htaccess::Config as HtaccessConfig;
|
||||
#[cfg(unix)]
|
||||
use super::filesystem::open_root_directory;
|
||||
use super::htaccess;
|
||||
use super::htaccess::Config as HtaccessConfig;
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use http::{HeaderName, HeaderValue, StatusCode};
|
||||
use regex::Regex;
|
||||
|
||||
@@ -11,9 +11,26 @@ pub(super) async fn php_response(
|
||||
context: RequestContext,
|
||||
) -> Response {
|
||||
let start = Instant::now();
|
||||
let mut response = php_response_inner(service, php, method, headers, original_uri, script_path, path_info, query, body, context).await;
|
||||
php.metrics.record(response.status(), start.elapsed().as_micros().min(u64::MAX as u128) as u64);
|
||||
response.extensions_mut().insert(crate::web_server::metrics::ResponseKind::Php);
|
||||
let mut response = php_response_inner(
|
||||
service,
|
||||
php,
|
||||
method,
|
||||
headers,
|
||||
original_uri,
|
||||
script_path,
|
||||
path_info,
|
||||
query,
|
||||
body,
|
||||
context,
|
||||
)
|
||||
.await;
|
||||
php.metrics.record(
|
||||
response.status(),
|
||||
start.elapsed().as_micros().min(u64::MAX as u128) as u64,
|
||||
);
|
||||
response
|
||||
.extensions_mut()
|
||||
.insert(crate::web_server::metrics::ResponseKind::Php);
|
||||
response
|
||||
}
|
||||
|
||||
@@ -51,15 +68,19 @@ async fn php_response_inner(
|
||||
return response;
|
||||
}
|
||||
};
|
||||
let mut io = match tokio::time::timeout(php.connect_timeout, connect_fastcgi(&php.endpoint)).await {
|
||||
Ok(Ok(io)) => io,
|
||||
Ok(Err(error)) => {
|
||||
php.metrics.failure(2);
|
||||
tracing::warn!(%error, service = %service.id, "PHP-FPM connection failed");
|
||||
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
|
||||
}
|
||||
Err(_) => { php.metrics.failure(1); return builtin_error_response(StatusCode::GATEWAY_TIMEOUT, &method); },
|
||||
};
|
||||
let mut io =
|
||||
match tokio::time::timeout(php.connect_timeout, connect_fastcgi(&php.endpoint)).await {
|
||||
Ok(Ok(io)) => io,
|
||||
Ok(Err(error)) => {
|
||||
php.metrics.failure(2);
|
||||
tracing::warn!(%error, service = %service.id, "PHP-FPM connection failed");
|
||||
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
|
||||
}
|
||||
Err(_) => {
|
||||
php.metrics.failure(1);
|
||||
return builtin_error_response(StatusCode::GATEWAY_TIMEOUT, &method);
|
||||
}
|
||||
};
|
||||
let params = match fastcgi_params(
|
||||
service,
|
||||
php,
|
||||
@@ -91,8 +112,9 @@ async fn php_response_inner(
|
||||
let mut body = body;
|
||||
let mut body_bytes = 0u64;
|
||||
while let Some(frame) = body.frame().await {
|
||||
let frame = frame
|
||||
.map_err(|error| FastCgiRequestWriteError::Io(io::Error::other(error.to_string())))?;
|
||||
let frame = frame.map_err(|error| {
|
||||
FastCgiRequestWriteError::Io(io::Error::other(error.to_string()))
|
||||
})?;
|
||||
if let Ok(data) = frame.into_data() {
|
||||
body_bytes = body_bytes.saturating_add(data.len() as u64);
|
||||
if php.max_request_body_bytes > 0 && body_bytes > php.max_request_body_bytes {
|
||||
@@ -117,7 +139,10 @@ async fn php_response_inner(
|
||||
tracing::warn!(%error, service = %service.id, "PHP-FPM request write failed");
|
||||
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
|
||||
}
|
||||
Err(_) => { php.metrics.failure(3); return builtin_error_response(StatusCode::GATEWAY_TIMEOUT, &method); },
|
||||
Err(_) => {
|
||||
php.metrics.failure(3);
|
||||
return builtin_error_response(StatusCode::GATEWAY_TIMEOUT, &method);
|
||||
}
|
||||
}
|
||||
|
||||
let mut stdout = Vec::new();
|
||||
@@ -128,7 +153,7 @@ async fn php_response_inner(
|
||||
Ok(value) => value,
|
||||
Err(error) if error.kind() == io::ErrorKind::TimedOut => {
|
||||
php.metrics.failure(5);
|
||||
return builtin_error_response(StatusCode::GATEWAY_TIMEOUT, &method)
|
||||
return builtin_error_response(StatusCode::GATEWAY_TIMEOUT, &method);
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, service = %service.id, "PHP-FPM response read failed");
|
||||
@@ -218,17 +243,24 @@ pub(super) fn method_not_allowed_response() -> Response {
|
||||
response
|
||||
}
|
||||
|
||||
pub(super) fn php_for_path<'a>(service: &'a CompiledService, path: &Path) -> Option<&'a CompiledPhp> {
|
||||
pub(super) fn php_for_path<'a>(
|
||||
service: &'a CompiledService,
|
||||
path: &Path,
|
||||
) -> Option<&'a CompiledPhp> {
|
||||
let php = service.php.as_ref()?;
|
||||
let extension = path
|
||||
.extension()
|
||||
.and_then(|value| value.to_str())?
|
||||
.to_ascii_lowercase();
|
||||
(php.extensions.contains(&extension) || htaccess::php_extension(service.htaccess.as_ref(), path)).then_some(php)
|
||||
(php.extensions.contains(&extension)
|
||||
|| htaccess::php_extension(service.htaccess.as_ref(), path))
|
||||
.then_some(php)
|
||||
}
|
||||
|
||||
pub(super) fn protected_script_without_handler(service: &CompiledService, path: &Path) -> bool {
|
||||
if service.php.is_some() { return false; }
|
||||
if service.php.is_some() {
|
||||
return false;
|
||||
}
|
||||
path.extension()
|
||||
.and_then(|value| value.to_str())
|
||||
.map(|value| value.to_ascii_lowercase())
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use super::{CompiledService, SymlinkPolicy};
|
||||
#[cfg(unix)]
|
||||
use std::{ffi::CString, sync::Arc};
|
||||
use std::{
|
||||
fs::File,
|
||||
io,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
#[cfg(unix)]
|
||||
use std::{ffi::CString, sync::Arc};
|
||||
|
||||
pub(super) struct FilesystemRoot {
|
||||
root: PathBuf,
|
||||
@@ -63,12 +63,18 @@ pub(super) fn open_root_directory(path: &Path) -> io::Result<File> {
|
||||
|
||||
pub(super) fn path_components(path: &str) -> io::Result<Vec<String>> {
|
||||
if !path.starts_with('/') {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "path is not absolute"));
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"path is not absolute",
|
||||
));
|
||||
}
|
||||
let mut result = Vec::new();
|
||||
for part in path.split('/').filter(|part| !part.is_empty()) {
|
||||
if part == "." || part == ".." || part.contains('\\') || part.contains('\0') {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "ambiguous path"));
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"ambiguous path",
|
||||
));
|
||||
}
|
||||
result.push(part.to_owned());
|
||||
}
|
||||
@@ -93,7 +99,10 @@ pub(super) fn secure_open_sync(root: &FilesystemRoot, components: &[String]) ->
|
||||
}
|
||||
let current = unsafe { File::from_raw_fd(fd) };
|
||||
let metadata = current.metadata()?;
|
||||
return Ok(Opened { file: current, metadata });
|
||||
return Ok(Opened {
|
||||
file: current,
|
||||
metadata,
|
||||
});
|
||||
}
|
||||
let mut current: Option<File> = None;
|
||||
for (index, component) in components.iter().enumerate() {
|
||||
@@ -135,7 +144,10 @@ pub(super) fn secure_open_sync(root: &FilesystemRoot, components: &[String]) ->
|
||||
"Web Server serves only regular files and directories",
|
||||
));
|
||||
}
|
||||
Ok(Opened { file: current, metadata })
|
||||
Ok(Opened {
|
||||
file: current,
|
||||
metadata,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -192,7 +204,10 @@ pub(super) fn list_directory_sync(
|
||||
|
||||
let opened = secure_open_sync(root, components)?;
|
||||
if !opened.metadata.is_dir() {
|
||||
return Err(io::Error::new(io::ErrorKind::NotADirectory, "not a directory"));
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::NotADirectory,
|
||||
"not a directory",
|
||||
));
|
||||
}
|
||||
let raw = opened.file.try_clone()?.into_raw_fd();
|
||||
let dir = unsafe { libc::fdopendir(raw) };
|
||||
@@ -241,7 +256,10 @@ pub(super) fn list_directory_sync(
|
||||
) -> io::Result<Vec<DirectoryEntry>> {
|
||||
let opened = secure_open_sync(root, components)?;
|
||||
if !opened.metadata.is_dir() {
|
||||
return Err(io::Error::new(io::ErrorKind::NotADirectory, "not a directory"));
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::NotADirectory,
|
||||
"not a directory",
|
||||
));
|
||||
}
|
||||
let mut path = root.root.clone();
|
||||
for component in components {
|
||||
@@ -249,7 +267,10 @@ pub(super) fn list_directory_sync(
|
||||
}
|
||||
let canonical = std::fs::canonicalize(path)?;
|
||||
if !canonical.starts_with(&root.root) {
|
||||
return Err(io::Error::new(io::ErrorKind::PermissionDenied, "path escaped document root"));
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"path escaped document root",
|
||||
));
|
||||
}
|
||||
let mut entries = Vec::new();
|
||||
for entry in std::fs::read_dir(canonical)? {
|
||||
@@ -275,4 +296,3 @@ pub(super) fn list_directory_sync(
|
||||
});
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
use super::{
|
||||
config::CompiledService,
|
||||
filesystem::path_components,
|
||||
request::RequestContext,
|
||||
config::CompiledService, filesystem::path_components, request::RequestContext,
|
||||
routing::open_components,
|
||||
};
|
||||
use anyhow::{bail, ensure, Context, Result};
|
||||
@@ -119,9 +117,19 @@ struct RewriteCondition {
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum ConditionMatcher {
|
||||
Regex { regex: Regex, negate: bool },
|
||||
Exact { value: String, negate: bool, insensitive: bool },
|
||||
File { kind: FileTest, negate: bool },
|
||||
Regex {
|
||||
regex: Regex,
|
||||
negate: bool,
|
||||
},
|
||||
Exact {
|
||||
value: String,
|
||||
negate: bool,
|
||||
insensitive: bool,
|
||||
},
|
||||
File {
|
||||
kind: FileTest,
|
||||
negate: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -198,7 +206,13 @@ fn tokens(value: &str) -> Result<Vec<String>> {
|
||||
fn flags(value: Option<&str>) -> Vec<String> {
|
||||
value
|
||||
.and_then(|value| value.strip_prefix('[').and_then(|v| v.strip_suffix(']')))
|
||||
.map(|value| value.split(',').map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()).collect())
|
||||
.map(|value| {
|
||||
value
|
||||
.split(',')
|
||||
.map(|v| v.trim().to_owned())
|
||||
.filter(|v| !v.is_empty())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -227,16 +241,26 @@ fn supported_response_header(name: &HeaderName) -> bool {
|
||||
|
||||
fn parse_duration(value: &str) -> Result<Duration> {
|
||||
let value = value.trim().trim_matches('"').trim();
|
||||
if let Some(seconds) = value.strip_prefix('A').or_else(|| value.strip_prefix('a'))
|
||||
if let Some(seconds) = value
|
||||
.strip_prefix('A')
|
||||
.or_else(|| value.strip_prefix('a'))
|
||||
.filter(|seconds| !seconds.is_empty() && seconds.bytes().all(|byte| byte.is_ascii_digit()))
|
||||
{
|
||||
let seconds: u64 = seconds.parse().context("invalid Expires duration")?;
|
||||
return Ok(Duration::from_secs(seconds));
|
||||
}
|
||||
let parts = value.split_whitespace().collect::<Vec<_>>();
|
||||
ensure!(parts.len() >= 4, "Expires value must look like 'access plus 1 day' or A3600");
|
||||
ensure!(parts[0].eq_ignore_ascii_case("access") && parts[1].eq_ignore_ascii_case("plus"), "only access-based Expires values are supported");
|
||||
let count: u64 = parts[2].parse().context("invalid Expires duration number")?;
|
||||
ensure!(
|
||||
parts.len() >= 4,
|
||||
"Expires value must look like 'access plus 1 day' or A3600"
|
||||
);
|
||||
ensure!(
|
||||
parts[0].eq_ignore_ascii_case("access") && parts[1].eq_ignore_ascii_case("plus"),
|
||||
"only access-based Expires values are supported"
|
||||
);
|
||||
let count: u64 = parts[2]
|
||||
.parse()
|
||||
.context("invalid Expires duration number")?;
|
||||
let unit = parts[3].to_ascii_lowercase();
|
||||
let seconds = match unit.trim_end_matches('s') {
|
||||
"second" => count,
|
||||
@@ -252,32 +276,73 @@ fn parse_duration(value: &str) -> Result<Duration> {
|
||||
}
|
||||
|
||||
fn parse_condition(parts: &[String]) -> Result<RewriteCondition> {
|
||||
ensure!(parts.len() >= 3, "RewriteCond needs a test string and pattern");
|
||||
ensure!(
|
||||
parts.len() >= 3,
|
||||
"RewriteCond needs a test string and pattern"
|
||||
);
|
||||
let condition_flags = flags(parts.get(3).map(String::as_str));
|
||||
let insensitive = condition_flags.iter().any(|flag| flag.eq_ignore_ascii_case("NC"));
|
||||
let or_next = condition_flags.iter().any(|flag| flag.eq_ignore_ascii_case("OR"));
|
||||
let insensitive = condition_flags
|
||||
.iter()
|
||||
.any(|flag| flag.eq_ignore_ascii_case("NC"));
|
||||
let or_next = condition_flags
|
||||
.iter()
|
||||
.any(|flag| flag.eq_ignore_ascii_case("OR"));
|
||||
for flag in &condition_flags {
|
||||
ensure!(flag.eq_ignore_ascii_case("NC") || flag.eq_ignore_ascii_case("OR"), "unsupported RewriteCond flag [{flag}]");
|
||||
ensure!(
|
||||
flag.eq_ignore_ascii_case("NC") || flag.eq_ignore_ascii_case("OR"),
|
||||
"unsupported RewriteCond flag [{flag}]"
|
||||
);
|
||||
}
|
||||
let raw = parts[2].as_str();
|
||||
let matcher = if let Some(value) = raw.strip_prefix("!=") {
|
||||
ConditionMatcher::Exact { value: value.to_owned(), negate: true, insensitive }
|
||||
ConditionMatcher::Exact {
|
||||
value: value.to_owned(),
|
||||
negate: true,
|
||||
insensitive,
|
||||
}
|
||||
} else if let Some(value) = raw.strip_prefix('=') {
|
||||
ConditionMatcher::Exact { value: value.to_owned(), negate: false, insensitive }
|
||||
ConditionMatcher::Exact {
|
||||
value: value.to_owned(),
|
||||
negate: false,
|
||||
insensitive,
|
||||
}
|
||||
} else {
|
||||
let (negate, raw) = raw.strip_prefix('!').map_or((false, raw), |v| (true, v));
|
||||
match raw {
|
||||
"-f" => ConditionMatcher::File { kind: FileTest::File, negate },
|
||||
"-d" => ConditionMatcher::File { kind: FileTest::Directory, negate },
|
||||
"-s" => ConditionMatcher::File { kind: FileTest::NonEmptyFile, negate },
|
||||
_ => ConditionMatcher::Regex { regex: ci_regex(raw, insensitive)?, negate },
|
||||
"-f" => ConditionMatcher::File {
|
||||
kind: FileTest::File,
|
||||
negate,
|
||||
},
|
||||
"-d" => ConditionMatcher::File {
|
||||
kind: FileTest::Directory,
|
||||
negate,
|
||||
},
|
||||
"-s" => ConditionMatcher::File {
|
||||
kind: FileTest::NonEmptyFile,
|
||||
negate,
|
||||
},
|
||||
_ => ConditionMatcher::Regex {
|
||||
regex: ci_regex(raw, insensitive)?,
|
||||
negate,
|
||||
},
|
||||
}
|
||||
};
|
||||
Ok(RewriteCondition { input: parts[1].clone(), matcher, or_next })
|
||||
Ok(RewriteCondition {
|
||||
input: parts[1].clone(),
|
||||
matcher,
|
||||
or_next,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_rewrite_rule(parts: &[String], conditions: Vec<RewriteCondition>, state: &mut ParseState) -> Result<RewriteRule> {
|
||||
ensure!(parts.len() >= 3, "RewriteRule needs a pattern and substitution");
|
||||
fn parse_rewrite_rule(
|
||||
parts: &[String],
|
||||
conditions: Vec<RewriteCondition>,
|
||||
state: &mut ParseState,
|
||||
) -> Result<RewriteRule> {
|
||||
ensure!(
|
||||
parts.len() >= 3,
|
||||
"RewriteRule needs a pattern and substitution"
|
||||
);
|
||||
let rule_flags = flags(parts.get(3).map(String::as_str));
|
||||
let mut redirect = None;
|
||||
let mut forbidden = false;
|
||||
@@ -319,15 +384,30 @@ fn parse_rewrite_rule(parts: &[String], conditions: Vec<RewriteCondition>, state
|
||||
|
||||
fn normalize_extension(value: &str) -> Result<String> {
|
||||
let value = value.trim().trim_start_matches('.').to_ascii_lowercase();
|
||||
ensure!(!value.is_empty() && value.len() <= 32 && value.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_')), "invalid extension in .htaccess");
|
||||
ensure!(
|
||||
!value.is_empty()
|
||||
&& value.len() <= 32
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_')),
|
||||
"invalid extension in .htaccess"
|
||||
);
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn unsupported(state: &mut ParseState, config: &Config, file: &Path, line: usize, message: String) -> Result<()> {
|
||||
fn unsupported(
|
||||
state: &mut ParseState,
|
||||
config: &Config,
|
||||
file: &Path,
|
||||
line: usize,
|
||||
message: String,
|
||||
) -> Result<()> {
|
||||
if config.strict {
|
||||
bail!("{}:{line}: {message}", file.display());
|
||||
}
|
||||
state.unsupported.push(format!("{}:{line}: {message}", file.display()));
|
||||
state
|
||||
.unsupported
|
||||
.push(format!("{}:{line}: {message}", file.display()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -344,17 +424,33 @@ fn read_htaccess_nofollow(path: &Path) -> Result<String> {
|
||||
#[cfg(not(unix))]
|
||||
let mut file = {
|
||||
let metadata = fs::symlink_metadata(path)?;
|
||||
ensure!(!metadata.file_type().is_symlink(), "{} must not be a symlink", path.display());
|
||||
ensure!(
|
||||
!metadata.file_type().is_symlink(),
|
||||
"{} must not be a symlink",
|
||||
path.display()
|
||||
);
|
||||
fs::File::open(path)?
|
||||
};
|
||||
let metadata = file.metadata()?;
|
||||
ensure!(metadata.is_file(), "{} is not a regular file", path.display());
|
||||
ensure!(metadata.len() <= MAX_HTACCESS_FILE_BYTES, "{} exceeds the 128 KiB .htaccess limit", path.display());
|
||||
ensure!(
|
||||
metadata.is_file(),
|
||||
"{} is not a regular file",
|
||||
path.display()
|
||||
);
|
||||
ensure!(
|
||||
metadata.len() <= MAX_HTACCESS_FILE_BYTES,
|
||||
"{} exceeds the 128 KiB .htaccess limit",
|
||||
path.display()
|
||||
);
|
||||
let mut content = String::new();
|
||||
(&mut file)
|
||||
.take(MAX_HTACCESS_FILE_BYTES + 1)
|
||||
.read_to_string(&mut content)
|
||||
.with_context(|| format!("{} is not valid UTF-8", path.display()))?;
|
||||
ensure!(content.len() as u64 <= MAX_HTACCESS_FILE_BYTES, "{} exceeds the 128 KiB .htaccess limit", path.display());
|
||||
ensure!(
|
||||
content.len() as u64 <= MAX_HTACCESS_FILE_BYTES,
|
||||
"{} exceeds the 128 KiB .htaccess limit",
|
||||
path.display()
|
||||
);
|
||||
Ok(content)
|
||||
}
|
||||
@@ -1,5 +1,19 @@
|
||||
pub async fn apply_rewrites(compiled: Option<&Compiled>, service: &CompiledService, method: &Method, headers: &HeaderMap, uri: &Uri, context: &RequestContext, initial_path: &str, initial_query: Option<&str>) -> Result<RewriteOutcome> {
|
||||
let Some(compiled) = compiled else { return Ok(RewriteOutcome::Internal { path: initial_path.to_owned(), query: initial_query.map(str::to_owned) }); };
|
||||
pub async fn apply_rewrites(
|
||||
compiled: Option<&Compiled>,
|
||||
service: &CompiledService,
|
||||
method: &Method,
|
||||
headers: &HeaderMap,
|
||||
uri: &Uri,
|
||||
context: &RequestContext,
|
||||
initial_path: &str,
|
||||
initial_query: Option<&str>,
|
||||
) -> Result<RewriteOutcome> {
|
||||
let Some(compiled) = compiled else {
|
||||
return Ok(RewriteOutcome::Internal {
|
||||
path: initial_path.to_owned(),
|
||||
query: initial_query.map(str::to_owned),
|
||||
});
|
||||
};
|
||||
let mut path = initial_path.to_owned();
|
||||
let mut query = initial_query.map(str::to_owned);
|
||||
let mut exhausted = false;
|
||||
@@ -10,37 +24,95 @@ pub async fn apply_rewrites(compiled: Option<&Compiled>, service: &CompiledServi
|
||||
'scope: for scope in scopes {
|
||||
for rule in &scope.rewrites {
|
||||
let relative = scope_relative_path(scope, &path);
|
||||
if !rule.pattern.is_match(&relative) { continue; }
|
||||
let (conditions_ok, condition_captures) = conditions_match(rule, service, method, headers, &path, query.as_deref(), uri, context).await;
|
||||
if !conditions_ok { continue; }
|
||||
let Some(captures) = rule.pattern.captures(&relative) else { continue; };
|
||||
if rule.forbidden { return Ok(RewriteOutcome::Forbidden); }
|
||||
if !rule.pattern.is_match(&relative) {
|
||||
continue;
|
||||
}
|
||||
let (conditions_ok, condition_captures) = conditions_match(
|
||||
rule,
|
||||
service,
|
||||
method,
|
||||
headers,
|
||||
&path,
|
||||
query.as_deref(),
|
||||
uri,
|
||||
context,
|
||||
)
|
||||
.await;
|
||||
if !conditions_ok {
|
||||
continue;
|
||||
}
|
||||
let Some(captures) = rule.pattern.captures(&relative) else {
|
||||
continue;
|
||||
};
|
||||
if rule.forbidden {
|
||||
return Ok(RewriteOutcome::Forbidden);
|
||||
}
|
||||
let replacement = replacement_with_captures(rule, &captures, &condition_captures);
|
||||
if replacement != "-" {
|
||||
let (replacement_path, replacement_query) = if let Some((target, query_part)) = replacement.split_once('?') { (target, Some(query_part.to_owned())) } else { (replacement.as_str(), None) };
|
||||
let target = if rule.redirect.is_some() && (replacement_path.starts_with("http://") || replacement_path.starts_with("https://")) { replacement_path.to_owned() } else { scoped_target(scope, replacement_path) };
|
||||
let (replacement_path, replacement_query) =
|
||||
if let Some((target, query_part)) = replacement.split_once('?') {
|
||||
(target, Some(query_part.to_owned()))
|
||||
} else {
|
||||
(replacement.as_str(), None)
|
||||
};
|
||||
let target = if rule.redirect.is_some()
|
||||
&& (replacement_path.starts_with("http://")
|
||||
|| replacement_path.starts_with("https://"))
|
||||
{
|
||||
replacement_path.to_owned()
|
||||
} else {
|
||||
scoped_target(scope, replacement_path)
|
||||
};
|
||||
let next_query = if rule.qsa {
|
||||
match (replacement_query, query.clone()) {
|
||||
(Some(new), Some(old)) if !new.is_empty() && !old.is_empty() => Some(format!("{new}&{old}")),
|
||||
(Some(new), Some(old)) if !new.is_empty() && !old.is_empty() => {
|
||||
Some(format!("{new}&{old}"))
|
||||
}
|
||||
(Some(new), _) => Some(new),
|
||||
(None, old) => old,
|
||||
}
|
||||
} else { replacement_query.or_else(|| query.clone()) };
|
||||
} else {
|
||||
replacement_query.or_else(|| query.clone())
|
||||
};
|
||||
if let Some(status) = rule.redirect {
|
||||
let mut location = target;
|
||||
if let Some(query) = next_query.filter(|q| !q.is_empty()) { location.push('?'); location.push_str(&query); }
|
||||
return Ok(RewriteOutcome::Redirect(redirect_response(status, &location)?));
|
||||
if let Some(query) = next_query.filter(|q| !q.is_empty()) {
|
||||
location.push('?');
|
||||
location.push_str(&query);
|
||||
}
|
||||
return Ok(RewriteOutcome::Redirect(redirect_response(
|
||||
status, &location,
|
||||
)?));
|
||||
}
|
||||
ensure!(
|
||||
target.starts_with('/'),
|
||||
".htaccess internal rewrite must stay on an absolute local path"
|
||||
);
|
||||
if target != path || next_query != query {
|
||||
changed = true;
|
||||
path = target;
|
||||
query = next_query;
|
||||
}
|
||||
ensure!(target.starts_with('/'), ".htaccess internal rewrite must stay on an absolute local path");
|
||||
if target != path || next_query != query { changed = true; path = target; query = next_query; }
|
||||
}
|
||||
if rule.end { end = true; break 'scope; }
|
||||
if rule.last { break 'scope; }
|
||||
if rule.end {
|
||||
end = true;
|
||||
break 'scope;
|
||||
}
|
||||
if rule.last {
|
||||
break 'scope;
|
||||
}
|
||||
}
|
||||
}
|
||||
if end || !changed { break; }
|
||||
if pass == 7 { exhausted = true; }
|
||||
if end || !changed {
|
||||
break;
|
||||
}
|
||||
if pass == 7 {
|
||||
exhausted = true;
|
||||
}
|
||||
}
|
||||
ensure!(!exhausted, ".htaccess rewrite exceeded the 8-pass safety limit");
|
||||
ensure!(
|
||||
!exhausted,
|
||||
".htaccess rewrite exceeded the 8-pass safety limit"
|
||||
);
|
||||
Ok(RewriteOutcome::Internal { path, query })
|
||||
}
|
||||
@@ -28,15 +28,15 @@ pub(crate) struct PhpMetrics {
|
||||
pub(crate) status_4xx: AtomicU64,
|
||||
pub(crate) status_5xx: AtomicU64,
|
||||
pub(crate) response_headers_us: AtomicU64,
|
||||
pub(crate) response_bytes: AtomicU64,
|
||||
pub(crate) response_bytes: AtomicU64,
|
||||
pub(crate) in_flight_headers: AtomicU64,
|
||||
pub(crate) static_requests: AtomicU64,
|
||||
pub(crate) php_requests: AtomicU64,
|
||||
pub(crate) other_requests: AtomicU64,
|
||||
pub(crate) methods: [AtomicU64; 5],
|
||||
pub(crate) selected_status: [AtomicU64; 8],
|
||||
pub(crate) methods: [AtomicU64; 5],
|
||||
pub(crate) selected_status: [AtomicU64; 8],
|
||||
pub(crate) failures: [AtomicU64; 9],
|
||||
pub(crate) compression: [AtomicU64; 4],
|
||||
pub(crate) compression: [AtomicU64; 4],
|
||||
}
|
||||
|
||||
pub(crate) struct HeadersInFlight<'a>(&'a AtomicU64);
|
||||
|
||||
@@ -10,7 +10,6 @@ pub struct RequestContext {
|
||||
pub version: Version,
|
||||
}
|
||||
|
||||
|
||||
pub(super) fn server_protocol(version: http::Version) -> &'static str {
|
||||
match version {
|
||||
http::Version::HTTP_09 => "HTTP/0.9",
|
||||
|
||||
@@ -161,13 +161,22 @@ async fn file_response_inner(
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
let sendfile_candidate = if service.sendfile == super::SendfileMode::Auto
|
||||
&& !multipart && single_range.is_none() && content_encoding.is_none()
|
||||
&& !multipart
|
||||
&& single_range.is_none()
|
||||
&& content_encoding.is_none()
|
||||
&& body_length >= 64 * 1024
|
||||
{
|
||||
opened.file.try_clone().ok().map(|file| crate::server::sendfile::SendfileCandidate {
|
||||
file: std::sync::Arc::new(file), length: body_length,
|
||||
})
|
||||
} else { None };
|
||||
opened
|
||||
.file
|
||||
.try_clone()
|
||||
.ok()
|
||||
.map(|file| crate::server::sendfile::SendfileCandidate {
|
||||
file: std::sync::Arc::new(file),
|
||||
length: body_length,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut file = tokio::fs::File::from_std(opened.file);
|
||||
if let Some(boundary) = boundary {
|
||||
let ranges = ranges.expect("multipart ranges");
|
||||
@@ -203,7 +212,8 @@ async fn file_response_inner(
|
||||
.await;
|
||||
});
|
||||
*response.body_mut() = Body::new(file_body::FileBody::new(
|
||||
ReaderStream::with_capacity(reader, stream_capacity), response_length,
|
||||
ReaderStream::with_capacity(reader, stream_capacity),
|
||||
response_length,
|
||||
));
|
||||
return response;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
use bytes::Bytes;
|
||||
use futures_util::Stream;
|
||||
use http_body::{Body, Frame, SizeHint};
|
||||
use std::{io, pin::Pin, task::{Context, Poll}};
|
||||
use std::{
|
||||
io,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
pub(super) struct FileBody<S> {
|
||||
stream: Option<S>,
|
||||
@@ -10,7 +14,10 @@ pub(super) struct FileBody<S> {
|
||||
|
||||
impl<S> FileBody<S> {
|
||||
pub(super) fn new(stream: S, length: u64) -> Self {
|
||||
Self { stream: (length != 0).then_some(stream), remaining: length }
|
||||
Self {
|
||||
stream: (length != 0).then_some(stream),
|
||||
remaining: length,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,14 +33,17 @@ where
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Frame<Bytes>, io::Error>>> {
|
||||
let this = self.get_mut();
|
||||
let Some(stream) = this.stream.as_mut() else { return Poll::Ready(None) };
|
||||
let Some(stream) = this.stream.as_mut() else {
|
||||
return Poll::Ready(None);
|
||||
};
|
||||
match Pin::new(stream).poll_next(cx) {
|
||||
Poll::Ready(Some(Ok(data))) => {
|
||||
if data.len() as u64 > this.remaining {
|
||||
this.stream = None;
|
||||
this.remaining = 0;
|
||||
return Poll::Ready(Some(Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData, "local file body exceeded its declared length",
|
||||
io::ErrorKind::InvalidData,
|
||||
"local file body exceeded its declared length",
|
||||
))));
|
||||
}
|
||||
this.remaining -= data.len() as u64;
|
||||
@@ -46,7 +56,8 @@ where
|
||||
this.stream = None;
|
||||
this.remaining = 0;
|
||||
Poll::Ready(Some(Err(io::Error::new(
|
||||
io::ErrorKind::UnexpectedEof, "local file body ended before its declared length",
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
"local file body ended before its declared length",
|
||||
))))
|
||||
}
|
||||
Poll::Ready(Some(Err(error))) => {
|
||||
@@ -58,9 +69,13 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn is_end_stream(&self) -> bool { self.stream.is_none() }
|
||||
fn is_end_stream(&self) -> bool {
|
||||
self.stream.is_none()
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> SizeHint { SizeHint::with_exact(self.remaining) }
|
||||
fn size_hint(&self) -> SizeHint {
|
||||
SizeHint::with_exact(self.remaining)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -17,30 +17,54 @@ async fn final_file_frame_is_terminal_without_an_extra_eof_poll() {
|
||||
let mut body = FileBody::new(ReaderStream::with_capacity(file.take(6), 3), 6);
|
||||
assert_eq!(body.size_hint().exact(), Some(6));
|
||||
assert!(!body.is_end_stream());
|
||||
assert_eq!(body.frame().await.unwrap().unwrap().into_data().unwrap(), "abc");
|
||||
assert_eq!(
|
||||
body.frame().await.unwrap().unwrap().into_data().unwrap(),
|
||||
"abc"
|
||||
);
|
||||
assert_eq!(body.size_hint().exact(), Some(3));
|
||||
assert!(!body.is_end_stream());
|
||||
assert_eq!(body.frame().await.unwrap().unwrap().into_data().unwrap(), "def");
|
||||
assert!(body.is_end_stream(), "the final data frame must end the body before another poll");
|
||||
assert_eq!(
|
||||
body.frame().await.unwrap().unwrap().into_data().unwrap(),
|
||||
"def"
|
||||
);
|
||||
assert!(
|
||||
body.is_end_stream(),
|
||||
"the final data frame must end the body before another poll"
|
||||
);
|
||||
assert_eq!(body.size_hint().exact(), Some(0));
|
||||
assert!(body.stream.is_none(), "the reader/file is released at the length boundary");
|
||||
assert!(
|
||||
body.stream.is_none(),
|
||||
"the reader/file is released at the length boundary"
|
||||
);
|
||||
assert!(body.frame().await.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn short_file_and_local_stream_errors_never_become_successful_eof() {
|
||||
let mut short = FileBody::new(stream::iter([Ok(Bytes::from_static(b"abc"))]), 6);
|
||||
assert_eq!(short.frame().await.unwrap().unwrap().into_data().unwrap(), "abc");
|
||||
assert_eq!(short.frame().await.unwrap().unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
|
||||
assert_eq!(
|
||||
short.frame().await.unwrap().unwrap().into_data().unwrap(),
|
||||
"abc"
|
||||
);
|
||||
assert_eq!(
|
||||
short.frame().await.unwrap().unwrap_err().kind(),
|
||||
io::ErrorKind::UnexpectedEof
|
||||
);
|
||||
assert!(short.is_end_stream());
|
||||
assert!(short.frame().await.is_none());
|
||||
|
||||
let mut failed = FileBody::new(stream::iter([Err(io::Error::other("read failed"))]), 6);
|
||||
assert_eq!(failed.frame().await.unwrap().unwrap_err().to_string(), "read failed");
|
||||
assert_eq!(
|
||||
failed.frame().await.unwrap().unwrap_err().to_string(),
|
||||
"read failed"
|
||||
);
|
||||
assert!(failed.is_end_stream());
|
||||
|
||||
let mut oversized = FileBody::new(stream::iter([Ok(Bytes::from_static(b"abcdef"))]), 3);
|
||||
assert_eq!(oversized.frame().await.unwrap().unwrap_err().kind(), io::ErrorKind::InvalidData);
|
||||
assert_eq!(
|
||||
oversized.frame().await.unwrap().unwrap_err().kind(),
|
||||
io::ErrorKind::InvalidData
|
||||
);
|
||||
assert!(oversized.is_end_stream());
|
||||
}
|
||||
|
||||
@@ -51,10 +75,24 @@ async fn file_shrunk_after_open_returns_unexpected_eof() {
|
||||
tokio::fs::write(&path, b"abcdef").await.unwrap();
|
||||
let file = tokio::fs::File::open(&path).await.unwrap();
|
||||
let expected = file.metadata().await.unwrap().len();
|
||||
std::fs::OpenOptions::new().write(true).open(path).unwrap().set_len(3).unwrap();
|
||||
let mut body = FileBody::new(ReaderStream::with_capacity(file.take(expected), 3), expected);
|
||||
assert_eq!(body.frame().await.unwrap().unwrap().into_data().unwrap(), "abc");
|
||||
assert_eq!(body.frame().await.unwrap().unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
|
||||
std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(path)
|
||||
.unwrap()
|
||||
.set_len(3)
|
||||
.unwrap();
|
||||
let mut body = FileBody::new(
|
||||
ReaderStream::with_capacity(file.take(expected), 3),
|
||||
expected,
|
||||
);
|
||||
assert_eq!(
|
||||
body.frame().await.unwrap().unwrap().into_data().unwrap(),
|
||||
"abc"
|
||||
);
|
||||
assert_eq!(
|
||||
body.frame().await.unwrap().unwrap_err().kind(),
|
||||
io::ErrorKind::UnexpectedEof
|
||||
);
|
||||
assert!(body.is_end_stream());
|
||||
assert!(body.stream.is_none());
|
||||
}
|
||||
@@ -67,12 +105,22 @@ async fn zero_length_file_is_terminal_without_polling_the_reader() {
|
||||
assert!(body.frame().await.is_none());
|
||||
}
|
||||
|
||||
fn settings() -> Settings { Settings { enabled: true, ..Default::default() } }
|
||||
fn settings() -> Settings {
|
||||
Settings {
|
||||
enabled: true,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn cacheable(body: AxumBody, length: u64) -> Response {
|
||||
let mut response = Response::new(body);
|
||||
response.headers_mut().insert("cache-control", HeaderValue::from_static("public, max-age=600"));
|
||||
response.headers_mut().insert("content-length", length.to_string().parse().unwrap());
|
||||
response.headers_mut().insert(
|
||||
"cache-control",
|
||||
HeaderValue::from_static("public, max-age=600"),
|
||||
);
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-length", length.to_string().parse().unwrap());
|
||||
response
|
||||
}
|
||||
|
||||
@@ -85,17 +133,33 @@ async fn fully_delivered_file_fills_cache_before_consumer_drops_without_polling_
|
||||
let body = FileBody::new(ReaderStream::with_capacity(file.take(6), 6), 6);
|
||||
let cache = Cache::new(1);
|
||||
let settings = settings();
|
||||
let ticket = cache.ticket(1, "http", "localhost", "site", "/file", &HeaderMap::new()).unwrap();
|
||||
let ticket = cache
|
||||
.ticket(1, "http", "localhost", "site", "/file", &HeaderMap::new())
|
||||
.unwrap();
|
||||
let response = cacheable(AxumBody::new(body), 6);
|
||||
let plan = cache::plan(StatusCode::OK, response.headers(), &settings, Duration::ZERO).unwrap();
|
||||
let mut body = cache.wrap(response, ticket.clone(), plan, &settings).into_body();
|
||||
assert_eq!(body.frame().await.unwrap().unwrap().into_data().unwrap(), "abcdef");
|
||||
let plan = cache::plan(
|
||||
StatusCode::OK,
|
||||
response.headers(),
|
||||
&settings,
|
||||
Duration::ZERO,
|
||||
)
|
||||
.unwrap();
|
||||
let mut body = cache
|
||||
.wrap(response, ticket.clone(), plan, &settings)
|
||||
.into_body();
|
||||
assert_eq!(
|
||||
body.frame().await.unwrap().unwrap().into_data().unwrap(),
|
||||
"abcdef"
|
||||
);
|
||||
drop(body);
|
||||
assert_eq!(cache.view().entries, 1);
|
||||
assert_eq!(cache.view().rejected_fills, 0);
|
||||
assert_eq!(cache.view().fills_active, 0);
|
||||
let hit = cache.get(&ticket).unwrap();
|
||||
assert_eq!(hit.response.into_body().collect().await.unwrap().to_bytes(), "abcdef");
|
||||
assert_eq!(
|
||||
hit.response.into_body().collect().await.unwrap().to_bytes(),
|
||||
"abcdef"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -103,14 +167,35 @@ async fn incomplete_or_cancelled_file_cannot_fill_cache() {
|
||||
for short in [false, true] {
|
||||
let cache = Cache::new(1);
|
||||
let settings = settings();
|
||||
let ticket = cache.ticket(1, "http", "localhost", "site", "/file", &HeaderMap::new()).unwrap();
|
||||
let chunks = if short { vec![Ok(Bytes::from_static(b"abc"))] }
|
||||
else { vec![Ok(Bytes::from_static(b"abc")), Ok(Bytes::from_static(b"def"))] };
|
||||
let ticket = cache
|
||||
.ticket(1, "http", "localhost", "site", "/file", &HeaderMap::new())
|
||||
.unwrap();
|
||||
let chunks = if short {
|
||||
vec![Ok(Bytes::from_static(b"abc"))]
|
||||
} else {
|
||||
vec![
|
||||
Ok(Bytes::from_static(b"abc")),
|
||||
Ok(Bytes::from_static(b"def")),
|
||||
]
|
||||
};
|
||||
let response = cacheable(AxumBody::new(FileBody::new(stream::iter(chunks), 6)), 6);
|
||||
let plan = cache::plan(StatusCode::OK, response.headers(), &settings, Duration::ZERO).unwrap();
|
||||
let mut body = cache.wrap(response, ticket.clone(), plan, &settings).into_body();
|
||||
assert_eq!(body.frame().await.unwrap().unwrap().into_data().unwrap(), "abc");
|
||||
if short { assert!(body.frame().await.unwrap().is_err()); }
|
||||
let plan = cache::plan(
|
||||
StatusCode::OK,
|
||||
response.headers(),
|
||||
&settings,
|
||||
Duration::ZERO,
|
||||
)
|
||||
.unwrap();
|
||||
let mut body = cache
|
||||
.wrap(response, ticket.clone(), plan, &settings)
|
||||
.into_body();
|
||||
assert_eq!(
|
||||
body.frame().await.unwrap().unwrap().into_data().unwrap(),
|
||||
"abc"
|
||||
);
|
||||
if short {
|
||||
assert!(body.frame().await.unwrap().is_err());
|
||||
}
|
||||
drop(body);
|
||||
assert!(cache.get(&ticket).is_none());
|
||||
assert_eq!(cache.view().rejected_fills, 1);
|
||||
|
||||
@@ -8,7 +8,10 @@ use axum::{body::Body, response::Response};
|
||||
use http::{header::LOCATION, HeaderMap, HeaderValue, StatusCode};
|
||||
use std::io;
|
||||
|
||||
pub(super) async fn open_components(service: &CompiledService, components: Vec<String>) -> io::Result<Opened> {
|
||||
pub(super) async fn open_components(
|
||||
service: &CompiledService,
|
||||
components: Vec<String>,
|
||||
) -> io::Result<Opened> {
|
||||
let root = FilesystemRoot::for_service(service);
|
||||
tokio::task::spawn_blocking(move || secure_open_sync(&root, &components))
|
||||
.await
|
||||
@@ -28,7 +31,10 @@ fn target_path_and_query(
|
||||
Some((path, query)) => (path.to_owned(), Some(query.to_owned())),
|
||||
None => (expanded, query.map(str::to_owned)),
|
||||
};
|
||||
ensure!(path.starts_with('/'), "Web Server internal target must start with /");
|
||||
ensure!(
|
||||
path.starts_with('/'),
|
||||
"Web Server internal target must start with /"
|
||||
);
|
||||
crate::acl::validate_decoded_routing_path(&path)
|
||||
.map_err(|_| anyhow::anyhow!("invalid Web Server internal target"))?;
|
||||
Ok((path, query))
|
||||
@@ -54,11 +60,7 @@ pub(super) fn apply_rewrites(
|
||||
.pattern
|
||||
.replace(&path, rule.replacement.as_str())
|
||||
.to_string();
|
||||
let (next_path, next_query) = target_path_and_query(
|
||||
&replacement,
|
||||
&path,
|
||||
query.as_deref(),
|
||||
)?;
|
||||
let (next_path, next_query) = target_path_and_query(&replacement, &path, query.as_deref())?;
|
||||
if let Some(status) = rule.status {
|
||||
let mut target = next_path;
|
||||
if let Some(query) = next_query.filter(|value| !value.is_empty()) {
|
||||
@@ -142,7 +144,9 @@ pub(super) async fn select_precompressed(
|
||||
continue;
|
||||
}
|
||||
let mut sidecar = components.to_vec();
|
||||
let Some(last) = sidecar.last_mut() else { continue };
|
||||
let Some(last) = sidecar.last_mut() else {
|
||||
continue;
|
||||
};
|
||||
last.push_str(suffix);
|
||||
if let Ok(opened) = open_components(service, sidecar).await {
|
||||
if opened.metadata.is_file() {
|
||||
@@ -152,4 +156,3 @@ pub(super) async fn select_precompressed(
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
@@ -35,8 +35,8 @@ pub(super) fn hardening_denied_path(service: &CompiledService, path: &str) -> bo
|
||||
"id_ed25519",
|
||||
];
|
||||
let backup_suffixes = [
|
||||
".bak", ".backup", ".old", ".orig", ".save", ".swp", ".swo", ".sql",
|
||||
".sqlite", ".sqlite3", ".db",
|
||||
".bak", ".backup", ".old", ".orig", ".save", ".swp", ".swo", ".sql", ".sqlite", ".sqlite3",
|
||||
".db",
|
||||
];
|
||||
path_components(path).ok().is_some_and(|components| {
|
||||
components.iter().any(|component| {
|
||||
@@ -46,14 +46,18 @@ pub(super) fn hardening_denied_path(service: &CompiledService, path: &str) -> bo
|
||||
|| component.starts_with(".env.")
|
||||
|| sensitive_names.contains(&component.as_str())
|
||||
|| component.ends_with('~')
|
||||
|| backup_suffixes.iter().any(|suffix| component.ends_with(*suffix))
|
||||
|| backup_suffixes
|
||||
.iter()
|
||||
.any(|suffix| component.ends_with(*suffix))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn hardening_denied_method(service: &CompiledService, method: &Method) -> bool {
|
||||
service.hardening.block_common_attacks
|
||||
&& (method == Method::CONNECT || method == Method::TRACE || method.as_str().eq_ignore_ascii_case("TRACK"))
|
||||
&& (method == Method::CONNECT
|
||||
|| method == Method::TRACE
|
||||
|| method.as_str().eq_ignore_ascii_case("TRACK"))
|
||||
}
|
||||
|
||||
pub(super) fn strip_unnecessary_headers(response: &mut Response, service: &CompiledService) {
|
||||
@@ -73,4 +77,3 @@ pub(super) fn strip_unnecessary_headers(response: &mut Response, service: &Compi
|
||||
response.headers_mut().remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
+32
-9
@@ -122,7 +122,13 @@ async fn missing_files_and_disabled_directory_listing_return_normal_errors() {
|
||||
assert_eq!(missing.headers()[CONTENT_TYPE], "text/html; charset=utf-8");
|
||||
assert_eq!(missing.headers()["x-content-type-options"], "nosniff");
|
||||
assert_eq!(
|
||||
missing.into_body().collect().await.unwrap().to_bytes().as_ref(),
|
||||
missing
|
||||
.into_body()
|
||||
.collect()
|
||||
.await
|
||||
.unwrap()
|
||||
.to_bytes()
|
||||
.as_ref(),
|
||||
crate::pages::builtin_gateway_error(StatusCode::NOT_FOUND)
|
||||
.unwrap()
|
||||
.as_bytes()
|
||||
@@ -210,7 +216,9 @@ async fn internal_filesystem_diagnostics_never_appear_in_public_error_responses(
|
||||
.unwrap()
|
||||
.as_bytes()
|
||||
);
|
||||
assert!(!body.windows(b"RustProxy:".len()).any(|w| w == b"RustProxy:"));
|
||||
assert!(!body
|
||||
.windows(b"RustProxy:".len())
|
||||
.any(|w| w == b"RustProxy:"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,7 +230,13 @@ async fn web_server_validation_and_unmapped_error_statuses_are_styled() {
|
||||
assert_eq!(invalid.status(), StatusCode::BAD_REQUEST);
|
||||
assert_eq!(invalid.headers()[CONTENT_TYPE], "text/html; charset=utf-8");
|
||||
assert_eq!(
|
||||
invalid.into_body().collect().await.unwrap().to_bytes().as_ref(),
|
||||
invalid
|
||||
.into_body()
|
||||
.collect()
|
||||
.await
|
||||
.unwrap()
|
||||
.to_bytes()
|
||||
.as_ref(),
|
||||
crate::pages::builtin_gateway_error(StatusCode::BAD_REQUEST)
|
||||
.unwrap()
|
||||
.as_bytes()
|
||||
@@ -255,7 +269,10 @@ async fn web_server_validation_and_unmapped_error_statuses_are_styled() {
|
||||
assert_eq!(fallback.status(), StatusCode::IM_A_TEAPOT);
|
||||
assert_eq!(fallback.headers()[CONTENT_TYPE], "text/html; charset=utf-8");
|
||||
assert_eq!(fallback.headers()[CACHE_CONTROL], "no-store");
|
||||
assert!(fallback.extensions().get::<crate::pages::PageServed>().is_none());
|
||||
assert!(fallback
|
||||
.extensions()
|
||||
.get::<crate::pages::PageServed>()
|
||||
.is_none());
|
||||
let fallback_html = fallback.into_body().collect().await.unwrap().to_bytes();
|
||||
let fallback_html = std::str::from_utf8(&fallback_html).unwrap();
|
||||
assert!(fallback_html.contains("<h1>418 -"));
|
||||
@@ -272,7 +289,13 @@ async fn web_server_validation_and_unmapped_error_statuses_are_styled() {
|
||||
head.headers()[CONTENT_LENGTH],
|
||||
HeaderValue::from_str(&fallback_html.len().to_string()).unwrap()
|
||||
);
|
||||
assert!(head.into_body().collect().await.unwrap().to_bytes().is_empty());
|
||||
assert!(head
|
||||
.into_body()
|
||||
.collect()
|
||||
.await
|
||||
.unwrap()
|
||||
.to_bytes()
|
||||
.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1831,10 +1854,10 @@ async fn web_metrics_count_handler_status_method_and_consumed_body_bytes() {
|
||||
assert_eq!(view["status_4xx"], 1);
|
||||
assert_eq!(view["static_requests"], 2);
|
||||
assert_eq!(view["other_requests"], 1);
|
||||
assert_eq!(view["methods"][0], 2);
|
||||
assert_eq!(view["methods"][4], 1);
|
||||
assert_eq!(view["selected_status"][0], 2);
|
||||
assert_eq!(view["selected_status"][4], 1);
|
||||
assert_eq!(view["methods"][0], 2);
|
||||
assert_eq!(view["methods"][4], 1);
|
||||
assert_eq!(view["selected_status"][0], 2);
|
||||
assert_eq!(view["selected_status"][4], 1);
|
||||
assert_eq!(view["response_bytes"], 5 + missing_bytes as u64);
|
||||
assert_eq!(view["active_headers"], 0);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user