This commit is contained in:
Mateusz Gruszczyński committed 2026-11-20 19:51:27 +01:00
1 parent 15425fb803
commit 0fc9c0d239
21 files changed
+395 -36

No files matched your search

+14 -1
View File
@@ -177,6 +177,19 @@ 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.
publiccookies: () => [{
name: t("cacheRuleTplPubliccookies"), enabled: false, stage: "request", match: "all",
conditions: [
{ field: "method", operator: "equals", values: ["GET", "HEAD"] },
{ field: "header", name: "Cookie", operator: "exists" },
{ 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,
}],
tracking: () => [{ name: t("cacheRuleTplTracking"), stage: "request", match: "all", conditions: [], actions: [{ type: "strip_query", params: ["utm_*", "fbclid", "gclid", "msclkid", "mc_cid", "mc_eid", "_ga"] }] }],
api: () => [{ name: t("cacheRuleTplApi"), stage: "request", match: "all", conditions: [{ field: "path", operator: "prefix", values: ["/api/"] }], actions: [{ type: "pass" }] }],
language: () => [{ name: t("cacheRuleTplLanguage"), stage: "request", match: "all", conditions: [], actions: [{ type: "hash_cookie", name: "lang" }] }],
@@ -274,7 +287,7 @@ window.rustProxyCacheRules = (() => {
helpLinks.append(guide, docs);
root.append(helpLinks);
}
const templates = select([["", t("cacheRulesTemplates")], ...Object.keys(TEMPLATES).map(key => [key, t(`cacheRuleTpl${key[0].toUpperCase()}${key.slice(1)}`)])], "", t("cacheRulesTemplates"));
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"));
templates.classList.add("cache-rules-templates");
const importButton = el("button", t("cacheRulesImportVcl"), "outline"); importButton.type = "button";
const exportButton = el("button", t("cacheRulesExportVcl"), "outline"); exportButton.type = "button";
+7
View File
@@ -190,6 +190,13 @@ impl Candidate {
}
}
/// A response body still owns an active cache fill. The proxy uses this
/// marker to finish filling a cacheable HEAD miss without sending a body.
#[derive(Clone, Copy)]
pub(crate) struct PendingFill {
pub max_body_bytes: usize,
}
struct FillBody {
inner: Body,
candidate: Option<Candidate>,
+9 -2
View File
@@ -205,13 +205,20 @@ impl Cache {
candidate.finish();
return Response::from_parts(parts, body);
}
Response::from_parts(
// A HEAD miss is fetched upstream as GET. The proxy must still consume
// the GET body to publish this candidate before stripping the body for
// the HEAD client. Mark *only* responses with a live fill candidate.
let mut response = Response::from_parts(
parts,
Body::new(FillBody {
inner: body,
candidate: Some(candidate),
done: false,
}),
)
);
response.extensions_mut().insert(PendingFill {
max_body_bytes: settings.max_object_bytes,
});
response
}
}
+66
View File
@@ -1061,4 +1061,70 @@ sub vcl_deliver {
post.method = Method::POST;
assert!(compiled.evaluate_request(&post, false).pass.is_some());
}
#[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();
for cookie in [
"sso_session=secret",
"sso_session=secret; marketing_id=xyz",
"tracking=one; unknown=two",
] {
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}");
let mut forwarded = input.headers.clone();
outcome.rewrite_cookies(&mut forwarded);
assert!(!forwarded.contains_key(http::header::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"),
]);
let outcome = compiled.evaluate_request(&split, false);
let mut forwarded = split.headers.clone();
outcome.rewrite_cookies(&mut forwarded);
assert!(!forwarded.contains_key(http::header::COOKIE));
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")]);
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}");
}
let with_auth = request("/rezerwa/15", None, &[
("cookie", "session=secret"), ("authorization", "Bearer access"),
]);
let outcome = compiled.evaluate_request(&with_auth, false);
assert!(outcome.lookup.is_none());
assert!(outcome.strip_cookies.is_none());
for method in [Method::POST, Method::PUT, Method::DELETE] {
let mut input = request("/rezerwa/15", None, &[("cookie", "session=secret")]);
input.method = method;
let outcome = compiled.evaluate_request(&input, false);
assert!(outcome.lookup.is_none());
assert!(outcome.strip_cookies.is_none());
}
let mut head = request("/rezerwa/15", None, &[("cookie", "parent=secret")]);
head.method = Method::HEAD;
assert!(compiled.evaluate_request(&head, false).lookup.is_some());
}
}
+128 -1
View File
@@ -41,6 +41,38 @@ fn should_replace_error_page(response: &Response, minimal_welcome: bool) -> bool
.is_none()
}
// A cacheable HEAD miss is sent to the origin as GET. The resulting body
// must be read to EOF for FillBody to publish the entry; dropping it here
// would turn every cold HEAD into another MISS. Only drain bodies explicitly
// marked by the cache layer. Enforce byte and wall-clock limits so a broken
// origin cannot leave unbounded detached work after the HEAD response.
fn strip_head_response_body(response: &mut Response) {
let fill = response.extensions_mut().remove::<crate::cache::PendingFill>();
let body = std::mem::replace(response.body_mut(), Body::empty());
if let Some(fill) = fill {
tokio::spawn(async move {
let _ = tokio::time::timeout(Duration::from_secs(30), async move {
let mut body = body;
let mut received = 0usize;
while let Some(frame) = body.frame().await {
match frame {
Ok(frame) => {
if let Some(data) = frame.data_ref() {
received = received.saturating_add(data.len());
if received > fill.max_body_bytes {
break;
}
}
}
Err(_) => break,
}
}
})
.await;
});
}
}
async fn observe(state: Arc<App>, mut request: Request) -> Response {
let snapshot = state.config.load_full();
let selected = response_context(&snapshot, &request);
@@ -478,7 +510,7 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
.fetch_add(1, Ordering::Relaxed);
}
if is_head {
*response.body_mut() = Body::empty();
strip_head_response_body(&mut response);
}
let response_read_timeout = frontend_context
.as_ref()
@@ -518,6 +550,101 @@ fn effective_host(request: &Request, tls: bool) -> Result<HeaderValue, ()> {
}
}
#[cfg(test)]
mod head_cache_fill_tests {
use super::*;
#[tokio::test]
async fn head_miss_finishes_cache_fill_without_delivering_body() {
let cache = crate::cache::Cache::new(1);
let settings = crate::cache::Settings {
enabled: true,
varnish_compatible: false,
..Default::default()
};
let ticket = cache
.ticket(1, "https", "example.test", "app", "/head", &HeaderMap::new())
.expect("valid cache ticket");
let mut origin = Response::new(Body::from("cached from HEAD"));
origin.headers_mut().insert(
::http::header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=60"),
);
origin.headers_mut().insert(
::http::header::CONTENT_LENGTH,
HeaderValue::from_static("16"),
);
let plan = crate::cache::plan(
StatusCode::OK,
origin.headers(),
&settings,
Duration::ZERO,
)
.expect("cacheable GET representation");
let mut head = cache.wrap(origin, ticket.clone(), plan, &settings);
assert!(head.extensions().get::<crate::cache::PendingFill>().is_some());
strip_head_response_body(&mut head);
assert_eq!(head.headers()[::http::header::CONTENT_LENGTH], "16");
assert!(head.body().is_end_stream(), "HEAD must have no response body");
assert!(head.extensions().get::<crate::cache::PendingFill>().is_none());
// The cache fill is detached from the HEAD response. It must finish
// independently, allowing a later GET or HEAD to reuse this object.
let hit = tokio::time::timeout(Duration::from_secs(2), async {
loop {
if let Some(hit) = cache.get(&ticket) {
break hit;
}
tokio::task::yield_now().await;
}
})
.await
.expect("HEAD fill should populate cache");
assert_eq!(
hit.response.into_body().collect().await.unwrap().to_bytes(),
Bytes::from_static(b"cached from HEAD")
);
}
#[tokio::test]
async fn oversized_head_fill_is_not_published() {
let cache = crate::cache::Cache::new(1);
let settings = crate::cache::Settings {
enabled: true,
varnish_compatible: false,
max_object_bytes: 1024,
..Default::default()
};
let ticket = cache
.ticket(1, "https", "example.test", "app", "/too-big", &HeaderMap::new())
.expect("valid cache ticket");
let mut origin = Response::new(Body::from(Bytes::from(vec![b'x'; 1025])));
origin.headers_mut().insert(
::http::header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=60"),
);
let plan = crate::cache::plan(
StatusCode::OK,
origin.headers(),
&settings,
Duration::ZERO,
)
.expect("cacheable headers, unknown body length");
let mut head = cache.wrap(origin, ticket.clone(), plan, &settings);
strip_head_response_body(&mut head);
assert!(head.body().is_end_stream());
tokio::time::sleep(Duration::from_millis(20)).await;
assert!(cache.get(&ticket).is_none(), "oversized HEAD must not be cached");
}
#[tokio::test]
async fn head_without_cache_fill_drops_body() {
let mut response = Response::new(Body::from("not cacheable"));
strip_head_response_body(&mut response);
assert!(response.body().is_end_stream());
}
}
#[cfg(test)]
mod auth_provider_page_interception_tests {
use super::*;