This commit is contained in:
Mateusz Gruszczyński committed 2026-11-19 16:23:30 +01:00
1 parent 38a23e2210
commit 45b1fc04c7
36 files changed
+9594 -7892

No files matched your search

+8 -4
View File
@@ -145,6 +145,7 @@ async fn cache_rules_test(
client_ip,
};
let request_outcome = rules.evaluate_request(&request, false);
request_outcome.apply_headers(&mut headers);
request_outcome.rewrite_cookies(&mut headers);
let query = match request_outcome.rewrite_query(uri.query()) {
Some(rewritten) => rewritten,
@@ -161,7 +162,10 @@ async fn cache_rules_test(
} else if !settings.enabled {
Some("cache_disabled")
} else {
crate::cache::request_policy(&method, &headers, true, &path, query.is_some(), &settings)
crate::cache::request_policy_with_vcl_cookie(
&method, &headers, true, &path, query.is_some(), &settings,
request_outcome.lookup.is_some(),
)
.bypass_reason()
};
let mut response_value = Value::Null;
@@ -175,9 +179,7 @@ async fn cache_rules_test(
})?;
let mut response_headers = cache_rule_headers(&response.headers)?;
let outcome = rules.evaluate_response(&request, status, &response_headers, false);
if outcome.overrides.strip_set_cookie {
response_headers.remove(http::header::SET_COOKIE);
}
outcome.overrides.apply_headers(&mut response_headers);
let plan = if request_policy.is_none() {
crate::cache::plan_with(
status,
@@ -220,6 +222,8 @@ async fn cache_rules_test(
"matched": request_outcome.matched,
"overridden": request_outcome.overridden,
"pass": request_outcome.pass,
"lookup": request_outcome.lookup,
"header_edits": request_outcome.header_edits,
"target": target,
"cookie": headers.get(http::header::COOKIE).and_then(|v| v.to_str().ok()),
"variant": request_outcome.hash,
+1
View File
@@ -24,6 +24,7 @@ pub(super) static READER_DOCUMENTS: &[(&str, &str, &str)] = &[
reader_doc!("docs/WEB_SERVER.md", "guides"),
reader_doc!("docs/PHP_FPM.md", "guides"),
reader_doc!("docs/CACHE.md", "guides"),
reader_doc!("docs/VCL.md", "guides"),
reader_doc!("docs/RESPONSE_DELIVERY.md", "guides"),
reader_doc!("docs/TRANSPORT.md", "guides"),
reader_doc!("docs/STREAMS.md", "guides"),
+11 -5
View File
@@ -2,7 +2,7 @@
"openapi": "3.0.3",
"info": {
"title": "RustProxy Administration API",
"version": "0.38.7",
"version": "0.38.8",
"description": "Administration API for the active panel origin. Sign in through the panel; the same-origin HttpOnly cookie authenticates all private operations. Mutations also require the exact Origin, X-RustProxy-Request: 1 and a session-bound X-CSRF-Token. Loopback HTTP is the default; Settings can enable HTTPS before using a non-loopback administration bind. This document contains no live configuration or credentials. Object schemas marked extensible are summaries: full configuration validation is authoritative in Rust. The API also permits explicitly scoped GeneralApiBearer tokens on a narrow route allowlist, with RO/RW and source CIDR checks; API-token management and Prometheus-token management are browser-session-only."
},
"servers": [
@@ -8770,7 +8770,7 @@
},
"CacheRule": {
"type": "object",
"description": "Cache rule (since 0.37.1). Request rules run before the cache lookup (vcl_recv/vcl_hash), response rules on a backend response (vcl_backend_response), deliver rules on every response sent to the client (vcl_deliver). Vhost rules run before global rules; for TTL, grace, pass and no_store the first matching rule wins.",
"description": "Cache rule (since 0.37.1, extended in 0.38.8). Request rules run in vcl_recv then vcl_hash after return(hash); response rules run before origin cache admission; deliver rules run before sending headers. Vhost rules precede global rules and own their mutated header fields. Later assignments in the same scope take precedence unless a terminal return stops the stage. VCL import is a supported subset and returns warnings for unsupported operations.",
"required": [
"id",
"actions"
@@ -8856,13 +8856,14 @@
},
"actions": {
"type": "array",
"minItems": 1,
"minItems": 0,
"maxItems": 16,
"items": {
"type": "object",
"description": "type: pass, strip_cookies{keep}, strip_query{params,keep_only}, hash_header{name}, hash_cookie{name} (request); ttl{seconds}, grace{seconds}, no_store, ignore_cache_control, strip_set_cookie (response); set_header{name,value}, default_header{name,value} (only when the response lacks the header, since 0.37.2), remove_header{name} (deliver; deliver rules apply to every response of the vhost, also when caching is off).",
"description": "type: pass, lookup (VCL return(hash), Cookie exception in Varnish-compatible mode), strip_cookies{keep}, strip_query{params,keep_only}, hash_header{name}, hash_cookie{name}, set_request_header{name,value}, remove_request_header{name} (request; protected auth/cache/framing headers cannot be changed); ttl{seconds}, grace{seconds}, no_store, allow_store (reverses rule no_store only; origin restrictions remain), ignore_cache_control, strip_set_cookie, set_backend_header{name,value}, remove_backend_header{name} (response, applied before cacheability and forwarded headers); set_header{name,value}, default_header{name,value}, remove_header{name} (deliver, including cache-disabled responses).",
"additionalProperties": true
}
},
"description": "Zero actions allowed only with stop=true (terminal return)."
},
"stop": {
"type": "boolean"
@@ -8873,6 +8874,11 @@
"type": "string"
},
"description": "Global rules only: limit to these vhost ids (empty = all)."
},
"hash_stage": {
"type": "boolean",
"default": false,
"description": "Run this request-stage rule in vcl_hash, after vcl_recv. Imported VCL sets this automatically."
}
}
},
+145 -40
View File
@@ -18,11 +18,11 @@ window.rustProxyCacheRules = (() => {
response_header: { ops: ["exists", "equals", "contains", "regex"], name: true, stages: ["response", "deliver"] },
};
const ACTIONS = {
request: ["pass", "strip_cookies", "strip_query", "hash_header", "hash_cookie"],
response: ["ttl", "grace", "no_store", "ignore_cache_control", "strip_set_cookie"],
request: ["pass", "lookup", "strip_cookies", "strip_query", "hash_header", "hash_cookie", "set_request_header", "remove_request_header"],
response: ["ttl", "grace", "no_store", "allow_store", "ignore_cache_control", "strip_set_cookie", "set_backend_header", "remove_backend_header"],
deliver: ["set_header", "default_header", "remove_header"],
};
const ASPECTS = { pass: "pass", ttl: "ttl", grace: "grace", no_store: "store" };
const ASPECTS = { pass: "request_routing", lookup: "request_routing", strip_cookies: "request_cookies", strip_query: "request_query", ttl: "ttl", grace: "grace", no_store: "store", allow_store: "store" };
const tk = (prefix, value) => t(`${prefix}${String(value).split("_").map(part => part[0].toUpperCase() + part.slice(1)).join("")}`);
const fieldLabel = field => tk("cacheRuleField", field);
const opLabel = op => tk("cacheRuleOp", op);
@@ -40,10 +40,11 @@ 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, vhosts: [...(rule.vhosts || [])] };
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 || [])] };
}
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 };
if (rule.hash_stage) out.hash_stage = true;
if (global && rule.vhosts.length) out.vhosts = rule.vhosts;
return out;
}
@@ -81,15 +82,21 @@ window.rustProxyCacheRules = (() => {
return rule.actions.map(a => {
switch (a.type) {
case "pass": return "return (pass);";
case "lookup": return rule.hash_stage ? "return (lookup);" : "return (hash);";
case "strip_cookies": return a.keep?.length ? `# keep only cookies: ${a.keep.join(", ")}\nset req.http.Cookie = regsuball(req.http.Cookie, "(^|;\\s*)(?!(${a.keep.map(reEsc).join("|")})=)[^;=]+=[^;]*", "");` : "unset req.http.Cookie;";
case "strip_query": return a.keep_only ? `# keep only query parameters: ${(a.params || []).join(", ")}` : (a.params?.length ? `set req.url = regsuball(req.url, "([?&])(${a.params.map(p => globRe(p).replace(/\.\*/g, "[^=&]*")).join("|")})=[^&]*", "\\1");` : `set req.url = regsub(req.url, "\\?.*$", "");`);
case "hash_header": return `hash_data(req.http.${a.name});`;
case "hash_cookie": return `hash_data(regsub(req.http.Cookie, "^.*(?:^|;\\s*)${reEsc(a.name)}=([^;]*).*$", "\\1"));`;
case "set_request_header": return `set req.http.${a.name} = "${esc(a.value ?? "")}";`;
case "remove_request_header": return `unset req.http.${a.name};`;
case "ttl": return `set beresp.ttl = ${a.seconds ?? 0}s;`;
case "grace": return `set beresp.grace = ${a.seconds ?? 0}s;`;
case "no_store": return "set beresp.uncacheable = true;";
case "allow_store": return "set beresp.uncacheable = false;";
case "ignore_cache_control": return "unset beresp.http.Cache-Control;";
case "strip_set_cookie": return "unset beresp.http.Set-Cookie;";
case "set_backend_header": return `set beresp.http.${a.name} = "${esc(a.value ?? "")}";`;
case "remove_backend_header": return `unset beresp.http.${a.name};`;
case "set_header": return `set resp.http.${a.name} = "${esc(a.value ?? "")}";`;
case "remove_header": return `unset resp.http.${a.name};`;
case "default_header": return `if (!resp.http.${a.name}) { set resp.http.${a.name} = "${esc(a.value ?? "")}"; }`;
@@ -99,20 +106,39 @@ window.rustProxyCacheRules = (() => {
}
function ruleVcl(rule) {
const lines = vclActions(rule).flatMap(line => line.split("\n"));
// An imported return(deliver) may be represented by stop=true and no actions.
// Preserve terminal control flow even when preceded by header/TTL actions.
if (rule.stop && !lines.some(line => /^return\s*\(/.test(line)))
lines.push(`return (${rule.stage === "request" ? (rule.hash_stage ? "lookup" : "hash") : "deliver"});`);
const conditions = rule.conditions.map(c => vclCondition(c, rule.stage));
const joined = conditions.join(rule.match === "any" ? " ||\n " : " &&\n ");
const body = lines.map(line => ` ${line}`).join("\n");
const head = `# ${rule.name || rule.id}${rule.enabled === false ? " (disabled)" : ""}${rule.vhosts?.length ? ` · vhosts: ${rule.vhosts.join(", ")}` : ""}`;
return conditions.length ? `${head}\nif (${joined}) {\n${body}\n}` : `${head}\n${body.replace(/^ {4}/gm, "")}`;
const limits = [];
if (rule.enabled === false) limits.push("This rule is DISABLED in RustProxy; the preview is not executable equivalently.");
if (rule.vhosts?.length) limits.push("Vhost targeting is stored in RustProxy config, not represented by VCL.");
if (rule.conditions.some(c => ["client_ip", "extension", "query", "cookie"].includes(c.field)))
limits.push("One or more graphical conditions have no guaranteed VCL import round-trip.");
if (rule.actions.some(a => ["hash_cookie", "strip_query", "strip_cookies", "default_header", "ignore_cache_control"].includes(a.type)))
limits.push("One or more graphical actions are only approximated in this VCL display.");
const notes = limits.map(limit => `# PREVIEW LIMITATION: ${limit}`).join("\n");
const description = notes ? `${head}\n${notes}` : head;
return conditions.length ? `${description}\nif (${joined}) {\n${body}\n}` : `${description}\n${body.replace(/^ {4}/gm, "")}`;
}
function exportVcl(rules) {
const subs = { request: "vcl_recv", response: "vcl_backend_response", deliver: "vcl_deliver" };
const blocks = ["vcl 4.1;", "# Generated by RustProxy cache rules (read-only preview)"];
const blocks = [
"vcl 4.1;",
"# RustProxy DISPLAY PREVIEW, not a lossless VCL backup or a deployable Varnish config.",
"# Source of truth: saved graphical rules. Import supports only the documented subset.",
"# Some rules (client IP, cookie allowlists, hash_cookie, disabled rules and other actions)",
"# have no matching VCL importer syntax. Check Rules -> Cache & VCL guide."
];
const indent = text => text.replace(/^/gm, " ");
for (const stage of STAGES) {
const items = rules.filter(rule => rule.stage === stage);
const main = items.map(rule => ({ ...rule, actions: rule.actions.filter(a => !a.type.startsWith("hash_")) })).filter(rule => rule.actions.length);
const hash = items.map(rule => ({ ...rule, actions: rule.actions.filter(a => a.type.startsWith("hash_")) })).filter(rule => rule.actions.length);
const main = items.filter(rule => !rule.hash_stage).map(rule => ({ ...rule, actions: rule.actions.filter(a => !a.type.startsWith("hash_")) })).filter(rule => rule.actions.length || rule.stop);
const hash = items.map(rule => ({ ...rule, actions: rule.hash_stage ? rule.actions : rule.actions.filter(a => a.type.startsWith("hash_")) })).filter(rule => (rule.actions.length || (rule.stop && rule.hash_stage)) && stage === "request");
if (main.length) blocks.push(`\nsub ${subs[stage]} {\n${main.map(rule => indent(ruleVcl(rule))).join("\n\n")}\n}`);
if (hash.length) blocks.push(`\nsub vcl_hash {\n${hash.map(rule => indent(ruleVcl(rule))).join("\n\n")}\n}`);
}
@@ -122,8 +148,8 @@ window.rustProxyCacheRules = (() => {
const actions = rule.actions.map(a => {
if (a.type === "ttl" || a.type === "grace") return `${actionLabel(a.type)} ${fmtDuration(a.seconds)}`;
if (a.type === "strip_query") return `${actionLabel(a.type)}${a.params?.length ? `: ${a.params.join(", ")}` : ""}`;
if (a.type === "set_header" || a.type === "default_header") return `${actionLabel(a.type)}: ${a.name || "-"}${a.value ? ` = ${a.value}` : ""}`;
if (a.type === "remove_header" || a.type === "hash_header" || a.type === "hash_cookie") return `${actionLabel(a.type)}: ${a.name || "-"}`;
if (a.type === "set_header" || a.type === "default_header" || a.type === "set_backend_header" || a.type === "set_request_header") return `${actionLabel(a.type)}: ${a.name || "-"}${a.value ? ` = ${a.value}` : ""}`;
if (a.type === "remove_header" || a.type === "remove_backend_header" || a.type === "remove_request_header" || a.type === "hash_header" || a.type === "hash_cookie") return `${actionLabel(a.type)}: ${a.name || "-"}`;
return actionLabel(a.type);
});
return actions.join(" · ");
@@ -142,7 +168,8 @@ window.rustProxyCacheRules = (() => {
tracking: () => [{ name: t("cacheRuleTplTracking"), stage: "request", match: "all", conditions: [], actions: [{ type: "strip_query", params: ["utm_*", "fbclid", "gclid", "msclkid", "mc_cid", "mc_eid", "_ga"] }] }],
api: () => [{ name: t("cacheRuleTplApi"), stage: "request", match: "all", conditions: [{ field: "path", operator: "prefix", values: ["/api/"] }], actions: [{ type: "pass" }] }],
language: () => [{ name: t("cacheRuleTplLanguage"), stage: "request", match: "all", conditions: [], actions: [{ type: "hash_cookie", name: "lang" }] }],
notfound: () => [{ name: t("cacheRuleTplNotFound"), stage: "response", match: "all", conditions: [{ field: "status", operator: "equals", values: ["404"] }], actions: [{ type: "ttl", seconds: 60 }] }],
// No negative-cache template: the storage layer currently stores 200 only.
// A TTL rule matching 404 would appear enabled but could never yield HIT.
headers: () => [{ name: t("cacheRuleTplHeaders"), stage: "deliver", match: "all", conditions: [], actions: [{ type: "remove_header", name: "X-Powered-By" }] }],
browser: () => [{ name: t("cacheRuleTplBrowser"), stage: "deliver", match: "all", conditions: [{ field: "extension", operator: "equals", values: ["css", "js", "mjs", "png", "jpg", "jpeg", "gif", "webp", "avif", "svg", "ico", "woff", "woff2"] }, { field: "status", operator: "equals", values: ["200"] }], actions: [{ type: "set_header", name: "Cache-Control", value: "public, max-age=2592000" }] }],
nobrowser: () => [{ name: t("cacheRuleTplNoBrowser"), stage: "deliver", match: "any", conditions: [{ field: "content_type", operator: "prefix", values: ["text/html"] }, { field: "path", operator: "prefix", values: ["/admin", "/account"] }], actions: [{ type: "set_header", name: "Cache-Control", value: "no-store" }] }],
@@ -160,7 +187,7 @@ window.rustProxyCacheRules = (() => {
for (const global of globals) {
if (global.stage !== local.stage) continue;
const shared = [...aspects(normalize(global))].filter(aspect => mine.has(aspect));
if (shared.length) notes.push(t("cacheRulesOverrideNotice").replace("{vhost}", local.name || local.id).replace("{global}", global.name || global.id).replace("{aspects}", shared.map(aspect => t(`cacheRuleAspect${aspect[0].toUpperCase()}${aspect.slice(1)}`)).join(", ")));
if (shared.length) notes.push(t("cacheRulesOverrideNotice").replace("{vhost}", local.name || local.id).replace("{global}", global.name || global.id).replace("{aspects}", shared.map(aspect => ({ request_cookies: actionLabel("strip_cookies"), request_query: actionLabel("strip_query") })[aspect] || t(`cacheRuleAspect${aspect[0].toUpperCase()}${aspect.slice(1)}`)).join(", ")));
}
}
return notes;
@@ -221,7 +248,20 @@ window.rustProxyCacheRules = (() => {
const root = el("div", undefined, `cache-rules cache-rules-${scope}`);
const changed = () => { root.dispatchEvent(new Event("input", { bubbles: true })); options.onChange?.(); };
const toolbar = el("div", undefined, "cache-rules-toolbar");
if (scope === "vhost") { const docs = el("a", t("cacheRulesDocs"), "docs-link"); docs.href = "/docs#doc=docs%2FCACHE.md&section=cache-rules-vcl-style"; docs.target = "_blank"; docs.rel = "noopener noreferrer"; root.append(docs); }
if (scope === "vhost") {
// Both ordinary vhost and Docker assignment editors use this component.
// The shared guide opener is delegated in settings.js, so dynamic editors
// receive the same modal without binding additional event handlers.
const helpLinks = el("div", undefined, "cache-rules-vhost-links");
const docs = el("a", t("cacheRulesDocs"), "docs-link");
docs.href = "/docs#doc=docs%2FCACHE.md&section=cache-rules-vcl-style";
docs.target = "_blank";
docs.rel = "noopener noreferrer";
const guide = el("button", t("cacheGuideOpen"), "outline cache-guide-trigger");
guide.type = "button";
helpLinks.append(guide, docs);
root.append(helpLinks);
}
const templates = select([["", t("cacheRulesTemplates")], ...Object.keys(TEMPLATES).map(key => [key, t(`cacheRuleTpl${key[0].toUpperCase()}${key.slice(1)}`)])], "", t("cacheRulesTemplates"));
templates.classList.add("cache-rules-templates");
const importButton = el("button", t("cacheRulesImportVcl"), "outline"); importButton.type = "button";
@@ -236,9 +276,21 @@ window.rustProxyCacheRules = (() => {
const importBox = el("div", undefined, "cache-rules-import"); importBox.hidden = true;
const importText = document.createElement("textarea"); importText.rows = 10; importText.spellcheck = false; importText.placeholder = "sub vcl_recv {\n if (req.url ~ \"^/admin\") {\n return (pass);\n }\n}";
const importRun = el("button", t("cacheRulesImportRun"), "primary"); importRun.type = "button";
const importApply = el("button", t("cacheRulesImportApplyPartial"), "outline"); importApply.type = "button"; importApply.hidden = true;
const importCancel = el("button", t("cancel"), "outline"); importCancel.type = "button";
const importResult = el("div", undefined, "cache-rules-import-result");
const importActions = el("div", undefined, "form-actions"); importActions.append(importRun, importCancel);
const importActions = el("div", undefined, "form-actions"); importActions.append(importRun, importApply, importCancel);
let pendingImport = null, importGeneration = 0;
// Any edit/close/submit supersedes older in-flight API responses. An old
// parse result must never mutate the editor after the user cancelled it.
const resetImportPreview = () => {
importGeneration++;
pendingImport = null;
importApply.hidden = true;
importResult.replaceChildren();
importRun.disabled = false;
};
importText.addEventListener("input", resetImportPreview);
importBox.append(el("p", t("cacheRulesImportHelp"), "fine"), importText, importActions, importResult);
const exportBox = el("details", undefined, "cache-rules-export"); const exportSummary = el("summary", t("cacheRulesVclPreview")); const exportPre = el("pre", "", "metrics-example mono cache-rules-vcl");
exportBox.append(exportSummary, exportPre);
@@ -312,7 +364,7 @@ window.rustProxyCacheRules = (() => {
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; rule.actions = rule.actions.filter(a => ACTIONS[rule.stage].includes(a.type)); if (!rule.actions.length) rule.actions = [{ type: ACTIONS[rule.stage][0] }]; rule.conditions = rule.conditions.filter(c => FIELDS[c.field].stages.includes(rule.stage)); render(); changed(); });
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(); });
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(); });
@@ -378,7 +430,7 @@ window.rustProxyCacheRules = (() => {
const row = el("div", undefined, "cache-rule-row");
const type = select(ACTIONS[rule.stage].map(value => [value, actionLabel(value)]), action.type, t("cacheRuleAction"));
const params = el("span", undefined, "cache-rule-params");
const remove = el("button", "×", "quiet"); remove.type = "button"; remove.setAttribute("aria-label", t("remove")); remove.disabled = rule.actions.length <= 1;
const remove = el("button", "×", "quiet"); remove.type = "button"; remove.setAttribute("aria-label", t("remove")); remove.disabled = rule.actions.length <= 1 && !rule.stop;
type.addEventListener("change", () => { rule.actions[index] = { type: type.value }; render(); changed(); });
remove.addEventListener("click", () => { rule.actions.splice(index, 1); render(); changed(); });
const listInput = (key, placeholder) => { const node = textInput((action[key] || []).join(", "), placeholder); node.addEventListener("input", () => { action[key] = splitList(node.value); changed(); }); return node; };
@@ -393,6 +445,8 @@ window.rustProxyCacheRules = (() => {
case "hash_header": params.append(nameInput("Accept-Language")); break;
case "hash_cookie": params.append(nameInput("lang")); break;
case "ttl": case "grace": params.append(durationInput(action.seconds ?? (action.type === "ttl" ? 3600 : 60), seconds => { action.seconds = seconds; changed(); })); if (action.seconds == null) action.seconds = action.type === "ttl" ? 3600 : 60; break;
case "set_backend_header": case "set_request_header": { const value = textInput(action.value, t("cacheRuleHeaderValue")); value.addEventListener("input", () => { action.value = value.value; changed(); }); params.append(nameInput(action.type === "set_request_header" ? "X-Device" : "Cache-Control"), value); break; }
case "remove_backend_header": case "remove_request_header": params.append(nameInput(action.type === "remove_request_header" ? "X-Tracking" : "Cache-Control")); break;
case "set_header": { const value = textInput(action.value, t("cacheRuleHeaderValue")); value.addEventListener("input", () => { action.value = value.value; changed(); }); params.append(nameInput("X-Cache-Rule"), value); break; }
case "default_header": { const value = textInput(action.value, t("cacheRuleHeaderValue")); value.addEventListener("input", () => { action.value = value.value; changed(); }); params.append(nameInput("Cache-Control"), value); break; }
case "remove_header": params.append(nameInput("X-Powered-By")); break;
@@ -404,33 +458,53 @@ window.rustProxyCacheRules = (() => {
function buildTester() {
const node = el("details", undefined, "cache-rules-tester");
node.append(el("summary", t("cacheRulesTester")));
const grid = el("div", undefined, "cache-rules-tester-grid");
const bodyWrap = el("div", undefined, "cache-rules-tester-body");
const sections = el("div", undefined, "cache-rules-tester-sections");
const requestPane = el("section", undefined, "cache-rules-tester-pane");
requestPane.append(el("h4", t("cacheRulesTesterRequestTitle"), "cache-rules-tester-heading"));
const requestGrid = el("div", undefined, "cache-rules-tester-grid cache-rules-tester-request-grid");
const method = select(["GET", "HEAD", "POST"].map(value => [value, value]), "GET", t("cacheRuleFieldMethod"));
const url = textInput("", scope === "vhost" ? "/produkt?id=7&utm_source=fb" : "https://shop.example.com/produkt?id=7&utm_source=fb", "mono");
const vhostSelect = select([["", t("cacheRulesTesterNoVhost")], ...targetList().map(target => [target.id, targetTitle(target)])], vhostId, t("cacheRulesTesterVhost"));
if (scope === "global") document.addEventListener("rustproxy-cache-targets", () => {
if (!root.isConnected) return;
const current = vhostSelect.value;
vhostSelect.replaceChildren(...[["", t("cacheRulesTesterNoVhost")], ...targetList().map(target => [target.id, targetTitle(target)])].map(([value, text]) => { const option = el("option", text); option.value = value; return option; }));
vhostSelect.value = [...vhostSelect.options].some(option => option.value === current) ? current : "";
});
const headers = document.createElement("textarea"); headers.rows = 3; headers.placeholder = "Cookie: lang=pl; sid=1\nAccept-Language: pl"; headers.spellcheck = false;
const headers = document.createElement("textarea"); headers.rows = 2; headers.placeholder = "Cookie: lang=pl; sid=1\nAccept-Language: pl"; headers.spellcheck = false;
const clientIp = textInput("", "203.0.113.10", "mono");
const status = el("input"); status.type = "number"; status.min = 100; status.max = 599; status.value = 200;
const responseHeaders = document.createElement("textarea"); responseHeaders.rows = 3; responseHeaders.placeholder = "Cache-Control: public, max-age=60\nContent-Type: text/html"; responseHeaders.spellcheck = false;
const responseHeaders = document.createElement("textarea"); responseHeaders.rows = 2; responseHeaders.placeholder = "Cache-Control: public, max-age=60\nContent-Type: text/html"; responseHeaders.spellcheck = false;
const run = el("button", t("cacheRulesTesterRun"), "primary"); run.type = "button";
const result = el("div", undefined, "cache-rules-tester-result");
const field = (key, control) => { const label = el("label", undefined, "cache-rule-field"); label.append(el("span", t(key)), control); return label; };
grid.append(field("cacheRuleFieldMethod", method), field("cacheRulesTesterUrl", url));
if (scope === "global") grid.append(field("cacheRulesTesterVhost", vhostSelect));
grid.append(field("cacheRulesTesterHeaders", headers), field("cacheRuleFieldClientIp", clientIp), field("cacheRuleFieldStatus", status), field("cacheRulesTesterResponseHeaders", responseHeaders));
const result = el("div", undefined, "cache-rules-tester-result"); result.setAttribute("aria-live", "polite");
const field = (key, control, cls) => { const label = el("label", undefined, `cache-rule-field ${cls}`); label.append(el("span", t(key)), control); return label; };
requestGrid.append(field("cacheRuleFieldMethod", method, "is-method"), field("cacheRulesTesterUrl", url, "is-url"));
if (scope === "global") requestGrid.append(field("cacheRulesTesterVhost", vhostSelect, "is-vhost"));
requestGrid.append(field("cacheRuleFieldClientIp", clientIp, "is-ip"), field("cacheRulesTesterHeaders", headers, "is-headers"));
requestPane.append(requestGrid);
const responsePane = el("section", undefined, "cache-rules-tester-pane");
responsePane.append(el("h4", t("cacheRulesTesterResponseTitle"), "cache-rules-tester-heading"));
const responseGrid = el("div", undefined, "cache-rules-tester-grid cache-rules-tester-response-grid");
responseGrid.append(field("cacheRuleFieldStatus", status, "is-status"), field("cacheRulesTesterResponseHeaders", responseHeaders, "is-response-headers"));
responsePane.append(responseGrid);
sections.append(requestPane, responsePane);
const pairs = text => String(text || "").split(/\r?\n/).map(line => line.trim()).filter(Boolean).map(line => { const at = line.indexOf(":"); return at > 0 ? [line.slice(0, at).trim(), line.slice(at + 1).trim()] : [line, ""]; });
run.addEventListener("click", async () => {
run.disabled = true; result.replaceChildren(el("p", t("cacheRulesTesterRunning"), "fine"));
try {
const body = { request: { method: method.value, url: url.value.trim(), headers: pairs(headers.value), client_ip: clientIp.value.trim() || null }, response: { status: Number(status.value) || 200, headers: pairs(responseHeaders.value) } };
if (scope === "global") { body.global_rules = read(); body.vhost_id = vhostSelect.value || null; }
else { body.vhost_id = vhostId || null; body.vhost_rules = read(); body.ignore_global_rules = ignoreGlobal; if (!vhostId) body.vhost_id = null; }
renderResult(await api("/api/cache/rules/test", { method: "POST", body: JSON.stringify(body) }));
const requestHeaders = pairs(headers.value);
// A draft/new vhost has no stored frontend.hosts entry yet. With a
// path-only test use its current editor hostname, not an empty Host,
// so global host conditions are evaluated consistently.
if (scope === "vhost" && url.value.trim().startsWith("/") && !requestHeaders.some(([name]) => name.toLowerCase() === "host")) {
const host = String(typeof options.testHost === "function" ? options.testHost() || "" : "").trim();
if (host && !host.startsWith("*.")) requestHeaders.push(["Host", host]);
}
const payload = { request: { method: method.value, url: url.value.trim(), headers: requestHeaders, client_ip: clientIp.value.trim() || null }, response: { status: Number(status.value) || 200, headers: pairs(responseHeaders.value) } };
if (scope === "global") { payload.global_rules = read(); payload.vhost_id = vhostSelect.value || null; }
else { payload.vhost_id = vhostId || null; payload.vhost_rules = read(); payload.ignore_global_rules = ignoreGlobal; }
renderResult(await api("/api/cache/rules/test", { method: "POST", body: JSON.stringify(payload) }));
} catch (error) { result.replaceChildren(el("p", error.message, "fine is-error")); }
finally { run.disabled = false; }
});
@@ -441,6 +515,7 @@ window.rustProxyCacheRules = (() => {
const request = data.request || {};
line(t("cacheRulesResultDecision"), request.cacheable ? (data.response?.stored ? t("cacheRulesResultHit").replace("{ttl}", fmtDuration(data.response.ttl)).replace("{grace}", fmtDuration(data.response.grace)) : t("cacheRulesResultNotStored").replace("{reason}", data.response?.reason || "-")) : t("cacheRulesResultPass").replace("{reason}", request.reason || "-"), request.cacheable && data.response?.stored ? "is-ok" : "is-warn");
line(t("cacheRulesResultRequest"), names(request.matched));
if (request.header_edits?.length) line(t("cacheRulesResultRequestHeaders"), request.header_edits.map(edit => edit.type === "set" ? `${edit.name}: ${edit.value}` : `−${edit.name}`).join(", "));
line(t("cacheRulesResultKey"), `${data.host || "-"}${request.target || ""}${request.variant?.length ? ` + ${request.variant.join(", ")}` : ""}`);
if (request.cookie != null) line(t("cacheRulesResultCookie"), request.cookie || "—");
if (data.response) line(t("cacheRulesResultResponse"), names(data.response.matched));
@@ -448,8 +523,10 @@ window.rustProxyCacheRules = (() => {
for (const item of [...(request.overridden || []), ...(data.response?.overridden || [])]) line(t("cacheRulesResultOverridden"), t("cacheRulesResultOverriddenText").replace("{winner}", item.winner).replace("{ignored}", item.ignored).replace("{aspect}", t(`cacheRuleAspect${item.aspect[0].toUpperCase()}${item.aspect.slice(1)}`)), "is-warn");
result.replaceChildren(...items);
}
const actions = el("div", undefined, "form-actions"); actions.append(run);
node.append(el("p", t("cacheRulesTesterHelp"), "fine"), grid, actions, result);
const footer = el("div", undefined, "cache-rules-tester-footer");
footer.append(el("p", t(scope === "global" ? "cacheRulesTesterHelpGlobal" : "cacheRulesTesterHelpVhost"), "fine"), run);
bodyWrap.append(sections, footer, result);
node.append(bodyWrap);
return { node };
}
function addRules(items) {
@@ -464,28 +541,56 @@ window.rustProxyCacheRules = (() => {
}
templates.addEventListener("change", () => { const make = TEMPLATES[templates.value]; templates.value = ""; if (!make) return; const added = addRules(make()); if (added) toast(t("cacheRulesTemplateAdded").replace("{count}", added)); });
addButton.addEventListener("click", () => { const rule = blankRule(taken()); rules.push(rule); open.add(rule.id); render(); changed(); list.lastElementChild?.scrollIntoView?.({ block: "nearest", behavior: "smooth" }); });
importButton.addEventListener("click", () => { importBox.hidden = !importBox.hidden; if (!importBox.hidden) importText.focus(); });
importCancel.addEventListener("click", () => { importBox.hidden = true; importResult.replaceChildren(); });
importButton.addEventListener("click", () => { importBox.hidden = !importBox.hidden; if (importBox.hidden) resetImportPreview(); else importText.focus(); });
importCancel.addEventListener("click", () => { importBox.hidden = true; resetImportPreview(); });
importRun.addEventListener("click", async () => {
importRun.disabled = true; importResult.replaceChildren();
resetImportPreview();
const generation = importGeneration;
importRun.disabled = true;
const source = importText.value;
try {
const data = await api("/api/cache/rules/import-vcl", { method: "POST", body: JSON.stringify({ vcl: importText.value }) });
const data = await api("/api/cache/rules/import-vcl", { method: "POST", body: JSON.stringify({ vcl: source }) });
// The user must opt into a partial/approximated import after seeing
// warnings. Previously incomplete VCL was added before any warning was shown.
if (generation !== importGeneration || importText.value !== source || importBox.hidden) return;
if (data.warnings?.length) {
const list = el("ul", undefined, "cache-rules-warnings");
for (const warning of data.warnings) list.append(el("li", warning));
importResult.append(el("p", t("cacheRulesImportWarnings"), "fine is-warn"), list);
if (data.rules?.length) {
pendingImport = data.rules;
importApply.hidden = false;
importResult.append(el("p", t("cacheRulesImportPending").replace("{count}", data.rules.length), "fine"));
} else {
importResult.append(el("p", t("cacheRulesImportNoActions"), "fine"));
}
return;
}
const added = addRules(data.rules || []);
importResult.append(el("p", t("cacheRulesImportDone").replace("{count}", added), "fine is-ok"));
if (data.warnings?.length) { const list = el("ul", undefined, "cache-rules-warnings"); for (const warning of data.warnings) list.append(el("li", warning)); importResult.append(el("p", t("cacheRulesImportWarnings"), "fine"), list); }
} catch (error) { importResult.append(el("p", error.message, "fine is-error")); }
finally { importRun.disabled = false; }
importResult.append(el("p", added ? t("cacheRulesImportDone").replace("{count}", added) : t("cacheRulesImportNoActions"), "fine is-ok"));
} catch (error) {
if (generation === importGeneration && !importBox.hidden)
importResult.append(el("p", error.message, "fine is-error"));
} finally {
if (generation === importGeneration) importRun.disabled = false;
}
});
importApply.addEventListener("click", () => {
if (!pendingImport) return;
const added = addRules(pendingImport);
resetImportPreview();
importResult.append(el("p", t("cacheRulesImportDone").replace("{count}", added), "fine is-ok"));
});
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() {
for (const rule of rules) {
if (!rule.actions.length) throw new Error(t("cacheRuleNeedsAction").replace("{rule}", rule.name || rule.id));
if (!rule.actions.length && !rule.stop) 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));
}
for (const a of rule.actions) if (["hash_header", "hash_cookie", "set_header", "default_header", "remove_header"].includes(a.type) && !a.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id));
for (const a of rule.actions) if (["hash_header", "hash_cookie", "set_request_header", "remove_request_header", "set_backend_header", "remove_backend_header", "set_header", "default_header", "remove_header"].includes(a.type) && !a.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id));
}
return rules.map(rule => clean(rule, scope === "global"));
}
+3 -3
View File
@@ -102,18 +102,18 @@
rows as a subgrid, so a caption that wraps to more lines makes the whole
caption row taller and every control in the row still starts on the same
line. Multi-line text areas take the whole row instead of a narrow column. */
:is(.vh-grid>.vh-field, .cache-rules-tester-grid>.cache-rule-field, .field-grid>label:not([class])) {
:is(.vh-grid>.vh-field, .field-grid>label:not([class])) {
grid-row: span 2;
}
:is(.vh-grid>.vh-field, .cache-rules-tester-grid>.cache-rule-field, .field-grid>label:not([class])):has(>:nth-child(2):last-child) {
:is(.vh-grid>.vh-field, .field-grid>label:not([class])):has(>:nth-child(2):last-child) {
display: grid;
grid-template-rows: subgrid;
row-gap: 4px;
align-content: start;
}
:is(.vh-grid>.vh-field, .cache-rules-tester-grid>.cache-rule-field, .field-grid>label:not([class])):has(>:nth-child(2):last-child)>:first-child {
:is(.vh-grid>.vh-field, .field-grid>label:not([class])):has(>:nth-child(2):last-child)>:first-child {
align-self: end;
}
+225 -8
View File
@@ -2700,35 +2700,184 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
font-size: 13px;
}
/* Shared compact rule tester (global Cache, Vhosts and Docker vhosts).
Keep controls aligned without the vhost editor's two-row subgrid. */
.cache-rules-vhost-links {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px 14px;
}
.cache-rules-vhost-links>.cache-guide-trigger {
width: auto;
min-height: 30px;
padding: 5px 10px;
font-size: 12px;
}
.cache-rules-tester {
padding: 10px 12px;
width: 100%;
max-width: 1120px;
min-width: 0;
padding: 0;
border: 1px solid var(--line);
border-radius: var(--rp-radius-surface, 0px);
container-type: inline-size;
}
.cache-rules-tester>summary {
padding: 9px 12px;
font-weight: 600;
}
.cache-rules-tester[open]>summary {
border-bottom: 1px solid var(--line);
}
.cache-rules-tester-body {
display: grid;
gap: 10px;
padding: 11px 12px 12px;
}
.cache-rules-tester-sections {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 390px), 1fr));
gap: 10px;
align-items: stretch;
}
.cache-rules-tester-pane {
min-width: 0;
padding: 10px;
border: 1px solid var(--line);
border-radius: var(--rp-radius-surface, 0px);
background: var(--panel2);
}
.cache-rules-tester-heading {
margin: 0 0 8px;
font-size: 11px;
letter-spacing: .05em;
text-transform: uppercase;
color: var(--muted);
}
.cache-rules-tester-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 10px 14px;
margin-top: 8px;
grid-template-columns: minmax(100px, .65fr) repeat(2, minmax(0, 1fr));
gap: 8px 10px;
margin: 0;
align-items: start;
}
.cache-rules-tester-grid>.cache-rule-field {
display: flex;
flex-direction: column;
gap: 4px;
grid-row: auto;
min-width: 0;
margin: 0;
}
.cache-rules-tester-grid>.cache-rule-field>span {
display: block;
color: var(--muted);
font-size: 11px;
line-height: 1.25;
}
.cache-rules-tester-grid :is(input, select, textarea) {
display: block;
width: 100%;
min-width: 0;
max-width: 100%;
margin: 0;
padding: 6px 8px;
box-sizing: border-box;
font-size: 12px;
}
.cache-rules-tester-grid :is(input, select) {
height: 34px;
min-height: 34px;
}
.cache-rules-tester-grid textarea {
min-height: 52px;
font-family: var(--mono);
font-size: 12px;
line-height: 1.35;
resize: vertical;
}
.cache-rules-tester-request-grid>.is-url,
.cache-rules-tester-request-grid>.is-vhost {
grid-column: span 2;
}
.cache-rules-tester-request-grid>.is-headers {
grid-column: 1 / -1;
}
.cache-rules-tester-response-grid {
grid-template-columns: 110px minmax(0, 1fr);
}
.cache-rules-tester-footer {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 8px 12px;
}
.cache-rules-tester-footer>.fine {
flex: 1 1 370px;
min-width: 0;
margin: 0;
font-size: 11px;
line-height: 1.4;
}
.cache-rules-tester-footer>button {
flex: 0 0 auto;
width: auto;
min-height: 32px;
padding: 6px 13px;
}
.cache-rules-tester-result {
display: grid;
gap: 4px;
margin-top: 8px;
min-width: 0;
}
.cache-rules-tester-result:empty { display: none; }
.cache-rules-result-line {
display: grid;
grid-template-columns: minmax(140px, 200px) minmax(0, 1fr);
gap: 10px;
grid-template-columns: minmax(120px, 190px) minmax(0, 1fr);
gap: 8px 10px;
padding: 6px 9px;
border: 1px solid var(--line);
overflow-wrap: anywhere;
font-size: 12px;
}
.cache-rules-result-line>strong { min-width: 0; }
@container (max-width: 550px) {
.cache-rules-tester-body { padding: 9px; }
.cache-rules-tester-pane { padding: 9px; }
.cache-rules-tester-request-grid { grid-template-columns: minmax(105px, 1fr) minmax(0, 1fr); }
.cache-rules-tester-request-grid>.is-url,
.cache-rules-tester-request-grid>.is-vhost { grid-column: 1 / -1; }
.cache-rules-tester-request-grid>.is-ip { grid-column: span 1; }
.cache-rules-tester-response-grid { grid-template-columns: minmax(0, 1fr); }
.cache-rules-tester-response-grid>.is-status { max-width: 170px; }
.cache-rules-tester-response-grid>.is-response-headers { grid-column: 1 / -1; }
.cache-rules-result-line { grid-template-columns: minmax(0, 1fr); gap: 3px; }
}
.cache-rules-result-line.is-ok>strong {
@@ -3404,3 +3553,71 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
grid-template-columns: 1fr;
}
}
/* Contextual cache / VCL help in Settings -> Cache. */
.cache-guide-heading-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-left: auto;
}
#cache-form .cache-guide-trigger { width: auto; }
#cache-form [data-cache-settings-page=rules]>.cache-guide-trigger { margin-left: 10px; }
.cache-vcl-guide-dialog {
width: calc(min(980px, 100vw - 24px) / var(--ui-scale, 1));
max-height: calc((100dvh - 28px) / var(--ui-scale, 1));
overflow: hidden;
}
.cache-guide-dialog-heading { justify-content: space-between; }
.cache-guide-dialog-heading h2 { margin: 3px 0 0; }
.cache-guide-content {
overflow-y: auto;
max-height: calc((100dvh - 110px) / var(--ui-scale, 1));
padding: 14px;
}
.cache-guide-content>.fine { margin: 0 0 12px; }
.cache-guide-current {
border: 1px solid var(--line);
background: var(--panel2);
padding: 12px;
margin-bottom: 12px;
}
.cache-guide-current-pills { display: flex; flex-wrap: wrap; gap: 7px; margin-bottom: 8px; }
.cache-guide-current p { margin: 5px 0 0; }
.cache-guide-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
align-items: stretch;
gap: 10px;
}
.cache-guide-card {
min-width: 0;
border: 1px solid var(--line);
background: var(--panel);
padding: 13px;
}
.cache-guide-card h3 { margin: 0 0 8px; font-size: 14px; }
.cache-guide-card p { font-size: 12px; line-height: 1.55; margin: 0; }
.cache-guide-card p+p { margin-top: 9px; }
.cache-guide-card pre {
margin: 9px 0;
padding: 10px;
max-width: 100%;
overflow: auto;
color: var(--text);
background: var(--panel2);
border: 1px solid var(--line);
font-size: 11px;
line-height: 1.5;
tab-size: 2;
}
.cache-guide-card pre code { white-space: pre; }
.cache-guide-import-example { margin-top: 4px; width: auto; }
.cache-guide-footer { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; margin-top: 13px; }
.cache-guide-footer>.fine { flex: 1 1 100%; margin: 0; }
@media (max-width: 720px) {
.cache-guide-grid { grid-template-columns: minmax(0, 1fr); }
.cache-guide-content { padding: 10px; }
.cache-guide-card { padding: 11px; }
}
+3 -3
View File
@@ -758,13 +758,13 @@
if (!picked.length) return { acl_profile_ids: [], inherit_acl_profiles: !inherited.length };
return { acl_profile_ids: picked, inherit_acl_profiles: true };
}
function cacheEditor(assignment, agent, key, enabled) {
function cacheEditor(assignment, agent, key, enabled, testHost) {
const details = el("details", undefined, "docker-cache-editor"), summary = el("summary"); summary.append(el("span", t("dockerCacheSettings")), el("small", t("dockerCacheSettingsHelp"), "fine")); details.append(summary);
const grid = el("div", undefined, "field-grid docker-cache-grid");
const ttl = input(assignment?.cache_default_ttl_seconds ?? "", "number", "docker-cache-ttl"); ttl.min = 0; ttl.max = 31536000; ttl.placeholder = String(envelope?.config?.cache?.default_ttl_seconds ?? "");
grid.append(labeled("dockerCacheTtl", ttl, t("dockerCacheTtlHelp")));
const vhostId = poolRoutes.find(item => item.agent_id === agent.id && item.service_key === key)?.pool_id || "";
const rules = window.rustProxyCacheRules?.create?.({ scope: "vhost", vhostId, rules: assignment?.cache_rules || [], ignoreGlobal: assignment?.cache_ignore_global_rules === true, ignoreId: "", autoLoadHits: false });
const rules = window.rustProxyCacheRules?.create?.({ scope: "vhost", vhostId, rules: assignment?.cache_rules || [], ignoreGlobal: assignment?.cache_ignore_global_rules === true, ignoreId: "", autoLoadHits: false, testHost });
if (rules?.node) { rules.node.classList.add("docker-cache-rules"); details._rules = rules; }
details.append(grid); if (rules?.node) details.append(rules.node);
details.addEventListener("toggle", () => { if (details.open && !details.hidden) void rules?.refreshHits?.(); });
@@ -1063,7 +1063,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), 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), 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); }
+138 -14
View File
@@ -2739,8 +2739,12 @@
hidden="" id="settings-page-cache" role="tabpanel">
<form class="card edit-form" id="cache-form">
<div class="card-heading">
<h2 data-i18n="cacheSettings">Cache</h2><span class="pill live"
data-i18n="hotApply">LIVE APPLY</span>
<h2 data-i18n="cacheSettings">Cache</h2>
<div class="cache-guide-heading-actions">
<button class="outline cache-guide-trigger" type="button"
data-i18n="cacheGuideOpen">Cache &amp; VCL guide</button>
<span class="pill live" data-i18n="hotApply">LIVE APPLY</span>
</div>
</div>
<nav aria-label="Cache settings" class="settings-tabs sub-tabs" id="cache-settings-tabs"
role="tablist">
@@ -2761,6 +2765,8 @@
href="/docs#doc=docs%2FCACHE.md&amp;section=cache-rules-vcl-style"
target="_blank" rel="noopener noreferrer" data-i18n="cacheRulesDocs">Cache rules
documentation</a>
<button class="outline cache-guide-trigger" type="button"
data-i18n="cacheGuideOpen">Cache &amp; VCL guide</button>
<div id="cache-rules-root"></div>
</div>
<div data-cache-settings-page="general">
@@ -2768,10 +2774,10 @@
</h3>
<label class="check"><input class="switch" id="cache-enabled" type="checkbox" /><span
data-i18n="enableCache">Enable shared cache</span></label>
<p class="fine" data-i18n="cacheSafety">Only complete public-safe GET responses.
Authorization, cookies and private/no-store responses still bypass the cache.
One byte range can be served from a complete cached object;
multipart/unsupported ranges pass through.</p>
<p class="fine" data-i18n="cacheSafety">Only eligible GET/HEAD responses.
Authorization and private/no-store responses bypass storage. Cookies normally
bypass unless an eligible compatible VCL rule explicitly opts in. A single range
may use a complete cached object; unsupported ranges bypass.</p>
<div class="cache-varnish-setting">
<label class="check"><input class="switch" id="cache-varnish-compatible"
type="checkbox" /><span
@@ -2790,12 +2796,15 @@
during grace); existing cookie rules, Authorization, Vary,
PURGE/BAN, HOT/COLD and transformations stay active.</p>
<p class="fine" data-i18n="cacheVarnishCompatibleBackendHelp">Origin
no-cache with a validator remains revalidatable. If an explicit
fallback TTL is set, public no-cache responses may instead be reused
for that TTL, even without a validator. Private/no-store/Set-Cookie
and Surrogate-Control: no-store remain blocked. Zero-TTL objects may
be retained for stale-if-error or revalidation; explicit
stale-while-revalidate=0 is respected.</p>
no-cache with ETag/Last-Modified remains revalidatable. With a
positive fallback TTL, compatible mode can cache eligible no-cache
responses even without public or a validator. Private, no-store,
Set-Cookie and Surrogate-Control: no-store remain blocked.
This is a configured override, not vanilla Varnish behavior.</p>
<p class="fine" data-i18n="cacheVarnishCompatibleVclHelp">Use
return(pass) for session cookies before return(hash) for selected
public routes. In Rules, the Cache &amp; VCL guide explains Vary,
header edits and importer limits. Per-vhost overrides take precedence.</p>
<p class="fine" data-i18n="cacheVarnishCompatibleModeHelp">Implicit
grace (60 seconds by default, configurable below) only applies to
eligible fresh-at-storage responses without an explicit
@@ -2811,8 +2820,7 @@
<input id="cache-varnish-grace" type="number" min="0" max="604800" step="1"
required />
</div>
<label data-i18n="cacheDefaultTtl" for="cache-default-ttl">Fallback TTL for public
responses (0 = off)</label><input id="cache-default-ttl" max="604800" min="0"
<label data-i18n="cacheDefaultTtl" for="cache-default-ttl">Fallback TTL (seconds): public, or headerless/no-cache in compatibility mode (0 = off)</label><input id="cache-default-ttl" max="604800" min="0"
required="" type="number" />
<label class="check"><input class="switch" id="cache-query" type="checkbox" /><span
data-i18n="bypassQuery">Bypass URLs with a query string</span></label>
@@ -4126,6 +4134,122 @@
</div>
</main>
</div>
<dialog aria-labelledby="cache-vcl-guide-title" aria-modal="true"
class="vhost-dialog cache-vcl-guide-dialog" id="cache-vcl-guide-dialog">
<div class="window-heading cache-guide-dialog-heading">
<div>
<span class="small-label" data-i18n="cacheGuideEyebrow">CACHE SETTINGS · VCL SUBSET</span>
<h2 data-i18n="cacheGuideTitle" id="cache-vcl-guide-title">Practical cache &amp; VCL guide</h2>
</div>
<button class="outline" data-i18n="close" id="cache-vcl-guide-close" type="button">Close</button>
</div>
<div class="cache-guide-content">
<p class="fine" data-i18n="cacheGuideIntro">Practical notes for RustProxy, not a promise of complete Varnish VCL compatibility. Only imported and accepted rules are executed.</p>
<div class="cache-guide-current" role="status" aria-live="polite">
<div class="cache-guide-current-pills">
<span class="pill" id="cache-guide-mode"></span>
<span class="pill" id="cache-guide-ttl"></span>
<span class="pill" id="cache-guide-grace"></span>
<span class="pill" id="cache-guide-context"></span>
</div>
<p class="fine" id="cache-guide-current-note"></p>
<p class="fine" id="cache-guide-scope-note"></p>
<p class="fine" data-i18n="cacheGuideUnsaved">Values reflect the current form, which may contain unsaved changes.</p>
</div>
<div class="cache-guide-grid">
<section class="cache-guide-card">
<h3 data-i18n="cacheGuideFreshnessTitle">no-cache, TTL and grace</h3>
<p data-i18n="cacheGuideFreshnessText">With Varnish compatibility and a positive fallback TTL, an eligible Cache-Control: no-cache response can be served as HIT for that TTL without public. With compatibility off, no-cache requires validation before reuse. Grace is a separate stale-response window, not a fallback TTL.</p>
<pre><code>Cache-Control: no-cache
Fallback TTL: 60 s
Varnish-compatible: ON</code></pre>
<p class="fine" data-i18n="cacheGuideFreshnessWarning">Do not expect a HIT for private/no-store/Set-Cookie or when the request is BYPASS. This override is not the default Varnish VCL behavior.</p>
</section>
<section class="cache-guide-card">
<h3 data-i18n="cacheGuideCookieTitle">Cookie and return(hash)</h3>
<p data-i18n="cacheGuideCookieText">Cookies normally trigger BYPASS. In compatible mode, an explicit return(hash) can admit eligible Cookie requests; the full Cookie remains on the backend request and partitions the cache. Catch session cookies with return(pass) first.</p>
<pre><code>sub vcl_recv {
if (req.http.Cookie ~ "session=") {
return (pass);
}
if (req.url ~ "^/public/") {
return (hash);
}
}</code></pre>
<button class="outline cache-guide-import-example" type="button"
data-i18n="cacheGuideInsert">Insert into VCL importer</button>
<p class="fine" data-i18n="cacheGuideCookieWarning">unset req.http.Cookie removes ALL cookies, including from the request sent to the backend. Authorization and authentication protections still apply.</p>
</section>
<section class="cache-guide-card">
<h3 data-i18n="cacheGuideVaryTitle">Vary and cache variants</h3>
<p data-i18n="cacheGuideVaryText">set/unset beresp.http.Vary changes variant selection before storing. set/unset resp.http.Vary only changes what the client sees; it does not repair the stored cache key. An assignment replaces the whole Vary list.</p>
<pre><code>sub vcl_backend_response {
set beresp.http.Vary =
"Accept-Encoding, Accept-Language";
}
sub vcl_deliver {
unset resp.http.X-Powered-By;
}</code></pre>
<button class="outline cache-guide-import-example" type="button"
data-i18n="cacheGuideInsert">Insert into VCL importer</button>
<p class="fine" data-i18n="cacheGuideVaryWarning">Never remove a required Vary dimension for a personalized or encoded response. RustProxy may restore Vary: Cookie for cookie-partitioned objects; static Ignore Vary: Cookie requires public and other safety checks.</p>
</section>
<section class="cache-guide-card">
<h3 data-i18n="cacheGuideHeadersTitle">set/unset headers</h3>
<p data-i18n="cacheGuideHeadersText">beresp.http.* edits the backend response before the cache decision; resp.http.* edits only the delivered response. Removing beresp.http.Cache-Control can change cache eligibility, while removing resp.http.Cache-Control cannot.</p>
<pre><code>sub vcl_backend_response {
unset beresp.http.X-Debug;
set beresp.http.Cache-Control =
"public, max-age=60";
}
sub vcl_deliver {
unset resp.http.X-Powered-By;
}</code></pre>
<button class="outline cache-guide-import-example" type="button"
data-i18n="cacheGuideInsert">Insert into VCL importer</button>
<p class="fine" data-i18n="cacheGuideHeadersWarning">Only literal string assignments are imported; protected transport/body headers cannot be edited. Removing Set-Cookie requires a dedicated backend action and is unsafe for session responses.</p>
</section>
<section class="cache-guide-card">
<h3 data-i18n="cacheGuideRequestTitle">Request headers and storage overrides</h3>
<p data-i18n="cacheGuideRequestText">Safe set/unset req.http headers are applied before subsequent rules, hashing and forwarding to the origin. beresp.uncacheable = false reverses an earlier rule's no-store decision, but does not override origin private/no-store/Set-Cookie.</p>
<pre><code>sub vcl_recv {
unset req.http.X-Tracking;
set req.http.X-Device = "mobile";
}
sub vcl_backend_response {
set beresp.uncacheable = false;
}</code></pre>
<button class="outline cache-guide-import-example" type="button"
data-i18n="cacheGuideInsert">Insert into VCL importer</button>
<p class="fine" data-i18n="cacheGuideRequestWarning">Authorization, Cookie (except dedicated unset), Cache-Control and forwarding/transport headers are protected in request rules. Complex URL rewrites are warned about, not guessed. Always review import warnings.</p>
<p class="fine" data-i18n="cacheGuideUncacheableDifference">RustProxy's beresp.uncacheable = false applies only to a previous cache-rule restriction; this is not Varnish's exact behavior. The backend's private/no-store and Set-Cookie protections remain unless deliberately rewritten by a separate trusted rule.</p>
</section>
<section class="cache-guide-card">
<h3 data-i18n="cacheGuideStagesTitle">VCL stages and rule precedence</h3>
<p data-i18n="cacheGuideStagesText">vcl_recv handles pass/hash and request rewrites; vcl_hash supports selected hash_data(req.http.X); vcl_backend_response handles TTL, grace and backend headers; vcl_deliver edits final headers, even on HIT or BYPASS.</p>
<p class="fine" data-i18n="cacheGuidePrecedenceText">Rules for the vhost are evaluated before matching global rules. Per-vhost changes win on conflicting supported settings and headers, or global rules may be disabled for the vhost. Importing VCL converts it into graphical rules; review warnings and the resulting order before saving.</p>
<p class="fine" data-i18n="cacheGuideUnsupportedText">Not yet a full Varnish interpreter: vcl_hit/vcl_miss/vcl_pass hooks, arbitrary sub/call, VMOD, ACL expressions, beresp.keep, hit-for-miss/pass, restart, retry, synth and purge are not executed as VCL.</p>
<p class="fine" data-i18n="cacheGuideBuiltInHash">hash_data(req.url) and hash_data(req.http.Host) are already included in the internal cache key. vcl_hash can add one extra req.http.* header, but it does not automatically generate a matching Vary header.</p>
<p class="fine" data-i18n="cacheGuideStatusRestriction">RustProxy currently stores only HTTP 200 responses. A TTL rule for 404/301 does not enable caching of those statuses; the former 404 template was removed to avoid suggesting otherwise.</p>
<p class="fine" data-i18n="cacheGuideVclPreviewWarning">VCL export is a readable preview, not a lossless round-trip. If import reports warnings, rules are not added until you explicitly accept the partial result. Editing the source or closing the importer discards any pending import.</p>
</section>
<section class="cache-guide-card">
<h3 data-i18n="cacheGuideDiagnoseTitle">Why isn't it a HIT?</h3>
<p data-i18n="cacheGuideDiagnoseText">Enable X-Cache and detailed reason headers; disable Only on HIT while debugging. Send two identical GET requests with curl (not a browser hard reload), then compare the cache outcome and origin headers.</p>
<pre><code>curl -sS -D - -o /dev/null \
https://example.com/public/page
curl -sS -D - -o /dev/null \
https://example.com/public/page</code></pre>
<p class="fine" data-i18n="cacheGuideDiagnoseReasons">BYPASS usually means request exclusion (Cookie, Authorization, route or query). MISS means the backend was contacted, but does not prove that the response was stored. Check X-Cache-Reason, Cache-Control, Set-Cookie, Vary and Age.</p>
</section>
</div>
<div class="cache-guide-footer">
<p class="fine" data-i18n="cacheGuideScope">These VCL rules affect reverse-proxy vhosts; they do not execute on the embedded administration panel or all Web Server sources. Test on a non-production vhost first.</p>
<a class="docs-link" href="/docs#doc=docs%2FVCL.md" target="_blank" rel="noopener noreferrer" data-i18n="cacheGuideDocsVcl">Complete supported VCL syntax and limits</a>
<a class="docs-link" href="/docs#doc=docs%2FCACHE.md" target="_blank" rel="noopener noreferrer" data-i18n="cacheGuideDocsCache">HTTP cache policy and diagnostics</a>
</div>
</div>
</dialog>
<dialog aria-labelledby="cache-invalidation-title" class="vhost-dialog cache-operation-dialog"
id="cache-invalidation-dialog">
<article class="card">
+48
View File
@@ -103,6 +103,54 @@
button.addEventListener("keydown", event => { const index = cacheTabs.indexOf(button); let next; if (event.key === "ArrowRight" || event.key === "ArrowDown") next = (index + 1) % cacheTabs.length; else if (event.key === "ArrowLeft" || event.key === "ArrowUp") next = (index + cacheTabs.length - 1) % cacheTabs.length; else if (event.key === "Home") next = 0; else if (event.key === "End") next = cacheTabs.length - 1; else return; event.preventDefault(); selectCacheTab(cacheTabs[next].dataset.cacheSettingsTab, true); });
}
selectCacheTab("general");
const cacheGuideDialog = $("cache-vcl-guide-dialog");
let guideEditor = null;
let guideIsLocal = false;
function openCacheGuide(trigger) {
if (!cacheGuideDialog) return;
// One guide serves the static global editor and both dynamic vhost editors.
// Keep its destination tied to the button that opened it; never silently
// insert a vhost example into global rules or vice versa.
guideEditor = trigger?.closest(".cache-rules") || $("cache-rules-root")?.querySelector(".cache-rules") || null;
guideIsLocal = guideEditor?.classList.contains("cache-rules-vhost") === true;
const isDocker = guideIsLocal && !!guideEditor.closest(".docker-cache-editor");
const compatible = $("cache-varnish-compatible").checked;
const enabled = $("cache-enabled").checked;
const ttl = Math.max(0, Number($("cache-default-ttl").value) || 0);
const grace = Math.max(0, Number($("cache-varnish-grace").value) || 0);
const mode = $("cache-guide-mode");
mode.textContent = t(compatible ? "cacheGuideModeOn" : "cacheGuideModeOff");
mode.classList.toggle("live", compatible);
$("cache-guide-ttl").textContent = t("cacheGuideTtlStatus").replace("{seconds}", ttl);
$("cache-guide-grace").textContent = t("cacheGuideGraceStatus").replace("{seconds}", grace);
$("cache-guide-current-note").textContent = t(!enabled ? "cacheGuideCacheOffNote" : !compatible ? "cacheGuideRfcNote" : ttl > 0 ? "cacheGuideCompatNote" : "cacheGuideCompatZeroNote");
$("cache-guide-context").textContent = t(isDocker ? "cacheGuideContextDocker" : guideIsLocal ? "cacheGuideContextVhost" : "cacheGuideContextGlobal");
$("cache-guide-scope-note").textContent = t(isDocker ? "cacheGuideScopeDocker" : guideIsLocal ? "cacheGuideScopeVhost" : "cacheGuideScopeGlobal");
if (!cacheGuideDialog.open) cacheGuideDialog.showModal();
}
// Event delegation is needed: the ordinary vhost dialog and the Docker
// service editors are created after settings.js has registered its events.
document.addEventListener("click", event => {
const button = event.target.closest?.(".cache-guide-trigger");
if (!button) return;
event.preventDefault();
openCacheGuide(button);
});
$("cache-vcl-guide-close")?.addEventListener("click", () => cacheGuideDialog.close());
cacheGuideDialog?.querySelectorAll(".cache-guide-import-example").forEach(button => button.addEventListener("click", () => {
const source = button.closest(".cache-guide-card")?.querySelector("pre code")?.textContent?.trim();
const importer = guideEditor?.isConnected ? guideEditor.querySelector(".cache-rules-import") : null;
const editor = importer?.querySelector("textarea");
if (!source || !editor) { toast(t("cacheGuideImporterUnavailable"), true); return; }
editor.value = [editor.value.trim(), source].filter(Boolean).join("\n\n");
// Invalidates any pending partial-import preview from an older source.
editor.dispatchEvent(new Event("input", { bubbles: true }));
importer.hidden = false;
cacheGuideDialog.close();
if (!guideIsLocal) selectCacheTab("rules");
importer.scrollIntoView({ block: "nearest", behavior: "smooth" });
editor.focus({ preventScroll: true });
}));
const loggingTabs = [...document.querySelectorAll("[data-logging-settings-tab]")];
function selectLoggingTab(name, focus = false) {
if (!loggingTabs.some(button => button.dataset.loggingSettingsTab === name)) return;
+4 -1
View File
@@ -536,7 +536,10 @@ function load(value = defaults(), migrationIds = [], show = true) {
note(unsafeCacheFields, "vhCacheForceHelp");
const cacheRulesFields = el("div", undefined, "vh-wide vh-cache-rules"); cacheOptions.append(cacheRulesFields);
cacheRulesFields.append(el("h4", t("vhCacheRulesTitle")), el("p", t("vhCacheRulesHelp"), "fine"));
vhostCacheRulesEditor = window.rustProxyCacheRules.create({ scope: "vhost", vhostId: editing || "", rules: cache.rules || [], ignoreGlobal: cache.ignore_global_rules === true });
vhostCacheRulesEditor = window.rustProxyCacheRules.create({
scope: "vhost", vhostId: editing || "", rules: cache.rules || [], ignoreGlobal: cache.ignore_global_rules === true,
testHost: () => lines(read("hosts")?.value || "").find(host => host && !host.startsWith("*.")) || "",
});
cacheRulesFields.append(vhostCacheRulesEditor.node);
if (editing) cacheOptions.append(button("vhPurgeCache", () => purge(editing)));
const syncCacheVisibility = () => {
+16 -1
View File
@@ -215,6 +215,20 @@ pub fn request_policy(
path: &str,
has_query: bool,
settings: &Settings,
) -> RequestPolicy {
request_policy_with_vcl_cookie(method, headers, empty_body, path, has_query, settings, false)
}
/// VCL return(hash) may override the built-in Cookie pass only in compatibility
/// mode. Authorization, no-store, invalid methods and other guards remain.
pub fn request_policy_with_vcl_cookie(
method: &Method,
headers: &HeaderMap,
empty_body: bool,
path: &str,
has_query: bool,
settings: &Settings,
allow_cookie: bool,
) -> RequestPolicy {
if method != Method::GET && method != Method::HEAD {
return RequestPolicy::Bypass("request_method");
@@ -246,7 +260,8 @@ pub fn request_policy(
("upgrade", "request_upgrade"),
] {
if headers.contains_key(key) {
if key == "cookie" && settings.ignore_cookie_for_path(path) {
if key == "cookie" && (settings.ignore_cookie_for_path(path)
|| (settings.varnish_compatible && allow_cookie)) {
continue;
}
return RequestPolicy::Bypass(reason);
+10 -5
View File
@@ -187,12 +187,13 @@ pub fn plan_with(
if !forced && settings.varnish_compatible && surrogate_no_store(headers) {
return None;
}
let override_public_no_cache = settings.varnish_compatible
// Explicit compatibility-mode fallback overrides origin no-cache even when
// it does not contain public. Strict mode always follows RFC 9111.
let override_no_cache = settings.varnish_compatible
&& control.contains_key("no-cache")
&& control.contains_key("public")
&& settings.default_ttl_seconds > 0;
&& (settings.default_ttl_seconds > 0 || overrides.ttl.is_some_and(|ttl| ttl > 0));
let requires_revalidation =
!forced && control.contains_key("no-cache") && !override_public_no_cache;
!forced && control.contains_key("no-cache") && !override_no_cache;
let must_revalidate = !forced && control.contains_key("must-revalidate");
let proxy_revalidate = !forced && control.contains_key("proxy-revalidate");
let parse_window = |name: &str| -> Option<u64> {
@@ -219,7 +220,7 @@ pub fn plan_with(
Some(ttl)
} else if forced {
(settings.default_ttl_seconds > 0).then_some(settings.default_ttl_seconds)
} else if override_public_no_cache {
} else if override_no_cache {
Some(settings.default_ttl_seconds)
} else if let Some(value) = control.get("s-maxage").or_else(|| control.get("max-age")) {
Some(value.as_ref()?.parse::<u64>().ok()?)
@@ -233,6 +234,10 @@ pub fn plan_with(
)
} else if control.contains_key("public") {
Some(settings.default_ttl_seconds)
} else if settings.varnish_compatible && settings.default_ttl_seconds > 0 {
// In compatibility mode a configured default TTL can also be used
// for headerless, otherwise eligible 200s (Varnish default_ttl style).
Some(settings.default_ttl_seconds)
} else {
None
};
+317 -108
View File
@@ -23,6 +23,30 @@ 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")
&& !name.starts_with("x-forwarded-")
&& !name.starts_with("proxy-")
&& !name.starts_with("x-rustproxy-")
&& !name.starts_with("sec-")
&& !name.starts_with("if-"),
"request header {header} cannot be changed by cache rules"
);
Ok(header)
}
fn yes_rule() -> bool {
true
}
@@ -122,6 +146,10 @@ pub struct RuleCondition {
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum RuleAction {
Pass,
/// Explicit VCL return(hash): allow a Cookie-bearing request to reach lookup.
Lookup,
SetRequestHeader { name: String, value: String },
RemoveRequestHeader { name: String },
StripCookies {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
keep: Vec<String>,
@@ -145,8 +173,13 @@ 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 },
SetHeader {
name: String,
value: String,
@@ -164,6 +197,9 @@ impl RuleAction {
fn stage(&self) -> RuleStage {
match self {
Self::Pass
| Self::Lookup
| Self::SetRequestHeader { .. }
| Self::RemoveRequestHeader { .. }
| Self::StripCookies { .. }
| Self::StripQuery { .. }
| Self::HashHeader { .. }
@@ -171,8 +207,11 @@ impl RuleAction {
Self::Ttl { .. }
| Self::Grace { .. }
| Self::NoStore
| Self::AllowStore
| Self::IgnoreCacheControl
| Self::StripSetCookie => RuleStage::Response,
| Self::StripSetCookie
| Self::SetBackendHeader { .. }
| Self::RemoveBackendHeader { .. } => RuleStage::Response,
Self::SetHeader { .. } | Self::RemoveHeader { .. } | Self::DefaultHeader { .. } => {
RuleStage::Deliver
}
@@ -180,10 +219,12 @@ impl RuleAction {
}
fn aspect(&self) -> Option<&'static str> {
match self {
Self::Pass => Some("pass"),
Self::Pass | Self::Lookup => Some("request_routing"),
Self::StripCookies { .. } => Some("request_cookies"),
Self::StripQuery { .. } => Some("request_query"),
Self::Ttl { .. } => Some("ttl"),
Self::Grace { .. } => Some("grace"),
Self::NoStore => Some("store"),
Self::NoStore | Self::AllowStore => Some("store"),
_ => None,
}
}
@@ -206,6 +247,9 @@ 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 = "Vec::is_empty")]
pub vhosts: Vec<String>,
}
@@ -365,6 +409,7 @@ pub struct CompiledRule {
conditions: Vec<CompiledCondition>,
actions: Vec<RuleAction>,
stop: bool,
hash_stage: bool,
counter: Arc<AtomicU64>,
}
@@ -516,6 +561,16 @@ fn compile_condition(condition: &RuleCondition, stage: RuleStage) -> Result<Comp
fn validate_action(action: &RuleAction) -> Result<()> {
match action {
RuleAction::SetRequestHeader { name, value } => {
request_rule_header_name(name)?;
ensure!(
value.len() <= 1024 && HeaderValue::from_str(value).is_ok(),
"invalid request header value"
);
}
RuleAction::RemoveRequestHeader { name } => {
request_rule_header_name(name)?;
}
RuleAction::StripCookies { keep } => {
ensure!(keep.len() <= MAX_RULE_VALUES, "too many cookie names");
ensure!(
@@ -537,8 +592,8 @@ fn validate_action(action: &RuleAction) -> Result<()> {
RuleAction::HashHeader { name } => {
let header = rule_header_name(name)?;
ensure!(
header != http::header::COOKIE && header != http::header::AUTHORIZATION,
"use hash cookie instead of hashing the whole Cookie or Authorization header"
header != http::header::AUTHORIZATION,
"Authorization cannot be added to a shared cache key"
);
}
RuleAction::HashCookie { name } => ensure!(valid_cookie_name(name), "invalid cookie name"),
@@ -548,7 +603,9 @@ fn validate_action(action: &RuleAction) -> Result<()> {
"TTL and grace are limited to one year"
)
}
RuleAction::SetHeader { name, value } | RuleAction::DefaultHeader { name, value } => {
RuleAction::SetBackendHeader { name, value }
| RuleAction::SetHeader { name, value }
| RuleAction::DefaultHeader { name, value } => {
let header = rule_header_name(name)?;
ensure!(
!PROTECTED_RULE_HEADERS.contains(&header.as_str()),
@@ -559,7 +616,7 @@ fn validate_action(action: &RuleAction) -> Result<()> {
"invalid header value"
);
}
RuleAction::RemoveHeader { name } => {
RuleAction::RemoveBackendHeader { name } | RuleAction::RemoveHeader { name } => {
let header = rule_header_name(name)?;
ensure!(
!PROTECTED_RULE_HEADERS.contains(&header.as_str()),
@@ -567,7 +624,9 @@ fn validate_action(action: &RuleAction) -> Result<()> {
);
}
RuleAction::Pass
| RuleAction::Lookup
| RuleAction::NoStore
| RuleAction::AllowStore
| RuleAction::IgnoreCacheControl
| RuleAction::StripSetCookie => {}
}
@@ -617,8 +676,13 @@ fn compile_rule(rule: &Rule, origin: RuleOrigin, scope: &str) -> Result<Compiled
rule.id
);
ensure!(
!rule.actions.is_empty() && rule.actions.len() <= MAX_RULE_ACTIONS,
"cache rule {} needs 1-{MAX_RULE_ACTIONS} actions",
(!rule.actions.is_empty() || rule.stop) && rule.actions.len() <= MAX_RULE_ACTIONS,
"cache rule {} needs 1-{MAX_RULE_ACTIONS} actions, or a terminal return",
rule.id
);
ensure!(
!rule.hash_stage || rule.stage == RuleStage::Request,
"cache rule {}: hash_stage requires the request stage",
rule.id
);
for action in &rule.actions {
@@ -646,6 +710,7 @@ fn compile_rule(rule: &Rule, origin: RuleOrigin, scope: &str) -> Result<Compiled
conditions,
actions: rule.actions.clone(),
stop: rule.stop,
hash_stage: rule.hash_stage,
counter: rule_counter(origin, scope, &rule.id),
})
}
@@ -653,6 +718,7 @@ fn compile_rule(rule: &Rule, origin: RuleOrigin, scope: &str) -> Result<Compiled
#[derive(Debug, Default)]
pub struct CompiledRules {
request: Vec<CompiledRule>,
hash: Vec<CompiledRule>,
response: Vec<CompiledRule>,
deliver: Vec<CompiledRule>,
}
@@ -682,6 +748,7 @@ impl CompiledRules {
}
let item = compile_rule(rule, origin, vhost_id)?;
match item.stage {
RuleStage::Request if item.hash_stage => compiled.hash.push(item),
RuleStage::Request => compiled.request.push(item),
RuleStage::Response => compiled.response.push(item),
RuleStage::Deliver => compiled.deliver.push(item),
@@ -690,7 +757,8 @@ impl CompiledRules {
Ok(compiled)
}
pub fn is_empty(&self) -> bool {
self.request.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()
@@ -871,6 +939,10 @@ pub struct RuleOverride {
#[derive(Debug, Clone, Default, Serialize)]
pub struct RequestRuleOutcome {
pub pass: Option<String>,
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>>,
pub query_edits: Vec<(Vec<String>, bool)>,
pub hash: Vec<String>,
@@ -878,6 +950,13 @@ pub struct RequestRuleOutcome {
pub overridden: Vec<RuleOverride>,
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum BackendHeaderEdit {
Set { name: String, value: String },
Remove { name: String },
}
#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
pub struct ResponseOverrides {
pub ttl: Option<u64>,
@@ -885,6 +964,8 @@ pub struct ResponseOverrides {
pub no_store: bool,
pub ignore_cache_control: bool,
pub strip_set_cookie: bool,
/// Ordered backend header mutations. Global rules cannot replace vhost edits.
pub header_edits: Vec<BackendHeaderEdit>,
}
impl ResponseOverrides {
@@ -894,10 +975,31 @@ impl ResponseOverrides {
no_store: false,
ignore_cache_control: false,
strip_set_cookie: false,
header_edits: Vec::new(),
};
pub fn is_none(&self) -> bool {
*self == Self::NONE
}
pub fn apply_headers(&self, headers: &mut HeaderMap) {
for edit in &self.header_edits {
match edit {
BackendHeaderEdit::Set { name, value } => {
if let (Ok(header), Ok(value)) = (
http::HeaderName::from_bytes(name.as_bytes()),
HeaderValue::from_str(value),
) {
headers.insert(header, value);
}
}
BackendHeaderEdit::Remove { name } => {
headers.remove(name.as_str());
}
}
}
if self.strip_set_cookie {
headers.remove(http::header::SET_COOKIE);
}
}
}
#[derive(Debug, Clone, Default, Serialize)]
@@ -913,6 +1015,8 @@ pub struct DeliverRuleOutcome {
pub defaults: Vec<(String, String)>,
pub remove: Vec<String>,
pub matched: Vec<RuleMatchInfo>,
#[serde(skip)]
edits: Vec<(u8, String, String)>,
}
fn info(rule: &CompiledRule) -> RuleMatchInfo {
@@ -939,17 +1043,17 @@ fn claim(
rule.id
);
match owners.get(aspect) {
Some(winner) => {
if winner != &label {
overridden.push(RuleOverride {
aspect,
winner: winner.clone(),
ignored: label,
});
}
Some(winner) if winner.starts_with("vhost:") && rule.origin == RuleOrigin::Global => {
overridden.push(RuleOverride {
aspect,
winner: winner.clone(),
ignored: label,
});
false
}
None => {
_ => {
// Last matching assignment wins within the same scope; vhost
// priority is preserved over later global rules.
owners.insert(aspect, label);
true
}
@@ -960,59 +1064,98 @@ impl CompiledRules {
pub fn evaluate_request(&self, request: &RuleRequest, count: bool) -> RequestRuleOutcome {
let mut outcome = RequestRuleOutcome::default();
let mut owners = HashMap::new();
for rule in &self.request {
if !rule.matches(request, None) {
continue;
}
if count {
rule.counter.fetch_add(1, Ordering::Relaxed);
}
outcome.matched.push(info(rule));
for action in &rule.actions {
if let Some(aspect) = action.aspect() {
if !claim(&mut owners, &mut outcome.overridden, aspect, rule) {
continue;
}
}
match action {
RuleAction::Pass => outcome.pass = Some(rule.id.clone()),
RuleAction::StripCookies { keep } => match &mut outcome.strip_cookies {
Some(existing) => existing.retain(|name| keep.contains(name)),
None => outcome.strip_cookies = Some(keep.clone()),
},
RuleAction::StripQuery { params, keep_only } => {
outcome.query_edits.push((params.clone(), *keep_only))
}
RuleAction::HashHeader { name } => {
let value = rule_header_name(name)
.ok()
.map(|header| {
request
.headers
.get_all(&header)
.iter()
.filter_map(|v| v.to_str().ok())
.collect::<Vec<_>>()
.join(",")
})
.unwrap_or_default();
outcome
.hash
.push(format!("h:{}={value}", name.to_ascii_lowercase()));
}
RuleAction::HashCookie { name } => {
let value = cookie_values(&request.headers)
.find(|(key, _)| key == name)
.map(|(_, value)| value)
.unwrap_or("");
outcome.hash.push(format!("c:{name}={value}"));
}
_ => {}
}
}
if rule.stop {
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.
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) {
continue;
}
if count {
rule.counter.fetch_add(1, Ordering::Relaxed);
}
outcome.matched.push(info(rule));
for action in &rule.actions {
if let Some(aspect) = action.aspect() {
if !claim(&mut owners, &mut outcome.overridden, aspect, rule) {
continue;
}
}
match action {
RuleAction::Pass => {
outcome.pass = Some(rule.id.clone());
outcome.lookup = None;
}
RuleAction::Lookup => {
outcome.lookup = Some(rule.id.clone());
outcome.pass = None;
},
RuleAction::SetRequestHeader { name, value } => {
let key = name.to_ascii_lowercase();
if header_owners.get(&key) == Some(&RuleOrigin::Vhost)
&& rule.origin != RuleOrigin::Vhost
{ continue; }
header_owners.insert(key.clone(), rule.origin);
let header = http::HeaderName::from_bytes(key.as_bytes())
.expect("validated request header");
let value_header = HeaderValue::from_str(value)
.expect("validated request header value");
current.headers.insert(header, value_header);
outcome.header_edits.push(BackendHeaderEdit::Set {
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; }
header_owners.insert(key.clone(), rule.origin);
current.headers.remove(key.as_str());
outcome.header_edits.push(BackendHeaderEdit::Remove { name: key });
}
RuleAction::StripCookies { keep } => {
match &mut outcome.strip_cookies {
Some(existing) => existing.retain(|name| keep.contains(name)),
None => outcome.strip_cookies = Some(keep.clone()),
}
outcome.rewrite_cookies(&mut current.headers);
}
RuleAction::StripQuery { params, keep_only } => {
outcome.query_edits.push((params.clone(), *keep_only));
if let Some(rewritten) = outcome.rewrite_query(current.query.as_deref()) {
current.query = rewritten;
}
}
RuleAction::HashHeader { name } => {
let value = rule_header_name(name)
.ok()
.map(|header| {
current.headers.get_all(&header).iter()
.filter_map(|v| v.to_str().ok())
.collect::<Vec<_>>().join(",")
})
.unwrap_or_default();
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("");
outcome.hash.push(format!("c:{name}={value}"));
}
_ => {}
}
}
if rule.stop {
break;
}
}
}
outcome
}
@@ -1026,8 +1169,10 @@ impl CompiledRules {
) -> ResponseRuleOutcome {
let mut outcome = ResponseRuleOutcome::default();
let mut owners = HashMap::new();
let mut header_owners: HashMap<String, RuleOrigin> = HashMap::new();
let mut current = headers.clone();
for rule in &self.response {
if !rule.matches(request, Some((status, headers))) {
if !rule.matches(request, Some((status, &current))) {
continue;
}
if count {
@@ -1044,8 +1189,41 @@ impl CompiledRules {
RuleAction::Ttl { seconds } => outcome.overrides.ttl = Some(*seconds),
RuleAction::Grace { seconds } => outcome.overrides.grace = Some(*seconds),
RuleAction::NoStore => outcome.overrides.no_store = true,
RuleAction::AllowStore => outcome.overrides.no_store = false,
RuleAction::IgnoreCacheControl => outcome.overrides.ignore_cache_control = true,
RuleAction::StripSetCookie => outcome.overrides.strip_set_cookie = true,
RuleAction::StripSetCookie => {
if header_owners.get("set-cookie") != Some(&RuleOrigin::Vhost)
|| rule.origin == RuleOrigin::Vhost
{
header_owners.insert("set-cookie".into(), rule.origin);
outcome.overrides.strip_set_cookie = true;
current.remove(http::header::SET_COOKIE);
}
}
RuleAction::SetBackendHeader { name, value } => {
let key = name.to_ascii_lowercase();
if header_owners.get(&key) == Some(&RuleOrigin::Vhost)
&& rule.origin != RuleOrigin::Vhost
{ 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)
) {
current.insert(header, value_header);
outcome.overrides.header_edits.push(BackendHeaderEdit::Set {
name: key, value: value.clone(),
});
}
}
RuleAction::RemoveBackendHeader { name } => {
let key = name.to_ascii_lowercase();
if header_owners.get(&key) == Some(&RuleOrigin::Vhost)
&& rule.origin != RuleOrigin::Vhost
{ continue; }
header_owners.insert(key.clone(), rule.origin);
current.remove(key.as_str());
outcome.overrides.header_edits.push(BackendHeaderEdit::Remove { name: key });
}
_ => {}
}
}
@@ -1064,37 +1242,72 @@ impl CompiledRules {
count: bool,
) -> DeliverRuleOutcome {
let mut outcome = DeliverRuleOutcome::default();
let mut ownership: HashMap<String, RuleOrigin> = HashMap::new();
let mut current = headers.clone();
for rule in &self.deliver {
if !rule.matches(request, Some((status, headers))) {
if !rule.matches(request, Some((status, &current))) {
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 {
match action {
RuleAction::SetHeader { name, value } => {
outcome.set.push((name.to_ascii_lowercase(), value.clone()))
let (kind, name, value) = match action {
RuleAction::SetHeader { name, value } => (1, name, value.as_str()),
RuleAction::DefaultHeader { name, value } => (2, name, value.as_str()),
RuleAction::RemoveHeader { name } => (3, name, ""),
_ => continue,
};
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; }
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"));
}
RuleAction::RemoveHeader { name } => {
outcome.remove.push(name.to_ascii_lowercase())
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"));
}
_ => {
outcome.remove.push(name.clone());
current.remove(name.as_str());
}
RuleAction::DefaultHeader { name, value } => outcome
.defaults
.push((name.to_ascii_lowercase(), value.clone())),
_ => {}
}
outcome.edits.push((kind, name, value.to_owned()));
}
if rule.stop {
break;
}
if rule.stop { break; }
}
outcome
}
}
impl RequestRuleOutcome {
pub fn apply_headers(&self, headers: &mut HeaderMap) {
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),
) {
headers.insert(name, value);
}
}
BackendHeaderEdit::Remove { name } => {
headers.remove(name.as_str());
}
}
}
}
pub fn rewrite_cookies(&self, headers: &mut HeaderMap) {
let Some(keep) = &self.strip_cookies else {
return;
@@ -1151,30 +1364,26 @@ impl RequestRuleOutcome {
impl DeliverRuleOutcome {
pub fn apply(&self, headers: &mut HeaderMap) {
for name in &self.remove {
if let Ok(header) = http::HeaderName::from_bytes(name.as_bytes()) {
headers.remove(header);
}
}
for (name, value) in &self.set {
if let (Ok(header), Ok(value)) = (
http::HeaderName::from_bytes(name.as_bytes()),
HeaderValue::from_str(value),
) {
headers.insert(header, value);
}
}
for (name, value) in &self.defaults {
if let (Ok(header), Ok(value)) = (
http::HeaderName::from_bytes(name.as_bytes()),
HeaderValue::from_str(value),
) {
if !headers.contains_key(&header) {
headers.insert(header, value);
for (kind, name, value) in &self.edits {
let Ok(header) = http::HeaderName::from_bytes(name.as_bytes()) else { continue; };
match kind {
1 => {
if let Ok(value) = HeaderValue::from_str(value) {
headers.insert(header, value);
}
}
2 => {
if !headers.contains_key(&header) {
if let Ok(value) = HeaderValue::from_str(value) {
headers.insert(header, value);
}
}
}
_ => { headers.remove(header); }
}
}
}
}
#[derive(Debug, Clone)]
+376
View File
@@ -346,6 +346,8 @@ sub vcl_deliver {
.find(|rule| rule.actions.contains(&RuleAction::Ttl { seconds: 3600 }))
.unwrap();
assert!(else_rule.conditions[0].negate);
assert!(imported.warnings.iter().any(|warning| warning.contains("regsuball(req.url")));
assert!(imported.warnings.iter().any(|warning| warning.contains("empty values")));
assert!(imported
.warnings
.iter()
@@ -357,4 +359,378 @@ sub vcl_deliver {
assert!(import_vcl("sub vcl_recv { if (").is_err());
assert!(import_vcl("vcl 4.1;").is_err());
}
#[test]
fn imported_vcl_cookie_pass_and_hash_stages_obey_terminal_returns() {
let imported = import_vcl(r#"
vcl 4.1;
sub vcl_recv {
if (req.http.Cookie ~ "sid=") { return(pass); }
if (req.http.Cookie) { return(hash); }
return(hash);
}
sub vcl_hash { hash_data(req.http.Cookie); }
"#).unwrap();
assert!(imported.warnings.is_empty(), "{:?}", imported.warnings);
let compiled = CompiledRules::compile("shop", &[], &imported.rules, false).unwrap();
let session = request("/home", None, &[("cookie", "sid=123; lang=pl")]);
let session_out = compiled.evaluate_request(&session, false);
assert!(session_out.pass.is_some());
assert!(session_out.lookup.is_none());
assert!(session_out.hash.is_empty(), "vcl_hash cannot run after pass");
let language = request("/home", None, &[("cookie", "lang=pl")]);
let out = compiled.evaluate_request(&language, false);
assert!(out.pass.is_none());
assert!(out.lookup.is_some());
assert_eq!(out.hash_variant(), "h:cookie=lang=pl");
let mut compatible = Settings::default();
assert_eq!(
request_policy_with_vcl_cookie(&Method::GET, &language.headers, true, "/home", false, &compatible, true),
RequestPolicy::Use
);
assert_eq!(
request_policy(&Method::GET, &language.headers, true, "/home", false, &compatible),
RequestPolicy::Bypass("request_cookie")
);
compatible.varnish_compatible = false;
assert_eq!(
request_policy_with_vcl_cookie(&Method::GET, &language.headers, true, "/home", false, &compatible, true),
RequestPolicy::Bypass("request_cookie")
);
let with_authorization = request("/home", None, &[("cookie", "lang=pl"), ("authorization", "Basic user")]);
compatible.varnish_compatible = true;
assert_eq!(
request_policy_with_vcl_cookie(&Method::GET, &with_authorization.headers, true, "/home", false, &compatible, true),
RequestPolicy::Bypass("request_authorization")
);
}
#[test]
fn imported_vcl_nested_elsif_else_and_earlier_cookie_unset_are_visible() {
let imported = import_vcl(r#"
sub vcl_recv {
if (req.url ~ "^/static") {
unset req.http.Cookie;
if (req.http.Cookie) { return(pass); }
else { return(hash); }
} elsif (req.url ~ "^/private") { return(pass); }
else { return(hash); }
}
"#).unwrap();
assert!(imported.warnings.is_empty(), "{:?}", imported.warnings);
let compiled = CompiledRules::compile("shop", &[], &imported.rules, false).unwrap();
let asset = request("/static/index.html", None, &[("cookie", "lang=pl; sid=7")]);
let matched = compiled.evaluate_request(&asset, false);
assert!(matched.lookup.is_some());
assert!(matched.pass.is_none());
let mut headers = asset.headers.clone();
matched.rewrite_cookies(&mut headers);
assert!(!headers.contains_key("cookie"));
assert!(compiled.evaluate_request(&request("/private/a", None, &[]), false).pass.is_some());
assert!(compiled.evaluate_request(&request("/other", None, &[]), false).lookup.is_some());
}
#[test]
fn imported_backend_header_edits_change_policy_before_cache_admission() {
let imported = import_vcl(r#"
sub vcl_backend_response {
unset beresp.http.Cache-Control;
set beresp.http.Cache-Control = "public, max-age=77";
if (beresp.http.Cache-Control == "public, max-age=77") {
set beresp.ttl = 88s;
}
}
"#).unwrap();
assert!(imported.warnings.is_empty(), "{:?}", imported.warnings);
let compiled = CompiledRules::compile("shop", &[], &imported.rules, false).unwrap();
let mut response = HeaderMap::new();
response.insert("cache-control", HeaderValue::from_static("private, no-store"));
let out = compiled.evaluate_response(&request("/", None, &[]), StatusCode::OK, &response, false);
assert_eq!(out.overrides.ttl, Some(88));
out.overrides.apply_headers(&mut response);
assert_eq!(response["cache-control"], "public, max-age=77");
let strict = Settings {varnish_compatible: false, ..Default::default()};
assert!(plan_with(StatusCode::OK, &response, &strict, std::time::Duration::ZERO, &out.overrides).is_some());
}
#[test]
fn vhost_backend_header_wins_and_subsequent_rule_sees_mutation() {
let local = vec![
rule(serde_json::json!({"id":"local", "stage":"response", "actions":[{"type":"set_backend_header","name":"Cache-Control","value":"public, max-age=120"}]})),
rule(serde_json::json!({"id":"local-second", "stage":"response", "conditions":[{"field":"response_header","name":"Cache-Control","operator":"equals","values":["public, max-age=120"]}], "actions":[{"type":"ttl","seconds":125}]})),
];
let global = vec![rule(serde_json::json!({"id":"global", "stage":"response", "actions":[{"type":"remove_backend_header","name":"Cache-Control"}, {"type":"ttl","seconds":5}]}))];
let compiled = CompiledRules::compile("shop", &local, &global, false).unwrap();
let original = HeaderMap::new();
let outcome = compiled.evaluate_response(&request("/", None, &[]), StatusCode::OK, &original, false);
let mut rewritten = original;
outcome.overrides.apply_headers(&mut rewritten);
assert_eq!(rewritten["cache-control"], "public, max-age=120");
assert_eq!(outcome.overrides.ttl, Some(125));
assert!(outcome.overridden.iter().any(|entry| entry.ignored == "global:global"));
}
#[test]
fn vhost_delivery_mutations_remain_ordered_and_global_cannot_unset() {
let local = vec![
rule(serde_json::json!({"id":"first", "stage":"deliver", "actions":[{"type":"set_header","name":"X-Decision","value":"first"}]})),
rule(serde_json::json!({"id":"second", "stage":"deliver", "conditions":[{"field":"response_header","name":"X-Decision","operator":"equals","values":["first"]}], "actions":[{"type":"remove_header","name":"X-Decision"}, {"type":"default_header","name":"X-Decision","value":"second"}]})),
];
let global = vec![rule(serde_json::json!({"id":"global", "stage":"deliver", "actions":[{"type":"remove_header","name":"X-Decision"}]}))];
let compiled = CompiledRules::compile("shop", &local, &global, false).unwrap();
let mut headers = HeaderMap::new();
let outcome = compiled.evaluate_deliver(&request("/", None, &[]), StatusCode::OK, &headers, false);
outcome.apply(&mut headers);
assert_eq!(headers["x-decision"], "second");
}
#[test]
fn imported_terminal_deliver_does_not_run_following_rules() {
let imported = import_vcl(r#"
sub vcl_deliver {
if (req.url ~ "^/private") { return(deliver); }
set resp.http.X-Later = "yes";
}
"#).unwrap();
assert!(imported.warnings.is_empty(), "{:?}", imported.warnings);
let compiled = CompiledRules::compile("shop", &[], &imported.rules, false).unwrap();
let mut response = HeaderMap::new();
compiled.evaluate_deliver(&request("/private", None, &[]), StatusCode::OK, &response, false).apply(&mut response);
assert!(!response.contains_key("x-later"));
compiled.evaluate_deliver(&request("/public", None, &[]), StatusCode::OK, &response, false).apply(&mut response);
assert_eq!(response["x-later"], "yes");
}
#[test]
fn vcl_request_header_edits_are_visible_to_later_guards_hash_and_origin() {
let imported = import_vcl(r#"
sub vcl_recv {
set req.http.X-Device = "mobile";
if (req.http.X-Device == "mobile") {
unset req.http.X-Tracking;
return(hash);
}
}
sub vcl_hash { hash_data(req.http.X-Device); }
"#).unwrap();
assert!(imported.warnings.is_empty(), "{:?}", imported.warnings);
let compiled = CompiledRules::compile("shop", &[], &imported.rules, false).unwrap();
let original = request("/catalog", None, &[("x-tracking", "secret"), ("cookie", "lang=pl")]);
let outcome = compiled.evaluate_request(&original, false);
assert!(outcome.pass.is_none());
assert!(outcome.lookup.is_some());
assert_eq!(outcome.hash_variant(), "h:x-device=mobile");
assert_eq!(original.headers.get("x-tracking").unwrap(), "secret");
let mut forwarded = original.headers.clone();
outcome.apply_headers(&mut forwarded);
outcome.rewrite_cookies(&mut forwarded);
assert_eq!(forwarded["x-device"], "mobile");
assert!(!forwarded.contains_key("x-tracking"));
assert_eq!(forwarded["cookie"], "lang=pl");
}
#[test]
fn request_header_overrides_respect_vhost_priority_but_allow_other_globals() {
let local = vec![rule(serde_json::json!({
"id": "local-header", "actions": [{"type":"set_request_header", "name":"X-Device", "value":"local"}]
}))];
let global = vec![
rule(serde_json::json!({
"id": "global-header", "actions": [
{"type":"set_request_header", "name":"X-Device", "value":"global"},
{"type":"set_request_header", "name":"X-Public-View", "value":"yes"}
]
})),
rule(serde_json::json!({
"id": "global-match", "conditions": [{"field":"header", "name":"X-Device", "operator":"equals", "values":["local"]}],
"actions": [{"type":"hash_header", "name":"X-Public-View"}]
})),
];
let compiled = CompiledRules::compile("shop", &local, &global, false).unwrap();
let outcome = compiled.evaluate_request(&request("/", None, &[]), false);
let mut forwarded = HeaderMap::new();
outcome.apply_headers(&mut forwarded);
assert_eq!(forwarded["x-device"], "local");
assert_eq!(forwarded["x-public-view"], "yes");
assert_eq!(outcome.hash_variant(), "h:x-public-view=yes");
}
#[test]
fn unsafe_request_edits_are_rejected_without_discarding_valid_neighbors() {
for name in ["Authorization", "Cookie", "Cache-Control", "X-Forwarded-For", "If-None-Match", "Host", "Content-Length"] {
let rules = vec![rule(serde_json::json!({
"id": "unsafe", "actions": [{"type":"remove_request_header", "name":name}]
}))];
assert!(validate_rules(&rules, true).is_err(), "must protect {name}");
}
let imported = import_vcl(r#"
sub vcl_recv {
set req.http.X-Safe = "one";
unset req.http.Authorization;
set req.http.X-Safe = "two";
}
"#).unwrap();
assert_eq!(imported.warnings.len(), 1, "{:?}", imported.warnings);
let compiled = CompiledRules::compile("shop", &[], &imported.rules, false).unwrap();
let outcome = compiled.evaluate_request(&request("/", None, &[("authorization", "Bearer x")]), false);
let mut headers = HeaderMap::new();
headers.insert("authorization", HeaderValue::from_static("Bearer x"));
outcome.apply_headers(&mut headers);
assert_eq!(headers["x-safe"], "two");
assert_eq!(headers["authorization"], "Bearer x");
}
#[test]
fn uncacheable_false_reverses_only_previous_rule_no_store() {
let imported = import_vcl(r#"
sub vcl_backend_response {
set beresp.uncacheable = true;
set beresp.uncacheable = false;
set beresp.ttl = 60s;
}
"#).unwrap();
assert!(imported.warnings.is_empty(), "{:?}", imported.warnings);
let compiled = CompiledRules::compile("shop", &[], &imported.rules, false).unwrap();
let mut response = HeaderMap::new();
response.insert("cache-control", HeaderValue::from_static("max-age=30"));
let outcome = compiled.evaluate_response(&request("/", None, &[]), StatusCode::OK, &response, false);
assert!(!outcome.overrides.no_store);
assert_eq!(outcome.overrides.ttl, Some(60));
let strict = Settings { varnish_compatible: false, ..Default::default() };
assert!(plan_with(StatusCode::OK, &response, &strict, std::time::Duration::ZERO, &outcome.overrides).is_some());
response.insert("cache-control", HeaderValue::from_static("private, no-store"));
assert!(plan_with(StatusCode::OK, &response, &strict, std::time::Duration::ZERO, &outcome.overrides).is_none());
response.remove("cache-control");
response.insert("set-cookie", HeaderValue::from_static("sid=1"));
assert!(plan_with(StatusCode::OK, &response, &strict, std::time::Duration::ZERO, &outcome.overrides).is_none());
}
#[test]
fn vhost_allow_store_overrides_global_no_store() {
let local = vec![rule(serde_json::json!({"id":"local-store", "stage":"response", "actions":[{"type":"allow_store"}]}))];
let global = vec![rule(serde_json::json!({"id":"global-store", "stage":"response", "actions":[{"type":"no_store"}]}))];
let rules = CompiledRules::compile("shop", &local, &global, false).unwrap();
let outcome = rules.evaluate_response(&request("/", None, &[]), StatusCode::OK, &HeaderMap::new(), false);
assert!(!outcome.overrides.no_store);
assert!(outcome.overridden.iter().any(|entry| entry.aspect == "store" && entry.ignored == "global:global-store"));
}
#[test]
fn unsupported_url_regex_is_warned_not_misconverted_to_query_removal() {
let imported = import_vcl(r#"
sub vcl_recv {
set req.url = regsub(req.url, "^/utm_foo", "/other");
set req.url = regsuball(req.url, "^/utm_foo", "\\1");
set req.url = regsuball(req.url, "(\\?|&)(utm_foo)=[^&]*", "deleted");
}
"#).unwrap();
assert!(imported.rules.is_empty(), "unsupported VCL must never strip unrelated query parameters");
assert_eq!(imported.warnings.len(), 3, "{:?}", imported.warnings);
}
#[test]
fn valid_vcl_import_flushes_long_action_blocks_instead_of_dropping_them() {
let mut source = String::from("sub vcl_recv {\n");
for id in 1..=20 { source.push_str(&format!("set req.http.X-Rule-{id} = \"ok\";\n")); }
source.push_str("}");
let imported = import_vcl(&source).unwrap();
assert!(imported.warnings.is_empty(), "{:?}", imported.warnings);
let rules = CompiledRules::compile("shop", &[], &imported.rules, false).unwrap();
let outcome = rules.evaluate_request(&request("/", None, &[]), false);
let mut headers = HeaderMap::new();
outcome.apply_headers(&mut headers);
assert_eq!(headers["x-rule-1"], "ok");
assert_eq!(headers["x-rule-20"], "ok");
}
#[test]
fn vcl_builtin_hash_fields_are_already_in_rustproxy_key() {
let imported = import_vcl(r#"
sub vcl_recv {
set req.http.X-Device = "mobile";
return(hash);
}
sub vcl_hash {
hash_data(req.url);
hash_data(req.http.Host);
hash_data(req.http.X-Device);
return(lookup);
}
"#).unwrap();
assert!(imported.warnings.is_empty(), "{:?}", imported.warnings);
validate_rules(&imported.rules, true).unwrap();
let rules = CompiledRules::compile("shop", &[], &imported.rules, false).unwrap();
let outcome = rules.evaluate_request(&request("/catalog", Some("lang=pl"), &[]), false);
assert!(outcome.lookup.is_some());
assert!(outcome.pass.is_none());
// The path, query and authority already form the base cache key.
assert_eq!(outcome.hash, vec!["h:x-device=mobile"]);
}
#[test]
fn vcl_quoted_strings_support_escaped_quotes_and_backslashes() {
let imported = import_vcl(r#"
sub vcl_recv {
set req.http.X-Note = "quote: \" and slash: \\";
}
sub vcl_deliver {
set resp.http.X-Note = "a \"quote\" and a \\ slash";
}
"#).unwrap();
assert!(imported.warnings.is_empty(), "{:?}", imported.warnings);
let rules = CompiledRules::compile("shop", &[], &imported.rules, false).unwrap();
let mut headers = HeaderMap::new();
rules.evaluate_request(&request("/", None, &[]), false).apply_headers(&mut headers);
assert_eq!(headers["x-note"], "quote: \" and slash: \\");
let mut response_headers = HeaderMap::new();
rules.evaluate_deliver(&request("/", None, &[]), StatusCode::OK, &response_headers, false)
.apply(&mut response_headers);
assert_eq!(response_headers["x-note"], "a \"quote\" and a \\ slash");
}
#[test]
fn malformed_vcl_statements_are_warned_and_do_not_apply_partial_actions() {
let imported = import_vcl(r#"
sub vcl_recv {
return(hash, pass);
hash_data(req.http.X-Should-Not-Hash);
set req.http.X-Allowed = "yes";
}
sub vcl_hash {
hash_data(req.http.X-Extra, req.http.X-Another);
hash_data(req.http.X-Allowed);
}
sub vcl_backend_response {
set beresp.ttl = 90s + 20s;
unset beresp.http.Vary extra;
set beresp.ttl = 30s;
}
sub vcl_deliver {
set resp.http.X-Bad + "no";
unset resp.http.Vary extra;
unset resp.http.X-Trace;
}
"#).unwrap();
assert!(imported.warnings.iter().any(|warning| warning.contains("return requires")), "{:?}", imported.warnings);
assert!(imported.warnings.iter().any(|warning| warning.contains("hash_data is only supported inside")));
assert!(imported.warnings.iter().any(|warning| warning.contains("hash_data supports")));
assert!(imported.warnings.iter().any(|warning| warning.contains("set beresp requires")));
assert!(imported.warnings.iter().any(|warning| warning.contains("unset beresp requires")));
assert!(imported.warnings.iter().any(|warning| warning.contains("unset resp requires")));
validate_rules(&imported.rules, true).unwrap();
let rules = CompiledRules::compile("shop", &[], &imported.rules, false).unwrap();
let outcome = rules.evaluate_request(&request("/", None, &[]), false);
assert!(outcome.pass.is_none());
assert!(outcome.lookup.is_none());
assert_eq!(outcome.hash, vec!["h:x-allowed=yes"]);
let response = rules.evaluate_response(&request("/", None, &[]), StatusCode::OK, &HeaderMap::new(), false);
assert_eq!(response.overrides.ttl, Some(30));
assert!(response.overrides.header_edits.is_empty());
}
#[test]
fn vcl_tokenizer_rejects_unclosed_quotes_and_comments() {
assert!(import_vcl("sub vcl_recv { set req.http.X-A = \"missing; }").is_err());
assert!(import_vcl("sub vcl_recv { /* missing */ set req.http.X-A = \"x\"; /*").is_err());
}
}
+38 -10
View File
@@ -257,13 +257,11 @@ mod varnish_compatible_tests {
assert_eq!(fallback_plan.ttl, 42);
assert!(!fallback_plan.requires_revalidation);
let nonpublic_no_cache = headers("no-cache, max-age=60");
assert!(plan(
StatusCode::OK,
&nonpublic_no_cache,
&fallback,
Duration::ZERO
)
.is_none());
let nonpublic_plan = plan(StatusCode::OK, &nonpublic_no_cache, &fallback, Duration::ZERO)
.expect("compatible fallback overrides no-cache without public");
assert_eq!(nonpublic_plan.ttl, 42);
assert!(!nonpublic_plan.requires_revalidation);
assert!(plan(StatusCode::OK, &nonpublic_no_cache, &strict, Duration::ZERO).is_none());
let mut surrogate = public_no_cache.clone();
surrogate.insert(
"surrogate-control",
@@ -308,6 +306,36 @@ mod varnish_compatible_tests {
assert!(plan(StatusCode::OK, &vary, &fallback, Duration::ZERO).is_none());
}
#[test]
fn compatibility_fallback_and_explicit_vcl_ttl_keep_strict_revalidation() {
let mut compatible = Settings::default();
compatible.default_ttl_seconds = 60;
let mut strict = compatible.clone();
strict.varnish_compatible = false;
let response = headers("no-cache");
assert_eq!(plan(StatusCode::OK, &response, &compatible, Duration::ZERO).unwrap().ttl, 60);
assert!(plan(StatusCode::OK, &response, &strict, Duration::ZERO).is_none());
compatible.default_ttl_seconds = 0;
let mut overrides = ResponseOverrides::NONE;
overrides.ttl = Some(25);
let custom = plan_with(StatusCode::OK, &response, &compatible, Duration::ZERO, &overrides)
.expect("explicit vcl ttl in compatibility mode overrides no-cache");
assert_eq!(custom.ttl, 25);
assert!(!custom.requires_revalidation);
assert!(plan_with(StatusCode::OK, &response, &strict, Duration::ZERO, &overrides).is_none());
let empty_headers = HeaderMap::new();
compatible.default_ttl_seconds = 40;
let default_plan = plan(StatusCode::OK, &empty_headers, &compatible, Duration::ZERO)
.expect("compatible default ttl also applies to otherwise eligible headerless 200");
assert_eq!(default_plan.ttl, 40);
assert!(plan(StatusCode::OK, &empty_headers, &strict, Duration::ZERO).is_none());
for blocked in ["no-store", "private"] {
assert!(plan(StatusCode::OK, &headers(blocked), &compatible, Duration::ZERO).is_none());
}
}
#[test]
fn explicit_zero_grace_and_stale_if_error_are_preserved() {
let compatible = Settings::default();
@@ -425,7 +453,7 @@ mod varnish_compatible_tests {
}
#[tokio::test]
async fn positive_fallback_ttl_reuses_only_public_no_cache_entries() {
async fn positive_fallback_ttl_reuses_no_cache_even_without_public() {
let cache = Cache::new(1);
let settings = Settings {
default_ttl_seconds: 75,
@@ -442,7 +470,7 @@ mod varnish_compatible_tests {
)
.unwrap();
let mut response = Response::new(Body::from("public css"));
*response.headers_mut() = headers("public, no-cache");
*response.headers_mut() = headers("no-cache");
let p = plan(
StatusCode::OK,
response.headers(),
@@ -460,7 +488,7 @@ mod varnish_compatible_tests {
.unwrap();
let hit = cache
.get(&ticket)
.expect("explicit public override allows fresh HIT without ETag");
.expect("explicit compatible override allows fresh HIT without public or ETag");
assert!(hit.remaining_ttl > 0);
}
+321 -192
View File
@@ -44,6 +44,7 @@ fn vcl_tokens(source: &str) -> Result<Vec<(VclToken, usize)>> {
}
index += 1;
}
ensure!(index + 1 < bytes.len(), "line {line}: unterminated block comment");
index += 2;
continue;
}
@@ -59,13 +60,36 @@ fn vcl_tokens(source: &str) -> Result<Vec<(VclToken, usize)>> {
continue;
}
if byte == b'"' {
let start = index + 1;
let end = source[start..]
.find('"')
.map(|offset| start + offset)
.ok_or_else(|| anyhow::anyhow!("line {line}: unterminated string"))?;
tokens.push((VclToken::Str(source[start..end].to_owned()), line));
index = end + 1;
// 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();
let mut terminated = false;
while index < bytes.len() {
match bytes[index] {
b'"' => {
index += 1;
terminated = true;
break;
}
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; }
value.push(ch);
index += ch.len_utf8();
}
}
}
ensure!(terminated, "line {string_line}: unterminated string");
tokens.push((VclToken::Str(value), string_line));
continue;
}
if byte.is_ascii_alphabetic() || byte == b'_' {
@@ -431,62 +455,83 @@ fn vcl_atom(
}
}
fn vcl_conditions(
expr: &VclExpr,
stage: RuleStage,
) -> std::result::Result<(RuleMatch, Vec<RuleCondition>), String> {
let single = |expr: &VclExpr| -> std::result::Result<RuleCondition, String> {
match expr {
VclExpr::Atom(tokens) => vcl_atom(tokens, stage, false).map(|atom| atom.condition),
VclExpr::Not(inner) => match inner.as_ref() {
VclExpr::Atom(tokens) => vcl_atom(tokens, stage, true).map(|atom| atom.condition),
_ => Err("negated groups are not supported".into()),
},
_ => Err("nested && / || groups are not supported".into()),
}
};
/// 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,
) -> std::result::Result<Vec<Vec<RuleCondition>>, String> {
match expr {
VclExpr::And(items) => Ok((
RuleMatch::All,
items
.iter()
.map(single)
.collect::<std::result::Result<_, _>>()?,
)),
VclExpr::Or(items) => Ok((
RuleMatch::Any,
items
.iter()
.map(single)
.collect::<std::result::Result<_, _>>()?,
)),
other => Ok((RuleMatch::All, vec![single(other)?])),
VclExpr::Atom(tokens) => Ok(vec![vec![vcl_atom(tokens, stage, negate)?.condition]]),
VclExpr::Not(inner) => vcl_clauses(inner, stage, !negate),
VclExpr::And(items) | VclExpr::Or(items) => {
let product = matches!(expr, VclExpr::And(_)) != negate;
let mut result: Vec<Vec<RuleCondition>> = vec![Vec::new()];
for item in items {
let next = vcl_clauses(item, stage, negate)?;
if product {
let mut joined = Vec::new();
for previous in &result {
for conditions in &next {
if previous.len() + conditions.len() > MAX_RULE_CONDITIONS {
return Err("VCL condition is too complex for cache rules".into());
}
let mut combined = previous.clone();
combined.extend(conditions.iter().cloned());
joined.push(combined);
if joined.len() > MAX_CACHE_RULES {
return Err("VCL condition expansion exceeds rule limit".into());
}
}
}
result = joined;
} else {
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());
}
}
}
Ok(result)
}
}
}
fn query_params_from_regex(pattern: &str) -> Vec<String> {
static CLASS: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
regex::Regex::new(r"\[[^\]]*\][+*]?|\.\*|\.\+").expect("static regex")
});
let simplified = CLASS.replace_all(pattern, "*");
/// 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"(\?|&)(")
.or_else(|| pattern.strip_prefix("([?&])("))?
.strip_suffix(")=[^&]+")
})?;
let mut params = Vec::new();
for token in
simplified.split(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '*')))
{
if token.len() > 64
|| !token
.chars()
.next()
.is_some_and(|c| c.is_ascii_alphabetic())
for part in suffix.split('|') {
let item = if let Some(prefix) = part.strip_suffix("[a-z]+")
.or_else(|| part.strip_suffix("[^=&]*"))
.or_else(|| part.strip_suffix("[^=&]+"))
{
continue;
}
let token = token.to_owned();
if !params.contains(&token) {
params.push(token);
format!("{prefix}*")
} else {
part.to_owned()
};
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'*'))
{
return None;
}
if !params.contains(&item) { params.push(item); }
}
params
(!params.is_empty()).then_some(params)
}
fn vcl_actions(
@@ -504,16 +549,17 @@ fn vcl_actions(
.first()
.map(|word| word.to_ascii_lowercase())
.unwrap_or_default();
let joined = words.join(" ").to_ascii_lowercase();
match (stage, first.as_str()) {
(_, "return") => {
let target = words
.get(2)
.map(|word| word.to_ascii_lowercase())
.unwrap_or_default();
let target = match tokens {
[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" | "pipe") => Ok(vec![RuleAction::Pass]),
(RuleStage::Request, "hash" | "lookup") => Ok(Vec::new()),
(RuleStage::Request, "pass") => Ok(vec![RuleAction::Pass]),
(RuleStage::Request, "hash") => Ok(vec![RuleAction::Lookup]),
(RuleStage::Request, "lookup") => Ok(vec![RuleAction::Lookup]),
(RuleStage::Response, "pass" | "hit_for_pass" | "uncacheable") => {
Ok(vec![RuleAction::NoStore])
}
@@ -523,46 +569,68 @@ fn vcl_actions(
_ => Err(format!("return ({target}) is not supported here")),
}
}
(RuleStage::Request, "unset")
if words
.get(1)
.is_some_and(|word| word.eq_ignore_ascii_case("req.http.cookie")) =>
{
Ok(vec![RuleAction::StripCookies { keep: Vec::new() }])
}
(RuleStage::Request, "set")
if words
.get(1)
.is_some_and(|word| word.eq_ignore_ascii_case("req.url"))
&& joined.contains("regsub") =>
{
let pattern = words
.iter()
.find(|word| word.contains('?') || word.contains('&') || word.contains("utm"))
.cloned()
.unwrap_or_default();
let params = query_params_from_regex(&pattern);
if params.is_empty() {
Err("req.url rewrite not recognised as query parameter removal".into())
(RuleStage::Request, "unset") => {
let target = words.get(1).cloned().unwrap_or_default();
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() }])
} else {
Ok(vec![RuleAction::StripQuery {
params,
keep_only: false,
}])
Err(format!("unset {target} is not supported"))
}
}
(RuleStage::Request, "hash_data") => match words.get(2) {
Some(word)
if word.to_ascii_lowercase().starts_with("req.http.")
&& !word.eq_ignore_ascii_case("req.http.cookie") =>
{
Ok(vec![RuleAction::HashHeader {
name: word[9..].to_owned(),
}])
(RuleStage::Request, "set") => {
let target = words.get(1).cloned().unwrap_or_default();
if target.eq_ignore_ascii_case("req.url") {
let pattern = match tokens {
[VclToken::Ident(_), VclToken::Ident(_), VclToken::Sym("="),
VclToken::Ident(func), VclToken::Sym("("), VclToken::Ident(url),
VclToken::Sym(","), VclToken::Str(pattern), VclToken::Sym(","),
VclToken::Str(replacement), VclToken::Sym(")")]
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 }])
} 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) =>
Ok(vec![RuleAction::SetRequestHeader {
name: target[9..].to_owned(), value: value.clone(),
}]),
_ => Err(format!("set {target} requires a constant string")),
}
} else {
Err(format!("set {target} is not supported"))
}
_ => Err("hash_data is only imported for a single request header".into()),
}
(RuleStage::Request, "hash_data") => match tokens {
[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() }])
}
_ => Err("hash_data supports req.url, req.http.Host or one req.http.<header>".into()),
},
(RuleStage::Response, "set") => {
if tokens.len() != 4 || !matches!(tokens.get(2), Some(VclToken::Sym("="))) {
return Err("set beresp requires exactly one assignment".into());
}
let target = words
.get(1)
.map(|word| word.to_ascii_lowercase())
@@ -578,20 +646,29 @@ fn vcl_actions(
"beresp.uncacheable" if value.eq_ignore_ascii_case("true") => {
Ok(vec![RuleAction::NoStore])
}
"beresp.uncacheable" if value.eq_ignore_ascii_case("false") => {
Ok(vec![RuleAction::AllowStore])
}
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(),
}])
} else {
Err(format!("set {target} requires a constant string"))
}
}
_ => Err(format!("set {target} is not supported")),
}
}
(RuleStage::Response, "unset") => {
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 == "beresp.http.cache-control"
|| word == "beresp.http.expires"
|| word == "beresp.http.pragma" =>
{
Ok(vec![RuleAction::IgnoreCacheControl])
Some(word) if word.starts_with("beresp.http.") => {
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()),
@@ -603,8 +680,8 @@ fn vcl_actions(
.strip_prefix("resp.http.")
.or_else(|| target.strip_prefix("RESP.HTTP."))
.ok_or_else(|| format!("set {target} is not supported"))?;
match (tokens.get(3), tokens.len()) {
(Some(VclToken::Str(value)), 4) => Ok(vec![RuleAction::SetHeader {
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(),
}]),
@@ -614,6 +691,7 @@ fn vcl_actions(
}
}
(RuleStage::Deliver, "unset") => {
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.")
@@ -647,48 +725,73 @@ impl VclBuilder {
fn push(
&mut self,
stage: RuleStage,
match_mode: RuleMatch,
conditions: Vec<RuleCondition>,
guards: &[VclExpr],
actions: Vec<RuleAction>,
stop: bool,
hash_stage: bool,
line: usize,
) {
if actions.is_empty() {
return;
}
if self.rules.len() >= MAX_CACHE_RULES {
self.warnings.push(format!(
"line {line}: rule limit reached, the rest of the 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: id.clone(),
name: format!(
"VCL {} line {line}",
match stage {
RuleStage::Request => "vcl_recv",
RuleStage::Response => "vcl_backend_response",
RuleStage::Deliver => "vcl_deliver",
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;
}
),
enabled: true,
stage,
match_mode,
conditions,
actions,
stop: false,
vhosts: Vec::new(),
};
match compile_rule(&rule, RuleOrigin::Global, "") {
Ok(_) => self.rules.push(rule),
Err(error) => self.warnings.push(format!("line {line}: {error}")),
};
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;
}
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 {
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}")),
}
}
}
@@ -696,71 +799,97 @@ impl VclBuilder {
&mut self,
stage: RuleStage,
statements: &[VclStatement],
inherited: Option<(RuleMatch, Vec<RuleCondition>)>,
guards: &[VclExpr],
hash_stage: bool,
) {
let mut pending: Vec<RuleAction> = Vec::new();
let mut pending_line = 0;
let flush = |builder: &mut Self,
pending: &mut Vec<RuleAction>,
line: usize,
inherited: &Option<(RuleMatch, Vec<RuleCondition>)>| {
let (mode, conditions) = inherited.clone().unwrap_or((RuleMatch::All, Vec::new()));
builder.push(stage, mode, conditions, std::mem::take(pending), line);
};
for statement in statements {
match statement {
VclStatement::Simple(tokens, line) => match vcl_actions(tokens, stage) {
VclStatement::Simple(tokens, line) => match 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)
} {
Ok(actions) => {
if pending.is_empty() {
pending_line = *line;
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]+")))
{
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(")=[^&]+")))
{
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);
}
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; }
}
pending.extend(actions);
}
Err(error) => self.warnings.push(format!("line {line}: {error}")),
},
VclStatement::If(branches, line) => {
flush(self, &mut pending, pending_line, &inherited);
if inherited.is_some() {
self.warnings.push(format!(
"line {line}: nested if is not imported; flatten it into one condition"
));
continue;
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<RuleCondition> = Vec::new();
let mut previous_ok = true;
for (index, (condition, body)) in branches.iter().enumerate() {
let parsed = match condition {
Some(expr) => vcl_conditions(expr, stage),
None => {
if previous.len() == 1 && previous_ok {
let mut negated = previous[0].clone();
negated.negate = !negated.negate;
Ok((RuleMatch::All, vec![negated]))
} else {
Err("else branch after a complex condition is not imported"
.into())
}
}
};
match parsed {
Ok((mode, conditions)) => {
if index == 0 || condition.is_none() {
previous = conditions.clone();
} else {
previous_ok = false;
}
self.statements(stage, body, Some((mode, conditions)));
}
Err(error) => {
previous_ok = false;
self.warnings.push(format!("line {line}: {error}"));
}
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());
}
self.statements(stage, body, &branch_guards, hash_stage);
}
}
}
}
flush(self, &mut pending, pending_line, &inherited);
if !pending.is_empty() {
self.push(stage, guards, pending, false, hash_stage, pending_line);
}
}
}
@@ -795,7 +924,7 @@ pub fn import_vcl(source: &str) -> Result<VclImport> {
match vcl_stage(&name) {
Some(stage) => {
found = true;
builder.statements(stage, &body, None);
builder.statements(stage, &body, &[], name == "vcl_hash");
}
None => builder
.warnings
+17 -2
View File
@@ -7,6 +7,7 @@ pub(super) enum CachePlan {
Enabled {
force_cache: bool,
ignore_cookie: bool,
vcl_cookie_lookup: bool,
},
}
@@ -24,9 +25,21 @@ impl CachePlan {
Self::Enabled {
force_cache,
ignore_cookie: !force_cache && settings.ignore_cookie_for_path(path),
vcl_cookie_lookup: false,
}
}
pub(super) fn with_vcl_cookie_lookup(mut self, allowed: bool) -> Self {
if let Self::Enabled { vcl_cookie_lookup, .. } = &mut self {
*vcl_cookie_lookup = allowed;
}
self
}
pub(super) fn vcl_cookie_lookup(self) -> bool {
matches!(self, Self::Enabled { vcl_cookie_lookup: true, .. })
}
pub(super) fn force_cache(self) -> bool {
matches!(
self,
@@ -61,8 +74,10 @@ impl CachePlan {
Self::Enabled {
force_cache: true, ..
} => crate::cache::forced_request_policy(method, headers, body_empty),
Self::Enabled { .. } => {
crate::cache::request_policy(method, headers, body_empty, path, has_query, settings)
Self::Enabled { vcl_cookie_lookup, .. } => {
crate::cache::request_policy_with_vcl_cookie(
method, headers, body_empty, path, has_query, settings, vcl_cookie_lookup,
)
}
}
}
+14 -23
View File
@@ -127,26 +127,11 @@ 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_pass = false;
if !admin_control_plane && !cache_settings.active_for(route.cache) {
if let Some(rules) = cache_settings
.compiled_rules
.clone()
.filter(|rules| rules.has_deliver_rules())
{
let rule_request = crate::cache::RuleRequest {
host: host.clone(),
path: path.to_string(),
query: request.uri().query().map(str::to_owned),
method: request.method().clone(),
headers: request.headers().clone(),
client_ip: Some(context.client_ip),
};
if let Some(sink) = request.extensions().get::<crate::cache::RuleSink>() {
sink.set(Arc::new(crate::cache::RuleContext { rules, request: rule_request }));
}
}
}
if !admin_control_plane && cache_settings.active_for(route.cache) {
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 {
host: host.clone(),
@@ -158,6 +143,7 @@ if !admin_control_plane && cache_settings.active_for(route.cache) {
};
let outcome = rules.evaluate_request(&rule_request, true);
if !outcome.matched.is_empty() {
outcome.apply_headers(request.headers_mut());
outcome.rewrite_cookies(request.headers_mut());
cache_rule_query = outcome.rewrite_query(request.uri().query());
if let Some(query) = &cache_rule_query {
@@ -175,6 +161,7 @@ if !admin_control_plane && cache_settings.active_for(route.cache) {
}
cache_rule_variant = outcome.hash_variant();
cache_rule_pass = outcome.pass.is_some();
cache_rule_lookup = outcome.lookup.is_some();
rule_request.headers = request.headers().clone();
rule_request.query = request.uri().query().map(str::to_owned);
}
@@ -239,9 +226,10 @@ let cache_plan = cache_plan::CachePlan::new(policy_reason, cache_settings, &path
.frontend
.as_ref()
.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();
let ignore_static_cookie = cache_plan.ignore_cookie();
// 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,
request.uri().query().is_some(), cache_settings,
@@ -333,7 +321,10 @@ let effective_policy = cache_plan::combine_policy(original_policy, || {
request.uri().query().is_some(), cache_settings,
)
});
let force_vary_cookie = force_cache && request.headers().contains_key(::http::header::COOKIE);
// 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 effective_reason = effective_policy.bypass_reason();
let revalidation_reason = effective_policy.revalidation_reason();
+5 -1
View File
@@ -168,7 +168,11 @@ if let (Some(ticket), Some(plan), Some(transformed)) =
cache_settings,
fill_leader.take(),
);
if cache_settings.proactive_refresh_enabled && proactive_remaining_ttl > 0 {
// Avoid refreshing a cookie/credential-keyed entry without its original
// VCL variation context: proactive refresh must never collapse users.
if cache_settings.proactive_refresh_enabled && proactive_remaining_ttl > 0
&& !force_vary_cookie && !force_vary_authorization
{
schedule_proactive_refresh(
CacheRefreshContext {
state: state.clone(),
+18 -6
View File
@@ -112,12 +112,24 @@ if handshake.as_ref().is_some_and(|handshake| {
"RustProxy: HTTP/1.1 WebSocket upstream returned 2xx without switching protocols\n",
);
}
let cache_rule_overrides = match (&cache_rule_context, cache_ticket.is_some()) {
(Some(rule_context), true) => rule_context.response_overrides(response.status(), response.headers()),
_ => crate::cache::ResponseOverrides::NONE,
};
if cache_rule_overrides.strip_set_cookie {
response.headers_mut().remove(::http::header::SET_COOKIE);
let 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);
}
}
}
let origin_status = response.status();
crate::cache::normalize_static_cookie_vary(
+1 -3
View File
@@ -386,9 +386,7 @@ async fn refresh_cache_once(
.map(|rules| rules.response_overrides(origin.status(), origin.headers()))
.unwrap_or(crate::cache::ResponseOverrides::NONE);
let mut origin = origin;
if rule_overrides.strip_set_cookie {
origin.headers_mut().remove(::http::header::SET_COOKIE);
}
rule_overrides.apply_headers(origin.headers_mut());
let Some(origin_plan) = crate::cache::plan_with(
origin.status(),
origin.headers(),