This commit is contained in:
Mateusz Gruszczyński committed 2026-11-20 20:54:40 +01:00
1 parent 53d92e0da6
commit 08d1608ef5
21 files changed
+928 -408

No files matched your search

+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/CACHE_TEMPLATE_LIBRARY.md", "guides"),
reader_doc!("docs/VCL.md", "guides"),
reader_doc!("docs/VCL_SUPPORT_MATRIX.md", "guides"),
reader_doc!("docs/VCL_TRAFFIC_COOKBOOK.md", "guides"),
+1 -1
View File
@@ -8865,7 +8865,7 @@
"maxItems": 16,
"items": {
"type": "object",
"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).",
"description": "type: pass, lookup (VCL return(hash), Cookie exception in Varnish-compatible mode), strip_cookies{keep}, remove_named_cookies{names} (exact-name removal; sessions and unknown cookies remain), 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)."
+222 -20
View File
@@ -18,11 +18,11 @@ window.rustProxyCacheRules = (() => {
response_header: { ops: ["exists", "equals", "contains", "regex"], name: true, stages: ["response", "deliver"] },
};
const ACTIONS = {
request: ["pass", "lookup", "strip_cookies", "strip_query", "hash_header", "hash_cookie", "set_request_header", "remove_request_header"],
request: ["pass", "lookup", "strip_cookies", "remove_named_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: "request_routing", lookup: "request_routing", strip_cookies: "request_cookies", strip_query: "request_query", ttl: "ttl", grace: "grace", no_store: "store", allow_store: "store" };
const ASPECTS = { pass: "request_routing", lookup: "request_routing", strip_cookies: "request_cookies", remove_named_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);
@@ -84,6 +84,7 @@ window.rustProxyCacheRules = (() => {
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 "remove_named_cookies": return `remove_req_cookies(${(a.names || []).map(name => `"${esc(name)}"`).join(", ")});`;
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"));`;
@@ -121,6 +122,8 @@ window.rustProxyCacheRules = (() => {
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.");
if (rule.actions.some(a => a.type === "remove_named_cookies"))
limits.push("remove_req_cookies() is a RustProxy extension, not standard Varnish VCL.");
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, "")}`;
@@ -148,6 +151,7 @@ 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 === "remove_named_cookies") return `${actionLabel(a.type)}: ${(a.names || []).join(", ")}`;
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);
@@ -159,6 +163,21 @@ window.rustProxyCacheRules = (() => {
for (const [unit, size] of [...durationUnits].reverse()) if (seconds >= size && seconds % size === 0) return `${seconds / size}${unit}`;
return `${seconds}s`;
}
// These are ordinary graphical rules, not a separate VCL engine. Keep
// privacy boundaries fail-closed: rules which can increase cache reuse or
// alter downstream caching start disabled until the operator reviews them.
const templatePass = (label, conditions, match = "all") => ({
name: t(label), stage: "request", match, conditions,
actions: [{ type: "pass" }], stop: true,
});
const templatePath = (value) => ({ field: "path", operator: "regex", values: [value] });
const templateResponse = (label, conditions, actions, enabled = false) => ({
name: t(label), stage: "response", match: "all", conditions, actions, enabled,
});
const templateDeliver = (label, conditions, actions, enabled = true) => ({
name: t(label), stage: "deliver", match: "all", conditions, actions, enabled,
});
const protectedPaths = "^/(?:admin|auth|login|logout|user|users|account|profile|settings|dashboard|cart|checkout|orders|billing|payment)(?:/|[?]|$)";
const TEMPLATES = {
wordpress: () => [{ name: t("cacheRuleTplWordpress"), stage: "request", match: "any", conditions: [{ field: "path", operator: "regex", values: ["^/(wp-admin|wp-login\\.php|xmlrpc\\.php|wp-json)"] }, { field: "header", name: "cookie", operator: "regex", values: ["wordpress_logged_in_|comment_author_|woocommerce_items_in_cart|wp-postpass_"] }], actions: [{ type: "pass" }] }],
static: () => [
@@ -177,9 +196,9 @@ window.rustProxyCacheRules = (() => {
{ name: t("cacheRuleTplCdnRemaining"), stage: "request", match: "all", conditions: [{ field: "header", name: "Cookie", operator: "exists" }], actions: [{ type: "pass" }], stop: true },
];
},
// Opt-in for a verified public vhost. Do not try to infer the Cookie
// Domain: it is absent from the HTTP Cookie request header. Disabled by
// default; the operator must review the private-path exclusions first.
// Separate from the CDN template: remove only explicitly named cookies
// confirmed to be irrelevant to this Vhost. HTTP Cookie has no Domain
// attribute, so no origin inference or wildcard session-cookie removal.
publiccookies: () => [{
name: t("cacheRuleTplPubliccookies"), enabled: false, stage: "request", match: "all",
conditions: [
@@ -188,7 +207,7 @@ window.rustProxyCacheRules = (() => {
{ field: "header", name: "Authorization", operator: "exists", negate: true },
{ field: "path", operator: "regex", values: ["^/(admin|api|auth|login|logout|account|profile|user|settings|dashboard|cart|checkout|panel|konto|wp-admin|wp-login[.]php)(/|[?]|$)"], negate: true },
],
actions: [{ type: "strip_cookies", keep: [] }, { type: "lookup" }], stop: true,
actions: [{ type: "remove_named_cookies", names: ["REPLACE_WITH_VERIFIED_PARENT_COOKIE_NAME"] }], stop: false,
}],
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" }] }],
@@ -199,7 +218,110 @@ window.rustProxyCacheRules = (() => {
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" }] }],
security: () => [{ name: t("cacheRuleTplSecurity"), stage: "deliver", match: "all", conditions: [], actions: [{ type: "default_header", name: "X-Content-Type-Options", value: "nosniff" }, { type: "default_header", name: "Referrer-Policy", value: "strict-origin-when-cross-origin" }] }],
// Safety and authenticated traffic. No rule below removes unknown cookies.
safemethods: () => [templatePass("cacheRuleTplSafemethods", [{ field: "method", operator: "equals", values: ["GET", "HEAD"], negate: true }])],
authbypass: () => [templatePass("cacheRuleTplAuthbypass", [{ field: "header", name: "Authorization", operator: "exists" }])],
cookiepass: () => [templatePass("cacheRuleTplCookiepass", [{ field: "header", name: "Cookie", operator: "exists" }])],
sessioncookies: () => [templatePass("cacheRuleTplSessioncookies", [{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:session|sessionid|PHPSESSID|laravel_session|connect[.]sid|sid)="] }])],
privateroutes: () => [
templatePass("cacheRuleTplPrivateroutesPass", [templatePath(protectedPaths)]),
templateResponse("cacheRuleTplPrivateroutesStore", [templatePath(protectedPaths)], [{ type: "no_store" }], true),
templateDeliver("cacheRuleTplPrivateroutesBrowser", [templatePath(protectedPaths)], [{ type: "set_header", name: "Cache-Control", value: "private, no-store" }]),
],
preview: () => [templatePass("cacheRuleTplPreview", [
templatePath("^/(?:preview|draft)(?:/|[?]|$)"),
{ field: "query", name: "preview", operator: "exists" },
{ field: "query", name: "draft", operator: "exists" },
], "any")],
checkout: () => [templatePass("cacheRuleTplCheckout", [templatePath("^/(?:cart|checkout|payment|billing|orders?)(?:/|[?]|$)")])],
webhooks: () => [templatePass("cacheRuleTplWebhooks", [templatePath("^/(?:webhooks?|callbacks?|hooks)(?:/|[?]|$)")])],
healthchecks: () => [templatePass("cacheRuleTplHealthchecks", [templatePath("^/(?:health|healthz|readyz|livez|metrics|status)(?:/|[?]|$)")])],
graphql: () => [templatePass("cacheRuleTplGraphql", [templatePath("^/graphql(?:/|[?]|$)")])],
streaming: () => [templatePass("cacheRuleTplStreaming", [
{ field: "header", name: "Accept", operator: "contains", values: ["text/event-stream"] },
{ field: "header", name: "Upgrade", operator: "exists" },
], "any")],
signedurls: () => [templatePass("cacheRuleTplSignedurls", [
...["token", "access_token", "signature", "sig", "auth_token"].map(name => ({ field: "query", name, operator: "exists" })),
], "any")],
// Framework-specific guards are independent from the CDN allowlist.
woocommerce: () => [templatePass("cacheRuleTplWoocommerce", [
templatePath("^/(?:cart|checkout|my-account)(?:/|[?]|$)"),
{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:wordpress_logged_in_[^=;]*|woocommerce_items_in_cart|wp_woocommerce_session_[^=;]*|woocommerce_cart_hash)="] },
], "any")],
django: () => [templatePass("cacheRuleTplDjango", [{ field: "cookie", name: "sessionid", operator: "exists" }])],
laravel: () => [templatePass("cacheRuleTplLaravel", [{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:laravel_session|PHPSESSID)="] }])],
authjs: () => [templatePass("cacheRuleTplAuthjs", [{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:__Secure-)?(?:next-auth[.]session-token|authjs[.]session-token)="] }])],
aspnet: () => [templatePass("cacheRuleTplAspnet", [{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:[.]AspNetCore[.]Cookies|ASP[.]NET_SessionId)="] }])],
drupal: () => [templatePass("cacheRuleTplDrupal", [{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:S?SESS[a-fA-F0-9]+)="] }])],
// Cache acceleration must be opt-in: names, routes, representation privacy,
// Vary, and origin Cache-Control must be checked before activation.
publicjson: () => [templateResponse("cacheRuleTplPublicjson", [
{ field: "path", operator: "prefix", values: ["/api/public/"] },
{ field: "status", operator: "equals", values: ["200"] },
{ field: "content_type", operator: "prefix", values: ["application/json"] },
], [{ type: "ttl", seconds: 60 }, { type: "grace", seconds: 30 }])],
publicpages: () => [templateResponse("cacheRuleTplPublicpages", [
templatePath("^/(?:blog|news|articles|catalog|products)(?:/|[?]|$)"),
{ field: "status", operator: "equals", values: ["200"] },
{ field: "content_type", operator: "prefix", values: ["text/html"] },
], [{ type: "ttl", seconds: 300 }, { type: "grace", seconds: 60 }])],
feeds: () => [templateResponse("cacheRuleTplFeeds", [
templatePath("^/(?:feed|rss|rss[.]xml|atom[.]xml)(?:/|[?]|$)"),
{ field: "status", operator: "equals", values: ["200"] },
], [{ type: "ttl", seconds: 600 }])],
sitemap: () => [templateResponse("cacheRuleTplSitemap", [
templatePath("^/(?:sitemap(?:_index)?[.]xml|sitemap/)") ,
{ field: "status", operator: "equals", values: ["200"] },
], [{ type: "ttl", seconds: 3600 }])],
hashedassets: () => [templateResponse("cacheRuleTplHashedassets", [
templatePath("^/(?:assets|static|build)/[^?]*[.-][a-zA-Z0-9_-]{8,}[.](?:js|mjs|css|png|webp|avif|svg|woff2?)(?:[?]|$)"),
{ field: "status", operator: "equals", values: ["200"] },
], [{ type: "ttl", seconds: 31536000 }])],
imagecache: () => [templateResponse("cacheRuleTplImagecache", [
{ field: "extension", operator: "equals", values: ["png", "jpg", "jpeg", "webp", "avif", "gif", "svg"] },
{ field: "status", operator: "equals", values: ["200"] },
], [{ type: "ttl", seconds: 86400 }])],
fontcache: () => [templateResponse("cacheRuleTplFontcache", [
{ field: "extension", operator: "equals", values: ["woff", "woff2", "ttf", "otf"] },
{ field: "status", operator: "equals", values: ["200"] },
], [{ type: "ttl", seconds: 2592000 }])],
searchttl: () => [templateResponse("cacheRuleTplSearchttl", [
{ field: "path", operator: "prefix", values: ["/search"] },
{ field: "status", operator: "equals", values: ["200"] },
], [{ type: "ttl", seconds: 15 }])],
// Cache blocking AND browser no-store are separate stages: a deliver rule
// alone cannot prevent a shared-cache HIT. Purge old objects on activation.
nocachehtml: () => [
templateResponse("cacheRuleTplNocachehtmlResponse", [{ field: "content_type", operator: "prefix", values: ["text/html"] }], [{ type: "no_store" }], true),
templateDeliver("cacheRuleTplNocachehtmlDeliver", [{ field: "content_type", operator: "prefix", values: ["text/html"] }], [{ type: "set_header", name: "Cache-Control", value: "no-store" }]),
],
privateapi: () => [
templatePass("cacheRuleTplPrivateapiPass", [{ field: "path", operator: "prefix", values: ["/api/private/"] }]),
templateResponse("cacheRuleTplPrivateapiStore", [{ field: "path", operator: "prefix", values: ["/api/private/"] }], [{ type: "no_store" }], true),
templateDeliver("cacheRuleTplPrivateapiBrowser", [{ field: "path", operator: "prefix", values: ["/api/private/"] }], [{ type: "set_header", name: "Cache-Control", value: "private, no-store" }]),
],
privatedownloads: () => [
{ ...templatePass("cacheRuleTplPrivatedownloadsPass", [{ field: "path", operator: "prefix", values: ["/private-downloads/"] }]), enabled: false },
templateDeliver("cacheRuleTplPrivatedownloadsBrowser", [{ field: "path", operator: "prefix", values: ["/private-downloads/"] }], [{ type: "set_header", name: "Cache-Control", value: "private, no-store" }], false),
],
stagingnoindex: () => [templateDeliver("cacheRuleTplStagingnoindex", [], [{ type: "default_header", name: "X-Robots-Tag", value: "noindex, nofollow" }], false)],
frameguard: () => [templateDeliver("cacheRuleTplFrameguard", [], [{ type: "default_header", name: "X-Frame-Options", value: "SAMEORIGIN" }], false)],
};
// Display order is deliberate. Parent-domain cookie cleanup stays a
// distinct template and can be inserted before CDN strip/pass guards.
const TEMPLATE_GROUPS = [
{ id: "privacy", keys: ["safemethods", "authbypass", "cookiepass", "sessioncookies", "privateroutes", "preview", "checkout", "webhooks", "healthchecks", "graphql", "streaming", "signedurls", "nocachehtml", "privateapi", "privatedownloads"] },
{ id: "frameworks", keys: ["wordpress", "woocommerce", "django", "laravel", "authjs", "aspnet", "drupal"] },
{ id: "cookies", keys: ["cdn", "publiccookies"] },
{ id: "public", keys: ["publicjson", "publicpages", "feeds", "sitemap", "hashedassets", "imagecache", "fontcache", "searchttl", "static", "tracking"] },
{ id: "variants", keys: ["language"] },
{ id: "delivery", keys: ["headers", "browser", "nobrowser", "security", "stagingnoindex", "frameguard"] },
{ id: "other", keys: ["api"] },
];
const templateName = key => t(key === "nobrowser" ? "cacheRuleTplNoBrowser" : `cacheRuleTpl${key[0].toUpperCase()}${key.slice(1)}`);
const templateHelp = key => t(`cacheRuleTplHelp${key[0].toUpperCase()}${key.slice(1)}`);
const templateAvailable = (key, scope) => scope === "vhost" || key !== "publiccookies";
function applicableGlobals(vhostId) {
return (envelope?.config?.cache?.rules || []).filter(rule => rule.enabled !== false && (!rule.vhosts?.length || rule.vhosts.includes(vhostId)));
}
@@ -287,15 +409,42 @@ window.rustProxyCacheRules = (() => {
helpLinks.append(guide, docs);
root.append(helpLinks);
}
const templates = select([["", t("cacheRulesTemplates")], ...Object.keys(TEMPLATES).filter(key => scope === "vhost" || key !== "publiccookies").map(key => [key, t(`cacheRuleTpl${key[0].toUpperCase()}${key.slice(1)}`)])], "", t("cacheRulesTemplates"));
const templates = el("select");
const placeholder = el("option", t("cacheRulesTemplates")); placeholder.value = "";
templates.append(placeholder);
for (const group of TEMPLATE_GROUPS) {
const visible = group.keys.filter(key => templateAvailable(key, scope));
if (!visible.length) continue;
const optgroup = document.createElement("optgroup");
optgroup.label = t(`cacheRuleTplGroup${group.id[0].toUpperCase()}${group.id.slice(1)}`);
for (const key of visible) {
const option = el("option", templateName(key));
option.value = key;
option.title = templateHelp(key);
optgroup.append(option);
}
templates.append(optgroup);
}
templates.setAttribute("aria-label", t("cacheRulesTemplates"));
templates.classList.add("cache-rules-templates");
const browseButton = el("button", t("cacheRuleCatalogBrowse"), "outline");
browseButton.type = "button"; browseButton.setAttribute("aria-expanded", "false");
const importButton = el("button", t("cacheRulesImportVcl"), "outline"); importButton.type = "button";
const exportButton = el("button", t("cacheRulesExportVcl"), "outline"); exportButton.type = "button";
const addButton = el("button", t("cacheRulesAdd"), "primary"); addButton.type = "button";
toolbar.append(templates, importButton, exportButton, addButton);
toolbar.append(templates, browseButton, importButton, exportButton, addButton);
const ignoreWrap = el("label", undefined, "check cache-rules-ignore"), ignoreBox = el("input", undefined, "switch"); ignoreBox.type = "checkbox"; ignoreBox.checked = ignoreGlobal; if (options.ignoreId !== "") ignoreBox.id = options.ignoreId || "vh-cache-ignore-global-rules";
ignoreWrap.append(ignoreBox, el("span", t("cacheRulesIgnoreGlobal")));
const notices = el("div", undefined, "cache-rules-notices");
const catalog = el("section", undefined, "cache-rule-catalog"); catalog.hidden = true;
const catalogHeading = el("h4", t("cacheRuleCatalogTitle"));
const catalogNote = el("p", t("cacheRuleCatalogHelp"), "fine");
const catalogSearch = el("input", undefined, "cache-rule-catalog-search");
catalogSearch.type = "search";
catalogSearch.placeholder = t("cacheRuleCatalogSearch");
catalogSearch.setAttribute("aria-label", t("cacheRuleCatalogSearch"));
const catalogGroups = el("div", undefined, "cache-rule-catalog-groups");
catalog.append(catalogHeading, catalogNote, catalogSearch, catalogGroups);
const list = el("div", undefined, "cache-rules-list");
const empty = el("p", t(scope === "vhost" ? "cacheRulesEmptyVhost" : "cacheRulesEmpty"), "fine cache-rules-empty");
const importBox = el("div", undefined, "cache-rules-import"); importBox.hidden = true;
@@ -322,8 +471,8 @@ window.rustProxyCacheRules = (() => {
const tester = buildTester();
root.append(toolbar);
if (scope === "vhost") root.append(ignoreWrap);
root.append(notices, importBox, list, empty, exportBox, tester.node);
for (const isolated of [tester.node, importBox]) for (const type of ["input", "change"]) isolated.addEventListener(type, event => event.stopPropagation());
root.append(notices, catalog, importBox, list, empty, exportBox, tester.node);
for (const isolated of [tester.node, importBox, catalog]) for (const type of ["input", "change"]) isolated.addEventListener(type, event => event.stopPropagation());
root.addEventListener("keydown", event => { if (event.key === "Enter" && event.target.matches?.("input:not([type=checkbox])")) event.preventDefault(); });
function taken() { return new Set(rules.map(rule => rule.id)); }
if (scope === "global") {
@@ -462,6 +611,7 @@ window.rustProxyCacheRules = (() => {
const nameInput = placeholder => { const node = textInput(action.name, placeholder); node.addEventListener("input", () => { action.name = node.value.trim(); changed(); }); return node; };
switch (action.type) {
case "strip_cookies": params.append(listInput("keep", t("cacheRuleKeepCookies"))); break;
case "remove_named_cookies": params.append(listInput("names", t("cacheRuleRemoveNamedCookies"))); break;
case "strip_query": {
const keepOnly = el("label", undefined, "check"), box = el("input", undefined, "switch"); box.type = "checkbox"; box.checked = !!action.keep_only; keepOnly.append(box, el("span", t("cacheRuleKeepOnly")));
box.addEventListener("change", () => { action.keep_only = box.checked; changed(); });
@@ -554,17 +704,69 @@ window.rustProxyCacheRules = (() => {
node.append(bodyWrap);
return { node };
}
function addRules(items) {
const ids = taken(); let added = 0;
for (const item of items) {
if (rules.length >= MAX_RULES) { toast(t("cacheRulesLimit"), true); break; }
function addRules(items, templateKey = "") {
if (rules.length + items.length > MAX_RULES) { toast(t("cacheRulesLimit"), true); return 0; }
const ids = taken();
const addedRules = items.map(item => {
const rule = normalize({ ...item, id: slug(item.id || item.name, ids), vhosts: scope === "global" ? item.vhosts || [] : [] });
ids.add(rule.id); rules.push(rule); added++;
}
render(); if (added) changed();
return added;
ids.add(rule.id);
return rule;
});
// The parent-name rule must execute before the independent CDN cookie
// strip / remaining-cookie pass checks; never move or merge CDN rules.
const cdnIndex = templateKey === "publiccookies" ? rules.findIndex(rule =>
/^CDN:/.test(rule.name || "") && rule.conditions.some(c => c.field === "header" && String(c.name || "").toLowerCase() === "cookie") &&
rule.actions.some(a => a.type === "strip_cookies" || a.type === "pass")) : -1;
if (cdnIndex >= 0) rules.splice(cdnIndex, 0, ...addedRules);
else rules.push(...addedRules);
if (addedRules.length) open.add(addedRules[0].id);
render();
if (addedRules.length) changed();
return addedRules.length;
}
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)); });
function addTemplate(key) {
const make = TEMPLATES[key];
if (!make || !templateAvailable(key, scope)) return;
const items = make(), added = addRules(items, key);
if (!added) return;
const needsReview = items.some(item => item.enabled === false);
toast(t(needsReview ? "cacheRuleCatalogAddedDisabled" : "cacheRulesTemplateAdded").replace("{count}", added));
}
function renderCatalog() {
catalogGroups.replaceChildren();
const query = catalogSearch.value.trim().toLocaleLowerCase();
let shown = 0;
for (const group of TEMPLATE_GROUPS) {
const matches = group.keys.filter(key => templateAvailable(key, scope) &&
(!query || `${templateName(key)} ${templateHelp(key)} ${t(`cacheRuleTplGroup${group.id[0].toUpperCase()}${group.id.slice(1)}`)}`.toLocaleLowerCase().includes(query)));
if (!matches.length) continue;
const section = el("section", undefined, "cache-rule-catalog-group");
section.append(el("h5", t(`cacheRuleTplGroup${group.id[0].toUpperCase()}${group.id.slice(1)}`)));
for (const key of matches) {
const card = el("div", undefined, "cache-rule-catalog-card");
const copy = el("div", undefined, "cache-rule-catalog-card-copy");
const heading = el("strong", templateName(key));
const description = el("p", templateHelp(key), "fine");
copy.append(heading, description);
if (TEMPLATES[key]().some(rule => rule.enabled === false))
copy.append(el("span", t("cacheRuleCatalogReview"), "cache-rule-catalog-review"));
const add = el("button", t("cacheRuleCatalogAdd"), "outline");
add.type = "button";
add.setAttribute("aria-label", `${t("cacheRuleCatalogAdd")}: ${templateName(key)}`);
add.addEventListener("click", () => addTemplate(key));
card.append(copy, add); section.append(card); shown++;
}
catalogGroups.append(section);
}
if (!shown) catalogGroups.append(el("p", t("cacheRuleCatalogEmpty"), "fine"));
}
browseButton.addEventListener("click", () => {
catalog.hidden = !catalog.hidden;
browseButton.setAttribute("aria-expanded", String(!catalog.hidden));
if (!catalog.hidden) { renderCatalog(); catalogSearch.focus(); }
});
catalogSearch.addEventListener("input", renderCatalog);
templates.addEventListener("change", () => { const key = templates.value; templates.value = ""; addTemplate(key); });
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) resetImportPreview(); else importText.focus(); });
importCancel.addEventListener("click", () => { importBox.hidden = true; resetImportPreview(); });
@@ -627,5 +829,5 @@ window.rustProxyCacheRules = (() => {
if (options.autoLoadHits !== false) void refreshHits();
return { node: root, read, ignoreGlobal: () => ignoreGlobal, set(next) { rules = (next || []).map(normalize); open = new Set(); render(); }, refreshHits };
}
return { create, exportVcl, TEMPLATES };
return { create, exportVcl, TEMPLATES, TEMPLATE_GROUPS };
})();
+59
View File
@@ -2470,6 +2470,65 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
margin-left: auto;
}
/* Searchable, grouped one-click cache/VCL rule library. The native select
above remains for quick keyboard access and existing editor workflows. */
.cache-rule-catalog {
display: grid;
gap: 10px;
padding: 14px;
border: 1px solid var(--line);
border-radius: var(--rp-radius-surface, 0px);
background: var(--panel2);
min-width: 0;
}
.cache-rule-catalog>h4,
.cache-rule-catalog>p,
.cache-rule-catalog-card p { margin: 0; }
.cache-rule-catalog-search { width: min(100%, 480px); }
.cache-rule-catalog-groups {
max-height: 540px;
overflow: auto;
display: grid;
gap: 14px;
padding-right: 4px;
}
.cache-rule-catalog-group { display: grid; gap: 7px; min-width: 0; }
.cache-rule-catalog-group>h5 { margin: 0; font-size: 13px; }
.cache-rule-catalog-card {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 9px 11px;
border: 1px solid var(--line);
border-radius: var(--rp-radius-surface, 0px);
background: var(--panel);
min-width: 0;
}
.cache-rule-catalog-card-copy {
display: grid;
gap: 3px;
min-width: 0;
overflow-wrap: anywhere;
}
.cache-rule-catalog-card-copy strong { font-size: 13px; line-height: 1.4; }
.cache-rule-catalog-card-copy p { font-size: 12px; }
.cache-rule-catalog-review { color: var(--accent); font-size: 11px; }
.cache-rule-catalog-card>button { flex: 0 0 auto; }
@media (max-width: 540px) {
.cache-rule-catalog { padding: 9px; }
.cache-rule-catalog-card { align-items: flex-start; }
}
.cache-rules-notices {
display: grid;
gap: 4px;
+66 -17
View File
@@ -154,6 +154,8 @@ pub enum RuleAction {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
keep: Vec<String>,
},
/// Remove only explicitly named cookies; retain unknown/session cookies.
RemoveNamedCookies { names: Vec<String> },
StripQuery {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
params: Vec<String>,
@@ -201,6 +203,7 @@ impl RuleAction {
| Self::SetRequestHeader { .. }
| Self::RemoveRequestHeader { .. }
| Self::StripCookies { .. }
| Self::RemoveNamedCookies { .. }
| Self::StripQuery { .. }
| Self::HashHeader { .. }
| Self::HashCookie { .. } => RuleStage::Request,
@@ -220,7 +223,7 @@ impl RuleAction {
fn aspect(&self) -> Option<&'static str> {
match self {
Self::Pass | Self::Lookup => Some("request_routing"),
Self::StripCookies { .. } => Some("request_cookies"),
Self::StripCookies { .. } | Self::RemoveNamedCookies { .. } => Some("request_cookies"),
Self::StripQuery { .. } => Some("request_query"),
Self::Ttl { .. } => Some("ttl"),
Self::Grace { .. } => Some("grace"),
@@ -578,6 +581,12 @@ fn validate_action(action: &RuleAction) -> Result<()> {
"invalid cookie name"
);
}
RuleAction::RemoveNamedCookies { names } => {
ensure!(!names.is_empty() && names.len() <= MAX_RULE_VALUES,
"remove_named_cookies requires 1 to 64 exact cookie names");
ensure!(names.iter().all(|name| valid_cookie_name(name)),
"invalid cookie name");
}
RuleAction::StripQuery { params, keep_only } => {
ensure!(
!params.is_empty() || !keep_only,
@@ -960,6 +969,8 @@ pub struct RequestRuleOutcome {
/// to the rule evaluation copy.
pub header_edits: Vec<BackendHeaderEdit>,
pub strip_cookies: Option<Vec<String>>,
/// Exact names removed without discarding unrelated session cookies.
pub remove_named_cookies: Vec<String>,
pub query_edits: Vec<(Vec<String>, bool)>,
pub hash: Vec<String>,
pub matched: Vec<RuleMatchInfo>,
@@ -1142,6 +1153,14 @@ impl CompiledRules {
}
outcome.rewrite_cookies(&mut current.headers);
}
RuleAction::RemoveNamedCookies { names } => {
for name in names {
if !outcome.remove_named_cookies.contains(name) {
outcome.remove_named_cookies.push(name.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()) {
@@ -1325,24 +1344,54 @@ impl RequestRuleOutcome {
}
}
pub fn rewrite_cookies(&self, headers: &mut HeaderMap) {
let Some(keep) = &self.strip_cookies else {
return;
};
let kept: Vec<String> = cookie_values(headers)
.filter(|(name, _)| keep.iter().any(|item| item == name))
.map(|(name, value)| {
if value.is_empty() {
name.to_owned()
} else {
format!("{name}={value}")
if self.remove_named_cookies.is_empty() {
// Preserve the pre-existing keep-list behavior for unchanged rules.
let Some(keep) = &self.strip_cookies else { return; };
let kept: Vec<String> = cookie_values(headers)
.filter(|(name, _)| keep.iter().any(|item| item == name))
.map(|(name, value)| {
if value.is_empty() { name.to_owned() }
else { format!("{name}={value}") }
})
.collect();
headers.remove(http::header::COOKIE);
if !kept.is_empty() {
if let Ok(value) = HeaderValue::from_str(&kept.join("; ")) {
headers.insert(http::header::COOKIE, value);
}
})
.collect();
headers.remove(http::header::COOKIE);
if !kept.is_empty() {
if let Ok(value) = HeaderValue::from_str(&kept.join("; ")) {
headers.insert(http::header::COOKIE, value);
}
return;
}
// Fail closed: never delete an unknown or malformed Cookie field while
// removing selected parent-domain names. Leave it for later pass rules
// or RustProxy's request_cookie policy to reject.
let mut kept = Vec::new();
for header in headers.get_all(http::header::COOKIE).iter() {
let Ok(raw) = header.to_str() else { return; };
for part in raw.split(';') {
let Some((name, value)) = part.trim().split_once('=') else { return; };
// Do not normalize whitespace *inside* a cookie name: a
// malformed/lookalike name must stay present and bypass.
if !valid_cookie_name(name) { return; }
if self.remove_named_cookies.iter().any(|removed| removed == name) {
continue;
}
if self.strip_cookies.as_ref().is_some_and(|allow| !allow.iter().any(|item| item == name)) {
continue;
}
kept.push(format!("{name}={value}"));
}
}
let replacement = if kept.is_empty() { None } else {
match HeaderValue::from_str(&kept.join("; ")) {
Ok(value) => Some(value),
Err(_) => return,
}
};
headers.remove(http::header::COOKIE);
if let Some(value) = replacement {
headers.insert(http::header::COOKIE, value);
}
}
pub fn rewrite_query(&self, query: Option<&str>) -> Option<Option<String>> {
+92 -40
View File
@@ -1063,68 +1063,120 @@ sub vcl_deliver {
}
#[test]
fn vcl_public_vhost_template_strips_inherited_cookies_only_on_public_get_head() {
let vcl = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/examples/vcl/public-vhost-ignore-cookies.vcl"
));
let imported = import_vcl(vcl).unwrap();
assert!(imported.warnings.is_empty(), "{:?}", imported.warnings);
assert!(!imported.rules.is_empty());
validate_rules(&imported.rules, false).unwrap();
let compiled = CompiledRules::compile("public", &imported.rules, &[], false).unwrap();
fn vcl_parent_cookie_names_run_before_separate_cdn_template_without_losing_sessions() {
let parent = include_str!(concat!(env!("CARGO_MANIFEST_DIR"),
"/examples/vcl/public-vhost-remove-parent-cookies.vcl"))
.replace("REPLACE_WITH_VERIFIED_PARENT_COOKIE_NAME", "parent_marketing");
let cdn = include_str!(concat!(env!("CARGO_MANIFEST_DIR"),
"/examples/vcl/cdn-technical-cookies.vcl"));
let imported_parent = import_vcl(&parent).unwrap();
assert!(imported_parent.warnings.is_empty(), "{:?}", imported_parent.warnings);
validate_rules(&imported_parent.rules, false).unwrap();
assert!(imported_parent.rules.iter().any(|rule| rule.actions.iter().any(|action|
matches!(action, RuleAction::RemoveNamedCookies { names }
if names.len() == 1 && names[0] == "parent_marketing"))));
assert!(!imported_parent.rules.iter().any(|rule|
rule.actions.iter().any(|action| matches!(action, RuleAction::Lookup | RuleAction::StripCookies { .. }))));
for cookie in [
"sso_session=secret",
"sso_session=secret; marketing_id=xyz",
"tracking=one; unknown=two",
// Combine the *separate* examples in the same Vhost rule order. A
// parent+CDN mix must cache, while a parent+session mix must pass.
let combined = import_vcl(&format!("{parent}\n{cdn}")).unwrap();
assert!(combined.warnings.is_empty(), "{:?}", combined.warnings);
validate_rules(&combined.rules, false).unwrap();
let compiled = CompiledRules::compile("public", &combined.rules, &[], false).unwrap();
for (cookie, forwarded_cookie, bypass) in [
("parent_marketing=1", None, false),
("parent_marketing=1; __cf_bm=2", None, false),
("__cf_bm=2; parent_marketing=1", None, false),
("parent_marketing=1; app_session=abc", Some("app_session=abc"), true),
("__cf_bm=2; parent_marketing=1; app_session=abc", Some("__cf_bm=2; app_session=abc"), true),
("app_session=abc", Some("app_session=abc"), true),
("unknown=1", Some("unknown=1"), true),
("__cf_bm=2", None, false),
] {
let input = request("/rezerwa/15", None, &[("cookie", cookie)]);
let outcome = compiled.evaluate_request(&input, false);
assert!(outcome.pass.is_none(), "unexpected pass on {cookie}");
assert!(outcome.lookup.is_some(), "missing hash on {cookie}");
assert_eq!(outcome.pass.is_some(), bypass, "Cookie: {cookie}");
assert_eq!(outcome.lookup.is_some(), !bypass, "Cookie: {cookie}");
let mut forwarded = input.headers.clone();
outcome.rewrite_cookies(&mut forwarded);
assert!(!forwarded.contains_key(http::header::COOKIE), "{cookie}");
assert_eq!(forwarded.get("cookie").and_then(|value| value.to_str().ok()),
forwarded_cookie, "Cookie: {cookie}");
}
// Cookie can be split across fields; both must be dropped only here.
let split = request("/", None, &[
("cookie", "parent_session=one"),
("cookie", "preference=two"),
// Multiple physical Cookie fields are handled without deleting sessions.
let split = request("/rezerwa/15", None, &[
("cookie", "parent_marketing=1"),
("cookie", "app_session=abc"),
]);
let outcome = compiled.evaluate_request(&split, false);
assert!(outcome.pass.is_some());
let mut forwarded = split.headers.clone();
outcome.rewrite_cookies(&mut forwarded);
assert!(!forwarded.contains_key(http::header::COOKIE));
assert_eq!(forwarded.get("cookie").unwrap(), "app_session=abc");
let anonymous = request("/rezerwa/15", None, &[]);
assert!(compiled.evaluate_request(&anonymous, false).lookup.is_none());
for path in [
"/admin", "/admin/users", "/api/orders", "/auth/callback",
"/login", "/login/callback", "/account", "/profile",
"/checkout", "/cart", "/konto", "/wp-admin",
] {
let input = request(path, None, &[("cookie", "session=secret")]);
// Malformed or non-UTF8 Cookie fields must be preserved and bypassed.
for malformed in [&b"parent_marketing=1; BROKEN"[..],
&b"parent_marketing=1;"[..],
&b"parent_marketing =1"[..],
&b"parent_marketing=1; app_session=\xff"[..]] {
let mut input = request("/rezerwa/15", None, &[]);
input.headers.insert(http::header::COOKIE, HeaderValue::from_bytes(malformed).unwrap());
let outcome = compiled.evaluate_request(&input, false);
assert!(outcome.lookup.is_none(), "private path must not hash: {path}");
assert!(outcome.strip_cookies.is_none(), "private cookie stripped: {path}");
assert!(outcome.pass.is_some());
let mut forwarded = input.headers.clone();
outcome.rewrite_cookies(&mut forwarded);
assert_eq!(forwarded.get("cookie"), input.headers.get("cookie"));
}
for path in ["/admin", "/admin/users", "/api/orders", "/auth/callback",
"/login", "/account", "/profile", "/checkout", "/cart", "/konto"] {
let input = request(path, None, &[("cookie", "parent_marketing=1")]);
let outcome = compiled.evaluate_request(&input, false);
assert!(outcome.pass.is_some(), "{path}");
assert!(outcome.remove_named_cookies.is_empty(), "{path}");
}
let with_auth = request("/rezerwa/15", None, &[
("cookie", "session=secret"), ("authorization", "Bearer access"),
("cookie", "parent_marketing=1"), ("authorization", "Bearer access"),
]);
let outcome = compiled.evaluate_request(&with_auth, false);
assert!(outcome.lookup.is_none());
assert!(outcome.strip_cookies.is_none());
assert!(outcome.pass.is_some());
assert!(outcome.remove_named_cookies.is_empty());
for method in [Method::POST, Method::PUT, Method::DELETE] {
let mut input = request("/rezerwa/15", None, &[("cookie", "session=secret")]);
let mut input = request("/rezerwa/15", None, &[("cookie", "parent_marketing=1")]);
input.method = method;
let outcome = compiled.evaluate_request(&input, false);
assert!(outcome.lookup.is_none());
assert!(outcome.strip_cookies.is_none());
assert!(outcome.pass.is_some());
assert!(outcome.remove_named_cookies.is_empty());
}
let mut head = request("/rezerwa/15", None, &[("cookie", "parent=secret")]);
let mut head = request("/rezerwa/15", None, &[("cookie", "parent_marketing=1")]);
head.method = Method::HEAD;
assert!(compiled.evaluate_request(&head, false).lookup.is_some());
let outcome = compiled.evaluate_request(&head, false);
assert!(outcome.lookup.is_some());
let mut forwarded = head.headers.clone();
outcome.rewrite_cookies(&mut forwarded);
assert!(!forwarded.contains_key(http::header::COOKIE));
}
#[test]
fn selective_cookie_remove_vcl_import_rejects_bad_grammar_and_names() {
for vcl in [
"sub vcl_recv { remove_req_cookies(); }",
"sub vcl_recv { remove_req_cookies(parent); }",
r#"sub vcl_recv { remove_req_cookies("parent",); }"#,
r#"sub vcl_recv { remove_req_cookies("parent" "other"); }"#,
] {
let result = import_vcl(vcl).unwrap();
assert!(!result.warnings.is_empty(), "{vcl}");
assert!(result.rules.is_empty(), "{vcl}");
}
for bad in [serde_json::json!({"id": "bad", "actions": [{"type": "remove_named_cookies", "names": []}]}),
serde_json::json!({"id": "bad", "actions": [{"type": "remove_named_cookies", "names": ["bad;name"]}]})] {
assert!(validate_rules(&[rule(bad)], false).is_err());
}
let good = import_vcl(r#"sub vcl_recv { remove_req_cookies("parent_a", "parent_b"); }"#).unwrap();
assert!(good.warnings.is_empty());
validate_rules(&good.rules, false).unwrap();
}
}
+25
View File
@@ -606,6 +606,31 @@ fn vcl_actions(
Err(format!("set {target} is not supported"))
}
}
// RustProxy-specific, safe exact-name Cookie removal (not stock Varnish VCL).
(RuleStage::Request, "remove_req_cookies") => {
if tokens.len() < 4
|| !matches!(tokens.get(1), Some(VclToken::Sym("(")))
|| !matches!(tokens.last(), Some(VclToken::Sym(")")))
{
return Err("remove_req_cookies requires quoted cookie names".into());
}
let args = &tokens[2..tokens.len() - 1];
if args.len() % 2 == 0 {
return Err("remove_req_cookies expects comma-separated quoted names".into());
}
let mut names = Vec::new();
for (index, arg) in args.iter().enumerate() {
if index % 2 == 0 {
match arg {
VclToken::Str(name) => names.push(name.clone()),
_ => return Err("remove_req_cookies names must be quoted".into()),
}
} else if !matches!(arg, VclToken::Sym(",")) {
return Err("remove_req_cookies expects commas".into());
}
}
Ok(vec![RuleAction::RemoveNamedCookies { names }])
}
(RuleStage::Request, "hash_data") => match tokens {
[VclToken::Ident(_), VclToken::Sym("("), VclToken::Ident(value), VclToken::Sym(")")]
if value.eq_ignore_ascii_case("req.url") =>