Files
RustProxy/src/policy/compile.rs
T
2026-11-28 17:36:53 +01:00

729 lines
25 KiB
Rust

use super::{
expression::{self, CompiledMap, Fetch, Sample, Template, ValueType},
*,
};
use anyhow::{ensure, Context as _, Result};
use http::HeaderName;
use regex::Regex;
use std::{
collections::{BTreeMap, HashSet},
sync::{
atomic::{AtomicU64, Ordering},
Arc,
},
};
#[derive(Debug, Clone)]
pub(super) enum Matcher {
Text(Operator, Vec<String>, bool),
Regex(Vec<Regex>),
Number(Operator, Vec<i64>),
Cidr(Vec<ipnet::IpNet>),
Exists,
}
impl Matcher {
pub fn test(&self, sample: &Sample) -> bool {
if matches!(sample, Sample::Invalid) {
return matches!(self, Self::Exists);
}
match self {
Self::Exists => true,
Self::Text(op, expected, fold) => {
let text = sample.text();
let text = if *fold {
text.to_ascii_lowercase()
} else {
text
};
expected.iter().any(|expected| match op {
Operator::Equals => text == *expected,
Operator::Contains => text.contains(expected),
Operator::Prefix => text.starts_with(expected),
Operator::Suffix => text.ends_with(expected),
_ => false,
})
}
Self::Regex(patterns) => {
let text = sample.text();
patterns.iter().any(|p| p.is_match(&text))
}
Self::Number(op, expected) => sample.integer().is_some_and(|actual| {
expected.iter().any(|n| match op {
Operator::Eq => actual == *n,
Operator::Ne => actual != *n,
Operator::Gt => actual > *n,
Operator::Ge => actual >= *n,
Operator::Lt => actual < *n,
Operator::Le => actual <= *n,
_ => false,
})
}),
Self::Cidr(nets) => sample
.text()
.parse::<std::net::IpAddr>()
.is_ok_and(|ip| nets.iter().any(|n| n.contains(&ip))),
}
}
}
#[derive(Debug, Clone)]
pub(super) enum Predicate {
All(Vec<Predicate>),
Any(Vec<Predicate>),
Not(Box<Predicate>),
Test(Fetch, Matcher),
}
impl Predicate {
pub fn matches(&self, ctx: &Context) -> bool {
match self {
Self::All(items) => items.iter().all(|item| item.matches(ctx)),
Self::Any(items) => items.iter().any(|item| item.matches(ctx)),
Self::Not(item) => !item.matches(ctx),
Self::Test(fetch, matcher) => fetch.samples(ctx).iter().any(|s| matcher.test(s)),
}
}
fn private(&self) -> bool {
match self {
Self::All(v) | Self::Any(v) => v.iter().any(Self::private),
Self::Not(v) => v.private(),
Self::Test(fetch, _) => fetch.private,
}
}
}
#[derive(Debug, Clone, Copy)]
pub(super) enum HeaderOp {
Set,
Append,
Remove,
Default,
Normalize,
Merge,
RemoveValue,
}
#[derive(Debug, Clone)]
pub(super) enum CompiledAction {
Header(HeaderOp, HeaderName, Option<Template>),
Replace(HeaderName, Regex, Template, bool),
SetVar(String, Template),
UnsetVar(String),
Path(Template),
Query(Template),
Backend(String),
Terminal(u16, Option<Template>, Option<Template>),
Pass,
Lookup,
NoStore,
Ttl(u64),
Grace(u64),
HashHeader(String),
DisableCompression,
Stop,
}
impl CompiledAction {
fn private(&self) -> bool {
match self {
Self::Header(_, _, Some(t)) | Self::Replace(_, _, t, _) | Self::SetVar(_, t) => {
t.private
}
_ => false,
}
}
pub fn label(&self) -> &'static str {
match self {
Self::Header(op, _, _) => match op {
HeaderOp::Set => "set_header",
HeaderOp::Append => "append_header",
HeaderOp::Remove => "remove_header",
HeaderOp::Default => "set_if_missing",
HeaderOp::Normalize => "normalize_header",
HeaderOp::Merge => "merge_header",
HeaderOp::RemoveValue => "remove_value",
},
Self::Replace(_, _, _, false) => "replace_header",
Self::Replace(_, _, _, true) => "replace_value",
Self::SetVar(..) => "set_var",
Self::UnsetVar(..) => "unset_var",
Self::Path(_) => "set_path",
Self::Query(_) => "set_query",
Self::Backend(_) => "use_backend",
Self::Terminal(_, _, Some(_)) => "redirect",
Self::Terminal(..) => "return",
Self::Pass => "pass",
Self::Lookup => "lookup",
Self::NoStore => "no_store",
Self::Ttl(_) => "set_ttl",
Self::Grace(_) => "set_grace",
Self::HashHeader(_) => "hash_header",
Self::DisableCompression => "disable_compression",
Self::Stop => "stop",
}
}
}
#[derive(Debug, Clone)]
pub(super) struct CompiledRule {
pub id: String,
pub stage: Stage,
pub condition: Predicate,
pub actions: Vec<CompiledAction>,
pub stop: bool,
pub matches: Arc<AtomicU64>,
pub errors: Arc<AtomicU64>,
}
#[derive(Debug, Clone, Default)]
pub struct CompiledPolicy {
pub(super) rules: Vec<CompiledRule>,
private_response: bool,
}
impl CompiledPolicy {
pub fn stats(&self) -> Vec<RuleStats> {
self.rules
.iter()
.map(|r| RuleStats {
id: r.id.clone(),
stage: r.stage,
matches: r.matches.load(Ordering::Relaxed),
errors: r.errors.load(Ordering::Relaxed),
})
.collect()
}
pub fn is_empty(&self) -> bool {
self.rules.is_empty()
}
pub fn has_stage(&self, stage: Stage) -> bool {
self.rules.iter().any(|r| r.stage == stage)
}
pub fn requires_private_response(&self) -> bool {
self.private_response
}
pub fn backend_ids(&self) -> Vec<&str> {
self.rules
.iter()
.flat_map(|r| &r.actions)
.filter_map(|a| match a {
CompiledAction::Backend(id) => Some(id.as_str()),
_ => None,
})
.collect()
}
}
pub(super) fn header_name(name: &str, stage: Stage) -> Result<HeaderName> {
ensure!(name.len() <= 128, "policy header name is too long");
let name: HeaderName = name.parse().context("invalid policy header name")?;
let text = name.as_str();
ensure!(
!matches!(
text,
"host"
| "connection"
| "content-length"
| "content-encoding"
| "content-range"
| "transfer-encoding"
| "te"
| "trailer"
| "upgrade"
| "keep-alive"
| "proxy-connection"
| "proxy-authorization"
| "proxy-authenticate"
| "forwarded"
| "x-real-ip"
| "x-request-id"
| "alt-svc"
| "date"
| "set-cookie"
) && !text.starts_with("x-forwarded-")
&& !text.starts_with("sec-")
&& !text.starts_with("x-rustproxy-")
&& !text.starts_with("x-rust-proxy-"),
"protected HTTP/identity header cannot be modified: {name}"
);
if !stage.response() {
ensure!(
!matches!(
text,
"authorization"
| "cookie"
| "cache-control"
| "pragma"
| "range"
| "x-client-ip"
| "true-client-ip"
| "cf-connecting-ip"
| "content-type"
| "expect"
| "via"
) && !text.starts_with("if-")
&& !text.starts_with("proxy-"),
"request security/cache header cannot be modified: {name}"
);
}
ensure!(
stage != Stage::BackendResponse || text != "age",
"Age can only be changed at delivery"
);
Ok(name)
}
fn list_header(name: &HeaderName) -> Result<()> {
ensure!(matches!(name.as_str(), "vary" | "allow" | "accept-encoding" | "content-language" |
"access-control-allow-methods" | "access-control-allow-headers" | "access-control-expose-headers"),
"list operations are supported only for Vary, Allow, Accept-Encoding, Content-Language and CORS token lists");
Ok(())
}
#[derive(Default)]
struct CompileBudget {
nodes: usize,
regexes: usize,
}
fn condition(
input: &Condition,
stage: Stage,
settings: &Settings,
maps: &BTreeMap<String, Arc<CompiledMap>>,
stack: &mut Vec<String>,
depth: usize,
budget: &mut CompileBudget,
) -> Result<Predicate> {
budget.nodes += 1;
ensure!(
depth <= 16 && budget.nodes <= 4096,
"policy condition expansion limit exceeded"
);
Ok(match input {
Condition::All { all } | Condition::Any { any: all } => {
ensure!(all.len() <= 32, "at most 32 children per condition group");
let items = all
.iter()
.map(|c| condition(c, stage, settings, maps, stack, depth + 1, budget))
.collect::<Result<_>>()?;
if matches!(input, Condition::All { .. }) {
Predicate::All(items)
} else {
Predicate::Any(items)
}
}
Condition::Not { not } => Predicate::Not(Box::new(condition(
not,
stage,
settings,
maps,
stack,
depth + 1,
budget,
)?)),
Condition::Acl { acl } => {
ensure!(expression::identifier(acl), "invalid ACL name");
ensure!(!stack.contains(acl), "cyclic policy ACL {acl}");
let target = settings
.acls
.get(acl)
.with_context(|| format!("unknown policy ACL {acl}"))?;
stack.push(acl.clone());
let result = condition(target, stage, settings, maps, stack, depth + 1, budget)?;
stack.pop();
result
}
Condition::Compare {
fetch,
operator,
values,
ignore_case,
} => {
ensure!(values.len() <= 64, "at most 64 values per policy condition");
for value in values {
expression::bounded(value, expression::MAX_REGEX, "condition value")?;
}
budget.regexes += fetch.matches("regsub(").count()
+ if *operator == Operator::Regex {
values.len()
} else {
0
};
ensure!(
budget.regexes <= 128,
"expanded conditions exceed 128 compiled regex patterns per scope"
);
let fetch = Fetch::compile(fetch, stage, maps)?;
ensure!(
(*operator == Operator::Exists) == values.is_empty(),
"exists takes no values; other operators need values"
);
let matcher = match operator {
Operator::Exists => Matcher::Exists,
Operator::Regex => Matcher::Regex(
values
.iter()
.map(|v| expression::regex(v, *ignore_case))
.collect::<Result<_>>()?,
),
Operator::Cidr => {
ensure!(
fetch.kind == ValueType::Ip || fetch.kind == ValueType::String,
"cidr needs an IP/string sample"
);
Matcher::Cidr(
values
.iter()
.map(|v| {
v.parse::<ipnet::IpNet>()
.or_else(|_| {
v.parse::<std::net::IpAddr>().map(ipnet::IpNet::from)
})
.map(|v| v.trunc())
.context("invalid policy IP/CIDR")
})
.collect::<Result<_>>()?,
)
}
Operator::Eq
| Operator::Ne
| Operator::Gt
| Operator::Ge
| Operator::Lt
| Operator::Le => {
ensure!(
matches!(fetch.kind, ValueType::Integer | ValueType::Boolean),
"numeric operator requires an integer/boolean sample"
);
ensure!(
values.len() == 1 || *operator == Operator::Eq,
"numeric inequalities need exactly one value"
);
ensure!(
!ignore_case,
"ignore_case is not valid for numeric comparisons"
);
Matcher::Number(
*operator,
values
.iter()
.map(|v| v.parse().context("invalid integer comparison"))
.collect::<Result<_>>()?,
)
}
_ => {
ensure!(
fetch.kind == ValueType::String,
"string operator requires a string sample"
);
Matcher::Text(
*operator,
values
.iter()
.map(|v| {
if *ignore_case {
v.to_ascii_lowercase()
} else {
v.clone()
}
})
.collect(),
*ignore_case,
)
}
};
Predicate::Test(fetch, matcher)
}
})
}
fn action(
action: &Action,
stage: Stage,
maps: &BTreeMap<String, Arc<CompiledMap>>,
) -> Result<CompiledAction> {
let template = |value: &str| Template::compile(value, stage, maps);
let header = |op, name: &str, value: Option<&str>| -> Result<_> {
let name = header_name(name, stage)?;
if matches!(
op,
HeaderOp::Normalize | HeaderOp::Merge | HeaderOp::RemoveValue
) {
list_header(&name)?;
}
Ok(CompiledAction::Header(
op,
name,
value.map(template).transpose()?,
))
};
Ok(match action {
Action::SetHeader { name, value } => header(HeaderOp::Set, name, Some(value))?,
Action::AppendHeader { name, value } => header(HeaderOp::Append, name, Some(value))?,
Action::RemoveHeader { name } => header(HeaderOp::Remove, name, None)?,
Action::SetIfMissing { name, value } => header(HeaderOp::Default, name, Some(value))?,
Action::NormalizeHeader { name } => header(HeaderOp::Normalize, name, None)?,
Action::MergeHeader { name, value } => header(HeaderOp::Merge, name, Some(value))?,
Action::RemoveValue { name, value } => header(HeaderOp::RemoveValue, name, Some(value))?,
Action::ReplaceHeader {
name,
pattern,
replacement,
}
| Action::ReplaceValue {
name,
pattern,
replacement,
} => CompiledAction::Replace(
header_name(name, stage)?,
expression::regex(pattern, false)?,
template(replacement)?,
matches!(action, Action::ReplaceValue { .. }),
),
Action::SetVar { name, value } => {
ensure!(
expression::variable(name),
"only named txn.* variables are writable"
);
CompiledAction::SetVar(name.clone(), template(value)?)
}
Action::UnsetVar { name } => {
ensure!(
expression::variable(name),
"only named txn.* variables are writable"
);
CompiledAction::UnsetVar(name.clone())
}
Action::SetPath { value } | Action::SetQuery { value } => {
ensure!(
stage == Stage::PreRoute,
"path/query rewrites are permitted only before routing and access checks"
);
if matches!(action, Action::SetPath { .. }) {
CompiledAction::Path(template(value)?)
} else {
CompiledAction::Query(template(value)?)
}
}
Action::UseBackend { id } => {
ensure!(
matches!(stage, Stage::PreRoute | Stage::Request),
"backend selection must precede cache and upstream dispatch"
);
ensure!(
expression::identifier(id),
"backend action requires a literal configured backend ID"
);
CompiledAction::Backend(id.clone())
}
Action::Deny { status } => {
ensure!(
matches!(stage, Stage::PreRoute | Stage::Request),
"deny is a request action"
);
ensure!((400..=599).contains(status), "deny status must be 400..599");
CompiledAction::Terminal(*status, None, None)
}
Action::Return { status, body } => {
ensure!(
stage == Stage::Request,
"return requires the request stage after location access/authentication checks"
);
ensure!(
(200..=599).contains(status) && !matches!(status, 204 | 304),
"return status must permit a response body (200..599 except 204/304)"
);
CompiledAction::Terminal(*status, Some(template(body)?), None)
}
Action::Redirect { status, location } => {
ensure!(
stage == Stage::Request,
"redirect requires the request stage after location access/authentication checks"
);
ensure!(
matches!(status, 301 | 302 | 303 | 307 | 308),
"invalid redirect status"
);
CompiledAction::Terminal(*status, None, Some(template(location)?))
}
Action::Pass | Action::Lookup | Action::HashHeader { .. } => {
ensure!(
matches!(stage, Stage::PreRoute | Stage::Request),
"cache lookup decisions must precede lookup"
);
match action {
Action::Pass => CompiledAction::Pass,
Action::Lookup => CompiledAction::Lookup,
Action::HashHeader { name } => {
let name: HeaderName = name.parse().context("invalid cache hash header")?;
CompiledAction::HashHeader(name.as_str().into())
}
_ => unreachable!(),
}
}
Action::NoStore => {
ensure!(
matches!(
stage,
Stage::PreRoute | Stage::Request | Stage::BackendResponse
),
"no_store must run before cache admission"
);
CompiledAction::NoStore
}
Action::SetTtl { seconds } | Action::SetGrace { seconds } => {
ensure!(
stage == Stage::BackendResponse,
"TTL/grace require backend_response stage"
);
ensure!(*seconds <= 365 * 86400, "TTL/grace is limited to one year");
if matches!(action, Action::SetTtl { .. }) {
CompiledAction::Ttl(*seconds)
} else {
CompiledAction::Grace(*seconds)
}
}
Action::DisableCompression => {
ensure!(
stage != Stage::AfterResponse,
"compression cannot be disabled after encoding"
);
CompiledAction::DisableCompression
}
Action::Stop => CompiledAction::Stop,
})
}
pub(super) fn compile(settings: &Settings) -> Result<CompiledPolicy> {
ensure!(
settings.rules.len() <= 128 && settings.acls.len() <= 128 && settings.maps.len() <= 16,
"policy limits: 128 rules, 128 named ACLs, 16 maps per scope"
);
let serialized = serde_json::to_string(settings)?;
ensure!(
serialized.len() <= 256 * 1024,
"policy configuration exceeds 256 KiB"
);
ensure!(
settings
.maps
.values()
.map(|m| m.entries.len())
.sum::<usize>()
<= 1024,
"at most 1024 policy map entries per scope"
);
fn regex_count(c: &Condition) -> usize {
match c {
Condition::All { all } | Condition::Any { any: all } => {
all.iter().map(regex_count).sum()
}
Condition::Not { not } => regex_count(not),
Condition::Compare {
operator: Operator::Regex,
values,
..
} => values.len(),
_ => 0,
}
}
let regex_count = settings.acls.values().map(regex_count).sum::<usize>()
+ settings
.rules
.iter()
.map(|r| {
regex_count(&r.when)
+ r.actions
.iter()
.filter(|a| {
matches!(
a,
Action::ReplaceHeader { .. } | Action::ReplaceValue { .. }
)
})
.count()
})
.sum::<usize>()
+ settings
.maps
.values()
.filter(|m| matches!(m.kind, MapKind::Regex))
.map(|m| m.entries.len())
.sum::<usize>()
+ serialized.matches("regsub(").count();
ensure!(
regex_count <= 128,
"at most 128 regex patterns per policy scope"
);
let mut maps = BTreeMap::new();
for (name, definition) in &settings.maps {
ensure!(
expression::identifier(name),
"invalid policy map name {name:?}"
);
maps.insert(
name.clone(),
Arc::new(CompiledMap::compile(definition).with_context(|| format!("map {name}"))?),
);
}
for (name, acl) in &settings.acls {
ensure!(
expression::identifier(name),
"invalid policy ACL name {name:?}"
);
condition(
acl,
Stage::AfterResponse,
settings,
&maps,
&mut vec![name.clone()],
0,
&mut CompileBudget::default(),
)
.with_context(|| format!("ACL {name}"))?;
}
let mut result = CompiledPolicy::default();
let mut ids = HashSet::new();
let mut budget = CompileBudget::default();
for rule in &settings.rules {
ensure!(
expression::identifier(&rule.id) && ids.insert(rule.id.clone()),
"policy rule IDs must be unique nonempty identifiers"
);
expression::bounded(&rule.name, 256, "rule name")?;
ensure!(
!rule.actions.is_empty() && rule.actions.len() <= 16,
"each policy rule needs 1..16 actions"
);
let when = condition(
&rule.when,
rule.stage,
settings,
&maps,
&mut Vec::new(),
0,
&mut budget,
)
.with_context(|| format!("policy rule {} condition", rule.id))?;
let actions = rule
.actions
.iter()
.map(|a| {
action(a, rule.stage, &maps)
.with_context(|| format!("policy rule {} action", rule.id))
})
.collect::<Result<Vec<_>>>()?;
if !rule.enabled {
continue;
}
if rule.stage == Stage::BackendResponse
&& (when.private() || actions.iter().any(CompiledAction::private))
{
result.private_response = true;
}
result.rules.push(CompiledRule {
id: rule.id.clone(),
stage: rule.stage,
condition: when,
actions,
stop: rule.stop,
matches: Arc::new(AtomicU64::new(0)),
errors: Arc::new(AtomicU64::new(0)),
});
}
Ok(result)
}