This commit is contained in:
Mateusz Gruszczyński committed 2026-11-25 15:47:34 +01:00
1 parent 6df256cdbb
commit 0d6249e383
159 files changed
+16737 -1971

No files matched your search

+2
View File
@@ -264,6 +264,7 @@ pub fn compile_with_active(
guarded_bindings.sort();
guarded_bindings.dedup();
let global_headers = config.headers.compile()?;
let global_policy = Arc::new(config.policy.compile()?);
let global_security = config.global_security.compile()?;
ensure!(
config.host_policies.len() <= 256,
@@ -385,6 +386,7 @@ pub fn compile_with_active(
host_acls,
global_security,
headers: global_headers,
policy: global_policy,
})
}
fn normalize_prefix(prefix: &mut String) -> Result<()> {
+75
View File
@@ -0,0 +1,75 @@
mod http_policy_tests {
use super::*;
fn validation() -> ValidationPolicy {
ValidationPolicy {
tls_addr: None,
cert_dir: None,
data_dir: None,
proxy_addr: "127.0.0.1:8080".parse().unwrap(),
admin_addr: "127.0.0.1:9090".parse().unwrap(),
}
}
fn settings(stage: &str, action: serde_json::Value) -> crate::policy::Settings {
serde_json::from_value(
serde_json::json!({"rules":[{"id":"test","stage":stage,"actions":[action]}]}),
)
.unwrap()
}
#[test]
fn legacy_configuration_defaults_to_no_http_policies() {
let config: Config = serde_json::from_str("{}").unwrap();
assert!(config.policy.is_empty());
assert!(serde_json::to_value(&config)
.unwrap()
.get("policy")
.is_none());
let snapshot = compile(
demo_config("127.0.0.1:9000".parse().unwrap()),
1,
&validation(),
)
.unwrap();
assert!(snapshot.policy.is_empty());
let route = snapshot.select("localhost", "/").unwrap();
assert!(route.policy.is_empty());
assert!(!route.frontend.as_ref().unwrap().has_policies);
}
#[test]
fn location_pre_route_and_unknown_backend_are_rejected_before_activation() {
let mut config = demo_config("127.0.0.1:9000".parse().unwrap());
config.vhosts[0].routes[0].policy = settings(
"pre_route",
serde_json::json!({"type":"set_path","value":"/new"}),
);
assert!(compile(config.clone(), 1, &validation())
.unwrap_err()
.to_string()
.contains("pre_route"));
config.vhosts[0].routes[0].policy = settings(
"request",
serde_json::json!({"type":"use_backend","id":"missing"}),
);
assert!(compile(config.clone(), 1, &validation())
.unwrap_err()
.to_string()
.contains("backend"));
config.vhosts[0].routes[0].policy = settings(
"request",
serde_json::json!({"type":"use_backend","id":"demo"}),
);
assert!(compile(config, 1, &validation()).is_ok());
}
#[test]
fn policy_on_legacy_root_route_is_preserved_instead_of_migrated_away() {
let mut config = demo_config("127.0.0.1:9000".parse().unwrap());
config.vhosts[0].routes[0].policy = settings(
"after_response",
serde_json::json!({"type":"set_header","name":"X-Location","value":"root"}),
);
assert!(!config.vhosts[0].routes[0].is_legacy_main_fallback());
let snapshot = compile(config, 1, &validation()).unwrap();
let route = snapshot.select("localhost", "/").unwrap();
assert!(!route.policy.is_empty());
assert!(route.frontend.as_ref().unwrap().has_policies);
}
}
+6 -4
View File
@@ -84,6 +84,8 @@ pub struct Config {
pub acl_profiles: Vec<AclProfile>,
#[serde(default, skip_serializing_if = "HeaderRules::is_empty")]
pub headers: HeaderRules,
#[serde(default, skip_serializing_if = "crate::policy::Settings::is_empty")]
pub policy: crate::policy::Settings,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
@@ -244,7 +246,6 @@ pub struct CompiledLocationRedirect {
#[derive(Debug, Clone)]
pub struct CompiledRoute {
/// Request conditions besides the path (all must hold); `None` for plain locations.
pub conditions: Option<Arc<crate::vhost::CompiledConditions>>,
pub backend_id: Option<String>,
pub bindings: Vec<crate::vhost::Listener>,
@@ -270,14 +271,13 @@ pub struct CompiledRoute {
pub country_access: crate::rate_limit::CountryAccess,
pub method_policy: crate::vhost::MethodPolicy,
pub headers: CompiledHeaders,
pub policy: Arc<crate::policy::CompiledPolicy>,
pub unavailable: bool,
}
#[derive(Debug)]
pub struct CompiledFrontend {
/// Some enabled location has request conditions: the route is selected again
/// with the final client address (and country) before forwarding.
pub conditional_routes: bool,
/// Some location condition tests the client country.
pub has_policies: bool,
pub route_conditions_country: bool,
pub websockets: bool,
pub websocket_legacy_support: bool,
@@ -314,6 +314,7 @@ pub struct CompiledFrontend {
pub profile_policies: Vec<crate::acl::ProfileAccess>,
pub acl: Option<CompiledAcl>,
pub headers: CompiledHeaders,
pub policy: Arc<crate::policy::CompiledPolicy>,
pub security: crate::security::CompiledSecurity,
pub compression: crate::compression::Overrides,
pub cache: crate::cache::Settings,
@@ -347,6 +348,7 @@ pub struct Snapshot {
host_acls: HashMap<String, Arc<CompiledAcl>>,
pub global_security: CompiledGlobalSecurity,
pub headers: CompiledHeaders,
pub policy: Arc<crate::policy::CompiledPolicy>,
}
impl std::fmt::Debug for Snapshot {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+76 -43
View File
@@ -139,9 +139,7 @@ fn compile_routing(
backend.id = member_id;
let health = host.load_balancing.health_for(definition);
if health.mode != crate::balance::HealthMode::Off {
if let Some(probe) =
health_probe_backend(&definition.backend(), health.port)?
{
if let Some(probe) = health_probe_backend(&definition.backend(), health.port)? {
let mut probe = compile_backend_reusing(
&probe,
desired_policy,
@@ -153,7 +151,10 @@ fn compile_routing(
.and_then(|item| item.health_probe.as_deref()),
)
.with_context(|| {
format!("vhost {} backend {} health check port", host.id, definition.id)
format!(
"vhost {} backend {} health check port",
host.id, definition.id
)
})?;
probe.id = format!("{}/{}#health", host.id, definition.id);
backend.health_probe = Some(Arc::new(probe));
@@ -234,7 +235,21 @@ fn compile_routing(
.first()
.map(|entry| (entry.acl.clone(), entry.countries.clone()))
.unwrap_or_else(|| (None, crate::rate_limit::CountryAccess::default()));
let host_policy = Arc::new(host.policy.compile()?);
for id in host_policy.backend_ids() {
ensure!(
host.backends.iter().any(|backend| backend.id == id),
"vhost {} policy references unknown backend {}",
host.id,
id
);
}
let frontend = Arc::new(CompiledFrontend {
has_policies: !host.policy.is_empty()
|| host
.routes
.iter()
.any(|route| route.enabled && !route.policy.is_empty()),
conditional_routes: host
.routes
.iter()
@@ -263,7 +278,9 @@ fn compile_routing(
cloudflare_client_ip: host.cloudflare_client_ip,
timing_headers: host.timing_headers,
timing_header_names: host.timing_header_names,
timing_allow_origin: crate::vhost::timing_allow_origin_value(&host.timing_allow_origin)?,
timing_allow_origin: crate::vhost::timing_allow_origin_value(
&host.timing_allow_origin,
)?,
backend_header: host.backend_header,
backend_timing_header: host.backend_timing_header,
rate_limit: host.rate_limit.clone(),
@@ -295,6 +312,7 @@ fn compile_routing(
profile_policies,
acl: host.acl.as_ref().map(Acl::compile).transpose()?,
headers: host.headers.compile()?,
policy: host_policy,
security: host.security_headers.compile()?,
compression: host.compression.clone(),
cache: host.cache.resolve_for(&config.cache, &host.id)?,
@@ -351,6 +369,7 @@ fn compile_routing(
country_access: crate::rate_limit::CountryAccess::default(),
method_policy: crate::vhost::MethodPolicy::default(),
headers: crate::headers::CompiledHeaders::default(),
policy: Arc::new(crate::policy::CompiledPolicy::default()),
unavailable: host.transient_unavailable && host.source.is_reverse_proxy(),
});
for name in &routing_hosts {
@@ -415,8 +434,6 @@ fn compile_routing(
let route_conditions = crate::vhost::CompiledConditions::compile(&route.conditions)
.with_context(|| format!("vhost {} location {}", host.id, route.id))?
.map(Arc::new);
// Locations with conditions may share a path: the first whose conditions
// hold is used, the others are skipped.
if !route.internal && route.conditions.is_empty() {
ensure!(
path_bindings.insert((route.match_type, route.path_prefix.clone())),
@@ -429,8 +446,6 @@ fn compile_routing(
crate::vhost::PathMatch::Regex | crate::vhost::PathMatch::RegexInsensitive
)
{
// Regular expressions are tried in list order, so a conditional copy of an
// earlier unconditional pattern could never be reached.
ensure!(
!path_bindings.contains(&(route.match_type, route.path_prefix.clone())),
"location {}: an earlier location without conditions already uses this regular expression, so this one would never match; move it above that location",
@@ -454,6 +469,25 @@ fn compile_routing(
};
let acl = route.acl.as_ref().map(Acl::compile).transpose()?;
let headers = route.headers.compile()?;
let policy = Arc::new(route.policy.compile()?);
ensure!(
!policy.has_stage(crate::policy::Stage::PreRoute),
"pre_route policy belongs to global or vhost scope, not a location"
);
for id in policy.backend_ids() {
ensure!(
route.source.is_reverse_proxy()
&& route.response.is_none()
&& route.redirect.is_none()
&& host.backends.iter().any(|backend| backend.id == id)
&& (route.backend_ids.is_empty()
|| route.backend_ids.iter().any(|backend| backend == id)),
"vhost {} location {} policy references an unavailable backend {}",
host.id,
route.id,
id
);
}
if route.source.is_reverse_proxy() {
if let Some(id) = &route.backend_id {
ensure!(
@@ -464,22 +498,22 @@ fn compile_routing(
}
}
if host.enabled && route.enabled {
let (source, route_pool, backend) =
if route.response.is_some() || route.redirect.is_some() {
(CompiledSource::ReverseProxy, None, None)
} else {
match &route.source {
crate::vhost::Source::ReverseProxy => {
let pool = pool.as_ref().ok_or_else(|| {
anyhow::anyhow!(
let (source, route_pool, backend) = if route.response.is_some()
|| route.redirect.is_some()
{
(CompiledSource::ReverseProxy, None, None)
} else {
match &route.source {
crate::vhost::Source::ReverseProxy => {
let pool = pool.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"vhost {} location {} Reverse Proxy source has no backend pool",
host.id,
route.id
)
})?;
let pool = if route.backend_ids.is_empty()
&& route.load_balancing.is_none()
{
})?;
let pool =
if route.backend_ids.is_empty() && route.load_balancing.is_none() {
pool.clone()
} else {
Arc::new(
@@ -488,37 +522,35 @@ fn compile_routing(
&route.backend_ids,
route.load_balancing.as_ref(),
)
.with_context(|| {
format!("vhost {} location {}", host.id, route.id)
})?,
.with_context(
|| format!("vhost {} location {}", host.id, route.id),
)?,
)
};
let backend = if let Some(id) = route.backend_id.as_deref() {
pool.members
.iter()
.find(|member| member.definition.id == id)
.map(|member| member.backend.clone())
.ok_or_else(|| anyhow::anyhow!("unknown backend {id}"))?
} else {
pool.members[0].backend.clone()
};
(CompiledSource::ReverseProxy, Some(pool), Some(backend))
}
crate::vhost::Source::WebServer { web_service_id } => (
CompiledSource::WebServer(web_services[web_service_id].clone()),
None,
None,
),
let backend = if let Some(id) = route.backend_id.as_deref() {
pool.members
.iter()
.find(|member| member.definition.id == id)
.map(|member| member.backend.clone())
.ok_or_else(|| anyhow::anyhow!("unknown backend {id}"))?
} else {
pool.members[0].backend.clone()
};
(CompiledSource::ReverseProxy, Some(pool), Some(backend))
}
};
crate::vhost::Source::WebServer { web_service_id } => (
CompiledSource::WebServer(web_services[web_service_id].clone()),
None,
None,
),
}
};
let compiled = Arc::new(CompiledRoute {
conditions: route_conditions,
backend_id: route.backend_id.clone(),
bindings: frontend.bindings.clone(),
frontend: Some(frontend.clone()),
pool: route_pool,
// Responses of a conditional location depend on request attributes
// outside the cache key, so they are never cached.
cache: if route.conditions.is_empty() {
route.cache
} else {
@@ -543,6 +575,7 @@ fn compile_routing(
country_access: route.country_access.clone(),
method_policy: route.method_policy.clone(),
headers,
policy,
unavailable: false,
});
for name in &routing_hosts {
+26 -6
View File
@@ -1,4 +1,28 @@
impl Snapshot {
pub fn http_policy_statistics(&self) -> serde_json::Value {
let mut scopes = Vec::new();
scopes.push(serde_json::json!({"scope":"global", "rules":self.policy.stats()}));
let mut seen = std::collections::BTreeSet::new();
for frontend in self.frontends.values().flatten() {
if seen.insert(frontend.id.clone()) && !frontend.policy.is_empty() {
scopes.push(serde_json::json!({"scope":"vhost", "vhost":frontend.id, "rules":frontend.policy.stats()}));
}
}
seen.clear();
for route in self.routes.values().flatten() {
if seen.insert(route.id.clone()) && !route.policy.is_empty() {
scopes.push(serde_json::json!({"scope":"location", "vhost":route.frontend.as_ref().map(|frontend| &frontend.id),
"location":route.name, "rules":route.policy.stats()}));
}
}
scopes.sort_by_key(|scope| {
format!(
"{}:{}:{}",
scope["scope"], scope["vhost"], scope["location"]
)
});
serde_json::json!({"revision":self.envelope.revision,"scopes":scopes})
}
fn find_host_pattern<T>(host: &str, mut lookup: impl FnMut(&str) -> Option<T>) -> Option<T> {
if let Some(value) = lookup(host) {
return Some(value);
@@ -74,7 +98,7 @@ impl Snapshot {
) -> Option<&Arc<CompiledRoute>> {
self.select_on_request(host, path, local, tls, None)
}
/// Route selection with request facts, so locations with conditions can match.
pub fn select_on_request(
&self,
host: &str,
@@ -290,11 +314,7 @@ fn host_pattern_rank(pattern: &str, host: &str) -> usize {
pattern.len()
}
}
/// Location selection. Order: exact → prefix-priority → regex and any-path rules (list
/// order) → longest prefix. A location with `conditions` is a candidate only when all of
/// them hold for `request`; without request facts (cache refresh, early response
/// handling) conditional locations are skipped. Among equal candidates a conditional
/// location wins over an unconditional one (exact paths, prefixes of equal length).
fn select_route<'a, F>(
routes: &'a [Arc<CompiledRoute>],
path: &str,