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

+7
View File
@@ -8,6 +8,7 @@ enum ConfigSection {
Transform,
Forwarding,
Headers,
Policy,
Prometheus,
Geoip,
Administration,
@@ -37,6 +38,7 @@ impl ConfigSection {
"transform" => Some(Self::Transform),
"forwarding" => Some(Self::Forwarding),
"headers" => Some(Self::Headers),
"policy" => Some(Self::Policy),
"prometheus" => Some(Self::Prometheus),
"geoip" => Some(Self::Geoip),
"administration" => Some(Self::Administration),
@@ -67,6 +69,7 @@ impl ConfigSection {
Self::Transform => json!(&config.transform),
Self::Forwarding => json!(&config.forwarding),
Self::Headers => json!(&config.headers),
Self::Policy => json!(&config.policy),
Self::Prometheus => json!(&config.prometheus),
Self::Geoip => json!(&config.geoip_updates),
Self::Administration => json!(&config.administration),
@@ -128,6 +131,10 @@ impl ConfigSection {
config.forwarding =
serde_json::from_value(value).map_err(|error| invalid_section(name, error))?
}
Self::Policy => {
config.policy =
serde_json::from_value(value).map_err(|error| invalid_section(name, error))?
}
Self::Headers => {
config.headers =
serde_json::from_value(value).map_err(|error| invalid_section(name, error))?
+1
View File
@@ -17,6 +17,7 @@ pub(super) static READER_DOCUMENTS: &[(&str, &str, &str)] = &[
reader_doc!("docs/SCREENSHOTS.md", "guides"),
reader_doc!("docs/INSTALL.md", "guides"),
reader_doc!("docs/CONFIGURATION.md", "guides"),
reader_doc!("docs/POLICY.md", "guides"),
reader_doc!("docs/HEADLESS.md", "guides"),
reader_doc!("docs/VHOSTS.md", "guides"),
reader_doc!("docs/CUSTOM_LOCATIONS.md", "guides"),
+1
View File
@@ -10,6 +10,7 @@ mod tests {
.iter()
.any(|doc| doc["path"] == "docs/WEB_SERVER.md"));
assert!(documents.iter().any(|doc| doc["path"] == "docs/PHP_FPM.md"));
assert!(documents.iter().any(|doc| doc["path"] == "docs/POLICY.md"));
assert!(documents
.iter()
.any(|doc| doc["path"] == "docs/FEATURES.md"));
+1
View File
@@ -13,6 +13,7 @@ include!("file_logs.rs");
include!("file_log_search.rs");
include!("operations.rs");
include!("cache_rules.rs");
include!("policy.rs");
include!("alerts.rs");
include!("certificate_api.rs");
include!("certificates.rs");
+1541 -66
View File
File diff suppressed because it is too large. Load diff
+281
View File
@@ -0,0 +1,281 @@
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PolicyImportInput {
source: String,
}
async fn policy_import_haproxy(
Json(input): Json<PolicyImportInput>,
) -> Result<Json<crate::policy::ImportResult>, ApiError> {
crate::policy::import_haproxy(&input.source)
.map(Json)
.map_err(|error| ApiError(StatusCode::UNPROCESSABLE_ENTITY, format!("{error:#}")))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PolicyTestHeader {
name: String,
value: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PolicyTestRequest {
#[serde(default = "cache_rule_test_method")]
method: String,
#[serde(default)]
host: String,
path: String,
#[serde(default)]
query: Option<String>,
#[serde(default)]
headers: Vec<PolicyTestHeader>,
#[serde(default)]
client_ip: Option<String>,
#[serde(default)]
country: Option<String>,
#[serde(default)]
tls: bool,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PolicyTestResponse {
status: u16,
#[serde(default)]
headers: Vec<PolicyTestHeader>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PolicyTestInput {
policy: crate::policy::Settings,
stage: crate::policy::Stage,
request: PolicyTestRequest,
#[serde(default)]
response: Option<PolicyTestResponse>,
#[serde(default)]
variables: std::collections::BTreeMap<String, String>,
#[serde(default)]
cache_status: Option<String>,
#[serde(default)]
srv_id: Option<String>,
#[serde(default)]
srv_url: Option<String>,
#[serde(default)]
backend_time: Option<String>,
#[serde(default)]
location: Option<String>,
#[serde(default)]
vhost: Option<String>,
#[serde(default)]
req_id: Option<String>,
#[serde(default)]
lb_algorithm: Option<String>,
#[serde(default)]
hash_key: Option<String>,
}
fn policy_test_error(message: impl Into<String>) -> ApiError {
ApiError(StatusCode::UNPROCESSABLE_ENTITY, message.into())
}
fn policy_test_headers(input: Vec<PolicyTestHeader>) -> Result<http::HeaderMap, ApiError> {
if input.len() > 128
|| input
.iter()
.map(|header| header.name.len() + header.value.len())
.sum::<usize>()
> 64 * 1024
{
return Err(policy_test_error("test headers exceed 128 fields / 64 KiB"));
}
let mut headers = http::HeaderMap::new();
for item in input {
let name = http::HeaderName::from_bytes(item.name.as_bytes())
.map_err(|_| policy_test_error("invalid test header name"))?;
let value = http::HeaderValue::from_str(&item.value)
.map_err(|_| policy_test_error("invalid test header value"))?;
headers.append(name, value);
}
Ok(headers)
}
fn policy_headers_json(headers: &http::HeaderMap) -> Vec<Value> {
headers
.iter()
.map(|(name, value)| {
json!({
"name": name.as_str(), "value": value.to_str().unwrap_or("[non-text header]"),
})
})
.collect()
}
fn evaluate_policy_test(input: PolicyTestInput) -> Result<Value, ApiError> {
let policy = input
.policy
.compile()
.map_err(|error| policy_test_error(format!("{error:#}")))?;
let request = input.request;
if request.path.len() > 8192
|| request
.query
.as_ref()
.is_some_and(|query| query.len() > 8192)
|| !request.path.starts_with('/')
|| request.path.starts_with("//")
|| request.path.contains(['?', '#'])
|| crate::acl::routing_path_view(&request.path).is_err()
{
return Err(policy_test_error("invalid test request path"));
}
let method = http::Method::from_bytes(request.method.as_bytes())
.map_err(|_| policy_test_error("invalid test method"))?;
let host = if request.host.is_empty() {
"example.test".to_owned()
} else {
crate::config::request_host(&request.host)
.map_err(|_| policy_test_error("invalid test hostname"))?
};
let client_ip = request
.client_ip
.as_deref()
.filter(|value| !value.is_empty())
.map(|value| value.parse())
.transpose()
.map_err(|_| policy_test_error("invalid test client IP"))?;
if request.country.as_ref().is_some_and(|value| {
value.len() != 2 || !value.bytes().all(|byte| byte.is_ascii_alphabetic())
}) {
return Err(policy_test_error("test country must be a two-letter code"));
}
if input.variables.len() > 64
|| input.variables.iter().any(|(name, value)| {
name.len() > 128
|| !name.starts_with("txn.")
|| value.len() > 8192
|| value.chars().any(char::is_control)
})
|| input
.variables
.iter()
.map(|(name, value)| name.len() + value.len())
.sum::<usize>()
> 64 * 1024
{
return Err(policy_test_error(
"invalid or oversized transaction variables",
));
}
for value in [
&input.cache_status,
&input.srv_id,
&input.srv_url,
&input.backend_time,
&input.location,
&input.vhost,
&input.req_id,
&input.lb_algorithm,
&input.hash_key,
]
.into_iter()
.flatten()
{
if value.len() > 8192 || value.chars().any(char::is_control) {
return Err(policy_test_error("invalid or oversized test metadata"));
}
}
let mut context = crate::policy::Context {
request_headers: policy_test_headers(request.headers)?,
method: method.as_str().to_owned(),
path: request.path,
query: request.query,
host,
client_ip,
country: request.country.map(|value| value.to_ascii_uppercase()),
tls: request.tls,
variables: input.variables,
cache_status: input.cache_status,
srv_id: input.srv_id,
srv_url: input.srv_url,
backend_time: input.backend_time,
location: input.location,
vhost: input.vhost,
req_id: input.req_id,
lb_algorithm: input.lb_algorithm,
hash_key: input.hash_key,
..Default::default()
};
if let Some(response) = input.response {
if !(100..=599).contains(&response.status) {
return Err(policy_test_error("invalid test response status"));
}
context.status = Some(response.status);
context.response_headers = policy_test_headers(response.headers)?;
} else if input.stage.response() {
return Err(policy_test_error(
"a response is required to test a response stage",
));
}
let outcome = policy.apply(input.stage, &mut context, true);
Ok(json!({
"request": {"method": context.method, "host": context.host, "path": context.path,
"query": context.query, "headers": policy_headers_json(&context.request_headers)},
"response": context.status.map(|status| json!({"status":status,"headers":policy_headers_json(&context.response_headers)})),
"variables": context.variables,
"trace": outcome.trace, "terminal": outcome.terminal, "backend": outcome.backend,
"cache": outcome.cache, "disable_compression": outcome.disable_compression, "stopped": outcome.stopped,
"requires_private_response": policy.requires_private_response(),
"scope": "single_policy_stage",
}))
}
async fn policy_test(Json(input): Json<PolicyTestInput>) -> Result<Json<Value>, ApiError> {
evaluate_policy_test(input).map(Json)
}
async fn policy_stats(State(state): State<Arc<App>>) -> Json<Value> {
Json(state.config.load_full().http_policy_statistics())
}
#[cfg(test)]
mod policy_api_tests {
use super::*;
#[test]
fn tester_keeps_duplicate_header_fields_and_uses_runtime_engine() {
let input = serde_json::from_value(json!({
"policy": {"rules":[{"id":"vary","stage":"after_response", "when":{
"fetch":"res.fhdr_cnt(Vary)","operator":"eq","values":["2"]},
"actions":[{"type":"normalize_header","name":"Vary"}]}]},
"stage":"after_response", "request":{"path":"/"},
"response":{"status":200,"headers":[{"name":"Vary","value":"Accept-Encoding"},
{"name":"Vary","value":"Accept, Accept-Encoding"}]}
}))
.unwrap();
let result = evaluate_policy_test(input).unwrap();
assert_eq!(result["trace"][0]["matched"], true);
let headers = result["response"]["headers"].as_array().unwrap();
assert_eq!(headers.len(), 1);
assert!(headers[0]["value"]
.as_str()
.unwrap()
.to_ascii_lowercase()
.contains("accept"));
}
#[test]
fn tester_rejects_missing_response_and_unknown_configuration() {
let input = serde_json::from_value(
json!({"policy":{},"stage":"after_response","request":{"path":"/"}}),
)
.unwrap();
assert!(evaluate_policy_test(input).is_err());
assert!(serde_json::from_value::<PolicyTestInput>(
json!({"policy":{"unknown":1},"stage":"request","request":{"path":"/"}})
)
.is_err());
}
}
+95
View File
@@ -0,0 +1,95 @@
#[tokio::test]
async fn http_policy_endpoints_require_session_and_csrf_and_never_save_drafts() {
let (router, store, _dir, secret, csrf) = fixture().await;
let cookie = format!("{}={secret}", auth::COOKIE_NAME);
for (path, body) in [
(
"/api/policy/import-haproxy",
json!({"source":"http-after-response set-header X-Test yes"}),
),
(
"/api/policy/test",
json!({"policy":{},"stage":"request","request":{"path":"/"}}),
),
] {
let send = |cookie_value: Option<&str>, csrf_value: Option<&str>| {
let mut builder = request(path)
.method("POST")
.header("origin", "http://127.0.0.1:9090")
.header("x-rustproxy-request", "1")
.header("content-type", "application/json");
if let Some(cookie) = cookie_value {
builder = builder.header("cookie", cookie);
}
if let Some(csrf) = csrf_value {
builder = builder.header("x-csrf-token", csrf);
}
builder.body(Body::from(body.to_string())).unwrap()
};
let response = router.clone().oneshot(send(None, None)).await.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED, "{path}");
let response = router
.clone()
.oneshot(send(Some(&cookie), None))
.await
.unwrap();
assert_eq!(response.status(), StatusCode::FORBIDDEN, "{path}");
let response = router
.clone()
.oneshot(send(Some(&cookie), Some(&csrf)))
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK, "{path}");
assert!(!general_api_token_allowed(&Method::POST, path, "rw"));
}
let response = router
.clone()
.oneshot(
request("/api/config/policy")
.header("cookie", &cookie)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let current = json_body(response).await;
assert!(current.to_string().contains("\"rules\":[]"), "{current}");
let stats = router
.clone()
.oneshot(request("/api/policy/stats").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(stats.status(), StatusCode::UNAUTHORIZED);
let stats = router
.clone()
.oneshot(
request("/api/policy/stats")
.header("cookie", &cookie)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(stats.status(), StatusCode::OK);
assert!(json_body(stats).await["scopes"].is_array());
store.close().await;
}
#[test]
fn http_policy_openapi_matches_models_and_private_endpoints() {
let schema: Value = serde_json::from_str(include_str!("openapi.json")).unwrap();
for path in ["/api/policy/import-haproxy", "/api/policy/test"] {
assert_eq!(
schema["paths"][path]["post"]["security"],
json!([{"AdminSession":[]}])
);
}
for name in ["Config", "Vhost", "DockerAssignment"] {
assert_eq!(
schema["components"]["schemas"][name]["properties"]["policy"]["$ref"],
"#/components/schemas/HttpPolicy"
);
}
assert_eq!(schema["info"]["version"], env!("CARGO_PKG_VERSION"));
}
+10
View File
@@ -93,6 +93,7 @@ fn admin_app_javascript() -> &'static str {
include_str!("web/integrations.js"),
include_str!("web/acl-picker.js"),
include_str!("web/cache-rules.js"),
include_str!("web/policy.js"),
admin_vhosts_javascript(),
include_str!("web/web-server-profiles.js"),
include_str!("web/web-server.js"),
@@ -270,6 +271,15 @@ pub fn router(state: Arc<App>) -> Router {
"/api/cache/rules/import-vcl",
post(cache_rules_import_vcl).layer(DefaultBodyLimit::max(300 * 1024)),
)
.route(
"/api/policy/import-haproxy",
post(policy_import_haproxy).layer(DefaultBodyLimit::max(300 * 1024)),
)
.route(
"/api/policy/test",
post(policy_test).layer(DefaultBodyLimit::max(300 * 1024)),
)
.route("/api/policy/stats", get(policy_stats))
.route("/api/cache/bans/{id}", delete(cache_ban_delete))
.route("/api/tunnels", get(active_tunnels))
.route(
+1
View File
@@ -4793,4 +4793,5 @@ mod tests {
include!("certificate_inspection_tests.rs");
include!("preferences_tests.rs");
include!("policy_access_tests.rs");
}
+10
View File
@@ -1,4 +1,5 @@
let cacheRulesEditor = null, cacheRulesRendered = "";
let globalPolicyEditor = null, globalPolicyRendered = "";
function renderSettings() {
if (!envelope) return; const config = envelope.config; window.rustProxySettings?.render();
if (!settingsDirty.has("listeners-form")) window.rustProxyIntegrations?.renderListeners();
@@ -83,6 +84,14 @@ function renderSettings() {
$("error-log-status").textContent = errorSink ? `${t("loggingQueue")}: ${fmt(errorSink.queue_dropped)} ${t("loggingDropped")} / ${fmt(errorSink.written)} ${t("loggingSent")} / ${fmt(errorSink.errors)} ${t("errors")} · ${t("loggingCapacity")}: ${fmt(errorSink.queue_capacity)}` : "";
if (!settingsDirty.has("forwarding-form")) { $("trusted-proxies").value = (config.forwarding?.trusted_proxies || []).join("\n"); $("trusted-proto").checked = !!config.forwarding?.trust_forwarded_proto; }
if (!settingsDirty.has("headers-form")) { for (const direction of ["request", "response"]) renderHeaderRules(direction, config.headers?.[direction] || []); }
if (!settingsDirty.has("policy-form") && window.rustProxyPolicy) {
const policyJson = JSON.stringify(config.policy || {});
if (!globalPolicyEditor || policyJson !== globalPolicyRendered) {
globalPolicyEditor = window.rustProxyPolicy.create({ value: config.policy || {}, scope: "global", onChange: () => setSettingsDirty("policy-form") });
globalPolicyRendered = policyJson;
$("global-policy-rules-root")?.replaceChildren(globalPolicyEditor.node);
}
}
const global = config.global_security || {};
if (!settingsDirty.has("global-security-form")) {
const country = global.country_access || {}, methods = global.method_policy || {}, content = global.content_type_policy || {}, rate = global.rate_limit || {};
@@ -471,6 +480,7 @@ bindSettingsForm("error-log-form", next => {
}, "logging", selectLoggingSection);
bindSettingsForm("forwarding-form", next => { next.forwarding = { trusted_proxies: $("trusted-proxies").value.split(/[\n,]/).map(s => s.trim()).filter(Boolean), trust_forwarded_proto: $("trusted-proto").checked }; }, "forwarding");
bindSettingsForm("headers-form", next => { next.headers = { request: collectHeaderRules("request"), response: collectHeaderRules("response") }; }, "headers");
bindSettingsForm("policy-form", next => { next.policy = globalPolicyEditor ? globalPolicyEditor.read() : (next.policy || {}); }, "policy");
$("log-format-preset").addEventListener("change", event => applyLoggingPreset(event.target.value));
$("error-log-enabled").addEventListener("change", syncErrorLogMode);
$("log-format-open").addEventListener("click", openLoggingBuilder);
+158 -33
View File
@@ -40,14 +40,71 @@ window.rustProxyCacheRules = (() => {
return { id, name: t("cacheRuleNewName"), enabled: true, stage, match: "all", conditions: [], actions: [{ type: ACTIONS[stage][0] }], stop: false, vhosts: [] };
}
function normalize(rule) {
return { id: rule.id, name: rule.name || "", enabled: rule.enabled !== false, stage: rule.stage || "request", match: rule.match || "all", conditions: (rule.conditions || []).map(c => ({ ...c, values: [...(c.values || [])] })), actions: (rule.actions || []).map(a => ({ ...a })), stop: !!rule.stop, hash_stage: !!rule.hash_stage, vhosts: [...(rule.vhosts || [])] };
return { ...structuredClone(rule), id: rule.id, name: rule.name || "", enabled: rule.enabled !== false, stage: rule.stage || "request", match: rule.match || "all", conditions: (rule.conditions || []).map(c => ({ ...structuredClone(c), values: [...(c.values || [])] })), actions: structuredClone(rule.actions || []), stop: !!rule.stop, hash_stage: !!rule.hash_stage, vhosts: [...(rule.vhosts || [])] };
}
function clean(rule, global) {
const out = { id: rule.id, name: rule.name, enabled: rule.enabled, stage: rule.stage, match: rule.match, conditions: rule.conditions.map(c => { const item = { field: c.field, operator: c.operator, values: c.operator === "exists" ? [] : c.values }; if (FIELDS[c.field]?.name) item.name = c.name || ""; if (c.negate) item.negate = true; return item; }), actions: rule.actions.map(a => ({ ...a })), stop: rule.stop };
const out = { ...structuredClone(rule), id: rule.id, name: rule.name, enabled: rule.enabled, stage: rule.stage, match: rule.match, conditions: rule.conditions.map(c => { const item = { ...structuredClone(c), field: c.field, operator: c.operator, values: c.operator === "exists" ? [] : [...c.values] }; if (FIELDS[c.field]?.name) item.name = c.name || ""; if (c.negate) item.negate = true; return item; }), actions: structuredClone(rule.actions), stop: rule.stop };
delete out.hash_stage;
delete out.vhosts;
if (rule.hash_stage) out.hash_stage = true;
if (global && rule.vhosts.length) out.vhosts = rule.vhosts;
if (global && rule.vhosts.length) out.vhosts = [...rule.vhosts];
return out;
}
const flowMarker = rule => Array.isArray(rule.vcl_flow?.branches) && rule.vcl_flow.branches.length > 0;
function flowFailure(rule) { return new Error(t("cacheRulesFlowInvalid").replace("{rule}", rule?.name || rule?.id || "VCL")); }
// Structural checks only. Conditions/actions are evaluated and validated by
// Rust; this prevents UI operations from splitting or silently flattening a
// saved imported program before it reaches that compiler.
function validateFlow(rules) {
const groups = new Map();
rules.forEach((rule, position) => {
const flow = rule.vcl_flow;
if (!flow) return;
if (flow.version !== 1 || typeof flow.group !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(flow.group) ||
!Number.isInteger(flow.index) || flow.index < 0 || flow.index >= MAX_RULES || !Number.isInteger(flow.count) || flow.count < 1 || flow.count > MAX_RULES ||
!Array.isArray(flow.guards || []) || (flow.guards || []).length > 16 ||
!Array.isArray(flow.branches || []) || (flow.branches || []).length > 16) throw flowFailure(rule);
if (!groups.has(flow.group)) groups.set(flow.group, []);
groups.get(flow.group).push({ rule, position });
});
for (const members of groups.values()) {
const first = members[0], count = first.rule.vcl_flow.count;
if (members.length !== count) throw flowFailure(first.rule);
let conditionCount = 0;
const activeEntries = new Set(), lastBranches = new Map();
members.forEach(({ rule, position }, index) => {
const flow = rule.vcl_flow, guards = flow.guards || [];
if (position !== first.position + index || flow.index !== index || flow.count !== count ||
rule.enabled !== first.rule.enabled || JSON.stringify(rule.vhosts) !== JSON.stringify(first.rule.vhosts) ||
rule.conditions.length || rule.match !== "all") throw flowFailure(rule);
if (flowMarker(rule) && (rule.actions.length || rule.stop)) throw flowFailure(rule);
guards.forEach((guard, depth) => {
if (!guard || !Number.isInteger(guard.entry) || !Number.isInteger(guard.branch)) throw flowFailure(rule);
const entry = members[guard.entry]?.rule;
const ancestors = entry?.vcl_flow?.guards || [];
if (guard.entry < 0 || guard.entry >= index || !activeEntries.has(guard.entry) || guard.branch < 0 || !entry || !flowMarker(entry) ||
guard.branch >= entry.vcl_flow.branches.length || rule.stage !== entry.stage || rule.hash_stage !== entry.hash_stage ||
ancestors.length !== depth || ancestors.some((ancestor, i) => ancestor.entry !== guards[i].entry || ancestor.branch !== guards[i].branch) ||
guard.branch < (lastBranches.get(guard.entry) ?? 0)) throw flowFailure(rule);
lastBranches.set(guard.entry, guard.branch);
});
for (const entry of activeEntries) if (!guards.some(guard => guard.entry === entry)) activeEntries.delete(entry);
if (flowMarker(rule)) activeEntries.add(index);
(flow.branches || []).forEach((branch, branchIndex, branches) => {
if (!branch || !Array.isArray(branch.any) || !branch.any.length || branch.any.length > 128 ||
branch.any.some(clause => !Array.isArray(clause) || clause.length > 16)) throw flowFailure(rule);
if (branch.any.some(clause => !clause.length) && (branch.any.length !== 1 || branchIndex !== branches.length - 1)) throw flowFailure(rule);
conditionCount += branch.any.reduce((sum, clause) => sum + clause.length, 0);
if (conditionCount > 2048) throw flowFailure(rule);
});
});
}
}
function newFlowGroup(taken) {
let group;
do { group = `vcl-${Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, "0")).join("")}`; } while (taken.has(group));
taken.add(group); return group;
}
const esc = value => String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
const reEsc = value => String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const globRe = value => String(value).split("*").map(reEsc).join(".*");
@@ -132,6 +189,7 @@ window.rustProxyCacheRules = (() => {
return conditions.length ? `${description}\nif (${joined}) {\n${body}\n}` : `${description}\n${body.replace(/^ {4}/gm, "")}`;
}
function exportVcl(rules) {
if (rules.some(rule => rule.vcl_flow)) throw new Error(t("cacheRulesFlowExportJson"));
const subs = { request: "vcl_recv", response: "vcl_backend_response", deliver: "vcl_deliver" };
const blocks = [
"vcl 4.1;",
@@ -502,12 +560,29 @@ window.rustProxyCacheRules = (() => {
for (const isolated of [tester.node, importBox, catalog]) for (const type of ["input", "change"]) isolated.addEventListener(type, event => event.stopPropagation());
root.addEventListener("keydown", event => { if (event.key === "Enter" && event.target.matches?.("input:not([type=checkbox])")) event.preventDefault(); });
function taken() { return new Set(rules.map(rule => rule.id)); }
function unit(index) {
const group = rules[index]?.vcl_flow?.group;
if (!group) return { start: index, length: 1, members: [rules[index]] };
const start = rules.findIndex(rule => rule.vcl_flow?.group === group);
const members = rules.filter(rule => rule.vcl_flow?.group === group);
return { start, length: members.length, members };
}
function safelyEditFlow(action) {
try { validateFlow(rules); action(); } catch (error) { render(); toast(error.message, true); }
}
function updateExport() {
const hasFlow = rules.some(rule => rule.vcl_flow);
exportButton.textContent = t(hasFlow ? "cacheRulesExportJson" : "cacheRulesExportVcl");
exportSummary.textContent = t(hasFlow ? "cacheRulesJsonPreview" : "cacheRulesVclPreview");
exportPre.textContent = hasFlow ? JSON.stringify(rules.map(rule => clean(rule, scope === "global")), null, 2) : exportVcl(rules);
}
if (scope === "global") {
void loadTargets();
document.addEventListener("rustproxy-cache-targets", () => { if (root.isConnected && open.size) render(); });
}
function renderNotices() {
notices.replaceChildren();
if (rules.some(rule => rule.vcl_flow)) notices.append(el("p", t("cacheRulesFlowHelp"), "fine cache-rules-notice"));
if (scope !== "vhost") return;
const globals = applicableGlobals(vhostId);
if (ignoreGlobal) { if (globals.length) notices.append(el("p", t("cacheRulesGlobalSkipped").replace("{count}", globals.length), "fine cache-rules-notice")); return; }
@@ -524,11 +599,21 @@ window.rustProxyCacheRules = (() => {
list.replaceChildren(...rules.map((rule, index) => ruleCard(rule, index)));
empty.hidden = rules.length > 0;
addButton.disabled = rules.length >= MAX_RULES;
exportPre.textContent = exportVcl(rules);
updateExport();
renderNotices();
}
function move(from, to) { if (to < 0 || to >= rules.length) return; const [item] = rules.splice(from, 1); rules.splice(to, 0, item); render(); changed(); }
function move(from, to) {
if (from < 0 || from >= rules.length || to < 0 || to >= rules.length) return;
safelyEditFlow(() => {
const source = unit(from), target = unit(to);
if (source.start === target.start) return;
const destination = source.start < target.start ? target.start + target.length - source.length : target.start;
const moved = rules.splice(source.start, source.length);
rules.splice(destination, 0, ...moved); render(); changed();
});
}
function ruleCard(rule, index) {
const grouped = !!rule.vcl_flow, block = unit(index);
const card = el("div", undefined, `cache-rule${rule.enabled ? "" : " is-disabled"}${open.has(rule.id) ? " is-open" : ""}`); card.draggable = true; card.dataset.index = index;
card.addEventListener("dragstart", event => { event.dataTransfer.setData("text/plain", String(index)); card.classList.add("is-dragging"); });
card.addEventListener("dragend", () => card.classList.remove("is-dragging"));
@@ -536,23 +621,36 @@ window.rustProxyCacheRules = (() => {
card.addEventListener("dragleave", () => card.classList.remove("is-drop"));
card.addEventListener("drop", event => { event.preventDefault(); card.classList.remove("is-drop"); const from = Number(event.dataTransfer.getData("text/plain")); if (Number.isInteger(from) && from !== index) move(from, index); });
const head = el("div", undefined, "cache-rule-head");
const grip = el("span", "⠿", "cache-rule-grip"); grip.title = t("cacheRulesDrag");
const grip = el("span", "⠿", "cache-rule-grip"); grip.title = t(grouped ? "cacheRulesFlowMove" : "cacheRulesDrag");
const toggle = el("input", undefined, "switch"); toggle.type = "checkbox"; toggle.checked = rule.enabled; toggle.setAttribute("aria-label", t("enabled"));
toggle.addEventListener("change", () => { rule.enabled = toggle.checked; card.classList.toggle("is-disabled", !rule.enabled); exportPre.textContent = exportVcl(rules); changed(); });
toggle.addEventListener("change", () => safelyEditFlow(() => { for (const item of block.members) item.enabled = toggle.checked; render(); changed(); }));
const title = el("button", undefined, "cache-rule-title"); title.type = "button"; title.dataset.uiIconName = "none";
title.append(el("b", rule.name || rule.id), el("span", t(STAGE_KEYS[rule.stage]), "pill cache-rule-stage"), el("span", summary(rule), "fine cache-rule-summary"));
title.append(el("b", rule.name || rule.id), el("span", t(STAGE_KEYS[rule.stage]), "pill cache-rule-stage"), el("span", flowMarker(rule) ? t("cacheRuleFlowBranch") : summary(rule), "fine cache-rule-summary"));
title.addEventListener("click", () => { if (open.has(rule.id)) open.delete(rule.id); else open.add(rule.id); render(); });
const hitKey = scope === "vhost" ? `vhost:${vhostId}:${rule.id}` : `global:${rule.id}`;
const hitCount = el("span", hits[hitKey] != null ? t("cacheRulesHits").replace("{count}", fmt(hits[hitKey])) : "", "fine cache-rule-hits");
hitCount.dataset.hitKey = hitKey;
const actions = el("span", undefined, "cache-rule-actions");
const up = el("button", "↑", "quiet"); up.type = "button"; up.disabled = index === 0; up.setAttribute("aria-label", t("cacheRulesMoveUp")); up.addEventListener("click", () => move(index, index - 1));
const down = el("button", "↓", "quiet"); down.type = "button"; down.disabled = index === rules.length - 1; down.setAttribute("aria-label", t("cacheRulesMoveDown")); down.addEventListener("click", () => move(index, index + 1));
const copy = el("button", t("cacheRulesDuplicate"), "quiet"); copy.type = "button"; copy.addEventListener("click", () => { if (rules.length >= MAX_RULES) return; const clone = normalize(structuredClone(rule)); clone.id = slug(`${rule.id}-copy`, taken()); clone.name = `${rule.name || rule.id} (${t("cacheRulesCopySuffix")})`; rules.splice(index + 1, 0, clone); open.add(clone.id); render(); changed(); });
const remove = el("button", t("remove"), "quiet danger"); remove.type = "button"; remove.addEventListener("click", () => { rules.splice(index, 1); open.delete(rule.id); render(); changed(); });
const up = el("button", "↑", "quiet"); up.type = "button"; up.disabled = block.start === 0; up.setAttribute("aria-label", t("cacheRulesMoveUp")); up.addEventListener("click", () => move(index, block.start - 1));
const down = el("button", "↓", "quiet"); down.type = "button"; down.disabled = block.start + block.length === rules.length; down.setAttribute("aria-label", t("cacheRulesMoveDown")); down.addEventListener("click", () => move(index, block.start + block.length));
const copy = el("button", t(grouped ? "cacheRulesFlowDuplicate" : "cacheRulesDuplicate"), "quiet"); copy.type = "button"; copy.disabled = rules.length + block.length > MAX_RULES;
copy.addEventListener("click", () => safelyEditFlow(() => {
if (rules.length + block.length > MAX_RULES) { toast(t("cacheRulesLimit"), true); return; }
const ids = taken(), group = grouped ? newFlowGroup(new Set(rules.map(item => item.vcl_flow?.group).filter(Boolean))) : null;
const copies = block.members.map(item => {
const clone = normalize(item); clone.id = slug(`${item.id}-copy`, ids); ids.add(clone.id);
clone.name = `${item.name || item.id} (${t("cacheRulesCopySuffix")})`;
if (group) clone.vcl_flow.group = group;
return clone;
});
rules.splice(block.start + block.length, 0, ...copies); open.add(copies[0].id); render(); changed();
}));
const remove = el("button", t(grouped ? "cacheRulesFlowRemove" : "remove"), "quiet danger"); remove.type = "button";
remove.addEventListener("click", () => safelyEditFlow(() => { rules.splice(block.start, block.length); for (const item of block.members) open.delete(item.id); render(); changed(); }));
actions.append(up, down, copy, remove);
head.append(grip, toggle, title, hitCount, actions);
card.append(head);
if (grouped) card.append(el("p", t("cacheRuleFlowPart").replace("{index}", rule.vcl_flow.index + 1).replace("{count}", rule.vcl_flow.count), "fine cache-rules-notice cache-rule-note"));
if (scope === "global") for (const note of globalOverrideNotes(rule)) card.append(el("p", note, "fine cache-rules-notice cache-rule-note"));
if (cookieOnlyPass(rule)) {
// Controlled migration: an explicit pass is never relaxed automatically.
@@ -568,16 +666,19 @@ window.rustProxyCacheRules = (() => {
}
function ruleEditor(rule) {
const body = el("div", undefined, "cache-rule-body");
const grouped = !!rule.vcl_flow, marker = flowMarker(rule);
const grid = el("div", undefined, "cache-rule-grid");
const name = textInput(rule.name, t("cacheRuleNamePlaceholder")); name.maxLength = 96;
name.addEventListener("input", () => { rule.name = name.value; changed(); syncPreview(); });
const id = textInput(rule.id, "", "mono"); id.maxLength = 64; id.pattern = "[A-Za-z0-9_\\-]{1,64}";
id.addEventListener("change", () => { const value = id.value.trim(); if (!/^[A-Za-z0-9_-]{1,64}$/.test(value) || (value !== rule.id && taken().has(value))) { id.value = rule.id; toast(t("cacheRuleIdInvalid"), true); return; } open.delete(rule.id); rule.id = value; open.add(value); changed(); });
const stage = select(STAGES.map(value => [value, t(STAGE_KEYS[value])]), rule.stage, t("cacheRuleStage"));
stage.addEventListener("change", () => { rule.stage = stage.value; if (rule.stage !== "request") rule.hash_stage = false; rule.actions = rule.actions.filter(a => ACTIONS[rule.stage].includes(a.type)); if (!rule.actions.length && !rule.stop) rule.actions = [{ type: ACTIONS[rule.stage][0] }]; rule.conditions = rule.conditions.filter(c => FIELDS[c.field].stages.includes(rule.stage)); render(); changed(); });
stage.disabled = grouped;
stage.addEventListener("change", () => { if (grouped) { stage.value = rule.stage; toast(t("cacheRulesFlowStructureLocked"), true); return; } rule.stage = stage.value; if (rule.stage !== "request") rule.hash_stage = false; rule.actions = rule.actions.filter(a => ACTIONS[rule.stage].includes(a.type)); if (!rule.actions.length && !rule.stop) rule.actions = [{ type: ACTIONS[rule.stage][0] }]; rule.conditions = rule.conditions.filter(c => FIELDS[c.field].stages.includes(rule.stage)); render(); changed(); });
const match = select([["all", t("cacheRuleMatchAll")], ["any", t("cacheRuleMatchAny")]], rule.match, t("cacheRuleMatch"));
match.addEventListener("change", () => { rule.match = match.value; changed(); syncPreview(); });
const stop = el("input", undefined, "switch"); stop.type = "checkbox"; stop.checked = rule.stop; stop.addEventListener("change", () => { rule.stop = stop.checked; changed(); });
match.disabled = grouped;
match.addEventListener("change", () => { if (grouped) { match.value = rule.match; toast(t("cacheRulesFlowStructureLocked"), true); return; } rule.match = match.value; changed(); syncPreview(); });
const stop = el("input", undefined, "switch"); stop.type = "checkbox"; stop.checked = rule.stop; stop.disabled = grouped; stop.addEventListener("change", () => { if (grouped) { stop.checked = rule.stop; toast(t("cacheRulesFlowStructureLocked"), true); return; } rule.stop = stop.checked; changed(); });
const labeled = (key, control, help) => { const label = el("label", undefined, "cache-rule-field"); label.append(el("span", t(key)), control); if (help) label.append(el("small", t(help), "fine")); return label; };
const stopLabel = el("label", undefined, "check cache-rule-stop"); stopLabel.append(stop, el("span", t("cacheRuleStop")));
grid.append(labeled("cacheRuleName", name), labeled("cacheRuleId", id), labeled("cacheRuleStage", stage, `cacheRuleStageHelp${rule.stage[0].toUpperCase()}${rule.stage.slice(1)}`), labeled("cacheRuleMatch", match), stopLabel);
@@ -585,32 +686,40 @@ window.rustProxyCacheRules = (() => {
if (scope === "global") {
const vhostItems = targetList().map(target => ({ id: target.id, title: targetTitle(target), detail: target.docker ? target.id : (target.hosts || []).slice(0, 3).join(", "), search: (target.hosts || []).join(" "), badge: target.docker ? "Docker" : "", badgeClass: "is-allow" }));
const picker = window.rustProxyChoicePicker.create({ className: "cache-rule-vhosts", selected: rule.vhosts, items: vhostItems, limit: 64, labels: { choose: "cacheRuleVhostsAll", selected: "cacheRuleVhostsSelected", none: "cacheRuleVhostsNone", empty: "cacheRuleVhostsEmpty" } });
picker.addEventListener("choicechange", event => { rule.vhosts = event.detail || []; exportPre.textContent = exportVcl(rules); });
picker.addEventListener("change", changed);
picker.addEventListener("choicechange", event => {
if (grouped) safelyEditFlow(() => { for (const item of unit(rules.indexOf(rule)).members) item.vhosts = [...(event.detail || [])]; render(); changed(); });
else { rule.vhosts = event.detail || []; updateExport(); }
});
picker.addEventListener("change", () => { if (!grouped) changed(); });
const field = el("div", undefined, "cache-rule-field cache-rule-vhosts-field"); field.append(el("span", t("cacheRuleVhosts")), picker, el("small", t("cacheRuleVhostsHelp"), "fine"));
body.append(field);
}
const conditions = el("div", undefined, "cache-rule-section");
conditions.append(el("h4", t("cacheRuleConditions")));
const conditionRows = el("div", undefined, "cache-rule-rows");
rule.conditions.forEach((condition, index) => conditionRows.append(conditionRow(rule, condition, index)));
if (!rule.conditions.length) conditionRows.append(el("p", t("cacheRuleNoConditions"), "fine"));
if (grouped) {
conditionRows.append(el("p", t("cacheRulesFlowStructureLocked"), "fine"), el("pre", JSON.stringify(rule.vcl_flow, null, 2), "metrics-example mono cache-rule-flow"));
} else {
rule.conditions.forEach((condition, index) => conditionRows.append(conditionRow(rule, condition, index)));
if (!rule.conditions.length) conditionRows.append(el("p", t("cacheRuleNoConditions"), "fine"));
}
const addCondition = el("button", t("cacheRuleAddCondition"), "outline"); addCondition.type = "button";
addCondition.disabled = rule.conditions.length >= 16;
addCondition.addEventListener("click", () => { rule.conditions.push({ field: "path", operator: "prefix", values: [] }); render(); changed(); });
addCondition.disabled = grouped || rule.conditions.length >= 16;
addCondition.addEventListener("click", () => { if (grouped) return; rule.conditions.push({ field: "path", operator: "prefix", values: [] }); render(); changed(); });
conditions.append(conditionRows, addCondition);
const actionsSection = el("div", undefined, "cache-rule-section");
actionsSection.append(el("h4", t("cacheRuleActions")));
const actionRows = el("div", undefined, "cache-rule-rows");
rule.actions.forEach((action, index) => actionRows.append(actionRow(rule, action, index)));
const addAction = el("button", t("cacheRuleAddAction"), "outline"); addAction.type = "button";
addAction.disabled = rule.actions.length >= 16;
addAction.addEventListener("click", () => { const used = new Set(rule.actions.map(a => a.type)); rule.actions.push({ type: ACTIONS[rule.stage].find(type => !used.has(type)) || ACTIONS[rule.stage][0] }); render(); changed(); });
addAction.disabled = marker || rule.actions.length >= 16;
addAction.addEventListener("click", () => { if (marker) return; const used = new Set(rule.actions.map(a => a.type)); rule.actions.push({ type: ACTIONS[rule.stage].find(type => !used.has(type)) || ACTIONS[rule.stage][0] }); render(); changed(); });
if (marker) actionRows.append(el("p", t("cacheRuleFlowBranch"), "fine"));
actionsSection.append(actionRows, addAction);
const preview = el("pre", "", "metrics-example mono cache-rule-vcl");
const syncPreview = () => { preview.textContent = ruleVcl(rule); exportPre.textContent = exportVcl(rules); };
const syncPreview = () => { preview.textContent = grouped ? JSON.stringify(clean(rule, scope === "global"), null, 2) : ruleVcl(rule); updateExport(); };
body.addEventListener("input", syncPreview); body.addEventListener("change", syncPreview);
const previewWrap = el("div", undefined, "cache-rule-section"); previewWrap.append(el("h4", t("cacheRuleVcl")), preview);
const previewWrap = el("div", undefined, "cache-rule-section"); previewWrap.append(el("h4", t(grouped ? "cacheRulesJsonPreview" : "cacheRuleVcl")), preview);
body.append(conditions, actionsSection, previewWrap);
syncPreview();
return body;
@@ -745,10 +854,18 @@ window.rustProxyCacheRules = (() => {
}
function addRules(items, templateKey = "") {
if (rules.length + items.length > MAX_RULES) { toast(t("cacheRulesLimit"), true); return 0; }
const ids = taken();
const ids = taken(), groups = new Set(rules.map(rule => rule.vcl_flow?.group).filter(Boolean)), remappedGroups = new Map();
const addedRules = items.map(item => {
const rule = normalize({ ...item, id: slug(item.id || item.name, ids), vhosts: scope === "global" ? item.vhosts || [] : [] });
ids.add(rule.id);
if (rule.vcl_flow) {
const original = rule.vcl_flow.group;
if (!remappedGroups.has(original)) {
const group = groups.has(original) ? newFlowGroup(groups) : original;
remappedGroups.set(original, group); groups.add(group);
}
rule.vcl_flow.group = remappedGroups.get(original);
}
return rule;
});
// The parent-name rule must execute before the independent CDN cookie
@@ -756,8 +873,10 @@ window.rustProxyCacheRules = (() => {
const cdnIndex = templateKey === "publiccookies" ? rules.findIndex(rule =>
/^CDN:/.test(rule.name || "") && rule.conditions.some(c => c.field === "header" && String(c.name || "").toLowerCase() === "cookie") &&
rule.actions.some(a => a.type === "strip_cookies" || a.type === "pass" || a.type === "cookie_pass")) : -1;
if (cdnIndex >= 0) rules.splice(cdnIndex, 0, ...addedRules);
else rules.push(...addedRules);
const candidate = [...rules];
candidate.splice(cdnIndex >= 0 ? unit(cdnIndex).start : candidate.length, 0, ...addedRules);
validateFlow(candidate);
rules = candidate;
if (addedRules.length) open.add(addedRules[0].id);
render();
if (addedRules.length) changed();
@@ -766,7 +885,9 @@ window.rustProxyCacheRules = (() => {
function addTemplate(key) {
const make = TEMPLATES[key];
if (!make || !templateAvailable(key, scope)) return;
const items = make(), added = addRules(items, key);
const items = make();
let added;
try { added = addRules(items, key); } catch (error) { toast(error.message, true); return; }
if (!added) return;
const needsReview = items.some(item => item.enabled === false);
toast(t(needsReview ? "cacheRuleCatalogAddedDisabled" : "cacheRulesTemplateAdded").replace("{count}", added));
@@ -843,15 +964,19 @@ window.rustProxyCacheRules = (() => {
});
importApply.addEventListener("click", () => {
if (!pendingImport) return;
const added = addRules(pendingImport);
resetImportPreview();
importResult.append(el("p", t("cacheRulesImportDone").replace("{count}", added), "fine is-ok"));
try {
const added = addRules(pendingImport);
if (!added) return;
resetImportPreview();
importResult.append(el("p", t("cacheRulesImportDone").replace("{count}", added), "fine is-ok"));
} catch (error) { importResult.append(el("p", error.message, "fine is-error")); }
});
exportButton.addEventListener("click", async () => { exportBox.open = true; exportBox.scrollIntoView?.({ block: "nearest", behavior: "smooth" }); try { await navigator.clipboard.writeText(exportPre.textContent); toast(t("copied")); } catch { } });
ignoreBox.addEventListener("change", () => { ignoreGlobal = ignoreBox.checked; renderNotices(); changed(); });
function read() {
validateFlow(rules);
for (const rule of rules) {
if (!rule.actions.length && !rule.stop) throw new Error(t("cacheRuleNeedsAction").replace("{rule}", rule.name || rule.id));
if (!rule.actions.length && !rule.stop && !flowMarker(rule)) throw new Error(t("cacheRuleNeedsAction").replace("{rule}", rule.name || rule.id));
for (const c of rule.conditions) {
if (FIELDS[c.field].name && !c.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id));
if (c.operator !== "exists" && !(c.values || []).length) throw new Error(t("cacheRuleNeedsValue").replace("{rule}", rule.name || rule.id));
+96
View File
@@ -0,0 +1,96 @@
/* Shared global, vhost, Docker and location HTTP policy editor. */
.http-policy-editor,
.policy-visual,
.policy-rules,
.policy-detail-body,
.policy-actions,
.policy-test-output {
display: grid;
gap: 12px;
min-width: 0;
}
.http-policy-editor { width: 100%; margin-top: 10px; }
.http-policy-editor p,
.http-policy-editor h4 { margin: 0; }
.http-policy-editor [hidden] { display: none !important; }
.policy-toolbar,
.policy-row-controls,
.policy-rule-heading {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
}
.policy-toolbar > button,
.policy-row-controls > button { width: auto; }
.policy-toolbar > [aria-pressed="true"] { border-color: var(--accent); color: var(--accent); }
.policy-guide { margin-left: auto; }
.policy-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; min-width: 0; }
.policy-wide { grid-column: 1 / -1; }
.policy-field { display: grid; gap: 5px; min-width: 0; color: var(--muted); font-size: 12px; }
.policy-field > :is(input, select, textarea) { min-width: 0; width: 100%; margin: 0; }
.policy-field > textarea { resize: vertical; font-family: ui-monospace, monospace; font-size: 12px; line-height: 1.5; }
.policy-check { display: flex; gap: 8px; align-items: center; }
.policy-check > input { width: auto; flex: 0 0 auto; }
.policy-rule {
display: grid;
gap: 14px;
min-width: 0;
padding: 16px;
border: 1px solid var(--line);
border-left: 3px solid var(--accent);
background: var(--panel2);
border-radius: var(--rp-radius-surface, 0px);
}
.policy-rule.is-disabled { border-left-color: var(--muted); }
.policy-rule.is-disabled .policy-order { color: var(--muted); }
.policy-rule-heading > .policy-field:not(.policy-check) { flex: 1 1 180px; }
.policy-order { color: var(--accent); }
.policy-action {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(155px, 1fr));
gap: 10px;
align-items: end;
padding: 12px;
background: var(--panel);
border: 1px solid var(--line);
min-width: 0;
}
.policy-action > .policy-row-controls { grid-column: 1 / -1; justify-content: flex-end; }
.http-policy-editor details { min-width: 0; border: 1px solid var(--line); border-radius: var(--rp-radius-surface, 0px); }
.http-policy-editor details > summary { padding: 10px 12px; cursor: pointer; color: var(--text); font-weight: 600; }
.policy-detail-body { padding: 12px; border-top: 1px solid var(--line); }
.policy-rule > button,
.policy-detail-body > button { justify-self: start; }
.policy-result {
margin: 0;
padding: 12px;
max-height: 420px;
overflow: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
background: var(--code-bg);
border: 1px solid var(--line);
color: var(--text);
font-size: 12px;
line-height: 1.5;
}
.policy-message { padding: 10px; border: 1px solid var(--line); white-space: pre-wrap; }
.policy-message.is-error { color: var(--red); border-color: var(--danger-line-strong); }
.policy-trace { width: 100%; border-collapse: collapse; font-size: 12px; table-layout: fixed; }
.policy-trace th,
.policy-trace td { padding: 8px; text-align: left; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; white-space: pre-wrap; }
.policy-trace .is-matched td:first-child { color: var(--green); }
.policy-trace .is-skipped { color: var(--muted); }
.policy-counter-scroll { overflow: auto; display: grid; gap: 10px; }
.policy-counter-scroll > table { min-width: 520px; }
.docker-policy-editor { margin: 12px 0; border: 1px solid var(--line); padding: 12px; }
.docker-policy-editor > summary { cursor: pointer; font-weight: 600; }
@media (max-width: 760px) {
.policy-grid { grid-template-columns: 1fr; }
.policy-rule { padding: 12px; }
.policy-rule-heading > .policy-row-controls { width: 100%; justify-content: flex-end; }
.policy-action { grid-template-columns: minmax(0, 1fr); }
.policy-toolbar > button { flex: 1 1 auto; }
.policy-guide { margin: 0; }
}
+1 -3
View File
@@ -62,14 +62,12 @@ From the repository root:
```bash
python3 scripts/build/panel_css.py --check
python3 tools/dev/test_panel_css.py
python3 scripts/preflight.py
python3 scripts/audit_css_usage.py --strict
bash dev.sh check
bash dev.sh test
```
The first three commands require only Python 3.10+. The optional CSS audit
The stylesheet check requires only Python 3.10+. The optional CSS audit
requires `tinycss2` and `cssselect2`; install them in a development environment,
not on the deployed server. `--structure-json PATH` records repeated selectors,
conditional blocks, properties and identical declaration blocks. `--json PATH`
+1
View File
@@ -6,6 +6,7 @@
"30-overview.css",
"40-editors.css",
"50-settings.css",
"55-policy.css",
"60-monitoring.css",
"70-responsive.css"
]
+7 -2
View File
@@ -882,6 +882,11 @@
grid.append(checkboxField("vhTimingHeaders", box("docker-timing-headers", assignment?.timing_headers)), checkboxField("vhBackendHeader", box("docker-backend-header", assignment?.backend_header)), checkboxField("vhBackendTimingHeader", box("docker-backend-timing-header", assignment?.backend_timing_header)));
details.append(grid); return details;
}
function policyEditor(assignment, row) {
const details = el("details", undefined, "docker-policy-editor"); details.append(el("summary", t("policyTitle")));
const policy = window.rustProxyPolicy.create({ value: assignment?.policy || {}, scope: "vhost", onChange: () => row.classList.add("is-dirty") });
details.append(policy.node); row._readPolicy = () => policy.read(); return details;
}
function collectDiagnostics(row) {
const on = cls => row.querySelector(cls)?.checked === true;
return { timing_headers: on(".docker-timing-headers"), backend_header: on(".docker-backend-header"), backend_timing_header: on(".docker-backend-timing-header") };
@@ -903,7 +908,7 @@
allow_certificate_mismatch: row.querySelector(".docker-cert-mismatch")?.checked === true,
acl: inline && row.querySelector(".docker-acl-public")?.checked !== true ? { default: row.querySelector(".docker-acl-default").value, rules: parseRules(row.querySelector(".docker-acl-rules").value) } : null,
proxy_timeouts: { connect_timeout_seconds: Number(row.querySelector(".docker-proxy-connect").value), response_header_timeout_seconds: Number(row.querySelector(".docker-proxy-header").value), read_timeout_seconds: Number(row.querySelector(".docker-proxy-read").value), send_timeout_seconds: Number(row.querySelector(".docker-proxy-send").value) },
health_check: collectHealth(row), passive_health: collectPassiveHealth(row)
health_check: collectHealth(row), passive_health: collectPassiveHealth(row), policy: row._readPolicy?.() || {}
};
}
async function saveAssignment(agentId, row, publish) {
@@ -1063,7 +1068,7 @@
protocolOptions.append(h1, checkboxField("dockerHttp2Enabled", h2Enabled), checkboxField("dockerHttp3Enabled", h3Enabled));
protocolBox.append(protocolSummary, protocolOptions);
route.append(hostField, aliases.node, backendIpSettings, labeled("dockerBackendScheme", scheme), switches); syncHostHelp();
editor.append(route, protocolBox, aclEditor(assignment, agent), securityEditor(assignment), cacheEditor(assignment, agent, key, cacheEnabled, () => expandedHost(host.value.trim() || technical, domainSelect.value)), diagnosticsEditor(assignment), timeoutEditor(assignment), healthEditor(assignment), passiveHealthEditor(assignment));
editor.append(route, protocolBox, aclEditor(assignment, agent), securityEditor(assignment), cacheEditor(assignment, agent, key, cacheEnabled, () => expandedHost(host.value.trim() || technical, domainSelect.value)), diagnosticsEditor(assignment), policyEditor(assignment, row), timeoutEditor(assignment), healthEditor(assignment), passiveHealthEditor(assignment));
const actions = el("div", undefined, "docker-service-actions"); apply = el("button", t("dockerApplyService"), "outline docker-apply"); apply.type = "button"; apply.disabled = !publish.checked; apply.addEventListener("click", async () => { apply.disabled = true; try { await saveAssignment(agent.id, row, true); } catch (error) { toast(error.message, true); } finally { if (row.isConnected) apply.disabled = !publish.checked; } }); actions.append(apply); editor.append(actions);
function updateHint() { syncCertificateHint(); editorHint.textContent = hintFor({ hostname: host.value.trim(), domain: domainSelect.value, targetLabel: target.selectedOptions?.[0]?.textContent || t("dockerBackendIpAuto"), scheme: scheme.value, h2: h2Enabled.checked, h3: h3Enabled.checked, aliasCount: aliases.count() }); } updateHint();
for (const control of [host, aliases.input, target, scheme]) { control.addEventListener("input", updateHint); control.addEventListener("change", updateHint); }
+12
View File
@@ -2513,6 +2513,8 @@
data-i18n="globalSecurityHeaders" type="button">Security headers</button>
<button aria-selected="false" data-policy-settings-tab="headers"
data-i18n="customHeaders" type="button">Global custom headers</button>
<button aria-selected="false" data-policy-settings-tab="policy"
data-i18n="policyTitle" role="tab" tabindex="-1" type="button">HTTP policies</button>
<button aria-selected="false" data-policy-settings-tab="response"
data-i18n="responseSettings" type="button">Client response</button>
</nav>
@@ -2726,6 +2728,16 @@
type="submit">Apply header rules</button></div>
</form>
</div>
<div data-policy-settings-page="policy" hidden="">
<form class="card edit-form" id="policy-form">
<div class="card-heading">
<h2 data-i18n="policyTitle">HTTP policies</h2>
<span class="pill live" data-i18n="hotApply">LIVE APPLY</span>
</div>
<div id="global-policy-rules-root"></div>
<div class="form-actions"><button class="primary" data-i18n="policySave" type="submit">Apply HTTP policies</button></div>
</form>
</div>
<div data-policy-settings-page="response" hidden="">
<form class="card edit-form" id="response-form">
<div class="card-heading">
+286
View File
@@ -0,0 +1,286 @@
"use strict";
// The editor only builds configuration. Import, validation and test evaluation use
// the same Rust compiler/evaluator as live traffic; there is no JS policy engine.
window.rustProxyPolicy = (() => {
const STAGES = ["pre_route", "request", "backend_request", "backend_response", "deliver", "after_response"];
const OPERATORS = ["equals", "contains", "prefix", "suffix", "regex", "exists", "cidr", "eq", "ne", "gt", "ge", "lt", "le"];
const ACTION_FIELDS = {
set_header: ["name", "value"], append_header: ["name", "value"], remove_header: ["name"], set_if_missing: ["name", "value"],
normalize_header: ["name"], merge_header: ["name", "value"], remove_value: ["name", "value"], replace_header: ["name", "pattern", "replacement"], replace_value: ["name", "pattern", "replacement"],
set_var: ["name", "value"], unset_var: ["name"], set_path: ["value"], set_query: ["value"], use_backend: ["id"],
deny: ["status"], return: ["status", "body"], redirect: ["status", "location"], pass: [], lookup: [], no_store: [],
set_ttl: ["seconds"], set_grace: ["seconds"], hash_header: ["name"], disable_compression: [], stop: []
};
const clone = value => structuredClone(value);
const label = (prefix, value) => t(`${prefix}${String(value).split("_").map(part => part[0].toUpperCase() + part.slice(1)).join("")}`);
const text = (tag, key, cls) => { const node = el(tag, t(key), cls); node.dataset.i18n = key; return node; };
const button = (key, fn, cls = "quiet") => { const node = text("button", key, cls); node.type = "button"; node.addEventListener("click", fn); return node; };
const object = value => value !== null && typeof value === "object" && !Array.isArray(value);
function settings(value) {
if (!object(value) || (value.rules !== undefined && !Array.isArray(value.rules)) || (value.acls !== undefined && !object(value.acls)) || (value.maps !== undefined && !object(value.maps))) throw Error(t("policyInvalid"));
const copy = clone(value);
copy.rules ??= []; copy.acls ??= {}; copy.maps ??= {};
if (copy.rules.length > 128 || copy.rules.some(rule => !object(rule) || !Array.isArray(rule.actions))) throw Error(t("policyInvalid"));
return copy;
}
function headers(source) {
return String(source).split(/\r?\n/).filter(line => line.trim()).map((line, index) => {
const at = line.indexOf(":");
if (at < 1 || /^[ \t]/.test(line)) throw Error(t("policyHeaderInvalid").replace("{line}", index + 1));
return { name: line.slice(0, at).trim(), value: line.slice(at + 1).replace(/^[ \t]+|[ \t]+$/g, "") };
});
}
function input(parent, key, value, options = {}) {
const holder = el("label", undefined, `policy-field${options.wide ? " policy-wide" : ""}${options.type === "checkbox" ? " policy-check" : ""}`);
const node = document.createElement(options.type === "textarea" ? "textarea" : options.values ? "select" : "input");
if (options.values) for (const [v, name] of options.values) { const item = el("option", name); item.value = v; node.append(item); }
else if (options.type !== "textarea") node.type = options.type || "text";
if (options.type === "checkbox") node.checked = Boolean(value); else node.value = value ?? "";
if (!options.values && options.type !== "checkbox") { node.spellcheck = false; node.autocomplete = "off"; }
if (options.rows) node.rows = options.rows;
if (options.maxLength) node.maxLength = options.maxLength;
if (options.min !== undefined) node.min = options.min;
if (options.max !== undefined) node.max = options.max;
if (options.placeholder) node.placeholder = options.placeholder;
node.setAttribute("aria-label", t(key));
if (options.type === "checkbox") holder.append(node, text("span", key)); else holder.append(text("span", key), node);
parent.append(holder); return node;
}
function defaultAction(type) {
const action = { type };
for (const field of ACTION_FIELDS[type] || []) action[field] = field === "status" ? (type === "deny" ? 403 : type === "redirect" ? 302 : 200) : field === "seconds" ? 60 : "";
if (type === "normalize_header") action.name = "Vary";
return action;
}
function limitTerminalActions(select, stage) {
for (const option of select.options) option.disabled = ["return", "redirect"].includes(option.value) && stage !== "request";
}
function uniqueId(rules, prefix = "policy") { let n = 1; while (rules.some(rule => rule.id === `${prefix}-${n}`)) n++; return `${prefix}-${n}`; }
function mergeImports(current, addition) {
const next = settings(current), incoming = settings(addition);
for (const kind of ["acls", "maps"]) for (const [name, value] of Object.entries(incoming[kind])) {
if (Object.hasOwn(next[kind], name) && JSON.stringify(next[kind][name]) !== JSON.stringify(value)) throw Error(t("policyImportCollision").replace("{name}", name));
Object.defineProperty(next[kind], name, { value: clone(value), enumerable: true, configurable: true, writable: true });
}
for (const rule of incoming.rules) {
const copy = clone(rule);
if (next.rules.some(item => item.id === copy.id)) copy.id = uniqueId(next.rules, "imported");
next.rules.push(copy);
}
return settings(next);
}
function preset(kind, id) {
const base = { id, name: t(kind === "vary" ? "policyPresetVary" : "policyPresetNormalize"), enabled: true, stage: kind === "vary" ? "backend_response" : "after_response", when: { all: [] }, actions: [], stop: false };
if (kind === "vary") {
base.when.all = [
{ fetch: "res.fhdr_cnt(Vary)", operator: "eq", values: ["2"] },
{ fetch: "res.fhdr(Vary)", operator: "equals", values: ["Accept-Encoding"], ignore_case: true },
{ fetch: "res.fhdr(Vary)", operator: "equals", values: ["Accept,Accept-Encoding", "Accept, Accept-Encoding"], ignore_case: true }
];
base.actions = [{ type: "set_header", name: "Vary", value: "Accept, Accept-Encoding" }];
} else base.actions = [{ type: "normalize_header", name: "Vary" }];
return base;
}
function create({ value = {}, scope = "vhost", onChange = () => {} } = {}) {
let model = settings(value), mode = "visual", epoch = 0, importResult = null;
const stagesForScope = STAGES.filter(stage => scope !== "location" || stage !== "pre_route");
const node = el("section", undefined, "http-policy-editor vh-wide"), message = el("p", undefined, "policy-message fine");
message.setAttribute("role", "status"); message.setAttribute("aria-live", "polite"); message.hidden = true;
const toolbar = el("div", undefined, "policy-toolbar"), visual = el("div", undefined, "policy-visual"), rawPane = el("div", undefined, "policy-raw"); rawPane.hidden = true;
node.append(text("p", "policyIntro", "fine"), text("p", "policyCompatibility", "fine"), toolbar, message, visual, rawPane);
const raw = input(rawPane, "policyJson", JSON.stringify(model, null, 2), { type: "textarea", rows: 18, maxLength: 262144, wide: true });
const fail = error => { message.textContent = error.message || String(error); message.classList.add("is-error"); message.hidden = false; };
const clear = () => { message.hidden = true; message.classList.remove("is-error"); };
const change = () => { epoch++; clear(); onChange(); };
const safely = fn => (...args) => { try { return fn(...args); } catch (error) { fail(error); } };
const parse = (control, check = value => value) => {
try { const value = check(JSON.parse(control.value)); control.setCustomValidity(""); return value; }
catch (error) { control.setCustomValidity(error.message || t("policyInvalid")); throw error; }
};
function read() {
if (mode !== "json") for (const control of visual.querySelectorAll(".policy-config-json")) control._readJson();
const value = mode === "json" ? settings(parse(raw, settings)) : settings(model);
if (scope === "location" && value.rules.some(rule => rule.stage === "pre_route")) throw Error(t("policyLocationStage"));
return value;
}
function setValue(value) { model = settings(value); raw.value = JSON.stringify(model, null, 2); raw.setCustomValidity(""); render(); }
const setMode = safely(next => {
model = read(); mode = next; visual.hidden = mode !== "visual"; rawPane.hidden = mode !== "json";
if (mode === "json") raw.value = JSON.stringify(model, null, 2); else render();
visualButton.setAttribute("aria-pressed", String(mode === "visual")); jsonButton.setAttribute("aria-pressed", String(mode === "json")); clear();
});
const visualButton = button("policyVisual", () => setMode("visual")), jsonButton = button("policyJson", () => setMode("json"));
visualButton.setAttribute("aria-pressed", "true"); jsonButton.setAttribute("aria-pressed", "false"); toolbar.append(visualButton, jsonButton);
raw.addEventListener("input", () => { raw.setCustomValidity(""); change(); });
const guide = el("a", t("documentation"), "policy-guide"); guide.href = "/docs#doc=docs%2FPOLICY.md"; guide.target = "_blank"; guide.rel = "noopener"; toolbar.append(guide);
const editJson = (parent, key, current, apply, check = value => value, rows = 4) => {
const area = input(parent, key, JSON.stringify(current, null, 2), { type: "textarea", rows, maxLength: 65536, wide: true }); area.classList.add("policy-config-json");
area._readJson = () => { const data = parse(area, check); apply(data); return data; };
area.addEventListener("input", () => { try { area._readJson(); } catch { } change(); }); return area;
};
const requireObject = value => { if (!object(value)) throw Error(t("policyInvalid")); return value; };
function renderAction(parent, rule, action, index, refresh) {
const row = el("div", undefined, "policy-action"); parent.append(row);
const known = Object.hasOwn(ACTION_FIELDS, action.type), choices = Object.keys(ACTION_FIELDS).map(type => [type, label("policyAction", type)]);
if (!known) choices.unshift([action.type || "", action.type || t("policyAdvancedAction")]);
const op = input(row, "policyAction", action.type, { values: choices });
op.dataset.policyAction = ""; limitTerminalActions(op, rule.stage || "request");
op.addEventListener("change", safely(() => { read(); rule.actions[index] = defaultAction(op.value); refresh(); change(); }));
if (!known) editJson(row, "policyAdvancedAction", action, value => { rule.actions[index] = value; }, requireObject);
else for (const key of ACTION_FIELDS[action.type]) {
const number = ["status", "seconds"].includes(key), field = input(row, `policyField${key[0].toUpperCase()}${key.slice(1)}`, action[key], { type: number ? "number" : key === "body" ? "textarea" : "text", rows: key === "body" ? 2 : undefined, maxLength: key === "body" ? 65536 : 8192, min: number ? 0 : undefined });
field.addEventListener("input", () => { action[key] = number ? Number(field.value) : field.value; change(); });
}
const controls = el("div", undefined, "policy-row-controls"); row.append(controls);
const up = button("policyMoveUp", safely(() => { read(); [rule.actions[index - 1], rule.actions[index]] = [rule.actions[index], rule.actions[index - 1]]; refresh(); change(); })); up.disabled = index === 0;
const down = button("policyMoveDown", safely(() => { read(); [rule.actions[index + 1], rule.actions[index]] = [rule.actions[index], rule.actions[index + 1]]; refresh(); change(); })); down.disabled = index === rule.actions.length - 1;
controls.append(up, down, button("remove", safely(() => { read(); rule.actions.splice(index, 1); refresh(); change(); })));
}
function renderRule(parent, rule, index) {
const card = el("article", undefined, `policy-rule${rule.enabled === false ? " is-disabled" : ""}`); card.dataset.ruleId = rule.id || ""; parent.append(card);
const heading = el("div", undefined, "policy-rule-heading"), enabled = input(heading, "enabled", rule.enabled !== false, { type: "checkbox" });
heading.append(el("b", `${index + 1}.`, "policy-order"));
const title = input(heading, "policyRuleName", rule.name || "", { maxLength: 128 });
card.append(heading);
enabled.addEventListener("change", () => { rule.enabled = enabled.checked; card.classList.toggle("is-disabled", !enabled.checked); change(); });
title.addEventListener("input", () => { rule.name = title.value; change(); });
const commands = el("div", undefined, "policy-row-controls"); heading.append(commands);
const up = button("policyMoveUp", safely(() => { read(); [model.rules[index - 1], model.rules[index]] = [model.rules[index], model.rules[index - 1]]; render(); change(); })); up.disabled = index === 0;
const down = button("policyMoveDown", safely(() => { read(); [model.rules[index + 1], model.rules[index]] = [model.rules[index], model.rules[index + 1]]; render(); change(); })); down.disabled = index === model.rules.length - 1;
commands.append(up, down, button("remove", safely(() => { read(); model.rules.splice(index, 1); render(); change(); })));
const meta = el("div", undefined, "policy-grid"), id = input(meta, "policyRuleId", rule.id, { maxLength: 128 });
const stages = [...stagesForScope]; if (rule.stage && !stages.includes(rule.stage)) stages.push(rule.stage);
const stage = input(meta, "policyStage", rule.stage || "request", { values: stages.map(stage => [stage, label("policyStage", stage)]) });
const stop = input(meta, "policyStop", !!rule.stop, { type: "checkbox" });
id.addEventListener("input", () => { rule.id = id.value; change(); }); stop.addEventListener("change", () => { rule.stop = stop.checked; change(); });
const stageHint = el("p", label("policyStageHelp", stage.value), "policy-wide fine");
stage.addEventListener("change", () => { rule.stage = stage.value; stageHint.textContent = label("policyStageHelp", stage.value); for (const op of card.querySelectorAll("select[data-policy-action]")) limitTerminalActions(op, stage.value); change(); });
meta.append(stageHint); card.append(meta);
const conditions = el("details", undefined, "policy-conditions"), conditionSummary = text("summary", "policyConditions"); conditions.append(conditionSummary); card.append(conditions);
const conditionBody = el("div", undefined, "policy-detail-body"); conditions.append(conditionBody);
const when = editJson(conditionBody, "policyConditionJson", rule.when || { all: [] }, value => { rule.when = value; }, requireObject, 5);
const simple = el("div", undefined, "policy-grid"), fetch = input(simple, "policyFetch", "res.fhdr(Vary)", { maxLength: 4096 });
const operator = input(simple, "policyOperator", "equals", { values: OPERATORS.map(op => [op, op]) });
const values = input(simple, "policyValues", "Accept-Encoding", { type: "textarea", rows: 2, maxLength: 8192 });
const ignore = input(simple, "policyIgnoreCase", true, { type: "checkbox" });
const modeSelect = input(simple, "policyCombine", "all", { values: [["all", "AND"], ["any", "OR"]] });
operator.addEventListener("change", () => { values.disabled = operator.value === "exists"; });
simple.append(button("policyAddCondition", safely(() => {
const before = parse(when, requireObject), condition = { fetch: fetch.value, operator: operator.value, values: operator.value === "exists" ? [] : values.value.split(/\r?\n/).filter(value => value.length), ignore_case: ignore.checked };
const group = modeSelect.value;
const empty = Object.keys(before).length === 1 && ((Array.isArray(before.all) && !before.all.length) || (Array.isArray(before.any) && !before.any.length));
rule.when = empty ? { [group]: [condition] } : Object.keys(before).length === 1 && Array.isArray(before[group]) ? { [group]: [...before[group], condition] } : { [group]: [before, condition] };
when.value = JSON.stringify(rule.when, null, 2); when.setCustomValidity(""); change();
})));
conditionBody.append(simple, text("p", "policyConditionsHelp", "fine"));
card.append(text("h4", "policyActions")); const actions = el("div", undefined, "policy-actions"); card.append(actions);
const refresh = () => { actions.replaceChildren(); rule.actions.forEach((action, index) => renderAction(actions, rule, action, index, refresh)); };
refresh(); const addAction = button("policyAddAction", safely(() => { read(); if (rule.actions.length >= 16) throw Error(t("policyActionLimit")); rule.actions.push(defaultAction("set_header")); refresh(); change(); })); card.append(addAction);
}
function render() {
visual.replaceChildren();
const bar = el("div", undefined, "policy-toolbar"); visual.append(bar);
const add = safely(kind => {
model = read(); if (model.rules.length >= 128) throw Error(t("policyRuleLimit"));
const id = uniqueId(model.rules);
model.rules.push(kind ? preset(kind, id) : { id, name: t("policyNewRule"), enabled: true, stage: "after_response", when: { all: [] }, actions: [defaultAction("set_header")], stop: false });
render(); change();
});
bar.append(button("policyAddRule", () => add(), "primary"), button("policyPresetVary", () => add("vary")), button("policyPresetNormalize", () => add("normalize")));
if (!model.rules.length) visual.append(text("p", "policyEmpty", "fine"));
const rules = el("div", undefined, "policy-rules"); visual.append(rules); model.rules.forEach((rule, index) => renderRule(rules, rule, index));
const definitions = el("details", undefined, "policy-definitions"); definitions.append(text("summary", "policyDefinitions"));
const body = el("div", undefined, "policy-detail-body"); definitions.append(body);
editJson(body, "policyAcls", model.acls, value => { model.acls = value; }, requireObject, 5);
editJson(body, "policyMaps", model.maps, value => { model.maps = value; }, requireObject, 5);
body.append(text("p", "policyDefinitionsHelp", "fine")); visual.append(definitions);
}
render();
// Import is staged: server validation, visible preview, then an explicit add
// to the unsaved draft. Source changes invalidate a pending preview.
const importer = el("details", undefined, "policy-import"); importer.append(text("summary", "policyImport"));
const importBody = el("div", undefined, "policy-detail-body"); importer.append(importBody);
const source = input(importBody, "policyHaproxySource", "", { type: "textarea", rows: 7, maxLength: 262144, wide: true, placeholder: "acl vary_duplicate res.fhdr_cnt(Vary) eq 2\nacl vary_encoding res.fhdr(Vary) -i Accept-Encoding\nacl vary_combined res.fhdr(Vary) -i \"Accept,Accept-Encoding\" \"Accept, Accept-Encoding\"\nhttp-response set-header Vary \"Accept, Accept-Encoding\" if vary_duplicate vary_encoding vary_combined" });
source.setAttribute("form", "rustproxy-policy-tools");
const imported = el("pre", undefined, "policy-result"), importNotes = el("p", undefined, "fine"); imported.hidden = true; importNotes.hidden = true;
const applyImport = button("policyImportAdd", safely(() => {
if (!importResult) return;
const next = mergeImports(read(), importResult.policy); setValue(next); change(); importResult = null; applyImport.disabled = true;
importNotes.textContent = t("policyImportAdded"); importNotes.hidden = false;
})); applyImport.disabled = true;
const importButton = button("policyImportPreview", async () => {
clear(); importResult = null; applyImport.disabled = true; importButton.disabled = true; imported.hidden = true; importNotes.hidden = true;
const submitted = source.value;
try {
const result = await api("/api/policy/import-haproxy", { method: "POST", body: JSON.stringify({ source: submitted }) });
if (source.value !== submitted) return;
settings(result.policy); importResult = result; imported.textContent = JSON.stringify(result.policy, null, 2); imported.hidden = false;
importNotes.textContent = (result.warnings || []).join("\n") || t("policyImportReady"); importNotes.hidden = false; applyImport.disabled = false;
} catch (error) { fail(error); } finally { importButton.disabled = false; }
});
source.addEventListener("input", event => { event.stopPropagation(); importResult = null; applyImport.disabled = true; imported.hidden = true; importNotes.hidden = true; });
source.addEventListener("change", event => event.stopPropagation());
const importActions = el("div", undefined, "policy-toolbar"); importActions.append(importButton, applyImport);
importBody.append(importActions, importNotes, imported, text("p", "policyImportHelp", "fine")); node.append(importer);
const tester = el("details", undefined, "policy-tester"); tester.append(text("summary", "policyTest"));
const testBody = el("div", undefined, "policy-detail-body"), testGrid = el("div", undefined, "policy-grid"); tester.append(testBody); testBody.append(text("p", "policyTestHelp", "fine"), testGrid);
const testStage = input(testGrid, "policyStage", "after_response", { values: stagesForScope.map(stage => [stage, label("policyStage", stage)]) });
const method = input(testGrid, "policyMethod", "GET", { values: ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"].map(value => [value, value]) });
const host = input(testGrid, "policyHost", "example.com", { maxLength: 255 }), path = input(testGrid, "policyPath", "/", { maxLength: 8192 }), query = input(testGrid, "policyQuery", "", { maxLength: 8192 });
const ip = input(testGrid, "policyClientIp", "203.0.113.10", { maxLength: 64 }), country = input(testGrid, "policyCountry", "PL", { maxLength: 2 }), tls = input(testGrid, "policyTls", true, { type: "checkbox" });
const status = input(testGrid, "policyStatus", 200, { type: "number", min: 100, max: 599 });
const cache = input(testGrid, "policyCacheStatus", "MISS", { values: [["", "—"], ...["HIT", "MISS", "BYPASS"].map(value => [value, value])] }), backend = input(testGrid, "policyBackend", "", { maxLength: 128 });
const requestHeaders = input(testGrid, "policyRequestHeaders", "Accept-Encoding: gzip\nAccept: text/html", { type: "textarea", rows: 4, maxLength: 65536, wide: true });
const responseHeaders = input(testGrid, "policyResponseHeaders", "Vary: Accept-Encoding\nVary: Accept,Accept-Encoding", { type: "textarea", rows: 4, maxLength: 65536, wide: true });
const variables = input(testGrid, "policyVariables", "{}", { type: "textarea", rows: 2, maxLength: 8192, wide: true });
const resultBox = el("div", undefined, "policy-test-output"); resultBox.setAttribute("aria-live", "polite");
const testButton = button("policyRunTest", async () => {
clear(); testButton.disabled = true; resultBox.replaceChildren(); const submittedEpoch = epoch;
try {
const vars = parse(variables, requireObject);
if (Object.values(vars).some(value => typeof value !== "string")) throw Error(t("policyVariablesInvalid"));
const payload = { policy: read(), stage: testStage.value, request: { method: method.value, host: host.value, path: path.value, query: query.value || null, headers: headers(requestHeaders.value), client_ip: ip.value || null, country: country.value || null, tls: tls.checked }, response: { status: Number(status.value), headers: headers(responseHeaders.value) }, variables: vars, cache_status: cache.value || null, srv_id: backend.value || null };
const result = await api("/api/policy/test", { method: "POST", body: JSON.stringify(payload) });
if (epoch !== submittedEpoch) { resultBox.append(text("p", "policyTestStale", "fine")); return; }
if (result.requires_private_response) resultBox.append(text("p", "policyPrivateResponse", "fine"));
const table = el("table", undefined, "policy-trace"), head = el("tr");
for (const key of ["policyRuleId", "policyStage", "policyMatched", "policyActions"]) head.append(text("th", key));
const thead = el("thead"), body = el("tbody"); thead.append(head); table.append(thead, body);
for (const entry of result.trace || []) {
const row = el("tr"); row.className = entry.matched ? "is-matched" : "is-skipped";
row.append(el("td", entry.rule), el("td", label("policyStage", entry.stage)), el("td", t(entry.matched ? "policyYes" : "policyNo")), el("td", [...(entry.actions || []), ...(entry.warnings || [])].join("\n"))); body.append(row);
}
if (body.children.length) resultBox.append(table); else resultBox.append(text("p", "policyNoStageRules", "fine"));
const printHeaders = (key, values) => { resultBox.append(text("h4", key), el("pre", (values || []).map(item => `${item.name}: ${item.value}`).join("\n") || "—", "policy-result")); };
printHeaders("policyRequestResult", result.request?.headers); printHeaders("policyResponseResult", result.response?.headers);
const details = el("details"); details.append(text("summary", "policyFullResult"), el("pre", JSON.stringify(result, null, 2), "policy-result")); resultBox.append(details);
} catch (error) { fail(error); } finally { testButton.disabled = false; }
}, "primary");
// Tester input changes invalidate an in-flight result without dirtying config.
for (const control of testGrid.querySelectorAll("input, select, textarea")) control.setAttribute("form", "rustproxy-policy-tools");
testGrid.addEventListener("input", event => { event.stopPropagation(); epoch++; }); testGrid.addEventListener("change", event => { event.stopPropagation(); epoch++; });
testBody.append(testButton, resultBox); node.append(tester);
const counters = el("details", undefined, "policy-counters"); counters.append(text("summary", "policyCounters"));
const counterBody = el("div", undefined, "policy-detail-body"), counterResult = el("div", undefined, "policy-counter-scroll");
counterResult.setAttribute("aria-live", "polite"); counterBody.append(text("p", "policyCountersHelp", "fine"));
const refreshCounters = button("policyRefreshCounters", async () => {
refreshCounters.disabled = true; counterResult.replaceChildren(); clear();
try {
const result = await api("/api/policy/stats");
counterResult.append(el("p", `${t("policySavedRevision")}: ${result.revision}`, "fine"));
const table = el("table", undefined, "policy-trace"), thead = el("thead"), heading = el("tr"), body = el("tbody");
for (const key of ["policyScope", "policyRuleId", "policyStage", "policyMatches", "policyErrors"]) heading.append(text("th", key));
thead.append(heading); table.append(thead, body);
for (const item of result.scopes || []) for (const rule of item.rules || []) {
const row = el("tr"), identity = [item.scope, item.vhost, item.location].filter(Boolean).join(" / ");
row.append(el("td", identity), el("td", rule.id), el("td", label("policyStage", rule.stage)), el("td", String(rule.matches ?? 0)), el("td", String(rule.errors ?? 0))); body.append(row);
}
if (body.children.length) counterResult.append(table); else counterResult.append(text("p", "policyCountersEmpty", "fine"));
} catch (error) { fail(error); } finally { refreshCounters.disabled = false; }
});
counterBody.append(refreshCounters, counterResult); counters.append(counterBody); node.append(counters);
node.dataset.policyScope = scope;
return { node, read, set: setValue };
}
return { create, settings, headers, mergeImports, preset };
})();
+2 -2
View File
@@ -9,7 +9,7 @@
const requestedTab = typeof location !== "undefined" && location.pathname === "/logging"
? "logging"
: (typeof location !== "undefined" && location.pathname === "/settings" ? new URLSearchParams(location.search).get("tab") : null);
const tabAliases = { http2: "connections", headers: "policies", response: "policies" };
const tabAliases = { http2: "connections", headers: "policies", response: "policies", policy: "policies" };
function pinnedAdminHostname(value) {
try {
const url = new URL(value);
@@ -91,7 +91,7 @@
event.preventDefault(); selectPolicyTab(policyTabs[next].dataset.policySettingsTab, true);
});
}
selectPolicyTab(["headers", "response", "security-headers", "block-allow"].includes(requestedTab) ? requestedTab : "block-allow");
selectPolicyTab(["headers", "policy", "response", "security-headers", "block-allow"].includes(requestedTab) ? requestedTab : "block-allow");
const cacheTabs = [...document.querySelectorAll("[data-cache-settings-tab]")];
function selectCacheTab(name, focus = false) {
if (!cacheTabs.some(button => button.dataset.cacheSettingsTab === name)) return;
@@ -0,0 +1,190 @@
// Cache/VCL editor round-trip regressions. Requires Node.js and jsdom.
// Run: node src/admin/web/tests/cache-rules.dom.test.cjs
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { JSDOM } = require('jsdom');
const root = path.resolve(__dirname, '../../../..');
const translations = JSON.parse(fs.readFileSync(path.join(root, 'langs/en_US.json'), 'utf8')).translations;
const dom = new JSDOM('<html><body><form id="fixture"><main id="root"></main></form></body></html>', { runScripts: 'outside-only', url: 'https://panel.example.test' });
const w = dom.window, d = w.document;
w.structuredClone = structuredClone;
w.t = key => translations[key] || key;
w.el = (tag, text, cls) => { const node = d.createElement(tag); if (text !== undefined) node.textContent = text; if (cls) node.className = cls; return node; };
w.envelope = { config: { cache: { rules: [] }, vhosts: [] } };
w.authenticated = false;
w.fmt = value => String(value);
w.rustProxyChoicePicker = { create: options => { const node = d.createElement('div'); node.className = options.className || ''; return node; } };
let notices = [], calls = [], reply = {}, dirty = 0, editor, checks = 0;
w.toast = (message, error) => notices.push({ message, error });
w.api = async (url, options) => { calls.push({ url, body: options?.body ? JSON.parse(options.body) : null }); return structuredClone(reply); };
w.eval(fs.readFileSync(path.join(root, 'src/admin/web/cache-rules.js'), 'utf8'));
const api = w.rustProxyCacheRules;
const plain = value => JSON.parse(JSON.stringify(value));
const flush = () => new Promise(resolve => setImmediate(resolve));
function mount(rules = [], scope = 'vhost') {
notices = []; calls = []; dirty = 0;
editor = api.create({ rules, scope, vhostId: 'site', autoLoadHits: false, onChange: () => dirty++ });
d.getElementById('root').replaceChildren(editor.node);
}
function button(key, within = editor.node) {
const found = [...within.querySelectorAll('button')].find(node => node.textContent === w.t(key) || node.getAttribute('aria-label') === w.t(key));
assert.ok(found, `button ${key}`); return found;
}
function card(index = 0) { return editor.node.querySelectorAll('.cache-rule')[index]; }
function open(index = 0) { card(index).querySelector('.cache-rule-title').click(); return card(index); }
function field(key, within) {
const found = [...within.querySelectorAll('.cache-rule-field')].find(node => node.firstElementChild?.textContent === w.t(key));
assert.ok(found, `field ${key}`); return found.querySelector('input, select, textarea');
}
function fill(node, value, event = 'input') { node.value = value; node.dispatchEvent(new w.Event(event, { bubbles: true })); }
function drop(from, to) { const event = new w.Event('drop', { bubbles: true, cancelable: true }); Object.defineProperty(event, 'dataTransfer', { value: { getData: () => String(from) } }); card(to).dispatchEvent(event); }
async function importRules(rules, warnings = []) {
reply = { rules, warnings }; button('cacheRulesImportVcl').click();
fill(editor.node.querySelector('.cache-rules-import textarea'), 'sub vcl_recv { if (req.http.X-Mode == "old") { set req.http.X-Mode = "new"; } else { return (pass); } }');
button('cacheRulesImportRun').click(); await flush();
}
async function check(name, fn) { await fn(); checks++; console.log(`ok ${checks} - ${name}`); }
(async () => {
const ordinary = { id: 'ordinary', name: 'Ordinary', enabled: true, stage: 'request', match: 'all', conditions: [{ field: 'path', operator: 'prefix', values: ['/assets'] }], actions: [{ type: 'set_request_header', name: 'X-Device', value: 'desktop' }], stop: false };
const hashing = { id: 'hash', name: 'Imported hash', enabled: true, stage: 'request', match: 'all', conditions: [], actions: [{ type: 'hash_header', name: 'X-Device' }], stop: false, hash_stage: true };
const flow = [
{ ...ordinary, id: 'vcl-if', name: 'If decision', conditions: [], actions: [], vcl_flow: { version: 1, group: 'vcl-fixture', index: 0, count: 3, branches: [{ any: [[{ field: 'header', name: 'X-Mode', operator: 'equals', values: ['old'] }]] }, { any: [[]] }] } },
{ ...ordinary, id: 'vcl-then', name: 'Selected branch', conditions: [], actions: [{ type: 'set_request_header', name: 'X-Mode', value: 'new' }], vcl_flow: { version: 1, group: 'vcl-fixture', index: 1, count: 3, guards: [{ entry: 0, branch: 0 }] } },
{ ...ordinary, id: 'vcl-else', name: 'Else branch', conditions: [], actions: [{ type: 'pass' }], stop: true, vcl_flow: { version: 1, group: 'vcl-fixture', index: 2, count: 3, guards: [{ entry: 0, branch: 1 }] } },
];
await check('existing request and imported hash rules survive opening and save', () => {
mount([ordinary, hashing]); open(); assert.deepEqual(plain(editor.read()), [ordinary, hashing]);
assert.equal(dirty, 0);
});
await check('ordinary reorder keeps hash phase and edited action values', () => {
const first = card(); const input = [...first.querySelectorAll('input')].find(node => node.placeholder === w.t('cacheRuleHeaderValue'));
fill(input, 'mobile'); button('cacheRulesMoveDown', first).click();
assert.deepEqual(plain(editor.read()), [hashing, { ...ordinary, actions: [{ ...ordinary.actions[0], value: 'mobile' }] }]);
assert.equal(ordinary.actions[0].value, 'desktop');
});
await check('tester sends the same saved-rule structure without configuration writes', async () => {
mount([ordinary, hashing]); reply = { request: { cacheable: true }, response: { stored: true, ttl: 60, grace: 0 } };
button('cacheRulesTesterRun').click(); await flush();
assert.equal(calls.length, 1); assert.equal(calls[0].url, '/api/cache/rules/test');
assert.deepEqual(calls[0].body.vhost_rules, [ordinary, hashing]); assert.equal(dirty, 0);
});
await check('opening a branch marker allows zero actions and preserves every condition and guard', () => {
mount(flow); open(); assert.deepEqual(plain(editor.read()), flow); assert.equal(dirty, 0);
const copy = editor.read(); copy[0].vcl_flow.branches[0].any[0][0].values[0] = 'tampered';
copy[1].vcl_flow.guards[0].branch = 1;
assert.deepEqual(plain(editor.read()), flow); assert.equal(flow[0].vcl_flow.branches[0].any[0][0].values[0], 'old');
});
await check('structural controls are disabled and reject synthetic changes without flattening', () => {
const marker = card();
assert.ok(field('cacheRuleStage', marker).disabled); assert.ok(field('cacheRuleMatch', marker).disabled);
assert.ok(marker.querySelector('.cache-rule-stop input').disabled);
assert.ok(button('cacheRuleAddCondition', marker).disabled); assert.ok(button('cacheRuleAddAction', marker).disabled);
fill(field('cacheRuleStage', marker), 'deliver', 'change');
fill(field('cacheRuleMatch', marker), 'any', 'change');
assert.deepEqual(plain(editor.read()), flow); assert.equal(dirty, 0); assert.equal(notices.length, 2);
});
await check('editing an action and renaming a rule preserve branch references', () => {
mount(flow); const row = open(1);
fill(row.querySelector('input[placeholder="' + w.t('cacheRuleHeaderValue') + '"]'), 'reviewed');
fill(field('cacheRuleId', row), 'renamed-action', 'change');
const saved = plain(editor.read());
assert.equal(saved[1].actions[0].value, 'reviewed'); assert.equal(saved[1].id, 'renamed-action');
assert.deepEqual(saved.map(rule => rule.vcl_flow), flow.map(rule => rule.vcl_flow));
assert.equal(flow[1].actions[0].value, 'new');
});
await check('moving any member or dropping a flat rule cannot split a VCL block', () => {
mount([ordinary, ...flow, hashing]);
button('cacheRulesMoveDown', card(2)).click();
assert.deepEqual(plain(editor.read()), [ordinary, hashing, ...flow]);
drop(0, 3); assert.deepEqual(plain(editor.read()), [hashing, ...flow, ordinary]);
button('cacheRulesMoveUp', card(3)).click();
assert.deepEqual(plain(editor.read()), [...flow, hashing, ordinary]);
const before = dirty; drop(0, 2); assert.equal(dirty, before); assert.deepEqual(plain(editor.read()), [...flow, hashing, ordinary]);
});
await check('enable controls change the complete block and leave unrelated rules alone', () => {
mount([ordinary, ...flow]);
const toggle = card(2).querySelector('.cache-rule-head input'); toggle.checked = false; toggle.dispatchEvent(new w.Event('change', { bubbles: true }));
assert.deepEqual(plain(editor.read()), [ordinary, ...flow.map(rule => ({ ...rule, enabled: false }))]);
assert.equal(dirty, 1);
});
await check('duplicate creates independent group and rule IDs; remove deletes the complete copy', () => {
mount([ordinary, ...flow]); button('cacheRulesFlowDuplicate', card(2)).click();
const saved = plain(editor.read()), copies = saved.slice(4);
assert.equal(saved.length, 7); assert.equal(new Set(saved.map(rule => rule.id)).size, 7);
assert.match(copies[0].vcl_flow.group, /^vcl-[a-f0-9]{32}$/); assert.notEqual(copies[0].vcl_flow.group, flow[0].vcl_flow.group);
assert.equal(new Set(copies.map(rule => rule.vcl_flow.group)).size, 1);
assert.deepEqual(copies.map(rule => ({ ...rule.vcl_flow, group: 'vcl-fixture' })), flow.map(rule => rule.vcl_flow));
button('cacheRulesFlowRemove', card(5)).click(); assert.deepEqual(plain(editor.read()), [ordinary, ...flow]);
});
await check('vhost targeting is updated atomically for the whole global VCL block', () => {
mount([ordinary, ...flow], 'global'); const row = open(2);
row.querySelector('.cache-rule-vhosts').dispatchEvent(new w.CustomEvent('choicechange', { detail: ['site-a', 'site-b'], bubbles: true }));
const saved = plain(editor.read()); assert.deepEqual(saved[0], ordinary);
assert.ok(saved.slice(1).every(rule => JSON.stringify(rule.vhosts) === '["site-a","site-b"]'));
const detached = editor.read(); detached[1].vhosts.push('tampered'); assert.equal(editor.read()[1].vhosts.length, 2);
});
await check('importing the same block again remaps IDs without changing its guards', async () => {
mount(flow); await importRules(flow);
const saved = plain(editor.read()), added = saved.slice(3);
assert.equal(saved.length, 6); assert.deepEqual(saved.slice(0, 3), flow);
assert.equal(new Set(saved.map(rule => rule.id)).size, 6); assert.notEqual(added[0].vcl_flow.group, flow[0].vcl_flow.group);
assert.deepEqual(added.map(rule => ({ ...rule.vcl_flow, group: 'vcl-fixture' })), flow.map(rule => rule.vcl_flow));
assert.equal(dirty, 1); assert.deepEqual(flow[1].vcl_flow.guards, [{ entry: 0, branch: 0 }]);
});
await check('partial import keeps the complete structure only after explicit acceptance', async () => {
mount([ordinary]); await importRules(flow, ['Unsupported log statement was omitted.']);
assert.deepEqual(plain(editor.read()), [ordinary]); assert.equal(dirty, 0);
button('cacheRulesImportApplyPartial').click();
assert.deepEqual(plain(editor.read()), [ordinary, ...flow]); assert.equal(dirty, 1);
});
await check('incomplete import is rejected atomically and preserves existing rules', async () => {
mount([ordinary]); await importRules(flow.slice(0, 2));
assert.deepEqual(plain(editor.read()), [ordinary]); assert.equal(dirty, 0);
assert.match(editor.node.querySelector('.cache-rules-import-result .is-error').textContent, /incomplete or structurally changed/);
});
await check('reordered or incomplete saved metadata cannot be saved or accidentally moved', () => {
mount([flow[0], flow[2], flow[1], ordinary]);
assert.throws(() => editor.read(), /incomplete or structurally changed/);
button('cacheRulesMoveUp', card(3)).click(); assert.equal(dirty, 0); assert.equal(notices.length, 1);
assert.equal(card(3).querySelector('.cache-rule-title b').textContent, ordinary.name);
editor.set(flow.slice(0, 2)); assert.throws(() => editor.read(), /incomplete or structurally changed/);
});
await check('tester and JSON export preserve the full imported program without executing in JavaScript', async () => {
mount(flow); reply = { request: { cacheable: false, reason: 'pass' } };
button('cacheRulesTesterRun').click(); await flush();
assert.equal(calls.length, 1); assert.equal(calls[0].url, '/api/cache/rules/test'); assert.deepEqual(calls[0].body.vhost_rules, flow);
assert.ok(button('cacheRulesExportJson')); assert.deepEqual(JSON.parse(editor.node.querySelector('.cache-rules-vcl').textContent), flow);
assert.throws(() => api.exportVcl(flow), /complete JSON export/); assert.equal(dirty, 0);
});
await check('a hash-stage imported action retains its phase when its action is edited', () => {
const hashFlow = { ...hashing, vcl_flow: { version: 1, group: 'vcl-hash', index: 0, count: 1 } };
mount([hashFlow]); const row = open();
const name = row.querySelector('input[placeholder="Accept-Language"]'); fill(name, 'X-Experiment');
assert.deepEqual(plain(editor.read()), [{ ...hashFlow, actions: [{ type: 'hash_header', name: 'X-Experiment' }] }]);
});
await check('nested guards and OR clauses survive editing and moving the complete program', () => {
const parent = { entry: 0, branch: 0 };
const nested = [
{ ...flow[0], vcl_flow: { ...flow[0].vcl_flow, group: 'vcl-nested', count: 5, branches: flow[0].vcl_flow.branches.slice(0, 1) } },
{ ...flow[0], id: 'nested-if', vcl_flow: { ...flow[0].vcl_flow, group: 'vcl-nested', index: 1, count: 5, guards: [parent], branches: [{ any: [[{ field: 'header', name: 'X-Inner', operator: 'exists' }], [{ field: 'path', operator: 'prefix', values: ['/public'] }]] }, { any: [[]] }] } },
{ ...flow[1], actions: [{ type: 'remove_request_header', name: 'X-Mode' }], vcl_flow: { ...flow[1].vcl_flow, group: 'vcl-nested', index: 2, count: 5, guards: [parent, { branch: 0, entry: 1 }] } },
{ ...flow[1], id: 'nested-else', vcl_flow: { ...flow[1].vcl_flow, group: 'vcl-nested', index: 3, count: 5, guards: [{ branch: 0, entry: 0 }, { entry: 1, branch: 1 }] } },
{ ...flow[2], vcl_flow: { ...flow[2].vcl_flow, group: 'vcl-nested', index: 4, count: 5, guards: [parent] } },
];
mount([...nested, ordinary]); open(2);
assert.deepEqual(plain(editor.read()), [...nested, ordinary]);
button('cacheRulesMoveDown', card(2)).click(); assert.deepEqual(plain(editor.read()), [ordinary, ...nested]);
const invalid = structuredClone(nested); invalid[4].vcl_flow.guards.push({ entry: 1, branch: 0 });
editor.set(invalid); assert.throws(() => editor.read(), /incomplete or structurally changed/);
});
await check('cross-phase guards and altered branch markers are rejected before save', () => {
const wrongPhase = structuredClone(flow); wrongPhase[1].hash_stage = true;
mount(wrongPhase); assert.throws(() => editor.read(), /incomplete or structurally changed/);
const wrongMarker = structuredClone(flow); wrongMarker[0].actions = [{ type: 'pass' }];
editor.set(wrongMarker); assert.throws(() => editor.read(), /incomplete or structurally changed/);
});
console.log(`PASS: ${checks} cache/VCL editor DOM regression checks`);
dom.window.close();
})().catch(error => { console.error(error); dom.window.close(); process.exitCode = 1; });
+130
View File
@@ -0,0 +1,130 @@
// Fast policy editor regressions using a DOM. Requires Node.js and jsdom.
// Run: node src/admin/web/tests/policy.dom.test.cjs
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { JSDOM } = require('jsdom');
const root = path.resolve(__dirname, '../../../..');
const translations = JSON.parse(fs.readFileSync(path.join(root, 'langs/en_US.json'), 'utf8')).translations;
const dom = new JSDOM('<html><body><form id="fixture"><main id="root"></main><button type="submit">Save</button></form></body></html>', { runScripts: 'outside-only', url: 'https://panel.example.test' });
const w = dom.window, d = w.document;
w.structuredClone = structuredClone;
w.t = key => translations[key] || key;
w.el = (tag, text, cls) => { const n = d.createElement(tag); if (text !== undefined) n.textContent = text; if (cls) n.className = cls; return n; };
let dirty = 0, bubbled = 0, calls = [], response = {}, pending = false, resolver;
w.api = async (url, options) => { calls.push({ url, body: options?.body ? JSON.parse(options.body) : null }); if (pending) return new Promise(resolve => { resolver = resolve; }); return structuredClone(response); };
d.getElementById('fixture').addEventListener('input', () => bubbled++);
w.eval(fs.readFileSync(path.join(root, 'src/admin/web/policy.js'), 'utf8'));
const plain = value => JSON.parse(JSON.stringify(value));
const api = w.rustProxyPolicy;
let editor, checks = 0;
const flush = () => new Promise(resolve => setImmediate(resolve));
function mount(value = {}, scope = 'vhost') { dirty = 0; bubbled = 0; calls = []; pending = false; editor = api.create({ value, scope, onChange: () => dirty++ }); d.getElementById('root').replaceChildren(editor.node); }
function button(key, within = editor.node) { const found = [...within.querySelectorAll('button')].find(n => n.textContent === w.t(key)); assert.ok(found, `button ${key}`); return found; }
function control(key, within = editor.node) { const found = [...within.querySelectorAll('input, textarea, select')].find(n => n.getAttribute('aria-label') === w.t(key)); assert.ok(found, `control ${key}`); return found; }
function fill(node, value, event = 'input') { node.value = value; node.dispatchEvent(new w.Event(event, { bubbles: true })); }
async function check(name, fn) { await fn(); checks++; console.log(`ok ${checks} - ${name}`); }
(async () => {
const original = { acls: { mobile: { fetch: 'req.fhdr(User-Agent)', operator: 'contains', values: ['mobile'], ignore_case: true } }, maps: { devices: { kind: 'exact', entries: [{ key: 'a', value: 'b' }], default: 'fallback', ignore_case: false } }, rules: [
{ id: 'one', name: '<img src=x onerror=alert(1)>', enabled: false, stage: 'request', when: { any: [{ acl: 'mobile' }, { not: { fetch: 'req.fhdr(X-Test)', operator: 'exists', values: [] } }] }, actions: [{ type: 'set_var', name: 'txn.device', value: '%[req.fhdr(User-Agent),lower,map(devices)]' }], stop: true },
{ id: 'two', name: 'Response', enabled: true, stage: 'after_response', when: { all: [] }, actions: [{ type: 'normalize_header', name: 'Vary' }], stop: false }
] };
await check('duplicate and empty header fields are preserved', () => {
assert.deepEqual(plain(api.headers('Vary: Accept-Encoding\nVary: Accept,Accept-Encoding\nX-Empty:\nX-URL: https://example.test:8443/')), [{ name: 'Vary', value: 'Accept-Encoding' }, { name: 'Vary', value: 'Accept,Accept-Encoding' }, { name: 'X-Empty', value: '' }, { name: 'X-URL', value: 'https://example.test:8443/' }]);
assert.throws(() => api.headers('not a header'), /Invalid header/);
assert.throws(() => api.headers(' folded: header'), /Invalid header/);
});
await check('opening complex existing settings preserves all values', () => { mount(original); assert.deepEqual(plain(editor.read()), original); assert.equal(editor.node.querySelector('img'), null); });
await check('reordering rules preserves ACLs, maps, conditions and actions', () => {
button('policyMoveDown', editor.node.querySelector('.policy-rule-heading')).click();
assert.deepEqual(plain(editor.read()), { ...original, rules: [original.rules[1], original.rules[0]] });
});
await check('raw JSON round trip is lossless and malformed JSON prevents switching/save', () => {
mount(original); button('policyJson').click(); const raw = editor.node.querySelector('.policy-raw textarea');
assert.deepEqual(plain(editor.read()), original); fill(raw, '{broken'); assert.throws(() => editor.read());
button('policyVisual').click(); assert.equal(editor.node.querySelector('.policy-raw').hidden, false);
fill(raw, JSON.stringify(original)); button('policyVisual').click(); assert.deepEqual(plain(editor.read()), original);
});
await check('editing nested condition JSON is never discarded by reorder', () => {
mount(original); const condition = editor.node.querySelector('.policy-conditions textarea'); fill(condition, '{broken');
button('policyMoveDown', editor.node.querySelector('.policy-rule-heading')).click(); assert.throws(() => editor.read());
assert.equal(editor.node.querySelector('.policy-rule').dataset.ruleId, 'one');
fill(condition, JSON.stringify({ acl: 'mobile' })); button('policyMoveDown', editor.node.querySelector('.policy-rule-heading')).click();
assert.deepEqual(plain(editor.read().rules[1].when), { acl: 'mobile' });
});
await check('first OR condition replaces the empty default group', () => {
mount(); button('policyAddRule').click(); const conditions = editor.node.querySelector('.policy-conditions');
fill(control('policyCombine', conditions), 'any', 'change'); button('policyAddCondition', conditions).click();
const expression = plain(editor.read().rules[0].when); assert.equal(expression.any.length, 1); assert.equal(expression.any[0].fetch, 'res.fhdr(Vary)');
});
await check('presets encode full-field count and final Vary normalization', () => {
mount(); button('policyPresetVary').click(); button('policyPresetNormalize').click();
const rules = editor.read().rules; assert.equal(rules[0].stage, 'backend_response'); assert.equal(rules[0].when.all.length, 3);
assert.deepEqual(plain(rules[0].when.all[0]), { fetch: 'res.fhdr_cnt(Vary)', operator: 'eq', values: ['2'] });
assert.deepEqual(plain(rules[1].actions), [{ type: 'normalize_header', name: 'Vary' }]); assert.equal(rules[1].stage, 'after_response');
});
await check('import requires review and explicit add; existing rules are retained', async () => {
mount(original); response = { policy: { rules: [{ ...original.rules[1], id: 'one' }] }, warnings: [] };
fill(control('policyHaproxySource'), 'http-after-response normalize-header Vary'); button('policyImportPreview').click(); await flush();
assert.deepEqual(plain(editor.read()), original); assert.equal(dirty, 0);
button('policyImportAdd').click(); const result = editor.read(); assert.equal(result.rules.length, 3); assert.equal(result.rules[2].id, 'imported-1');
assert.deepEqual(plain(result.acls), original.acls); assert.deepEqual(calls.map(c => c.url), ['/api/policy/import-haproxy']);
});
await check('name collisions reject imports atomically and special keys remain data', () => {
assert.throws(() => api.mergeImports(original, { acls: { mobile: { all: [] } }, rules: [{ id: 'bad', actions: [] }] }), /mobile/);
const special = api.mergeImports({}, JSON.parse('{"acls":{"__proto__":{"all":[]}},"rules":[]}'));
assert.equal(Object.hasOwn(special.acls, '__proto__'), true); assert.equal(Object.getPrototypeOf(special.acls), Object.prototype);
assert.equal(editor.read().rules.length, 3);
});
await check('source edits invalidate a pending import preview', async () => {
mount(); response = { policy: { rules: [original.rules[1]] }, warnings: [] };
fill(control('policyHaproxySource'), 'source'); button('policyImportPreview').click(); await flush();
assert.equal(button('policyImportAdd').disabled, false); fill(control('policyHaproxySource'), 'modified'); assert.equal(button('policyImportAdd').disabled, true);
assert.equal(editor.read().rules.length, 0);
});
await check('server tester receives duplicate headers and renders trace as text', async () => {
mount({ rules: [original.rules[1]] });
response = { request: { headers: [{ name: 'X-Unsafe', value: '<script>throw Error(1)</script>' }] }, response: { status: 200, headers: [{ name: 'Vary', value: 'Accept-Encoding, Accept' }] }, trace: [{ rule: 'two', stage: 'after_response', matched: true, actions: ['normalize_header'], warnings: [] }], variables: {} };
button('policyRunTest').click(); await flush();
assert.equal(calls[0].url, '/api/policy/test'); assert.equal(calls[0].body.stage, 'after_response');
assert.deepEqual(calls[0].body.response.headers, [{ name: 'Vary', value: 'Accept-Encoding' }, { name: 'Vary', value: 'Accept,Accept-Encoding' }]);
assert.equal(editor.node.querySelectorAll('.policy-trace tbody tr').length, 1); assert.equal(editor.node.querySelector('.policy-test-output script'), null);
assert.match(editor.node.querySelector('.policy-test-output').textContent, /<script>/);
});
await check('tester inputs neither dirty nor invalidate the enclosing config form', async () => {
mount(); fill(control('policyVariables'), 'malformed'); button('policyRunTest').click(); await flush();
assert.equal(dirty, 0); assert.equal(bubbled, 0); assert.equal(control('policyVariables').form, null); assert.equal(d.getElementById('fixture').checkValidity(), true);
});
await check('pre_route is unavailable and rejected in a location draft', () => {
mount({}, 'location'); assert.equal(editor.node.querySelector('.policy-tester option[value="pre_route"]'), null);
button('policyJson').click(); fill(editor.node.querySelector('.policy-raw textarea'), JSON.stringify({ rules: [{ id: 'bad', stage: 'pre_route', actions: [] }] }));
assert.throws(() => editor.read(), /pre_route/);
});
await check('return and redirect are selectable only after request access checks', () => {
mount({ rules: [{ id: 'terminal', stage: 'pre_route', actions: [{ type: 'return', status: 200, body: 'existing draft' }] }] });
const action = control('policyAction', editor.node.querySelector('.policy-action'));
for (const type of ['return', 'redirect']) assert.equal(action.querySelector(`option[value="${type}"]`).disabled, true);
assert.equal(action.querySelector('option[value="deny"]').disabled, false);
assert.equal(editor.read().rules[0].actions[0].body, 'existing draft');
fill(control('policyStage', editor.node.querySelector('.policy-rule')), 'request', 'change');
for (const type of ['return', 'redirect']) assert.equal(action.querySelector(`option[value="${type}"]`).disabled, false);
assert.equal(editor.read().rules[0].actions[0].body, 'existing draft');
});
await check('in-flight test result is discarded when inputs change', async () => {
mount({ rules: [original.rules[1]] }); pending = true; button('policyRunTest').click(); await flush();
fill(control('policyHost'), 'changed.example'); resolver({ trace: [] }); await flush();
assert.match(editor.node.querySelector('.policy-test-output').textContent, /changed during evaluation/); pending = false;
});
await check('live counters use a read-only saved-config request and do not dirty drafts', async () => {
mount(); response = { revision: 7, scopes: [{ scope: 'vhost', vhost: 'site-a', rules: [{ id: 'vary', stage: 'after_response', matches: 32, errors: 1 }] }] };
button('policyRefreshCounters').click(); await flush();
assert.deepEqual(calls, [{ url: '/api/policy/stats', body: null }]); assert.equal(dirty, 0);
const output = editor.node.querySelector('.policy-counter-scroll').textContent; assert.match(output, /7/); assert.match(output, /site-a/); assert.match(output, /32/);
assert.equal(editor.read().rules.length, 0);
});
await check('separate editor instances keep separate drafts', () => {
const first = api.create({ value: original }), second = api.create({ value: { rules: [original.rules[1]] } });
button('policyAddRule', first.node).click(); assert.equal(first.read().rules.length, 3); assert.equal(second.read().rules.length, 1); assert.equal(original.rules.length, 2);
});
console.log(`PASS: ${checks} DOM policy editor regression checks`); dom.window.close();
})().catch(error => { console.error(error); dom.window.close(); process.exitCode = 1; });
+132
View File
@@ -0,0 +1,132 @@
// Component regression tests. Requires Node.js and Playwright Chromium.
// Run: node src/admin/web/tests/policy.test.cjs
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { chromium } = require('playwright');
const root = path.resolve(__dirname, '../../../..');
const policyFile = path.join(root, 'src/admin/web/policy.js');
const translations = JSON.parse(fs.readFileSync(path.join(root, 'langs/en_US.json'), 'utf8')).translations;
let checks = 0;
async function check(name, fn) { await fn(); checks++; console.log(`ok ${checks} - ${name}`); }
(async () => {
const browser = await chromium.launch({ headless: true, ...(process.env.POLICY_TEST_CHROMIUM ? { executablePath: process.env.POLICY_TEST_CHROMIUM } : {}) });
try {
const page = await browser.newPage({ viewport: { width: 1180, height: 900 } });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.setContent('<html><body style="margin:20px"><form id="fixture"><div id="root"></div><button type="submit">Save</button></form></body></html>');
await page.evaluate(translations => {
window.translations = translations;
window.t = key => translations[key] || key;
window.el = (tag, text, cls) => { const node = document.createElement(tag); if (text !== undefined) node.textContent = text; if (cls) node.className = cls; return node; };
window.changed = 0; window.parentChanged = 0; window.calls = [];
document.getElementById('fixture').addEventListener('input', () => window.parentChanged++);
window.api = async (url, options) => { const body = options?.body ? JSON.parse(options.body) : null; window.calls.push({ url, body }); if (window.pendingApi) return new Promise(resolve => { window.resolveApi = resolve; }); return structuredClone(window.apiResult || {}); };
}, translations);
for (const file of ['00-tokens.css', '10-base.css', '55-policy.css']) await page.addStyleTag({ path: path.join(root, 'src/admin/web/css', file) });
await page.addScriptTag({ path: policyFile });
const mount = async (value = {}, scope = 'vhost') => page.evaluate(({ value, scope }) => {
window.changed = 0; window.parentChanged = 0; window.calls = [];
window.editor = window.rustProxyPolicy.create({ value, scope, onChange: () => window.changed++ });
document.getElementById('root').replaceChildren(window.editor.node);
}, { value, scope });
await check('header parser preserves repeated fields and empty values', async () => {
const values = await page.evaluate(() => window.rustProxyPolicy.headers('Vary: Accept-Encoding\nVary: Accept,Accept-Encoding\nX-Empty:\nX-URL: https://example.test:8443/'));
assert.deepEqual(values, [{ name: 'Vary', value: 'Accept-Encoding' }, { name: 'Vary', value: 'Accept,Accept-Encoding' }, { name: 'X-Empty', value: '' }, { name: 'X-URL', value: 'https://example.test:8443/' }]);
assert.equal(await page.evaluate(() => { try { window.rustProxyPolicy.headers('not a header'); return false; } catch { return true; } }), true);
});
const original = { acls: { mobile: { fetch: 'req.fhdr(User-Agent)', operator: 'contains', values: ['mobile'], ignore_case: true } }, maps: { devices: { kind: 'exact', entries: [{ key: 'a', value: 'b' }], default: 'fallback', ignore_case: false } }, rules: [
{ id: 'one', name: '<img src=x onerror=alert(1)>', enabled: false, stage: 'request', when: { any: [{ acl: 'mobile' }, { not: { fetch: 'req.fhdr(X-Test)', operator: 'exists', values: [] } }] }, actions: [{ type: 'set_var', name: 'txn.device', value: '%[req.fhdr(User-Agent),lower,map(devices)]' }], stop: true },
{ id: 'two', name: 'Response', enabled: true, stage: 'after_response', when: { all: [] }, actions: [{ type: 'normalize_header', name: 'Vary' }], stop: false }
] };
await check('complex rules, ACLs and maps survive opening and reading', async () => {
await mount(original); assert.deepEqual(await page.evaluate(() => window.editor.read()), original);
assert.equal(await page.locator('img').count(), 0);
});
await check('rule reorder preserves every condition, action and definition', async () => {
await page.locator('.policy-rule').first().locator('.policy-rule-heading').getByRole('button', { name: 'Move down', exact: true }).click();
const value = await page.evaluate(() => window.editor.read());
assert.deepEqual(value, { ...original, rules: [original.rules[1], original.rules[0]] });
});
await check('raw/visual round trip is lossless and invalid raw JSON blocks reading', async () => {
await mount(original); await page.getByRole('button', { name: 'Policy JSON', exact: true }).click();
assert.deepEqual(await page.evaluate(() => window.editor.read()), original);
await page.locator('.policy-raw textarea').fill('{broken');
assert.equal(await page.evaluate(() => { try { window.editor.read(); return false; } catch { return true; } }), true);
await page.getByRole('button', { name: 'Rule builder', exact: true }).click();
assert.equal(await page.locator('.policy-raw').isVisible(), true);
await page.locator('.policy-raw textarea').fill(JSON.stringify(original));
await page.getByRole('button', { name: 'Rule builder', exact: true }).click();
assert.deepEqual(await page.evaluate(() => window.editor.read()), original);
});
await check('Vary preset keeps field-count and separate full-field conditions', async () => {
await mount(); await page.getByRole('button', { name: 'Fix duplicate Vary (exact match)', exact: true }).click();
const rule = await page.evaluate(() => window.editor.read().rules[0]);
assert.equal(rule.stage, 'backend_response'); assert.equal(rule.when.all.length, 3);
assert.deepEqual(rule.when.all[0], { fetch: 'res.fhdr_cnt(Vary)', operator: 'eq', values: ['2'] });
assert.deepEqual(rule.actions, [{ type: 'set_header', name: 'Vary', value: 'Accept, Accept-Encoding' }]);
await page.getByRole('button', { name: 'Normalize Vary (preserve dimensions)', exact: true }).click();
assert.deepEqual(await page.evaluate(() => window.editor.read().rules[1].actions), [{ type: 'normalize_header', name: 'Vary' }]);
});
await check('import preview never silently activates or replaces existing rules', async () => {
await mount(original); await page.locator('.policy-import > summary').click();
const incoming = { acls: {}, maps: {}, rules: [{ ...original.rules[1], id: 'one' }] };
await page.evaluate(policy => { window.apiResult = { policy, warnings: [] }; }, incoming);
await page.getByLabel('HAProxy source', { exact: true }).fill('http-after-response normalize-header Vary');
await page.getByRole('button', { name: 'Validate and preview import', exact: true }).click();
assert.deepEqual(await page.evaluate(() => window.editor.read()), original);
await page.getByRole('button', { name: 'Add imported rules to draft', exact: true }).click();
const value = await page.evaluate(() => window.editor.read());
assert.equal(value.rules.length, 3); assert.equal(value.rules[2].id, 'imported-1'); assert.deepEqual(value.acls, original.acls);
assert.deepEqual(await page.evaluate(() => window.calls.map(call => call.url)), ['/api/policy/import-haproxy']);
});
await check('conflicting ACL imports are rejected atomically', async () => {
const value = await page.evaluate(original => {
try { window.rustProxyPolicy.mergeImports(original, { acls: { mobile: { all: [] } }, rules: [{ id: 'unsafe', actions: [] }] }); return null; }
catch (error) { return error.message; }
}, original);
assert.match(value, /mobile/);
assert.equal(await page.evaluate(() => window.editor.read().rules.length), 3);
});
await check('tester uses server API and preserves duplicate request/response fields', async () => {
await mount({ rules: [original.rules[1]] }); await page.locator('.policy-tester > summary').click();
const response = { request: { headers: [{ name: 'X-Unsafe', value: '<script>throw Error(1)</script>' }] }, response: { status: 200, headers: [{ name: 'Vary', value: 'Accept-Encoding, Accept' }] }, trace: [{ rule: 'two', stage: 'after_response', matched: true, actions: ['normalize_header'], warnings: [] }], variables: {}, cache: {} };
await page.evaluate(response => { window.apiResult = response; }, response);
await page.getByRole('button', { name: 'Run test', exact: true }).click();
const calls = await page.evaluate(() => window.calls); assert.equal(calls[0].url, '/api/policy/test');
assert.deepEqual(calls[0].body.response.headers, [{ name: 'Vary', value: 'Accept-Encoding' }, { name: 'Vary', value: 'Accept,Accept-Encoding' }]);
assert.equal(calls[0].body.stage, 'after_response'); assert.equal(await page.locator('.policy-trace tbody tr').count(), 1);
assert.match(await page.locator('.policy-test-output').innerText(), /<script>/); assert.equal(await page.locator('.policy-test-output script').count(), 0);
});
await check('tester inputs do not dirty or invalidate the configuration form', async () => {
await mount(); await page.locator('.policy-tester > summary').click();
await page.getByLabel('Transaction variables (JSON string values)', { exact: true }).fill('malformed');
await page.getByRole('button', { name: 'Run test', exact: true }).click();
assert.equal(await page.evaluate(() => window.changed), 0); assert.equal(await page.evaluate(() => window.parentChanged), 0);
assert.equal(await page.evaluate(() => document.getElementById('fixture').checkValidity()), true);
});
await check('location editor excludes pre_route and refuses raw configuration using it', async () => {
await mount({}, 'location');
assert.equal(await page.locator('.policy-tester option[value="pre_route"]').count(), 0);
await page.getByRole('button', { name: 'Policy JSON', exact: true }).click();
await page.locator('.policy-raw textarea').fill(JSON.stringify({ rules: [{ id: 'bad', stage: 'pre_route', actions: [] }] }));
assert.match(await page.evaluate(() => { try { window.editor.read(); return ''; } catch (error) { return error.message; } }), /pre_route/);
});
await check('asynchronous tester rejects stale results after input changes', async () => {
await mount({ rules: [original.rules[1]] }); await page.locator('.policy-tester > summary').click();
await page.evaluate(() => { window.pendingApi = true; });
await page.getByRole('button', { name: 'Run test', exact: true }).click();
await page.getByLabel('Host', { exact: true }).fill('different.example');
await page.evaluate(() => { window.pendingApi = false; window.resolveApi({ trace: [] }); });
await page.getByText('The draft or test input changed during evaluation. Run the test again.', { exact: true }).waitFor();
});
await check('responsive policy editor remains within the viewport', async () => {
await mount({ rules: [original.rules[1]] });
await page.setViewportSize({ width: 390, height: 850 });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= 390), true);
if (process.env.POLICY_TEST_SCREENSHOT) await page.screenshot({ path: process.env.POLICY_TEST_SCREENSHOT, fullPage: true });
});
assert.deepEqual(errors, []); console.log(`PASS: ${checks} policy editor regression checks`);
} finally { await browser.close(); }
})().catch(error => { console.error(error); process.exitCode = 1; });
+11 -3
View File
@@ -1,5 +1,5 @@
"use strict";
let vhostCacheRulesEditor = null;
let vhostCacheRulesEditor = null, vhostPolicyEditor = null;
let basicEditor = null, locationsReader = () => [], aclControl = null, editing = null, revision = null, dirty = false, initialized = false, readBindings = () => [], readHosts = () => [], countryRatesReader = () => [], uaRatesReader = () => [], pagesEditor = null, stagedCertificates = [], uploading = false, draftEpoch = 0, backendHealthEditorControl = null, vhostBalancingControl = null, vhostHeadersControl = null, headersPreviewControl = null, presetsRefresh = () => { };
const chartHistory = new Map();
const backendTrafficHistory = new Map();
@@ -23,7 +23,7 @@ const field = (parent, name, key, value, type = "text", options = {}) => {
};
const group = (key, advanced = false) => {
const box = el(advanced ? "details" : "fieldset", undefined, "vh-group");
box.dataset.tab = ({ vhEditor: "details", vhFrontends: "details", vhBackendPool: "backends", vhBackendDiagnostics: "headers", vhProxyTimeouts: "backends", vhBalancing: "backends", vhSticky: "backends", vhHealth: "health", vhPassiveHealth: "health", vhSecurity: "security", vhTrafficPolicy: "security", vhTinyauth: "auth", vhResponsePolicy: "headers", vhHeaders: "headers", vhHeadersPreview: "headers", vhAdvanced: "advanced", vhLocations: "locations", vhSsl: "ssl", vhSslSettings: "ssl", vhCache: "cache", vhCompression: "compression", vhTransform: "transform", vhPages: "pages" })[key] || "advanced"; box.append(text(advanced ? "summary" : "legend", key));
box.dataset.tab = ({ vhEditor: "details", vhFrontends: "details", vhBackendPool: "backends", vhBackendDiagnostics: "headers", vhProxyTimeouts: "backends", vhBalancing: "backends", vhSticky: "backends", vhHealth: "health", vhPassiveHealth: "health", vhSecurity: "security", vhTrafficPolicy: "security", vhTinyauth: "auth", vhResponsePolicy: "headers", vhHeaders: "headers", policyTitle: "headers", vhHeadersPreview: "headers", vhAdvanced: "advanced", vhLocations: "locations", vhSsl: "ssl", vhSslSettings: "ssl", vhCache: "cache", vhCompression: "compression", vhTransform: "transform", vhPages: "pages" })[key] || "advanced"; box.append(text(advanced ? "summary" : "legend", key));
const body = el("div", undefined, "vh-grid"); box.append(body); container.append(box); return body;
};
const note = (parent, key) => { const node = text("p", key, "fine vh-wide"); parent.append(node); return node; };
@@ -174,7 +174,7 @@ function suspendDraft() {
editing, revision, label: $("vhost-editing").textContent,
fields: window.rustProxyDrafts.takeChildren(container), tabs: window.rustProxyDrafts.takeChildren($("vhost-tabs")),
basicEditor, locationsReader, aclControl, readBindings, readHosts, countryRatesReader, uaRatesReader, pagesEditor, backendHealthEditorControl,
stagedCertificates, uploading
stagedCertificates, uploading, vhostPolicyEditor, vhostCacheRulesEditor, vhostHeadersControl, headersPreviewControl, presetsRefresh
};
const title = read("id")?.value.trim() || editing || t("draftUntitled");
draftEpoch++; editing = null; revision = null; dirty = false; stagedCertificates = []; uploading = false; dialog.close();
@@ -184,6 +184,8 @@ function restoreDraft(state) {
draftEpoch++; window.rustProxyDrafts.restoreChildren(container, state.fields); window.rustProxyDrafts.restoreChildren($("vhost-tabs"), state.tabs);
editing = state.editing; revision = state.revision; basicEditor = state.basicEditor; locationsReader = state.locationsReader; aclControl = state.aclControl;
readBindings = state.readBindings; readHosts = state.readHosts; countryRatesReader = state.countryRatesReader; uaRatesReader = state.uaRatesReader || (() => []); pagesEditor = state.pagesEditor; backendHealthEditorControl = state.backendHealthEditorControl || null;
vhostPolicyEditor = state.vhostPolicyEditor || null; vhostCacheRulesEditor = state.vhostCacheRulesEditor || null;
vhostHeadersControl = state.vhostHeadersControl || null; headersPreviewControl = state.headersPreviewControl || null; presetsRefresh = state.presetsRefresh || (() => {});
stagedCertificates = state.stagedCertificates || []; uploading = state.uploading === true; initialized = true; dirty = true; $("vhost-editing").textContent = state.label;
if (!dialog.open) dialog.showModal(); if (latestStatus) renderStatus(latestStatus);
}
@@ -402,6 +404,7 @@ function locationsEditor(parent, values) {
country_access: { mode: str("location-country-mode", r), countries: lines(str("location-country-list", r)).map(value => value.toUpperCase()) },
method_policy: { mode: str("location-method-mode", r), methods: lines(str("location-method-list", r)).map(value => value.toUpperCase()) },
headers: r.readHeaders(),
policy: r.readPolicy(),
rewrite: { mode: handled ? rewriteMode : "preserve", value: handled && rewriteMode !== "preserve" ? read("location-rewrite-value", r).value.trim() : "" },
response: action === "return" ? { status: Number(str("location-response-status", r)), content_type: str("location-response-type", r), body: read("location-response-body", r).value } : null,
redirect: action === "redirect" ? { status: Number(str("location-redirect-status", r)), target: str("location-redirect-target", r), rewrite_pattern: nullable("location-redirect-pattern", r), preserve_query: yes("location-redirect-query", r) } : null,
@@ -501,6 +504,11 @@ function locationsEditor(parent, values) {
const raw = field(jsonPane, "location-headers", "headersAdvancedJson", JSON.stringify(value.headers || {}, null, 2), "textarea", { rows: 8, maxLength: 65536 });
const editor = headerEditors(visualPane, value.headers || {}, raw, sync, () => ({ location: str("location-id", row) || "main" })); row.readHeaders = () => editor.read();
const policyBox = el("details", undefined, "vh-wide location-section"), policyBody = el("div", undefined, "policy-detail-body");
policyBox.append(text("summary", "policyTitle"), policyBody); body.append(policyBox);
const policyEditor = window.rustProxyPolicy.create({ value: value.policy || {}, scope: "location", onChange: sync });
policyBody.append(policyEditor.node); row.readPolicy = () => policyEditor.read();
const preview = el("section", undefined, "vh-wide location-preview");
preview.append(text("h4", "locationPreviewTitle"));
const previewStatus = text("p", "locationPreviewDisabled", "fine location-preview-disabled"); preview.append(previewStatus);
+2 -1
View File
@@ -579,6 +579,7 @@ function load(value = defaults(), migrationIds = [], show = true) {
transformEnabled.addEventListener("change", syncTransform); customTransformExtensions.addEventListener("change", syncTransform); syncTransform();
note(transformOptions, "vhTransformHelp");
g = group("vhHeaders"); g.parentElement.classList.add("hdr-rules-anchor"); vhostHeadersControl = headerEditors(g, value.headers || {});
g = group("policyTitle"); vhostPolicyEditor = window.rustProxyPolicy.create({ value: value.policy || {}, scope: "vhost", onChange: changed }); g.append(vhostPolicyEditor.node);
g = group("vhPages"); g.classList.add("vh-pages-grid"); pagesEditor = window.rustProxyPages.vhostEditor(g, value.pages || {});
initTabs(); dirty = false; if (latestStatus) renderStatus(latestStatus); if (show && !dialog.open) dialog.showModal();
headersPreviewControl?.refresh(); presetsRefresh();
@@ -662,7 +663,7 @@ function collect() {
allow_private: yes("oidc-private"), address_allowlist: lines(str("oidc-allowlist")),
tls_ca_pem: nullable("oidc-ca"), connect_timeout_seconds: num("oidc-connect"),
timeout_seconds: num("oidc-timeout"), session_ttl_seconds: num("oidc-ttl") },
backends: members, routes: paths, acl, headers,
backends: members, routes: paths, acl, headers, policy: vhostPolicyEditor ? vhostPolicyEditor.read() : {},
load_balancing: {
algorithm: str("algorithm"), ...(vhostBalancingControl?.hash() ? { hash: vhostBalancingControl.hash() } : {}), slow_start_seconds: num("slow-start"), keepalive: { enabled: yes("keepalive"), idle_timeout_seconds: num("idle-timeout"), max_idle_per_host: num("max-idle"), tcp_keepalive_seconds: num("tcp-keepalive"), pool_recycle_requests: num("pool-recycle-requests"), pool_recycle_seconds: num("pool-recycle-seconds"), http1_max_buffer_bytes: num("http1-max-buffer") },
retry: { max_retries: num("retry-max"), retry_connect_errors: yes("retry-connect"), retry_timeouts: yes("retry-timeouts"), retry_statuses: str("retry-statuses").split(/[\s,]+/).filter(Boolean).map(value => Number(value)) },
+1
View File
@@ -61,6 +61,7 @@ function headersPreview(parent) {
const column = (key, hint) => { const col = el("section", undefined, "hdr-preview-col"); col.append(text("h4", key), text("p", hint, "fine")); const listNode = el("ul", undefined, "hdr-preview-list"); col.append(listNode); columns.append(col); return listNode; };
const requestList = column("hdrPreviewRequest", "hdrPreviewRequestHint"), responseList = column("hdrPreviewResponse", "hdrPreviewResponseHint");
box.append(text("p", "hdrPreviewHelp", "fine"));
box.append(text("p", "policyHeaderPreviewHelp", "fine"));
const fillSelect = (node, options, current) => { node.replaceChildren(...options.map(([value, label]) => { const o = el("option", label); o.value = value; return o; })); node.value = options.some(([v]) => v === current) ? current : options[0]?.[0] ?? ""; return node.value; };
const readRoutes = () => { try { return JSON.parse(read("paths")?.value || "[]"); } catch { return []; } };
const safe = fn => { try { return fn(); } catch { return undefined; } };
+61
View File
@@ -1340,6 +1340,67 @@ mod tests {
"stored no-cache response still requires validation next time"
);
}
#[tokio::test]
async fn response_overrides_survive_foreground_revalidation() {
let cache = Cache::new(1);
let t = ticket(&cache, &HeaderMap::new());
let s = settings();
let mut h = headers("public, max-age=600");
h.insert("etag", HeaderValue::from_static("\"origin\""));
let p = plan(StatusCode::OK, &h, &s, Duration::ZERO).unwrap();
let mut response = Response::new(Body::from("payload"));
*response.headers_mut() = h;
cache
.wrap(response, t.clone(), p, &s)
.into_body()
.collect()
.await
.unwrap();
let cached = cache.revalidation(&t).expect("cached validator/body");
let validation = headers("public, max-age=600");
let overrides = ResponseOverrides {
ttl: Some(17),
grace: Some(9),
..ResponseOverrides::NONE
};
let hit = cache
.publish_revalidated_with(
t.clone(),
&cached,
cached.merge_validation_headers(&validation),
&validation,
&s,
Duration::ZERO,
&overrides,
)
.expect("validated body");
assert_eq!(hit.remaining_ttl, 17);
{
let store = cache.store.lock().unwrap();
let entry = store.entries.values().next().unwrap();
assert_eq!(entry.ttl, 17);
assert_eq!(entry.stale_while_revalidate, 9);
}
let no_store = ResponseOverrides {
no_store: true,
..overrides
};
assert!(
cache
.publish_revalidated_with(
t,
&cached,
cached.merge_validation_headers(&validation),
&validation,
&s,
Duration::ZERO,
&no_store,
)
.is_none(),
"no_store must prevent publishing a 304 refresh"
);
}
#[tokio::test]
async fn resident_age_survives_successful_revalidation() {
let cache = Cache::new(1);
+32 -1
View File
@@ -17,6 +17,28 @@ impl Cache {
validation_headers: &HeaderMap,
settings: &Settings,
response_delay: Duration,
) -> Option<Hit> {
self.publish_revalidated_with(
ticket,
cached,
headers,
validation_headers,
settings,
response_delay,
&ResponseOverrides::NONE,
)
}
#[allow(clippy::too_many_arguments)]
pub fn publish_revalidated_with(
&self,
ticket: Ticket,
cached: &Revalidation,
headers: HeaderMap,
validation_headers: &HeaderMap,
settings: &Settings,
response_delay: Duration,
overrides: &ResponseOverrides,
) -> Option<Hit> {
self.publish_validated(
ticket,
@@ -25,6 +47,7 @@ impl Cache {
validation_headers,
settings,
response_delay,
overrides,
true,
)
}
@@ -45,6 +68,7 @@ impl Cache {
validation_headers,
settings,
response_delay,
&ResponseOverrides::NONE,
false,
)
.is_some()
@@ -59,9 +83,16 @@ impl Cache {
validation_headers: &HeaderMap,
settings: &Settings,
response_delay: Duration,
overrides: &ResponseOverrides,
client_hit: bool,
) -> Option<Hit> {
let plan = plan(StatusCode::OK, &headers, settings, response_delay)?;
let plan = plan_with(
StatusCode::OK,
&headers,
settings,
response_delay,
overrides,
)?;
if cached.body.len() > settings.max_object_bytes {
return None;
}
+1
View File
@@ -13,3 +13,4 @@ include!("lookup.rs");
include!("policy.rs");
include!("fill.rs");
include!("tests.rs");
include!("vcl_matrix_tests.rs");
+58 -10
View File
@@ -441,18 +441,66 @@ mod cache_decision_tests {
)
.unwrap();
assert!(imported.warnings.is_empty(), "{:?}", imported.warnings);
assert_eq!(imported.rules.len(), 2);
assert_eq!(imported.rules[0].actions, vec![RuleAction::CookiePass]);
assert!(imported.rules[0].stop);
assert_eq!(imported.rules[1].actions, vec![RuleAction::Pass]);
let json = serde_json::to_value(&imported.rules[0]).unwrap();
assert_eq!(
imported.rules.len(),
4,
"two branch entries and two action steps"
);
for entry in [0, 2] {
let marker = &imported.rules[entry];
assert!(marker.actions.is_empty() && !marker.stop);
let flow = marker.vcl_flow.as_ref().unwrap();
assert_eq!(usize::from(flow.index), entry);
assert_eq!(flow.count, 4);
assert_eq!(flow.branches.len(), 1);
assert!(flow.guards.is_empty());
let step = &imported.rules[entry + 1];
assert!(step.stop);
let step_flow = step.vcl_flow.as_ref().unwrap();
assert!(step_flow.branches.is_empty());
assert_eq!(
step_flow.guards,
vec![VclGuard {
entry: entry as u16,
branch: 0
}]
);
}
assert_eq!(imported.rules[1].actions, vec![RuleAction::CookiePass]);
assert_eq!(imported.rules[3].actions, vec![RuleAction::Pass]);
let json = serde_json::to_value(&imported.rules[1]).unwrap();
assert_eq!(json["actions"][0]["type"], "cookie_pass");
// A guard without a Cookie condition is rejected at import time.
let restored: Vec<Rule> =
serde_json::from_value(serde_json::to_value(&imported.rules).unwrap()).unwrap();
assert_eq!(
restored, imported.rules,
"roundtrip must preserve control metadata"
);
let compiled = compile(restored);
let session = compiled.evaluate_request(&get("/", &[("cookie", "SESSabc=1")]), false);
assert!(session.pass.is_some() && session.pass_cookie_guard);
let admin = compiled.evaluate_request(&get("/admin", &[]), false);
assert!(admin.pass.is_some() && !admin.pass_cookie_guard);
assert!(compiled
.evaluate_request(&get("/", &[]), false)
.pass
.is_none());
let invalid = import_vcl(
"vcl 4.1;\nsub vcl_recv {\n if (req.url ~ \"^/x\") { return (cookie_pass); }\n}\n",
)
.unwrap();
assert!(invalid.rules.is_empty());
assert_eq!(
invalid.rules.len(),
1,
"only the harmless branch entry remains"
);
assert!(invalid.rules[0].actions.is_empty() && !invalid.rules[0].stop);
assert_eq!(
invalid.rules[0].vcl_flow.as_ref().unwrap().branches.len(),
1
);
let skipped = compile(invalid.rules.clone()).evaluate_request(&get("/x", &[]), false);
assert!(skipped.pass.is_none() && skipped.matched.is_empty());
assert!(
invalid
.warnings
@@ -461,11 +509,12 @@ mod cache_decision_tests {
"{:?}",
invalid.warnings
);
// Older configurations keep deserializing unchanged.
let legacy: Rule =
serde_json::from_value(serde_json::json!({"id": "x", "actions": [{"type": "pass"}]}))
.unwrap();
assert_eq!(legacy.actions, vec![RuleAction::Pass]);
assert!(legacy.vcl_flow.is_none());
}
#[test]
@@ -500,8 +549,7 @@ mod cache_decision_tests {
&settings
)
.is_some());
// Private paths are protected only by an explicit pass (or by
// cache.bypass_prefixes); the Drupal example has none.
assert_eq!(
relax(&rules, &get("/admin/style.css", &session), &settings).is_none(),
has_private_paths
+522 -110
View File
@@ -5,6 +5,8 @@ const MAX_RULE_VALUES: usize = 64;
const MAX_RULE_VALUE_BYTES: usize = 512;
const MAX_RULE_REGEX_BYTES: usize = 1 << 16;
const MAX_RULE_TTL_SECONDS: u64 = 365 * 86_400;
const MAX_VCL_FLOW_BRANCHES: usize = 16;
const MAX_VCL_FLOW_CONDITIONS: usize = MAX_CACHE_RULES * MAX_RULE_CONDITIONS;
const PROTECTED_RULE_HEADERS: &[&str] = &[
"connection",
"content-length",
@@ -23,20 +25,32 @@ const PROTECTED_RULE_HEADERS: &[&str] = &[
"alt-svc",
];
/// Restrict request-side VCL mutations to representation headers. Identity,
/// authorization, cache directives and transport framing must remain under
/// RustProxy's normal request/security policy.
fn request_rule_header_name(value: &str) -> Result<http::HeaderName> {
let header = rule_header_name(value)?;
let name = header.as_str();
ensure!(
!PROTECTED_RULE_HEADERS.contains(&name)
&& !matches!(name,
"authorization" | "cookie" | "cache-control" | "pragma" |
"range" | "if-match" | "if-none-match" | "if-modified-since" |
"if-unmodified-since" | "if-range" | "forwarded" | "via" |
"x-real-ip" | "x-client-ip" | "true-client-ip" | "cf-connecting-ip" |
"content-type" | "expect")
&& !matches!(
name,
"authorization"
| "cookie"
| "cache-control"
| "pragma"
| "range"
| "if-match"
| "if-none-match"
| "if-modified-since"
| "if-unmodified-since"
| "if-range"
| "forwarded"
| "via"
| "x-real-ip"
| "x-client-ip"
| "true-client-ip"
| "cf-connecting-ip"
| "content-type"
| "expect"
)
&& !name.starts_with("x-forwarded-")
&& !name.starts_with("proxy-")
&& !name.starts_with("x-rustproxy-")
@@ -145,26 +159,24 @@ pub struct RuleCondition {
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum RuleAction {
/// Explicit VCL `return(pass)`. Never relaxed by any global cache option.
Pass,
/// Cookie/session guard: BYPASS a request because it carries cookies.
/// Unlike `pass`, the central cache decision may let a *public static
/// asset* reach the cache when the global "Ignore request cookies for
/// static files" option is on and no other rule would bypass the same
/// request (see `cache::static_cookie_guard_relaxation`).
/// VCL: `return(cookie_pass)` (RustProxy extension).
CookiePass,
/// Explicit VCL return(hash): allow a Cookie-bearing request to reach lookup.
Lookup,
SetRequestHeader { name: String, value: String },
RemoveRequestHeader { name: String },
SetRequestHeader {
name: String,
value: String,
},
RemoveRequestHeader {
name: String,
},
StripCookies {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
keep: Vec<String>,
},
/// Remove explicitly named cookies or names matching a trailing-* prefix.
/// Unknown cookies remain available for session checks and cache bypass.
RemoveNamedCookies { names: Vec<String> },
RemoveNamedCookies {
names: Vec<String>,
},
StripQuery {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
params: Vec<String>,
@@ -184,13 +196,16 @@ pub enum RuleAction {
seconds: u64,
},
NoStore,
/// Reverse an earlier rule NoStore without bypassing origin privacy guards.
AllowStore,
IgnoreCacheControl,
StripSetCookie,
/// Rewrite a backend header before determining cacheability and delivery.
SetBackendHeader { name: String, value: String },
RemoveBackendHeader { name: String },
SetBackendHeader {
name: String,
value: String,
},
RemoveBackendHeader {
name: String,
},
SetHeader {
name: String,
value: String,
@@ -260,13 +275,274 @@ pub struct Rule {
pub actions: Vec<RuleAction>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub stop: bool,
/// Imported vcl_hash actions run after vcl_recv (even after return(hash)).
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub hash_stage: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub vcl_flow: Option<VclFlow>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub vhosts: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct VclFlow {
pub version: u8,
pub group: String,
pub index: u16,
pub count: u16,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub guards: Vec<VclGuard>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub branches: Vec<VclBranch>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct VclGuard {
pub entry: u16,
pub branch: u16,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct VclBranch {
pub any: Vec<Vec<RuleCondition>>,
}
fn validate_vcl_flow_node(rule: &Rule) -> Result<()> {
let Some(flow) = &rule.vcl_flow else {
return Ok(());
};
ensure!(
flow.version == 1,
"cache rule {}: unsupported VCL flow version",
rule.id
);
ensure!(
flow.group.len() <= 64 && crate::config::valid_id(&flow.group),
"cache rule {}: invalid VCL flow group",
rule.id
);
ensure!(
flow.count > 0 && usize::from(flow.count) <= MAX_CACHE_RULES && flow.index < flow.count,
"cache rule {}: invalid VCL flow position",
rule.id
);
ensure!(
rule.conditions.is_empty() && rule.match_mode == RuleMatch::All,
"cache rule {}: VCL flow conditions belong to branch-entry markers",
rule.id
);
ensure!(
flow.guards.len() <= MAX_RULE_CONDITIONS,
"cache rule {}: VCL flow nesting exceeds {MAX_RULE_CONDITIONS}",
rule.id
);
ensure!(
flow.branches.len() <= MAX_VCL_FLOW_BRANCHES,
"cache rule {}: too many VCL branches",
rule.id
);
if !flow.branches.is_empty() {
ensure!(
rule.actions.is_empty() && !rule.stop,
"cache rule {}: VCL branch-entry markers cannot contain actions or stop",
rule.id
);
}
let mut conditions = 0;
for (branch_index, branch) in flow.branches.iter().enumerate() {
ensure!(
!branch.any.is_empty() && branch.any.len() <= MAX_CACHE_RULES,
"cache rule {}: invalid VCL branch clause count",
rule.id
);
for clause in &branch.any {
ensure!(
clause.len() <= MAX_RULE_CONDITIONS,
"cache rule {}: too many conditions in a VCL clause",
rule.id
);
if clause.is_empty() {
ensure!(
branch.any.len() == 1 && branch_index + 1 == flow.branches.len(),
"cache rule {}: unconditional VCL branch must be the final branch",
rule.id
);
}
conditions += clause.len();
}
}
ensure!(
conditions <= MAX_VCL_FLOW_CONDITIONS,
"cache rule {}: VCL flow condition limit exceeded",
rule.id
);
Ok(())
}
fn vcl_branch_without_cookie(branch: &VclBranch) -> Option<bool> {
let mut unknown_clause = false;
for clause in &branch.any {
let mut unknown_atom = false;
let mut false_atom = false;
for condition in clause {
let cookie = condition.field == ConditionField::Cookie
|| (condition.field == ConditionField::Header
&& condition
.name
.as_deref()
.is_some_and(|name| name.trim().eq_ignore_ascii_case("cookie")));
if cookie {
if !condition.negate {
false_atom = true;
break;
}
} else {
unknown_atom = true;
}
}
if !false_atom {
if !unknown_atom {
return Some(true);
}
unknown_clause = true;
}
}
if unknown_clause {
None
} else {
Some(false)
}
}
fn vcl_guard_requires_cookie(guard: &VclGuard, group: &[Rule]) -> bool {
let Some(entry) = group
.get(usize::from(guard.entry))
.and_then(|rule| rule.vcl_flow.as_ref())
else {
return false;
};
entry
.branches
.get(usize::from(guard.branch))
.is_some_and(|branch| vcl_branch_without_cookie(branch) == Some(false))
|| entry
.branches
.iter()
.take(usize::from(guard.branch))
.any(|branch| vcl_branch_without_cookie(branch) == Some(true))
}
fn validate_vcl_flows(rules: &[Rule]) -> Result<()> {
let mut groups = HashSet::new();
let mut position = 0;
while let Some(first) = rules.get(position) {
let Some(first_flow) = &first.vcl_flow else {
position += 1;
continue;
};
validate_vcl_flow_node(first)?;
ensure!(
first_flow.index == 0 && groups.insert(first_flow.group.as_str()),
"VCL flow group {} is reordered, incomplete or duplicated; keep each import together",
first_flow.group
);
let end = position + usize::from(first_flow.count);
ensure!(
end <= rules.len(),
"VCL flow group {} is incomplete",
first_flow.group
);
let group = &rules[position..end];
let mut open = vec![false; group.len()];
let mut last_branch = vec![None; group.len()];
let mut condition_count = 0usize;
for (index, rule) in group.iter().enumerate() {
let flow = rule.vcl_flow.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"VCL flow group {} is interrupted by a flat rule",
first_flow.group
)
})?;
validate_vcl_flow_node(rule)?;
ensure!(
flow.group == first_flow.group
&& flow.count == first_flow.count
&& usize::from(flow.index) == index,
"VCL flow group {} must remain complete and in its original order",
first_flow.group
);
ensure!(
rule.enabled == first.enabled && rule.vhosts == first.vhosts,
"VCL flow group {} must use one enabled state and vhost scope",
first_flow.group
);
for (depth, guard) in flow.guards.iter().enumerate() {
let entry_index = usize::from(guard.entry);
ensure!(
entry_index < index && open[entry_index],
"cache rule {}: VCL guard must reference an open earlier branch entry",
rule.id
);
let entry_rule = &group[entry_index];
let entry = entry_rule
.vcl_flow
.as_ref()
.expect("earlier group node validated");
ensure!(
entry_rule.stage == rule.stage && entry_rule.hash_stage == rule.hash_stage,
"cache rule {}: VCL guard cannot cross hooks",
rule.id
);
ensure!(
usize::from(guard.branch) < entry.branches.len()
&& entry.guards.as_slice() == &flow.guards[..depth],
"cache rule {}: invalid VCL guard ancestry or branch",
rule.id
);
ensure!(
last_branch[entry_index].is_none_or(|previous| guard.branch >= previous),
"cache rule {}: VCL branches cannot be reordered or re-entered",
rule.id
);
last_branch[entry_index] = Some(guard.branch);
}
for (entry, active) in open.iter_mut().enumerate().take(index) {
if !flow
.guards
.iter()
.any(|guard| usize::from(guard.entry) == entry)
{
*active = false;
}
}
open[index] = !flow.branches.is_empty();
condition_count += flow
.branches
.iter()
.flat_map(|branch| &branch.any)
.map(Vec::len)
.sum::<usize>();
ensure!(
condition_count <= MAX_VCL_FLOW_CONDITIONS,
"VCL flow group {} exceeds {MAX_VCL_FLOW_CONDITIONS} condition nodes",
flow.group
);
if rule
.actions
.iter()
.any(|action| matches!(action, RuleAction::CookiePass))
{
ensure!(flow.guards.iter().any(|guard| vcl_guard_requires_cookie(guard, group)),
"cache rule {}: cookie_pass needs a branch guaranteed to require Cookie; use pass otherwise", rule.id);
}
}
position = end;
}
Ok(())
}
fn rule_header_name(value: &str) -> Result<http::HeaderName> {
let name = http::HeaderName::from_bytes(value.trim().as_bytes())
.map_err(|_| anyhow::anyhow!("invalid header name {value:?}"))?;
@@ -281,15 +557,11 @@ fn valid_cookie_name(value: &str) -> bool {
.all(|byte| byte.is_ascii_graphic() && !b"()<>@,;:\\\"/[]?={}".contains(&byte))
}
// Selective Cookie removal accepts exact names or a single trailing '*'.
// No interior wildcards, '?' patterns, empty prefixes or general regexes:
// a broad match here could expose a logged-in page from shared cache.
fn valid_cookie_remove_selector(value: &str) -> bool {
if value.len() > 128 {
return false;
}
match value.strip_suffix('*') {
// Avoid accidentally stripping huge sets of cookies with "a*" / "s*".
Some(prefix) => prefix.len() >= 3 && !prefix.contains('*') && valid_cookie_name(prefix),
None => !value.contains('*') && valid_cookie_name(value),
}
@@ -336,10 +608,11 @@ pub fn validate_rules(rules: &[Rule], global: bool) -> Result<()> {
);
}
}
validate_vcl_flows(rules)?;
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RuleOrigin {
Vhost,
@@ -444,9 +717,20 @@ pub struct CompiledRule {
actions: Vec<RuleAction>,
stop: bool,
hash_stage: bool,
vcl_flow: Option<CompiledVclFlow>,
counter: Arc<AtomicU64>,
}
#[derive(Debug)]
struct CompiledVclFlow {
group: String,
index: u16,
guards: Vec<VclGuard>,
branches: Vec<Vec<Vec<CompiledCondition>>>,
}
type VclChoices<'a> = HashMap<(RuleOrigin, &'a str, u16), Option<u16>>;
fn compile_condition(condition: &RuleCondition, stage: RuleStage) -> Result<CompiledCondition> {
ensure!(
!(condition.field.response_only() && stage == RuleStage::Request),
@@ -613,10 +897,14 @@ fn validate_action(action: &RuleAction) -> Result<()> {
);
}
RuleAction::RemoveNamedCookies { names } => {
ensure!(!names.is_empty() && names.len() <= MAX_RULE_VALUES,
"remove_named_cookies requires 1 to 64 cookie names or prefix* selectors");
ensure!(names.iter().all(|name| valid_cookie_remove_selector(name)),
"invalid cookie removal selector (use an exact name or prefix*)");
ensure!(
!names.is_empty() && names.len() <= MAX_RULE_VALUES,
"remove_named_cookies requires 1 to 64 cookie names or prefix* selectors"
);
ensure!(
names.iter().all(|name| valid_cookie_remove_selector(name)),
"invalid cookie removal selector (use an exact name or prefix*)"
);
}
RuleAction::StripQuery { params, keep_only } => {
ensure!(
@@ -701,7 +989,6 @@ pub fn rule_hit_counts() -> BTreeMap<String, u64> {
.collect()
}
/// A positive condition on the request Cookie header or on one cookie name.
fn condition_tests_cookie(condition: &RuleCondition) -> bool {
!condition.negate
&& match condition.field {
@@ -715,6 +1002,7 @@ fn condition_tests_cookie(condition: &RuleCondition) -> bool {
}
fn compile_rule(rule: &Rule, origin: RuleOrigin, scope: &str) -> Result<CompiledRule> {
validate_vcl_flow_node(rule)?;
ensure!(
crate::config::valid_id(&rule.id),
"invalid cache rule id {:?}",
@@ -730,7 +1018,13 @@ fn compile_rule(rule: &Rule, origin: RuleOrigin, scope: &str) -> Result<Compiled
rule.id
);
ensure!(
(!rule.actions.is_empty() || rule.stop) && rule.actions.len() <= MAX_RULE_ACTIONS,
(!rule.actions.is_empty()
|| rule.stop
|| rule
.vcl_flow
.as_ref()
.is_some_and(|flow| !flow.branches.is_empty()))
&& rule.actions.len() <= MAX_RULE_ACTIONS,
"cache rule {} needs 1-{MAX_RULE_ACTIONS} actions, or a terminal return",
rule.id
);
@@ -749,7 +1043,12 @@ fn compile_rule(rule: &Rule, origin: RuleOrigin, scope: &str) -> Result<Compiled
validate_action(action)
.map_err(|error| anyhow::anyhow!("cache rule {}: {error}", rule.id))?;
}
if rule.actions.iter().any(|action| matches!(action, RuleAction::CookiePass)) {
if rule.vcl_flow.is_none()
&& rule
.actions
.iter()
.any(|action| matches!(action, RuleAction::CookiePass))
{
ensure!(
rule.conditions.iter().any(condition_tests_cookie),
"cache rule {}: cookie_pass needs at least one non-negated Cookie condition; use pass for other bypass rules",
@@ -762,6 +1061,35 @@ fn compile_rule(rule: &Rule, origin: RuleOrigin, scope: &str) -> Result<Compiled
.map(|condition| compile_condition(condition, rule.stage))
.collect::<Result<Vec<_>>>()
.map_err(|error| anyhow::anyhow!("cache rule {}: {error}", rule.id))?;
let vcl_flow = rule
.vcl_flow
.as_ref()
.map(|flow| {
let branches = flow
.branches
.iter()
.map(|branch| {
branch
.any
.iter()
.map(|clause| {
clause
.iter()
.map(|condition| compile_condition(condition, rule.stage))
.collect::<Result<Vec<_>>>()
})
.collect::<Result<Vec<_>>>()
})
.collect::<Result<Vec<_>>>()?;
Ok::<_, anyhow::Error>(CompiledVclFlow {
group: flow.group.clone(),
index: flow.index,
guards: flow.guards.clone(),
branches,
})
})
.transpose()
.map_err(|error| anyhow::anyhow!("cache rule {}: {error}", rule.id))?;
Ok(CompiledRule {
id: rule.id.clone(),
name: rule.name.clone(),
@@ -772,6 +1100,7 @@ fn compile_rule(rule: &Rule, origin: RuleOrigin, scope: &str) -> Result<Compiled
actions: rule.actions.clone(),
stop: rule.stop,
hash_stage: rule.hash_stage,
vcl_flow,
counter: rule_counter(origin, scope, &rule.id),
})
}
@@ -791,6 +1120,8 @@ impl CompiledRules {
global: &[Rule],
ignore_global: bool,
) -> Result<Self> {
validate_vcl_flows(vhost)?;
validate_vcl_flows(global)?;
let mut compiled = Self::default();
let globals = global
.iter()
@@ -818,8 +1149,10 @@ impl CompiledRules {
Ok(compiled)
}
pub fn is_empty(&self) -> bool {
self.request.is_empty() && self.hash.is_empty()
&& self.response.is_empty() && self.deliver.is_empty()
self.request.is_empty()
&& self.hash.is_empty()
&& self.response.is_empty()
&& self.deliver.is_empty()
}
pub fn has_deliver_rules(&self) -> bool {
!self.deliver.is_empty()
@@ -910,11 +1243,6 @@ impl CompiledCondition {
.as_ref()
.map(|header| {
if header.as_str() == http::header::COOKIE.as_str() {
// Cookie can appear in several field lines. An anchored
// allowlist must match all of them, not just one. Bad
// UTF-8 or an empty field must still count as present
// so subsequent `if (req.http.Cookie) return(pass)`
// remains fail-closed.
let mut parts = Vec::new();
for value in request.headers.get_all(header).iter() {
match value.to_str() {
@@ -922,8 +1250,11 @@ impl CompiledCondition {
Err(_) => return vec![Cow::Borrowed("")],
}
}
return if parts.is_empty() { Vec::new() }
else { vec![Cow::Owned(parts.join("; "))] };
return if parts.is_empty() {
Vec::new()
} else {
vec![Cow::Owned(parts.join("; "))]
};
}
request
.headers
@@ -981,6 +1312,39 @@ impl CompiledCondition {
}
impl CompiledRule {
fn matches_with_flow<'a>(
&'a self,
request: &RuleRequest,
response: Option<(StatusCode, &HeaderMap)>,
choices: &mut VclChoices<'a>,
) -> bool {
let Some(flow) = &self.vcl_flow else {
return self.matches(request, response);
};
if !flow.guards.iter().all(|guard| {
choices.get(&(self.origin, flow.group.as_str(), guard.entry))
== Some(&Some(guard.branch))
}) {
return false;
}
if !flow.branches.is_empty() {
let selected = flow
.branches
.iter()
.position(|branch| {
branch.iter().any(|clause| {
clause
.iter()
.all(|condition| condition.matches(request, response))
})
})
.map(|branch| branch as u16);
choices.insert((self.origin, flow.group.as_str(), flow.index), selected);
return false;
}
self.matches(request, response)
}
fn matches(&self, request: &RuleRequest, response: Option<(StatusCode, &HeaderMap)>) -> bool {
if self.conditions.is_empty() {
return true;
@@ -1016,16 +1380,11 @@ pub struct RuleOverride {
#[derive(Debug, Clone, Default, Serialize)]
pub struct RequestRuleOutcome {
pub pass: Option<String>,
/// True when the winning `pass` came from a `cookie_pass` guard rather
/// than from an explicit `pass`. Only such a bypass can be relaxed.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub pass_cookie_guard: bool,
pub lookup: Option<String>,
/// Ordered, validated edits applied to the forwarded request as well as
/// to the rule evaluation copy.
pub header_edits: Vec<BackendHeaderEdit>,
pub strip_cookies: Option<Vec<String>>,
/// Exact names removed without discarding unrelated session cookies.
pub remove_named_cookies: Vec<String>,
pub query_edits: Vec<(Vec<String>, bool)>,
pub hash: Vec<String>,
@@ -1135,8 +1494,6 @@ fn claim(
false
}
_ => {
// Last matching assignment wins within the same scope; vhost
// priority is preserved over later global rules.
owners.insert(aspect, label);
true
}
@@ -1148,17 +1505,18 @@ impl CompiledRules {
self.evaluate_request_mode(request, count, false)
}
/// Evaluate request rules as if every `cookie_pass` guard were absent:
/// the guard action is skipped and its rule does not stop evaluation, so
/// any later explicit `pass` (or request edit) is still observed. Used by
/// the central static-cookie decision; never counts rule hits.
pub fn evaluate_request_without_cookie_guards(&self, request: &RuleRequest) -> RequestRuleOutcome {
pub fn evaluate_request_without_cookie_guards(
&self,
request: &RuleRequest,
) -> RequestRuleOutcome {
self.evaluate_request_mode(request, false, true)
}
pub fn has_cookie_guards(&self) -> bool {
self.request.iter().chain(self.hash.iter()).any(|rule| {
rule.actions.iter().any(|action| matches!(action, RuleAction::CookiePass))
rule.actions
.iter()
.any(|action| matches!(action, RuleAction::CookiePass))
})
}
@@ -1172,14 +1530,14 @@ impl CompiledRules {
let mut owners = HashMap::new();
let mut header_owners: HashMap<String, RuleOrigin> = HashMap::new();
let mut current = request.clone();
// In Varnish, vcl_hash runs after vcl_recv's return(hash), not as
// ordinary statements after it. Preserve that ordering in imported VCL.
let mut choices = VclChoices::new();
for (is_hash_stage, rules) in [(false, &self.request), (true, &self.hash)] {
if is_hash_stage && outcome.pass.is_some() {
break;
}
for rule in rules.iter() {
if !rule.matches(&current, None) {
if !rule.matches_with_flow(&current, None, &mut choices) {
continue;
}
if count {
@@ -1212,12 +1570,14 @@ impl CompiledRules {
outcome.lookup = Some(rule.id.clone());
outcome.pass = None;
outcome.pass_cookie_guard = false;
},
}
RuleAction::SetRequestHeader { name, value } => {
let key = name.to_ascii_lowercase();
if header_owners.get(&key) == Some(&RuleOrigin::Vhost)
&& rule.origin != RuleOrigin::Vhost
{ continue; }
{
continue;
}
header_owners.insert(key.clone(), rule.origin);
let header = http::HeaderName::from_bytes(key.as_bytes())
.expect("validated request header");
@@ -1225,17 +1585,22 @@ impl CompiledRules {
.expect("validated request header value");
current.headers.insert(header, value_header);
outcome.header_edits.push(BackendHeaderEdit::Set {
name: key, value: value.clone(),
name: key,
value: value.clone(),
});
}
RuleAction::RemoveRequestHeader { name } => {
let key = name.to_ascii_lowercase();
if header_owners.get(&key) == Some(&RuleOrigin::Vhost)
&& rule.origin != RuleOrigin::Vhost
{ continue; }
{
continue;
}
header_owners.insert(key.clone(), rule.origin);
current.headers.remove(key.as_str());
outcome.header_edits.push(BackendHeaderEdit::Remove { name: key });
outcome
.header_edits
.push(BackendHeaderEdit::Remove { name: key });
}
RuleAction::StripCookies { keep } => {
match &mut outcome.strip_cookies {
@@ -1254,7 +1619,8 @@ impl CompiledRules {
}
RuleAction::StripQuery { params, keep_only } => {
outcome.query_edits.push((params.clone(), *keep_only));
if let Some(rewritten) = outcome.rewrite_query(current.query.as_deref()) {
if let Some(rewritten) = outcome.rewrite_query(current.query.as_deref())
{
current.query = rewritten;
}
}
@@ -1262,17 +1628,24 @@ impl CompiledRules {
let value = rule_header_name(name)
.ok()
.map(|header| {
current.headers.get_all(&header).iter()
current
.headers
.get_all(&header)
.iter()
.filter_map(|v| v.to_str().ok())
.collect::<Vec<_>>().join(",")
.collect::<Vec<_>>()
.join(",")
})
.unwrap_or_default();
outcome.hash.push(format!("h:{}={value}", name.to_ascii_lowercase()));
outcome
.hash
.push(format!("h:{}={value}", name.to_ascii_lowercase()));
}
RuleAction::HashCookie { name } => {
let value = cookie_values(&current.headers)
.find(|(key, _)| key == name)
.map(|(_, value)| value).unwrap_or("");
.map(|(_, value)| value)
.unwrap_or("");
outcome.hash.push(format!("c:{name}={value}"));
}
_ => {}
@@ -1297,8 +1670,9 @@ impl CompiledRules {
let mut owners = HashMap::new();
let mut header_owners: HashMap<String, RuleOrigin> = HashMap::new();
let mut current = headers.clone();
let mut choices = VclChoices::new();
for rule in &self.response {
if !rule.matches(request, Some((status, &current))) {
if !rule.matches_with_flow(request, Some((status, &current)), &mut choices) {
continue;
}
if count {
@@ -1330,14 +1704,18 @@ impl CompiledRules {
let key = name.to_ascii_lowercase();
if header_owners.get(&key) == Some(&RuleOrigin::Vhost)
&& rule.origin != RuleOrigin::Vhost
{ continue; }
{
continue;
}
header_owners.insert(key.clone(), rule.origin);
if let (Ok(header), Ok(value_header)) = (
http::HeaderName::from_bytes(key.as_bytes()), HeaderValue::from_str(value)
http::HeaderName::from_bytes(key.as_bytes()),
HeaderValue::from_str(value),
) {
current.insert(header, value_header);
outcome.overrides.header_edits.push(BackendHeaderEdit::Set {
name: key, value: value.clone(),
name: key,
value: value.clone(),
});
}
}
@@ -1345,10 +1723,15 @@ impl CompiledRules {
let key = name.to_ascii_lowercase();
if header_owners.get(&key) == Some(&RuleOrigin::Vhost)
&& rule.origin != RuleOrigin::Vhost
{ continue; }
{
continue;
}
header_owners.insert(key.clone(), rule.origin);
current.remove(key.as_str());
outcome.overrides.header_edits.push(BackendHeaderEdit::Remove { name: key });
outcome
.overrides
.header_edits
.push(BackendHeaderEdit::Remove { name: key });
}
_ => {}
}
@@ -1370,11 +1753,14 @@ impl CompiledRules {
let mut outcome = DeliverRuleOutcome::default();
let mut ownership: HashMap<String, RuleOrigin> = HashMap::new();
let mut current = headers.clone();
let mut choices = VclChoices::new();
for rule in &self.deliver {
if !rule.matches(request, Some((status, &current))) {
if !rule.matches_with_flow(request, Some((status, &current)), &mut choices) {
continue;
}
if count { rule.counter.fetch_add(1, Ordering::Relaxed); }
if count {
rule.counter.fetch_add(1, Ordering::Relaxed);
}
outcome.matched.push(info(rule));
for action in &rule.actions {
let (kind, name, value) = match action {
@@ -1386,20 +1772,27 @@ impl CompiledRules {
let name = name.to_ascii_lowercase();
if ownership.get(&name) == Some(&RuleOrigin::Vhost)
&& rule.origin != RuleOrigin::Vhost
{ continue; }
// A default (set-if-missing) does not claim an existing header.
if kind == 2 && current.contains_key(name.as_str()) { continue; }
{
continue;
}
if kind == 2 && current.contains_key(name.as_str()) {
continue;
}
ownership.insert(name.clone(), rule.origin);
match kind {
1 => {
outcome.set.push((name.clone(), value.to_owned()));
current.insert(http::HeaderName::from_bytes(name.as_bytes()).expect("validated name"),
HeaderValue::from_str(value).expect("validated value"));
current.insert(
http::HeaderName::from_bytes(name.as_bytes()).expect("validated name"),
HeaderValue::from_str(value).expect("validated value"),
);
}
2 => {
outcome.defaults.push((name.clone(), value.to_owned()));
current.insert(http::HeaderName::from_bytes(name.as_bytes()).expect("validated name"),
HeaderValue::from_str(value).expect("validated value"));
current.insert(
http::HeaderName::from_bytes(name.as_bytes()).expect("validated name"),
HeaderValue::from_str(value).expect("validated value"),
);
}
_ => {
outcome.remove.push(name.clone());
@@ -1408,11 +1801,12 @@ impl CompiledRules {
}
outcome.edits.push((kind, name, value.to_owned()));
}
if rule.stop { break; }
if rule.stop {
break;
}
}
outcome
}
}
impl RequestRuleOutcome {
@@ -1420,7 +1814,6 @@ impl RequestRuleOutcome {
for edit in &self.header_edits {
match edit {
BackendHeaderEdit::Set { name, value } => {
// Names and values were validated when the rule was compiled.
if let (Ok(name), Ok(value)) = (
http::HeaderName::from_bytes(name.as_bytes()),
HeaderValue::from_str(value),
@@ -1436,13 +1829,17 @@ impl RequestRuleOutcome {
}
pub fn rewrite_cookies(&self, headers: &mut HeaderMap) {
if self.remove_named_cookies.is_empty() {
// Preserve the pre-existing keep-list behavior for unchanged rules.
let Some(keep) = &self.strip_cookies else { return; };
let Some(keep) = &self.strip_cookies else {
return;
};
let kept: Vec<String> = cookie_values(headers)
.filter(|(name, _)| keep.iter().any(|item| item == name))
.map(|(name, value)| {
if value.is_empty() { name.to_owned() }
else { format!("{name}={value}") }
if value.is_empty() {
name.to_owned()
} else {
format!("{name}={value}")
}
})
.collect();
headers.remove(http::header::COOKIE);
@@ -1454,27 +1851,39 @@ impl RequestRuleOutcome {
return;
}
// Fail closed: never delete an unknown or malformed Cookie field while
// removing selected parent-domain names. Leave it for later pass rules
// or RustProxy's request_cookie policy to reject.
let mut kept = Vec::new();
for header in headers.get_all(http::header::COOKIE).iter() {
let Ok(raw) = header.to_str() else { return; };
let Ok(raw) = header.to_str() else {
return;
};
for part in raw.split(';') {
let Some((name, value)) = part.trim().split_once('=') else { return; };
// Do not normalize whitespace *inside* a cookie name: a
// malformed/lookalike name must stay present and bypass.
if !valid_cookie_name(name) { return; }
if self.remove_named_cookies.iter().any(|selector| cookie_remove_selector_matches(selector, name)) {
let Some((name, value)) = part.trim().split_once('=') else {
return;
};
if !valid_cookie_name(name) {
return;
}
if self
.remove_named_cookies
.iter()
.any(|selector| cookie_remove_selector_matches(selector, name))
{
continue;
}
if self.strip_cookies.as_ref().is_some_and(|allow| !allow.iter().any(|item| item == name)) {
if self
.strip_cookies
.as_ref()
.is_some_and(|allow| !allow.iter().any(|item| item == name))
{
continue;
}
kept.push(format!("{name}={value}"));
}
}
let replacement = if kept.is_empty() { None } else {
let replacement = if kept.is_empty() {
None
} else {
match HeaderValue::from_str(&kept.join("; ")) {
Ok(value) => Some(value),
Err(_) => return,
@@ -1521,7 +1930,9 @@ impl RequestRuleOutcome {
impl DeliverRuleOutcome {
pub fn apply(&self, headers: &mut HeaderMap) {
for (kind, name, value) in &self.edits {
let Ok(header) = http::HeaderName::from_bytes(name.as_bytes()) else { continue; };
let Ok(header) = http::HeaderName::from_bytes(name.as_bytes()) else {
continue;
};
match kind {
1 => {
if let Ok(value) = HeaderValue::from_str(value) {
@@ -1535,11 +1946,12 @@ impl DeliverRuleOutcome {
}
}
}
_ => { headers.remove(header); }
_ => {
headers.remove(header);
}
}
}
}
}
#[derive(Debug, Clone)]
+202 -76
View File
@@ -348,7 +348,16 @@ sub vcl_deliver {
.iter()
.find(|rule| rule.actions.contains(&RuleAction::Ttl { seconds: 3600 }))
.unwrap();
assert!(else_rule.conditions[0].negate);
let guard = else_rule.vcl_flow.as_ref().unwrap().guards.last().unwrap();
assert_eq!(guard.branch, 1);
let entry = imported.rules[usize::from(guard.entry)]
.vcl_flow
.as_ref()
.unwrap();
assert!(
entry.branches[1].any[0].is_empty(),
"else uses the saved branch decision"
);
assert!(imported
.warnings
.iter()
@@ -397,12 +406,19 @@ sub vcl_deliver {
imported.warnings
);
assert_eq!(
imported.rules.len(),
imported
.rules
.iter()
.filter(|rule| !rule.actions.is_empty() || rule.stop)
.count(),
1,
"unsupported VCL must not create executable rules"
);
validate_rules(&imported.rules, true).unwrap();
assert!(imported.rules[0].actions.contains(&RuleAction::Pass));
assert!(imported
.rules
.iter()
.any(|rule| rule.actions.contains(&RuleAction::Pass)));
}
#[test]
@@ -1034,26 +1050,37 @@ sub vcl_deliver {
result.rewrite_cookies(&mut forwarded);
assert_eq!(forwarded.get(http::header::COOKIE).unwrap(), cookie);
}
// Cookie may be split across multiple HTTP header field lines.
// Matching any single field line would discard a real session cookie.
let split = request("/", None, &[
("cookie", "__cf_bm=token"),
("cookie", "session=secret"),
]);
let split = request(
"/",
None,
&[("cookie", "__cf_bm=token"), ("cookie", "session=secret")],
);
let result = compiled.evaluate_request(&split, false);
assert!(result.pass.is_some());
assert!(result.strip_cookies.is_none());
let mut invalid_cookie = request("/", None, &[]);
invalid_cookie.headers.insert(http::header::COOKIE,
HeaderValue::from_bytes(b"__cf_bm=\xff").unwrap());
invalid_cookie.headers.insert(
http::header::COOKIE,
HeaderValue::from_bytes(b"__cf_bm=\xff").unwrap(),
);
let result = compiled.evaluate_request(&invalid_cookie, false);
assert!(result.pass.is_some());
assert!(result.strip_cookies.is_none());
for path in ["/admin", "/admin/settings", "/login", "/api/profile", "/konto"] {
for path in [
"/admin",
"/admin/settings",
"/login",
"/api/profile",
"/konto",
] {
let input = request(path, None, &[("cookie", "__cf_bm=token")]);
assert!(compiled.evaluate_request(&input, false).pass.is_some(), "{path}");
assert!(
compiled.evaluate_request(&input, false).pass.is_some(),
"{path}"
);
}
let input = request("/", None, &[("Authorization", "Bearer test")]);
assert!(compiled.evaluate_request(&input, false).pass.is_some());
@@ -1064,22 +1091,37 @@ sub vcl_deliver {
#[test]
fn vcl_parent_cookie_names_run_before_separate_cdn_template_without_losing_sessions() {
let parent = include_str!(concat!(env!("CARGO_MANIFEST_DIR"),
"/examples/vcl/public-vhost-remove-parent-cookies.vcl"))
.replace("REPLACE_WITH_VERIFIED_PARENT_COOKIE_NAME", "parent_marketing");
let cdn = include_str!(concat!(env!("CARGO_MANIFEST_DIR"),
"/examples/vcl/cdn-technical-cookies.vcl"));
let parent = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/examples/vcl/public-vhost-remove-parent-cookies.vcl"
))
.replace(
"REPLACE_WITH_VERIFIED_PARENT_COOKIE_NAME",
"parent_marketing",
);
let cdn = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/examples/vcl/cdn-technical-cookies.vcl"
));
let imported_parent = import_vcl(&parent).unwrap();
assert!(imported_parent.warnings.is_empty(), "{:?}", imported_parent.warnings);
assert!(
imported_parent.warnings.is_empty(),
"{:?}",
imported_parent.warnings
);
validate_rules(&imported_parent.rules, false).unwrap();
assert!(imported_parent.rules.iter().any(|rule| rule.actions.iter().any(|action|
matches!(action, RuleAction::RemoveNamedCookies { names }
if names.len() == 1 && names[0] == "parent_marketing"))));
assert!(!imported_parent.rules.iter().any(|rule|
rule.actions.iter().any(|action| matches!(action, RuleAction::Lookup | RuleAction::StripCookies { .. }))));
assert!(imported_parent
.rules
.iter()
.any(|rule| rule.actions.iter().any(
|action| matches!(action, RuleAction::RemoveNamedCookies { names }
if names.len() == 1 && names[0] == "parent_marketing")
)));
assert!(!imported_parent.rules.iter().any(|rule| rule
.actions
.iter()
.any(|action| matches!(action, RuleAction::Lookup | RuleAction::StripCookies { .. }))));
// Combine the *separate* examples in the same Vhost rule order. A
// parent+CDN mix must cache, while a parent+session mix must pass.
let combined = import_vcl(&format!("{parent}\n{cdn}")).unwrap();
assert!(combined.warnings.is_empty(), "{:?}", combined.warnings);
validate_rules(&combined.rules, false).unwrap();
@@ -1089,8 +1131,16 @@ sub vcl_deliver {
("parent_marketing=1", None, false),
("parent_marketing=1; __cf_bm=2", None, false),
("__cf_bm=2; parent_marketing=1", None, false),
("parent_marketing=1; app_session=abc", Some("app_session=abc"), true),
("__cf_bm=2; parent_marketing=1; app_session=abc", Some("__cf_bm=2; app_session=abc"), true),
(
"parent_marketing=1; app_session=abc",
Some("app_session=abc"),
true,
),
(
"__cf_bm=2; parent_marketing=1; app_session=abc",
Some("__cf_bm=2; app_session=abc"),
true,
),
("app_session=abc", Some("app_session=abc"), true),
("unknown=1", Some("unknown=1"), true),
("__cf_bm=2", None, false),
@@ -1101,44 +1151,71 @@ sub vcl_deliver {
assert_eq!(outcome.lookup.is_some(), !bypass, "Cookie: {cookie}");
let mut forwarded = input.headers.clone();
outcome.rewrite_cookies(&mut forwarded);
assert_eq!(forwarded.get("cookie").and_then(|value| value.to_str().ok()),
forwarded_cookie, "Cookie: {cookie}");
assert_eq!(
forwarded
.get("cookie")
.and_then(|value| value.to_str().ok()),
forwarded_cookie,
"Cookie: {cookie}"
);
}
// Multiple physical Cookie fields are handled without deleting sessions.
let split = request("/rezerwa/15", None, &[
("cookie", "parent_marketing=1"),
("cookie", "app_session=abc"),
]);
let split = request(
"/rezerwa/15",
None,
&[
("cookie", "parent_marketing=1"),
("cookie", "app_session=abc"),
],
);
let outcome = compiled.evaluate_request(&split, false);
assert!(outcome.pass.is_some());
let mut forwarded = split.headers.clone();
outcome.rewrite_cookies(&mut forwarded);
assert_eq!(forwarded.get("cookie").unwrap(), "app_session=abc");
// Malformed or non-UTF8 Cookie fields must be preserved and bypassed.
for malformed in [&b"parent_marketing=1; BROKEN"[..],
&b"parent_marketing=1;"[..],
&b"parent_marketing =1"[..],
&b"parent_marketing=1; app_session=\xff"[..]] {
for malformed in [
&b"parent_marketing=1; BROKEN"[..],
&b"parent_marketing=1;"[..],
&b"parent_marketing =1"[..],
&b"parent_marketing=1; app_session=\xff"[..],
] {
let mut input = request("/rezerwa/15", None, &[]);
input.headers.insert(http::header::COOKIE, HeaderValue::from_bytes(malformed).unwrap());
input.headers.insert(
http::header::COOKIE,
HeaderValue::from_bytes(malformed).unwrap(),
);
let outcome = compiled.evaluate_request(&input, false);
assert!(outcome.pass.is_some());
let mut forwarded = input.headers.clone();
outcome.rewrite_cookies(&mut forwarded);
assert_eq!(forwarded.get("cookie"), input.headers.get("cookie"));
}
for path in ["/admin", "/admin/users", "/api/orders", "/auth/callback",
"/login", "/account", "/profile", "/checkout", "/cart", "/konto"] {
for path in [
"/admin",
"/admin/users",
"/api/orders",
"/auth/callback",
"/login",
"/account",
"/profile",
"/checkout",
"/cart",
"/konto",
] {
let input = request(path, None, &[("cookie", "parent_marketing=1")]);
let outcome = compiled.evaluate_request(&input, false);
assert!(outcome.pass.is_some(), "{path}");
assert!(outcome.remove_named_cookies.is_empty(), "{path}");
}
let with_auth = request("/rezerwa/15", None, &[
("cookie", "parent_marketing=1"), ("authorization", "Bearer access"),
]);
let with_auth = request(
"/rezerwa/15",
None,
&[
("cookie", "parent_marketing=1"),
("authorization", "Bearer access"),
],
);
let outcome = compiled.evaluate_request(&with_auth, false);
assert!(outcome.pass.is_some());
assert!(outcome.remove_named_cookies.is_empty());
@@ -1170,38 +1247,54 @@ sub vcl_deliver {
assert!(!result.warnings.is_empty(), "{vcl}");
assert!(result.rules.is_empty(), "{vcl}");
}
for bad in [serde_json::json!({"id": "bad", "actions": [{"type": "remove_named_cookies", "names": []}]}),
serde_json::json!({"id": "bad", "actions": [{"type": "remove_named_cookies", "names": ["bad;name"]}]})] {
for bad in [
serde_json::json!({"id": "bad", "actions": [{"type": "remove_named_cookies", "names": []}]}),
serde_json::json!({"id": "bad", "actions": [{"type": "remove_named_cookies", "names": ["bad;name"]}]}),
] {
assert!(validate_rules(&[rule(bad)], false).is_err());
}
let good = import_vcl(r#"sub vcl_recv { remove_req_cookies("parent_a", "parent_b"); }"#).unwrap();
let good =
import_vcl(r#"sub vcl_recv { remove_req_cookies("parent_a", "parent_b"); }"#).unwrap();
assert!(good.warnings.is_empty());
validate_rules(&good.rules, false).unwrap();
}
#[test]
fn drupal6_parent_cookie_prefixes_are_removed_without_removing_local_session() {
let drupal = include_str!(concat!(env!("CARGO_MANIFEST_DIR"),
"/examples/vcl/drupal6-parent-session-cookies.vcl"));
let cdn = include_str!(concat!(env!("CARGO_MANIFEST_DIR"),
"/examples/vcl/cdn-technical-cookies.vcl"));
let drupal = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/examples/vcl/drupal6-parent-session-cookies.vcl"
));
let cdn = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/examples/vcl/cdn-technical-cookies.vcl"
));
let imported = import_vcl(&format!("{drupal}\n{cdn}")).unwrap();
assert!(imported.warnings.is_empty(), "{:?}", imported.warnings);
validate_rules(&imported.rules, false).unwrap();
let compiled = CompiledRules::compile("z", &imported.rules, &[], false).unwrap();
// Exact names and suffix-* prefixes are case-sensitive. The local
// "session" cookie must survive and force pass regardless of order.
for (cookie, forwarded, pass) in [
("SESSabcdef1234=parent", None, false),
("SSESSabcdef1234=parent", None, false),
("SESSabcdef1234=parent; _ga_4TEST=x", None, false),
("SESSabcdef1234=parent; __cf_bm=cdn", None, false),
("__cf_bm=cdn; SESSdifferenthash=parent", None, false),
("SESSabcdef=parent; session=app", Some("SESSabcdef=parent; session=app"), true),
("session=app; SESSabcdef=parent", Some("session=app; SESSabcdef=parent"), true),
("SESSabcdef=parent; other=unknown", Some("other=unknown"), true),
(
"SESSabcdef=parent; session=app",
Some("SESSabcdef=parent; session=app"),
true,
),
(
"session=app; SESSabcdef=parent",
Some("session=app; SESSabcdef=parent"),
true,
),
(
"SESSabcdef=parent; other=unknown",
Some("other=unknown"),
true,
),
("sessionid=abc", Some("sessionid=abc"), true),
("sessabcdef=other", Some("sessabcdef=other"), true),
("XSESSabcdef=other", Some("XSESSabcdef=other"), true),
@@ -1212,17 +1305,26 @@ sub vcl_deliver {
assert_eq!(result.pass.is_some(), pass, "Cookie: {cookie}");
let mut headers = input.headers.clone();
result.rewrite_cookies(&mut headers);
assert_eq!(headers.get("cookie").and_then(|v| v.to_str().ok()), forwarded,
"Cookie: {cookie}");
assert_eq!(
headers.get("cookie").and_then(|v| v.to_str().ok()),
forwarded,
"Cookie: {cookie}"
);
}
let separate = request("/rezerwa/15", None, &[
("cookie", "SESSabc=parent"), ("cookie", "session=app")]);
let separate = request(
"/rezerwa/15",
None,
&[("cookie", "SESSabc=parent"), ("cookie", "session=app")],
);
let result = compiled.evaluate_request(&separate, false);
assert!(result.pass.is_some());
let mut headers = separate.headers.clone();
result.rewrite_cookies(&mut headers);
assert!(headers.get_all("cookie").iter().any(|v| v.to_str().ok() == Some("session=app")));
assert!(headers
.get_all("cookie")
.iter()
.any(|v| v.to_str().ok() == Some("session=app")));
for path in ["/admin", "/login", "/account", "/api/orders"] {
let input = request(path, None, &[("cookie", "SESSabcdef=parent")]);
@@ -1230,8 +1332,14 @@ sub vcl_deliver {
assert!(result.pass.is_some(), "{path}");
assert!(result.remove_named_cookies.is_empty(), "{path}");
}
let authorized = request("/rezerwa/15", None, &[
("cookie", "SESSabcdef=parent"), ("authorization", "Bearer token")]);
let authorized = request(
"/rezerwa/15",
None,
&[
("cookie", "SESSabcdef=parent"),
("authorization", "Bearer token"),
],
);
assert!(compiled.evaluate_request(&authorized, false).pass.is_some());
let mut post = request("/rezerwa/15", None, &[("cookie", "SESSabcdef=parent")]);
@@ -1239,8 +1347,10 @@ sub vcl_deliver {
assert!(compiled.evaluate_request(&post, false).pass.is_some());
let mut malformed = request("/rezerwa/15", None, &[]);
malformed.headers.insert(http::header::COOKIE,
HeaderValue::from_static("SESSabc=parent; BROKEN"));
malformed.headers.insert(
http::header::COOKIE,
HeaderValue::from_static("SESSabc=parent; BROKEN"),
);
let result = compiled.evaluate_request(&malformed, false);
assert!(result.pass.is_some());
let mut forwarded = malformed.headers.clone();
@@ -1250,24 +1360,40 @@ sub vcl_deliver {
#[test]
fn cookie_prefix_selectors_reject_unsafe_wildcard_syntax() {
let vcl = import_vcl(r#"sub vcl_recv {
let vcl = import_vcl(
r#"sub vcl_recv {
remove_req_cookies("SESS*", "SSESS*", "_ga");
}"#).unwrap();
}"#,
)
.unwrap();
assert!(vcl.warnings.is_empty());
validate_rules(&vcl.rules, false).unwrap();
// A dot in a selector is a literal cookie-name character, not a regex.
let literal_dot = import_vcl(r#"sub vcl_recv {
let literal_dot = import_vcl(
r#"sub vcl_recv {
remove_req_cookies("SESS.*");
}"#).unwrap();
}"#,
)
.unwrap();
validate_rules(&literal_dot.rules, false).unwrap();
for invalid in ["*", "s*", "se*", "SE*SS", "SESS**", "SESS?", "SESS[0-9]*", ""] {
for invalid in [
"*",
"s*",
"se*",
"SE*SS",
"SESS**",
"SESS?",
"SESS[0-9]*",
"",
] {
let rule_json = serde_json::json!({"id": "invalid", "actions": [
{"type": "remove_named_cookies", "names": [invalid]}
]});
assert!(validate_rules(&[rule(rule_json)], false).is_err(), "{invalid}");
assert!(
validate_rules(&[rule(rule_json)], false).is_err(),
"{invalid}"
);
}
}
}
+326 -156
View File
@@ -1,4 +1,5 @@
const MAX_VCL_BYTES: usize = 256 * 1024;
const MAX_VCL_PARSE_DEPTH: usize = 64;
#[derive(Debug, Clone, PartialEq, Eq)]
enum VclToken {
@@ -44,7 +45,10 @@ fn vcl_tokens(source: &str) -> Result<Vec<(VclToken, usize)>> {
}
index += 1;
}
ensure!(index + 1 < bytes.len(), "line {line}: unterminated block comment");
ensure!(
index + 1 < bytes.len(),
"line {line}: unterminated block comment"
);
index += 2;
continue;
}
@@ -60,9 +64,6 @@ fn vcl_tokens(source: &str) -> Result<Vec<(VclToken, usize)>> {
continue;
}
if byte == b'"' {
// Quoted strings must support escaped quotes/backslashes. Keep
// regex/backreference escapes such as \\s and \\1 literally: they
// belong to the VCL expression, not to the tokenizer.
index += 1;
let string_line = line;
let mut value = String::new();
@@ -74,15 +75,18 @@ fn vcl_tokens(source: &str) -> Result<Vec<(VclToken, usize)>> {
terminated = true;
break;
}
b'\\' if index + 1 < bytes.len()
&& (bytes[index + 1] == b'"' || bytes[index + 1] == b'\\') =>
b'\\'
if index + 1 < bytes.len()
&& (bytes[index + 1] == b'"' || bytes[index + 1] == b'\\') =>
{
value.push(bytes[index + 1] as char);
index += 2;
}
_ => {
let ch = source[index..].chars().next().expect("valid UTF-8");
if ch == '\n' { line += 1; }
if ch == '\n' {
line += 1;
}
value.push(ch);
index += ch.len_utf8();
}
@@ -172,6 +176,8 @@ enum VclExpr {
struct VclParser {
tokens: Vec<(VclToken, usize)>,
position: usize,
block_depth: usize,
expression_depth: usize,
}
impl VclParser {
@@ -207,6 +213,17 @@ impl VclParser {
}
}
fn block(&mut self) -> Result<Vec<VclStatement>> {
ensure!(
self.block_depth < MAX_VCL_PARSE_DEPTH,
"line {}: VCL block nesting exceeds {MAX_VCL_PARSE_DEPTH}",
self.line()
);
self.block_depth += 1;
let result = self.block_inner();
self.block_depth -= 1;
result
}
fn block_inner(&mut self) -> Result<Vec<VclStatement>> {
self.expect("{")?;
let mut statements = Vec::new();
while !self.is_sym("}") {
@@ -292,6 +309,17 @@ impl VclParser {
})
}
fn unary(&mut self) -> Result<VclExpr> {
ensure!(
self.expression_depth < MAX_VCL_PARSE_DEPTH,
"line {}: VCL expression nesting exceeds {MAX_VCL_PARSE_DEPTH}",
self.line()
);
self.expression_depth += 1;
let result = self.unary_inner();
self.expression_depth -= 1;
result
}
fn unary_inner(&mut self) -> Result<VclExpr> {
if self.is_sym("!") {
self.next();
return Ok(VclExpr::Not(Box::new(self.unary()?)));
@@ -455,11 +483,10 @@ fn vcl_atom(
}
}
/// Compile supported VCL boolean expressions into disjunctive normal form.
/// Unlike flattening elsif/else or nested if statements, this preserves
/// earlier branch guards and lets terminal returns stop the correct path.
fn vcl_clauses(
expr: &VclExpr, stage: RuleStage, negate: bool,
expr: &VclExpr,
stage: RuleStage,
negate: bool,
) -> std::result::Result<Vec<Vec<RuleCondition>>, String> {
match expr {
VclExpr::Atom(tokens) => Ok(vec![vec![vcl_atom(tokens, stage, negate)?.condition]]),
@@ -486,7 +513,9 @@ fn vcl_clauses(
}
result = joined;
} else {
if result.len() == 1 && result[0].is_empty() { result.clear(); }
if result.len() == 1 && result[0].is_empty() {
result.clear();
}
result.extend(next);
if result.len() > MAX_CACHE_RULES {
return Err("VCL condition expansion exceeds rule limit".into());
@@ -498,24 +527,21 @@ fn vcl_clauses(
}
}
/// Only recognise the well-known tracking-query removal pattern. The older
/// heuristic extracted plausible words from *any* regex, which could turn a
/// path rewrite into unrelated query stripping. Unsupported rewrites must be
/// warned about rather than executed differently from their VCL source.
fn query_params_from_regex(pattern: &str) -> Option<Vec<String>> {
let suffix = pattern
.strip_prefix(r"(\?|&)(")
.or_else(|| pattern.strip_prefix("([?&])("))?
.strip_suffix(")=[^&]*")
.or_else(|| {
pattern.strip_prefix(r"(\?|&)(")
pattern
.strip_prefix(r"(\?|&)(")
.or_else(|| pattern.strip_prefix("([?&])("))?
.strip_suffix(")=[^&]+")
})?;
let mut params = Vec::new();
for part in suffix.split('|') {
let item = if let Some(prefix) = part.strip_suffix("[a-z]+")
let item = if let Some(prefix) = part
.strip_suffix("[a-z]+")
.or_else(|| part.strip_suffix("[^=&]*"))
.or_else(|| part.strip_suffix("[^=&]+"))
{
@@ -525,11 +551,15 @@ fn query_params_from_regex(pattern: &str) -> Option<Vec<String>> {
};
if item.len() > 64
|| !item.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
|| !item.bytes().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'*'))
|| !item
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'*'))
{
return None;
}
if !params.contains(&item) { params.push(item); }
if !params.contains(&item) {
params.push(item);
}
}
(!params.is_empty()).then_some(params)
}
@@ -552,14 +582,13 @@ fn vcl_actions(
match (stage, first.as_str()) {
(_, "return") => {
let target = match tokens {
[VclToken::Ident(_), VclToken::Sym("("), VclToken::Ident(target), VclToken::Sym(")")] =>
target.to_ascii_lowercase(),
[VclToken::Ident(_), VclToken::Sym("("), VclToken::Ident(target), VclToken::Sym(")")] => {
target.to_ascii_lowercase()
}
_ => return Err("return requires exactly one action: return(action)".into()),
};
match (stage, target.as_str()) {
(RuleStage::Request, "pass") => Ok(vec![RuleAction::Pass]),
// RustProxy extension: Cookie/session guard that the static
// cookie policy may relax for public static assets.
(RuleStage::Request, "cookie_pass") => Ok(vec![RuleAction::CookiePass]),
(RuleStage::Request, "hash") => Ok(vec![RuleAction::Lookup]),
(RuleStage::Request, "lookup") => Ok(vec![RuleAction::Lookup]),
@@ -574,11 +603,15 @@ fn vcl_actions(
}
(RuleStage::Request, "unset") => {
let target = words.get(1).cloned().unwrap_or_default();
if tokens.len() != 2 { return Err(format!("invalid unset {target} statement")); }
if tokens.len() != 2 {
return Err(format!("invalid unset {target} statement"));
}
if target.eq_ignore_ascii_case("req.http.cookie") {
Ok(vec![RuleAction::StripCookies { keep: Vec::new() }])
} else if target.to_ascii_lowercase().starts_with("req.http.") {
Ok(vec![RuleAction::RemoveRequestHeader { name: target[9..].to_owned() }])
Ok(vec![RuleAction::RemoveRequestHeader {
name: target[9..].to_owned(),
}])
} else {
Err(format!("unset {target} is not supported"))
}
@@ -594,28 +627,35 @@ fn vcl_actions(
if func == "regsuball" && url == "req.url" && replacement == r"\1" => pattern,
_ => return Err("req.url: only tracking-query regsuball with replacement backreference 1 is supported".into()),
};
let params = query_params_from_regex(pattern)
.ok_or_else(|| "req.url regex cannot be safely converted to query stripping".to_owned())?;
Ok(vec![RuleAction::StripQuery { params, keep_only: false }])
let params = query_params_from_regex(pattern).ok_or_else(|| {
"req.url regex cannot be safely converted to query stripping".to_owned()
})?;
Ok(vec![RuleAction::StripQuery {
params,
keep_only: false,
}])
} else if target.to_ascii_lowercase().starts_with("req.http.") {
match (tokens.get(2), tokens.get(3), tokens.len()) {
(Some(VclToken::Sym("=")), Some(VclToken::Str(value)), 4) =>
(Some(VclToken::Sym("=")), Some(VclToken::Str(value)), 4) => {
Ok(vec![RuleAction::SetRequestHeader {
name: target[9..].to_owned(), value: value.clone(),
}]),
name: target[9..].to_owned(),
value: value.clone(),
}])
}
_ => Err(format!("set {target} requires a constant string")),
}
} else {
Err(format!("set {target} is not supported"))
}
}
// RustProxy-specific exact-name / trailing-* Cookie removal (not stock Varnish VCL).
(RuleStage::Request, "remove_req_cookies") => {
if tokens.len() < 4
|| !matches!(tokens.get(1), Some(VclToken::Sym("(")))
|| !matches!(tokens.last(), Some(VclToken::Sym(")")))
{
return Err("remove_req_cookies requires quoted cookie names or prefix* selectors".into());
return Err(
"remove_req_cookies requires quoted cookie names or prefix* selectors".into(),
);
}
let args = &tokens[2..tokens.len() - 1];
if args.len().is_multiple_of(2) {
@@ -638,20 +678,19 @@ fn vcl_actions(
[VclToken::Ident(_), VclToken::Sym("("), VclToken::Ident(value), VclToken::Sym(")")]
if value.eq_ignore_ascii_case("req.url") =>
{
// RustProxy always hashes the full request target; adding it
// again would not change the variant, and is unnecessary.
Ok(Vec::new())
}
[VclToken::Ident(_), VclToken::Sym("("), VclToken::Ident(value), VclToken::Sym(")")]
if value.eq_ignore_ascii_case("req.http.host") =>
{
// The normalized authority is already part of the scoped key.
Ok(Vec::new())
}
[VclToken::Ident(_), VclToken::Sym("("), VclToken::Ident(value), VclToken::Sym(")")]
if value.to_ascii_lowercase().starts_with("req.http.") =>
{
Ok(vec![RuleAction::HashHeader { name: value[9..].to_owned() }])
Ok(vec![RuleAction::HashHeader {
name: value[9..].to_owned(),
}])
}
_ => Err("hash_data supports req.url, req.http.Host or one req.http.<header>".into()),
},
@@ -680,7 +719,8 @@ fn vcl_actions(
name if name.starts_with("beresp.http.") => {
if let (Some(VclToken::Str(value)), 4) = (tokens.get(3), tokens.len()) {
Ok(vec![RuleAction::SetBackendHeader {
name: name[12..].to_owned(), value: value.clone(),
name: name[12..].to_owned(),
value: value.clone(),
}])
} else {
Err(format!("set {target} requires a constant string"))
@@ -690,13 +730,17 @@ fn vcl_actions(
}
}
(RuleStage::Response, "unset") => {
if tokens.len() != 2 { return Err("unset beresp requires exactly one header".into()); }
if tokens.len() != 2 {
return Err("unset beresp requires exactly one header".into());
}
match words.get(1).map(|word| word.to_ascii_lowercase()) {
Some(word) if word == "beresp.http.set-cookie" => {
Ok(vec![RuleAction::StripSetCookie])
}
Some(word) if word.starts_with("beresp.http.") => {
Ok(vec![RuleAction::RemoveBackendHeader { name: word[12..].to_owned() }])
Ok(vec![RuleAction::RemoveBackendHeader {
name: word[12..].to_owned(),
}])
}
Some(word) => Err(format!("unset {word} is not supported")),
None => Err("unset without a target".into()),
@@ -709,17 +753,21 @@ fn vcl_actions(
.or_else(|| target.strip_prefix("RESP.HTTP."))
.ok_or_else(|| format!("set {target} is not supported"))?;
match (tokens.get(2), tokens.get(3), tokens.len()) {
(Some(VclToken::Sym("=")), Some(VclToken::Str(value)), 4) => Ok(vec![RuleAction::SetHeader {
name: name.to_owned(),
value: value.clone(),
}]),
(Some(VclToken::Sym("=")), Some(VclToken::Str(value)), 4) => {
Ok(vec![RuleAction::SetHeader {
name: name.to_owned(),
value: value.clone(),
}])
}
_ => Err(format!(
"set resp.http.{name} only supports a constant string"
)),
}
}
(RuleStage::Deliver, "unset") => {
if tokens.len() != 2 { return Err("unset resp requires exactly one header".into()); }
if tokens.len() != 2 {
return Err("unset resp requires exactly one header".into());
}
let target = words.get(1).cloned().unwrap_or_default();
target
.strip_prefix("resp.http.")
@@ -747,78 +795,132 @@ struct VclBuilder {
rules: Vec<Rule>,
warnings: Vec<String>,
ids: HashSet<String>,
group: String,
}
impl VclBuilder {
fn push(
&mut self,
stage: RuleStage,
guards: &[VclExpr],
guards: &[VclGuard],
actions: Vec<RuleAction>,
stop: bool,
hash_stage: bool,
line: usize,
) {
if actions.is_empty() && !stop { return; }
let mut clauses: Vec<Vec<RuleCondition>> = vec![Vec::new()];
for guard in guards {
let options = match vcl_clauses(guard, stage, false) {
Ok(options) => options,
Err(error) => {
self.warnings.push(format!("line {line}: {error}"));
return;
}
};
let mut joined = Vec::new();
for prefix in &clauses {
for conditions in &options {
if prefix.len() + conditions.len() > MAX_RULE_CONDITIONS {
self.warnings.push(format!("line {line}: condition limit reached"));
return;
}
let mut combination = prefix.clone();
combination.extend(conditions.iter().cloned());
joined.push(combination);
if joined.len() > MAX_CACHE_RULES {
self.warnings.push(format!("line {line}: condition expansion limit reached"));
return;
}
}
}
clauses = joined;
branches: Vec<VclBranch>,
) -> Option<u16> {
if actions.is_empty() && !stop && branches.is_empty() {
return None;
}
for conditions in clauses {
if self.rules.len() >= MAX_CACHE_RULES {
self.warnings.push(format!("line {line}: rule limit reached, remaining VCL was skipped"));
return;
}
let base = format!("vcl-{}-{line}", stage.label());
let mut id = base.clone();
let mut index = 2;
while !self.ids.insert(id.clone()) {
id = format!("{base}-{index}");
index += 1;
}
let rule = Rule {
id,
name: if hash_stage { format!("VCL vcl_hash line {line}") }
else { format!("VCL {} line {line}", match stage {
if self.rules.len() >= MAX_CACHE_RULES {
self.warnings.push(format!(
"line {line}: rule limit reached, remaining VCL was skipped"
));
return None;
}
let condition_count: usize = self
.rules
.iter()
.filter_map(|rule| rule.vcl_flow.as_ref())
.flat_map(|flow| &flow.branches)
.chain(branches.iter())
.flat_map(|branch| &branch.any)
.map(Vec::len)
.sum();
if condition_count > MAX_VCL_FLOW_CONDITIONS {
self.warnings
.push(format!("line {line}: VCL flow condition limit reached"));
return None;
}
let base = format!("vcl-{}-{line}", stage.label());
let mut id = base.clone();
let mut suffix = 2;
while !self.ids.insert(id.clone()) {
id = format!("{base}-{suffix}");
suffix += 1;
}
let index = self.rules.len() as u16;
let marker = !branches.is_empty();
let rule = Rule {
id,
name: format!(
"VCL {}{} line {line}",
if hash_stage {
"vcl_hash"
} else {
match stage {
RuleStage::Request => "vcl_recv",
RuleStage::Response => "vcl_backend_response",
RuleStage::Deliver => "vcl_deliver",
}) },
enabled: true,
stage,
match_mode: RuleMatch::All,
conditions,
actions: actions.clone(),
stop,
hash_stage,
vhosts: Vec::new(),
};
match compile_rule(&rule, RuleOrigin::Global, "") {
Ok(_) => self.rules.push(rule),
Err(error) => self.warnings.push(format!("line {line}: {error}")),
}
},
if marker { " branch" } else { "" }
),
enabled: true,
stage,
match_mode: RuleMatch::All,
conditions: Vec::new(),
actions,
stop,
hash_stage,
vcl_flow: Some(VclFlow {
version: 1,
group: self.group.clone(),
index,
count: MAX_CACHE_RULES as u16,
guards: guards.to_vec(),
branches,
}),
vhosts: Vec::new(),
};
match compile_rule(&rule, RuleOrigin::Global, "") {
Ok(_) => {
self.rules.push(rule);
Some(index)
}
Err(error) => {
self.warnings.push(format!("line {line}: {error}"));
None
}
}
}
fn skipped_statements(
&mut self,
stage: RuleStage,
statements: &[VclStatement],
hash_stage: bool,
) {
for statement in statements {
match statement {
VclStatement::Simple(tokens, line) => {
let result = if !hash_stage
&& matches!(tokens.first(), Some(VclToken::Ident(name)) if name == "hash_data")
{
Err("hash_data is only supported inside sub vcl_hash".to_owned())
} else {
vcl_actions(tokens, stage)
};
if let Err(error) = result {
let warning = format!("line {line}: {error}");
if !self.warnings.contains(&warning) {
self.warnings.push(warning);
}
}
}
VclStatement::If(branches, line) => {
for (condition, body) in branches {
if let Some(condition) = condition {
if let Err(error) = vcl_clauses(condition, stage, false) {
let warning = format!("line {line}: {error}");
if !self.warnings.contains(&warning) {
self.warnings.push(warning);
}
}
}
self.skipped_statements(stage, body, hash_stage);
}
}
}
}
}
@@ -827,7 +929,7 @@ impl VclBuilder {
&mut self,
stage: RuleStage,
statements: &[VclStatement],
guards: &[VclExpr],
guards: &[VclGuard],
hash_stage: bool,
) {
let mut pending: Vec<RuleAction> = Vec::new();
@@ -842,95 +944,153 @@ impl VclBuilder {
vcl_actions(tokens, stage)
} {
Ok(actions) => {
if matches!(tokens.get(1), Some(VclToken::Ident(target)) if target == "req.url")
&& actions.iter().any(|action| matches!(action, RuleAction::StripQuery { .. }))
if actions
.iter()
.any(|action| matches!(action, RuleAction::CookiePass))
&& !guards
.iter()
.any(|guard| vcl_guard_requires_cookie(guard, &self.rules))
{
self.warnings.push(format!("line {line}: cookie_pass needs a branch guaranteed to require Cookie; use pass otherwise"));
continue;
}
if matches!(tokens.get(1), Some(VclToken::Ident(target)) if target == "req.url")
&& actions
.iter()
.any(|action| matches!(action, RuleAction::StripQuery { .. }))
{
// Converting regex rewriting to query parsing is
// intentionally not claimed to be byte-for-byte
// equivalent (separator and empty-value handling).
self.warnings.push(format!(
"line {line}: regsuball(req.url, ...) was converted to strip_query; query separators and empty values can differ; review the rule before saving"
));
if tokens.iter().any(|token| matches!(token,
VclToken::Str(value) if value.contains("[a-z]+")))
{
if tokens.iter().any(|token| {
matches!(token,
VclToken::Str(value) if value.contains("[a-z]+"))
}) {
self.warnings.push(format!(
"line {line}: query parameter name class [a-z]+ was approximated as a wildcard"
));
}
if tokens.iter().any(|token| matches!(token,
VclToken::Str(value) if value.ends_with(")=[^&]+")))
{
if tokens.iter().any(|token| {
matches!(token,
VclToken::Str(value) if value.ends_with(")=[^&]+"))
}) {
self.warnings.push(format!(
"line {line}: the original regex preserves parameters with empty values, while strip_query also removes them"
));
}
}
// Validate each converted action independently. One
// disallowed header must not silently discard the
// adjacent, otherwise valid VCL statements.
for action in actions {
if let Err(error) = validate_action(&action) {
self.warnings.push(format!("line {line}: {error}"));
continue;
}
if pending.len() >= MAX_RULE_ACTIONS {
self.push(stage, guards, std::mem::take(&mut pending),
false, hash_stage, pending_line);
self.push(
stage,
guards,
std::mem::take(&mut pending),
false,
hash_stage,
pending_line,
Vec::new(),
);
}
if pending.is_empty() {
pending_line = *line;
}
if pending.is_empty() { pending_line = *line; }
pending.push(action);
}
// return terminates only the matching branch of this hook,
// not the separate vcl_hash hook.
let terminal = matches!(tokens.first(), Some(VclToken::Ident(word))
if word.eq_ignore_ascii_case("return"));
if terminal {
self.push(stage, guards, std::mem::take(&mut pending), true,
hash_stage, *line);
// Unconditional returns terminate this statement block.
// Conditional returns terminate at runtime via Rule.stop.
if guards.is_empty() { break; }
self.push(
stage,
guards,
std::mem::take(&mut pending),
true,
hash_stage,
*line,
Vec::new(),
);
if guards.is_empty() {
break;
}
}
}
Err(error) => {
self.warnings.push(format!("line {line}: {error}"));
// An unsupported action may be the only statement in
// a conditional block. No rule is pushed in that case,
// so validate its guards here as well; otherwise an
// unsupported condition could be silently omitted.
for guard in guards {
if let Err(error) = vcl_clauses(guard, stage, false) {
let warning = format!("line {line}: {error}");
if !self.warnings.contains(&warning) {
self.warnings.push(warning);
}
}
},
VclStatement::If(branches, line) => {
if !pending.is_empty() {
self.push(
stage,
guards,
std::mem::take(&mut pending),
false,
hash_stage,
pending_line,
Vec::new(),
);
}
let mut predicates = Vec::new();
let mut valid = true;
for (condition, _) in branches {
match condition
.as_ref()
.map(|condition| vcl_clauses(condition, stage, false))
.unwrap_or_else(|| Ok(vec![Vec::new()]))
{
Ok(any) => predicates.push(VclBranch { any }),
Err(error) => {
self.warnings.push(format!("line {line}: {error}"));
valid = false;
}
}
}
},
VclStatement::If(branches, _line) => {
if !pending.is_empty() {
self.push(stage, guards, std::mem::take(&mut pending), false,
hash_stage, pending_line);
}
let mut previous = Vec::new();
for (condition, body) in branches {
let mut branch_guards = guards.to_vec();
branch_guards.extend(previous.iter().cloned().map(|previous| {
VclExpr::Not(Box::new(previous))
}));
if let Some(condition) = condition {
branch_guards.push(condition.clone());
previous.push(condition.clone());
let entry = valid
.then(|| {
self.push(
stage,
guards,
Vec::new(),
false,
hash_stage,
*line,
predicates,
)
})
.flatten();
let Some(entry) = entry else {
for (_, body) in branches {
self.skipped_statements(stage, body, hash_stage);
}
continue;
};
for (branch, (_, body)) in branches.iter().enumerate() {
let mut branch_guards = guards.to_vec();
branch_guards.push(VclGuard {
entry,
branch: branch as u16,
});
self.statements(stage, body, &branch_guards, hash_stage);
}
}
}
}
if !pending.is_empty() {
self.push(stage, guards, pending, false, hash_stage, pending_line);
self.push(
stage,
guards,
pending,
false,
hash_stage,
pending_line,
Vec::new(),
);
}
}
}
@@ -945,11 +1105,14 @@ pub fn import_vcl(source: &str) -> Result<VclImport> {
let mut parser = VclParser {
tokens,
position: 0,
block_depth: 0,
expression_depth: 0,
};
let mut builder = VclBuilder {
rules: Vec::new(),
warnings: Vec::new(),
ids: HashSet::new(),
group: format!("vcl-{:032x}", rand::random::<u128>()),
};
let mut found = false;
while let Some(token) = parser.next() {
@@ -989,6 +1152,13 @@ pub fn import_vcl(source: &str) -> Result<VclImport> {
found,
"no vcl_recv, vcl_backend_response or vcl_deliver subroutine found"
);
let count = builder.rules.len() as u16;
for rule in &mut builder.rules {
if let Some(flow) = &mut rule.vcl_flow {
flow.count = count;
}
}
validate_vcl_flows(&builder.rules)?;
Ok(VclImport {
rules: builder.rules,
warnings: builder.warnings,
+1356
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -14,3 +14,6 @@ include!("config/route_policy_tests.rs");
include!("config/transport_tests.rs");
#[cfg(test)]
include!("config/routing_conditions_tests.rs");
#[cfg(test)]
include!("config/http_policy_tests.rs");
+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,
+4
View File
@@ -183,6 +183,8 @@ pub struct Assignment {
pub cache_rules: Vec<crate::cache::Rule>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub cache_ignore_global_rules: bool,
#[serde(default, skip_serializing_if = "crate::policy::Settings::is_empty")]
pub policy: crate::policy::Settings,
pub transform_enabled: bool,
pub acl_profile_id: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
@@ -240,6 +242,7 @@ impl Default for Assignment {
cache_default_ttl_seconds: None,
cache_rules: Vec::new(),
cache_ignore_global_rules: false,
policy: crate::policy::Settings::default(),
transform_enabled: false,
acl_profile_id: None,
acl_profile_ids: Vec::new(),
@@ -569,6 +572,7 @@ impl Settings {
if let Some(acl) = &assignment.acl {
acl.compile().context("invalid Docker assignment ACL")?;
}
assignment.policy.compile().context("invalid Docker assignment HTTP policy")?;
assignment
.proxy_timeouts
.validate()
+1
View File
@@ -380,6 +380,7 @@ fn build_vhost(
"rules": &assignment.cache_rules,
"ignore_global_rules": assignment.cache_ignore_global_rules
},
"policy": &assignment.policy,
"transform": {"enabled": assignment.transform_enabled},
"acl_profile_id": acl_profile_id,
"acl_profile_ids": acl_profile_ids,
+1
View File
@@ -17,6 +17,7 @@ mod hex;
pub mod logging;
pub mod metrics;
pub mod not_found;
pub mod policy;
pub mod proxy;
pub mod runtime;
pub mod server;
+733
View File
@@ -0,0 +1,733 @@
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)
}
/// A backend response selected or changed using client-specific facts must
/// not be admitted to a shared cache merely because it has a public TTL.
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"
);
// Bound total regex programs, including converters, before allocation.
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:?}"
);
// Unused definitions must still be well formed, and cycles must never
// become latent errors activated by a later edit.
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)
}
+359
View File
@@ -0,0 +1,359 @@
use super::{
compile::{CompiledAction, HeaderOp},
expression::MAX_VALUE,
*,
};
use http::{HeaderMap, HeaderName, HeaderValue};
impl CompiledPolicy {
pub fn apply(&self, stage: Stage, context: &mut Context, trace: bool) -> Outcome {
let mut outcome = Outcome::default();
for rule in self.rules.iter().filter(|r| r.stage == stage) {
let matched = rule.condition.matches(context);
let mut entry = TraceEntry {
rule: rule.id.clone(),
stage,
matched,
actions: Vec::new(),
warnings: Vec::new(),
};
if matched {
if !trace {
rule.matches
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
for action in &rule.actions {
match apply_action(action, stage, context, &mut outcome) {
Ok(()) => {
if trace {
entry.actions.push(action.label().into());
}
}
Err(warning) => {
if !trace {
rule.errors
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
if trace {
entry.warnings.push(warning);
}
}
}
if outcome.stopped || outcome.terminal.is_some() {
break;
}
}
outcome.stopped |= rule.stop;
}
if trace {
outcome.trace.push(entry);
}
if outcome.stopped || outcome.terminal.is_some() {
break;
}
}
outcome
}
}
fn render(template: &super::expression::Template, context: &Context) -> Result<String, String> {
template.render(context).ok_or_else(|| {
"rendered policy value exceeded limits or contained controls; action skipped".into()
})
}
fn apply_action(
action: &CompiledAction,
stage: Stage,
context: &mut Context,
outcome: &mut Outcome,
) -> Result<(), String> {
let vary_edit = match action {
CompiledAction::Header(_, name, _) | CompiledAction::Replace(name, _, _, _) => {
name == http::header::VARY
}
_ => false,
};
if vary_edit && matches!(stage, Stage::Deliver | Stage::AfterResponse) {
let before = context.response_headers.clone();
let required = vary_tokens(&before)?;
apply_action_inner(action, stage, context, outcome)?;
let valid = vary_tokens(&context.response_headers).is_ok_and(|current| {
current.contains("*") || (!required.contains("*") && required.is_subset(&current))
});
if !valid {
context.response_headers = before;
return Err("delivery Vary edit would remove a variation dimension or introduce malformed Vary; action skipped".into());
}
return Ok(());
}
apply_action_inner(action, stage, context, outcome)
}
fn vary_tokens(headers: &HeaderMap) -> Result<std::collections::HashSet<String>, String> {
let mut tokens = Vec::new();
let mut seen = std::collections::HashSet::new();
for value in headers.get_all(http::header::VARY) {
add_tokens(
value
.to_str()
.map_err(|_| "non-text Vary left unchanged".to_owned())?,
&mut tokens,
&mut seen,
)?;
}
Ok(seen)
}
fn apply_action_inner(
action: &CompiledAction,
stage: Stage,
context: &mut Context,
outcome: &mut Outcome,
) -> Result<(), String> {
match action {
CompiledAction::Header(op, name, value) => {
let text = value.as_ref().map(|t| render(t, context)).transpose()?;
let headers = if stage.response() {
&mut context.response_headers
} else {
&mut context.request_headers
};
match op {
HeaderOp::Remove => {
headers.remove(name);
}
HeaderOp::Set | HeaderOp::Append | HeaderOp::Default => {
if matches!(op, HeaderOp::Default) && headers.contains_key(name) {
return Ok(());
}
let value = HeaderValue::from_str(text.as_deref().unwrap_or_default())
.map_err(|_| "invalid rendered HTTP header; action skipped".to_owned())?;
if matches!(op, HeaderOp::Append) {
headers.append(name.clone(), value);
} else {
headers.insert(name.clone(), value);
}
}
HeaderOp::Normalize | HeaderOp::Merge | HeaderOp::RemoveValue => {
normalize(headers, name, *op, text.as_deref())?;
}
}
}
CompiledAction::Replace(name, pattern, replacement, list) => {
let replacement = render(replacement, context)?;
let headers = if stage.response() {
&mut context.response_headers
} else {
&mut context.request_headers
};
let mut values = Vec::new();
for value in headers.get_all(name) {
let text = value
.to_str()
.map_err(|_| "non-text HTTP header; replacement skipped".to_owned())?;
let replaced = if *list {
let mut joined = String::new();
for (index, item) in super::expression::list_members(text).iter().enumerate() {
let part = super::expression::replace_bounded(pattern, item, &replacement)
.ok_or_else(|| {
"replacement exceeds header limit; action skipped".to_owned()
})?;
let separator = if index == 0 { "" } else { ", " };
if joined.len() + separator.len() + part.len() > MAX_VALUE {
return Err("replacement exceeds header limit; action skipped".into());
}
joined.push_str(separator);
joined.push_str(&part);
}
joined
} else {
super::expression::replace_bounded(pattern, text, &replacement).ok_or_else(
|| "replacement exceeds header limit; action skipped".to_owned(),
)?
};
if replaced.len() > MAX_VALUE {
return Err("replacement exceeded header limit; action skipped".into());
}
values.push(
HeaderValue::from_str(&replaced)
.map_err(|_| "invalid replacement header; action skipped".to_owned())?,
);
}
if !values.is_empty() {
headers.remove(name);
for value in values {
headers.append(name.clone(), value);
}
}
}
CompiledAction::SetVar(name, value) => {
let value = render(value, context)?;
if !context.variables.contains_key(name) && context.variables.len() >= 64 {
return Err("transaction variable count exceeded; action skipped".into());
}
let bytes = context
.variables
.iter()
.filter(|(key, _)| *key != name)
.map(|(k, v)| k.len() + v.len())
.sum::<usize>()
+ name.len()
+ value.len();
if bytes > 64 * 1024 {
return Err("transaction variable budget exceeded; action skipped".into());
}
context.variables.insert(name.clone(), value);
}
CompiledAction::UnsetVar(name) => {
context.variables.remove(name);
}
CompiledAction::Path(value) => {
let value = render(value, context)?;
if !value.starts_with('/')
|| value.starts_with("//")
|| value.contains(['?', '#', '\\'])
|| value.parse::<http::uri::PathAndQuery>().is_err()
{
return Err("invalid rewritten origin-form path; action skipped".into());
}
context.path = value;
}
CompiledAction::Query(value) => {
let value = render(value, context)?;
if value.contains('#')
|| format!("/?{value}")
.parse::<http::uri::PathAndQuery>()
.is_err()
{
return Err("invalid rewritten query; action skipped".into());
}
context.query = (!value.is_empty()).then_some(value);
}
CompiledAction::Backend(id) => {
outcome.backend = Some(id.clone());
outcome.cache.pass = true;
outcome.cache.lookup = false;
}
CompiledAction::Terminal(status, body, location) => {
let body = body
.as_ref()
.map(|t| render(t, context))
.transpose()?
.unwrap_or_default();
let location = location.as_ref().map(|t| render(t, context)).transpose()?;
if let Some(location) = &location {
if location.is_empty() || HeaderValue::from_str(location).is_err() {
return Err("invalid redirect Location; action skipped".into());
}
// Literal local paths and absolute HTTP(S) URLs only; prevent
// network-path targets or non-HTTP URI schemes.
let local = location.starts_with('/')
&& !location.starts_with("//")
&& !location.contains('\\');
let absolute = location.parse::<http::Uri>().is_ok_and(|u| {
matches!(u.scheme_str(), Some("http" | "https")) && u.authority().is_some()
});
if !local && !absolute {
return Err(
"redirect requires a local path or HTTP(S) URL; action skipped".into(),
);
}
}
outcome.terminal = Some(TerminalResponse {
status: *status,
body,
location,
});
outcome.cache.pass = true;
}
CompiledAction::Pass => {
outcome.cache.pass = true;
outcome.cache.lookup = false;
}
CompiledAction::Lookup => {
if !outcome.cache.pass {
outcome.cache.lookup = true;
}
}
CompiledAction::NoStore => {
outcome.cache.no_store = true;
}
CompiledAction::Ttl(value) => {
outcome.cache.ttl = Some(*value);
}
CompiledAction::Grace(value) => {
outcome.cache.grace = Some(*value);
}
CompiledAction::HashHeader(name) => {
if !outcome.cache.hash_headers.contains(name) {
outcome.cache.hash_headers.push(name.clone());
}
}
CompiledAction::DisableCompression => {
outcome.disable_compression = true;
}
CompiledAction::Stop => {
outcome.stopped = true;
}
}
Ok(())
}
fn normalize(
headers: &mut HeaderMap,
name: &HeaderName,
operation: HeaderOp,
value: Option<&str>,
) -> Result<(), String> {
let mut tokens: Vec<String> = Vec::new();
let mut seen = std::collections::HashSet::new();
for field in headers.get_all(name) {
let text = field
.to_str()
.map_err(|_| "non-text token-list header; action skipped".to_owned())?;
add_tokens(text, &mut tokens, &mut seen)?;
}
match operation {
HeaderOp::Merge => add_tokens(value.unwrap_or_default(), &mut tokens, &mut seen)?,
HeaderOp::RemoveValue => {
let mut remove = Vec::new();
let mut unique = std::collections::HashSet::new();
add_tokens(value.unwrap_or_default(), &mut remove, &mut unique)?;
if name == http::header::VARY && unique.contains("*") {
return Err("Vary wildcard cannot be removed by a list operation".into());
}
tokens.retain(|token| !unique.contains(&token.to_ascii_lowercase()));
}
_ => {}
}
// Wildcard Vary remains uncacheable, irrespective of any other tokens.
if name == http::header::VARY && tokens.iter().any(|token| token == "*") {
tokens = vec!["*".into()];
}
if tokens.is_empty() {
headers.remove(name);
return Ok(());
}
let text = tokens.join(", ");
if text.len() > MAX_VALUE {
return Err("normalized header exceeds limit; action skipped".into());
}
let value = HeaderValue::from_str(&text)
.map_err(|_| "invalid normalized header; action skipped".to_owned())?;
headers.insert(name.clone(), value);
Ok(())
}
fn add_tokens(
text: &str,
tokens: &mut Vec<String>,
seen: &mut std::collections::HashSet<String>,
) -> Result<(), String> {
for token in text.split(',') {
let token = token.trim();
if token.is_empty() || token.parse::<HeaderName>().is_err() {
return Err("malformed token-list header left unchanged".into());
}
if seen.insert(token.to_ascii_lowercase()) {
tokens.push(token.to_owned());
}
}
Ok(())
}
+800
View File
@@ -0,0 +1,800 @@
use super::{Context, MapDefinition, MapKind, Stage};
use anyhow::{bail, ensure, Context as _, Result};
use http::HeaderName;
use regex::{Regex, RegexBuilder};
use std::{collections::BTreeMap, net::IpAddr, sync::Arc};
pub(super) const MAX_VALUE: usize = 8192;
pub(super) const MAX_REGEX: usize = 4096;
pub(super) fn bounded(value: &str, limit: usize, label: &str) -> Result<()> {
ensure!(
value.len() <= limit && !value.chars().any(char::is_control),
"{label} must be at most {limit} bytes without control characters"
);
Ok(())
}
pub(super) fn regex(pattern: &str, fold: bool) -> Result<Regex> {
bounded(pattern, MAX_REGEX, "regex")?;
RegexBuilder::new(pattern)
.case_insensitive(fold)
.size_limit(256 * 1024)
.dfa_size_limit(256 * 1024)
.build()
.context("invalid or oversized policy regex")
}
pub(super) fn identifier(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 128
&& value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
}
pub(super) fn variable(value: &str) -> bool {
value.strip_prefix("txn.").is_some_and(identifier)
}
#[derive(Debug, Clone)]
pub(super) enum Sample {
Text(String),
Int(i64),
Bool(bool),
Ip(IpAddr),
Invalid,
}
impl Sample {
pub fn text(&self) -> String {
match self {
Self::Text(value) => value.clone(),
Self::Int(value) => value.to_string(),
Self::Bool(value) => if *value { "1" } else { "0" }.to_owned(),
Self::Ip(value) => value.to_string(),
Self::Invalid => "-".into(),
}
}
pub fn integer(&self) -> Option<i64> {
match self {
Self::Int(value) => Some(*value),
Self::Bool(value) => Some(i64::from(*value)),
Self::Text(value) => value.parse().ok(),
Self::Ip(_) | Self::Invalid => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ValueType {
String,
Integer,
Ip,
Boolean,
}
#[derive(Debug, Clone)]
enum Base {
Header {
response: bool,
full: bool,
count: bool,
name: Option<HeaderName>,
occurrence: Option<isize>,
},
Cookie {
response: bool,
name: String,
},
Query(String),
Property(String),
Variable(String),
Literal(Sample),
}
#[derive(Debug, Clone)]
enum Converter {
Lower,
Upper,
Trim,
Length,
Map(Arc<CompiledMap>, Option<String>),
Replace(Regex, String),
}
#[derive(Debug, Clone)]
pub(super) struct Fetch {
base: Base,
converters: Vec<Converter>,
pub kind: ValueType,
pub private: bool,
}
#[derive(Debug, Clone)]
enum MapKey {
Exact(String),
Prefix(String),
Regex(Regex),
Ip(ipnet::IpNet),
}
#[derive(Debug, Clone)]
pub(super) struct CompiledMap {
entries: Vec<(MapKey, String)>,
default: Option<String>,
fold: bool,
}
impl CompiledMap {
pub fn compile(definition: &MapDefinition) -> Result<Self> {
ensure!(
definition.entries.len() <= 1024,
"at most 1024 entries per policy map"
);
if let Some(value) = &definition.default {
bounded(value, MAX_VALUE, "map default")?;
}
let mut entries = Vec::new();
let mut seen = std::collections::HashSet::new();
for entry in &definition.entries {
bounded(&entry.key, MAX_REGEX, "map key")?;
bounded(&entry.value, MAX_VALUE, "map value")?;
let key = if definition.ignore_case {
entry.key.to_ascii_lowercase()
} else {
entry.key.clone()
};
ensure!(
seen.insert(key.clone()),
"duplicate policy map key {:?}",
entry.key
);
let key = match definition.kind {
MapKind::Exact => MapKey::Exact(key),
MapKind::Prefix => MapKey::Prefix(key),
MapKind::Regex => MapKey::Regex(regex(&entry.key, definition.ignore_case)?),
MapKind::Ip => MapKey::Ip(
entry
.key
.parse::<ipnet::IpNet>()
.or_else(|_| entry.key.parse::<IpAddr>().map(ipnet::IpNet::from))
.context("invalid IP map key")?
.trunc(),
),
};
entries.push((key, entry.value.clone()));
}
match definition.kind {
MapKind::Prefix => entries.sort_by_key(|(key, _)| match key {
MapKey::Prefix(value) => std::cmp::Reverse(value.len()),
_ => std::cmp::Reverse(0),
}),
MapKind::Ip => entries.sort_by_key(|(key, _)| match key {
MapKey::Ip(value) => std::cmp::Reverse(value.prefix_len()),
_ => std::cmp::Reverse(0),
}),
_ => {}
}
Ok(Self {
entries,
default: definition.default.clone(),
fold: definition.ignore_case,
})
}
fn get(&self, value: &str) -> Option<String> {
let folded = self.fold.then(|| value.to_ascii_lowercase());
let text = folded.as_deref().unwrap_or(value);
self.entries
.iter()
.find(|(key, _)| match key {
MapKey::Exact(key) => key == text,
MapKey::Prefix(key) => text.starts_with(key),
MapKey::Regex(key) => key.is_match(value),
MapKey::Ip(key) => value.parse::<IpAddr>().is_ok_and(|ip| key.contains(&ip)),
})
.map(|(_, value)| value.clone())
.or_else(|| self.default.clone())
}
}
pub(super) fn split_args(value: &str) -> Result<Vec<&str>> {
let mut parts = Vec::new();
let mut depth = 0usize;
let mut start = 0usize;
let mut quote = None;
let mut escaped = false;
for (index, ch) in value.char_indices() {
if escaped {
escaped = false;
continue;
}
if ch == '\\' {
escaped = true;
continue;
}
if let Some(delimiter) = quote {
if ch == delimiter {
quote = None;
}
continue;
}
match ch {
'\'' | '"' => quote = Some(ch),
'(' => {
depth += 1;
ensure!(depth <= 8, "sample expression too deeply nested");
}
')' => {
ensure!(depth > 0, "unbalanced sample expression");
depth -= 1;
}
',' if depth == 0 => {
parts.push(value[start..index].trim());
start = index + 1;
}
_ => {}
}
}
ensure!(
depth == 0 && quote.is_none() && !escaped,
"unbalanced sample expression"
);
parts.push(value[start..].trim());
Ok(parts)
}
fn call(value: &str) -> Option<(&str, &str)> {
let (name, tail) = value.split_once('(')?;
Some((name, tail.strip_suffix(')')?))
}
fn unquote(value: &str) -> &str {
value
.strip_prefix('"')
.and_then(|v| v.strip_suffix('"'))
.or_else(|| value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')))
.unwrap_or(value)
}
impl Fetch {
pub fn compile(
source: &str,
stage: Stage,
maps: &BTreeMap<String, Arc<CompiledMap>>,
) -> Result<Self> {
bounded(source, MAX_VALUE, "fetch")?;
let parts = split_args(source)?;
ensure!(parts.len() <= 9, "at most 8 converters per sample");
let first = parts[0];
let (base, mut kind, private) = if let Some((name, args)) = call(first) {
if matches!(
name,
"req.hdr"
| "req.fhdr"
| "res.hdr"
| "res.fhdr"
| "req.hdr_cnt"
| "req.fhdr_cnt"
| "res.hdr_cnt"
| "res.fhdr_cnt"
) {
let response = name.starts_with("res.");
ensure!(
!response || stage.response(),
"response fetch is unavailable in {}",
stage.label()
);
let full = name.contains("fhdr");
let count = name.ends_with("_cnt");
let args = split_args(args)?;
ensure!(
args.len() <= if count { 1 } else { 2 },
"invalid header fetch arguments"
);
let header = if args[0].is_empty() {
None
} else {
Some(
args[0]
.parse::<HeaderName>()
.context("invalid sample header name")?,
)
};
let occurrence = args
.get(1)
.map(|v| v.parse::<isize>().context("invalid header occurrence"))
.transpose()?;
ensure!(
count || header.is_some(),
"value fetches require an explicit header name"
);
ensure!(
occurrence != Some(0),
"header occurrence is 1-based, or negative from the end"
);
(
Base::Header {
response,
full,
count,
name: header,
occurrence,
},
if count {
ValueType::Integer
} else {
ValueType::String
},
!response,
)
} else if matches!(name, "req.cook" | "res.cook") {
let response = name.starts_with("res.");
ensure!(
!response || stage.response(),
"response cookie unavailable in request stage"
);
ensure!(identifier(args), "invalid cookie name");
(
Base::Cookie {
response,
name: args.into(),
},
ValueType::String,
!response,
)
} else if matches!(name, "url_param" | "req.query") {
ensure!(identifier(args), "invalid query parameter name");
(Base::Query(args.into()), ValueType::String, false)
} else if name == "var" {
ensure!(variable(args), "only named txn.* variables are supported");
(Base::Variable(args.into()), ValueType::String, true)
} else if name == "str" {
(
Base::Literal(Sample::Text(unquote(args).into())),
ValueType::String,
false,
)
} else if name == "int" {
(
Base::Literal(Sample::Int(args.parse().context("invalid integer sample")?)),
ValueType::Integer,
false,
)
} else {
bail!("unsupported policy fetch {name}");
}
} else {
let property = match first {
"req.method" => "method",
"req.path" => "path",
"req.url" => "url",
"req.host" => "host",
"res.status" | "status" => "status",
"client_ip" => "src",
"tls" => "ssl_fc",
other => other,
};
let kind = match property {
"method" | "path" | "url" | "host" | "query" | "country" | "vhost" | "req_id" => {
ValueType::String
}
"src" => ValueType::Ip,
"ssl_fc" => ValueType::Boolean,
"status" => {
ensure!(
stage.response(),
"status is available only in response stages"
);
ValueType::Integer
}
"cache_status" | "backend_time" => {
ensure!(
matches!(stage, Stage::Deliver | Stage::AfterResponse),
"{property} is available only at delivery"
);
ValueType::String
}
"srv_id" | "srv_url" | "lb_algorithm" | "hash_key" => {
ensure!(
!matches!(stage, Stage::PreRoute | Stage::Request),
"{property} is unavailable before backend selection"
);
ValueType::String
}
"location" => {
ensure!(
stage != Stage::PreRoute,
"location is unavailable before routing"
);
ValueType::String
}
_ => bail!("unsupported policy fetch {first}"),
};
(
Base::Property(property.into()),
kind,
matches!(
property,
"src" | "country" | "req_id" | "method" | "ssl_fc" | "hash_key"
),
)
};
let mut converters = Vec::new();
for source in &parts[1..] {
let converter = match *source {
"lower" => Converter::Lower,
"upper" => Converter::Upper,
"trim" => Converter::Trim,
"length" => Converter::Length,
_ => {
let (name, args) = call(source).context("invalid sample converter")?;
let args = split_args(args)?;
match name {
"map" => {
ensure!(
(1..=2).contains(&args.len()) && identifier(args[0]),
"map expects a named map and optional default"
);
let map = maps
.get(args[0])
.with_context(|| format!("unknown policy map {}", args[0]))?
.clone();
Converter::Map(map, args.get(1).map(|v| unquote(v).to_owned()))
}
"regsub" => {
ensure!(
args.len() == 2,
"regsub expects pattern,replacement (global replacement)"
);
Converter::Replace(
regex(unquote(args[0]), false)?,
unquote(args[1]).into(),
)
}
_ => bail!("unsupported sample converter {name}"),
}
}
};
kind = if matches!(converter, Converter::Length) {
ValueType::Integer
} else {
ValueType::String
};
converters.push(converter);
}
Ok(Self {
base,
converters,
kind,
private,
})
}
pub fn samples(&self, ctx: &Context) -> Vec<Sample> {
let mut values = match &self.base {
Base::Header {
response,
full,
count,
name,
occurrence,
} => {
let headers = if *response {
&ctx.response_headers
} else {
&ctx.request_headers
};
let fields: Vec<_> = match name {
Some(name) => headers.get_all(name).iter().collect(),
None => headers.values().collect(),
};
if *count && *full {
vec![Sample::Int(fields.len() as i64)]
} else {
let mut samples: Vec<_> = fields
.into_iter()
.flat_map(|field| match field.to_str() {
Ok(value) => (if *full {
vec![value]
} else {
list_members(value)
})
.into_iter()
.map(|v| Sample::Text(v.to_owned()))
.collect(),
Err(_) => vec![Sample::Invalid],
})
.collect();
if *count {
vec![Sample::Int(samples.len() as i64)]
} else if let Some(n) = occurrence {
let index = if *n > 0 {
*n - 1
} else {
samples.len() as isize + n
};
if index >= 0 && (index as usize) < samples.len() {
vec![samples.remove(index as usize)]
} else {
Vec::new()
}
} else {
samples
}
}
}
Base::Cookie { response, name } => {
let mut values = Vec::new();
let headers = if *response {
&ctx.response_headers
} else {
&ctx.request_headers
};
for field in headers.get_all(if *response { "set-cookie" } else { "cookie" }) {
if let Ok(value) = field.to_str() {
for pair in value
.split(';')
.take(if *response { 1 } else { usize::MAX })
{
if let Some((key, value)) = pair.trim().split_once('=') {
if key == name {
values.push(Sample::Text(value.to_owned()));
}
}
}
}
}
values
}
Base::Query(name) => ctx
.query
.as_deref()
.into_iter()
.flat_map(|q| q.split('&'))
.filter_map(|part| {
let (key, value) = part.split_once('=').unwrap_or((part, ""));
(key == name).then(|| Sample::Text(value.to_owned()))
})
.collect(),
Base::Variable(name) => ctx
.variables
.get(name)
.cloned()
.map(Sample::Text)
.into_iter()
.collect(),
Base::Literal(value) => vec![value.clone()],
Base::Property(name) => {
if name == "src" {
ctx.client_ip.map(Sample::Ip).into_iter().collect()
} else if name == "ssl_fc" {
vec![Sample::Bool(ctx.tls)]
} else if name == "status" {
ctx.status
.map(|v| Sample::Int(i64::from(v)))
.into_iter()
.collect()
} else {
let text = match name.as_str() {
"method" => Some(ctx.method.clone()),
"path" => Some(ctx.path.clone()),
"url" => Some(
ctx.query
.as_ref()
.map(|q| format!("{}?{q}", ctx.path))
.unwrap_or_else(|| ctx.path.clone()),
),
"host" => Some(ctx.host.clone()),
"query" => ctx.query.clone(),
"country" => ctx.country.clone(),
"cache_status" => ctx.cache_status.clone(),
"srv_id" => ctx.srv_id.clone(),
"srv_url" => ctx.srv_url.clone(),
"backend_time" => ctx.backend_time.clone(),
"location" => ctx.location.clone(),
"vhost" => ctx.vhost.clone(),
"req_id" => ctx.req_id.clone(),
"lb_algorithm" => ctx.lb_algorithm.clone(),
"hash_key" => ctx.hash_key.clone(),
_ => None,
};
text.map(Sample::Text).into_iter().collect()
}
}
};
for converter in &self.converters {
values = values
.into_iter()
.filter_map(|value| {
if matches!(value, Sample::Invalid) {
return None;
}
let text = value.text();
let result = match converter {
Converter::Lower => Sample::Text(text.to_ascii_lowercase()),
Converter::Upper => Sample::Text(text.to_ascii_uppercase()),
Converter::Trim => Sample::Text(text.trim().to_owned()),
Converter::Length => Sample::Int(text.len() as i64),
Converter::Map(map, fallback) => {
Sample::Text(map.get(&text).or_else(|| fallback.clone())?)
}
Converter::Replace(pattern, replacement) => {
Sample::Text(replace_bounded(pattern, &text, replacement)?)
}
};
(result.text().len() <= MAX_VALUE).then_some(result)
})
.collect();
}
values
}
}
pub(super) fn list_members(value: &str) -> Vec<&str> {
let mut values = Vec::new();
let mut start = 0;
let mut quoted = false;
let mut escaped = false;
for (index, ch) in value.char_indices() {
if escaped {
escaped = false;
continue;
}
if quoted && ch == '\\' {
escaped = true;
continue;
}
if ch == '"' {
quoted = !quoted;
}
if ch == ',' && !quoted {
values.push(value[start..index].trim());
start = index + 1;
}
}
values.push(value[start..].trim());
values
}
#[derive(Debug, Clone)]
enum Segment {
Text(String),
Sample(Fetch),
}
#[derive(Debug, Clone)]
pub(super) struct Template {
segments: Vec<Segment>,
pub private: bool,
}
impl Template {
pub fn compile(
source: &str,
stage: Stage,
maps: &BTreeMap<String, Arc<CompiledMap>>,
) -> Result<Self> {
bounded(source, MAX_VALUE, "policy value")?;
let mut rest = source;
let mut segments = Vec::new();
let mut private = false;
while let Some(start) = rest.find("%[") {
segments.push(Segment::Text(rest[..start].to_owned()));
let after = &rest[start + 2..];
let end = sample_end(after).context("unterminated policy sample %[...]")?;
let fetch = Fetch::compile(&after[..end], stage, maps)?;
private |= fetch.private;
segments.push(Segment::Sample(fetch));
ensure!(segments.len() <= 64, "too many samples in policy value");
rest = &after[end + 1..];
}
segments.push(Segment::Text(rest.to_owned()));
Ok(Self { segments, private })
}
pub fn render(&self, ctx: &Context) -> Option<String> {
let mut result = String::new();
for segment in &self.segments {
match segment {
Segment::Text(value) => result.push_str(value),
Segment::Sample(fetch) => result.push_str(
&fetch
.samples(ctx)
.last()
.map(Sample::text)
.unwrap_or_else(|| "-".into()),
),
}
if result.len() > MAX_VALUE {
return None;
}
}
(!result.chars().any(char::is_control)).then_some(result)
}
}
pub(super) fn replace_bounded(pattern: &Regex, text: &str, replacement: &str) -> Option<String> {
if text.len() > MAX_VALUE || replacement.len() > MAX_VALUE {
return None;
}
let mut result = String::new();
let mut previous = 0;
for captures in pattern.captures_iter(text) {
let matched = captures.get(0)?;
let unchanged = &text[previous..matched.start()];
push_bounded(&mut result, unchanged)?;
expand_bounded(&captures, replacement, &mut result)?;
previous = matched.end();
}
if result.len() + text.len() - previous > MAX_VALUE {
return None;
}
result.push_str(&text[previous..]);
Some(result)
}
fn push_bounded(out: &mut String, value: &str) -> Option<()> {
if out.len() + value.len() > MAX_VALUE {
return None;
}
out.push_str(value);
Some(())
}
fn expand_bounded(captures: &regex::Captures<'_>, mut rest: &str, out: &mut String) -> Option<()> {
while let Some(at) = rest.find('$') {
push_bounded(out, &rest[..at])?;
rest = &rest[at + 1..];
if let Some(tail) = rest.strip_prefix('$') {
push_bounded(out, "$")?;
rest = tail;
continue;
}
let (name, tail) = if let Some(braced) = rest.strip_prefix('{') {
if let Some(end) = braced.find('}') {
(&braced[..end], &braced[end + 1..])
} else {
push_bounded(out, "$")?;
continue;
}
} else {
let end = rest
.bytes()
.take_while(|b| b.is_ascii_alphanumeric() || *b == b'_')
.count();
if end == 0 {
push_bounded(out, "$")?;
continue;
}
(&rest[..end], &rest[end..])
};
let captured = name
.parse::<usize>()
.ok()
.and_then(|index| captures.get(index))
.or_else(|| captures.name(name));
if let Some(captured) = captured {
push_bounded(out, captured.as_str())?;
}
rest = tail;
}
push_bounded(out, rest)
}
fn sample_end(source: &str) -> Option<usize> {
let mut depth = 0usize;
let mut quote = None;
let mut escaped = false;
for (at, ch) in source.char_indices() {
if escaped {
escaped = false;
continue;
}
if ch == '\\' {
escaped = true;
continue;
}
if let Some(delimiter) = quote {
if ch == delimiter {
quote = None;
}
continue;
}
match ch {
'\'' | '"' => quote = Some(ch),
'(' => depth += 1,
')' => depth = depth.checked_sub(1)?,
']' if depth == 0 => return Some(at),
_ => {}
}
}
None
}
+640
View File
@@ -0,0 +1,640 @@
use super::*;
use anyhow::{bail, ensure, Context as _, Result};
pub fn import_haproxy(source: &str) -> Result<ImportResult> {
ensure!(
source.len() <= 256 * 1024,
"HAProxy policy source exceeds 256 KiB"
);
let mut policy = Settings::default();
let mut warnings = Vec::new();
let mut lines = Vec::new();
let mut pending = String::new();
let mut first_line = 0;
for (index, line) in source.lines().enumerate() {
if pending.is_empty() {
first_line = index + 1;
}
let line = line.trim_end();
if line.ends_with('\\') && !line.ends_with("\\\\") {
pending.push_str(&line[..line.len() - 1]);
pending.push(' ');
} else {
pending.push_str(line);
lines.push((first_line, std::mem::take(&mut pending)));
}
}
ensure!(
pending.is_empty(),
"line {first_line}: unfinished line continuation"
);
for (line, text) in lines {
let tokens = tokens(&text).with_context(|| format!("line {line}"))?;
if tokens.is_empty() {
continue;
}
let result = import_line(&tokens, line, &mut policy, &mut warnings);
result.with_context(|| format!("line {line}"))?;
}
policy
.compile()
.context("imported policy did not validate (no rules were activated)")?;
Ok(ImportResult { policy, warnings })
}
fn tokens(line: &str) -> Result<Vec<String>> {
let mut result = Vec::new();
let mut value = String::new();
let mut quote = None;
let mut in_token = false;
let mut chars = line.chars().peekable();
while let Some(ch) = chars.next() {
if let Some(delimiter) = quote {
if ch == delimiter {
quote = None;
continue;
}
if ch == '\\' && delimiter == '"' {
let next = chars.next().context("unterminated quoted escape")?;
if matches!(next, '"' | '\\') {
value.push(next);
} else {
value.push('\\');
value.push(next);
}
} else {
value.push(ch);
}
continue;
}
match ch {
'#' => break,
'\'' | '"' => {
quote = Some(ch);
in_token = true;
}
'\\' => {
let next = chars.next().context("unfinished escape")?;
if next.is_whitespace() || matches!(next, '#' | '\'' | '"' | '\\') {
value.push(next);
} else {
value.push('\\');
value.push(next);
}
in_token = true;
}
ch if ch.is_whitespace() => {
if in_token {
result.push(std::mem::take(&mut value));
in_token = false;
}
}
_ => {
value.push(ch);
in_token = true;
}
}
}
ensure!(quote.is_none(), "unterminated quoted string");
if in_token {
result.push(value);
}
ensure!(result.len() <= 256, "too many tokens on one policy line");
Ok(result)
}
fn import_line(
tokens: &[String],
line: usize,
settings: &mut Settings,
warnings: &mut Vec<String>,
) -> Result<()> {
if tokens[0] == "acl" {
ensure!(tokens.len() >= 3, "acl needs a name and sample expression");
let name = &tokens[1];
ensure!(super::expression::identifier(name), "invalid ACL name");
let condition = acl_condition(&tokens[2..])?;
if let Some(previous) = settings.acls.remove(name) {
let mut any = match previous {
Condition::Any { any } => any,
other => vec![other],
};
any.push(condition);
settings.acls.insert(name.clone(), Condition::Any { any });
} else {
settings.acls.insert(name.clone(), condition);
}
ensure!(settings.acls.len() <= 128, "too many named ACLs");
return Ok(());
}
let (mut stage, body, top_backend) = match tokens[0].as_str() {
"http-request" => (Stage::Request, &tokens[1..], false),
"http-response" => (Stage::BackendResponse, &tokens[1..], false),
"http-after-response" => (Stage::AfterResponse, &tokens[1..], false),
"http-pre-route" => { warnings.push(format!("line {line}: http-pre-route is a RustProxy extension")); (Stage::PreRoute, &tokens[1..], false) },
"http-backend-request" => { warnings.push(format!("line {line}: http-backend-request is a RustProxy extension")); (Stage::BackendRequest, &tokens[1..], false) },
"http-deliver" => { warnings.push(format!("line {line}: http-deliver is a RustProxy extension")); (Stage::Deliver, &tokens[1..], false) },
"use_backend" | "use-server" => (Stage::Request, tokens, true),
other => bail!("unsupported directive {other:?}; only named ACLs and supported HTTP policy rules may be imported"),
};
ensure!(!body.is_empty(), "HTTP policy directive needs an action");
let (action, consumed, extension) = parse_action(body, top_backend)?;
if extension {
warnings.push(format!(
"line {line}: {} is a RustProxy policy extension",
body[0]
));
}
if matches!(action, Action::SetPath { .. } | Action::SetQuery { .. }) && stage == Stage::Request
{
stage = Stage::PreRoute;
warnings.push(format!("line {line}: URI rewrite runs in pre_route before route/access selection; review ordering against other request rules"));
}
if matches!(action, Action::UseBackend { .. }) {
warnings.push(format!("line {line}: backend target is a configured RustProxy member ID; selecting it bypasses shared cache"));
}
let rest = &body[consumed..];
let when = if rest.is_empty() {
Condition::default()
} else {
ensure!(
matches!(rest[0].as_str(), "if" | "unless"),
"unexpected extra action operands"
);
ensure!(rest.len() > 1, "empty ACL condition");
let mut parser = BooleanParser {
tokens: &rest[1..],
at: 0,
depth: 0,
};
let condition = parser.disjunction()?;
ensure!(
parser.at == parser.tokens.len(),
"unexpected condition token {:?}",
parser.tokens.get(parser.at)
);
if rest[0] == "unless" {
Condition::Not {
not: Box::new(condition),
}
} else {
condition
}
};
settings.rules.push(Rule {
id: format!("haproxy-line-{line}"),
name: format!("HAProxy line {line}"),
enabled: true,
stage,
when,
actions: vec![action],
stop: false,
});
ensure!(settings.rules.len() <= 128, "too many policy rules");
Ok(())
}
fn parse_action(tokens: &[String], top_backend: bool) -> Result<(Action, usize, bool)> {
let arg = |n: usize| {
tokens
.get(n)
.cloned()
.with_context(|| format!("{} lacks operand {n}", tokens[0]))
};
let name = tokens[0].as_str();
if top_backend {
return Ok((Action::UseBackend { id: arg(1)? }, 2, name == "use_backend"));
}
Ok(match name {
"set-header" => (
Action::SetHeader {
name: arg(1)?,
value: arg(2)?,
},
3,
false,
),
"add-header" => (
Action::AppendHeader {
name: arg(1)?,
value: arg(2)?,
},
3,
false,
),
"del-header" => (Action::RemoveHeader { name: arg(1)? }, 2, false),
"set-header-if-missing" => (
Action::SetIfMissing {
name: arg(1)?,
value: arg(2)?,
},
3,
true,
),
"normalize-header" => (Action::NormalizeHeader { name: arg(1)? }, 2, true),
"merge-header" => (
Action::MergeHeader {
name: arg(1)?,
value: arg(2)?,
},
3,
true,
),
"remove-value" => (
Action::RemoveValue {
name: arg(1)?,
value: arg(2)?,
},
3,
true,
),
"replace-header" | "replace-value" => {
let name = arg(1)?;
let pattern = arg(2)?;
let replacement = replacement(&arg(3)?);
let action = if tokens[0] == "replace-value" {
Action::ReplaceValue {
name,
pattern,
replacement,
}
} else {
Action::ReplaceHeader {
name,
pattern,
replacement,
}
};
(action, 4, false)
}
"set-path" => (Action::SetPath { value: arg(1)? }, 2, false),
"set-query" => (Action::SetQuery { value: arg(1)? }, 2, false),
"use-backend" => (Action::UseBackend { id: arg(1)? }, 2, true),
"deny" => {
if tokens.get(1).is_some_and(|v| v == "deny_status") {
(
Action::Deny {
status: arg(2)?.parse().context("invalid deny status")?,
},
3,
false,
)
} else {
(Action::Deny { status: 403 }, 1, false)
}
}
"return" => {
ensure!(
arg(1)? == "status",
"return requires status <code> [string <body>]"
);
let status = arg(2)?.parse().context("invalid return status")?;
if tokens.get(3).is_some_and(|v| v == "string") {
(
Action::Return {
status,
body: arg(4)?,
},
5,
false,
)
} else {
(
Action::Return {
status,
body: String::new(),
},
3,
false,
)
}
}
"redirect" => {
ensure!(arg(1)? == "location", "only redirect location is supported");
let location = arg(2)?;
if tokens.get(3).is_some_and(|v| v == "code") {
(
Action::Redirect {
status: arg(4)?.parse().context("invalid redirect status")?,
location,
},
5,
false,
)
} else {
(
Action::Redirect {
status: 302,
location,
},
3,
false,
)
}
}
"allow" => (Action::Stop, 1, false),
"stop" => (Action::Stop, 1, true),
"cache-pass" => (Action::Pass, 1, true),
"cache-lookup" => (Action::Lookup, 1, true),
"cache-no-store" => (Action::NoStore, 1, true),
"cache-ttl" => (
Action::SetTtl {
seconds: duration(&arg(1)?)?,
},
2,
true,
),
"cache-grace" => (
Action::SetGrace {
seconds: duration(&arg(1)?)?,
},
2,
true,
),
"cache-hash-header" => (Action::HashHeader { name: arg(1)? }, 2, true),
"disable-compression" => (Action::DisableCompression, 1, true),
_ => {
if let Some(variable) = name
.strip_prefix("set-var(")
.and_then(|v| v.strip_suffix(')'))
{
(
Action::SetVar {
name: variable.into(),
value: format!("%[{}]", arg(1)?),
},
2,
false,
)
} else if let Some(variable) = name
.strip_prefix("set-var-fmt(")
.and_then(|v| v.strip_suffix(')'))
{
(
Action::SetVar {
name: variable.into(),
value: arg(1)?,
},
2,
false,
)
} else if let Some(variable) = name
.strip_prefix("unset-var(")
.and_then(|v| v.strip_suffix(')'))
{
(
Action::UnsetVar {
name: variable.into(),
},
1,
false,
)
} else {
bail!("unsupported HTTP action {name:?}");
}
}
})
}
fn duration(value: &str) -> Result<u64> {
let (number, unit) = value.trim().split_at(
value
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(value.len()),
);
let n: u64 = number.parse().context("invalid duration")?;
let factor = match unit {
"" | "s" => 1,
"m" => 60,
"h" => 3600,
"d" => 86400,
_ => bail!("duration units: s, m, h, d"),
};
n.checked_mul(factor).context("duration overflow")
}
fn replacement(value: &str) -> String {
let mut result = String::new();
let mut chars = value.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '\\' && chars.peek().is_some_and(char::is_ascii_digit) {
result.push('$');
result.push('{');
result.push(chars.next().unwrap());
result.push('}');
} else if ch == '$' {
result.push_str("$$");
} else {
result.push(ch);
}
}
result
}
fn acl_condition(tokens: &[String]) -> Result<Condition> {
ensure!(!tokens.is_empty(), "empty inline ACL");
let original = &tokens[0];
let (fetch, default_operator) = match original.as_str() {
"path_beg" => ("path".into(), Operator::Prefix),
"path_end" => ("path".into(), Operator::Suffix),
"path_sub" => ("path".into(), Operator::Contains),
"path_reg" => ("path".into(), Operator::Regex),
"url_beg" => ("url".into(), Operator::Prefix),
"url_end" => ("url".into(), Operator::Suffix),
"url_sub" => ("url".into(), Operator::Contains),
"url_reg" => ("url".into(), Operator::Regex),
"src" => (original.clone(), Operator::Cidr),
"status" | "res.status" | "ssl_fc" => (original.clone(), Operator::Eq),
_ => (
original.clone(),
if original.contains("_cnt(")
|| original.ends_with(",length")
|| original.starts_with("int(")
{
Operator::Eq
} else {
Operator::Equals
},
),
};
let mut operator = default_operator;
let mut ignore_case = false;
let mut at = 1;
while at < tokens.len() {
match tokens[at].as_str() {
"-i" => {
ignore_case = true;
at += 1;
}
"-m" => {
at += 1;
operator = match tokens
.get(at)
.context("-m needs a matching method")?
.as_str()
{
"str" => Operator::Equals,
"sub" => Operator::Contains,
"beg" => Operator::Prefix,
"end" => Operator::Suffix,
"reg" => Operator::Regex,
"int" | "bool" => Operator::Eq,
"ip" => Operator::Cidr,
"found" => Operator::Exists,
other => bail!("unsupported ACL matching method {other}"),
};
at += 1;
}
"--" => {
at += 1;
break;
}
option
if option.starts_with('-')
&& option
.as_bytes()
.get(1)
.is_some_and(|b| !b.is_ascii_digit()) =>
{
bail!("unsupported ACL option {option}")
}
_ => break,
}
}
if operator == Operator::Eq && at < tokens.len() {
let comparison = match tokens[at].as_str() {
"eq" => Some(Operator::Eq),
"ne" => Some(Operator::Ne),
"gt" => Some(Operator::Gt),
"ge" => Some(Operator::Ge),
"lt" => Some(Operator::Lt),
"le" => Some(Operator::Le),
_ => None,
};
if let Some(comparison) = comparison {
operator = comparison;
at += 1;
}
}
let mut values = tokens[at..].to_vec();
if original == "ssl_fc" && values.is_empty() {
values.push("1".into());
}
ensure!(
operator == Operator::Exists || !values.is_empty(),
"ACL needs comparison values (use -m found for existence)"
);
ensure!(
operator != Operator::Exists || values.is_empty(),
"-m found takes no pattern"
);
Ok(Condition::Compare {
fetch,
operator,
values,
ignore_case,
})
}
struct BooleanParser<'a> {
tokens: &'a [String],
at: usize,
depth: usize,
}
impl BooleanParser<'_> {
fn peek(&self) -> Option<&str> {
self.tokens.get(self.at).map(String::as_str)
}
fn disjunction(&mut self) -> Result<Condition> {
let mut any = vec![self.conjunction()?];
while matches!(self.peek(), Some("or" | "||")) {
self.at += 1;
any.push(self.conjunction()?);
}
Ok(if any.len() == 1 {
any.remove(0)
} else {
Condition::Any { any }
})
}
fn conjunction(&mut self) -> Result<Condition> {
let mut all = Vec::new();
while self.peek().is_some_and(|t| !matches!(t, "or" | "||" | ")")) {
if self.peek() == Some("&&") {
ensure!(!all.is_empty(), "missing operand before &&");
self.at += 1;
ensure!(
self.peek()
.is_some_and(|t| !matches!(t, "or" | "||" | ")" | "&&")),
"missing operand after &&"
);
}
all.push(self.atom()?);
}
ensure!(!all.is_empty(), "empty condition branch");
Ok(if all.len() == 1 {
all.remove(0)
} else {
Condition::All { all }
})
}
fn atom(&mut self) -> Result<Condition> {
self.depth += 1;
ensure!(self.depth <= 16, "condition nesting exceeds 16");
let token = self
.tokens
.get(self.at)
.context("missing condition")?
.clone();
self.at += 1;
let result = if token == "!" {
Condition::Not {
not: Box::new(self.atom()?),
}
} else if token == "(" {
let group = self.disjunction()?;
ensure!(self.peek() == Some(")"), "unclosed condition group");
self.at += 1;
group
} else if token == "{" || token == "!{" {
let start = self.at;
while self.peek().is_some_and(|t| t != "}") {
self.at += 1;
}
ensure!(self.peek() == Some("}"), "unclosed inline ACL");
let predicate = acl_condition(&self.tokens[start..self.at])?;
self.at += 1;
if token == "!{" {
Condition::Not {
not: Box::new(predicate),
}
} else {
predicate
}
} else {
let (negate, name) = token
.strip_prefix('!')
.map(|v| (true, v))
.unwrap_or((false, token.as_str()));
let predicate = match name {
"TRUE" => Condition::default(),
"FALSE" => Condition::Any { any: Vec::new() },
_ => {
ensure!(
super::expression::identifier(name),
"invalid named ACL reference {name:?}"
);
Condition::Acl { acl: name.into() }
}
};
if negate {
Condition::Not {
not: Box::new(predicate),
}
} else {
predicate
}
};
self.depth -= 1;
Ok(result)
}
}
+12
View File
@@ -0,0 +1,12 @@
mod compile;
mod engine;
mod expression;
mod haproxy;
mod model;
pub use compile::CompiledPolicy;
pub use haproxy::import_haproxy;
pub use model::*;
#[cfg(test)]
mod tests;
+308
View File
@@ -0,0 +1,308 @@
use http::HeaderMap;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, net::IpAddr};
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Settings {
pub acls: BTreeMap<String, Condition>,
pub maps: BTreeMap<String, MapDefinition>,
pub rules: Vec<Rule>,
}
impl Settings {
pub fn is_empty(&self) -> bool {
self.acls.is_empty() && self.maps.is_empty() && self.rules.is_empty()
}
pub fn compile(&self) -> anyhow::Result<super::CompiledPolicy> {
super::compile::compile(self)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Stage {
PreRoute,
#[default]
Request,
BackendRequest,
BackendResponse,
Deliver,
AfterResponse,
}
impl Stage {
pub fn response(self) -> bool {
matches!(
self,
Self::BackendResponse | Self::Deliver | Self::AfterResponse
)
}
pub fn label(self) -> &'static str {
match self {
Self::PreRoute => "pre_route",
Self::Request => "request",
Self::BackendRequest => "backend_request",
Self::BackendResponse => "backend_response",
Self::Deliver => "deliver",
Self::AfterResponse => "after_response",
}
}
}
fn yes() -> bool {
true
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Rule {
pub id: String,
#[serde(default)]
pub name: String,
#[serde(default = "yes")]
pub enabled: bool,
#[serde(default)]
pub stage: Stage,
#[serde(default)]
pub when: Condition,
pub actions: Vec<Action>,
#[serde(default)]
pub stop: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged, deny_unknown_fields)]
pub enum Condition {
All {
all: Vec<Condition>,
},
Any {
any: Vec<Condition>,
},
Not {
not: Box<Condition>,
},
Acl {
acl: String,
},
Compare {
fetch: String,
operator: Operator,
#[serde(default)]
values: Vec<String>,
#[serde(default)]
ignore_case: bool,
},
}
impl Default for Condition {
fn default() -> Self {
Self::All { all: Vec::new() }
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Operator {
Equals,
Contains,
Prefix,
Suffix,
Regex,
Exists,
Cidr,
Eq,
Ne,
Gt,
Ge,
Lt,
Le,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MapKind {
#[default]
Exact,
Prefix,
Regex,
Ip,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct MapDefinition {
pub kind: MapKind,
pub entries: Vec<MapEntry>,
pub default: Option<String>,
pub ignore_case: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MapEntry {
pub key: String,
pub value: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum Action {
SetHeader {
name: String,
value: String,
},
AppendHeader {
name: String,
value: String,
},
RemoveHeader {
name: String,
},
SetIfMissing {
name: String,
value: String,
},
NormalizeHeader {
name: String,
},
MergeHeader {
name: String,
value: String,
},
RemoveValue {
name: String,
value: String,
},
ReplaceHeader {
name: String,
pattern: String,
replacement: String,
},
ReplaceValue {
name: String,
pattern: String,
replacement: String,
},
SetVar {
name: String,
value: String,
},
UnsetVar {
name: String,
},
SetPath {
value: String,
},
SetQuery {
value: String,
},
UseBackend {
id: String,
},
Deny {
#[serde(default = "forbidden")]
status: u16,
},
Return {
status: u16,
#[serde(default)]
body: String,
},
Redirect {
#[serde(default = "found")]
status: u16,
location: String,
},
Pass,
Lookup,
NoStore,
SetTtl {
seconds: u64,
},
SetGrace {
seconds: u64,
},
HashHeader {
name: String,
},
DisableCompression,
Stop,
}
fn forbidden() -> u16 {
403
}
fn found() -> u16 {
302
}
#[derive(Debug, Clone, Default)]
pub struct Context {
pub request_headers: HeaderMap,
pub response_headers: HeaderMap,
pub method: String,
pub path: String,
pub query: Option<String>,
pub host: String,
pub client_ip: Option<IpAddr>,
pub country: Option<String>,
pub tls: bool,
pub status: Option<u16>,
pub cache_status: Option<String>,
pub srv_id: Option<String>,
pub srv_url: Option<String>,
pub backend_time: Option<String>,
pub location: Option<String>,
pub vhost: Option<String>,
pub req_id: Option<String>,
pub lb_algorithm: Option<String>,
pub hash_key: Option<String>,
pub variables: BTreeMap<String, String>,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct CacheEffects {
pub pass: bool,
pub lookup: bool,
pub no_store: bool,
pub ttl: Option<u64>,
pub grace: Option<u64>,
pub hash_headers: Vec<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct TerminalResponse {
pub status: u16,
pub body: String,
pub location: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct Outcome {
pub terminal: Option<TerminalResponse>,
pub backend: Option<String>,
pub cache: CacheEffects,
pub disable_compression: bool,
pub stopped: bool,
pub trace: Vec<TraceEntry>,
}
#[derive(Debug, Clone, Serialize)]
pub struct TraceEntry {
pub rule: String,
pub stage: Stage,
pub matched: bool,
pub actions: Vec<String>,
pub warnings: Vec<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct RuleStats {
pub id: String,
pub stage: Stage,
pub matches: u64,
pub errors: u64,
}
#[derive(Debug, Clone, Serialize)]
pub struct ImportResult {
pub policy: Settings,
pub warnings: Vec<String>,
}
+650
View File
@@ -0,0 +1,650 @@
use super::*;
use http::HeaderValue;
use serde_json::{json, Value};
fn settings(value: Value) -> Settings {
serde_json::from_value(value).unwrap()
}
fn program(stage: &str, when: Value, actions: Value) -> CompiledPolicy {
settings(json!({"rules":[{"id":"test","stage":stage,"when":when,"actions":actions}]}))
.compile()
.unwrap()
}
fn context(fields: &[(&str, &str)]) -> Context {
let mut context = Context {
method: "GET".into(),
path: "/assets/file.js".into(),
host: "example.test".into(),
status: Some(200),
..Context::default()
};
for (name, value) in fields {
context.response_headers.append(
name.parse::<http::HeaderName>().unwrap(),
value.parse().unwrap(),
);
}
context
}
fn marker(stage: &str, when: Value) -> CompiledPolicy {
program(
stage,
when,
json!([{"type":"set_header","name":"X-Matched","value":"yes"}]),
)
}
const VARY_CONFIG: &str = r#"
acl vary_duplicate res.fhdr_cnt(Vary) eq 2
acl vary_encoding res.fhdr(Vary) -i Accept-Encoding
acl vary_combined res.fhdr(Vary) -i "Accept,Accept-Encoding" "Accept, Accept-Encoding"
http-response set-header Vary "Accept, Accept-Encoding" if vary_duplicate vary_encoding vary_combined
"#;
#[test]
fn exact_user_haproxy_example_works_for_both_spacings_and_orders() {
let imported = import_haproxy(VARY_CONFIG).unwrap();
assert!(imported.warnings.is_empty());
let policy = imported.policy.compile().unwrap();
for combined in [
"Accept,Accept-Encoding",
"Accept, Accept-Encoding",
"accept, accept-encoding",
] {
for reversed in [false, true] {
let mut fields = vec![("Vary", "accept-ENCODING"), ("Vary", combined)];
if reversed {
fields.reverse();
}
let mut ctx = context(&fields);
let result = policy.apply(Stage::BackendResponse, &mut ctx, true);
assert!(result.trace[0].matched);
assert_eq!(ctx.response_headers.get_all("vary").iter().count(), 1);
assert_eq!(ctx.response_headers["vary"], "Accept, Accept-Encoding");
}
}
}
#[test]
fn exact_example_does_not_match_one_or_three_fields_or_extra_dimension() {
let policy = import_haproxy(VARY_CONFIG)
.unwrap()
.policy
.compile()
.unwrap();
for fields in [
vec![],
vec![("Vary", "Accept, Accept-Encoding")],
vec![
("Vary", "Accept-Encoding"),
("Vary", "Accept, Accept-Encoding"),
("Vary", "Cookie"),
],
vec![
("Vary", "Accept-Encoding"),
("Vary", "Accept, Accept-Encoding, Cookie"),
],
] {
let mut ctx = context(&fields);
let before = ctx.response_headers.clone();
assert!(!policy.apply(Stage::BackendResponse, &mut ctx, true).trace[0].matched);
assert_eq!(ctx.response_headers, before);
}
}
#[test]
fn field_count_token_count_occurrence_and_quoted_commas_differ() {
let mut ctx = context(&[("X-List", "a, \"b,c\""), ("X-List", "d")]);
for (fetch, operator, values) in [
("res.fhdr_cnt(X-List)", "eq", json!(["2"])),
("res.hdr_cnt(X-List)", "eq", json!(["3"])),
("res.fhdr(X-List,1)", "equals", json!(["a, \"b,c\""])),
("res.hdr(X-List,-1)", "equals", json!(["d"])),
("res.hdr(X-List,2)", "equals", json!(["\"b,c\""])),
] {
let p = marker(
"backend_response",
json!({"fetch":fetch,"operator":operator,"values":values}),
);
assert!(
p.apply(Stage::BackendResponse, &mut ctx, true).trace[0].matched,
"{fetch}"
);
}
}
#[test]
fn missing_empty_and_nontext_fields_have_correct_existence() {
let p = marker(
"backend_response",
json!({"fetch":"res.fhdr(X-Test)","operator":"exists"}),
);
let mut ctx = context(&[]);
assert!(!p.apply(Stage::BackendResponse, &mut ctx, true).trace[0].matched);
ctx.response_headers
.insert("x-test", HeaderValue::from_static(""));
assert!(p.apply(Stage::BackendResponse, &mut ctx, true).trace[0].matched);
ctx.response_headers
.insert("x-test", HeaderValue::from_bytes(&[0xff]).unwrap());
assert!(p.apply(Stage::BackendResponse, &mut ctx, true).trace[0].matched);
let equal = marker(
"backend_response",
json!({"fetch":"res.fhdr(X-Test)","operator":"equals","values":[""]}),
);
assert!(!equal.apply(Stage::BackendResponse, &mut ctx, true).trace[0].matched);
for (operator, value) in [("equals", "-"), ("regex", "^-$"), ("regex", ".*")] {
let text_match = marker(
"backend_response",
json!({"fetch":"res.fhdr(X-Test)","operator":operator,"values":[value]}),
);
assert!(
!text_match
.apply(Stage::BackendResponse, &mut ctx, true)
.trace[0]
.matched
);
}
}
#[test]
fn named_acls_re_evaluate_after_prior_mutations() {
let p=settings(json!({"acls":{"changed":{"fetch":"res.fhdr(X-State)","operator":"equals","values":["new"]}},"rules":[
{"id":"first","stage":"deliver","actions":[{"type":"set_header","name":"X-State","value":"new"}]},
{"id":"next","stage":"deliver","when":{"acl":"changed"},"actions":[{"type":"set_header","name":"X-Result","value":"yes"}]}
]})).compile().unwrap();
let mut ctx = context(&[]);
p.apply(Stage::Deliver, &mut ctx, false);
assert_eq!(ctx.response_headers["x-result"], "yes");
}
#[test]
fn boolean_groups_unless_and_repeated_acl_definitions() {
let p=import_haproxy("acl selected path_beg /assets/\nacl selected path_beg /api/\nhttp-request set-header X-Selected yes if selected !{ method POST }\nhttp-request set-header X-Other yes unless selected\nhttp-request set-header X-Or yes if FALSE or selected\n").unwrap().policy.compile().unwrap();
let mut ctx = context(&[]);
p.apply(Stage::Request, &mut ctx, false);
assert_eq!(ctx.request_headers["x-selected"], "yes");
assert_eq!(ctx.request_headers["x-or"], "yes");
assert!(!ctx.request_headers.contains_key("x-other"));
ctx.path = "/other".into();
ctx.request_headers.clear();
p.apply(Stage::Request, &mut ctx, false);
assert_eq!(ctx.request_headers["x-other"], "yes");
}
#[test]
fn quoted_if_literal_is_action_operand_not_condition() {
let p = import_haproxy("http-response set-header X-Literal \"if\"")
.unwrap()
.policy
.compile()
.unwrap();
let mut ctx = context(&[]);
p.apply(Stage::BackendResponse, &mut ctx, false);
assert_eq!(ctx.response_headers["x-literal"], "if");
}
#[test]
fn importer_rejects_unknown_directives_and_incomplete_boolean_expressions() {
for source in [
"http-response set-header X-OK yes\nhttp-response lua.foo",
"acl x path_beg /\nhttp-request deny if x or",
"http-request deny if { method GET",
"http-request set-header X \"unterminated",
"frontend app",
"http-request deny if unknown",
] {
assert!(import_haproxy(source).is_err(), "{source}");
}
}
#[test]
fn importer_rejects_extra_action_operands_instead_of_accepting_prefix() {
assert!(import_haproxy("http-response set-header X yes extra").is_err());
assert!(import_haproxy("acl x res.fhdr(Vary) -m found unexpected").is_err());
}
#[test]
fn map_prefix_and_ip_use_longest_match() {
let p=settings(json!({"maps":{
"paths":{"kind":"prefix","entries":[{"key":"/","value":"root"},{"key":"/assets/","value":"assets"}]},
"nets":{"kind":"ip","entries":[{"key":"10.0.0.0/8","value":"wide"},{"key":"10.1.0.0/16","value":"narrow"}]}
},"rules":[{"id":"map","actions":[{"type":"set_header","name":"X-Path","value":"%[path,map(paths)]"},{"type":"set_header","name":"X-Net","value":"%[src,map(nets,other)]"}]}]})).compile().unwrap();
let mut ctx = context(&[]);
ctx.client_ip = Some("10.1.2.3".parse().unwrap());
p.apply(Stage::Request, &mut ctx, false);
assert_eq!(ctx.request_headers["x-path"], "assets");
assert_eq!(ctx.request_headers["x-net"], "narrow");
ctx.client_ip = Some("192.0.2.1".parse().unwrap());
p.apply(Stage::Request, &mut ctx, false);
assert_eq!(ctx.request_headers["x-net"], "other");
}
#[test]
fn transaction_vars_cross_stages_and_do_not_cross_transactions() {
let p=import_haproxy("http-request set-var(txn.device) req.fhdr(X-Device),lower\nhttp-after-response set-header X-Device %[var(txn.device)]").unwrap().policy.compile().unwrap();
let mut ctx = context(&[]);
ctx.request_headers
.insert("x-device", HeaderValue::from_static("MOBILE"));
p.apply(Stage::Request, &mut ctx, false);
p.apply(Stage::AfterResponse, &mut ctx, false);
assert_eq!(ctx.response_headers["x-device"], "mobile");
let mut other = context(&[]);
p.apply(Stage::AfterResponse, &mut other, false);
assert_eq!(other.response_headers["x-device"], "-");
}
#[test]
fn normalize_vary_retains_all_dimensions_and_deduplicates_case_insensitively() {
let p = program(
"after_response",
json!({"all":[]}),
json!([{"type":"normalize_header","name":"Vary"}]),
);
let mut ctx = context(&[
("Vary", "Accept-Encoding, Cookie"),
("Vary", "accept-encoding, Authorization, Accept-Language"),
]);
p.apply(Stage::AfterResponse, &mut ctx, false);
assert_eq!(
ctx.response_headers["vary"],
"Accept-Encoding, Cookie, Authorization, Accept-Language"
);
assert_eq!(ctx.response_headers.get_all("vary").iter().count(), 1);
}
#[test]
fn normalization_preserves_wildcard_and_leaves_malformed_values_unchanged() {
let p = program(
"after_response",
json!({"all":[]}),
json!([{"type":"normalize_header","name":"Vary"}]),
);
let mut ctx = context(&[("Vary", "Cookie"), ("Vary", "*, Accept-Encoding")]);
p.apply(Stage::AfterResponse, &mut ctx, false);
assert_eq!(ctx.response_headers["vary"], "*");
for value in ["Accept-Encoding,,Cookie", "bad token", "", "Cookie, ="] {
let mut ctx = context(&[("Vary", value)]);
let before = ctx.response_headers.clone();
assert_eq!(
p.apply(Stage::AfterResponse, &mut ctx, true).trace[0]
.warnings
.len(),
1
);
assert_eq!(ctx.response_headers, before);
}
}
#[test]
fn final_stage_cannot_erase_any_existing_vary_dimension() {
for action in [
json!({"type":"set_header","name":"Vary","value":"Accept-Encoding"}),
json!({"type":"remove_header","name":"Vary"}),
json!({"type":"remove_value","name":"Vary","value":"Cookie"}),
json!({"type":"replace_header","name":"Vary","pattern":"Cookie","replacement":"X-Other"}),
] {
let p = program("deliver", json!({"all":[]}), json!([action]));
let mut ctx = context(&[("Vary", "Cookie, Accept-Encoding")]);
let before = ctx.response_headers.clone();
assert!(!p.apply(Stage::Deliver, &mut ctx, true).trace[0]
.warnings
.is_empty());
assert_eq!(ctx.response_headers, before);
}
let p = program(
"after_response",
json!({"all":[]}),
json!([{"type":"set_header","name":"Vary","value":"Accept, Accept-Encoding"}]),
);
let mut ctx = context(&[
("Vary", "Accept-Encoding"),
("Vary", "Accept,Accept-Encoding"),
]);
assert!(p.apply(Stage::AfterResponse, &mut ctx, true).trace[0]
.warnings
.is_empty());
assert_eq!(ctx.response_headers["vary"], "Accept, Accept-Encoding");
}
#[test]
fn backend_stage_may_intentionally_change_variant_plan() {
let p = program(
"backend_response",
json!({"all":[]}),
json!([{"type":"set_header","name":"Vary","value":"Accept-Language"}]),
);
let mut ctx = context(&[("Vary", "Cookie")]);
p.apply(Stage::BackendResponse, &mut ctx, false);
assert_eq!(ctx.response_headers["vary"], "Accept-Language");
}
#[test]
fn list_actions_cannot_merge_set_cookie_or_cache_control() {
for name in ["Set-Cookie", "Cache-Control", "Date", "Content-Length"] {
assert!(settings(json!({"rules":[{"id":"bad","stage":"after_response","actions":[{"type":"normalize_header","name":name}]}]})).compile().is_err());
}
}
#[test]
fn private_backend_response_rules_are_marked_for_cache_bypass() {
let p = program(
"backend_response",
json!({"fetch":"req.fhdr(Cookie)","operator":"exists"}),
json!([{"type":"set_header","name":"X-Personal","value":"yes"}]),
);
assert!(p.requires_private_response());
let p = program(
"backend_response",
json!({"all":[]}),
json!([{"type":"set_header","name":"X-Personal","value":"%[var(txn.user)]"}]),
);
assert!(p.requires_private_response());
let p = program(
"backend_response",
json!({"fetch":"path","operator":"prefix","values":["/assets/"]}),
json!([{"type":"set_ttl","seconds":60}]),
);
assert!(!p.requires_private_response());
}
#[test]
fn method_tls_and_balancer_hash_response_dependencies_require_cache_bypass() {
for (fetch, operator, value) in [
("method", "equals", "HEAD"),
("req.method", "equals", "GET"),
("ssl_fc", "eq", "1"),
("tls", "eq", "0"),
("hash_key", "equals", "client-cookie"),
] {
let conditional = program(
"backend_response",
json!({"fetch":fetch,"operator":operator,"values":[value]}),
json!([{"type":"set_header","name":"X-Personal","value":"selected"}]),
);
assert!(conditional.requires_private_response(), "condition {fetch}");
let interpolated = program(
"backend_response",
json!({"all":[]}),
json!([{"type":"set_header","name":"X-Personal","value":format!("%[{fetch}]")}]),
);
assert!(interpolated.requires_private_response(), "template {fetch}");
}
let converted = program(
"backend_response",
json!({"all":[]}),
json!([{"type":"set_header","name":"X-Personal","value":"%[method,lower] %[hash_key,lower]"}]),
);
assert!(converted.requires_private_response());
let delivery = program(
"after_response",
json!({"all":[]}),
json!([{"type":"set_header","name":"X-Method","value":"%[method]"}]),
);
assert!(!delivery.requires_private_response());
}
#[test]
fn stage_capabilities_and_protected_headers_are_rejected_on_compile() {
for (stage, action) in [
("request", json!({"type":"set_path","value":"/private"})),
("after_response", json!({"type":"set_ttl","seconds":60})),
("deliver", json!({"type":"deny"})),
(
"request",
json!({"type":"set_header","name":"Authorization","value":"x"}),
),
(
"deliver",
json!({"type":"set_header","name":"Content-Length","value":"5"}),
),
("after_response", json!({"type":"disable_compression"})),
] {
assert!(
settings(json!({"rules":[{"id":"bad","stage":stage,"actions":[action]}]}))
.compile()
.is_err()
);
}
assert!(settings(json!({"rules":[{"id":"bad","when":{"fetch":"res.fhdr(Vary)","operator":"exists"},"actions":[{"type":"stop"}]}]})).compile().is_err());
}
#[test]
fn acl_cycles_unknown_fields_and_numeric_type_errors_are_rejected() {
assert!(settings(json!({"acls":{"a":{"acl":"b"},"b":{"acl":"a"}}}))
.compile()
.is_err());
assert!(serde_json::from_value::<Settings>(json!({"unknown":true})).is_err());
assert!(serde_json::from_value::<Condition>(json!({"all":[],"typo":true})).is_err());
assert!(settings(json!({"rules":[{"id":"bad","when":{"fetch":"path","operator":"gt","values":["3"]},"actions":[{"type":"stop"}]}]})).compile().is_err());
}
#[test]
fn pass_is_monotonic_and_backend_selection_always_passes() {
let p = program(
"request",
json!({"all":[]}),
json!([{"type":"pass"},{"type":"lookup"},{"type":"use_backend","id":"member"}]),
);
let result = p.apply(Stage::Request, &mut context(&[]), false);
assert!(result.cache.pass);
assert!(!result.cache.lookup);
assert_eq!(result.backend.as_deref(), Some("member"));
assert_eq!(p.backend_ids(), vec!["member"]);
}
#[test]
fn stop_is_stage_local_and_sequential_rules_observe_mutations() {
let p=settings(json!({"rules":[
{"id":"stop","actions":[{"type":"stop"}]},
{"id":"skip","actions":[{"type":"set_header","name":"X-Skip","value":"yes"}]},
{"id":"later","stage":"after_response","actions":[{"type":"set_header","name":"X-Later","value":"yes"}]}
]})).compile().unwrap();
let mut ctx = context(&[]);
assert!(p.apply(Stage::Request, &mut ctx, false).stopped);
assert!(!ctx.request_headers.contains_key("x-skip"));
p.apply(Stage::AfterResponse, &mut ctx, false);
assert_eq!(ctx.response_headers["x-later"], "yes");
}
#[test]
fn template_uses_last_header_occurrence_while_acl_matches_any() {
let p = program(
"backend_response",
json!({"fetch":"res.fhdr(X-Multi)","operator":"equals","values":["first"]}),
json!([{"type":"set_header","name":"X-Last","value":"%[res.fhdr(X-Multi)]"}]),
);
let mut ctx = context(&[("X-Multi", "first"), ("X-Multi", "last")]);
p.apply(Stage::BackendResponse, &mut ctx, false);
assert_eq!(ctx.response_headers["x-last"], "last");
}
#[test]
fn replace_header_and_replace_value_preserve_field_cardinality() {
let p=import_haproxy("http-response replace-value X-List ^foo$ bar\nhttp-response replace-header X-Version ^v([0-9]+)$ \"version-\\1\"").unwrap().policy.compile().unwrap();
let mut ctx = context(&[
("X-List", "foo, other"),
("X-List", "foo"),
("X-Version", "v12"),
]);
p.apply(Stage::BackendResponse, &mut ctx, false);
assert_eq!(
ctx.response_headers
.get_all("x-list")
.iter()
.map(|v| v.to_str().unwrap())
.collect::<Vec<_>>(),
vec!["bar, other", "bar"]
);
assert_eq!(ctx.response_headers["x-version"], "version-12");
}
#[test]
fn invalid_dynamic_uri_or_header_does_not_partially_apply() {
let p = program(
"pre_route",
json!({"all":[]}),
json!([{"type":"set_path","value":"%[var(txn.path)]"},{"type":"set_header","name":"X-Test","value":"%[var(txn.value)]"}]),
);
let mut ctx = context(&[]);
ctx.variables
.insert("txn.path".into(), "//evil.example/path".into());
ctx.variables
.insert("txn.value".into(), "a\r\nInjected: yes".into());
let result = p.apply(Stage::PreRoute, &mut ctx, true);
assert_eq!(ctx.path, "/assets/file.js");
assert!(!ctx.request_headers.contains_key("x-test"));
assert_eq!(result.trace[0].warnings.len(), 2);
}
#[test]
fn disabled_rules_validate_but_do_not_execute() {
let p = settings(json!({"rules":[{"id":"off","enabled":false,"actions":[{"type":"deny"}]}]}))
.compile()
.unwrap();
assert!(p.is_empty());
assert!(p
.apply(Stage::Request, &mut context(&[]), true)
.trace
.is_empty());
assert!(settings(json!({"rules":[{"id":"off","enabled":false,"actions":[{"type":"set_header","name":"Host","value":"bad"}]}]})).compile().is_err());
}
#[test]
fn settings_roundtrip_is_lossless_for_native_policies() {
let original = import_haproxy(VARY_CONFIG).unwrap().policy;
let serialized = serde_json::to_value(&original).unwrap();
let roundtrip: Settings = serde_json::from_value(serialized.clone()).unwrap();
assert_eq!(serde_json::to_value(roundtrip).unwrap(), serialized);
}
#[test]
fn resource_limits_reject_oversized_programs_before_runtime() {
let rules = (0..129)
.map(|i| json!({"id":format!("r{i}"),"actions":[{"type":"stop"}]}))
.collect::<Vec<_>>();
assert!(settings(json!({"rules":rules})).compile().is_err());
assert!(import_haproxy(&" ".repeat(256 * 1024 + 1)).is_err());
let huge = "a".repeat(8193);
assert!(settings(json!({"rules":[{"id":"huge","actions":[{"type":"set_header","name":"X-Large","value":huge}]}]})).compile().is_err());
}
#[test]
fn live_counters_exclude_tester_and_count_skipped_actions() {
let p = program(
"deliver",
json!({"all":[]}),
json!([{"type":"remove_header","name":"Vary"}]),
);
let mut ctx = context(&[("Vary", "Cookie")]);
p.apply(Stage::Deliver, &mut ctx, true);
assert_eq!(p.stats()[0].matches, 0);
p.apply(Stage::Deliver, &mut ctx, false);
let stats = p.stats();
assert_eq!(stats[0].matches, 1);
assert_eq!(stats[0].errors, 1);
assert_eq!(p.clone().stats()[0].matches, 1);
}
#[test]
fn regex_converter_parses_character_classes_and_bounds_expansion() {
let p = program(
"request",
json!({"all":[]}),
json!([{"type":"set_header","name":"X-Clean","value":"%[path,regsub([0-9],x)]"}]),
);
let mut ctx = context(&[]);
ctx.path = "/a123".into();
p.apply(Stage::Request, &mut ctx, false);
assert_eq!(ctx.request_headers["x-clean"], "/axxx");
let p = program(
"backend_response",
json!({"all":[]}),
json!([{"type":"replace_header","name":"X-Value","pattern":"","replacement":"a".repeat(8192)}]),
);
let mut ctx = context(&[("X-Value", "data")]);
let before = ctx.response_headers.clone();
assert_eq!(
p.apply(Stage::BackendResponse, &mut ctx, true).trace[0]
.warnings
.len(),
1
);
assert_eq!(ctx.response_headers, before);
}
#[test]
fn merge_remove_and_default_preserve_other_fields() {
let p = program(
"backend_response",
json!({"all":[]}),
json!([
{"type":"merge_header","name":"Vary","value":"Cookie, Accept-Encoding"},
{"type":"remove_value","name":"Vary","value":"Accept-Language"},
{"type":"set_if_missing","name":"X-Existing","value":"new"},
{"type":"set_if_missing","name":"X-Missing","value":"default"}
]),
);
let mut ctx = context(&[("Vary", "Accept-Language, Cookie"), ("X-Existing", "")]);
p.apply(Stage::BackendResponse, &mut ctx, false);
assert_eq!(ctx.response_headers["vary"], "Cookie, Accept-Encoding");
assert_eq!(ctx.response_headers["x-existing"], "");
assert_eq!(ctx.response_headers["x-missing"], "default");
}
#[test]
fn redirect_deny_and_return_terminate_only_request_processing() {
for (action, status) in [
(json!({"type":"deny","status":429}), 429),
(
json!({"type":"return","status":200,"body":"maintenance"}),
200,
),
(
json!({"type":"redirect","status":307,"location":"https://example.test/new"}),
307,
),
] {
let p = program(
"request",
json!({"all":[]}),
json!([action,{"type":"set_header","name":"X-Unreached","value":"no"}]),
);
let mut ctx = context(&[]);
let result = p.apply(Stage::Request, &mut ctx, false);
assert_eq!(result.terminal.unwrap().status, status);
assert!(!ctx.request_headers.contains_key("x-unreached"));
}
}
#[test]
fn numeric_cidr_cookies_and_query_samples_are_typed_and_ordered() {
let p = marker(
"backend_response",
json!({"all":[
{"fetch":"status","operator":"ge","values":["200"]},
{"fetch":"src","operator":"cidr","values":["192.0.2.0/24"]},
{"fetch":"req.cook(session)","operator":"equals","values":["second"]},
{"fetch":"res.cook(session)","operator":"equals","values":["returned"]},
{"fetch":"url_param(x)","operator":"equals","values":["two"]}
]}),
);
let mut ctx = context(&[("Set-Cookie", "session=returned; Path=/; HttpOnly")]);
ctx.client_ip = Some("192.0.2.12".parse().unwrap());
ctx.query = Some("x=one&x=two".into());
ctx.request_headers
.append("cookie", HeaderValue::from_static("session=first"));
ctx.request_headers
.append("cookie", HeaderValue::from_static("session=second"));
assert!(p.apply(Stage::BackendResponse, &mut ctx, true).trace[0].matched);
}
#[test]
fn expanded_acl_regex_budget_rejects_repeated_expensive_programs() {
let rules = (0..128)
.map(|i| json!({"id":format!("r{i}"),"when":{"acl":"re"},"actions":[{"type":"stop"}]}))
.collect::<Vec<_>>();
assert!(settings(
json!({"acls":{"re":{"fetch":"path","operator":"regex","values":["a","b"]}},"rules":rules})
)
.compile()
.is_err());
}
#[test]
fn preroute_cannot_return_or_redirect_before_location_authorization() {
for action in [
json!({"type":"return","status":200,"body":"early"}),
json!({"type":"redirect","status":302,"location":"/new"}),
] {
assert!(
settings(json!({"rules":[{"id":"early","stage":"pre_route","actions":[action]}]}))
.compile()
.is_err()
);
}
let p = program(
"pre_route",
json!({"all":[]}),
json!([{"type":"deny","status":403}]),
);
assert_eq!(
p.apply(Stage::PreRoute, &mut context(&[]), false)
.terminal
.unwrap()
.status,
403
);
}
+205
View File
@@ -0,0 +1,205 @@
use super::*;
use crate::cache::{self, Cache, Ticket};
use axum::{body::Body, response::Response};
use http::{HeaderValue, StatusCode};
use http_body_util::BodyExt;
use std::{sync::Arc, time::Duration};
use tokio_util::sync::CancellationToken;
fn ticket(cache: &Cache, headers: &HeaderMap, variant: &str) -> Ticket {
cache
.ticket_scoped_for_config_variant(
0,
11,
"credentials",
"http",
"credentials.example",
"origin",
"/same-url",
headers,
variant,
)
.unwrap()
}
async fn fill(cache: &Arc<Cache>, settings: &Settings, ticket: Ticket, body: String, legacy: bool) {
let mut response = Response::new(Body::from(body));
response.headers_mut().insert(
"cache-control",
HeaderValue::from_static("public, max-age=600"),
);
response
.headers_mut()
.insert("etag", HeaderValue::from_static("\"credential-test\""));
response.headers_mut().insert(
"vary",
HeaderValue::from_static(if legacy {
"Authorization"
} else {
"Cookie, Authorization"
}),
);
let plan = cache::plan(StatusCode::OK, response.headers(), settings, Duration::ZERO).unwrap();
cache
.wrap(response, ticket, plan, settings)
.into_body()
.collect()
.await
.unwrap();
}
#[tokio::test]
async fn credential_partitions_reject_old_entries_and_survive_cold_restart() {
let directory = tempfile::tempdir().unwrap();
let settings = Settings {
enabled: true,
max_entries: 32,
max_bytes: 2 * 1024 * 1024,
max_object_bytes: 64 * 1024,
cold_enabled: true,
cold_max_entries: 64,
cold_max_bytes: 4 * 1024 * 1024,
..Settings::default()
};
let shutdown = CancellationToken::new();
let cache = Cache::start(
11,
Some(directory.path().to_path_buf()),
settings.clone(),
shutdown.clone(),
);
let mode = CachePlan::new(None, &settings, "/same-url", || true);
const EXISTING_VARIANT: &str = "h:x-device=mobile\nhttp-policy:existing-dimension";
let mut old_headers = HeaderMap::new();
old_headers.insert("authorization", HeaderValue::from_static("Bearer alice"));
let old = ticket(&cache, &old_headers, EXISTING_VARIANT);
fill(
&cache,
&settings,
old.clone(),
"old auth-only representation".to_owned(),
true,
)
.await;
assert!(cache.get_tiered(&old, &settings).await.is_some());
let mut cases = Vec::new();
for cookie in [None, Some(""), Some("session=one"), Some("session=two")] {
for authorization in [None, Some(""), Some("Bearer alice"), Some("Bearer bob")] {
let mut headers = HeaderMap::new();
if let Some(value) = cookie {
headers.insert("cookie", HeaderValue::from_str(value).unwrap());
}
if let Some(value) = authorization {
headers.insert("authorization", HeaderValue::from_str(value).unwrap());
}
let mut variant = EXISTING_VARIANT.to_owned();
mode.partition_credentials(&headers, &mut variant);
let key = ticket(&cache, &headers, &variant);
assert!(
cache.get_tiered(&key, &settings).await.is_none(),
"new credential partition must not see an old or different entry"
);
assert!(
cache.revalidation_tiered(&key).await.is_none(),
"old validators must not cross credential partitions"
);
let body = format!("cookie={cookie:?};authorization={authorization:?}");
fill(&cache, &settings, key.clone(), body.clone(), false).await;
cases.push((headers, variant, key, body));
}
}
assert_eq!(
cache.view().entries,
17,
"all 16 credential variants and the legacy entry coexist"
);
for (_, _, key, body) in &cases {
let hit = cache.get_tiered(key, &settings).await.unwrap();
assert_eq!(
hit.response.into_body().collect().await.unwrap().to_bytes(),
body.as_bytes()
);
}
assert_eq!(cache.flush_hot_to_cold().await, 17);
assert_eq!(cache.view().entries, 0);
shutdown.cancel();
drop(cache);
let restart_shutdown = CancellationToken::new();
let restarted = Cache::start(
11,
Some(directory.path().to_path_buf()),
settings.clone(),
restart_shutdown.clone(),
);
assert_eq!(restarted.view().cold_entries, 17);
for (headers, variant, _, body) in &cases {
let key = ticket(&restarted, headers, variant);
let hit = restarted
.get_tiered(&key, &settings)
.await
.expect("credential variant survives COLD restart");
assert_eq!(
hit.response.into_body().collect().await.unwrap().to_bytes(),
body.as_bytes()
);
}
assert_eq!(restarted.view().cold_hits, 16);
let mut unknown = old_headers.clone();
unknown.insert(
"cookie",
HeaderValue::from_static("session=new-after-restart"),
);
let mut variant = EXISTING_VARIANT.to_owned();
mode.partition_credentials(&unknown, &mut variant);
let missing = ticket(&restarted, &unknown, &variant);
assert!(restarted.get_tiered(&missing, &settings).await.is_none());
assert!(restarted.revalidation_tiered(&missing).await.is_none());
restart_shutdown.cancel();
}
#[test]
fn credential_partition_keeps_rule_dimensions_and_opaque_header_boundaries() {
let settings = Settings::default();
let forced = CachePlan::new(None, &settings, "/", || true);
let lookup = CachePlan::new(None, &settings, "/", || false).with_vcl_cookie_lookup(true);
let ordinary = CachePlan::new(None, &settings, "/", || false);
let variant = |mode: CachePlan, headers: &HeaderMap, existing: &str| {
let mut result = existing.to_owned();
mode.partition_credentials(headers, &mut result);
result
};
let empty = HeaderMap::new();
assert_eq!(
variant(ordinary, &empty, "h:x-device=mobile"),
"h:x-device=mobile"
);
assert_ne!(
variant(forced, &empty, "h:x-device=mobile"),
variant(forced, &empty, "h:x-device=desktop")
);
assert_ne!(variant(forced, &empty, ""), variant(lookup, &empty, ""));
let mut repeated = HeaderMap::new();
repeated.append("cookie", HeaderValue::from_static("a=one"));
repeated.append("cookie", HeaderValue::from_static("b=two"));
let mut combined = HeaderMap::new();
combined.insert("cookie", HeaderValue::from_static("a=one, b=two"));
assert_ne!(
variant(forced, &repeated, ""),
variant(forced, &combined, "")
);
assert_ne!(
variant(lookup, &repeated, ""),
variant(lookup, &combined, "")
);
combined.insert("authorization", HeaderValue::from_static("Bearer alice"));
assert!(!variant(forced, &combined, "").contains("alice"));
let mut present_empty = HeaderMap::new();
present_empty.insert("cookie", HeaderValue::from_static(""));
assert_ne!(
variant(lookup, &empty, ""),
variant(lookup, &present_empty, "")
);
}
+42
View File
@@ -69,6 +69,38 @@ impl CachePlan {
)
}
pub(super) fn vary_cookie(self) -> bool {
self.force_cache() || self.vcl_cookie_lookup()
}
pub(super) fn partition_credentials(self, headers: &HeaderMap, variant: &mut String) {
use sha2::{Digest, Sha256};
if !self.vary_cookie() {
return;
}
let mut digest = Sha256::new();
digest.update(b"rustproxy-credential-partition-v1");
digest.update([u8::from(self.force_cache())]);
digest.update((variant.len() as u64).to_be_bytes());
digest.update(variant.as_bytes());
for name in ["cookie", "authorization"] {
if name == "authorization" && !self.force_cache() {
continue;
}
digest.update((name.len() as u64).to_be_bytes());
digest.update(name.as_bytes());
let values = headers.get_all(name);
digest.update((values.iter().count() as u64).to_be_bytes());
for value in values.iter() {
digest.update((value.as_bytes().len() as u64).to_be_bytes());
digest.update(value.as_bytes());
}
}
*variant = format!(
"credential-v1:{}",
crate::hex::encode_lower(&digest.finalize())
);
}
pub(super) fn request_policy(
self,
method: &Method,
@@ -98,6 +130,14 @@ impl CachePlan {
}
}
pub(super) fn require_credential_vary(headers: &mut HeaderMap, cookie: bool, authorization: bool) {
for (needed, name) in [(cookie, "cookie"), (authorization, "authorization")] {
if needed && !crate::cache::varies_on(headers, name) {
headers.append(http::header::VARY, http::HeaderValue::from_static(name));
}
}
}
pub(super) fn combine_policy(
original: RequestPolicy,
rewritten: impl FnOnce() -> RequestPolicy,
@@ -127,5 +167,7 @@ pub(super) fn range_selection(
}
}
#[cfg(test)]
mod credential_tests;
#[cfg(test)]
mod tests;
+45
View File
@@ -20,6 +20,7 @@ struct ErrorFallbackRequest {
transport: Option<Transport>,
snapshot: Arc<crate::config::Snapshot>,
exchange: Option<Arc<Exchange>>,
http_policy: Option<HttpPolicy>,
connection_lease: Option<Arc<ConnectionLease>>,
stop: Option<ServerShutdown>,
depth: u8,
@@ -35,6 +36,7 @@ impl ErrorFallbackRequest {
transport: request.extensions().get::<Transport>().copied(),
snapshot: snapshot.clone(),
exchange: request.extensions().get::<Arc<Exchange>>().cloned(),
http_policy: request.extensions().get::<HttpPolicy>().cloned(),
connection_lease: request.extensions().get::<Arc<ConnectionLease>>().cloned(),
stop: request.extensions().get::<ServerShutdown>().cloned(),
depth: request
@@ -51,6 +53,7 @@ impl ErrorFallbackRequest {
peer: PeerAddr,
local: LocalAddr,
dispatch: InternalFallbackRoute,
target: &crate::config::CompiledRoute,
) -> Request {
let mut request = Request::new(Body::from(body));
*request.method_mut() = self.method.clone();
@@ -66,6 +69,44 @@ impl ErrorFallbackRequest {
if let Some(exchange) = &self.exchange {
request.extensions_mut().insert(exchange.clone());
}
if let Some(http_policy) = &self.http_policy {
let mut policy = http_policy
.0
.lock()
.unwrap_or_else(|error| error.into_inner());
let private_source = policy.backend.is_some()
|| policy.scopes.iter().any(|scope| {
scope.requires_private_response()
|| scope.has_stage(crate::policy::Stage::BackendRequest)
});
policy.cache.no_store |= private_source;
policy.cache.lookup = false;
policy.cache.ttl = None;
policy.cache.grace = None;
policy.backend = None;
policy.scopes =
policy_scope_list(&self.snapshot, target.frontend.as_deref(), Some(target));
policy.disabled |= policy_control_plane(Some(target));
policy.context.request_headers = self.headers.clone();
policy.context.method = self.method.as_str().to_owned();
policy.context.path = self.uri.path().to_owned();
policy.context.query = self.uri.query().map(str::to_owned);
policy.context.response_headers.clear();
policy.context.status = None;
policy.context.cache_status = None;
policy.context.srv_id = None;
policy.context.srv_url = None;
policy.context.backend_time = None;
policy.context.hash_key = None;
policy.context.lb_algorithm = target
.pool
.as_ref()
.map(|pool| pool.algorithm_name().to_owned());
policy.context.location = Some(target.name.clone());
policy.context.vhost = target.frontend.as_ref().map(|frontend| frontend.id.clone());
request.extensions_mut().insert(http_policy.clone());
}
if let Some(lease) = &self.connection_lease {
request.extensions_mut().insert(lease.clone());
}
@@ -177,6 +218,7 @@ async fn execute_error_fallback(
target: fallback.target.clone(),
depth: template.depth.saturating_add(1),
},
&target,
);
let mut response = Box::pin(forward_request(state, peer, local, request)).await;
response.extensions_mut().insert(ErrorFallbackResponse);
@@ -208,3 +250,6 @@ fn intercept_route_origin_error(
.insert(crate::pages::OriginProvidedResponse);
response
}
#[cfg(test)]
include!("error_fallback_policy_tests.rs");
+246
View File
@@ -0,0 +1,246 @@
mod error_fallback_policy_tests {
use super::*;
use crate::{
auth::Auth,
config::{self, Config, ValidationPolicy},
db::Store,
};
use serde_json::json;
use std::net::SocketAddr;
use tempfile::TempDir;
use tower::ServiceExt;
struct Fixture {
app: Arc<App>,
_directory: TempDir,
}
impl Fixture {
async fn new(config: Config) -> Self {
let directory = TempDir::new().unwrap();
let validation = 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(),
};
let store = Store::open(&directory.path().join("db"), &config)
.await
.unwrap();
let auth = Auth::new(store.clone(), directory.path().to_owned())
.await
.unwrap();
let snapshot = config::compile(config, 0, &validation).unwrap();
let app = App::new(
store,
snapshot,
validation,
auth,
32,
Duration::from_secs(5),
Duration::from_secs(5),
Duration::from_secs(30),
);
Self {
app,
_directory: directory,
}
}
async fn get(&self, tenant: &str) -> (StatusCode, HeaderMap, Bytes) {
let mut request = Request::builder()
.uri("/recover")
.header(HOST, "localhost")
.header(USER_AGENT, "fallback-policy/1.0")
.header("x-tenant", tenant)
.body(Body::empty())
.unwrap();
request
.extensions_mut()
.insert(PeerAddr("192.0.2.60:40000".parse().unwrap()));
request
.extensions_mut()
.insert(LocalAddr("127.0.0.1:8080".parse().unwrap()));
let response = router(self.app.clone()).oneshot(request).await.unwrap();
let (parts, body) = response.into_parts();
(
parts.status,
parts.headers,
body.collect().await.unwrap().to_bytes(),
)
}
async fn stop(self) {
self.app.shutdown.cancel();
self.app.tunnels.close();
self.app.tunnels.wait().await;
self.app.store.close().await;
}
}
struct Origin {
addr: SocketAddr,
hits: Arc<AtomicU64>,
task: tokio::task::JoinHandle<()>,
}
impl Drop for Origin {
fn drop(&mut self) {
self.task.abort();
}
}
async fn origin(failing: bool) -> Origin {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let hits = Arc::new(AtomicU64::new(0));
let counter = hits.clone();
let app = Router::new().fallback(move |request: Request| {
let counter = counter.clone();
async move {
counter.fetch_add(1, Ordering::Relaxed);
if failing {
return (StatusCode::SERVICE_UNAVAILABLE, "primary unavailable")
.into_response();
}
let tenant = request
.headers()
.get("x-tenant")
.and_then(|v| v.to_str().ok())
.unwrap_or("-");
let mut response = Response::new(Body::from(format!("recovery for {tenant}")));
response.headers_mut().insert(
"cache-control",
HeaderValue::from_static("public, max-age=600"),
);
response
.headers_mut()
.insert("content-type", HeaderValue::from_static("text/plain"));
for name in ["x-policy-request", "x-policy-backend"] {
if let Some(value) = request.headers().get(name) {
response.headers_mut().insert(name, value.clone());
}
}
response
}
});
let task = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
Origin { addr, hits, task }
}
fn config(primary: SocketAddr, recovery: SocketAddr) -> Config {
let mut config = config::demo_config(primary);
config.cache.expose_status = true;
config.cache.expose_only_hits = false;
config.cache.static_ignore_cookies = false;
config.cache.collapse_enabled = false;
config.vhosts[0].backends = serde_json::from_value(json!([
{"id":"primary","url":format!("http://{primary}"),"allow_private":true},
{"id":"recovery","url":format!("http://{recovery}"),"allow_private":true}
]))
.unwrap();
config.vhosts[0].routes = serde_json::from_value(json!([
{"id":"public","path_prefix":"/","backend_id":"primary",
"error_fallback":{"target":"recovery","statuses":[503]}},
{"id":"recovery","internal":true,"path_prefix":"/","backend_id":"recovery"}
]))
.unwrap();
config
}
fn late_rules(scope: &str) -> crate::policy::Settings {
serde_json::from_value(json!({"rules":[
{"id":"delivery","stage":"deliver","actions":[
{"type":"append_header","name":"X-Policy-Stages","value":format!("{scope}-deliver")}]},
{"id":"final","stage":"after_response","actions":[
{"type":"append_header","name":"X-Policy-Stages","value":format!("{scope}-after")}]}
]})).unwrap()
}
#[tokio::test]
async fn internal_fallback_preserves_variables_resets_backend_and_delivers_target_once() {
let primary = origin(true).await;
let recovery = origin(false).await;
let mut config = config(primary.addr, recovery.addr);
config.policy = late_rules("global");
config.vhosts[0].policy = late_rules("vhost");
let mut original = late_rules("original");
original.rules.insert(
0,
serde_json::from_value(json!({
"id":"classify","stage":"request","actions":[
{"type":"set_var","name":"txn.label","value":"original-variable"},
{"type":"use_backend","id":"primary"},
{"type":"no_store"}]
}))
.unwrap(),
);
config.vhosts[0].routes[0].policy = original;
let mut target = late_rules("target");
for rule in [
json!({"id":"target-request","stage":"request","actions":[
{"type":"set_header","name":"X-Policy-Request","value":"%[var(txn.label)]"}]}),
json!({"id":"target-backend","stage":"backend_request","actions":[
{"type":"set_header","name":"X-Policy-Backend","value":"%[srv_id]"}]}),
json!({"id":"target-response","stage":"backend_response","actions":[
{"type":"set_header","name":"X-Policy-Response","value":"%[location]"}]}),
json!({"id":"target-context","stage":"after_response","actions":[
{"type":"set_header","name":"X-Policy-Location","value":"%[location]"}]}),
] {
target.rules.push(serde_json::from_value(rule).unwrap());
}
config.vhosts[0].routes[1].policy = target;
let fixture = Fixture::new(config).await;
let (status, headers, body) = fixture.get("alice").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body.as_ref(), b"recovery for alice");
assert_eq!(headers["x-policy-request"], "original-variable");
assert_eq!(headers["x-policy-backend"], "recovery");
assert_eq!(headers["x-policy-response"], "recovery");
assert_eq!(headers["x-policy-location"], "recovery");
assert_eq!(headers["x-cache-reason"], "http_policy_pass");
let stages: Vec<_> = headers
.get_all("x-policy-stages")
.iter()
.map(|v| v.to_str().unwrap())
.collect();
assert_eq!(
stages,
[
"global-deliver",
"vhost-deliver",
"target-deliver",
"global-after",
"vhost-after",
"target-after"
]
);
assert_eq!(primary.hits.load(Ordering::Relaxed), 1);
assert_eq!(recovery.hits.load(Ordering::Relaxed), 1);
fixture.stop().await;
}
#[tokio::test]
async fn private_original_policy_cannot_enable_shared_cache_on_fallback() {
let primary = origin(true).await;
let recovery = origin(false).await;
let mut config = config(primary.addr, recovery.addr);
config.vhosts[0].routes[0].policy = serde_json::from_value(json!({"rules":[{
"id":"private-response","stage":"backend_response","actions":[
{"type":"set_header","name":"X-Tenant","value":"%[req.fhdr(X-Tenant)]"}]
}]}))
.unwrap();
let fixture = Fixture::new(config).await;
for tenant in ["alice", "bob"] {
let (status, headers, body) = fixture.get(tenant).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body.as_ref(), format!("recovery for {tenant}").as_bytes());
assert_eq!(headers["x-cache"], "BYPASS");
assert_eq!(headers["x-cache-reason"], "http_policy_no_store");
}
assert_eq!(primary.hits.load(Ordering::Relaxed), 2);
assert_eq!(recovery.hits.load(Ordering::Relaxed), 2);
fixture.stop().await;
}
}
+8 -2
View File
@@ -5,7 +5,9 @@ if let Some(ticket) = &cache_ticket {
exchange.set_cache_outcome(scope, &host, 2, revalidation_reason.or(freshness_revalidation_reason).unwrap_or("cache_miss"));
}
if revalidation_reason.is_none() {
if let Some(mut hit) = state.cache.get_tiered(ticket, cache_settings).await {
if let Some(mut hit) = state.cache.get_tiered(ticket, cache_settings).await.filter(|hit| {
only_cached || !hit.background_revalidate || !cache_refresh_requires_request
}) {
let conditional = crate::cache::conditional_not_modified(
&client_conditionals,
hit.response.headers(),
@@ -71,6 +73,7 @@ if let Some(ticket) = &cache_ticket {
}
}
if cache_settings.proactive_refresh_enabled
&& !cache_refresh_requires_request
&& !only_cached
&& !hit.stale
&& hit.remaining_ttl > 0
@@ -197,7 +200,9 @@ if handshake.is_none()
break;
}
crate::cache::FillClaim::Waited => {
if let Some(mut hit) = state.cache.get_tiered(ticket, cache_settings).await {
if let Some(mut hit) = state.cache.get_tiered(ticket, cache_settings).await.filter(|hit| {
!hit.background_revalidate || !cache_refresh_requires_request
}) {
let conditional = crate::cache::conditional_not_modified(
&client_conditionals,
hit.response.headers(),
@@ -208,6 +213,7 @@ if handshake.is_none()
"cache_collapsed_hit"
};
if cache_settings.proactive_refresh_enabled
&& !cache_refresh_requires_request
&& !hit.stale
&& hit.remaining_ttl > 0
{
+24 -19
View File
@@ -45,7 +45,6 @@ if route.unavailable {
if let crate::config::CompiledSource::WebServer(service) = &route.source {
return include!("web_source.rs");
}
// Header rules with %[variables] need request facts; computed only when used.
let header_templates = snapshot.headers.has_templates()
|| route.frontend.as_ref().is_some_and(|f| f.headers.has_templates())
|| route.headers.has_templates();
@@ -60,8 +59,9 @@ let template_hash_key = (header_templates
})
})
.flatten();
let policy_backend_id = policy_backend(http_policy.as_ref());
let (backend, backend_lease, affinity_cookie) = if let Some(pool) = &route.pool {
let selection = match &route.backend_id {
let selection = match policy_backend_id.as_ref().or(route.backend_id.as_ref()) {
Some(id) => pool.select_member_wait(id).await,
None => pool
.select_wait_uri(context.client_ip, request.headers(), balance_uri.as_ref(), tls)
@@ -142,8 +142,7 @@ let mut cache_rule_context: Option<Arc<crate::cache::RuleContext>> = None;
let mut cache_rule_query: Option<Option<String>> = None;
let mut cache_rule_variant = String::new();
let mut cache_rule_gate = crate::cache::RuleGate::None;
// Security and configuration gates are known before any rule runs; they always
// win, so a Cookie guard is only ever relaxed when none of them applies.
let gate_input = crate::cache::GateInput {
admin_control_plane,
basic_auth: frontend.is_some_and(|f| f.basic_auth.is_some()),
@@ -154,9 +153,7 @@ let gate_input = crate::cache::GateInput {
upgrade: handshake.is_some(),
};
let mut cache_rule_lookup = false;
// VCL request mutations (cookie/query edits) still affect the origin when
// cache storage is disabled for this route. Storage eligibility is evaluated
// separately below; administrative/control-plane traffic remains excluded.
if !admin_control_plane {
if let Some(rules) = cache_settings.compiled_rules.clone() {
let mut rule_request = crate::cache::RuleRequest {
@@ -169,9 +166,7 @@ if !admin_control_plane {
};
let mut outcome = rules.evaluate_request(&rule_request, true);
cache_rule_gate = crate::cache::RuleGate::from_outcome(&outcome);
// Central static-cookie decision: a `cookie_pass` guard (never an
// explicit `pass`) may yield to the static-file cookie policy. The
// unguarded outcome then drives the forwarded request and cache key.
if cache_rule_gate == crate::cache::RuleGate::CookieGuard
&& crate::cache::request_gate(gate_input, crate::cache::RuleGate::None).is_none()
{
@@ -213,7 +208,11 @@ if !admin_control_plane {
}
}
}
let policy_reason = crate::cache::request_gate(gate_input, cache_rule_gate);
policy_refresh_request(http_policy.as_ref(), request.headers(), request.uri());
let http_cache_effects = policy_cache_effects(http_policy.as_ref());
cache_rule_lookup |= http_cache_effects.lookup && !http_cache_effects.pass;
let policy_reason = crate::cache::request_gate(gate_input, cache_rule_gate)
.or_else(|| policy_cache_bypass(http_policy.as_ref()));
let static_cookie_relaxed = policy_reason.is_none()
&& cache_rule_gate == crate::cache::RuleGate::CookieGuardRelaxed;
let cache_enabled = policy_reason.is_none();
@@ -247,7 +246,6 @@ let cache_plan = cache_plan::CachePlan::new(policy_reason, cache_settings, &path
.is_some_and(|frontend| frontend.force_cache.matches(&path, &public_suffix))
}).with_vcl_cookie_lookup(cache_rule_lookup && cache_settings.varnish_compatible);
let force_cache = cache_plan.force_cache();
// Explicit VCL hash takes precedence over the static cookie shortcut.
let ignore_static_cookie = cache_plan.ignore_cookie() && !cache_plan.vcl_cookie_lookup();
let original_policy = cache_plan.request_policy(
request.method(), request.headers(), body_empty, &path,
@@ -360,6 +358,11 @@ if header_templates {
*exchange.header_vars.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(request_vars));
}
}
policy_backend_info(http_policy.as_ref(), &backend.id, &backend.origin);
if let Some(response) = policy_request_stage(&mut request, crate::policy::Stage::BackendRequest,
&snapshot, route.frontend.as_deref(), Some(route), &host, context.client_ip, country.as_deref(), tls) {
return response;
}
context.apply_upstream(
request.headers_mut(),
route
@@ -386,11 +389,9 @@ let effective_policy = cache_plan::combine_policy(original_policy, || {
request.uri().query().is_some(), cache_settings,
)
});
// Cookies admitted through explicit VCL lookup must not be shared between
// different Cookie values unless the rule removed Cookie before this point.
let force_vary_cookie = (force_cache || cache_plan.vcl_cookie_lookup())
&& request.headers().contains_key(::http::header::COOKIE);
let force_vary_authorization = force_cache && request.headers().contains_key(::http::header::AUTHORIZATION);
let force_vary_cookie = cache_plan.vary_cookie();
let force_vary_authorization = force_cache;
let effective_reason = effective_policy.bypass_reason();
let revalidation_reason = effective_policy.revalidation_reason();
let effective_cacheable = effective_reason.is_none();
@@ -404,8 +405,7 @@ let range_requested = !matches!(range_selection, crate::cache::RangeSelection::N
let cache_route = route.id.as_str();
let mut cache_key_headers = None;
// The forwarded request still carries a Cookie that the cache key ignores:
// the backend response must prove that it is shareable before storage.
let shared_static_cookie_fill = effective_cacheable
&& ignore_static_cookie
&& request.headers().contains_key(::http::header::COOKIE);
@@ -417,6 +417,9 @@ if shared_static_cookie_fill {
let key_headers = cache_key_headers
.as_ref()
.unwrap_or_else(|| request.headers());
policy_hash_variant(http_policy.as_ref(), request.headers(), &mut cache_rule_variant);
cache_plan.partition_credentials(request.headers(), &mut cache_rule_variant);
let cache_ticket = if effective_cacheable {
state.cache.ticket_scoped_for_config_variant(
snapshot.envelope.revision,
@@ -448,6 +451,8 @@ let freshness_revalidation_reason = cached_revalidation
.and_then(|cached| cached.request_freshness_revalidation_reason(&freshness_headers));
let pending_revalidation = revalidation_reason.is_some()
|| freshness_revalidation_reason.is_some()
|| ((force_vary_cookie || force_vary_authorization
|| policy_requires_foreground_refresh(http_policy.as_ref())) && cached_revalidation.is_some())
|| cached_revalidation
.as_ref()
.is_some_and(|cached| !cached.reusable_for_request(&freshness_headers));
+4 -3
View File
@@ -7,17 +7,18 @@ if response.status() == StatusCode::NOT_MODIFIED && revalidation_sent {
crate::cache::normalize_static_cookie_vary(
StatusCode::OK, &mut merged, cache_settings,
upstream_started.elapsed(), ignore_static_cookie,
&crate::cache::ResponseOverrides::NONE,
&cache_rule_overrides,
);
let client_not_modified =
crate::cache::conditional_not_modified(&client_conditionals, &merged);
let mut revalidated = if let Some(mut hit) = state.cache.publish_revalidated(
let mut revalidated = if let Some(mut hit) = state.cache.publish_revalidated_with(
ticket.clone(),
cached,
merged.clone(),
&origin_validation_headers,
cache_settings,
upstream_started.elapsed(),
&cache_rule_overrides,
) {
if !client_not_modified {
if let crate::cache::RangeSelection::Single(range) = range_selection {
@@ -160,7 +161,7 @@ if let (Some(ticket), Some(plan), Some(transformed)) =
);
if cache_settings.proactive_refresh_enabled && proactive_remaining_ttl > 0
&& !force_vary_cookie && !force_vary_authorization
&& !cache_refresh_requires_request
{
schedule_proactive_refresh(
CacheRefreshContext {
+7 -15
View File
@@ -120,25 +120,17 @@ let shared_static_reason = if shared_static_cookie_fill && cache_ticket.is_some(
} else {
None
};
let cache_rule_overrides = cache_rule_context
let mut cache_rule_overrides = cache_rule_context
.as_ref()
.map(|rules| rules.response_overrides(response.status(), response.headers()))
.unwrap_or(crate::cache::ResponseOverrides::NONE);
// VCL backend-response mutations affect both the cache plan and the actual
// response, including requests that bypass storage.
cache_rule_overrides.apply_headers(response.headers_mut());
// A shared intermediary downstream must also partition by the credentials
// that RustProxy uses internally, not just RustProxy's HOT/COLD variants.
for (needed, header) in [
(force_vary_cookie, "cookie"),
(force_vary_authorization, "authorization"),
] {
if needed && !crate::cache::varies_on(response.headers(), header) {
if let Ok(value) = http::HeaderValue::from_str(header) {
response.headers_mut().append(::http::header::VARY, value);
}
}
}
policy_backend_info(http_policy.as_ref(), &active_backend.id, &active_backend.origin);
policy_response_stage(http_policy.as_ref(), crate::policy::Stage::BackendResponse, &mut response, exchange.as_ref());
policy_response_overrides(http_policy.as_ref(), &mut cache_rule_overrides);
cache_plan::require_credential_vary(response.headers_mut(), force_vary_cookie, force_vary_authorization);
let origin_status = response.status();
crate::cache::normalize_static_cookie_vary(
origin_status, response.headers_mut(), cache_settings,
+4 -3
View File
@@ -53,6 +53,7 @@ if request.method() == Method::HEAD && cache_ticket.is_some() {
let retry_method = request.method().clone();
let retry_policy = route.pool.as_ref().map(|pool| &pool.settings.retry);
let pool_retry_possible = route.backend_id.is_none()
&& policy_backend(http_policy.as_ref()).is_none()
&& !admin_control_plane
&& handshake.is_none()
&& retry_safe_method(&retry_method)
@@ -125,10 +126,10 @@ if websocket_upstream_h2 {
h2_direct_session = Some(session);
}
let request_body_empty = request.body().size_hint().exact() == Some(0);
let proactive_base_headers = if cache_ticket.is_some() && cache_settings.proactive_refresh_enabled {
let proactive_base_headers = if cache_ticket.is_some() && cache_settings.proactive_refresh_enabled
&& !cache_refresh_requires_request {
let mut headers = request.headers().clone();
// A cookie-independent static entry is refreshed as an anonymous
// request; never replay one client's session to fill a shared object.
if shared_static_cookie_fill {
headers.remove(::http::header::COOKIE);
}
File diff suppressed because it is too large. Load diff
+10 -5
View File
@@ -23,7 +23,8 @@
let transform_settings = route.frontend.as_ref().map(|frontend| &frontend.transform);
let scope = route.frontend.as_ref().map(|frontend| frontend.id.as_str()).unwrap_or("");
let enabled = cache_settings.active_for(route.cache)
&& frontend.is_none_or(|frontend| frontend.basic_auth.is_none() && frontend.auth_provider.is_none());
&& frontend.is_none_or(|frontend| frontend.basic_auth.is_none() && frontend.auth_provider.is_none())
&& policy_cache_bypass(http_policy.as_ref()).is_none();
if let Some(exchange) = request.extensions().get::<Arc<Exchange>>() {
exchange.set_cache_enabled(enabled);
exchange.set_transform_enabled(transform_settings.is_some_and(|settings| settings.enabled));
@@ -59,11 +60,14 @@
headers.remove(::http::header::COOKIE);
Some(headers)
} else { None };
let mut http_policy_variant = String::new();
policy_hash_variant(http_policy.as_ref(), &request_headers, &mut http_policy_variant);
cache_plan.partition_credentials(&request_headers, &mut http_policy_variant);
let cache_ticket = if eligible {
state.cache.ticket_scoped_for_config(snapshot.envelope.revision,
state.cache.ticket_scoped_for_config_variant(snapshot.envelope.revision,
state.cache.revision(), scope, context.scheme,
original_host.to_str().unwrap_or(""), &route.id, &public_suffix,
key_headers.as_ref().unwrap_or(&request_headers))
key_headers.as_ref().unwrap_or(&request_headers), &http_policy_variant)
.map(|ticket| ticket.with_varnish_compatible(cache_settings.varnish_compatible))
} else { None };
let range = cache_plan::range_selection(eligible, &request_method, &request_headers);
@@ -210,6 +214,8 @@
response.extensions_mut().insert(ResponseRulesApplied);
response.extensions_mut().insert(StaticSourceResponse);
cache_plan::require_credential_vary(response.headers_mut(), force_cache, force_cache);
let response_status = response.status();
crate::cache::normalize_static_cookie_vary(
response_status, response.headers_mut(), cache_settings,
@@ -259,8 +265,7 @@
let mut plan = if canonical { origin.without_vary("accept-encoding") }
else { origin };
if force_cache {
if request_headers.contains_key(::http::header::COOKIE) { plan = plan.with_vary("cookie"); }
if request_headers.contains_key(::http::header::AUTHORIZATION) { plan = plan.with_vary("authorization"); }
plan = plan.with_vary("cookie").with_vary("authorization");
}
response = state.cache.wrap_with_fill(response, ticket,
plan.restrict(transformed), cache_settings, None);
+118 -6
View File
@@ -8,9 +8,17 @@ async fn forward(
request.extensions_mut().insert(cookies.clone());
let cache_rules = crate::cache::RuleSink::default();
request.extensions_mut().insert(cache_rules.clone());
let http_policy = request.extensions().get::<HttpPolicy>().cloned();
let exchange = request.extensions().get::<Arc<Exchange>>().cloned();
let mut response = forward_request(state, peer, local, request).await;
cookies.apply(&mut response);
cache_rules.apply(&mut response);
policy_response_stage(
http_policy.as_ref(),
crate::policy::Stage::Deliver,
&mut response,
exchange.as_ref(),
);
response
}
@@ -96,8 +104,9 @@ async fn forward_request(
.cloned()
.unwrap_or_else(|| state.config.load_full());
let internal_dispatch = request.extensions().get::<InternalFallbackRoute>().cloned();
let routing_uri = request.uri().clone();
let path = if let Some(path) = decoded_path.as_deref() {
let http_policy = request.extensions().get::<HttpPolicy>().cloned();
let mut routing_uri = request.uri().clone();
let mut path = if let Some(path) = decoded_path.as_deref() {
std::borrow::Cow::Borrowed(path)
} else {
let Ok(path) = crate::acl::routing_path_view(routing_uri.path()) else {
@@ -160,7 +169,6 @@ async fn forward_request(
_ => true,
}
});
// Requests answered by a redirect or local 404 host are logged under that host.
if let Some(exchange) = request.extensions().get::<Arc<Exchange>>() {
let site = redirect
.map(|(redirect, _)| crate::proxy::body::LogSite::Redirect(redirect.id.clone()))
@@ -267,6 +275,7 @@ async fn forward_request(
let mut country_resolved = false;
let mut country: Option<String> = None;
if capture_country
|| http_policy.is_some()
|| snapshot.global_security.country_access.needs_geoip()
|| snapshot.global_security.rate_limit.needs_geoip()
{
@@ -452,15 +461,93 @@ async fn forward_request(
});
return response;
}
let policy_reserved_path = frontend
.and_then(|frontend| frontend.auth_provider.as_ref())
.is_some_and(|auth| auth.reserved_path(&path));
if policy_reserved_path {
if let Some(policy) = &http_policy {
policy
.0
.lock()
.unwrap_or_else(|error| error.into_inner())
.disabled = true;
}
}
let policy_pre_route = !policy_reserved_path
&& internal_dispatch.is_none()
&& (snapshot.policy.has_stage(crate::policy::Stage::PreRoute)
|| frontend
.is_some_and(|frontend| frontend.policy.has_stage(crate::policy::Stage::PreRoute)));
if policy_pre_route {
if let Some(response) = policy_request_stage(
&mut request,
crate::policy::Stage::PreRoute,
&snapshot,
frontend.map(Arc::as_ref),
None,
&host,
context.client_ip,
country.as_deref(),
tls,
) {
return response;
}
if request.uri() != &routing_uri {
let Ok(rewritten) = crate::acl::routing_path_view(request.uri().path()) else {
return error(
StatusCode::BAD_REQUEST,
"RustProxy: invalid policy routing path\n",
);
};
path = std::borrow::Cow::Owned(rewritten.into_owned());
if frontend
.and_then(|frontend| frontend.auth_provider.as_ref())
.is_some_and(|auth| auth.reserved_path(&path))
{
return error(
StatusCode::BAD_REQUEST,
"RustProxy: policy cannot rewrite into authentication callback\n",
);
}
routing_uri = request.uri().clone();
let client_ip = context.client_ip;
context = match snapshot.forwarding.context_with_peer(
request.headers(),
peer.0,
local.0,
tls,
&original_host,
&routing_uri,
frontend.is_some_and(|frontend| frontend.auth_provider.is_some()),
request
.extensions()
.get::<Arc<crate::forwarding::PeerFormatting>>()
.map(Arc::as_ref),
true,
) {
Ok(context) => context,
Err(_) => {
return error(
StatusCode::BAD_REQUEST,
"RustProxy: invalid rewritten forwarding context\n",
)
}
};
if context.client_ip != client_ip && context.override_client_ip(client_ip).is_err() {
return error(
StatusCode::BAD_REQUEST,
"RustProxy: invalid policy client context\n",
);
}
}
}
let selected = if let Some(dispatch) = &internal_dispatch {
if frontend.is_none_or(|frontend| frontend.id != dispatch.vhost_id) {
None
} else {
snapshot.select_internal_on(&host, &dispatch.vhost_id, &dispatch.target, local.0, tls)
}
} else if frontend.is_some_and(|frontend| frontend.conditional_routes) {
// Locations with request conditions are selected here, with the final client
// address and country; earlier stages only saw unconditional locations.
} else if policy_pre_route || frontend.is_some_and(|frontend| frontend.conditional_routes) {
let facts = crate::vhost::RouteRequest {
method: request.method(),
headers: request.headers(),
@@ -486,6 +573,14 @@ async fn forward_request(
} else {
snapshot.select_on(&host, &path, local.0, tls)
};
if let Some(policy) = &http_policy {
let mut policy = policy.0.lock().unwrap_or_else(|error| error.into_inner());
policy.scopes = policy_scope_list(&snapshot, frontend.map(Arc::as_ref), selected);
policy.disabled |= policy_control_plane(selected);
policy.context.client_ip = Some(context.client_ip);
policy.context.country = country.clone();
policy.context.location = selected.map(|route| route.name.clone());
}
if let Some(route) = selected {
if let Some(response) = method_policy_denial(&route.method_policy, request.method()) {
return response;
@@ -581,6 +676,19 @@ async fn forward_request(
} else {
None
};
if let Some(response) = policy_request_stage(
&mut request,
crate::policy::Stage::Request,
&snapshot,
frontend.map(Arc::as_ref),
selected,
&host,
context.client_ip,
country.as_deref(),
tls,
) {
return response;
}
if crate::pages::literal_ip_authority(original_host.to_str().unwrap_or("")) {
if let Some(page) = &snapshot.envelope.config.pages.direct_ip {
return page.serve(request.method(), StatusCode::OK);
@@ -650,6 +758,10 @@ async fn forward_request(
shared_static_cookie_fill,
) = include!("forward/route_cache.rs");
let cache_refresh_requires_request = force_vary_cookie
|| force_vary_authorization
|| policy_requires_foreground_refresh(http_policy.as_ref());
let (serve_stale, mut fill_leader) = include!("forward/cache_lookup.rs");
let (
+3
View File
@@ -2,6 +2,7 @@ include!("types.rs");
include!("identity.rs");
include!("error_fallback.rs");
include!("cache_helpers.rs");
include!("policy.rs");
mod cache_plan;
mod web_cache_revalidation;
include!("cache_http_invalidation.rs");
@@ -20,3 +21,5 @@ include!("cache_http_invalidation_tests.rs");
include!("forward/cache_fast_path_tests.rs");
#[cfg(test)]
include!("forward/static_cookie_policy_tests.rs");
#[cfg(test)]
include!("forward/vcl_policy_matrix_tests.rs");
+380
View File
@@ -0,0 +1,380 @@
#[derive(Clone)]
struct HttpPolicy(Arc<Mutex<HttpPolicyTransaction>>);
struct HttpPolicyTransaction {
context: crate::policy::Context,
scopes: Vec<Arc<crate::policy::CompiledPolicy>>,
cache: crate::policy::CacheEffects,
backend: Option<String>,
disable_compression: bool,
disabled: bool,
}
fn policy_scope_list(
snapshot: &crate::config::Snapshot,
frontend: Option<&crate::config::CompiledFrontend>,
route: Option<&crate::config::CompiledRoute>,
) -> Vec<Arc<crate::policy::CompiledPolicy>> {
std::iter::once(snapshot.policy.clone())
.chain(frontend.map(|item| item.policy.clone()))
.chain(route.map(|item| item.policy.clone()))
.filter(|policy| !policy.is_empty())
.collect()
}
fn policy_control_plane(route: Option<&crate::config::CompiledRoute>) -> bool {
route.is_some_and(|route| {
route
.backend
.as_ref()
.is_some_and(|backend| backend.targets_admin_listener)
|| route.pool.as_ref().is_some_and(|pool| {
pool.members
.iter()
.any(|member| member.backend.targets_admin_listener)
})
})
}
fn new_http_policy(
request: &Request,
snapshot: &crate::config::Snapshot,
frontend: Option<&crate::config::CompiledFrontend>,
route: Option<&crate::config::CompiledRoute>,
tls: bool,
) -> Option<HttpPolicy> {
if snapshot.policy.is_empty() && frontend.is_none_or(|item| !item.has_policies) {
return None;
}
let context = crate::policy::Context {
request_headers: request.headers().clone(),
method: request.method().as_str().to_owned(),
path: request.uri().path().to_owned(),
query: request.uri().query().map(str::to_owned),
host: request
.headers()
.get(HOST)
.and_then(|value| value.to_str().ok())
.and_then(|value| request_host(value).ok())
.unwrap_or_default(),
tls,
vhost: frontend.map(|item| item.id.clone()),
location: route.map(|item| item.name.clone()),
req_id: request
.headers()
.get("x-request-id")
.and_then(|value| value.to_str().ok())
.map(str::to_owned),
..Default::default()
};
Some(HttpPolicy(Arc::new(Mutex::new(HttpPolicyTransaction {
context,
scopes: policy_scope_list(snapshot, frontend, route),
cache: Default::default(),
backend: None,
disable_compression: false,
disabled: policy_control_plane(route),
}))))
}
impl HttpPolicyTransaction {
fn apply(&mut self, stage: crate::policy::Stage) -> Option<crate::policy::TerminalResponse> {
if self.disabled {
return None;
}
for scope in &self.scopes {
if !scope.has_stage(stage) {
continue;
}
let outcome = scope.apply(stage, &mut self.context, false);
self.cache.pass |= outcome.cache.pass;
self.cache.lookup |= outcome.cache.lookup;
self.cache.no_store |= outcome.cache.no_store;
if outcome.cache.ttl.is_some() {
self.cache.ttl = outcome.cache.ttl;
}
if outcome.cache.grace.is_some() {
self.cache.grace = outcome.cache.grace;
}
for header in outcome.cache.hash_headers {
if !self.cache.hash_headers.contains(&header) {
self.cache.hash_headers.push(header);
}
}
if outcome.backend.is_some() {
self.backend = outcome.backend;
}
self.disable_compression |= outcome.disable_compression;
if outcome.terminal.is_some() {
return outcome.terminal;
}
}
None
}
}
fn policy_terminal(terminal: crate::policy::TerminalResponse) -> Response {
let status = StatusCode::from_u16(terminal.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
let mut response = (status, terminal.body).into_response();
if let Some(location) = terminal
.location
.and_then(|value| HeaderValue::from_str(&value).ok())
{
response
.headers_mut()
.insert(::http::header::LOCATION, location);
}
response.headers_mut().insert(
::http::header::CACHE_CONTROL,
HeaderValue::from_static("no-store"),
);
response.extensions_mut().insert(LocalGeneratedResponse);
response
}
fn policy_request_stage(
request: &mut Request,
stage: crate::policy::Stage,
snapshot: &crate::config::Snapshot,
frontend: Option<&crate::config::CompiledFrontend>,
route: Option<&crate::config::CompiledRoute>,
host: &str,
client_ip: std::net::IpAddr,
country: Option<&str>,
tls: bool,
) -> Option<Response> {
let policy = request.extensions().get::<HttpPolicy>()?.clone();
let mut policy = policy.0.lock().unwrap_or_else(|error| error.into_inner());
policy.disabled |= policy_control_plane(route);
if policy.disabled {
return None;
}
policy.scopes = policy_scope_list(snapshot, frontend, route);
policy.context.request_headers = request.headers().clone();
policy.context.method = request.method().as_str().to_owned();
policy.context.path = request.uri().path().to_owned();
policy.context.query = request.uri().query().map(str::to_owned);
policy.context.host = host.to_owned();
policy.context.client_ip = Some(client_ip);
policy.context.country = country.map(str::to_owned);
policy.context.tls = tls;
policy.context.location = route.map(|item| item.name.clone());
policy.context.vhost = frontend.map(|item| item.id.clone());
policy.context.lb_algorithm = route
.and_then(|item| item.pool.as_ref())
.map(|pool| pool.algorithm_name().to_owned());
policy.context.hash_key = route
.and_then(|item| item.pool.as_ref())
.and_then(|pool| pool.balance_key(client_ip, request.headers(), Some(request.uri())));
let terminal = policy.apply(stage);
if stage == crate::policy::Stage::PreRoute {
let target = match &policy.context.query {
Some(query) if !query.is_empty() => format!("{}?{}", policy.context.path, query),
_ => policy.context.path.clone(),
};
if target.len() > 8192 || crate::acl::routing_path_view(&policy.context.path).is_err() {
return Some(error(
StatusCode::BAD_REQUEST,
"RustProxy: invalid policy request target\n",
));
}
let Ok(target) = target.parse::<http::uri::PathAndQuery>() else {
return Some(error(
StatusCode::BAD_REQUEST,
"RustProxy: invalid policy request target\n",
));
};
let mut parts = request.uri().clone().into_parts();
parts.path_and_query = Some(target);
let Ok(uri) = Uri::from_parts(parts) else {
return Some(error(
StatusCode::BAD_REQUEST,
"RustProxy: invalid policy request target\n",
));
};
*request.uri_mut() = uri;
}
*request.headers_mut() = policy.context.request_headers.clone();
terminal.map(policy_terminal)
}
fn policy_backend_info(policy: Option<&HttpPolicy>, id: &str, url: &str) {
if let Some(policy) = policy {
let mut policy = policy.0.lock().unwrap_or_else(|error| error.into_inner());
policy.context.srv_id = Some(id.rsplit('/').next().unwrap_or(id).to_owned());
policy.context.srv_url = Some(url.to_owned());
}
}
fn policy_backend(policy: Option<&HttpPolicy>) -> Option<String> {
policy.and_then(|policy| {
let policy = policy.0.lock().unwrap_or_else(|error| error.into_inner());
(!policy.disabled).then(|| policy.backend.clone()).flatten()
})
}
fn policy_cache_effects(policy: Option<&HttpPolicy>) -> crate::policy::CacheEffects {
policy
.map(|policy| {
let policy = policy.0.lock().unwrap_or_else(|error| error.into_inner());
if policy.disabled {
Default::default()
} else {
policy.cache.clone()
}
})
.unwrap_or_default()
}
fn policy_cache_bypass(policy: Option<&HttpPolicy>) -> Option<&'static str> {
let policy = policy?;
let policy = policy.0.lock().unwrap_or_else(|error| error.into_inner());
if policy.disabled {
return None;
}
if policy.cache.pass {
return Some("http_policy_pass");
}
if policy.cache.no_store {
return Some("http_policy_no_store");
}
if policy.backend.is_some() {
return Some("http_policy_backend");
}
if policy
.scopes
.iter()
.any(|scope| scope.has_stage(crate::policy::Stage::BackendRequest))
{
return Some("http_policy_backend_request");
}
if policy
.scopes
.iter()
.any(|scope| scope.requires_private_response())
{
return Some("http_policy_private_response");
}
None
}
fn policy_requires_foreground_refresh(policy: Option<&HttpPolicy>) -> bool {
policy.is_some_and(|policy| {
let policy = policy.0.lock().unwrap_or_else(|error| error.into_inner());
!policy.disabled
&& (!policy.cache.hash_headers.is_empty()
|| policy
.scopes
.iter()
.any(|scope| scope.has_stage(crate::policy::Stage::BackendResponse)))
})
}
fn policy_hash_variant(policy: Option<&HttpPolicy>, headers: &HeaderMap, legacy: &mut String) {
use sha2::{Digest, Sha256};
let effects = policy_cache_effects(policy);
if effects.hash_headers.is_empty() {
return;
}
let mut hash = Sha256::new();
for name in effects.hash_headers {
hash.update((name.len() as u64).to_be_bytes());
hash.update(name.as_bytes());
let values = headers.get_all(name.as_str());
hash.update((values.iter().count() as u64).to_be_bytes());
for value in values.iter() {
hash.update((value.as_bytes().len() as u64).to_be_bytes());
hash.update(value.as_bytes());
}
}
legacy.push_str("\nhttp-policy:");
legacy.push_str(&crate::hex::encode_lower(&hash.finalize()));
}
fn policy_refresh_request(policy: Option<&HttpPolicy>, headers: &HeaderMap, uri: &Uri) {
if let Some(policy) = policy {
let mut policy = policy.0.lock().unwrap_or_else(|error| error.into_inner());
policy.context.request_headers = headers.clone();
policy.context.path = uri.path().to_owned();
policy.context.query = uri.query().map(str::to_owned);
}
}
fn policy_response_stage<B>(
policy: Option<&HttpPolicy>,
stage: crate::policy::Stage,
response: &mut http::Response<B>,
exchange: Option<&Arc<Exchange>>,
) {
let Some(policy) = policy else {
return;
};
if response
.extensions()
.get::<crate::auth_provider::AuthenticationResponse>()
.is_some()
|| response
.extensions()
.get::<crate::pages::MinimalWelcome>()
.is_some()
{
return;
}
let mut policy = policy.0.lock().unwrap_or_else(|error| error.into_inner());
if policy.disabled {
return;
}
policy.context.status = Some(response.status().as_u16());
policy.context.response_headers = response.headers().clone();
if let Some(exchange) = exchange {
policy.context.cache_status = Some(
match exchange.cache_status.load(Ordering::Relaxed) {
1 => "HIT",
2 => "MISS",
_ => "BYPASS",
}
.to_owned(),
);
if policy.context.cache_status.as_deref() == Some("HIT") {
policy.context.srv_id = None;
policy.context.srv_url = None;
policy.context.backend_time = None;
}
}
if let Some(origin) = response
.extensions()
.get::<OriginBackend>()
.filter(|_| policy.context.cache_status.as_deref() != Some("HIT"))
{
policy.context.srv_id = Some(origin.0.rsplit('/').next().unwrap_or(&origin.0).to_owned());
}
if let Some(timing) = response
.extensions()
.get::<OriginTiming>()
.filter(|_| policy.context.cache_status.as_deref() != Some("HIT"))
{
policy.context.backend_time = Some(format!("{:.2}ms", timing.0.as_secs_f64() * 1000.0));
}
let _ = policy.apply(stage);
*response.headers_mut() = policy.context.response_headers.clone();
if policy.disable_compression {
response.extensions_mut().insert(crate::compression::Skip);
}
}
fn policy_response_overrides(
policy: Option<&HttpPolicy>,
overrides: &mut crate::cache::ResponseOverrides,
) {
let effects = policy_cache_effects(policy);
if overrides.ttl.is_none() {
overrides.ttl = effects.ttl;
}
if overrides.grace.is_none() {
overrides.grace = effects.grace;
}
overrides.no_store |= effects.no_store;
}
+5
View File
@@ -259,6 +259,8 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
.as_ref()
.and_then(|frontend| frontend.proxy_timeouts.send_timeout())
.unwrap_or(state.body_idle_timeout);
let http_policy = new_http_policy(&request, &snapshot, frontend_context.as_deref(), route_context.as_deref(), transport_tls);
if let Some(policy) = &http_policy { request.extensions_mut().insert(policy.clone()); }
let request = request.map(|body| wrap_observed_request(body, &exchange, request_send_timeout));
let mut response = dispatch(state.clone(), request).await;
let final_route_context = response
@@ -539,6 +541,9 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
&vars,
);
}
if !minimal_welcome {
policy_response_stage(http_policy.as_ref(), crate::policy::Stage::AfterResponse, &mut response, Some(&exchange));
}
if response
.extensions()
.get::<crate::pages::PageServed>()
+4 -12
View File
@@ -1,6 +1,8 @@
use crate::cache::{Cache, RangeSelection, Revalidation, Settings, Ticket};
use axum::{body::Body, response::Response};
use http::{HeaderMap, HeaderValue, Method, StatusCode};
#[cfg(test)]
use http::HeaderValue;
use http::{HeaderMap, Method, StatusCode};
use std::time::Duration;
pub(super) struct WebRevalidated {
@@ -77,17 +79,7 @@ pub(super) fn finish_web_revalidation(
ignore_cookie,
&crate::cache::ResponseOverrides::NONE,
);
if force_cache {
if client.contains_key(::http::header::COOKIE) {
merged.append(::http::header::VARY, HeaderValue::from_static("Cookie"));
}
if client.contains_key(::http::header::AUTHORIZATION) {
merged.append(
::http::header::VARY,
HeaderValue::from_static("Authorization"),
);
}
}
super::cache_plan::require_credential_vary(&mut merged, force_cache, force_cache);
let can_store = origin_safe && !(ignore_cookie && crate::cache::varies_on(&merged, "cookie"));
let client_not_modified = crate::cache::conditional_not_modified(client, &merged);
let range = crate::cache::request_range(method, client);
+3
View File
@@ -12,3 +12,6 @@ include!("runtime/health_endpoint.rs");
include!("runtime/tests.rs");
#[cfg(test)]
include!("runtime/headless_tls_tests.rs");
#[cfg(test)]
include!("runtime/policy_revision_tests.rs");
+30
View File
@@ -0,0 +1,30 @@
mod policy_revision_tests {
use super::*;
fn policy() -> crate::policy::Settings {
serde_json::from_value(
serde_json::json!({"rules":[{"id":"representation", "stage":"backend_response",
"actions":[{"type":"set_header","name":"Vary","value":"Accept-Language"}]}]}),
)
.unwrap()
}
#[test]
fn policy_reload_invalidates_the_affected_cache_scope() {
let base = config::demo_config("127.0.0.1:9000".parse().unwrap());
let mut global = base.clone();
global.policy = policy();
assert_ne!(cache_revision(&base), cache_revision(&global));
let mut local = base.clone();
local.vhosts[0].policy = policy();
assert_eq!(cache_revision(&base), cache_revision(&local));
assert_ne!(
vhost_cache_revision(&base.vhosts[0]),
vhost_cache_revision(&local.vhosts[0])
);
let mut location = base.clone();
location.vhosts[0].routes[0].policy = policy();
assert_ne!(
vhost_cache_revision(&base.vhosts[0]),
vhost_cache_revision(&location.vhosts[0])
);
}
}
+7 -9
View File
@@ -100,13 +100,6 @@ fn cache_revision(config: &config::Config) -> u64 {
cache.expose_only_hits = false;
cache.expose_detailed_status = false;
cache.via_header = None;
// Operational tuning: memory/eviction limits, COLD demotion and GC,
// request coalescing, stale-if-error triggers and proactive refresh.
// They change how the cache is run, not what a stored object contains or
// who may receive it, so changing them must not purge HOT/COLD. New limits
// apply immediately (`Cache::configure` evicts above a lowered limit).
// Representation/privacy fields (enabled, varnish_compatible, TTL/grace,
// static Cookie policy, rules, cold_enabled/cold_path) stay in the digest.
let neutral = crate::cache::Settings::default();
cache.max_bytes = neutral.max_bytes;
cache.max_object_bytes = neutral.max_object_bytes;
@@ -147,14 +140,19 @@ fn cache_revision(config: &config::Config) -> u64 {
for service in &mut web_services {
service.sendfile = crate::web_server::SendfileMode::Off;
}
cache_digest(&(
let legacy = cache_digest(&(
&cache,
&transform,
&config.headers,
&config.forwarding,
&web_services,
&config.php_fpm_profiles,
))
));
if config.policy.is_empty() {
legacy
} else {
cache_digest(&(legacy, &config.policy))
}
}
fn cache_digest<T: serde::Serialize>(value: &T) -> u64 {
+7 -7
View File
@@ -238,8 +238,6 @@ pub enum PathMatch {
Exact,
Regex,
RegexInsensitive,
/// Any path: a vhost-wide rule selected only by its `conditions`. Evaluated with
/// regex locations, in list order.
Any,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
@@ -289,7 +287,9 @@ impl Default for LocationResponse {
pub enum Source {
#[default]
ReverseProxy,
WebServer { web_service_id: String },
WebServer {
web_service_id: String,
},
}
impl Source {
pub fn is_reverse_proxy(&self) -> bool {
@@ -400,6 +400,8 @@ pub struct Vhost {
pub acl: Option<Acl>,
#[serde(default)]
pub headers: HeaderRules,
#[serde(default, skip_serializing_if = "crate::policy::Settings::is_empty")]
pub policy: crate::policy::Settings,
#[serde(default)]
pub security_headers: SecurityHeaders,
#[serde(default)]
@@ -536,14 +538,10 @@ pub struct PathRoute {
pub source: Source,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub backend_id: Option<String>,
/// Backend group of this location (ids of vhost backends). Empty: the vhost pool
/// (or `backend_id`). Like a HAProxy `use_backend` target sharing the vhost servers.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub backend_ids: Vec<String>,
/// Location-specific balancing (algorithm, hash key, affinity) over its backends.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub load_balancing: Option<crate::balance::RouteBalancing>,
/// Extra request conditions (all must hold) besides the path.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub conditions: Vec<RouteCondition>,
pub id: String,
@@ -567,6 +565,8 @@ pub struct PathRoute {
pub method_policy: MethodPolicy,
#[serde(default)]
pub headers: HeaderRules,
#[serde(default, skip_serializing_if = "crate::policy::Settings::is_empty")]
pub policy: crate::policy::Settings,
#[serde(default)]
pub rewrite: PathRewrite,
#[serde(default, skip_serializing_if = "Option::is_none")]
+3
View File
@@ -17,6 +17,7 @@ impl Default for PathRoute {
country_access: crate::rate_limit::CountryAccess::default(),
method_policy: MethodPolicy::default(),
headers: HeaderRules::default(),
policy: crate::policy::Settings::default(),
rewrite: PathRewrite::default(),
response: None,
redirect: None,
@@ -43,6 +44,7 @@ impl PathRoute {
&& self.country_access.countries.is_empty()
&& self.method_policy == MethodPolicy::default()
&& self.headers.is_empty()
&& self.policy.is_empty()
&& self.rewrite.mode == RewriteMode::Preserve
&& self.rewrite.value.is_empty()
&& self.response.is_none()
@@ -340,6 +342,7 @@ impl Vhost {
self.security_headers.compile()?;
self.user_agent_blocking.compile()?;
self.headers.compile()?;
self.policy.compile()?;
if let Some(acl) = &self.acl {
acl.compile()?;
}