This commit is contained in:
Mateusz Gruszczyński committed 2026-11-20 23:14:19 +01:00
1 parent d455028de3
commit 5b2eaaff61
36 files changed
+2544 -102

No files matched your search

+38 -9
View File
@@ -144,7 +144,16 @@ async fn cache_rules_test(
headers: headers.clone(),
client_ip,
};
let request_outcome = rules.evaluate_request(&request, false);
let mut request_outcome = rules.evaluate_request(&request, false);
let mut rule_gate = crate::cache::RuleGate::from_outcome(&request_outcome);
if rule_gate == crate::cache::RuleGate::CookieGuard && settings.enabled {
if let Some(relaxed) =
crate::cache::static_cookie_guard_relaxation(&rules, &request, &request_outcome, &settings)
{
request_outcome = relaxed.outcome;
rule_gate = crate::cache::RuleGate::CookieGuardRelaxed;
}
}
request_outcome.apply_headers(&mut headers);
request_outcome.rewrite_cookies(&mut headers);
let query = match request_outcome.rewrite_query(uri.query()) {
@@ -157,17 +166,24 @@ async fn cache_rules_test(
Some(query) => format!("{path}?{query}"),
None => path.clone(),
};
let request_policy = if request_outcome.pass.is_some() {
Some("cache_rule")
} else if !settings.enabled {
Some("cache_disabled")
} else {
// Same precedence as live traffic (cache::request_gate). Vhost security
// gates (Basic auth, providers, sticky pools) are not simulated here.
let request_policy = crate::cache::request_gate(
crate::cache::GateInput { cache_enabled: settings.enabled, ..Default::default() },
rule_gate,
)
.or_else(|| {
crate::cache::request_policy_with_vcl_cookie(
&method, &headers, true, &path, query.is_some(), &settings,
request_outcome.lookup.is_some(),
)
.bypass_reason()
};
.bypass_reason()
});
let vcl_cookie_lookup = request_outcome.lookup.is_some() && settings.varnish_compatible;
let shared_static_cookie_fill = request_policy.is_none()
&& !vcl_cookie_lookup
&& settings.ignore_cookie_for_path(&path)
&& headers.contains_key(http::header::COOKIE);
let mut response_value = Value::Null;
let mut deliver_value = Value::Null;
if let Some(response) = input.response {
@@ -178,9 +194,14 @@ async fn cache_rules_test(
)
})?;
let mut response_headers = cache_rule_headers(&response.headers)?;
let shared_static_reason = if shared_static_cookie_fill {
crate::cache::shared_static_response_reason(status, &response_headers, &settings)
} else {
None
};
let outcome = rules.evaluate_response(&request, status, &response_headers, false);
outcome.overrides.apply_headers(&mut response_headers);
let plan = if request_policy.is_none() {
let plan = if request_policy.is_none() && shared_static_reason.is_none() {
crate::cache::plan_with(
status,
&response_headers,
@@ -193,6 +214,8 @@ async fn cache_rules_test(
};
let store_reason = if request_policy.is_some() {
None
} else if shared_static_reason.is_some() {
shared_static_reason
} else if outcome.overrides.no_store {
Some("cache_rule_no_store")
} else if plan.is_none() {
@@ -212,6 +235,7 @@ async fn cache_rules_test(
"ttl": plan.as_ref().map(|plan| plan.ttl()),
"grace": plan.as_ref().map(|plan| plan.grace()),
"reason": store_reason,
"reason_class": store_reason.map(|reason| crate::cache::reason_class(reason).as_str()),
});
let deliver = rules.evaluate_deliver(&request, status, &response_headers, false);
deliver_value = json!({"matched": deliver.matched, "set": deliver.set, "remove": deliver.remove, "defaults": deliver.defaults});
@@ -229,6 +253,11 @@ async fn cache_rules_test(
"variant": request_outcome.hash,
"cacheable": request_policy.is_none(),
"reason": request_policy,
"reason_class": request_policy.map(|reason| crate::cache::reason_class(reason).as_str()),
"cookie_guard": request_outcome.pass_cookie_guard
|| rule_gate == crate::cache::RuleGate::CookieGuardRelaxed,
"static_cookie_relaxed": rule_gate == crate::cache::RuleGate::CookieGuardRelaxed,
"shared_static_check": shared_static_cookie_fill,
},
"response": response_value,
"deliver": deliver_value,
+4 -3
View File
@@ -2337,7 +2337,8 @@
"maxItems": 64
},
"static_ignore_cookies": {
"type": "boolean"
"type": "boolean",
"description": "For configured static extensions: ignore Cookie in the cache key and let cookie_pass rules (not pass) yield for public static assets. A Cookie-bearing fill is stored only when the backend reply is explicitly public (public, s-maxage, max-age>0 or Expires), not HTML, and has no Set-Cookie, private, no-store or Vary: */Authorization."
},
"static_extensions": {
"type": "array",
@@ -2525,7 +2526,7 @@
"static_ignore_vary_cookie": {
"type": "boolean",
"default": true,
"description": "For cookie-independent configured static extensions only, omit Cookie from Vary on explicitly public, otherwise cacheable responses. Requires static_ignore_cookies. Preserves other Vary dimensions and all private/no-store/Set-Cookie safeguards."
"description": "For cookie-independent configured static extensions only, omit Cookie from Vary on explicitly public, otherwise cacheable responses. Requires static_ignore_cookies. Preserves other Vary dimensions and all private/no-store/Set-Cookie safeguards. A response fetched with a Cookie must also pass the shared-static storage guard."
}
},
"additionalProperties": false
@@ -8865,7 +8866,7 @@
"maxItems": 16,
"items": {
"type": "object",
"description": "type: pass, lookup (VCL return(hash), Cookie exception in Varnish-compatible mode), strip_cookies{keep}, remove_named_cookies{names} (exact names or trailing-* prefixes; remaining cookies, including application sessions, survive), 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 (explicit VCL return(pass); never relaxed), cookie_pass (Cookie/session guard, VCL return(cookie_pass) RustProxy extension; needs a non-negated Cookie condition; may be relaxed only for public static assets when static_ignore_cookies is on and no other rule bypasses the request), lookup (VCL return(hash), Cookie exception in Varnish-compatible mode), strip_cookies{keep}, remove_named_cookies{names} (exact names or trailing-* prefixes; remaining cookies, including application sessions, survive), 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)."
+53
View File
@@ -4366,6 +4366,59 @@ mod tests {
));
}
#[tokio::test]
async fn cache_rule_tester_reports_cookie_guard_relaxation_and_shared_static_guard() {
let (router, store, _dir, secret, csrf) = fixture().await;
let cookie = format!("{}={secret}", auth::COOKIE_NAME);
let rules = serde_json::json!([
{"id": "private", "conditions": [{"field": "path", "operator": "prefix", "values": ["/user/"]}], "actions": [{"type": "pass"}], "stop": true},
{"id": "sessions", "conditions": [{"field": "header", "name": "Cookie", "operator": "exists"}], "actions": [{"type": "cookie_pass"}], "stop": true}
]);
let run = |url: &str, response_headers: serde_json::Value| {
let body = serde_json::json!({
"global_rules": rules,
"request": {"method": "GET", "url": url, "headers": [["Cookie", "session=1"]]},
"response": {"status": 200, "headers": response_headers}
});
request("/api/cache/rules/test")
.method("POST")
.header("cookie", &cookie)
.header("origin", "http://127.0.0.1:9090")
.header("x-rustproxy-request", "1")
.header("x-csrf-token", csrf.as_str())
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap()
};
let read = |response: axum::response::Response| async move {
assert_eq!(response.status(), StatusCode::OK);
let body = axum::body::to_bytes(response.into_body(), 1 << 20).await.unwrap();
serde_json::from_slice::<serde_json::Value>(&body).unwrap()
};
let public = serde_json::json!([["Cache-Control", "public, max-age=600"], ["Content-Type", "text/css"]]);
let data = read(router.clone().oneshot(run("https://localhost/assets/app.css?v=2", public.clone())).await.unwrap()).await;
assert_eq!(data["request"]["cacheable"], true, "{data}");
assert_eq!(data["request"]["static_cookie_relaxed"], true);
assert_eq!(data["request"]["shared_static_check"], true);
assert_eq!(data["response"]["stored"], true);
let html = serde_json::json!([["Cache-Control", "public, max-age=600"], ["Content-Type", "text/html"]]);
let data = read(router.clone().oneshot(run("https://localhost/", html)).await.unwrap()).await;
assert_eq!(data["request"]["reason"], "cache_rule_cookie");
assert_eq!(data["request"]["reason_class"], "vcl_cookie_guard");
let data = read(router.clone().oneshot(run("https://localhost/user/a.png", public)).await.unwrap()).await;
assert_eq!(data["request"]["reason"], "cache_rule");
assert_eq!(data["request"]["reason_class"], "vcl_rule");
let private = serde_json::json!([["Cache-Control", "private, max-age=600"]]);
let data = read(router.clone().oneshot(run("https://localhost/assets/app.css", private)).await.unwrap()).await;
assert_eq!(data["response"]["stored"], false);
assert_eq!(data["response"]["reason"], "response_cache_control");
assert_eq!(data["response"]["reason_class"], "response");
store.close().await;
}
include!("certificate_inspection_tests.rs");
include!("preferences_tests.rs");
}
+55 -16
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", "remove_named_cookies", "strip_query", "hash_header", "hash_cookie", "set_request_header", "remove_request_header"],
request: ["pass", "cookie_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", remove_named_cookies: "request_cookies", strip_query: "request_query", ttl: "ttl", grace: "grace", no_store: "store", allow_store: "store" };
const ASPECTS = { pass: "request_routing", cookie_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);
@@ -82,6 +82,7 @@ window.rustProxyCacheRules = (() => {
return rule.actions.map(a => {
switch (a.type) {
case "pass": return "return (pass);";
case "cookie_pass": return "return (cookie_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(", ")});`;
@@ -124,6 +125,8 @@ window.rustProxyCacheRules = (() => {
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.");
if (rule.actions.some(a => a.type === "cookie_pass"))
limits.push("return(cookie_pass) is a RustProxy extension (Cookie guard); stock Varnish only knows return(pass).");
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, "")}`;
@@ -170,6 +173,12 @@ window.rustProxyCacheRules = (() => {
name: t(label), stage: "request", match, conditions,
actions: [{ type: "pass" }], stop: true,
});
// Cookie/session guards use cookie_pass: the same BYPASS for pages, but
// RustProxy may still cache a *public static asset* when the global static
// cookie policy is on and no explicit pass rule matches the request.
const templateCookieGuard = (label, conditions, match = "all") => ({
...templatePass(label, conditions, match), actions: [{ type: "cookie_pass" }],
});
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,
@@ -179,7 +188,12 @@ window.rustProxyCacheRules = (() => {
});
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" }] }],
// Path guard and Cookie guard are separate rules: the explicit path pass
// is never relaxed, the Cookie guard may yield to the static policy.
wordpress: () => [
{ name: t("cacheRuleTplWordpress"), stage: "request", match: "all", conditions: [{ field: "path", operator: "regex", values: ["^/(wp-admin|wp-login\\.php|xmlrpc\\.php|wp-json)"] }], actions: [{ type: "pass" }] },
{ name: t("cacheRuleTplWordpressCookies"), stage: "request", match: "all", conditions: [{ field: "header", name: "cookie", operator: "regex", values: ["wordpress_logged_in_|comment_author_|woocommerce_items_in_cart|wp-postpass_"] }], actions: [{ type: "cookie_pass" }] },
],
static: () => [
{ name: t("cacheRuleTplStaticCookies"), stage: "request", match: "all", conditions: [{ field: "extension", operator: "equals", values: ["css", "js", "mjs", "png", "jpg", "jpeg", "gif", "webp", "avif", "svg", "ico", "woff", "woff2"] }], actions: [{ type: "strip_cookies", keep: [] }] },
{ name: t("cacheRuleTplStaticTtl"), stage: "response", 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: "ttl", seconds: 2592000 }, { type: "strip_set_cookie" }] },
@@ -193,7 +207,7 @@ window.rustProxyCacheRules = (() => {
{ name: t("cacheRuleTplCdnPrivate"), stage: "request", match: "all", conditions: [{ field: "path", operator: "regex", values: ["^/(admin|api|auth|login|logout|panel|konto|dashboard)(/|$)"] }], actions: [{ type: "pass" }], stop: true },
{ name: t("cacheRuleTplCdnAuth"), stage: "request", match: "all", conditions: [{ field: "header", name: "Authorization", operator: "exists" }], actions: [{ type: "pass" }], stop: true },
{ name: t("cacheRuleTplCdnStrip"), stage: "request", match: "all", conditions: [{ field: "header", name: "Cookie", operator: "regex", values: [`^${technical}=[^;]*(?:;[ \\t]*${technical}=[^;]*)*$`] }], actions: [{ type: "strip_cookies", keep: [] }] },
{ name: t("cacheRuleTplCdnRemaining"), stage: "request", match: "all", conditions: [{ field: "header", name: "Cookie", operator: "exists" }], actions: [{ type: "pass" }], stop: true },
{ name: t("cacheRuleTplCdnRemaining"), stage: "request", match: "all", conditions: [{ field: "header", name: "Cookie", operator: "exists" }], actions: [{ type: "cookie_pass" }], stop: true },
];
},
// Separate from the CDN template: remove only explicitly named cookies
@@ -221,8 +235,8 @@ window.rustProxyCacheRules = (() => {
// 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)="] }])],
cookiepass: () => [templateCookieGuard("cacheRuleTplCookiepass", [{ field: "header", name: "Cookie", operator: "exists" }])],
sessioncookies: () => [templateCookieGuard("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),
@@ -245,15 +259,17 @@ window.rustProxyCacheRules = (() => {
...["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]+)="] }])],
woocommerce: () => [
templatePass("cacheRuleTplWoocommerce", [templatePath("^/(?:cart|checkout|my-account)(?:/|[?]|$)")]),
templateCookieGuard("cacheRuleTplWoocommerceCookies", [
{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:wordpress_logged_in_[^=;]*|woocommerce_items_in_cart|wp_woocommerce_session_[^=;]*|woocommerce_cart_hash)="] },
]),
],
django: () => [templateCookieGuard("cacheRuleTplDjango", [{ field: "cookie", name: "sessionid", operator: "exists" }])],
laravel: () => [templateCookieGuard("cacheRuleTplLaravel", [{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:laravel_session|PHPSESSID)="] }])],
authjs: () => [templateCookieGuard("cacheRuleTplAuthjs", [{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:__Secure-)?(?:next-auth[.]session-token|authjs[.]session-token)="] }])],
aspnet: () => [templateCookieGuard("cacheRuleTplAspnet", [{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:[.]AspNetCore[.]Cookies|ASP[.]NET_SessionId)="] }])],
drupal: () => [templateCookieGuard("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", [
@@ -325,6 +341,17 @@ window.rustProxyCacheRules = (() => {
function applicableGlobals(vhostId) {
return (envelope?.config?.cache?.rules || []).filter(rule => rule.enabled !== false && (!rule.vhosts?.length || rule.vhosts.includes(vhostId)));
}
// A request `pass` rule whose only conditions describe cookies (all match)
// or that has a Cookie condition alongside others (any match) is a likely
// Cookie/session guard created before cookie_pass existed.
function cookieOnlyPass(rule) {
if (rule.stage !== "request" || !rule.actions.some(a => a.type === "pass")) return false;
const isCookie = c => !c.negate && (c.field === "cookie" || (c.field === "header" && String(c.name || "").trim().toLowerCase() === "cookie"));
const cookies = rule.conditions.filter(isCookie);
if (!cookies.length) return false;
if (rule.match === "any") return rule.conditions.every(isCookie);
return rule.conditions.every(c => isCookie(c) || (c.field === "method" && !c.negate));
}
function aspects(rule) { return new Set(rule.actions.map(a => ASPECTS[a.type]).filter(Boolean)); }
function conflictsFor(vhostRules, globals) {
const notes = [];
@@ -527,6 +554,15 @@ window.rustProxyCacheRules = (() => {
head.append(grip, toggle, title, hitCount, actions);
card.append(head);
if (scope === "global") for (const note of globalOverrideNotes(rule)) card.append(el("p", note, "fine cache-rules-notice cache-rule-note"));
if (cookieOnlyPass(rule)) {
// Controlled migration: an explicit pass is never relaxed automatically.
// The operator may convert a Cookie-session guard after review.
const note = el("p", t("cacheRuleCookieGuardHint"), "fine cache-rules-notice cache-rule-note");
const convert = el("button", t("cacheRuleCookieGuardConvert"), "outline"); convert.type = "button";
convert.addEventListener("click", () => { rule.actions = rule.actions.map(a => a.type === "pass" ? { type: "cookie_pass" } : a); render(); changed(); toast(t("cacheRuleCookieGuardConverted")); });
note.append(" ", convert);
card.append(note);
}
if (open.has(rule.id)) card.append(ruleEditor(rule));
return card;
}
@@ -690,6 +726,9 @@ 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.reason_class) line(t("cacheRulesResultReasonClass"), t(`cacheReasonClass_${request.reason_class}`));
if (request.static_cookie_relaxed) line(t("cacheRulesResultStaticCookie"), t("cacheRulesResultStaticCookieRelaxed"), "is-ok");
else if (request.shared_static_check) line(t("cacheRulesResultStaticCookie"), t("cacheRulesResultStaticCookieChecked"));
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 || "—");
@@ -716,7 +755,7 @@ window.rustProxyCacheRules = (() => {
// 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;
rule.actions.some(a => a.type === "strip_cookies" || a.type === "pass" || a.type === "cookie_pass")) : -1;
if (cdnIndex >= 0) rules.splice(cdnIndex, 0, ...addedRules);
else rules.push(...addedRules);
if (addedRules.length) open.add(addedRules[0].id);
+1
View File
@@ -1,2 +1,3 @@
include!("policy/request.rs");
include!("policy/response.rs");
include!("policy/decision.rs");
+299
View File
@@ -0,0 +1,299 @@
// Central request-gate decision for the shared cache.
//
// Every reason that can keep a request away from the HOT/COLD cache is
// classified here, and its precedence is fixed in one place. The proxy request
// path (`proxy/forward/route_cache.rs`) and the administrator "Test a request"
// API (`admin/cache_rules.rs`) both use these functions, so diagnostics in the
// panel match what live traffic does.
//
// Precedence, strongest first:
//
// 1. Security - control-plane traffic, Basic auth, external auth
// providers, sticky-cookie pools. Never relaxed.
// 2. Configuration - cache disabled globally / per route, protocol upgrade.
// 3. VCL `pass` - an explicit `return(pass)` rule. Never relaxed.
// 4. VCL `cookie_pass` - a Cookie/session guard. Relaxed **only** for a public
// static asset under the "Ignore request cookies for
// static files" option, and only when no other rule would
// bypass the same request (see
// `static_cookie_guard_relaxation`).
// 5. Default request policy (`request_policy_with_vcl_cookie`): method,
// body, Authorization, Cookie, path/query exclusions, client directives.
// 6. Backend response policy (`plan_with`, `response_reason`) and, for a
// static request whose Cookie was ignored, `shared_static_response_reason`.
/// Broad class of a cache reason, for diagnostics and documentation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ReasonClass {
/// Absolute security bypass (authentication, credentials, control plane).
Security,
/// Cache or route disabled by configuration.
Configuration,
/// Explicit VCL / cache-rule `pass` or rule `no_store`.
VclRule,
/// VCL / cache-rule Cookie guard (`cookie_pass`).
VclCookieGuard,
/// RustProxy's built-in Cookie policy.
Cookie,
/// Other default request policy (method, body, directives, exclusions).
RequestPolicy,
/// Backend response properties (status, Cache-Control, Set-Cookie, Vary).
Response,
/// HIT / MISS / revalidation outcomes that are not a bypass.
Cache,
}
impl ReasonClass {
pub fn as_str(self) -> &'static str {
match self {
Self::Security => "security",
Self::Configuration => "configuration",
Self::VclRule => "vcl_rule",
Self::VclCookieGuard => "vcl_cookie_guard",
Self::Cookie => "cookie",
Self::RequestPolicy => "request_policy",
Self::Response => "response",
Self::Cache => "cache",
}
}
}
/// `X-Cache-Reason` for an unrelaxed explicit `pass` (unchanged since 0.2x).
pub const REASON_VCL_PASS: &str = "cache_rule";
/// `X-Cache-Reason` for an unrelaxed `cookie_pass` guard.
pub const REASON_VCL_COOKIE_GUARD: &str = "cache_rule_cookie";
/// MISS reason when a `cookie_pass` guard was relaxed for a public static.
pub const REASON_MISS_STATIC_COOKIE: &str = "cache_miss_static_cookie";
pub fn reason_class(reason: &str) -> ReasonClass {
match reason {
"admin_control_plane" | "basic_auth" | "sticky_cookie" | "request_authorization" => {
ReasonClass::Security
}
"cache_disabled" | "route_disabled" | "request_upgrade" | "configuration_changed" => {
ReasonClass::Configuration
}
REASON_VCL_PASS | "cache_rule_no_store" | "response_headers_policy" => ReasonClass::VclRule,
REASON_VCL_COOKIE_GUARD => ReasonClass::VclCookieGuard,
"request_cookie" => ReasonClass::Cookie,
reason if reason.starts_with("response_") => ReasonClass::Response,
reason if reason.starts_with("cache_") => ReasonClass::Cache,
reason
if reason.starts_with("request_")
|| matches!(reason, "query_excluded" | "path_excluded") =>
{
ReasonClass::RequestPolicy
}
// External authentication provider identifiers (tinyauth, authentik,
// oidc, ...) are reported verbatim and are security bypasses.
_ => ReasonClass::Security,
}
}
/// Inputs to the request gate that precede cache-rule evaluation results.
#[derive(Debug, Clone, Copy, Default)]
pub struct GateInput {
pub admin_control_plane: bool,
pub basic_auth: bool,
pub auth_provider: Option<&'static str>,
pub sticky_cookie: bool,
pub cache_enabled: bool,
pub route_disabled: bool,
pub upgrade: bool,
}
/// Effective VCL routing decision after the static-cookie relaxation step.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuleGate {
/// No request-rule bypass.
None,
/// Explicit `pass`: absolute for every resource type.
Pass,
/// Unrelaxed `cookie_pass` guard.
CookieGuard,
/// `cookie_pass` guard relaxed for a public static asset. Treated as
/// `None` by the gate; the request continues to the default policy.
CookieGuardRelaxed,
}
impl RuleGate {
pub fn from_outcome(outcome: &RequestRuleOutcome) -> Self {
match (&outcome.pass, outcome.pass_cookie_guard) {
(None, _) => Self::None,
(Some(_), false) => Self::Pass,
(Some(_), true) => Self::CookieGuard,
}
}
}
/// Request-gate reason, or `None` when the default request policy decides.
pub fn request_gate(input: GateInput, rule: RuleGate) -> Option<&'static str> {
if input.admin_control_plane {
Some("admin_control_plane")
} else if input.basic_auth {
Some("basic_auth")
} else if let Some(provider) = input.auth_provider {
Some(provider)
} else if input.sticky_cookie {
Some("sticky_cookie")
} else if !input.cache_enabled {
Some("cache_disabled")
} else if input.route_disabled {
Some("route_disabled")
} else if input.upgrade {
Some("request_upgrade")
} else {
match rule {
RuleGate::Pass => Some(REASON_VCL_PASS),
RuleGate::CookieGuard => Some(REASON_VCL_COOKIE_GUARD),
RuleGate::None | RuleGate::CookieGuardRelaxed => None,
}
}
}
/// Result of relaxing a `cookie_pass` guard for a public static asset.
#[derive(Debug, Clone)]
pub struct StaticCookieRelaxation {
/// Request-rule outcome without Cookie guards. Its request edits (header,
/// cookie and query rewrites, hash variants) replace the guarded outcome,
/// so the forwarded request and cache key match what every other client
/// gets for the same URL.
pub outcome: RequestRuleOutcome,
}
/// Decide whether a `cookie_pass` bypass may be relaxed for this request.
///
/// `request` must be the request **as received** (before rule edits). All of
/// the following must hold, otherwise the guard keeps BYPASS:
///
/// * the winning bypass is a `cookie_pass` guard (never an explicit `pass`);
/// * GET or HEAD; no `Authorization`; a `Cookie` header is present;
/// * "Ignore request cookies for static files" is on and the path has one of
/// the configured static extensions (the query string does not matter);
/// * re-evaluating the rules with every Cookie guard removed produces no
/// `pass` (so explicit rules after a terminal guard still apply);
/// * re-evaluating the rules with the Cookie header removed produces no
/// `pass` (the resource is cacheable for an anonymous client as well).
///
/// The extension is only a *candidate* signal. Public storage is decided
/// later from the backend response (`shared_static_response_reason`).
pub fn static_cookie_guard_relaxation(
rules: &CompiledRules,
request: &RuleRequest,
outcome: &RequestRuleOutcome,
settings: &Settings,
) -> Option<StaticCookieRelaxation> {
if outcome.pass.is_none() || !outcome.pass_cookie_guard {
return None;
}
if request.method != Method::GET && request.method != Method::HEAD {
return None;
}
if !settings.ignore_cookie_for_path(&request.path)
|| request.headers.contains_key(::http::header::AUTHORIZATION)
|| !request.headers.contains_key(::http::header::COOKIE)
{
return None;
}
let unguarded = rules.evaluate_request_without_cookie_guards(request);
if unguarded.pass.is_some() {
return None;
}
let mut anonymous = request.clone();
anonymous.headers.remove(::http::header::COOKIE);
if rules.evaluate_request(&anonymous, false).pass.is_some() {
return None;
}
Some(StaticCookieRelaxation { outcome: unguarded })
}
fn explicit_public_freshness(
headers: &HeaderMap,
control: &HashMap<String, Option<String>>,
) -> bool {
if control.contains_key("public") || control.contains_key("s-maxage") {
return true;
}
if control
.get("max-age")
.and_then(|value| value.as_deref())
.and_then(|value| value.parse::<u64>().ok())
.is_some_and(|value| value > 0)
{
return true;
}
if control.contains_key("max-age") {
// An explicit max-age (including 0) overrides Expires (RFC 9111 5.3).
return false;
}
let expires = headers
.get(::http::header::EXPIRES)
.and_then(|value| value.to_str().ok())
.and_then(|value| httpdate::parse_http_date(value).ok());
let date = headers
.get(::http::header::DATE)
.and_then(|value| value.to_str().ok())
.and_then(|value| httpdate::parse_http_date(value).ok())
.unwrap_or_else(SystemTime::now);
expires.is_some_and(|expires| expires > date)
}
/// Extra storage guard for a static request that carried a Cookie which the
/// cache key ignored (the static-cookie policy). Such an object will be served
/// to clients with *other* cookies, including anonymous ones, so the backend
/// must positively declare it shareable. Evaluated on the backend response
/// **before** VCL response rules, so `strip_set_cookie` or
/// `ignore_cache_control` cannot turn a private reply into a shared one.
///
/// Returns the `X-Cache-Reason` when storage must be refused.
pub fn shared_static_response_reason(
status: StatusCode,
headers: &HeaderMap,
settings: &Settings,
) -> Option<&'static str> {
if status != StatusCode::OK {
return Some("response_status");
}
if headers.contains_key(::http::header::SET_COOKIE) {
return Some("response_set_cookie");
}
let Some(control) = directives(headers) else {
return Some("response_cache_control_invalid");
};
if ["no-store", "private", "must-understand"]
.iter()
.any(|name| control.contains_key(*name))
{
return Some("response_cache_control");
}
if settings.varnish_compatible && surrogate_no_store(headers) {
return Some("response_surrogate_control");
}
for value in headers.get_all(::http::header::VARY) {
let Ok(text) = value.to_str() else {
return Some("response_vary");
};
for name in text.split(',').map(str::trim) {
if name == "*" || name.eq_ignore_ascii_case("authorization") {
return Some("response_vary");
}
}
}
// Dynamic documents served under a static-looking name (SPA fallbacks,
// error pages rendered with 200, "/user.css" generated per session).
if headers
.get(::http::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| {
let value = value.trim_start().to_ascii_lowercase();
value.starts_with("text/html") || value.starts_with("application/xhtml+xml")
})
{
return Some("response_static_dynamic");
}
if !explicit_public_freshness(headers, &control) {
return Some("response_static_not_public");
}
None
}
+520
View File
@@ -0,0 +1,520 @@
mod cache_decision_tests {
use super::*;
fn rule(json: serde_json::Value) -> Rule {
serde_json::from_value(json).unwrap()
}
fn request(
method: Method,
path: &str,
query: Option<&str>,
headers: &[(&str, &str)],
) -> RuleRequest {
let mut map = HeaderMap::new();
for (name, value) in headers {
map.append(
http::HeaderName::from_bytes(name.as_bytes()).unwrap(),
HeaderValue::from_str(value).unwrap(),
);
}
RuleRequest {
host: "site.example.test".into(),
path: path.into(),
query: query.map(str::to_owned),
method,
headers: map,
client_ip: None,
}
}
fn get(path: &str, headers: &[(&str, &str)]) -> RuleRequest {
request(Method::GET, path, None, headers)
}
fn compile(rules: Vec<Rule>) -> CompiledRules {
validate_rules(&rules, true).unwrap();
CompiledRules::compile("site", &[], &rules, false).unwrap()
}
fn guard(id: &str) -> Rule {
rule(
serde_json::json!({"id": id, "conditions": [{"field": "header", "name": "Cookie", "operator": "exists"}], "actions": [{"type": "cookie_pass"}], "stop": true}),
)
}
fn relax(
rules: &CompiledRules,
request: &RuleRequest,
settings: &Settings,
) -> Option<StaticCookieRelaxation> {
let outcome = rules.evaluate_request(request, false);
static_cookie_guard_relaxation(rules, request, &outcome, settings)
}
#[test]
fn cookie_pass_is_a_distinct_guard_and_needs_a_cookie_condition() {
let rules = compile(vec![guard("cookies")]);
let outcome = rules.evaluate_request(&get("/", &[("cookie", "a=1")]), false);
assert_eq!(outcome.pass.as_deref(), Some("cookies"));
assert!(outcome.pass_cookie_guard);
assert_eq!(RuleGate::from_outcome(&outcome), RuleGate::CookieGuard);
assert!(rules.has_cookie_guards());
for conditions in [
serde_json::json!([]),
serde_json::json!([{"field": "path", "operator": "prefix", "values": ["/"]}]),
serde_json::json!([{"field": "header", "name": "Cookie", "operator": "exists", "negate": true}]),
] {
let invalid = vec![rule(
serde_json::json!({"id": "bad", "conditions": conditions, "actions": [{"type": "cookie_pass"}]}),
)];
let error = validate_rules(&invalid, true).unwrap_err().to_string();
assert!(error.contains("cookie_pass needs"), "{error}");
}
// A named-cookie condition is accepted.
compile(vec![rule(
serde_json::json!({"id": "named", "conditions": [{"field": "cookie", "name": "sessionid", "operator": "exists"}], "actions": [{"type": "cookie_pass"}]}),
)]);
}
#[test]
fn explicit_pass_overrides_and_is_overridden_like_other_routing_actions() {
let rules = compile(vec![
guard("cookies"),
rule(
serde_json::json!({"id": "admin", "conditions": [{"field": "path", "operator": "prefix", "values": ["/admin"]}], "actions": [{"type": "pass"}]}),
),
]);
// stop on the guard: the explicit rule is not reached in normal mode ...
let outcome = rules.evaluate_request(&get("/admin/app.css", &[("cookie", "s=1")]), false);
assert!(outcome.pass_cookie_guard);
// ... but it is reached once guards are ignored.
let unguarded = rules
.evaluate_request_without_cookie_guards(&get("/admin/app.css", &[("cookie", "s=1")]));
assert_eq!(unguarded.pass.as_deref(), Some("admin"));
assert!(!unguarded.pass_cookie_guard);
}
#[test]
fn relaxation_requires_every_safety_condition() {
let settings = Settings::default();
let rules = compile(vec![
rule(
serde_json::json!({"id": "private", "conditions": [{"field": "path", "operator": "prefix", "values": ["/private/"]}], "actions": [{"type": "pass"}], "stop": true}),
),
guard("cookies"),
rule(
serde_json::json!({"id": "preview", "conditions": [{"field": "cookie", "name": "preview", "operator": "exists"}], "actions": [{"type": "pass"}]}),
),
rule(
serde_json::json!({"id": "utm", "actions": [{"type": "strip_query", "params": ["utm_*"]}]}),
),
]);
let cookie = [("cookie", "SESSabc=1; _ga=2")];
// Public static candidate with a query string: relaxed, and later
// request edits (query stripping) are part of the relaxed outcome.
let asset = request(
Method::GET,
"/theme/app.CSS",
Some("v=3&utm_source=x"),
&cookie,
);
let relaxed = relax(&rules, &asset, &settings).expect("static asset relaxed");
assert!(relaxed.outcome.pass.is_none());
assert_eq!(
relaxed.outcome.rewrite_query(asset.query.as_deref()),
Some(Some("v=3".into()))
);
assert!(relax(
&rules,
&request(Method::HEAD, "/app.js", None, &cookie),
&settings
)
.is_some());
// Not a configured static extension (HTML, extension-less, .php).
for path in ["/", "/node/1", "/index.php", "/feed.xml"] {
assert!(
relax(&rules, &get(path, &cookie), &settings).is_none(),
"{path}"
);
}
// Unsafe method, Authorization, explicit pass on path or later rule.
assert!(relax(
&rules,
&request(Method::POST, "/app.css", None, &cookie),
&settings
)
.is_none());
assert!(relax(
&rules,
&get(
"/app.css",
&[("cookie", "s=1"), ("authorization", "Bearer x")]
),
&settings
)
.is_none());
assert!(relax(&rules, &get("/private/a.png", &cookie), &settings).is_none());
assert!(relax(
&rules,
&get("/app.css", &[("cookie", "preview=1; s=1")]),
&settings
)
.is_none());
// Options off => the guard keeps BYPASS.
let off = Settings {
static_ignore_cookies: false,
..Settings::default()
};
assert!(relax(&rules, &asset, &off).is_none());
let narrow = Settings {
static_extensions: vec!["woff2".into()],
..Settings::default()
};
assert!(relax(&rules, &asset, &narrow).is_none());
}
#[test]
fn relaxation_refuses_resources_bypassed_for_anonymous_clients() {
let settings = Settings::default();
// Explicit pass when the consent cookie is *absent*.
let rules = compile(vec![
guard("cookies"),
rule(
serde_json::json!({"id": "consent", "conditions": [{"field": "cookie", "name": "consent", "operator": "exists", "negate": true}], "actions": [{"type": "pass"}]}),
),
]);
assert!(relax(
&rules,
&get("/app.css", &[("cookie", "consent=1; s=1")]),
&settings
)
.is_none());
}
#[test]
fn explicit_pass_is_never_relaxed() {
let settings = Settings::default();
let rules = compile(vec![rule(
serde_json::json!({"id": "cookies", "conditions": [{"field": "header", "name": "Cookie", "operator": "exists"}], "actions": [{"type": "pass"}], "stop": true}),
)]);
let asset = get("/app.css", &[("cookie", "s=1")]);
let outcome = rules.evaluate_request(&asset, false);
assert_eq!(RuleGate::from_outcome(&outcome), RuleGate::Pass);
assert!(static_cookie_guard_relaxation(&rules, &asset, &outcome, &settings).is_none());
}
#[test]
fn request_gate_precedence_is_fixed() {
let open = GateInput {
cache_enabled: true,
..Default::default()
};
assert_eq!(request_gate(open, RuleGate::None), None);
assert_eq!(request_gate(open, RuleGate::CookieGuardRelaxed), None);
assert_eq!(request_gate(open, RuleGate::Pass), Some(REASON_VCL_PASS));
assert_eq!(
request_gate(open, RuleGate::CookieGuard),
Some(REASON_VCL_COOKIE_GUARD)
);
// Security and configuration always win over rules and relaxation.
for (input, reason) in [
(
GateInput {
admin_control_plane: true,
..open
},
"admin_control_plane",
),
(
GateInput {
basic_auth: true,
..open
},
"basic_auth",
),
(
GateInput {
auth_provider: Some("oidc"),
..open
},
"oidc",
),
(
GateInput {
sticky_cookie: true,
..open
},
"sticky_cookie",
),
(
GateInput {
cache_enabled: false,
..open
},
"cache_disabled",
),
(
GateInput {
route_disabled: true,
..open
},
"route_disabled",
),
(
GateInput {
upgrade: true,
..open
},
"request_upgrade",
),
] {
for gate in [RuleGate::None, RuleGate::CookieGuardRelaxed, RuleGate::Pass] {
assert_eq!(request_gate(input, gate), Some(reason));
}
}
}
#[test]
fn reason_classes_tell_the_bypass_source_apart() {
for (reason, class) in [
("basic_auth", ReasonClass::Security),
("request_authorization", ReasonClass::Security),
("tinyauth", ReasonClass::Security),
("route_disabled", ReasonClass::Configuration),
("cache_rule", ReasonClass::VclRule),
("cache_rule_no_store", ReasonClass::VclRule),
("cache_rule_cookie", ReasonClass::VclCookieGuard),
("request_cookie", ReasonClass::Cookie),
("path_excluded", ReasonClass::RequestPolicy),
("request_no_cache", ReasonClass::RequestPolicy),
("response_set_cookie", ReasonClass::Response),
("response_static_not_public", ReasonClass::Response),
("cache_miss_static_cookie", ReasonClass::Cache),
] {
assert_eq!(reason_class(reason), class, "{reason}");
}
}
fn response(pairs: &[(&str, &str)]) -> HeaderMap {
let mut headers = HeaderMap::new();
for (name, value) in pairs {
headers.append(
http::HeaderName::from_bytes(name.as_bytes()).unwrap(),
HeaderValue::from_str(value).unwrap(),
);
}
headers
}
#[test]
fn shared_static_guard_requires_an_explicitly_public_reply() {
let settings = Settings::default();
let check = |status: u16, pairs: &[(&str, &str)]| {
shared_static_response_reason(
StatusCode::from_u16(status).unwrap(),
&response(pairs),
&settings,
)
};
let future = httpdate::fmt_http_date(SystemTime::now() + Duration::from_secs(600));
let past = httpdate::fmt_http_date(SystemTime::now() - Duration::from_secs(600));
for ok in [
vec![("cache-control", "public")],
vec![("cache-control", "max-age=60")],
vec![("cache-control", "s-maxage=60")],
vec![
("cache-control", "public, max-age=60"),
("vary", "Accept-Encoding, Cookie"),
],
vec![("expires", future.as_str()), ("content-type", "font/woff2")],
vec![
("cache-control", "max-age=60"),
("content-type", "text/css; charset=utf-8"),
],
] {
assert_eq!(check(200, &ok), None, "{ok:?}");
}
for (pairs, status, reason) in [
(
vec![("cache-control", "public, max-age=60")],
404,
"response_status",
),
(
vec![("cache-control", "public, max-age=60")],
206,
"response_status",
),
(
vec![
("cache-control", "public, max-age=60"),
("set-cookie", "a=1"),
],
200,
"response_set_cookie",
),
(
vec![("cache-control", "private, max-age=60")],
200,
"response_cache_control",
),
(
vec![("cache-control", "no-store")],
200,
"response_cache_control",
),
(
vec![("cache-control", "public, max-age=60"), ("vary", "*")],
200,
"response_vary",
),
(
vec![
("cache-control", "public, max-age=60"),
("vary", "Authorization"),
],
200,
"response_vary",
),
(
vec![
("cache-control", "public, max-age=60"),
("content-type", "text/html"),
],
200,
"response_static_dynamic",
),
(
vec![
("cache-control", "public, max-age=60"),
("content-type", "application/xhtml+xml"),
],
200,
"response_static_dynamic",
),
(
vec![("last-modified", "Mon, 01 Jan 2024 00:00:00 GMT")],
200,
"response_static_not_public",
),
(
vec![("cache-control", "max-age=0")],
200,
"response_static_not_public",
),
(
vec![("cache-control", "max-age=0"), ("expires", future.as_str())],
200,
"response_static_not_public",
),
(
vec![("expires", past.as_str())],
200,
"response_static_not_public",
),
(
vec![("cache-control", "max-age=1, max-age=2")],
200,
"response_cache_control_invalid",
),
(
vec![
("cache-control", "public"),
("surrogate-control", "no-store"),
],
200,
"response_surrogate_control",
),
] {
assert_eq!(check(status, &pairs), Some(reason), "{pairs:?}");
}
}
#[test]
fn vcl_import_and_rule_json_round_trip_cookie_pass() {
let imported = import_vcl(
"vcl 4.1;\nsub vcl_recv {\n if (req.http.Cookie ~ \"SESS[a-f0-9]+=\") {\n return (cookie_pass);\n }\n if (req.url ~ \"^/admin\") {\n return (pass);\n }\n}\n",
)
.unwrap();
assert!(imported.warnings.is_empty(), "{:?}", imported.warnings);
assert_eq!(imported.rules.len(), 2);
assert_eq!(imported.rules[0].actions, vec![RuleAction::CookiePass]);
assert!(imported.rules[0].stop);
assert_eq!(imported.rules[1].actions, vec![RuleAction::Pass]);
let json = serde_json::to_value(&imported.rules[0]).unwrap();
assert_eq!(json["actions"][0]["type"], "cookie_pass");
// A guard without a Cookie condition is rejected at import time.
let invalid = import_vcl(
"vcl 4.1;\nsub vcl_recv {\n if (req.url ~ \"^/x\") { return (cookie_pass); }\n}\n",
)
.unwrap();
assert!(invalid.rules.is_empty());
assert!(
invalid
.warnings
.iter()
.any(|w| w.contains("cookie_pass needs")),
"{:?}",
invalid.warnings
);
// Older configurations keep deserializing unchanged.
let legacy: Rule =
serde_json::from_value(serde_json::json!({"id": "x", "actions": [{"type": "pass"}]}))
.unwrap();
assert_eq!(legacy.actions, vec![RuleAction::Pass]);
}
#[test]
fn shipped_cdn_and_drupal_examples_relax_only_public_static_candidates() {
let settings = Settings::default();
for (vcl, has_private_paths) in [
(
include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/examples/vcl/cdn-technical-cookies.vcl"
)),
true,
),
(
include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/examples/vcl/drupal6-parent-session-cookies.vcl"
)),
false,
),
] {
let imported = import_vcl(vcl).unwrap();
assert!(imported.warnings.is_empty(), "{:?}", imported.warnings);
let rules = compile(imported.rules);
let session = [("cookie", "session=secret; _ga=1")];
let page = rules.evaluate_request(&get("/", &session), false);
assert_eq!(RuleGate::from_outcome(&page), RuleGate::CookieGuard);
assert!(relax(&rules, &get("/", &session), &settings).is_none());
assert!(relax(
&rules,
&get("/sites/all/themes/x/style.css", &session),
&settings
)
.is_some());
// Private paths are protected only by an explicit pass (or by
// cache.bypass_prefixes); the Drupal example has none.
assert_eq!(
relax(&rules, &get("/admin/style.css", &session), &settings).is_none(),
has_private_paths
);
assert!(relax(
&rules,
&get(
"/a.css",
&[("cookie", "session=1"), ("authorization", "Basic x")]
),
&settings
)
.is_none());
}
}
}
+71 -2
View File
@@ -145,7 +145,15 @@ pub struct RuleCondition {
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum RuleAction {
/// Explicit VCL `return(pass)`. Never relaxed by any global cache option.
Pass,
/// Cookie/session guard: BYPASS a request because it carries cookies.
/// Unlike `pass`, the central cache decision may let a *public static
/// asset* reach the cache when the global "Ignore request cookies for
/// static files" option is on and no other rule would bypass the same
/// request (see `cache::static_cookie_guard_relaxation`).
/// VCL: `return(cookie_pass)` (RustProxy extension).
CookiePass,
/// Explicit VCL return(hash): allow a Cookie-bearing request to reach lookup.
Lookup,
SetRequestHeader { name: String, value: String },
@@ -200,6 +208,7 @@ impl RuleAction {
fn stage(&self) -> RuleStage {
match self {
Self::Pass
| Self::CookiePass
| Self::Lookup
| Self::SetRequestHeader { .. }
| Self::RemoveRequestHeader { .. }
@@ -223,7 +232,7 @@ impl RuleAction {
}
fn aspect(&self) -> Option<&'static str> {
match self {
Self::Pass | Self::Lookup => Some("request_routing"),
Self::Pass | Self::CookiePass | Self::Lookup => Some("request_routing"),
Self::StripCookies { .. } | Self::RemoveNamedCookies { .. } => Some("request_cookies"),
Self::StripQuery { .. } => Some("request_query"),
Self::Ttl { .. } => Some("ttl"),
@@ -655,6 +664,7 @@ fn validate_action(action: &RuleAction) -> Result<()> {
);
}
RuleAction::Pass
| RuleAction::CookiePass
| RuleAction::Lookup
| RuleAction::NoStore
| RuleAction::AllowStore
@@ -691,6 +701,19 @@ pub fn rule_hit_counts() -> BTreeMap<String, u64> {
.collect()
}
/// A positive condition on the request Cookie header or on one cookie name.
fn condition_tests_cookie(condition: &RuleCondition) -> bool {
!condition.negate
&& match condition.field {
ConditionField::Cookie => true,
ConditionField::Header => condition
.name
.as_deref()
.is_some_and(|name| name.trim().eq_ignore_ascii_case("cookie")),
_ => false,
}
}
fn compile_rule(rule: &Rule, origin: RuleOrigin, scope: &str) -> Result<CompiledRule> {
ensure!(
crate::config::valid_id(&rule.id),
@@ -726,6 +749,13 @@ fn compile_rule(rule: &Rule, origin: RuleOrigin, scope: &str) -> Result<Compiled
validate_action(action)
.map_err(|error| anyhow::anyhow!("cache rule {}: {error}", rule.id))?;
}
if rule.actions.iter().any(|action| matches!(action, RuleAction::CookiePass)) {
ensure!(
rule.conditions.iter().any(condition_tests_cookie),
"cache rule {}: cookie_pass needs at least one non-negated Cookie condition; use pass for other bypass rules",
rule.id
);
}
let conditions = rule
.conditions
.iter()
@@ -986,6 +1016,10 @@ pub struct RuleOverride {
#[derive(Debug, Clone, Default, Serialize)]
pub struct RequestRuleOutcome {
pub pass: Option<String>,
/// True when the winning `pass` came from a `cookie_pass` guard rather
/// than from an explicit `pass`. Only such a bypass can be relaxed.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub pass_cookie_guard: bool,
pub lookup: Option<String>,
/// Ordered, validated edits applied to the forwarded request as well as
/// to the rule evaluation copy.
@@ -1111,6 +1145,29 @@ fn claim(
impl CompiledRules {
pub fn evaluate_request(&self, request: &RuleRequest, count: bool) -> RequestRuleOutcome {
self.evaluate_request_mode(request, count, false)
}
/// Evaluate request rules as if every `cookie_pass` guard were absent:
/// the guard action is skipped and its rule does not stop evaluation, so
/// any later explicit `pass` (or request edit) is still observed. Used by
/// the central static-cookie decision; never counts rule hits.
pub fn evaluate_request_without_cookie_guards(&self, request: &RuleRequest) -> RequestRuleOutcome {
self.evaluate_request_mode(request, false, true)
}
pub fn has_cookie_guards(&self) -> bool {
self.request.iter().chain(self.hash.iter()).any(|rule| {
rule.actions.iter().any(|action| matches!(action, RuleAction::CookiePass))
})
}
fn evaluate_request_mode(
&self,
request: &RuleRequest,
count: bool,
skip_cookie_guards: bool,
) -> RequestRuleOutcome {
let mut outcome = RequestRuleOutcome::default();
let mut owners = HashMap::new();
let mut header_owners: HashMap<String, RuleOrigin> = HashMap::new();
@@ -1129,7 +1186,12 @@ impl CompiledRules {
rule.counter.fetch_add(1, Ordering::Relaxed);
}
outcome.matched.push(info(rule));
let mut guard_skipped = false;
for action in &rule.actions {
if skip_cookie_guards && matches!(action, RuleAction::CookiePass) {
guard_skipped = true;
continue;
}
if let Some(aspect) = action.aspect() {
if !claim(&mut owners, &mut outcome.overridden, aspect, rule) {
continue;
@@ -1138,11 +1200,18 @@ impl CompiledRules {
match action {
RuleAction::Pass => {
outcome.pass = Some(rule.id.clone());
outcome.pass_cookie_guard = false;
outcome.lookup = None;
}
RuleAction::CookiePass => {
outcome.pass = Some(rule.id.clone());
outcome.pass_cookie_guard = true;
outcome.lookup = None;
}
RuleAction::Lookup => {
outcome.lookup = Some(rule.id.clone());
outcome.pass = None;
outcome.pass_cookie_guard = false;
},
RuleAction::SetRequestHeader { name, value } => {
let key = name.to_ascii_lowercase();
@@ -1209,7 +1278,7 @@ impl CompiledRules {
_ => {}
}
}
if rule.stop {
if rule.stop && !guard_skipped {
break;
}
}
+3
View File
@@ -24,3 +24,6 @@ include!("varnish_compatible_tests.rs");
#[cfg(test)]
include!("rules_tests.rs");
#[cfg(test)]
include!("policy/decision_tests.rs");
+4 -1
View File
@@ -558,6 +558,9 @@ fn vcl_actions(
};
match (stage, target.as_str()) {
(RuleStage::Request, "pass") => Ok(vec![RuleAction::Pass]),
// RustProxy extension: Cookie/session guard that the static
// cookie policy may relax for public static assets.
(RuleStage::Request, "cookie_pass") => Ok(vec![RuleAction::CookiePass]),
(RuleStage::Request, "hash") => Ok(vec![RuleAction::Lookup]),
(RuleStage::Request, "lookup") => Ok(vec![RuleAction::Lookup]),
(RuleStage::Response, "pass" | "hit_for_pass" | "uncacheable") => {
@@ -615,7 +618,7 @@ fn vcl_actions(
return Err("remove_req_cookies requires quoted cookie names or prefix* selectors".into());
}
let args = &tokens[2..tokens.len() - 1];
if args.len() % 2 == 0 {
if args.len().is_multiple_of(2) {
return Err("remove_req_cookies expects comma-separated quoted names".into());
}
let mut names = Vec::new();
+22 -7
View File
@@ -30,14 +30,23 @@ impl CachePlan {
}
pub(super) fn with_vcl_cookie_lookup(mut self, allowed: bool) -> Self {
if let Self::Enabled { vcl_cookie_lookup, .. } = &mut 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, .. })
matches!(
self,
Self::Enabled {
vcl_cookie_lookup: true,
..
}
)
}
pub(super) fn force_cache(self) -> bool {
@@ -74,11 +83,17 @@ impl CachePlan {
Self::Enabled {
force_cache: true, ..
} => crate::cache::forced_request_policy(method, headers, body_empty),
Self::Enabled { vcl_cookie_lookup, .. } => {
crate::cache::request_policy_with_vcl_cookie(
method, headers, body_empty, path, has_query, settings, vcl_cookie_lookup,
)
}
Self::Enabled {
vcl_cookie_lookup, ..
} => crate::cache::request_policy_with_vcl_cookie(
method,
headers,
body_empty,
path,
has_query,
settings,
vcl_cookie_lookup,
),
}
}
}
+37 -27
View File
@@ -126,7 +126,18 @@ if let Some(exchange) = request.extensions().get::<Arc<Exchange>>() {
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;
let mut cache_rule_gate = crate::cache::RuleGate::None;
// Security and configuration gates are known before any rule runs; they always
// win, so a Cookie guard is only ever relaxed when none of them applies.
let gate_input = crate::cache::GateInput {
admin_control_plane,
basic_auth: frontend.is_some_and(|f| f.basic_auth.is_some()),
auth_provider: frontend.and_then(|f| f.auth_provider.as_ref()).map(|p| p.id()),
sticky_cookie: route.pool.as_ref().is_some_and(|pool| pool.cookie_affinity()),
cache_enabled: cache_settings.enabled,
route_disabled: route.cache == Some(false),
upgrade: handshake.is_some(),
};
let mut cache_rule_lookup = false;
// VCL request mutations (cookie/query edits) still affect the origin when
// cache storage is disabled for this route. Storage eligibility is evaluated
@@ -141,7 +152,21 @@ if !admin_control_plane {
headers: request.headers().clone(),
client_ip: Some(context.client_ip),
};
let outcome = rules.evaluate_request(&rule_request, true);
let mut outcome = rules.evaluate_request(&rule_request, true);
cache_rule_gate = crate::cache::RuleGate::from_outcome(&outcome);
// Central static-cookie decision: a `cookie_pass` guard (never an
// explicit `pass`) may yield to the static-file cookie policy. The
// unguarded outcome then drives the forwarded request and cache key.
if cache_rule_gate == crate::cache::RuleGate::CookieGuard
&& crate::cache::request_gate(gate_input, crate::cache::RuleGate::None).is_none()
{
if let Some(relaxed) = crate::cache::static_cookie_guard_relaxation(
&rules, &rule_request, &outcome, cache_settings,
) {
outcome = relaxed.outcome;
cache_rule_gate = crate::cache::RuleGate::CookieGuardRelaxed;
}
}
if !outcome.matched.is_empty() {
outcome.apply_headers(request.headers_mut());
outcome.rewrite_cookies(request.headers_mut());
@@ -160,7 +185,6 @@ if !admin_control_plane {
}
}
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);
@@ -174,29 +198,9 @@ if !admin_control_plane {
}
}
}
let policy_reason = if admin_control_plane {
Some("admin_control_plane")
} else if frontend.is_some_and(|f| f.basic_auth.is_some()) {
Some("basic_auth")
} else if let Some(provider) = frontend.and_then(|f| f.auth_provider.as_ref()) {
Some(provider.id())
} else if route
.pool
.as_ref()
.is_some_and(|pool| pool.cookie_affinity())
{
Some("sticky_cookie")
} else if !cache_settings.enabled {
Some("cache_disabled")
} else if route.cache == Some(false) {
Some("route_disabled")
} else if handshake.is_some() {
Some("request_upgrade")
} else if cache_rule_pass {
Some("cache_rule")
} else {
None
};
let policy_reason = crate::cache::request_gate(gate_input, cache_rule_gate);
let static_cookie_relaxed = policy_reason.is_none()
&& cache_rule_gate == crate::cache::RuleGate::CookieGuardRelaxed;
let cache_enabled = policy_reason.is_none();
let body_empty = if cache_enabled
&& handshake.is_none()
@@ -339,7 +343,12 @@ let range_requested = !matches!(range_selection, crate::cache::RangeSelection::N
let cache_route = route.id.as_str();
let mut cache_key_headers = None;
if effective_cacheable && ignore_static_cookie && request.headers().contains_key(::http::header::COOKIE) {
// The forwarded request still carries a Cookie that the cache key ignores:
// the backend response must prove that it is shareable before storage.
let shared_static_cookie_fill = effective_cacheable
&& ignore_static_cookie
&& request.headers().contains_key(::http::header::COOKIE);
if shared_static_cookie_fill {
let mut headers = request.headers().clone();
headers.remove(::http::header::COOKIE);
cache_key_headers = Some(headers);
@@ -390,5 +399,6 @@ let miss_recorded = false;
range_selection, if_range, range_requested, effective_reason, revalidation_reason,
cache_ticket, client_conditionals, cached_revalidation, freshness_revalidation_reason,
pending_revalidation, miss_recorded, cache_rule_context,
static_cookie_relaxed, shared_static_cookie_fill,
)
}
@@ -0,0 +1,670 @@
// End-to-end regression tests for the static-asset Cookie policy and the
// central cache decision (cache::request_gate / static_cookie_guard_relaxation
// / shared_static_response_reason). They drive the real proxy router against
// an in-process origin and inspect X-Cache, X-Cache-Reason, Cache-Status and
// the number of origin requests.
mod static_cookie_policy_tests {
use super::*;
use crate::{
auth::Auth,
config::{self, Config, ValidationPolicy},
db::Store,
};
use std::collections::HashMap as Map;
use std::net::SocketAddr;
use std::sync::Mutex as StdMutex;
use std::time::SystemTime;
use tempfile::TempDir;
use tower::ServiceExt;
struct Fixture {
app: Arc<App>,
_directory: TempDir,
}
struct Received {
status: StatusCode,
headers: HeaderMap,
body: Bytes,
}
impl Received {
fn cache(&self) -> &str {
self.headers
.get("x-cache")
.and_then(|v| v.to_str().ok())
.unwrap_or("-")
}
fn reason(&self) -> &str {
self.headers
.get("x-cache-reason")
.and_then(|v| v.to_str().ok())
.unwrap_or("-")
}
fn body(&self) -> String {
String::from_utf8_lossy(&self.body).into_owned()
}
}
impl Fixture {
async fn new(config: Config) -> Self {
let directory = TempDir::new().unwrap();
let policy = ValidationPolicy {
tls_addr: None,
cert_dir: None,
data_dir: None,
proxy_addr: "127.0.0.1:8080".parse().unwrap(),
admin_addr: "127.0.0.1:9090".parse().unwrap(),
};
let store = Store::open(&directory.path().join("db"), &config)
.await
.unwrap();
let auth = Auth::new(store.clone(), directory.path().to_owned())
.await
.unwrap();
let snapshot = config::compile(config, 0, &policy).unwrap();
let app = App::new(
store,
snapshot,
policy,
auth,
32,
Duration::from_secs(5),
Duration::from_secs(5),
Duration::from_secs(30),
);
Self {
app,
_directory: directory,
}
}
async fn request(&self, method: Method, path: &str, headers: &[(&str, &str)]) -> Received {
let mut builder = Request::builder()
.method(method)
.uri(path)
.header(HOST, "localhost")
.header(USER_AGENT, "static-cookie-policy/1.0");
for (name, value) in headers {
builder = builder.header(*name, *value);
}
let mut request = builder.body(Body::empty()).unwrap();
request
.extensions_mut()
.insert(PeerAddr("192.0.2.60:40000".parse().unwrap()));
request
.extensions_mut()
.insert(LocalAddr("127.0.0.1:8080".parse().unwrap()));
let response = router(self.app.clone()).oneshot(request).await.unwrap();
let (parts, body) = response.into_parts();
let body = body.collect().await.unwrap().to_bytes();
Received {
status: parts.status,
headers: parts.headers,
body,
}
}
async fn get(&self, path: &str, headers: &[(&str, &str)]) -> Received {
self.request(Method::GET, path, headers).await
}
async fn stop(self) {
self.app.shutdown.cancel();
self.app.tunnels.close();
self.app.tunnels.wait().await;
self.app.store.close().await;
}
}
struct Origin {
addr: SocketAddr,
hits: Arc<StdMutex<Map<String, u64>>>,
task: tokio::task::JoinHandle<()>,
}
impl Origin {
fn count(&self, path: &str) -> u64 {
*self.hits.lock().unwrap().get(path).unwrap_or(&0)
}
}
impl Drop for Origin {
fn drop(&mut self) {
self.task.abort();
}
}
/// Origin with one behaviour per path. Bodies of *private* resources embed
/// the request Cookie, so any cross-user leak is visible in assertions.
async fn start_origin() -> Origin {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let hits: Arc<StdMutex<Map<String, u64>>> = Arc::default();
let counter = hits.clone();
let app = Router::new().fallback(move |request: Request| {
let counter = counter.clone();
async move {
let path = request.uri().path().to_owned();
*counter.lock().unwrap().entry(path.clone()).or_default() += 1;
let cookie = request
.headers()
.get("cookie")
.and_then(|v| v.to_str().ok())
.map(str::to_owned);
let gzip = request
.headers()
.get("accept-encoding")
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.contains("gzip"));
let now = SystemTime::now();
let mut headers: Vec<(&str, String)> = vec![
("date", httpdate::fmt_http_date(now)),
("etag", "\"v1\"".into()),
];
let mut status = StatusCode::OK;
let body: String;
match path.as_str() {
"/assets/app.css" | "/assets/auth.css" | "/assets/explicit.css" => {
headers.push(("content-type", "text/css".into()));
headers.push(("cache-control", "public, max-age=600".into()));
headers.push(("vary", "Accept-Encoding".into()));
body = "body{color:red}".into();
}
"/assets/drupal.js" => {
// Typical web-server static reply: max-age without public.
headers.push(("content-type", "application/javascript".into()));
headers.push(("cache-control", "max-age=1209600".into()));
body = "Drupal.behaviors={};".into();
}
"/fonts/site.woff2" => {
headers.push(("content-type", "font/woff2".into()));
headers.push((
"expires",
httpdate::fmt_http_date(now + Duration::from_secs(3600)),
));
body = "wOF2-font".into();
}
"/assets/vary.css" => {
headers.push(("content-type", "text/css".into()));
headers.push(("cache-control", "public, max-age=600".into()));
headers.push(("vary", "Cookie, Accept-Encoding".into()));
if gzip {
headers.push(("content-encoding", "gzip".into()));
body = "gzip-css".into();
} else {
body = "plain-css".into();
}
}
"/user/avatar.png" => {
// Private route: session required by the application.
match &cookie {
Some(cookie) => {
headers.push(("content-type", "image/png".into()));
headers.push(("cache-control", "public, max-age=600".into()));
body = format!("avatar-of[{cookie}]");
}
None => {
status = StatusCode::FORBIDDEN;
body = "forbidden".into();
}
}
}
"/assets/private.png" => {
headers.push(("content-type", "image/png".into()));
headers.push(("cache-control", "private, max-age=600".into()));
body = format!("private-png[{}]", cookie.as_deref().unwrap_or("-"));
}
"/assets/set-cookie.css" => {
headers.push(("content-type", "text/css".into()));
headers.push(("cache-control", "public, max-age=600".into()));
headers.push(("set-cookie", "SESSrefresh=1; Path=/".into()));
body = format!("refresh[{}]", cookie.as_deref().unwrap_or("-"));
}
"/assets/fallback.js" => {
// SPA fallback: HTML (personalised) under a .js name.
headers.push(("content-type", "text/html; charset=utf-8".into()));
headers.push(("cache-control", "public, max-age=600".into()));
body = format!("<html>hello [{}]</html>", cookie.as_deref().unwrap_or("-"));
}
"/assets/nofresh.css" => {
headers.push(("content-type", "text/css".into()));
headers.push(("last-modified", "Mon, 01 Jan 2024 00:00:00 GMT".into()));
body = format!("nofresh[{}]", cookie.as_deref().unwrap_or("-"));
}
_ => {
headers.push(("content-type", "text/html; charset=utf-8".into()));
headers.push(("cache-control", "public, max-age=600".into()));
body = format!("<p>page for [{}]</p>", cookie.as_deref().unwrap_or("-"));
}
}
let mut response = Response::new(Body::from(body));
*response.status_mut() = status;
for (name, value) in headers {
response
.headers_mut()
.append(name, HeaderValue::from_str(&value).unwrap());
}
response
}
});
let task = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
Origin { addr, hits, task }
}
fn rule(value: serde_json::Value) -> crate::cache::Rule {
serde_json::from_value(value).unwrap()
}
/// The security and session templates as shipped in 0.39.2 (cookie
/// guards use cookie_pass, everything else an explicit pass).
fn shipped_rules() -> Vec<crate::cache::Rule> {
vec![
rule(
serde_json::json!({"id": "methods", "conditions": [{"field": "method", "operator": "equals", "values": ["GET", "HEAD"], "negate": true}], "actions": [{"type": "pass"}], "stop": true}),
),
rule(
serde_json::json!({"id": "auth", "conditions": [{"field": "header", "name": "Authorization", "operator": "exists"}], "actions": [{"type": "pass"}], "stop": true}),
),
rule(
serde_json::json!({"id": "private-routes", "conditions": [{"field": "path", "operator": "regex", "values": ["^/(?:user|account|admin)(?:/|[?]|$)"]}], "actions": [{"type": "pass"}], "stop": true}),
),
rule(
serde_json::json!({"id": "drupal", "conditions": [{"field": "header", "name": "Cookie", "operator": "regex", "values": ["(?:^|;[ \\t]*)(?:S?SESS[a-fA-F0-9]+)="]}], "actions": [{"type": "cookie_pass"}], "stop": true}),
),
rule(
serde_json::json!({"id": "remaining-cookies", "conditions": [{"field": "header", "name": "Cookie", "operator": "exists"}], "actions": [{"type": "cookie_pass"}], "stop": true}),
),
]
}
fn test_config(origin: SocketAddr, rules: Vec<crate::cache::Rule>) -> Config {
let mut config = config::demo_config(origin);
config.cache.enabled = true;
config.cache.expose_status = true;
config.cache.expose_hits = true;
config.cache.expose_cache_status = true;
config.cache.expose_only_hits = false;
config.cache.static_ignore_cookies = true;
config.cache.static_ignore_vary_cookie = true;
config.cache.collapse_enabled = false;
config.cache.rules = rules;
config
}
const SESSION: &str = "session=abc123";
const DRUPAL6: &str = "SESS0123456789abcdef0123456789abcd=u7k2p; has_js=1";
#[tokio::test]
async fn public_css_without_and_with_session_cookie_reaches_hit() {
let origin = start_origin().await;
let fixture = Fixture::new(test_config(origin.addr, shipped_rules())).await;
// Anonymous: MISS -> HIT.
let first = fixture.get("/assets/app.css", &[]).await;
assert_eq!((first.cache(), first.reason()), ("MISS", "cache_miss"));
let second = fixture.get("/assets/app.css", &[]).await;
assert_eq!(second.cache(), "HIT");
// Logged-in on a different public asset: MISS (guard relaxed) -> HIT.
let logged = fixture
.get("/assets/auth.css", &[("cookie", SESSION)])
.await;
assert_eq!(logged.status, StatusCode::OK);
assert_eq!(
(logged.cache(), logged.reason()),
("MISS", crate::cache::REASON_MISS_STATIC_COOKIE)
);
let again = fixture
.get("/assets/auth.css", &[("cookie", SESSION)])
.await;
assert_eq!(again.cache(), "HIT");
// The same object is shared with anonymous clients and other users.
let anonymous = fixture.get("/assets/auth.css", &[]).await;
assert_eq!(anonymous.cache(), "HIT");
let other = fixture
.get("/assets/auth.css", &[("cookie", "session=zzz; theme=dark")])
.await;
assert_eq!(other.cache(), "HIT");
assert_eq!(origin.count("/assets/auth.css"), 1);
// Anonymous fill is reused by a logged-in client too.
let logged_app = fixture.get("/assets/app.css", &[("cookie", SESSION)]).await;
assert_eq!(logged_app.cache(), "HIT");
assert_eq!(origin.count("/assets/app.css"), 1);
assert!(logged_app
.headers
.get_all("cache-status")
.iter()
.any(|v| v.to_str().unwrap().starts_with("RustProxy; hit")));
fixture.stop().await;
}
#[tokio::test]
async fn drupal6_session_js_with_query_string_reaches_hit() {
let origin = start_origin().await;
let fixture = Fixture::new(test_config(origin.addr, shipped_rules())).await;
let first = fixture
.get("/assets/drupal.js?v=7.1", &[("cookie", DRUPAL6)])
.await;
assert_eq!(
(first.cache(), first.reason()),
("MISS", crate::cache::REASON_MISS_STATIC_COOKIE)
);
let second = fixture
.get("/assets/drupal.js?v=7.1", &[("cookie", DRUPAL6)])
.await;
assert_eq!(second.cache(), "HIT");
// Query string is part of the key: another version is a new object.
let other_version = fixture
.get("/assets/drupal.js?v=7.2", &[("cookie", DRUPAL6)])
.await;
assert_eq!(other_version.cache(), "MISS");
assert_eq!(origin.count("/assets/drupal.js"), 2);
// Drupal HTML for the same session is still bypassed by the guard.
let page = fixture.get("/node/1", &[("cookie", DRUPAL6)]).await;
assert_eq!(
(page.cache(), page.reason()),
("BYPASS", crate::cache::REASON_VCL_COOKIE_GUARD)
);
fixture.stop().await;
}
#[tokio::test]
async fn font_with_different_cookies_shares_one_entry_using_expires() {
let origin = start_origin().await;
let fixture = Fixture::new(test_config(origin.addr, shipped_rules())).await;
for (index, cookie) in ["session=a", "session=b; _ga=1", DRUPAL6, "x=1"]
.into_iter()
.enumerate()
{
let response = fixture
.get("/fonts/site.woff2", &[("cookie", cookie)])
.await;
assert_eq!(
response.cache(),
if index == 0 { "MISS" } else { "HIT" },
"{cookie}"
);
}
assert_eq!(origin.count("/fonts/site.woff2"), 1);
fixture.stop().await;
}
#[tokio::test]
async fn vary_cookie_static_is_shared_only_with_vary_option_and_keeps_encoding_variants() {
let origin = start_origin().await;
let fixture = Fixture::new(test_config(origin.addr, shipped_rules())).await;
let gzip = [("accept-encoding", "gzip")];
let anon_gzip = fixture.get("/assets/vary.css", &gzip).await;
assert_eq!(anon_gzip.cache(), "MISS");
assert_eq!(anon_gzip.headers["content-encoding"], "gzip");
assert!(!crate::cache::varies_on(&anon_gzip.headers, "cookie"));
assert!(crate::cache::varies_on(
&anon_gzip.headers,
"accept-encoding"
));
let logged_gzip = fixture
.get(
"/assets/vary.css",
&[("accept-encoding", "gzip"), ("cookie", SESSION)],
)
.await;
assert_eq!(logged_gzip.cache(), "HIT");
assert_eq!(logged_gzip.body(), "gzip-css");
// A different Accept-Encoding is a different variant ...
let logged_plain = fixture
.get(
"/assets/vary.css",
&[("accept-encoding", "identity"), ("cookie", "session=other")],
)
.await;
assert_eq!(logged_plain.cache(), "MISS");
assert_eq!(logged_plain.body(), "plain-css");
// ... and that variant is shared with anonymous identity clients.
let anon_plain = fixture
.get("/assets/vary.css", &[("accept-encoding", "identity")])
.await;
assert_eq!(anon_plain.cache(), "HIT");
assert_eq!(anon_plain.body(), "plain-css");
assert_eq!(origin.count("/assets/vary.css"), 2);
fixture.stop().await;
// Without the Vary: Cookie option nothing with Vary: Cookie is stored.
let origin = start_origin().await;
let mut config = test_config(origin.addr, shipped_rules());
config.cache.static_ignore_vary_cookie = false;
let fixture = Fixture::new(config).await;
for _ in 0..2 {
let response = fixture
.get(
"/assets/vary.css",
&[("accept-encoding", "gzip"), ("cookie", SESSION)],
)
.await;
assert_eq!(
(response.cache(), response.reason()),
("MISS", "response_vary_cookie")
);
assert!(crate::cache::varies_on(&response.headers, "cookie"));
}
assert_eq!(origin.count("/assets/vary.css"), 2);
fixture.stop().await;
}
#[tokio::test]
async fn logged_in_html_and_private_routes_stay_bypassed() {
let origin = start_origin().await;
let fixture = Fixture::new(test_config(origin.addr, shipped_rules())).await;
for _ in 0..2 {
let page = fixture.get("/", &[("cookie", SESSION)]).await;
assert_eq!(
(page.cache(), page.reason()),
("BYPASS", crate::cache::REASON_VCL_COOKIE_GUARD)
);
assert_eq!(page.body(), format!("<p>page for [{SESSION}]</p>"));
// A private-route image is protected by an explicit pass, which the
// static policy must never relax, even with a public-looking reply.
let avatar = fixture
.get("/user/avatar.png", &[("cookie", SESSION)])
.await;
assert_eq!((avatar.cache(), avatar.reason()), ("BYPASS", "cache_rule"));
assert_eq!(avatar.body(), format!("avatar-of[{SESSION}]"));
}
let anonymous = fixture.get("/user/avatar.png", &[]).await;
assert_eq!(anonymous.status, StatusCode::FORBIDDEN);
assert!(!anonymous.body().contains(SESSION));
assert_eq!(origin.count("/"), 2);
assert_eq!(origin.count("/user/avatar.png"), 3);
fixture.stop().await;
}
#[tokio::test]
async fn authorization_is_an_absolute_bypass_for_static_assets() {
let origin = start_origin().await;
// With the shipped Authorization rule ...
let fixture = Fixture::new(test_config(origin.addr, shipped_rules())).await;
let response = fixture
.get(
"/assets/app.css",
&[("authorization", "Bearer t"), ("cookie", SESSION)],
)
.await;
assert_eq!(
(response.cache(), response.reason()),
("BYPASS", "cache_rule")
);
fixture.stop().await;
// ... and without any rules (built-in policy).
let fixture = Fixture::new(test_config(origin.addr, Vec::new())).await;
for headers in [
vec![("authorization", "Bearer t")],
vec![("authorization", "Bearer t"), ("cookie", SESSION)],
] {
let response = fixture.get("/assets/app.css", &headers).await;
assert_eq!(
(response.cache(), response.reason()),
("BYPASS", "request_authorization")
);
}
assert_eq!(origin.count("/assets/app.css"), 3);
fixture.stop().await;
}
#[tokio::test]
async fn private_set_cookie_dynamic_and_unproven_statics_are_not_shared() {
let origin = start_origin().await;
let mut rules = shipped_rules();
// Operator response rules must not turn a private Cookie-bearing fill
// into a shared object.
rules.push(rule(serde_json::json!({"id": "force-png", "stage": "response", "conditions": [{"field": "path", "operator": "prefix", "values": ["/assets/private.png"]}], "actions": [{"type": "ignore_cache_control"}, {"type": "ttl", "seconds": 600}]})));
rules.push(rule(serde_json::json!({"id": "strip-sc", "stage": "response", "conditions": [{"field": "path", "operator": "prefix", "values": ["/assets/set-cookie.css"]}], "actions": [{"type": "strip_set_cookie"}]})));
let fixture = Fixture::new(test_config(origin.addr, rules)).await;
for (path, reason) in [
("/assets/private.png", "response_cache_control"),
("/assets/set-cookie.css", "response_set_cookie"),
("/assets/fallback.js", "response_static_dynamic"),
("/assets/nofresh.css", "response_static_not_public"),
] {
let logged = fixture.get(path, &[("cookie", SESSION)]).await;
assert_eq!(
(logged.cache(), logged.reason()),
("MISS", reason),
"{path}"
);
assert!(logged.body().contains(SESSION), "{path}");
// The next client must reach the origin and never see that body.
let anonymous = fixture.get(path, &[]).await;
assert_ne!(anonymous.cache(), "HIT", "{path}");
assert!(!anonymous.body().contains(SESSION), "{path}");
let other = fixture.get(path, &[("cookie", "session=other")]).await;
assert!(!other.body().contains(SESSION), "{path}");
}
fixture.stop().await;
}
#[tokio::test]
async fn explicit_vcl_pass_keeps_its_semantics() {
let origin = start_origin().await;
// 0.39.1 template shape: a plain pass on any Cookie.
let legacy = vec![rule(
serde_json::json!({"id": "any-cookie", "conditions": [{"field": "header", "name": "Cookie", "operator": "exists"}], "actions": [{"type": "pass"}], "stop": true}),
)];
let fixture = Fixture::new(test_config(origin.addr, legacy)).await;
for _ in 0..2 {
let logged = fixture
.get("/assets/explicit.css", &[("cookie", SESSION)])
.await;
assert_eq!((logged.cache(), logged.reason()), ("BYPASS", "cache_rule"));
}
assert_eq!(
fixture.get("/assets/explicit.css", &[]).await.cache(),
"MISS"
);
assert_eq!(
fixture.get("/assets/explicit.css", &[]).await.cache(),
"HIT"
);
// The anonymous object is still not served to the explicitly passed client.
let logged = fixture
.get("/assets/explicit.css", &[("cookie", SESSION)])
.await;
assert_eq!(logged.cache(), "BYPASS");
assert_eq!(origin.count("/assets/explicit.css"), 4);
fixture.stop().await;
// An explicit pass placed after a terminal Cookie guard still applies.
let origin = start_origin().await;
let mut rules = vec![rule(
serde_json::json!({"id": "any-cookie", "conditions": [{"field": "header", "name": "Cookie", "operator": "exists"}], "actions": [{"type": "cookie_pass"}], "stop": true}),
)];
rules.push(rule(serde_json::json!({"id": "preview", "conditions": [{"field": "cookie", "name": "preview", "operator": "exists"}], "actions": [{"type": "pass"}]})));
let fixture = Fixture::new(test_config(origin.addr, rules)).await;
for _ in 0..2 {
let preview = fixture
.get(
"/assets/explicit.css",
&[("cookie", "preview=1; session=a")],
)
.await;
assert_eq!(preview.cache(), "BYPASS");
}
let session = fixture
.get("/assets/explicit.css", &[("cookie", "session=a")])
.await;
assert_eq!(session.cache(), "MISS");
assert_eq!(origin.count("/assets/explicit.css"), 3);
fixture.stop().await;
}
#[tokio::test]
async fn get_and_head_share_the_same_static_cookie_decision() {
let origin = start_origin().await;
let fixture = Fixture::new(test_config(origin.addr, shipped_rules())).await;
let mut anonymous = Vec::new();
let mut logged = Vec::new();
for method in [Method::HEAD, Method::GET, Method::HEAD] {
// A HEAD miss is filled from an upstream GET whose body is stored
// in the background; let both fills settle before the next step.
tokio::time::sleep(Duration::from_millis(150)).await;
anonymous.push(
fixture
.request(method.clone(), "/assets/app.css", &[])
.await
.cache()
.to_owned(),
);
logged.push(
fixture
.request(method, "/assets/auth.css", &[("cookie", SESSION)])
.await
.cache()
.to_owned(),
);
}
assert_eq!(anonymous, logged);
assert_eq!(logged, ["MISS", "HIT", "HIT"]);
// GET-filled object answers a logged HEAD and vice versa.
let head = fixture
.request(Method::HEAD, "/assets/app.css", &[("cookie", DRUPAL6)])
.await;
assert_eq!(head.cache(), "HIT");
assert!(head.body.is_empty());
assert_eq!(
origin.count("/assets/app.css"),
origin.count("/assets/auth.css")
);
fixture.stop().await;
}
#[tokio::test]
async fn disabled_static_cookie_options_keep_previous_behaviour() {
let origin = start_origin().await;
let mut config = test_config(origin.addr, shipped_rules());
config.cache.static_ignore_cookies = false;
config.cache.static_ignore_vary_cookie = false;
let fixture = Fixture::new(config).await;
for _ in 0..2 {
let logged = fixture.get("/assets/app.css", &[("cookie", SESSION)]).await;
assert_eq!(
(logged.cache(), logged.reason()),
("BYPASS", crate::cache::REASON_VCL_COOKIE_GUARD)
);
}
assert_eq!(origin.count("/assets/app.css"), 2);
fixture.stop().await;
// Without rules, the built-in Cookie policy still bypasses.
let origin = start_origin().await;
let mut config = test_config(origin.addr, Vec::new());
config.cache.static_ignore_cookies = false;
let fixture = Fixture::new(config).await;
let logged = fixture.get("/assets/app.css", &[("cookie", SESSION)]).await;
assert_eq!(
(logged.cache(), logged.reason()),
("BYPASS", "request_cookie")
);
fixture.stop().await;
}
}
+7 -1
View File
@@ -122,7 +122,13 @@ let reason = effective_reason
if cache_ticket.is_some() && transformed_plan.is_none() {
"response_headers_policy"
} else if cache_ticket.is_some() {
if force_cache { "cache_miss_forced" } else { "cache_miss" }
if force_cache {
"cache_miss_forced"
} else if static_cookie_relaxed {
crate::cache::REASON_MISS_STATIC_COOKIE
} else {
"cache_miss"
}
} else {
"configuration_changed"
}
+13 -1
View File
@@ -112,6 +112,15 @@ if handshake.as_ref().is_some_and(|handshake| {
"RustProxy: HTTP/1.1 WebSocket upstream returned 2xx without switching protocols\n",
);
}
// Shared-static guard runs on the *original* backend headers, before VCL
// response edits such as strip_set_cookie or ignore_cache_control.
let shared_static_reason = if shared_static_cookie_fill && cache_ticket.is_some() {
crate::cache::shared_static_response_reason(
response.status(), response.headers(), cache_settings,
)
} else {
None
};
let cache_rule_overrides = cache_rule_context
.as_ref()
.map(|rules| rules.response_overrides(response.status(), response.headers()))
@@ -137,6 +146,7 @@ crate::cache::normalize_static_cookie_vary(
upstream_started.elapsed(), ignore_static_cookie, &cache_rule_overrides,
);
let origin_plan = if cache_ticket.is_some()
&& shared_static_reason.is_none()
&& !(ignore_static_cookie && crate::cache::varies_on(response.headers(), "cookie"))
{
crate::cache::plan_with(
@@ -153,7 +163,9 @@ let origin_plan = if cache_ticket.is_some()
None
};
let origin_reason = (cache_ticket.is_some() && origin_plan.is_none()).then(|| {
if ignore_static_cookie && crate::cache::varies_on(response.headers(), "cookie") {
if let Some(reason) = shared_static_reason {
reason
} else if ignore_static_cookie && crate::cache::varies_on(response.headers(), "cookie") {
"response_vary_cookie"
} else {
crate::cache::response_reason(response.status(), response.headers(), cache_settings)
+7 -1
View File
@@ -126,7 +126,13 @@ if websocket_upstream_h2 {
}
let request_body_empty = request.body().size_hint().exact() == Some(0);
let proactive_base_headers = if cache_ticket.is_some() && cache_settings.proactive_refresh_enabled {
request.headers().clone()
let mut headers = request.headers().clone();
// A cookie-independent static entry is refreshed as an anonymous
// request; never replay one client's session to fill a shared object.
if shared_static_cookie_fill {
headers.remove(::http::header::COOKIE);
}
headers
} else { HeaderMap::new() };
let response_header_timeout = frontend
.and_then(|frontend| frontend.proxy_timeouts.response_header_timeout())
+2
View File
@@ -597,6 +597,8 @@ async fn forward_request(
pending_revalidation,
mut miss_recorded,
cache_rule_context,
static_cookie_relaxed,
shared_static_cookie_fill,
) = include!("forward/route_cache.rs");
let (serve_stale, mut fill_leader) = include!("forward/cache_lookup.rs");
+2
View File
@@ -18,3 +18,5 @@ include!("forward/h3_navigation_tests.rs");
include!("cache_http_invalidation_tests.rs");
#[cfg(test)]
include!("forward/cache_fast_path_tests.rs");
#[cfg(test)]
include!("forward/static_cookie_policy_tests.rs");