v0.42.2_fix2
This commit is contained in:
1 parent
15c7f9ff9e
commit
25148f26eb
14 files changed
+407
-54
No files matched your search
@@ -367,8 +367,16 @@ impl Service {
|
||||
self.id
|
||||
)
|
||||
})?);
|
||||
let htaccess = htaccess::compile(&root, &self.htaccess)?;
|
||||
if let Some(compiled) = &htaccess {
|
||||
let mut htaccess = htaccess::compile(&root, &self.htaccess)?;
|
||||
if let Some(compiled) = &mut htaccess {
|
||||
if htaccess::rewrites_to_php(Some(compiled))
|
||||
&& (!self.php.enabled || !self.php.extensions.iter().any(|extension| extension == "php"))
|
||||
{
|
||||
compiled.warnings.push(format!(
|
||||
"Web Service {}: .htaccess rewrites to a .php script, but FastCGI handling for .php is disabled; configure a PHP-FPM/FastCGI endpoint and the php extension before expecting the route to work",
|
||||
self.id
|
||||
));
|
||||
}
|
||||
ensure!(
|
||||
(self.php.enabled && self.php.handler == FastCgiHandler::PhpFpm)
|
||||
|| !htaccess::adds_php_extensions(Some(compiled)),
|
||||
@@ -454,7 +462,18 @@ impl Service {
|
||||
name: self.name.clone(),
|
||||
sendfile: self.sendfile,
|
||||
root,
|
||||
index: self.index.clone(),
|
||||
// Keep explicit index priorities unchanged. For the stock static
|
||||
// default, PHP-capable services also try index.php when the HTML
|
||||
// indexes are absent, matching common PHP application installs.
|
||||
index: {
|
||||
let mut index = self.index.clone();
|
||||
if self.php.enabled && self.php.handler == FastCgiHandler::PhpFpm
|
||||
&& self.php.extensions.iter().any(|extension| extension == "php")
|
||||
&& index == default_index() {
|
||||
index.push("index.php".to_owned());
|
||||
}
|
||||
index
|
||||
},
|
||||
directory_listing: self.directory_listing,
|
||||
mime_types: self
|
||||
.mime_types
|
||||
|
||||
@@ -90,6 +90,9 @@ struct Scope {
|
||||
components: Vec<String>,
|
||||
rewrites: Vec<RewriteRule>,
|
||||
redirects: Vec<SimpleRedirect>,
|
||||
rewrite_base: Option<String>,
|
||||
accept_path_info: Option<AcceptPathInfoMode>,
|
||||
error_documents: BTreeMap<u16, String>,
|
||||
directory_index: Option<Vec<String>>,
|
||||
directory_listing: Option<bool>,
|
||||
mime_types: BTreeMap<String, HeaderValue>,
|
||||
@@ -103,6 +106,14 @@ struct Scope {
|
||||
file_rules: Vec<FileAccessRule>,
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum AcceptPathInfoMode {
|
||||
On,
|
||||
Off,
|
||||
Default,
|
||||
}
|
||||
|
||||
// Apache Files / FilesMatch rules apply to filenames below their directory.
|
||||
// Only bounded access-control directives are accepted inside these blocks.
|
||||
#[derive(Debug, Clone)]
|
||||
|
||||
@@ -165,6 +165,42 @@ fn parse_file(path: &Path, components: Vec<String>, config: &Config) -> Result<(
|
||||
if !state.rewrite_engine { state.pending_conditions.clear(); state.skip_next_rule = false; }
|
||||
}
|
||||
"rewritebase" => {
|
||||
ensure!(parts.len() == 2, "{}:{line_no}: RewriteBase expects one absolute URL prefix", path.display());
|
||||
let base = &parts[1];
|
||||
ensure!(base.starts_with('/') && !base.starts_with("//")
|
||||
&& !base.contains('\\') && !base.contains('?') && !base.contains('#')
|
||||
&& !base.chars().any(char::is_control),
|
||||
"{}:{line_no}: RewriteBase must be a safe absolute URL path", path.display());
|
||||
crate::acl::validate_decoded_routing_path(base)
|
||||
.map_err(|_| anyhow::anyhow!("{}:{line_no}: invalid RewriteBase path", path.display()))?;
|
||||
scope.rewrite_base = Some(if base.ends_with('/') { base.to_owned() } else { format!("{base}/") });
|
||||
}
|
||||
"acceptpathinfo" => {
|
||||
ensure!(parts.len() == 2, "{}:{line_no}: AcceptPathInfo expects On, Off or Default", path.display());
|
||||
scope.accept_path_info = if parts[1].eq_ignore_ascii_case("on") {
|
||||
Some(AcceptPathInfoMode::On)
|
||||
} else if parts[1].eq_ignore_ascii_case("off") {
|
||||
Some(AcceptPathInfoMode::Off)
|
||||
} else if parts[1].eq_ignore_ascii_case("default") {
|
||||
Some(AcceptPathInfoMode::Default)
|
||||
} else {
|
||||
bail!("{}:{line_no}: AcceptPathInfo expects On, Off or Default", path.display());
|
||||
};
|
||||
}
|
||||
"errordocument" => {
|
||||
ensure!(parts.len() == 3, "{}:{line_no}: ErrorDocument expects an HTTP error status and a local URL", path.display());
|
||||
let status: u16 = parts[1].parse().context("ErrorDocument status must be numeric")?;
|
||||
ensure!((400..600).contains(&status), "{}:{line_no}: ErrorDocument status must be 400..599", path.display());
|
||||
let target = &parts[2];
|
||||
ensure!(target.len() <= 1024 && target.starts_with('/') && !target.starts_with("//")
|
||||
&& !target.contains('\\') && !target.contains('#')
|
||||
&& !target.chars().any(char::is_control),
|
||||
"{}:{line_no}: ErrorDocument requires a safe local URL, not an external redirect or literal response", path.display());
|
||||
let path_only = target.split('?').next().unwrap_or_default();
|
||||
crate::acl::validate_decoded_routing_path(path_only)
|
||||
.map_err(|_| anyhow::anyhow!("{}:{line_no}: invalid ErrorDocument URL path", path.display()))?;
|
||||
target.parse::<Uri>().context("invalid ErrorDocument URL")?;
|
||||
scope.error_documents.insert(status, target.to_owned());
|
||||
}
|
||||
"rewritecond" if state.rewrite_engine => {
|
||||
condition_count += 1;
|
||||
@@ -269,7 +305,7 @@ fn parse_file(path: &Path, components: Vec<String>, config: &Config) -> Result<(
|
||||
scope.redirects.push(redirect_rule(&parts, directive == "redirectmatch")
|
||||
.with_context(|| format!("{}:{line_no}", path.display()))?);
|
||||
}
|
||||
"errordocument" | "setenvif" | "fallbackresource" => {
|
||||
"setenvif" | "fallbackresource" => {
|
||||
unsupported(&mut state, config, path, line_no, format!("directive {} is not in the RustProxy compatibility subset", parts[0]))?;
|
||||
}
|
||||
_ => unsupported(&mut state, config, path, line_no, format!("unsupported directive {}", parts[0]))?,
|
||||
@@ -335,6 +371,12 @@ pub fn adds_php_extensions(compiled: Option<&Compiled>) -> bool {
|
||||
compiled.is_some_and(|compiled| compiled.scopes.iter().any(|scope| !scope.php_extensions.is_empty()))
|
||||
}
|
||||
|
||||
pub fn rewrites_to_php(compiled: Option<&Compiled>) -> bool {
|
||||
compiled.is_some_and(|compiled| compiled.scopes.iter().any(|scope| {
|
||||
scope.rewrites.iter().any(|rule| rule.replacement.to_ascii_lowercase().contains(".php"))
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn protected_component(compiled: Option<&Compiled>, value: &str) -> bool {
|
||||
let lower = value.to_ascii_lowercase();
|
||||
if lower == ".htaccess" || lower == ".htpasswd" || lower.starts_with(".ht") { return true; }
|
||||
@@ -379,6 +421,25 @@ pub fn index_files<'a>(compiled: Option<&'a Compiled>, directory_components: &[S
|
||||
compiled.scopes.iter().filter(|scope| scope_matches(scope, directory_components)).filter_map(|scope| scope.directory_index.as_deref()).next_back().unwrap_or(fallback)
|
||||
}
|
||||
|
||||
pub fn accept_path_info(compiled: Option<&Compiled>, script_path: &str, fallback: bool) -> bool {
|
||||
match compiled.and_then(|compiled| matching_scopes(compiled, script_path).into_iter()
|
||||
.filter_map(|scope| scope.accept_path_info).last()) {
|
||||
Some(AcceptPathInfoMode::On) => true,
|
||||
Some(AcceptPathInfoMode::Off) => false,
|
||||
Some(AcceptPathInfoMode::Default) | None => fallback,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_error_documents(compiled: Option<&Compiled>) -> bool {
|
||||
compiled.is_some_and(|compiled| compiled.scopes.iter().any(|scope| !scope.error_documents.is_empty()))
|
||||
}
|
||||
|
||||
pub fn error_document<'a>(compiled: Option<&'a Compiled>, path: &str, status: StatusCode) -> Option<&'a str> {
|
||||
compiled?.scopes.iter().filter(|scope| {
|
||||
path_components(path).ok().is_some_and(|parts| scope_matches(scope, &parts))
|
||||
}).filter_map(|scope| scope.error_documents.get(&status.as_u16()).map(String::as_str)).last()
|
||||
}
|
||||
|
||||
pub fn directory_listing(compiled: Option<&Compiled>, directory_components: &[String], fallback: bool) -> bool {
|
||||
let Some(compiled) = compiled else { return fallback; };
|
||||
compiled.scopes.iter().filter(|scope| scope_matches(scope, directory_components)).filter_map(|scope| scope.directory_listing).next_back().unwrap_or(fallback)
|
||||
@@ -535,6 +596,7 @@ fn replacement_with_captures(rule: &RewriteRule, captures: ®ex::Captures<'_>,
|
||||
|
||||
fn scoped_target(scope: &Scope, replacement: &str) -> String {
|
||||
if replacement.starts_with('/') { return replacement.to_owned(); }
|
||||
if let Some(base) = &scope.rewrite_base { return format!("{base}{replacement}"); }
|
||||
if scope.components.is_empty() { format!("/{replacement}") } else if replacement.is_empty() { format!("/{}/", scope.components.join("/")) } else { format!("/{}/{}", scope.components.join("/"), replacement) }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use http::Version;
|
||||
use std::net::IpAddr;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RequestContext {
|
||||
pub client_ip: IpAddr,
|
||||
pub client_port: Option<u16>,
|
||||
|
||||
+62
-10
@@ -26,13 +26,18 @@ use std::{io, path::PathBuf};
|
||||
async fn resolve_script_path_info(
|
||||
service: &CompiledService,
|
||||
components: &[String],
|
||||
requested_path: &str,
|
||||
) -> Option<(String, String)> {
|
||||
let php = service.php.as_ref().filter(|php| php.path_info)?;
|
||||
if components.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
for script_end in 0..components.len() - 1 {
|
||||
let php = service.php.as_ref()?;
|
||||
for script_end in 0..components.len() {
|
||||
let script_path = format!("/{}", components[..=script_end].join("/"));
|
||||
// Preserve the exact suffix, including its final slash. Apache
|
||||
// front controllers depend on PATH_INFO retaining that slash.
|
||||
let Some(path_info) = requested_path.strip_prefix(&script_path)
|
||||
.filter(|suffix| suffix.starts_with('/')) else { continue; };
|
||||
if !htaccess::accept_path_info(service.htaccess.as_ref(), &script_path, php.path_info) {
|
||||
continue;
|
||||
}
|
||||
if !php.extensions.iter().any(|extension| {
|
||||
PathBuf::from(&script_path)
|
||||
.extension()
|
||||
@@ -43,8 +48,7 @@ async fn resolve_script_path_info(
|
||||
}
|
||||
match open_components(service, components[..=script_end].to_vec()).await {
|
||||
Ok(opened) if opened.metadata.is_file() => {
|
||||
let path_info = format!("/{}", components[script_end + 1..].join("/"));
|
||||
return Some((script_path, path_info));
|
||||
return Some((script_path, path_info.to_owned()));
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
@@ -113,7 +117,9 @@ async fn serve_inner(
|
||||
return builtin_error_response(status, &method)
|
||||
}
|
||||
Ok(htaccess::RewriteOutcome::Internal { path, query }) => (path, query),
|
||||
Err(_) => {
|
||||
Err(error) => {
|
||||
tracing::warn!(service = %service.id, path = %path, error = %error,
|
||||
".htaccess rewrite rejected Web Service request");
|
||||
return status_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"RustProxy: invalid .htaccess rewrite target\n",
|
||||
@@ -134,7 +140,7 @@ async fn serve_inner(
|
||||
return builtin_error_response(StatusCode::FORBIDDEN, &method);
|
||||
}
|
||||
if let Ok(components) = path_components(&rewritten_path) {
|
||||
if let Some((script_path, path_info)) = resolve_script_path_info(service, &components).await {
|
||||
if let Some((script_path, path_info)) = resolve_script_path_info(service, &components, &rewritten_path).await {
|
||||
let script_components = path_components(&script_path).unwrap_or_default();
|
||||
if hardening_denied_path(service, &script_path)
|
||||
|| script_components.iter().any(|component| {
|
||||
@@ -196,7 +202,7 @@ async fn serve_inner(
|
||||
) =>
|
||||
{
|
||||
if let Some((script_path, path_info)) =
|
||||
resolve_script_path_info(service, &components).await
|
||||
resolve_script_path_info(service, &components, &effective_path).await
|
||||
{
|
||||
let script_components = path_components(&script_path).unwrap_or_default();
|
||||
if hardening_denied_path(service, &script_path)
|
||||
@@ -416,12 +422,58 @@ pub async fn serve(
|
||||
let _in_flight =
|
||||
crate::web_server::metrics::HeadersInFlight::new(&service.web_metrics.in_flight_headers);
|
||||
let request_method = method.clone();
|
||||
// Copy request metadata only for services that actually have local error
|
||||
// documents. Normal requests without that feature avoid header cloning.
|
||||
let error_request = ((request_method == Method::GET || request_method == Method::HEAD)
|
||||
&& htaccess::has_error_documents(service.htaccess.as_ref()))
|
||||
.then(|| (headers.clone(), context.clone()));
|
||||
let mut response = serve_inner(service, method, headers, uri, path, body, context).await;
|
||||
let original_status = response.status();
|
||||
let mut used_local_error_document = false;
|
||||
// Only replace server-generated errors. FastCGI applications may already
|
||||
// provide their own error body; do not open a second FastCGI request while
|
||||
// the first one's streamed response could still hold a backend permit.
|
||||
if (original_status.is_client_error() || original_status.is_server_error())
|
||||
&& !matches!(response.extensions().get::<crate::web_server::metrics::ResponseKind>(),
|
||||
Some(crate::web_server::metrics::ResponseKind::Php))
|
||||
{
|
||||
if let Some((mut error_headers, replacement_context)) = error_request {
|
||||
if let Some(target) = htaccess::error_document(service.htaccess.as_ref(), path, original_status) {
|
||||
let target_path = target.split('?').next().unwrap_or_default();
|
||||
if target_path != path {
|
||||
if let Ok(target_uri) = target.parse::<Uri>() {
|
||||
// Serve the full error document, never a Range or 304
|
||||
// response produced from the original request headers.
|
||||
for name in [
|
||||
http::header::RANGE, http::header::IF_RANGE,
|
||||
http::header::IF_MODIFIED_SINCE, http::header::IF_NONE_MATCH,
|
||||
http::header::IF_MATCH, http::header::IF_UNMODIFIED_SINCE,
|
||||
] { error_headers.remove(name); }
|
||||
let replacement = serve_inner(
|
||||
service, request_method.clone(), error_headers, target_uri,
|
||||
target_path, Body::empty(), replacement_context,
|
||||
).await;
|
||||
if replacement.status() == StatusCode::OK {
|
||||
response = replacement;
|
||||
used_local_error_document = true;
|
||||
*response.status_mut() = original_status;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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);
|
||||
if used_local_error_document {
|
||||
// A local ErrorDocument is still an error response, even if the page's
|
||||
// normal Cache-Control or Expires rules say that successful pages are public.
|
||||
response.headers_mut().insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||
response.headers_mut().remove(http::header::EXPIRES);
|
||||
}
|
||||
strip_unnecessary_headers(&mut response, service);
|
||||
let kind = response
|
||||
.extensions()
|
||||
|
||||
+197
-6
@@ -1146,7 +1146,7 @@ async fn htaccess_legacy_deny_from_all_is_enforced_even_in_non_strict_mode() {
|
||||
};
|
||||
configured.validate().unwrap();
|
||||
let service = configured.compile().unwrap();
|
||||
assert_eq!(service.htaccess.as_ref().unwrap().warnings.len(), 2);
|
||||
assert_eq!(service.htaccess.as_ref().unwrap().warnings.len(), 1);
|
||||
assert_eq!(serve_request(&service, &request(Method::GET, "/index.html"), "/index.html").await.status(), StatusCode::OK);
|
||||
assert_eq!(serve_request(&service, &request(Method::GET, "/private/secret.txt"), "/private/secret.txt").await.status(), StatusCode::FORBIDDEN);
|
||||
}
|
||||
@@ -1189,7 +1189,7 @@ fn htaccess_strict_mode_rejects_unsupported_directives() {
|
||||
std::fs::write(tmp.path().join("index.html"), b"ok").unwrap();
|
||||
std::fs::write(
|
||||
tmp.path().join(".htaccess"),
|
||||
b"ErrorDocument 404 /404.html\n",
|
||||
b"SetEnvIf Request_URI ^/legacy legacy=1\n",
|
||||
)
|
||||
.unwrap();
|
||||
let mut configured = Service {
|
||||
@@ -1208,7 +1208,7 @@ fn htaccess_strict_mode_rejects_unsupported_directives() {
|
||||
.compile()
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("ErrorDocument"));
|
||||
.contains("SetEnvIf"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -2677,7 +2677,7 @@ ErrorDocument 404 /error.html
|
||||
config.validate().unwrap();
|
||||
let service = config.compile().unwrap();
|
||||
let (_, warnings) = service.htaccess_diagnostics().unwrap();
|
||||
assert_eq!(warnings.len(), 1); // ErrorDocument ignored in non-strict mode.
|
||||
assert!(warnings.is_empty(), "local ErrorDocument is supported: {warnings:?}");
|
||||
let redirect = serve_request(&service, &request(Method::GET, "/old/docs?a=1"), "/old/docs").await;
|
||||
assert_eq!(redirect.status(), StatusCode::MOVED_PERMANENTLY);
|
||||
assert_eq!(redirect.headers()[LOCATION], "/new/docs?a=1");
|
||||
@@ -2743,7 +2743,198 @@ AcceptPathInfo On
|
||||
};
|
||||
let service = config.compile().unwrap();
|
||||
let (_, warnings) = service.htaccess_diagnostics().unwrap();
|
||||
assert!(warnings.iter().any(|warning| warning.contains("ErrorDocument")));
|
||||
assert!(warnings.iter().any(|warning| warning.contains("AcceptPathInfo")));
|
||||
assert_eq!(warnings.len(), 3, "expected unsupported Options and missing PHP handler: {warnings:?}");
|
||||
assert_eq!(warnings.iter().filter(|warning| warning.contains("Options")).count(), 2);
|
||||
assert!(warnings.iter().any(|warning| warning.contains("FastCGI handling for .php is disabled")));
|
||||
assert!(!warnings.iter().any(|warning| warning.contains("RedirectMatch")));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn htaccess_observium_style_front_controller_executes_php_path_info_without_global_switch() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::write(tmp.path().join("index.php"), b"<?php // index").unwrap();
|
||||
std::fs::write(tmp.path().join("error.php"), b"<?php // errors").unwrap();
|
||||
std::fs::write(tmp.path().join("site.css"), b"static-css").unwrap();
|
||||
std::fs::write(tmp.path().join(".htaccess"), br#"# Original, representative application .htaccess
|
||||
Options FollowSymlinks Multiviews
|
||||
ErrorDocument 404 /error.php?404
|
||||
RedirectMatch 404 /\.
|
||||
RewriteEngine On
|
||||
RewriteBase /
|
||||
RewriteRule ^\..*$ - [F,L]
|
||||
RewriteCond %{REQUEST_FILENAME} !^favicon\.ico
|
||||
RewriteCond %{REQUEST_FILENAME} !-f
|
||||
RewriteCond %{REQUEST_FILENAME} !-d
|
||||
RewriteCond %{REQUEST_URI} !\.(js|ico|txt|gif|jpg|png|css|php)
|
||||
RewriteCond %{REQUEST_URI} !^api/
|
||||
RewriteCond %{REQUEST_URI} !^rrd/
|
||||
RewriteCond %{REQUEST_URI} !=/server-status
|
||||
RewriteRule ^(.*)$ index.php/$1/
|
||||
AcceptPathInfo On
|
||||
"#).unwrap();
|
||||
|
||||
let (endpoint, received) = fastcgi_fixture_record_params().await;
|
||||
let mut configured = Service {
|
||||
id: "front-controller-php-pathinfo".into(),
|
||||
name: "Generic PHP application".into(),
|
||||
document_root: tmp.path().to_path_buf(),
|
||||
htaccess: htaccess::Config { enabled: true, strict: false, ..Default::default() },
|
||||
php: Php { enabled: true, path_info: false, endpoint: format!("tcp:{endpoint}"), ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
configured.validate().unwrap();
|
||||
let service = configured.compile().unwrap();
|
||||
let warnings = &service.htaccess.as_ref().unwrap().warnings;
|
||||
assert_eq!(warnings.len(), 2, "expected only FollowSymlinks and MultiViews warnings: {warnings:?}");
|
||||
assert!(warnings.iter().all(|warning| warning.contains("Options")), "{warnings:?}");
|
||||
|
||||
let static_response = serve_request(&service, &request(Method::GET, "/site.css"), "/site.css").await;
|
||||
assert_eq!(static_response.status(), StatusCode::OK);
|
||||
assert_eq!(static_response.into_body().collect().await.unwrap().to_bytes(), "static-css");
|
||||
|
||||
let response = serve_request(&service, &request(Method::GET, "/devices/42?debug=1"), "/devices/42").await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let params = received.await.unwrap();
|
||||
assert_eq!(params["SCRIPT_FILENAME"], tmp.path().join("index.php").to_string_lossy());
|
||||
assert_eq!(params["SCRIPT_NAME"], "/index.php");
|
||||
assert_eq!(params["PATH_INFO"], "/devices/42/");
|
||||
assert_eq!(params["REQUEST_URI"], "/devices/42?debug=1");
|
||||
assert_eq!(params["QUERY_STRING"], "debug=1");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn htaccess_php_root_defaults_to_index_php_when_no_html_index_exists() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::write(tmp.path().join("index.php"), b"<?php // app").unwrap();
|
||||
std::fs::write(tmp.path().join(".htaccess"), b"RewriteEngine On\nAcceptPathInfo On\n").unwrap();
|
||||
let (endpoint, received) = fastcgi_fixture_record_params().await;
|
||||
let mut configured = Service {
|
||||
id: "php-root-default-index".into(),
|
||||
name: "PHP root".into(),
|
||||
document_root: tmp.path().to_path_buf(),
|
||||
htaccess: htaccess::Config { enabled: true, strict: true, ..Default::default() },
|
||||
php: Php { enabled: true, endpoint: format!("tcp:{endpoint}"), ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
configured.validate().unwrap();
|
||||
let service = configured.compile().unwrap();
|
||||
let response = serve_request(&service, &request(Method::GET, "/"), "/").await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let params = received.await.unwrap();
|
||||
assert_eq!(params["SCRIPT_NAME"], "/index.php");
|
||||
assert!(!params.contains_key("PATH_INFO"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn htaccess_accept_path_info_off_overrides_enabled_php_path_info() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::write(tmp.path().join("index.php"), b"<?php // app").unwrap();
|
||||
std::fs::write(tmp.path().join(".htaccess"), b"AcceptPathInfo Off\n").unwrap();
|
||||
let mut configured = Service {
|
||||
id: "pathinfo-overridden".into(),
|
||||
name: "Reject path info".into(),
|
||||
document_root: tmp.path().to_path_buf(),
|
||||
htaccess: htaccess::Config { enabled: true, strict: true, ..Default::default() },
|
||||
php: Php { enabled: true, path_info: true, endpoint: "tcp:127.0.0.1:9000".into(), ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
configured.validate().unwrap();
|
||||
let service = configured.compile().unwrap();
|
||||
assert!(!htaccess::accept_path_info(service.htaccess.as_ref(), "/index.php", true));
|
||||
let response = serve_request(&service, &request(Method::GET, "/index.php/abc"), "/index.php/abc").await;
|
||||
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn htaccess_local_error_document_renders_but_preserves_original_error_status() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::write(tmp.path().join("error.html"), b"custom-not-found").unwrap();
|
||||
std::fs::write(tmp.path().join(".htaccess"), b"ErrorDocument 404 /error.html?404\n").unwrap();
|
||||
let mut configured = Service {
|
||||
id: "local-error-document".into(),
|
||||
name: "Local errors".into(),
|
||||
document_root: tmp.path().to_path_buf(),
|
||||
htaccess: htaccess::Config { enabled: true, strict: true, ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
configured.validate().unwrap();
|
||||
let service = configured.compile().unwrap();
|
||||
let response = serve_request(&service, &request(Method::GET, "/missing"), "/missing").await;
|
||||
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||
assert_eq!(response.headers()[CACHE_CONTROL], "no-store");
|
||||
assert_eq!(response.into_body().collect().await.unwrap().to_bytes(), "custom-not-found");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn htaccess_rewrite_base_maps_relative_target_to_configured_url_prefix() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::create_dir(tmp.path().join("app")).unwrap();
|
||||
std::fs::create_dir(tmp.path().join("mounted")).unwrap();
|
||||
std::fs::write(tmp.path().join("mounted/landing.html"), b"mounted-ok").unwrap();
|
||||
std::fs::write(tmp.path().join("app/.htaccess"), b"RewriteEngine On\nRewriteBase /mounted/\nRewriteRule ^old$ landing.html [L]\n").unwrap();
|
||||
let mut configured = Service {
|
||||
id: "nested-rewrite-base".into(),
|
||||
name: "RewriteBase".into(),
|
||||
document_root: tmp.path().to_path_buf(),
|
||||
htaccess: htaccess::Config { enabled: true, strict: true, ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
configured.validate().unwrap();
|
||||
let service = configured.compile().unwrap();
|
||||
let response = serve_request(&service, &request(Method::GET, "/app/old"), "/app/old").await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.into_body().collect().await.unwrap().to_bytes(), "mounted-ok");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn htaccess_nested_accept_path_info_default_resets_parent_override() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::create_dir(tmp.path().join("nested")).unwrap();
|
||||
std::fs::write(tmp.path().join(".htaccess"), b"AcceptPathInfo On\n").unwrap();
|
||||
std::fs::write(tmp.path().join("nested/.htaccess"), b"AcceptPathInfo Default\n").unwrap();
|
||||
let ht = htaccess::compile(tmp.path(), &htaccess::Config { enabled: true, strict: true, ..Default::default() }).unwrap().unwrap();
|
||||
assert!(htaccess::accept_path_info(Some(&ht), "/index.php", false));
|
||||
assert!(!htaccess::accept_path_info(Some(&ht), "/nested/index.php", false));
|
||||
assert!(htaccess::accept_path_info(Some(&ht), "/nested/index.php", true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn htaccess_error_document_rejects_external_and_escaping_urls_even_non_strict() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
for bad in [
|
||||
"ErrorDocument 404 https://example.test/hidden\n",
|
||||
"ErrorDocument 404 //external.test/\n",
|
||||
"ErrorDocument 404 /../private\n",
|
||||
"ErrorDocument 404 /secret%2f..%2fother\n",
|
||||
"ErrorDocument 404 /malformed?x#frag\n",
|
||||
] {
|
||||
std::fs::write(tmp.path().join(".htaccess"), bad).unwrap();
|
||||
assert!(htaccess::compile(tmp.path(), &htaccess::Config { enabled: true, strict: false, ..Default::default() }).is_err(), "accepted {bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn htaccess_php_error_document_preserves_status_and_passes_its_own_query() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::write(tmp.path().join("error.php"), b"<?php // custom error").unwrap();
|
||||
std::fs::write(tmp.path().join(".htaccess"), b"ErrorDocument 404 /error.php?404\n").unwrap();
|
||||
let (endpoint, received) = fastcgi_fixture_record_params().await;
|
||||
let mut configured = Service {
|
||||
id: "php-local-error".into(),
|
||||
name: "PHP local error".into(),
|
||||
document_root: tmp.path().to_path_buf(),
|
||||
htaccess: htaccess::Config { enabled: true, strict: true, ..Default::default() },
|
||||
php: Php { enabled: true, endpoint: format!("tcp:{endpoint}"), ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
configured.validate().unwrap();
|
||||
let service = configured.compile().unwrap();
|
||||
let response = serve_request(&service, &request(Method::GET, "/missing?x=1"), "/missing").await;
|
||||
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||
assert_eq!(response.headers()[CACHE_CONTROL], "no-store");
|
||||
let params = received.await.unwrap();
|
||||
assert_eq!(params["SCRIPT_NAME"], "/error.php");
|
||||
assert_eq!(params["SCRIPT_FILENAME"], tmp.path().join("error.php").to_string_lossy());
|
||||
assert_eq!(params["QUERY_STRING"], "404");
|
||||
assert_eq!(params["REQUEST_URI"], "/error.php?404");
|
||||
}
|
||||
Reference in new issue
Block a user