v0.42.2_fix1

This commit is contained in:
Mateusz Gruszczyński committed 2026-11-26 11:53:05 +01:00
1 parent f38a2b9e5e
commit 15c7f9ff9e
24 files changed
+464 -77

No files matched your search

+132 -31
View File
@@ -2,11 +2,12 @@ use crate::config::Config;
use anyhow::{ensure, Result};
use arc_swap::ArcSwap;
use futures_util::{stream, StreamExt};
use serde::Serialize;
use std::{
collections::{BTreeSet, HashMap},
net::IpAddr,
sync::{Arc, LazyLock, Weak},
time::{Duration, Instant},
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use tokio::{sync::Notify, time::MissedTickBehavior};
use tokio_util::sync::CancellationToken;
@@ -18,7 +19,7 @@ const MAX_ADDRESSES: usize = 32;
const PARALLEL_LOOKUPS: usize = 8;
const LOOKUP_SECONDS: u64 = 4;
#[derive(Clone)]
#[derive(Clone, Debug)]
struct Addresses {
ips: Vec<IpAddr>,
valid_until: Instant,
@@ -26,8 +27,63 @@ struct Addresses {
static CACHE: LazyLock<ArcSwap<HashMap<String, Addresses>>> =
LazyLock::new(|| ArcSwap::from_pointee(HashMap::new()));
static DIAGNOSTICS: LazyLock<ArcSwap<HashMap<String, DnsDiagnostic>>> =
LazyLock::new(|| ArcSwap::from_pointee(HashMap::new()));
static CHANGED: LazyLock<Notify> = LazyLock::new(Notify::new);
#[derive(Clone)]
struct DnsDiagnostic {
checked_unix_ms: u64,
error: Option<String>,
}
/// A read-only view of the live resolver, not a second source of ACL permissions.
#[derive(Debug, Serialize)]
pub(crate) struct DnsAclStatus {
pub hostname: String,
pub state: &'static str,
pub addresses: Vec<IpAddr>,
pub last_checked_unix_ms: Option<u64>,
pub valid_for_seconds: Option<u64>,
pub error: Option<String>,
}
pub(crate) fn statuses(config: &Config) -> Result<Vec<DnsAclStatus>> {
let names = configured_hostnames(config)?;
let diagnostics = DIAGNOSTICS.load();
let cache = CACHE.load();
let now = Instant::now();
Ok(names.into_iter().map(|name| status_for_name(name, &cache, &diagnostics, now)).collect())
}
fn status_for_name(
hostname: String,
cache: &HashMap<String, Addresses>,
diagnostics: &HashMap<String, DnsDiagnostic>,
now: Instant,
) -> DnsAclStatus {
let latest = diagnostics.get(&hostname);
let cached = cache.get(&hostname);
let current = cached.filter(|entry| entry.valid_until > now);
let state = if current.is_some() {
"resolved"
} else if latest.is_none() {
"pending"
} else if latest.is_some_and(|entry| entry.error.is_some()) {
"failed"
} else {
"expired"
};
DnsAclStatus {
hostname,
state,
addresses: current.map_or_else(Vec::new, |entry| entry.ips.clone()),
last_checked_unix_ms: latest.map(|entry| entry.checked_unix_ms),
valid_for_seconds: current.map(|entry| entry.valid_until.duration_since(now).as_secs()),
error: latest.and_then(|entry| entry.error.clone()),
}
}
pub(crate) fn matches(name: &str, ip: IpAddr) -> bool {
let cache = CACHE.load();
cache.get(name).is_some_and(|entry| {
@@ -114,38 +170,47 @@ pub(crate) fn configured_hostnames(config: &Config) -> Result<Vec<String>> {
Ok(names.into_iter().collect())
}
async fn resolve(name: String) -> (String, Option<Addresses>) {
fn checked_unix_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64
}
fn validate_addresses(mut ips: Vec<IpAddr>) -> std::result::Result<Addresses, String> {
ips.sort_unstable();
ips.dedup();
if ips.is_empty() {
return Err("DNS response contains no A/AAAA addresses".into());
}
if ips.len() > MAX_ADDRESSES {
return Err(format!("DNS response exceeds the limit of {MAX_ADDRESSES} unique addresses"));
}
if ips
.iter()
.any(|ip| matches!(ip, IpAddr::V6(v6) if v6.to_ipv4_mapped().is_some()))
{
return Err("DNS response contains an IPv4-mapped IPv6 address".into());
}
Ok(Addresses {
ips,
valid_until: Instant::now() + Duration::from_secs(MAX_AGE_SECONDS),
})
}
async fn resolve(name: String) -> (String, std::result::Result<Addresses, String>) {
let lookup_name = name.clone();
let answer = tokio::time::timeout(
Duration::from_secs(LOOKUP_SECONDS),
tokio::net::lookup_host((lookup_name.as_str(), 0u16)),
)
.await;
let mut ips = match answer {
Ok(Ok(sockets)) => sockets.map(|socket| socket.ip()).collect::<Vec<_>>(),
_ => {
tracing::warn!(hostname = %name, "dynamic ACL DNS lookup failed; no addresses permitted");
return (name, None);
}
let result = match answer {
Err(_) => Err(format!("DNS lookup timed out after {LOOKUP_SECONDS} seconds")),
Ok(Err(error)) => Err(format!("system DNS resolver returned: {error}")),
Ok(Ok(sockets)) => validate_addresses(sockets.map(|socket| socket.ip()).collect()),
};
ips.sort_unstable();
ips.dedup();
if ips.is_empty()
|| ips.len() > MAX_ADDRESSES
|| ips
.iter()
.any(|ip| matches!(ip, IpAddr::V6(v6) if v6.to_ipv4_mapped().is_some()))
{
tracing::warn!(hostname = %name, "dynamic ACL DNS returned an invalid or excessive address set");
return (name, None);
}
(
name,
Some(Addresses {
ips,
valid_until: Instant::now() + Duration::from_secs(MAX_AGE_SECONDS),
}),
)
(name, result)
}
pub(crate) fn config_changed() {
@@ -155,6 +220,7 @@ pub(crate) fn config_changed() {
pub(crate) async fn poll_loop(app: Weak<crate::runtime::App>, shutdown: CancellationToken) {
let mut interval = tokio::time::interval(Duration::from_secs(REFRESH_SECONDS));
interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
let mut previous_names = Vec::new();
loop {
tokio::select! {
_ = shutdown.cancelled() => break,
@@ -165,16 +231,25 @@ pub(crate) async fn poll_loop(app: Weak<crate::runtime::App>, shutdown: Cancella
break;
};
let snapshot = state.config.load();
let Ok(names) = configured_hostnames(&snapshot.envelope.config) else {
continue;
let names = match configured_hostnames(&snapshot.envelope.config) {
Ok(names) => names,
Err(error) => {
tracing::error!(error = %error, "ACL DDNS inventory invalid; dynamic DNS rules fail closed");
CACHE.store(Arc::new(HashMap::new()));
DIAGNOSTICS.store(Arc::new(HashMap::new()));
continue;
}
};
drop(snapshot);
if names != previous_names {
tracing::info!(hostnames = ?names, "ACL DDNS resolver inventory updated");
previous_names = names.clone();
}
let results: HashMap<_, _> = tokio::select! {
_ = shutdown.cancelled() => break,
result = stream::iter(names.iter().cloned())
.map(resolve)
.buffer_unordered(PARALLEL_LOOKUPS)
.filter_map(|(name, answer)| async move { answer.map(|value| (name, value)) })
.collect() => result,
};
let current = state.config.load();
@@ -182,9 +257,35 @@ pub(crate) async fn poll_loop(app: Weak<crate::runtime::App>, shutdown: Cancella
CHANGED.notify_one();
continue;
}
CACHE.store(Arc::new(results));
let previous = CACHE.load();
let previous_diagnostics = DIAGNOSTICS.load();
let mut addresses = HashMap::new();
let mut diagnostics = HashMap::new();
for (hostname, result) in results {
let checked_unix_ms = checked_unix_ms();
match result {
Ok(value) => {
if previous.get(&hostname).is_none_or(|old| old.ips != value.ips)
|| previous_diagnostics.get(&hostname).is_some_and(|old| old.error.is_some())
{
tracing::info!(hostname = %hostname, addresses = ?value.ips,
"ACL DDNS resolved; allow rule matches only these client addresses");
}
addresses.insert(hostname.clone(), value);
diagnostics.insert(hostname, DnsDiagnostic { checked_unix_ms, error: None });
}
Err(error) => {
tracing::warn!(hostname = %hostname, reason = %error,
"ACL DDNS resolution failed; hostname allows no client addresses");
diagnostics.insert(hostname, DnsDiagnostic { checked_unix_ms, error: Some(error) });
}
}
}
CACHE.store(Arc::new(addresses));
DIAGNOSTICS.store(Arc::new(diagnostics));
}
CACHE.store(Arc::new(HashMap::new()));
DIAGNOSTICS.store(Arc::new(HashMap::new()));
}
#[cfg(test)]
+49
View File
@@ -34,5 +34,54 @@ mod tests {
CACHE.store(Arc::new(HashMap::new()));
assert!(!matches(name, new_ip));
}
#[test]
fn invalid_dns_answers_do_not_grant_access() {
assert!(validate_addresses(Vec::new()).unwrap_err().contains("no A/AAAA"));
let too_many = (1..=33)
.map(|octet| IpAddr::V4(std::net::Ipv4Addr::new(198, 51, 100, octet)))
.collect();
assert!(validate_addresses(too_many).unwrap_err().contains("limit"));
assert!(validate_addresses(vec!["::ffff:198.51.100.42".parse().unwrap()])
.unwrap_err().contains("IPv4-mapped"));
let valid = validate_addresses(vec!["198.51.100.2".parse().unwrap(), "198.51.100.2".parse().unwrap()]).unwrap();
assert_eq!(valid.ips.len(), 1);
}
#[test]
fn status_reports_pending_success_expiry_and_failure_independently_of_acl_decision() {
let mut config = Config::default();
config.global_security.acl = Some(crate::acl::Acl {
default: crate::acl::Action::Deny,
rules: vec![crate::acl::Rule {
network: "My-Home.Example".into(),
action: crate::acl::Action::Allow,
}],
});
let names = configured_hostnames(&config).unwrap();
assert_eq!(names, vec!["my-home.example"]);
let empty = HashMap::new();
let pending = status_for_name(names[0].clone(), &empty, &empty, Instant::now());
assert_eq!(pending.state, "pending");
let ip: IpAddr = "192.0.2.10".parse().unwrap();
let entries = HashMap::from([(names[0].clone(), Addresses {
ips: vec![ip], valid_until: Instant::now() + Duration::from_secs(120),
})]);
let diagnostics = HashMap::from([(names[0].clone(), DnsDiagnostic {
checked_unix_ms: 123, error: None,
})]);
let resolved = status_for_name(names[0].clone(), &entries, &diagnostics, Instant::now());
assert_eq!(resolved.state, "resolved");
assert_eq!(resolved.addresses, vec![ip]);
let expired = status_for_name(names[0].clone(), &entries, &diagnostics, Instant::now() + Duration::from_secs(121));
assert_eq!(expired.state, "expired");
assert!(expired.addresses.is_empty());
let failure = HashMap::from([(names[0].clone(), DnsDiagnostic {
checked_unix_ms: 456, error: Some("NXDOMAIN".into()),
})]);
let failed = status_for_name(names[0].clone(), &empty, &failure, Instant::now());
assert_eq!(failed.state, "failed");
assert_eq!(failed.error.as_deref(), Some("NXDOMAIN"));
}
}
+1
View File
@@ -3,6 +3,7 @@ fn general_api_token_allowed(method: &Method, path: &str, permission: &str) -> b
&& matches!(
path,
"/api/status"
| "/api/acl/dns-status"
| "/api/system-info"
| "/api/alerts"
| "/api/backends"
+30
View File
@@ -11200,6 +11200,36 @@
}
}
},
"/api/acl/dns-status": {
"get": {
"summary": "Live DNS/DDNS ACL resolver diagnostics",
"description": "Authenticated read-only snapshot of every DNS ACL name configured globally, in profiles, Vhosts and locations. Status is pending, resolved, failed or expired. Addresses are currently valid A/AAAA records; an error or expired entry grants no access. Check the actual client IP separately. DNS lookups are refreshed every 60 seconds and valid for at most 180 seconds.",
"tags": ["Monitoring"],
"operationId": "get_api_acl_dns_status",
"responses": {
"200": {
"description": "Resolver state",
"content": {"application/json": {"schema": {
"type": "object",
"required": ["refresh_seconds", "hostnames"],
"properties": {
"refresh_seconds": {"type": "integer", "example": 60},
"hostnames": {"type": "array", "items": {"type": "object", "required": ["hostname", "state", "addresses"], "properties": {
"hostname": {"type": "string"},
"state": {"type": "string", "enum": ["pending", "resolved", "failed", "expired"]},
"addresses": {"type": "array", "items": {"type": "string"}},
"last_checked_unix_ms": {"type": "integer", "nullable": true},
"valid_for_seconds": {"type": "integer", "nullable": true},
"error": {"type": "string", "nullable": true}
}}}
}
}}}
},
"401": {"description": "Authentication required"},
"403": {"description": "Administrative access forbidden"}
}
}
},
"/api/status": {
"get": {
"summary": "Application, listener, system and traffic status",
+1
View File
@@ -183,6 +183,7 @@ pub fn router(state: Arc<App>) -> Router {
.route("/favicon.svg", get(panel_assets::serve))
.route("/healthz", get(|| async { Json(json!({"status":"ok"})) }))
.route("/api/status", get(status))
.route("/api/acl/dns-status", get(dns_acl_status))
.route("/api/web-services/htaccess-warnings", get(web_service_htaccess_warnings))
.route("/api/system-info", get(system_info))
.route("/api/backends", get(backend_status))
+16
View File
@@ -1,5 +1,21 @@
include!("status_system.rs");
/// Live, read-only diagnostics for every configured DNS/DDNS ACL hostname.
/// In particular, a successful lookup need not match the address of a caller.
async fn dns_acl_status(State(state): State<Arc<App>>) -> Result<Json<Value>, ApiError> {
let snapshot = state.config.load();
let hostnames = crate::acl::dynamic::statuses(&snapshot.envelope.config).map_err(|error| {
ApiError(
StatusCode::INTERNAL_SERVER_ERROR,
format!("cannot enumerate ACL DDNS hostnames: {error}"),
)
})?;
Ok(Json(json!({
"refresh_seconds": crate::acl::dynamic::REFRESH_SECONDS,
"hostnames": hostnames,
})))
}
fn status_payload(state: &App) -> Value {
let snapshot = state.config.load_full();
let listeners = json!({
+31
View File
@@ -2597,11 +2597,42 @@ mod tests {
assert!(!dir.path().join("certs").join(&first_key_file).exists());
store.close().await;
}
#[tokio::test]
async fn dns_acl_status_is_authenticated_and_reports_configured_names() {
let mut config = Config::default();
config.global_security.acl = Some(crate::acl::Acl {
default: crate::acl::Action::Deny,
rules: vec![crate::acl::Rule {
network: "Home.Example.DDNS.Net".into(),
action: crate::acl::Action::Allow,
}],
});
let (router, store, _dir, secret, _) = fixture_with_config(config).await;
let response = router
.clone()
.oneshot(
request("/api/acl/dns-status")
.header("cookie", format!("{}={secret}", auth::COOKIE_NAME))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let status = json_body(response).await;
assert_eq!(status["refresh_seconds"], 60);
assert_eq!(status["hostnames"][0]["hostname"], "home.example.ddns.net");
assert_eq!(status["hostnames"][0]["state"], "pending");
assert!(status["hostnames"][0]["addresses"].as_array().unwrap().is_empty());
store.close().await;
}
#[tokio::test]
async fn anonymous_operational_paths_fail_closed_before_extractors() {
let (router, store, _dir, _, _) = fixture().await;
for path in [
"/api/status",
"/api/acl/dns-status",
"/api/system-info",
"/api/config",
"/api/config/history",
+6
View File
@@ -1101,6 +1101,12 @@
type="button">New profile</button>
</div>
<div class="entity-list" id="acl-profile-list"></div>
<details id="acl-dns-status" class="acl-profile-attached">
<summary data-i18n="aclDnsStatusTitle">DNS/DDNS ACL resolver status</summary>
<p class="fine" data-i18n="aclDnsStatusHelp">Shows the addresses currently permitted by DNS ACL rules, not the current visitor IP.</p>
<button type="button" class="outline" id="acl-dns-status-refresh" data-i18n="aclDnsStatusRefresh">Refresh DNS status</button>
<div id="acl-dns-status-list" class="entity-list" aria-live="polite"></div>
</details>
</article>
<form class="card edit-form" id="acl-profile-form">
<div class="card-heading">
+27
View File
@@ -228,6 +228,33 @@
const countryHelp = $("acl-profile-country-help"), countryLabel = $("acl-profile-country-label"), ipHelp = $("acl-profile-ip-help");
const i18n = (tag, key, cls) => { const node = el(tag, t(key), cls); node.dataset.i18n = key; return node; };
const dnsHint = i18n("p", "aclDnsHelp", "fine"); ipHelp?.after(dnsHint);
const dnsStatus = $("acl-dns-status"), dnsStatusList = $("acl-dns-status-list");
async function refreshDnsStatus() {
const button = $("acl-dns-status-refresh");
button.disabled = true;
try {
const snapshot = await api("/api/acl/dns-status");
const names = snapshot.hostnames || [];
const labels = { pending: "aclDnsPending", resolved: "aclDnsResolved", failed: "aclDnsFailed", expired: "aclDnsExpired" };
const rows = names.map(item => {
const card = el("div", undefined, "entity");
const title = el("div", undefined, "entity-top");
title.append(el("strong", item.hostname), el("span", t(labels[item.state] || "aclDnsPending")));
card.append(title);
const addresses = (item.addresses || []).join(", ");
card.append(el("p", `${t("aclDnsAddresses")}: ${addresses || "-"}`, "entity-details"));
const checked = item.last_checked_unix_ms ? new Date(item.last_checked_unix_ms).toLocaleString() : "-";
card.append(el("p", `${t("aclDnsChecked")}: ${checked} · TTL: ${item.valid_for_seconds ?? "-"} s`, "fine"));
if (item.error) card.append(el("p", `${t("aclDnsError")}: ${item.error}`, "fine"));
return card;
});
dnsStatusList.replaceChildren(...(rows.length ? rows : [el("p", t("aclDnsNoNames"), "fine")]));
} catch (error) {
dnsStatusList.replaceChildren(el("p", error.message, "fine"));
} finally { button.disabled = false; }
}
dnsStatus.addEventListener("toggle", () => { if (dnsStatus.open) void refreshDnsStatus(); });
$("acl-dns-status-refresh").addEventListener("click", () => void refreshDnsStatus());
const modeInputs = [...form.querySelectorAll('input[name="acl-profile-mode"]')];
const selectedMode = () => modeInputs.find(node => node.checked)?.value || "allow_exceptions";
const setMode = value => { for (const node of modeInputs) node.checked = node.value === value; };
+2 -1
View File
@@ -168,7 +168,7 @@ impl LegacyAccess {
#[derive(Debug, Clone)]
struct SimpleRedirect {
matcher: RedirectMatcher,
replacement: String,
replacement: Option<String>,
status: StatusCode,
}
@@ -233,6 +233,7 @@ pub enum RewriteOutcome {
Internal { path: String, query: Option<String> },
Redirect(Response),
Forbidden,
Status(StatusCode),
}
#[derive(Default)]
+22 -16
View File
@@ -5,27 +5,33 @@ fn redirect_status(value: &str) -> Option<StatusCode> {
"seeother" | "303" => Some(StatusCode::SEE_OTHER),
"307" => Some(StatusCode::TEMPORARY_REDIRECT),
"308" => Some(StatusCode::PERMANENT_REDIRECT),
"404" => Some(StatusCode::NOT_FOUND),
"gone" | "410" => Some(StatusCode::GONE),
_ => None,
}
}
fn redirect_rule(parts: &[String], regex: bool) -> Result<SimpleRedirect> {
let (status, source_index) = if parts.len() == 4 {
(redirect_status(&parts[1]).context("unsupported Redirect status")?, 2)
} else {
ensure!(parts.len() == 3, "Redirect / RedirectMatch expects [status] source target");
(StatusCode::FOUND, 1)
};
let explicit = parts.get(1).and_then(|value| redirect_status(value));
let (status, source_index) = explicit.map_or((StatusCode::FOUND, 1), |status| (status, 2));
let status_only = matches!(status, StatusCode::NOT_FOUND | StatusCode::GONE);
ensure!(parts.len() == source_index + if status_only { 1 } else { 2 },
"Redirect / RedirectMatch expects [status] source target, or 404/gone source without target");
let source = &parts[source_index];
let replacement = &parts[source_index + 1];
ensure!(!source.is_empty() && source.len() <= 512 && replacement.len() <= 1024,
"Redirect source/target is invalid");
ensure!((replacement.starts_with('/') && !replacement.starts_with("//"))
|| replacement.starts_with("http://") || replacement.starts_with("https://"),
"Redirect target must be a local absolute path or an explicit http(s) URL");
ensure!(!replacement.contains('\\') && !replacement.contains('\r') && !replacement.contains('\n'),
"Redirect target contains unsafe characters");
HeaderValue::from_str(replacement).context("invalid Redirect target")?;
ensure!(!source.is_empty() && source.len() <= 512, "Redirect source is invalid");
let replacement = if status_only {
None
} else {
let replacement = &parts[source_index + 1];
ensure!(replacement.len() <= 1024, "Redirect target is too long");
ensure!((replacement.starts_with('/') && !replacement.starts_with("//"))
|| replacement.starts_with("http://") || replacement.starts_with("https://"),
"Redirect target must be a local absolute path or an explicit http(s) URL");
ensure!(!replacement.contains('\\') && !replacement.contains('\r') && !replacement.contains('\n'),
"Redirect target contains unsafe characters");
HeaderValue::from_str(replacement).context("invalid Redirect target")?;
Some(replacement.to_owned())
};
let matcher = if regex {
RedirectMatcher::Regex(Regex::new(source).context("invalid RedirectMatch regex")?)
} else {
@@ -34,7 +40,7 @@ fn redirect_rule(parts: &[String], regex: bool) -> Result<SimpleRedirect> {
&& !source.contains('#') && !source.contains('\\'), "invalid Redirect path prefix");
RedirectMatcher::Prefix(source.to_owned())
};
Ok(SimpleRedirect { matcher, replacement: replacement.to_owned(), status })
Ok(SimpleRedirect { matcher, replacement, status })
}
// Only a safe, deterministic subset of Apache access rules is allowed in
+9 -4
View File
@@ -33,15 +33,20 @@ pub async fn apply_rewrites(
}
RedirectMatcher::Regex(_) => None,
};
let target = match &rule.matcher {
RedirectMatcher::Prefix(_) => tail.map(|tail| format!("{}{}", rule.replacement, tail)),
RedirectMatcher::Regex(regex) => regex.captures(&path).map(|captures| {
let target = match (&rule.matcher, rule.replacement.as_deref()) {
(RedirectMatcher::Prefix(_), None) => tail.map(|_| String::new()),
(RedirectMatcher::Regex(regex), None) => regex.is_match(&path).then(String::new),
(RedirectMatcher::Prefix(_), Some(base)) => tail.map(|tail| format!("{base}{tail}")),
(RedirectMatcher::Regex(regex), Some(base)) => regex.captures(&path).map(|captures| {
let mut target = String::new();
captures.expand(&rule.replacement, &mut target);
captures.expand(base, &mut target);
target
}),
};
if let Some(mut target) = target {
if rule.replacement.is_none() {
return Ok(RewriteOutcome::Status(rule.status));
}
ensure!((target.starts_with('/') && !target.starts_with("//"))
|| target.starts_with("http://") || target.starts_with("https://"),
"unsafe .htaccess Redirect expansion");
+3
View File
@@ -109,6 +109,9 @@ async fn serve_inner(
Ok(htaccess::RewriteOutcome::Forbidden) => {
return builtin_error_response(StatusCode::FORBIDDEN, &method)
}
Ok(htaccess::RewriteOutcome::Status(status)) => {
return builtin_error_response(status, &method)
}
Ok(htaccess::RewriteOutcome::Internal { path, query }) => (path, query),
Err(_) => {
return status_response(
+62
View File
@@ -2685,3 +2685,65 @@ ErrorDocument 404 /error.html
assert_eq!(regex.status(), StatusCode::FOUND);
assert_eq!(regex.headers()[LOCATION], "/archive/file.txt");
}
#[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#"
RedirectMatch 404 ^/missing/
Redirect gone /removed
Redirect 302 /old /new
"#).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() },
..Default::default()
};
let service = config.compile().unwrap();
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;
assert_eq!(gone.status(), StatusCode::GONE);
assert!(!gone.headers().contains_key(LOCATION));
let redirect = serve_request(&service, &request(Method::GET, "/old"), "/old").await;
assert_eq!(redirect.status(), StatusCode::FOUND);
assert_eq!(redirect.headers()[LOCATION], "/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#"
# Typical monitoring/PHP installation, without application-specific rules in RustProxy.
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 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() },
..Default::default()
};
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!(!warnings.iter().any(|warning| warning.contains("RedirectMatch")));
}