v0.41.0
This commit is contained in:
1 parent
27b640a0df
commit
aa27866531
46 files changed
+3368
-189
No files matched your search
@@ -244,6 +244,8 @@ 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>,
|
||||
pub frontend: Option<Arc<CompiledFrontend>>,
|
||||
@@ -272,6 +274,11 @@ pub struct CompiledRoute {
|
||||
}
|
||||
#[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 route_conditions_country: bool,
|
||||
pub websockets: bool,
|
||||
pub websocket_legacy_support: bool,
|
||||
pub websocket_rfc8441: bool,
|
||||
|
||||
+60
-7
@@ -235,6 +235,17 @@ fn compile_routing(
|
||||
.map(|entry| (entry.acl.clone(), entry.countries.clone()))
|
||||
.unwrap_or_else(|| (None, crate::rate_limit::CountryAccess::default()));
|
||||
let frontend = Arc::new(CompiledFrontend {
|
||||
conditional_routes: host
|
||||
.routes
|
||||
.iter()
|
||||
.any(|route| route.enabled && !route.conditions.is_empty()),
|
||||
route_conditions_country: host.routes.iter().any(|route| {
|
||||
route.enabled
|
||||
&& route
|
||||
.conditions
|
||||
.iter()
|
||||
.any(|c| c.source == crate::vhost::ConditionSource::Country)
|
||||
}),
|
||||
metrics,
|
||||
websockets: host.websockets,
|
||||
websocket_legacy_support: host.websocket_legacy_support,
|
||||
@@ -315,6 +326,7 @@ fn compile_routing(
|
||||
),
|
||||
};
|
||||
let fallback = Arc::new(CompiledRoute {
|
||||
conditions: None,
|
||||
backend_id: None,
|
||||
bindings: frontend.bindings.clone(),
|
||||
frontend: Some(frontend.clone()),
|
||||
@@ -395,13 +407,35 @@ fn compile_routing(
|
||||
normalize_prefix(&mut route.path_prefix)?;
|
||||
None
|
||||
}
|
||||
crate::vhost::PathMatch::Any => {
|
||||
route.path_prefix = "/".into();
|
||||
None
|
||||
}
|
||||
};
|
||||
if !route.internal {
|
||||
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())),
|
||||
"location {}: another location already uses the same path and match type",
|
||||
route.id
|
||||
);
|
||||
} else if !route.internal
|
||||
&& matches!(
|
||||
route.match_type,
|
||||
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",
|
||||
route.id
|
||||
);
|
||||
}
|
||||
validate_route_rewrite(route, path_regex.as_ref())?;
|
||||
validate_location_response(route.response.as_ref())?;
|
||||
@@ -443,6 +477,22 @@ fn compile_routing(
|
||||
route.id
|
||||
)
|
||||
})?;
|
||||
let pool = if route.backend_ids.is_empty()
|
||||
&& route.load_balancing.is_none()
|
||||
{
|
||||
pool.clone()
|
||||
} else {
|
||||
Arc::new(
|
||||
pool.derive(
|
||||
&route.id,
|
||||
&route.backend_ids,
|
||||
route.load_balancing.as_ref(),
|
||||
)
|
||||
.with_context(|| {
|
||||
format!("vhost {} location {}", host.id, route.id)
|
||||
})?,
|
||||
)
|
||||
};
|
||||
let backend = if let Some(id) = route.backend_id.as_deref() {
|
||||
pool.members
|
||||
.iter()
|
||||
@@ -452,11 +502,7 @@ fn compile_routing(
|
||||
} else {
|
||||
pool.members[0].backend.clone()
|
||||
};
|
||||
(
|
||||
CompiledSource::ReverseProxy,
|
||||
Some(pool.clone()),
|
||||
Some(backend),
|
||||
)
|
||||
(CompiledSource::ReverseProxy, Some(pool), Some(backend))
|
||||
}
|
||||
crate::vhost::Source::WebServer { web_service_id } => (
|
||||
CompiledSource::WebServer(web_services[web_service_id].clone()),
|
||||
@@ -466,11 +512,18 @@ fn compile_routing(
|
||||
}
|
||||
};
|
||||
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,
|
||||
cache: route.cache,
|
||||
// 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 {
|
||||
Some(false)
|
||||
},
|
||||
name: route.id.clone(),
|
||||
id: format!("{}/{}", host.id, route.id),
|
||||
internal: route.internal,
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
#[cfg(test)]
|
||||
mod routing_conditions_tests {
|
||||
use super::*;
|
||||
|
||||
const FIXTURE: &str = include_str!("../../tests/fixtures/routing_conditions_cases.json");
|
||||
|
||||
fn policy() -> ValidationPolicy {
|
||||
ValidationPolicy {
|
||||
proxy_addr: "127.0.0.1:8080".parse().unwrap(),
|
||||
admin_addr: "127.0.0.1:9090".parse().unwrap(),
|
||||
tls_addr: None,
|
||||
cert_dir: None,
|
||||
data_dir: None,
|
||||
}
|
||||
}
|
||||
fn config(vhost: serde_json::Value) -> anyhow::Result<Snapshot> {
|
||||
let cfg = serde_json::from_value(serde_json::json!({
|
||||
"listeners":{"endpoints":[{"id":"http","binding":{"address":"127.0.0.1:8080"}}]},
|
||||
"vhosts":[vhost]
|
||||
}))?;
|
||||
compile(cfg, 0, &policy())
|
||||
}
|
||||
|
||||
/// Shared with tools/dev/test_routing_tester.js (panel tester parity).
|
||||
#[test]
|
||||
fn fixture_cases_select_the_expected_location() {
|
||||
let fixture: serde_json::Value = serde_json::from_str(FIXTURE).unwrap();
|
||||
let snapshot = config(fixture["vhost"].clone()).unwrap();
|
||||
let local: std::net::SocketAddr = "127.0.0.1:8080".parse().unwrap();
|
||||
for case in fixture["cases"].as_array().unwrap() {
|
||||
let name = case["name"].as_str().unwrap();
|
||||
let method: http::Method = case["method"].as_str().unwrap_or("GET").parse().unwrap();
|
||||
let host = case["host"].as_str().unwrap_or("site.test");
|
||||
let path = case["path"].as_str().unwrap();
|
||||
let mut headers = http::HeaderMap::new();
|
||||
if let Some(map) = case["headers"].as_object() {
|
||||
for (key, value) in map {
|
||||
headers.insert(
|
||||
http::HeaderName::from_bytes(key.as_bytes()).unwrap(),
|
||||
value.as_str().unwrap().parse().unwrap(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let facts = crate::vhost::RouteRequest {
|
||||
method: &method,
|
||||
headers: &headers,
|
||||
query: case["query"].as_str(),
|
||||
host,
|
||||
client_ip: case["client_ip"].as_str().unwrap_or("203.0.113.5").parse().unwrap(),
|
||||
country: case["country"].as_str(),
|
||||
};
|
||||
let route = snapshot
|
||||
.select_on_request(host, path, local, false, Some(&facts))
|
||||
.unwrap_or_else(|| panic!("{name}: no route"));
|
||||
assert_eq!(route.name, case["expect"].as_str().unwrap(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conditional_locations_are_skipped_without_request_facts_and_never_cached() {
|
||||
let fixture: serde_json::Value = serde_json::from_str(FIXTURE).unwrap();
|
||||
let snapshot = config(fixture["vhost"].clone()).unwrap();
|
||||
let local: std::net::SocketAddr = "127.0.0.1:8080".parse().unwrap();
|
||||
let route = snapshot.select_on("site.test", "/api/x", local, false).unwrap();
|
||||
assert_eq!(route.name, "api");
|
||||
let route = snapshot.select_on("site.test", "/a.mp3", local, false).unwrap();
|
||||
assert_eq!(route.name, "mp3");
|
||||
let frontend = snapshot.frontend("site.test", local, false).unwrap();
|
||||
assert!(frontend.conditional_routes);
|
||||
assert!(frontend.route_conditions_country);
|
||||
let fixture_routes = fixture["vhost"]["routes"].as_array().unwrap();
|
||||
let conditional = fixture_routes
|
||||
.iter()
|
||||
.filter(|r| r.get("conditions").is_some())
|
||||
.count();
|
||||
assert!(conditional >= 5);
|
||||
// A conditional location never uses the cache.
|
||||
let headers = {
|
||||
let mut h = http::HeaderMap::new();
|
||||
h.insert("x-beta", "1".parse().unwrap());
|
||||
h
|
||||
};
|
||||
let facts = crate::vhost::RouteRequest {
|
||||
method: &http::Method::GET,
|
||||
headers: &headers,
|
||||
query: None,
|
||||
host: "site.test",
|
||||
client_ip: "203.0.113.5".parse().unwrap(),
|
||||
country: None,
|
||||
};
|
||||
let beta = snapshot
|
||||
.select_on_request("site.test", "/api/x", local, false, Some(&facts))
|
||||
.unwrap();
|
||||
assert_eq!(beta.name, "api-beta");
|
||||
assert_eq!(beta.cache, Some(false));
|
||||
assert_eq!(beta.pool.as_ref().unwrap().members.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_conditions_are_rejected() {
|
||||
let vhost = |routes: serde_json::Value| {
|
||||
serde_json::json!({
|
||||
"id":"v","frontend":{"hosts":["v.test"],"listener_ids":["http"]},
|
||||
"backends":[{"id":"a","url":"http://127.0.0.1:9001","allow_private":true}],
|
||||
"load_balancing":{"health_check":{"mode":"off"}},
|
||||
"routes":routes
|
||||
})
|
||||
};
|
||||
for routes in [
|
||||
serde_json::json!([{"id":"x","match_type":"any"}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"header","values":["1"]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"header","name":"bad name","values":["1"]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"ip","values":["10.0.0.0/8"]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"ip","operator":"cidr","values":["nope"]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"method","operator":"prefix","values":["GE"]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"country","values":["POL"]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"header","name":"a","operator":"exists","values":["1"]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"header","name":"a","operator":"regex","values":["("]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"header","name":"a","values":[]}]}]),
|
||||
serde_json::json!([{"id":"x","path_prefix":"/x","cache":true,"conditions":[{"source":"method","values":["GET"]}]}]),
|
||||
serde_json::json!([{"id":"x","internal":true,"conditions":[{"source":"method","values":["GET"]}]}]),
|
||||
serde_json::json!([
|
||||
{"id":"x","match_type":"regex","path_prefix":"\\.js$"},
|
||||
{"id":"y","match_type":"regex","path_prefix":"\\.js$","conditions":[{"source":"method","values":["GET"]}]}
|
||||
]),
|
||||
serde_json::json!([
|
||||
{"id":"x","path_prefix":"/x"},
|
||||
{"id":"y","path_prefix":"/x"}
|
||||
]),
|
||||
] {
|
||||
assert!(config(vhost(routes.clone())).is_err(), "{routes} should be rejected");
|
||||
}
|
||||
// A conditional copy before the unconditional regex is fine, and two
|
||||
// conditional prefixes may share a path.
|
||||
assert!(config(vhost(serde_json::json!([
|
||||
{"id":"y","match_type":"regex","path_prefix":"\\.js$","conditions":[{"source":"method","values":["GET"]}]},
|
||||
{"id":"x","match_type":"regex","path_prefix":"\\.js$"},
|
||||
{"id":"p1","path_prefix":"/p","conditions":[{"source":"header","name":"a","operator":"exists"}]},
|
||||
{"id":"p2","path_prefix":"/p","conditions":[{"source":"header","name":"b","operator":"exists"}]}
|
||||
])))
|
||||
.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_routes_serialize_without_new_fields() {
|
||||
let route: crate::vhost::PathRoute =
|
||||
serde_json::from_value(serde_json::json!({"id":"a","path_prefix":"/a"})).unwrap();
|
||||
let value = serde_json::to_value(&route).unwrap();
|
||||
for key in ["conditions", "backend_ids", "load_balancing"] {
|
||||
assert!(value.get(key).is_none(), "{key} should be omitted");
|
||||
}
|
||||
let condition: crate::vhost::RouteCondition = serde_json::from_value(
|
||||
serde_json::json!({"source":"header","name":"X-A","values":["1"]}),
|
||||
)
|
||||
.unwrap();
|
||||
let value = serde_json::to_value(&condition).unwrap();
|
||||
assert!(value.get("negate").is_none() && value.get("ignore_case").is_none());
|
||||
}
|
||||
}
|
||||
+70
-27
@@ -71,6 +71,17 @@ impl Snapshot {
|
||||
path: &str,
|
||||
local: SocketAddr,
|
||||
tls: bool,
|
||||
) -> 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,
|
||||
path: &str,
|
||||
local: SocketAddr,
|
||||
tls: bool,
|
||||
request: Option<&crate::vhost::RouteRequest<'_>>,
|
||||
) -> Option<&Arc<CompiledRoute>> {
|
||||
Self::find_host_pattern(host, |pattern| {
|
||||
let fallback = self.fallbacks.get(pattern).and_then(|routes| {
|
||||
@@ -81,9 +92,12 @@ impl Snapshot {
|
||||
self.routes
|
||||
.get(pattern)
|
||||
.and_then(|routes| {
|
||||
select_route(routes, path, |r| {
|
||||
r.bindings.iter().any(|l| l.matches(local, tls))
|
||||
})
|
||||
select_route(
|
||||
routes,
|
||||
path,
|
||||
|r| r.bindings.iter().any(|l| l.matches(local, tls)),
|
||||
request,
|
||||
)
|
||||
})
|
||||
.or(Some(fallback))
|
||||
})
|
||||
@@ -263,7 +277,7 @@ impl Snapshot {
|
||||
.and_then(|routes| routes.first())?;
|
||||
self.routes
|
||||
.get(pattern)
|
||||
.and_then(|routes| select_route(routes, path, |_| true))
|
||||
.and_then(|routes| select_route(routes, path, |_| true, None))
|
||||
.or(Some(fallback))
|
||||
.map(Arc::as_ref)
|
||||
})
|
||||
@@ -276,48 +290,77 @@ 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,
|
||||
allowed: F,
|
||||
request: Option<&crate::vhost::RouteRequest<'_>>,
|
||||
) -> Option<&'a Arc<CompiledRoute>>
|
||||
where
|
||||
F: Fn(&CompiledRoute) -> bool,
|
||||
{
|
||||
if let Some(exact) = routes.iter().find(|route| {
|
||||
let usable = |route: &CompiledRoute| {
|
||||
!route.internal
|
||||
&& allowed(route)
|
||||
&& route.match_type == crate::vhost::PathMatch::Exact
|
||||
&& route
|
||||
.conditions
|
||||
.as_ref()
|
||||
.is_none_or(|conditions| request.is_some_and(|r| conditions.matches(r)))
|
||||
};
|
||||
let exact = |route: &&Arc<CompiledRoute>| {
|
||||
route.match_type == crate::vhost::PathMatch::Exact
|
||||
&& route.path_prefix == path
|
||||
}) {
|
||||
&& usable(route)
|
||||
};
|
||||
if let Some(exact) = routes
|
||||
.iter()
|
||||
.filter(|route| route.conditions.is_some())
|
||||
.find(exact)
|
||||
.or_else(|| routes.iter().find(exact))
|
||||
{
|
||||
return Some(exact);
|
||||
}
|
||||
let prefix = routes
|
||||
.iter()
|
||||
.filter(|route| {
|
||||
!route.internal
|
||||
&& allowed(route)
|
||||
&& matches!(
|
||||
route.match_type,
|
||||
crate::vhost::PathMatch::Prefix | crate::vhost::PathMatch::PrefixPriority
|
||||
)
|
||||
&& prefix_matches(&route.path_prefix, path)
|
||||
})
|
||||
.max_by_key(|route| route.path_prefix.len());
|
||||
let mut prefix: Option<&Arc<CompiledRoute>> = None;
|
||||
for route in routes {
|
||||
if !matches!(
|
||||
route.match_type,
|
||||
crate::vhost::PathMatch::Prefix | crate::vhost::PathMatch::PrefixPriority
|
||||
) || !prefix_matches(&route.path_prefix, path)
|
||||
|| !usable(route)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let better = match prefix {
|
||||
None => true,
|
||||
Some(best) => {
|
||||
route.path_prefix.len() > best.path_prefix.len()
|
||||
|| (route.path_prefix.len() == best.path_prefix.len()
|
||||
&& route.conditions.is_some()
|
||||
&& best.conditions.is_none())
|
||||
}
|
||||
};
|
||||
if better {
|
||||
prefix = Some(route);
|
||||
}
|
||||
}
|
||||
if prefix.is_some_and(|route| route.match_type == crate::vhost::PathMatch::PrefixPriority) {
|
||||
return prefix;
|
||||
}
|
||||
if let Some(regex) = routes.iter().find(|route| {
|
||||
!route.internal
|
||||
&& allowed(route)
|
||||
&& matches!(
|
||||
route.match_type,
|
||||
crate::vhost::PathMatch::Regex | crate::vhost::PathMatch::RegexInsensitive
|
||||
)
|
||||
&& route
|
||||
let path_matches = match route.match_type {
|
||||
crate::vhost::PathMatch::Regex | crate::vhost::PathMatch::RegexInsensitive => route
|
||||
.path_regex
|
||||
.as_ref()
|
||||
.is_some_and(|regex| regex.is_match(path))
|
||||
.is_some_and(|regex| regex.is_match(path)),
|
||||
crate::vhost::PathMatch::Any => true,
|
||||
_ => false,
|
||||
};
|
||||
path_matches && usable(route)
|
||||
}) {
|
||||
return Some(regex);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user