v0.42.4_fixes

This commit is contained in:
Mateusz Gruszczyński committed 2026-11-27 13:56:59 +01:00
1 parent efc6eda4cd
commit 51631810e1
29 files changed
+1192 -394

No files matched your search

+2 -2
View File
@@ -423,7 +423,7 @@ pub fn index_files<'a>(compiled: Option<&'a Compiled>, directory_components: &[S
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()) {
.filter_map(|scope| scope.accept_path_info).next_back()) {
Some(AcceptPathInfoMode::On) => true,
Some(AcceptPathInfoMode::Off) => false,
Some(AcceptPathInfoMode::Default) | None => fallback,
@@ -437,7 +437,7 @@ pub fn has_error_documents(compiled: Option<&Compiled>) -> bool {
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()
}).filter_map(|scope| scope.error_documents.get(&status.as_u16()).map(String::as_str)).next_back()
}
pub fn directory_listing(compiled: Option<&Compiled>, directory_components: &[String], fallback: bool) -> bool {
+2 -2
View File
@@ -10,8 +10,8 @@ mod security;
mod serve;
pub use config::{
CacheRule, CompiledService, FastCgiHandler, Hardening, Php, PhpFpmProfile, Precompressed, RewriteRule,
SendfileMode, Service, SymlinkPolicy,
CacheRule, CompiledService, FastCgiHandler, Hardening, Php, PhpFpmProfile, Precompressed,
RewriteRule, SendfileMode, Service, SymlinkPolicy,
};
pub use htaccess::Config as HtaccessConfig;
pub use request::RequestContext;
+72 -27
View File
@@ -1,10 +1,10 @@
use super::{
config::FastCgiHandler,
fastcgi::{
method_not_allowed_response, php_for_path, php_response, protected_script_without_handler,
},
filesystem::{list_directory_sync, path_components, FilesystemRoot},
htaccess,
config::FastCgiHandler,
response::{
add_service_headers, builtin_error_response, directory_listing, directory_redirect,
file_response, io_response, status_response,
@@ -33,8 +33,12 @@ async fn resolve_script_path_info(
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; };
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;
}
@@ -123,7 +127,7 @@ async fn serve_inner(
return status_response(
StatusCode::BAD_REQUEST,
"RustProxy: invalid .htaccess rewrite target\n",
)
);
}
};
if crate::acl::validate_decoded_routing_path(&rewritten_path).is_err()
@@ -135,12 +139,18 @@ async fn serve_inner(
htaccess::protected_component(service.htaccess.as_ref(), component)
})
})
|| htaccess::denied(service.htaccess.as_ref(), &rewritten_path, context.client_ip)
|| htaccess::denied(
service.htaccess.as_ref(),
&rewritten_path,
context.client_ip,
)
{
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, &rewritten_path).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| {
@@ -188,7 +198,11 @@ async fn serve_inner(
|| components
.iter()
.any(|component| htaccess::protected_component(service.htaccess.as_ref(), component))
|| htaccess::denied(service.htaccess.as_ref(), &effective_path, context.client_ip)
|| htaccess::denied(
service.htaccess.as_ref(),
&effective_path,
context.client_ip,
)
{
return builtin_error_response(StatusCode::FORBIDDEN, &method);
}
@@ -253,7 +267,10 @@ async fn serve_inner(
.await;
}
if protected_script_without_handler(service, &public_path)
|| service.php.as_ref().is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
|| service
.php
.as_ref()
.is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
{
// A CGI-only root must never expose any non-executed file.
return builtin_error_response(StatusCode::FORBIDDEN, &method);
@@ -311,7 +328,10 @@ async fn serve_inner(
.await;
}
if protected_script_without_handler(service, &public_path)
|| service.php.as_ref().is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
|| service
.php
.as_ref()
.is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
{
return builtin_error_response(StatusCode::FORBIDDEN, &method);
}
@@ -350,12 +370,16 @@ async fn serve_inner(
if method != Method::GET && method != Method::HEAD {
return method_not_allowed_response();
}
if service.php.as_ref().is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
if service
.php
.as_ref()
.is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
|| !htaccess::directory_listing(
service.htaccess.as_ref(),
&components,
service.directory_listing,
) {
service.htaccess.as_ref(),
&components,
service.directory_listing,
)
{
return builtin_error_response(StatusCode::FORBIDDEN, &method);
}
let root = FilesystemRoot::for_service(service);
@@ -426,7 +450,7 @@ pub async fn serve(
// 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()));
.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;
@@ -434,25 +458,42 @@ pub async fn serve(
// 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))
&& !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) {
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); }
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;
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;
@@ -468,7 +509,9 @@ pub async fn serve(
// by Vhost/global pages in the outer HTTP response pipeline.
if used_local_error_document
|| matches!(
response.extensions().get::<crate::web_server::metrics::ResponseKind>(),
response
.extensions()
.get::<crate::web_server::metrics::ResponseKind>(),
Some(crate::web_server::metrics::ResponseKind::Php)
)
{
@@ -484,7 +527,9 @@ pub async fn serve(
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()
.insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
response.headers_mut().remove(http::header::EXPIRES);
}
strip_unnecessary_headers(&mut response, service);
+390 -79
View File
@@ -119,7 +119,10 @@ async fn missing_files_and_disabled_directory_listing_return_normal_errors() {
)
.await;
assert_eq!(missing.status(), StatusCode::NOT_FOUND);
assert!(missing.extensions().get::<crate::pages::OriginProvidedResponse>().is_none());
assert!(missing
.extensions()
.get::<crate::pages::OriginProvidedResponse>()
.is_none());
assert_eq!(missing.headers()[CACHE_CONTROL], "no-store");
assert_eq!(missing.headers()[CONTENT_TYPE], "text/html; charset=utf-8");
assert_eq!(missing.headers()["x-content-type-options"], "nosniff");
@@ -1142,46 +1145,125 @@ async fn htaccess_legacy_deny_from_all_is_enforced_even_in_non_strict_mode() {
id: "htaccess-deny-all".into(),
name: "htaccess deny all".into(),
document_root: tmp.path().to_path_buf(),
htaccess: htaccess::Config { enabled: true, strict: false, ..Default::default() },
htaccess: htaccess::Config {
enabled: true,
strict: false,
..Default::default()
},
..Default::default()
};
configured.validate().unwrap();
let service = configured.compile().unwrap();
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);
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
);
}
#[test]
fn htaccess_legacy_order_and_ip_rules_follow_apache_22_precedence() {
let tmp = TempDir::new().unwrap();
let ht = tmp.path().join(".htaccess");
let config = htaccess::Config { enabled: true, strict: true, ..Default::default() };
let config = htaccess::Config {
enabled: true,
strict: true,
..Default::default()
};
std::fs::write(&ht, b"Order deny,allow\nDeny from all\nAllow from 192.0.2.0/24\n").unwrap();
std::fs::write(
&ht,
b"Order deny,allow\nDeny from all\nAllow from 192.0.2.0/24\n",
)
.unwrap();
let compiled = htaccess::compile(tmp.path(), &config).unwrap().unwrap();
assert!(htaccess::denied(Some(&compiled), "/index.html", "198.51.100.1".parse().unwrap()));
assert!(!htaccess::denied(Some(&compiled), "/index.html", "192.0.2.42".parse().unwrap()));
assert!(htaccess::denied(
Some(&compiled),
"/index.html",
"198.51.100.1".parse().unwrap()
));
assert!(!htaccess::denied(
Some(&compiled),
"/index.html",
"192.0.2.42".parse().unwrap()
));
std::fs::write(&ht, b"Order allow,deny\nAllow from 192.0.2.0/24\nDeny from 192.0.2.42\n").unwrap();
std::fs::write(
&ht,
b"Order allow,deny\nAllow from 192.0.2.0/24\nDeny from 192.0.2.42\n",
)
.unwrap();
let compiled = htaccess::compile(tmp.path(), &config).unwrap().unwrap();
assert!(!htaccess::denied(Some(&compiled), "/index.html", "192.0.2.41".parse().unwrap()));
assert!(htaccess::denied(Some(&compiled), "/index.html", "192.0.2.42".parse().unwrap()));
assert!(htaccess::denied(Some(&compiled), "/index.html", "198.51.100.1".parse().unwrap()));
assert!(!htaccess::denied(
Some(&compiled),
"/index.html",
"192.0.2.41".parse().unwrap()
));
assert!(htaccess::denied(
Some(&compiled),
"/index.html",
"192.0.2.42".parse().unwrap()
));
assert!(htaccess::denied(
Some(&compiled),
"/index.html",
"198.51.100.1".parse().unwrap()
));
std::fs::write(&ht, b"Order allow,deny\nAllow from 2001:db8::/32\nDeny from 2001:db8::bad\n").unwrap();
std::fs::write(
&ht,
b"Order allow,deny\nAllow from 2001:db8::/32\nDeny from 2001:db8::bad\n",
)
.unwrap();
let compiled = htaccess::compile(tmp.path(), &config).unwrap().unwrap();
assert!(!htaccess::denied(Some(&compiled), "/index.html", "2001:db8::1".parse().unwrap()));
assert!(htaccess::denied(Some(&compiled), "/index.html", "2001:db8::bad".parse().unwrap()));
assert!(!htaccess::denied(
Some(&compiled),
"/index.html",
"2001:db8::1".parse().unwrap()
));
assert!(htaccess::denied(
Some(&compiled),
"/index.html",
"2001:db8::bad".parse().unwrap()
));
}
#[test]
fn htaccess_legacy_unsupported_hostnames_fail_closed_with_strict_disabled() {
let tmp = TempDir::new().unwrap();
std::fs::write(tmp.path().join(".htaccess"), b"Deny from protected.example\n").unwrap();
let config = htaccess::Config { enabled: true, strict: false, ..Default::default() };
let error = htaccess::compile(tmp.path(), &config).unwrap_err().to_string();
assert!(error.contains("only all, IP and CIDR are supported"), "{error}");
std::fs::write(
tmp.path().join(".htaccess"),
b"Deny from protected.example\n",
)
.unwrap();
let config = htaccess::Config {
enabled: true,
strict: false,
..Default::default()
};
let error = htaccess::compile(tmp.path(), &config)
.unwrap_err()
.to_string();
assert!(
error.contains("only all, IP and CIDR are supported"),
"{error}"
);
}
#[test]
@@ -2563,7 +2645,11 @@ fn fastcgi_handler_is_backward_compatible_and_prevents_php_as_cgi() {
async fn generic_fcgiwrap_mount_passes_public_script_name_without_exposing_other_files() {
let tmp = TempDir::new().unwrap();
std::fs::write(tmp.path().join("health.cgi"), b"#!/bin/sh\necho ok\n").unwrap();
std::fs::write(tmp.path().join("configuration.txt"), b"private CGI settings").unwrap();
std::fs::write(
tmp.path().join("configuration.txt"),
b"private CGI settings",
)
.unwrap();
let (address, received) = fastcgi_fixture_record_params().await;
let mut config = Service {
id: "cgi-app".into(),
@@ -2587,7 +2673,10 @@ async fn generic_fcgiwrap_mount_passes_public_script_name_without_exposing_other
let response = serve_request(&service, &request(Method::GET, uri), "/health.cgi/more").await;
assert_eq!(response.status(), StatusCode::OK);
let params = received.await.unwrap();
assert_eq!(params["SCRIPT_FILENAME"].as_str(), tmp.path().join("health.cgi").to_string_lossy().as_ref());
assert_eq!(
params["SCRIPT_FILENAME"].as_str(),
tmp.path().join("health.cgi").to_string_lossy().as_ref()
);
assert_eq!(params["SCRIPT_NAME"], "/app/cgi-bin/health.cgi");
assert_eq!(params["PATH_INFO"], "/more");
assert_eq!(params["REQUEST_URI"], uri);
@@ -2596,7 +2685,8 @@ async fn generic_fcgiwrap_mount_passes_public_script_name_without_exposing_other
&service,
&request(Method::GET, "/app/cgi-bin/configuration.txt"),
"/configuration.txt",
).await;
)
.await;
assert_eq!(forbidden.status(), StatusCode::FORBIDDEN);
}
@@ -2621,12 +2711,25 @@ async fn generic_fastcgi_responder_executes_only_configured_script_extensions()
};
config.validate().unwrap();
let service = config.compile().unwrap();
let executed = serve_request(&service, &request(Method::GET, "/handler.fcgi"), "/handler.fcgi").await;
let executed = serve_request(
&service,
&request(Method::GET, "/handler.fcgi"),
"/handler.fcgi",
)
.await;
assert_eq!(executed.status(), StatusCode::OK);
assert_eq!(received.await.unwrap()["SCRIPT_NAME"], "/handler.fcgi");
let static_file = serve_request(&service, &request(Method::GET, "/public.txt"), "/public.txt").await;
let static_file = serve_request(
&service,
&request(Method::GET, "/public.txt"),
"/public.txt",
)
.await;
assert_eq!(static_file.status(), StatusCode::OK);
assert_eq!(static_file.into_body().collect().await.unwrap().to_bytes(), "public");
assert_eq!(
static_file.into_body().collect().await.unwrap().to_bytes(),
"public"
);
}
#[tokio::test]
@@ -2635,19 +2738,26 @@ async fn htaccess_filesmatch_enforces_denial_including_directory_index() {
std::fs::write(tmp.path().join("index.html"), b"index").unwrap();
std::fs::write(tmp.path().join("secret.env"), b"secret").unwrap();
std::fs::write(tmp.path().join("public.txt"), b"public").unwrap();
std::fs::write(tmp.path().join(".htaccess"), r#"
std::fs::write(
tmp.path().join(".htaccess"),
r#"
<FilesMatch "^secret\.env$">
Require all denied
</FilesMatch>
<Files "index.html">
Deny from all
</Files>
"#).unwrap();
"#,
)
.unwrap();
let mut config = Service {
id: "files-rule".into(),
name: "Files rule".into(),
document_root: tmp.path().to_path_buf(),
htaccess: htaccess::Config { enabled: true, ..Default::default() },
htaccess: htaccess::Config {
enabled: true,
..Default::default()
},
..Default::default()
};
config.validate().unwrap();
@@ -2656,33 +2766,59 @@ Deny from all
let response = serve_request(&service, &request(Method::GET, path), path).await;
assert_eq!(response.status(), StatusCode::FORBIDDEN, "{path}");
}
let good = serve_request(&service, &request(Method::GET, "/public.txt"), "/public.txt").await;
let good = serve_request(
&service,
&request(Method::GET, "/public.txt"),
"/public.txt",
)
.await;
assert_eq!(good.status(), StatusCode::OK);
}
#[tokio::test]
async fn htaccess_redirect_and_redirectmatch_are_applied_without_rewriteengine() {
let tmp = TempDir::new().unwrap();
std::fs::write(tmp.path().join(".htaccess"), r#"
std::fs::write(
tmp.path().join(".htaccess"),
r#"
Redirect permanent /old /new
RedirectMatch 302 ^/old-files/(.*)$ /archive/$1
ErrorDocument 404 /error.html
"#).unwrap();
"#,
)
.unwrap();
let mut config = Service {
id: "redirects".into(),
name: "Redirects".into(),
document_root: tmp.path().to_path_buf(),
htaccess: htaccess::Config { enabled: true, strict: false, ..Default::default() },
htaccess: htaccess::Config {
enabled: true,
strict: false,
..Default::default()
},
..Default::default()
};
config.validate().unwrap();
let service = config.compile().unwrap();
let (_, warnings) = service.htaccess_diagnostics().unwrap();
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!(
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");
let regex = serve_request(&service, &request(Method::GET, "/old-files/file.txt"), "/old-files/file.txt").await;
let regex = serve_request(
&service,
&request(Method::GET, "/old-files/file.txt"),
"/old-files/file.txt",
)
.await;
assert_eq!(regex.status(), StatusCode::FOUND);
assert_eq!(regex.headers()[LOCATION], "/archive/file.txt");
}
@@ -2690,23 +2826,40 @@ ErrorDocument 404 /error.html
#[tokio::test]
async fn htaccess_status_only_redirects_do_not_require_location_headers() {
let tmp = TempDir::new().unwrap();
std::fs::write(tmp.path().join(".htaccess"), r#"
std::fs::write(
tmp.path().join(".htaccess"),
r#"
RedirectMatch 404 ^/missing/
Redirect gone /removed
Redirect 302 /old /new
"#).unwrap();
"#,
)
.unwrap();
let config = Service {
id: "status-only".into(),
name: "Status only".into(),
document_root: tmp.path().to_path_buf(),
htaccess: htaccess::Config { enabled: true, ..Default::default() },
htaccess: htaccess::Config {
enabled: true,
..Default::default()
},
..Default::default()
};
let service = config.compile().unwrap();
let not_found = serve_request(&service, &request(Method::GET, "/missing/secret"), "/missing/secret").await;
let not_found = serve_request(
&service,
&request(Method::GET, "/missing/secret"),
"/missing/secret",
)
.await;
assert_eq!(not_found.status(), StatusCode::NOT_FOUND);
assert!(!not_found.headers().contains_key(LOCATION));
let gone = serve_request(&service, &request(Method::GET, "/removed/file"), "/removed/file").await;
let gone = serve_request(
&service,
&request(Method::GET, "/removed/file"),
"/removed/file",
)
.await;
assert_eq!(gone.status(), StatusCode::GONE);
assert!(!gone.headers().contains_key(LOCATION));
let redirect = serve_request(&service, &request(Method::GET, "/old"), "/old").await;
@@ -2717,7 +2870,9 @@ Redirect 302 /old /new
#[test]
fn htaccess_popular_php_front_controller_file_compiles_without_strict_compatibility() {
let tmp = TempDir::new().unwrap();
std::fs::write(tmp.path().join(".htaccess"), r#"
std::fs::write(
tmp.path().join(".htaccess"),
r#"
# Typical monitoring/PHP installation, without application-specific rules in RustProxy.
Options FollowSymlinks Multiviews
ErrorDocument 404 /error.php?404
@@ -2734,20 +2889,40 @@ RewriteCond %{REQUEST_URI} !^rrd/
RewriteCond %{REQUEST_URI} !=/server-status
RewriteRule ^(.*)$ index.php/$1/
AcceptPathInfo On
"#).unwrap();
"#,
)
.unwrap();
let config = Service {
id: "monitoring-app".into(),
name: "Monitoring app".into(),
document_root: tmp.path().to_path_buf(),
htaccess: htaccess::Config { enabled: true, strict: false, ..Default::default() },
htaccess: htaccess::Config {
enabled: true,
strict: false,
..Default::default()
},
..Default::default()
};
let service = config.compile().unwrap();
let (_, warnings) = service.htaccess_diagnostics().unwrap();
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")));
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]
@@ -2756,7 +2931,9 @@ async fn htaccess_observium_style_front_controller_executes_php_path_info_withou
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
std::fs::write(
tmp.path().join(".htaccess"),
br#"# Original, representative application .htaccess
Options FollowSymlinks Multiviews
ErrorDocument 404 /error.php?404
RedirectMatch 404 /\.
@@ -2772,31 +2949,66 @@ RewriteCond %{REQUEST_URI} !^rrd/
RewriteCond %{REQUEST_URI} !=/server-status
RewriteRule ^(.*)$ index.php/$1/
AcceptPathInfo On
"#).unwrap();
"#,
)
.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() },
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:?}");
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;
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");
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;
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_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");
@@ -2807,14 +3019,26 @@ AcceptPathInfo On
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();
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() },
htaccess: htaccess::Config {
enabled: true,
strict: true,
..Default::default()
},
php: Php {
enabled: true,
endpoint: format!("tcp:{endpoint}"),
..Default::default()
},
..Default::default()
};
configured.validate().unwrap();
@@ -2835,14 +3059,32 @@ async fn htaccess_accept_path_info_off_overrides_enabled_php_path_info() {
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() },
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!(!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);
}
@@ -2850,12 +3092,20 @@ async fn htaccess_accept_path_info_off_overrides_enabled_php_path_info() {
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();
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() },
htaccess: htaccess::Config {
enabled: true,
strict: true,
..Default::default()
},
..Default::default()
};
configured.validate().unwrap();
@@ -2863,7 +3113,10 @@ async fn htaccess_local_error_document_renders_but_preserves_original_error_stat
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");
assert_eq!(
response.into_body().collect().await.unwrap().to_bytes(),
"custom-not-found"
);
}
#[tokio::test]
@@ -2872,19 +3125,30 @@ async fn htaccess_rewrite_base_maps_relative_target_to_configured_url_prefix() {
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();
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() },
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");
assert_eq!(
response.into_body().collect().await.unwrap().to_bytes(),
"mounted-ok"
);
}
#[test]
@@ -2892,11 +3156,32 @@ 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();
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));
assert!(!htaccess::accept_path_info(
Some(&ht),
"/nested/index.php",
false
));
assert!(htaccess::accept_path_info(
Some(&ht),
"/nested/index.php",
true
));
}
#[test]
@@ -2910,7 +3195,18 @@ fn htaccess_error_document_rejects_external_and_escaping_urls_even_non_strict()
"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:?}");
assert!(
htaccess::compile(
tmp.path(),
&htaccess::Config {
enabled: true,
strict: false,
..Default::default()
}
)
.is_err(),
"accepted {bad:?}"
);
}
}
@@ -2918,14 +3214,26 @@ fn htaccess_error_document_rejects_external_and_escaping_urls_even_non_strict()
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();
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() },
htaccess: htaccess::Config {
enabled: true,
strict: true,
..Default::default()
},
php: Php {
enabled: true,
endpoint: format!("tcp:{endpoint}"),
..Default::default()
},
..Default::default()
};
configured.validate().unwrap();
@@ -2935,7 +3243,10 @@ async fn htaccess_php_error_document_preserves_status_and_passes_its_own_query()
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["SCRIPT_FILENAME"],
tmp.path().join("error.php").to_string_lossy()
);
assert_eq!(params["QUERY_STRING"], "404");
assert_eq!(params["REQUEST_URI"], "/error.php?404");
}