From 5b2eaaff61afb216f31d0d49304386ebe72b5962 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Gruszczy=C5=84ski?= Date: Fri, 20 Nov 2026 23:14:19 +0100 Subject: [PATCH] v0.39.2 --- AGENTS.md | 2 +- CHANGELOG.md | 7 + Cargo.lock | 2 +- Cargo.toml | 2 +- docs/CACHE.md | 71 +- docs/CACHE_TEMPLATE_LIBRARY.md | 18 +- docs/FEATURES.md | 2 +- docs/VCL.md | 7 +- docs/VCL_SUPPORT_MATRIX.md | 5 +- docs/VCL_TRAFFIC_COOKBOOK.md | 18 +- docs/WEB_SERVER.md | 2 +- examples/vcl/cdn-technical-cookies.vcl | 6 +- .../vcl/drupal6-parent-session-cookies.vcl | 8 +- langs/en_US.json | 31 +- langs/pl_pl.json | 31 +- src/admin/cache_rules.rs | 47 +- src/admin/openapi.json | 7 +- src/admin/tests.rs | 53 ++ src/admin/web/cache-rules.js | 71 +- src/cache/policy.rs | 1 + src/cache/policy/decision.rs | 299 ++++++++ src/cache/policy/decision_tests.rs | 520 ++++++++++++++ src/cache/rules.rs | 73 +- src/cache/tests.rs | 3 + src/cache/vcl.rs | 5 +- src/proxy/cache_plan/mod.rs | 29 +- src/proxy/forward/route_cache.rs | 64 +- .../forward/static_cookie_policy_tests.rs | 670 ++++++++++++++++++ src/proxy/forward/success_finish.rs | 8 +- src/proxy/forward/success_prepare.rs | 14 +- src/proxy/forward/upstream.rs | 8 +- src/proxy/forward_entry.rs | 2 + src/proxy/mod.rs | 2 + tools/README.md | 1 + tools/dev/cache_edge_smoke.py | 537 ++++++++++++++ tools/dev/test_cache_rules_panel.js | 20 + 36 files changed, 2544 insertions(+), 102 deletions(-) create mode 100644 src/cache/policy/decision.rs create mode 100644 src/cache/policy/decision_tests.rs create mode 100644 src/proxy/forward/static_cookie_policy_tests.rs create mode 100755 tools/dev/cache_edge_smoke.py diff --git a/AGENTS.md b/AGENTS.md index e179029..297a784 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # RustProxy source and documentation maintenance -Current source version: **0.39.1**. The Cargo package and binary are named `rust-proxy`. +Current source version: **0.39.2**. The Cargo package and binary are named `rust-proxy`. Before editing, read [README.md](README.md), the relevant [documentation guide](docs/README.md) and the actual code and tests. Historical release experiments are not current specifications. Use the bundled `src/admin/openapi.json` for API routes and payloads; the source implementation is authoritative for runtime behavior. diff --git a/CHANGELOG.md b/CHANGELOG.md index e0c0184..f6386d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ Release history focused on **features, settings, default behavior, compatibility and fixes**. Changes to internal code structure and preliminary performance experiments are intentionally omitted. Historical descriptions reflect their respective releases; consult the current documentation for the settings available in the latest release. +## 0.39.2 — Central cache decision and public static assets for logged-in users + +- **Static assets for logged-in users:** fixed public CSS/JS/images/fonts getting `BYPASS / cache_rule` as soon as a browser carried a session cookie. Root cause: a request-stage `pass` from a session/Cookie rule disabled the cache in `route_cache.rs` before the static-cookie options (`static_ignore_cookies`, `static_ignore_vary_cookie`) were consulted. Added a central decision (`cache::request_gate`, `static_cookie_guard_relaxation`, `shared_static_response_reason`) with fixed precedence: security, configuration, explicit VCL `pass`, VCL Cookie guard, default request policy, backend response. New request action `cookie_pass` (VCL `return(cookie_pass)`, RustProxy extension) marks Cookie/session guards; it is relaxed only for GET/HEAD static-extension requests without `Authorization` when no other rule would bypass the request with guards removed or without cookies. Explicit `pass` is never relaxed and existing configurations are not rewritten; the rules editor offers **Convert to Cookie guard** for Cookie-only `pass` rules. Session, framework and CDN remaining-cookie templates now insert `cookie_pass` (WordPress/WooCommerce split into a path `pass` and a Cookie guard). A static fill whose Cookie is ignored in the key is stored only if the original backend reply is 200, explicitly public (`public`, `s-maxage`, `max-age>0` or future `Expires`), not HTML/XHTML and has no `Set-Cookie`, `private`, `no-store`, `Vary: *` or `Vary: Authorization` — evaluated before response rules, so `strip_set_cookie`/`ignore_cache_control` cannot share a private reply; such fills are refreshed proactively without the client Cookie. New reason codes `cache_rule_cookie`, `cache_miss_static_cookie`, `response_static_not_public`, `response_static_dynamic`; header names and formats are unchanged. **Test a request** uses the same decision and reports `reason_class`, `static_cookie_relaxed` and `shared_static_check`. Downgrading to 0.39.1 or older requires converting `cookie_pass` rules back to `pass`. Unit and proxy integration tests cover the regression matrix (anonymous/session CSS, Drupal 6 JS with query, fonts, `Vary: Cookie` + `Accept-Encoding` variants, HTML, private routes, Authorization, private/Set-Cookie/HTML/unproven statics, explicit pass, GET/HEAD, options off). +- **Configuration compatibility:** configurations without `cookie_pass` are unchanged and load in both directions. A configuration that uses `cookie_pass` is rejected by 0.39.1 and older. +- **Edge-case smoke test:** added `tools/dev/cache_edge_smoke.py`, a dependency-free black-box test of the real binary. `local` starts a mock origin and a headless proxy and runs 67 cache/VCL edge cases with cross-user leak detection (split and non-UTF-8 Cookie fields, `%2E`/path-parameter paths, HEAD/Range/304, compression and `Vary` variants, request coalescing with concurrent users); `remote` runs read-only checks against a deployed vhost with diagnostic headers enabled. +- **Maintenance:** `cargo fmt --check` and `cargo clippy` are clean again (`cache_plan` formatting, `is_multiple_of` in the VCL importer). + ## 0.39.1 — HEAD cache-fill and public Vhost cookie template (source-only changes) - **Selective Drupal 6 parent-session cleanup (0.39.1, no version bump):** the existing `remove_req_cookies(...)` / `remove_named_cookies` action now supports one case-sensitive trailing wildcard (for example `SESS*` or `SSESS*`), while exact-name matching and all separate CDN templates remain intact. Empty, shorter-than-3-character and embedded wildcard patterns are rejected. Added an opt-in VCL example that preserves local `session` cookies and explicit `BYPASS`, Rust regression cases and PL/EN UI hints. Verify cookie ownership before enabling and test logged-in sessions against a real origin. diff --git a/Cargo.lock b/Cargo.lock index 98adbbb..5615d13 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1914,7 +1914,7 @@ dependencies = [ [[package]] name = "rust-proxy" -version = "0.39.1" +version = "0.39.2" dependencies = [ "anyhow", "arc-swap", diff --git a/Cargo.toml b/Cargo.toml index 1b97860..2c45920 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rust-proxy" -version = "0.39.1" +version = "0.39.2" edition = "2021" rust-version = "1.99.1" description = "RustProxy - independent reverse proxy with local administration" diff --git a/docs/CACHE.md b/docs/CACHE.md index c5b9516..c016557 100644 --- a/docs/CACHE.md +++ b/docs/CACHE.md @@ -119,13 +119,78 @@ With the policy enabled, the middle request stays `HIT` if the entry is fresh. C In **Vhosts → Cache**, overrides for static extensions, bypass path prefixes and unsafe force targets each place the enable/override checkbox immediately above the associated multiline list. The fields are disabled while their individual override is off; their saved values and cache policy are unchanged. Never enable unsafe forced caching for personalized responses. +## Cache decision precedence, explicit `pass` and public static assets + +**Applies to RustProxy 0.39.2.** Every reason that keeps a request away from the HOT/COLD cache is classified by one central decision (`src/cache/policy/decision.rs`), used by live traffic and by **Test a request**. Reasons are evaluated strongest first: + +| # | Source | Examples (`X-Cache-Reason`) | Can a static-file option override it? | +|---|---|---|---| +| 1 | **Security** | `admin_control_plane`, `basic_auth`, auth provider id (`tinyauth`, `oidc`, …), `sticky_cookie`, `request_authorization` | Never | +| 2 | **Configuration** | `cache_disabled`, `route_disabled`, `request_upgrade` | Never | +| 3 | **Explicit VCL `pass`** (`return(pass)`, action `pass`) | `cache_rule` | Never | +| 4 | **VCL Cookie guard** (`return(cookie_pass)`, action `cookie_pass`) | `cache_rule_cookie` | Yes, for public static assets only (below) | +| 5 | **Default request policy** | `request_cookie`, `request_method`, `request_body`, `path_excluded`, `query_excluded`, `request_no_store`, … | `request_cookie` only, for configured static extensions (existing behavior) | +| 6 | **Backend response** | `response_status`, `response_set_cookie`, `response_cache_control`, `response_vary`, `response_vary_cookie`, `response_static_not_public`, `response_static_dynamic`, … | Never | + +### `pass` versus `cookie_pass` + +- **`pass`** is an explicit, absolute bypass. RustProxy never relaxes it, whatever the resource type or the global options. Existing rules and imported `return(pass)` keep exactly this meaning; there is no automatic conversion. +- **`cookie_pass`** is a *Cookie/session guard*: "bypass because this request carries (session) cookies". For pages, HTML, APIs and every other non-static request it behaves exactly like `pass`. A `cookie_pass` rule must have at least one non-negated Cookie condition (the `cookie` field or the `Cookie` request header); other bypass reasons belong in a separate `pass` rule. In VCL it is written `return(cookie_pass);` — a **RustProxy extension** (stock Varnish only knows `return(pass)`). +- The session templates (**Any Cookie**, **Common session cookies**, WordPress/WooCommerce cookies, Django, Laravel/PHP, Auth.js, ASP.NET, Drupal) and **CDN: bypass remaining cookies** now insert `cookie_pass`. Path, method, Authorization, preview, checkout, webhook and other guards still insert `pass`. WordPress and WooCommerce now insert two rules (explicit path `pass` + Cookie guard) instead of one mixed *any* rule. + +### Public static assets with a session cookie + +Before this change a logged-in browser got `BYPASS / cache_rule` for every CSS, JS, image and font, because the session rule ran first and the static-file options never got a chance to apply. Now, with **Settings → Cache → Ignore request cookies for static files** on (default), a `cookie_pass` bypass is relaxed **only if all** of the following hold: + +1. the winning request decision is a `cookie_pass` guard, not `pass`; +2. GET or HEAD, no `Authorization`, and a `Cookie` header is present; +3. the URL path ends in one of the configured static extensions (case-insensitive; the query string is ignored for this test and remains part of the cache key); +4. evaluating the rules **without any Cookie guard** gives no `pass` — so an explicit `pass` placed after a terminal Cookie guard (for example a `preview` cookie or `/admin` path rule) still wins; +5. evaluating the rules **without the Cookie header** gives no `pass` — the same URL is also cacheable for an anonymous client. + +The relaxed request then follows the normal static-cookie policy: Cookie is excluded from the cache key, so logged-in and anonymous clients share one object; header, cookie and query edits of the *non-guard* rules (for example tracking-parameter stripping) apply as for any other client, and `hash_cookie` / `hash_header` variants keep partitioning the key. The first relaxed MISS is reported as `cache_miss_static_cookie`. Nothing has to be added to each session rule. + +The extension is only a **candidate** signal. The browser's Cookie is still forwarded to the backend on a MISS, so the reply is stored only when it is **explicitly shareable**. This *shared-static guard* runs on the original backend headers, **before** response rules such as `strip_set_cookie` or `ignore_cache_control`, for every static fill whose Cookie was ignored in the key: + +| Backend reply | Result | +|---|---| +| Status other than 200 | not stored (`response_status`) | +| `Set-Cookie` (even if a rule later strips it) | not stored (`response_set_cookie`) | +| `Cache-Control: private`, `no-store` or `must-understand` (even with `ignore_cache_control`) | not stored (`response_cache_control`) | +| `Vary: *` or `Vary: Authorization` | not stored (`response_vary`) | +| `Content-Type: text/html` or `application/xhtml+xml` (SPA fallbacks, `/index.php/x.css`, error pages served as 200) | not stored (`response_static_dynamic`) | +| No explicit freshness: none of `public`, `s-maxage`, `max-age>0`, a future `Expires` (heuristic `Last-Modified`, `default_ttl_seconds` and rule TTLs do not count) | not stored (`response_static_not_public`) | +| `Vary: Cookie` | stored without the Cookie dimension only with **Ignore Vary: Cookie for public static assets** and `Cache-Control: public` (existing rule), otherwise `response_vary_cookie` | + +When the guard refuses storage the client still receives its own response (`X-Cache: MISS`), and the next client goes to the origin. Proactive refresh of such shared objects is sent **without** the client's Cookie. + +Disable **Ignore request cookies for static files** (globally or per Vhost) to restore the previous behavior exactly: `cookie_pass` then always bypasses, and the built-in policy reports `request_cookie`. + +### Diagnostics + +`X-Cache`, `X-Cache-Reason` and `Cache-Status` keep their names and formats; only new reason codes were added (`cache_rule_cookie`, `cache_miss_static_cookie`, `response_static_not_public`, `response_static_dynamic`). The source of a BYPASS can be read directly from the reason code using the precedence table above. **Test a request** additionally returns `reason_class` (`security`, `configuration`, `vcl_rule`, `vcl_cookie_guard`, `cookie`, `request_policy`, `response`, `cache`), `static_cookie_relaxed` and `shared_static_check`, and shows them in the panel. + +### Migrating existing rules + +- Saved rules are not changed. A `pass` rule that depends only on cookies keeps bypassing static files. +- In the rules editor such a rule shows a hint and a **Convert to Cookie guard** button (only for request rules whose conditions are Cookie conditions, optionally combined with a method condition). Review, convert and save; no cache purge is needed because the change only allows *new* public objects. +- For imported VCL replace `return(pass);` with `return(cookie_pass);` in Cookie/session branches only. +- Keep private resources protected by an explicit `pass` (path rules, **Private account routes**, `cache.bypass_prefixes`) or by `Cache-Control: private` / `no-store` at the origin. A Cookie guard alone does not protect `/account/avatar.png` if the origin labels it public. +- **Downgrade:** RustProxy 0.39.1 and older reject the unknown `cookie_pass` action when loading the configuration. Convert `cookie_pass` rules back to `pass` before installing an older binary. + +### Limitations + +- The decision trusts the origin's explicit public freshness for a Cookie-bearing fill. An origin that personalizes a `.css`/`.js`/image body and still sends `public` or `max-age` is misconfigured and would be shared; fix such resources with `private`/`no-store`, a path `pass` rule or `bypass_prefixes`. +- Only statics fetched **with** a Cookie need explicit freshness; objects filled by anonymous clients follow the ordinary cache policy and are then served to logged-in clients as well. +- Cache rules, including Cookie guards, do not apply to embedded Web Server sources (see [Web Server](WEB_SERVER.md)). + ## Cache rules (VCL-style) **Settings → Cache → Rules** holds global rules; **Vhosts → Cache → Cache rules for this vhost** holds rules for one vhost. They are built graphically ("If … Then …") and replace the most common Varnish VCL snippets without a scripting language. | Stage | VCL equivalent | Conditions | Actions | |---|---|---|---| -| Request | `vcl_recv`, `vcl_hash` | host, URL, path, extension, method, query parameter, request header, cookie, client IP | bypass cache (`pass`), explicit lookup (`hash`), remove cookies (all or all except listed), remove query parameters (list with `*`, or keep only listed), set/remove **safe request headers**, add a header or cookie value to the cache key | +| Request | `vcl_recv`, `vcl_hash` | host, URL, path, extension, method, query parameter, request header, cookie, client IP | bypass cache (`pass`), Cookie/session guard (`cookie_pass`, see [precedence](#cache-decision-precedence-explicit-pass-and-public-static-assets)), explicit lookup (`hash`), remove cookies (all or all except listed), remove query parameters (list with `*`, or keep only listed), set/remove **safe request headers**, add a header or cookie value to the cache key | | Backend response | `vcl_backend_response` | the request conditions plus status (`200`, `4xx`, `500-599`), Content-Type, response header | set TTL, set grace, do not store or **undo a rule-imposed do-not-store**, ignore backend `Cache-Control`/`Expires`, remove `Set-Cookie`, set/remove permitted backend response headers | | Deliver | `vcl_deliver` | the request and response conditions | set a response header, set it only if the response lacks it, or remove it | @@ -144,7 +209,7 @@ In **Vhosts → Cache**, overrides for static extensions, bypass path prefixes a - Reuse is scoped by frontend scheme, Host, exact client URL, Vhost/content policy and eligible `Vary` dimensions. HTTP and HTTPS objects do not cross-share. - GET and suitable HEAD requests may reuse a full object; changing request methods do not silently invalidate all cached GET results. -- Authorization, dynamic cookies, `Set-Cookie`, sticky-affinity cookies, Tinyauth and other private signals normally cause **BYPASS**. The static-extension exception may ignore `Vary: Cookie` only if the explicitly public response is otherwise safe to store and the global/vhost option is on. It never overrides `private`, `no-store` or `Set-Cookie`; the origin must guarantee that the complete asset response is not session-dependent. +- Authorization, dynamic cookies, `Set-Cookie`, sticky-affinity cookies, Tinyauth and other private signals normally cause **BYPASS**. The static-extension exception may ignore `Vary: Cookie` only if the explicitly public response is otherwise safe to store and the global/vhost option is on. It never overrides `private`, `no-store` or `Set-Cookie`; the origin must guarantee that the complete asset response is not session-dependent. A static fill fetched with a Cookie must also pass the [shared-static guard](#public-static-assets-with-a-session-cookie). - Only status **200 OK** responses can be stored in HOT/COLD. A cache-rule `ttl` targeting `404`, `301` or `302` cannot override this storage restriction; the older 404 TTL rule template was removed because it never produced HIT. Other response sizes, TTL, unsupported metadata, range/conditional semantics and request/client cache directives can prevent fill or require validation. - A Web Service selected as a Vhost source uses the same cache policy for eligible local files. File changes can be checked with `ETag` / `Last-Modified`; a 304 validation may refresh a stored body without downloading it again. @@ -169,7 +234,7 @@ for n in 1 2 3; do done ``` -Look for cache reason labels including `request_cookie`, `request_authorization`, `response_cache_control`, `route_disabled` and `cache_hit` when diagnostic headers are enabled. A `MISS` alone does not prove the object was admitted to HOT/COLD. +Look for cache reason labels including `request_cookie`, `request_authorization`, `cache_rule` (explicit VCL pass), `cache_rule_cookie` (VCL Cookie guard), `response_cache_control`, `response_static_not_public`, `route_disabled` and `cache_hit` when diagnostic headers are enabled; the [precedence table](#cache-decision-precedence-explicit-pass-and-public-static-assets) maps each code to its source. A `MISS` alone does not prove the object was admitted to HOT/COLD. ### Browser differs from curl (HTML, cookies, reloads) diff --git a/docs/CACHE_TEMPLATE_LIBRARY.md b/docs/CACHE_TEMPLATE_LIBRARY.md index 31b4c1f..b27df8b 100644 --- a/docs/CACHE_TEMPLATE_LIBRARY.md +++ b/docs/CACHE_TEMPLATE_LIBRARY.md @@ -1,6 +1,6 @@ # Cache rule template library: all 42 scenarios -**Applies to RustProxy 0.39.1.** This reference documents the 42 scenarios shipped by the graphical **Add from template...** and **Browse scenarios** controls. It describes the rules actually generated by `src/admin/web/cache-rules.js`, including their initial enabled state, exact matching scope, effects and limitations. The seven sections below follow the panel's category order. +**Applies to RustProxy 0.39.2.** This reference documents the 42 scenarios shipped by the graphical **Add from template...** and **Browse scenarios** controls. It describes the rules actually generated by `src/admin/web/cache-rules.js`, including their initial enabled state, exact matching scope, effects and limitations. The seven sections below follow the panel's category order. These are **graphical cache rules**, not scripts executed by a Varnish VCL engine. The panel can export a readable VCL preview, but that export is not a lossless rule backup. For the VCL import subset, see [VCL.md](VCL.md); for copyable VCL examples, see the [traffic cookbook](VCL_TRAFFIC_COOKBOOK.md). @@ -20,8 +20,8 @@ A template is **On** if its generated rule(s) are enabled when inserted; **Off** |---|---|---|---| | **Methods other than GET/HEAD** (`safemethods`) | 1 request, **On** | Method is not GET or HEAD -> `pass` (BYPASS). | Usually a safe guard for forms and writes. Other method restrictions still come from RustProxy's normal cache policy. | | **Authorization** (`authbypass`) | 1 request, **On** | An `Authorization` request header exists -> `pass`. | Applies to any route. Do not try to compensate by removing the header. | -| **Any Cookie** (`cookiepass`) | 1 request, **On** | Any `Cookie` header exists -> `pass`. | Conservative for unknown apps; place **after** a selective parent-domain/CDN cleanup if those cookies should be ignored. | -| **Common session cookies** (`sessioncookies`) | 1 request, **On** | Cookie header contains an exact cookie-name boundary for `session`, `sessionid`, `PHPSESSID`, `laravel_session`, `connect.sid` or `sid` -> `pass`. | Not an exhaustive session list. Add app-specific names or use **Any Cookie** as a fallback. | +| **Any Cookie** (`cookiepass`) | 1 request, **On** | Any `Cookie` header exists -> `cookie_pass` (Cookie guard: BYPASS for pages; public static assets may still be cached, see below). | Conservative for unknown apps; place **after** a selective parent-domain/CDN cleanup if those cookies should be ignored. | +| **Common session cookies** (`sessioncookies`) | 1 request, **On** | Cookie header contains an exact cookie-name boundary for `session`, `sessionid`, `PHPSESSID`, `laravel_session`, `connect.sid` or `sid` -> `cookie_pass`. | Not an exhaustive session list. Add app-specific names or use **Any Cookie** as a fallback. | | **Private account routes** (`privateroutes`) | 3: request + response + deliver, **On** | Paths starting with a complete segment `admin`, `auth`, `login`, `logout`, `user`, `users`, `account`, `profile`, `settings`, `dashboard`, `cart`, `checkout`, `orders`, `billing` or `payment`: `pass`, block storage and deliver `Cache-Control: private, no-store`. | Review locale prefixes, custom account URLs and API routes. Purge previously cached responses. | | **Preview or draft links** (`preview`) | 1 request, **On** | Path segment `/preview` or `/draft`, **or** a `preview`/`draft` query parameter -> `pass`. | Add other preview token names as needed. A query parameter's mere presence is sufficient. | | **Cart / checkout / payments** (`checkout`) | 1 request, **On** | `/cart`, `/checkout`, `/payment`, `/billing`, `/order`, `/orders` (and descendants) -> `pass`. | Does not by itself send browser no-store; configure application/private responses accordingly. | @@ -38,7 +38,7 @@ These templates are **cache protections, not authentication or authorization**. ## 2. CMS and framework sessions (7 scenarios) -All seven insert a **request-stage `pass` rule, enabled by default**. They **retain** cookies and forward them to the backend; none rewrites a session cookie. +All seven insert **request-stage rules, enabled by default**. Cookie triggers use `cookie_pass` (Cookie/session guard); path triggers use an explicit `pass`, so WordPress and WooCommerce insert two rules. They **retain** cookies and forward them to the backend; none rewrites a session cookie. | Template (internal key) | Trigger | Use and adjustments | |---|---|---| @@ -56,7 +56,7 @@ A framework template recognizes only the listed paths or cookie names. Where a s | Template (internal key) | Rules / default | Exact effect | Deployment notes | |---|---|---|---| -| **CDN technical cookies** (`cdn`) | 5 request rules, all **On** | `pass` non-GET/HEAD; `pass` `/admin`, `/api`, `/auth`, `/login`, `/logout`, `/panel`, `/konto`, `/dashboard`; `pass` `Authorization`; strip **the entire Cookie header only if every cookie name** belongs to the fixed Cloudflare/Akamai technical list; then `pass` if any Cookie remains. | Do not replace the anchored allowlist with a contains/substring match. Cookie names: `__cf_bm`, `cf_clearance`, `_cfuvid`, `__cfruid`, `__cfseq`, `_abck`, `ak_bmsc`, `bm_sz`, `bm_sv`. Use only if those values are irrelevant to the origin's representation. | +| **CDN technical cookies** (`cdn`) | 5 request rules, all **On** | `pass` non-GET/HEAD; `pass` `/admin`, `/api`, `/auth`, `/login`, `/logout`, `/panel`, `/konto`, `/dashboard`; `pass` `Authorization`; strip **the entire Cookie header only if every cookie name** belongs to the fixed Cloudflare/Akamai technical list; then `cookie_pass` if any Cookie remains. | Do not replace the anchored allowlist with a contains/substring match. Cookie names: `__cf_bm`, `cf_clearance`, `_cfuvid`, `__cfruid`, `__cfseq`, `_abck`, `ak_bmsc`, `bm_sz`, `bm_sv`. Use only if those values are irrelevant to the origin's representation. | | **Selected parent-domain cookies** (`publiccookies`) | 1 request rule, **Off**; **Vhost-only** | Only on GET/HEAD with Cookie, without Authorization and outside specified private prefixes: remove **only selected exact cookie names or trailing-`*` prefixes** entered by the operator; no forced cache lookup and no `stop`. | Replace `REPLACE_WITH_VERIFIED_PARENT_COOKIE_NAME` with verified names or prefixes (e.g. `SESS*` for an unrelated Drupal 6 parent, never if this Vhost uses Drupal sessions). Other cookies remain and can trigger the CDN remaining-cookie `pass` guard. | **Safe order for a Vhost using both:** @@ -74,7 +74,7 @@ For copyable VCL syntax, see [parent-domain cookie removal](VCL_TRAFFIC_COOKBOOK ## 4. Public content and cache TTL (10 scenarios) -Response-stage TTL rules only affect *otherwise eligible* responses. They do not override private/no-store cache policy, `Set-Cookie`, `Vary`, authentication, object limits or the **HTTP 200 only** storage restriction in RustProxy 0.39.1. They do not necessarily change `Cache-Control` seen by a browser. +Response-stage TTL rules only affect *otherwise eligible* responses. They do not override private/no-store cache policy, `Set-Cookie`, `Vary`, authentication, object limits or the **HTTP 200 only** storage restriction in RustProxy 0.39.2. They do not necessarily change `Cache-Control` seen by a browser. | Template (internal key) | Rules / default | Match and actions | Enable only when... | |---|---|---|---| @@ -116,9 +116,13 @@ These run at the **deliver** stage. Unless accompanied by request/response rules |---|---|---|---| | **API: bypass cache** (`api`) | 1 request, **On** | Path starts `/api/` -> `pass`. | Covers both private and public API endpoints. It does not send browser `no-store`; for public JSON caching remove or narrow this broad pass guard first. | +## `pass`, `cookie_pass` and static assets + +Templates whose only trigger is a cookie insert `cookie_pass`. For pages it is identical to `pass`. When **Ignore request cookies for static files** is on, RustProxy can still cache a **public** CSS/JS/image/font/... for a logged-in browser, provided no explicit `pass` (path, method, Authorization, preview, ...) matches the same request and the backend reply is explicitly public. An explicit `pass` is never relaxed. Rules added from an older version keep `pass`; the editor offers **Convert to Cookie guard** for Cookie-only `pass` rules. Details: [decision precedence](CACHE.md#cache-decision-precedence-explicit-pass-and-public-static-assets). + ## Rule-order pitfalls -- **`pass` takes precedence over later request edits:** if **Any Cookie** or **CDN BYPASS remaining cookies** runs first, a later parent-name cleanup rule never gets a chance to remove irrelevant cookies. This is the typical reason a browser shows `X-Cache: BYPASS` with `X-Cache-Reason: cache_rule` while a cookie-free `curl` gets HIT. +- **`pass` takes precedence over later request edits:** if **Any Cookie** or **CDN BYPASS remaining cookies** runs first, a later parent-name cleanup rule never gets a chance to remove irrelevant cookies. This is the typical reason a browser shows `X-Cache: BYPASS` with `X-Cache-Reason: cache_rule` (explicit pass) or `cache_rule_cookie` (Cookie guard) while a cookie-free `curl` gets HIT. Public static assets are no longer affected when the guard is a `cookie_pass`. - **A `pass` after selective cleanup still sees app sessions:** `parent_analytics=1; app_session=abc` must become `app_session=abc`, and the remaining-cookie guard must BYPASS. Never force `lookup` to override this. - **Global vs Vhost scope matters:** matching Vhost rules run before applicable global rules. Ordering controls in one list do not reorder the other list. A terminal request action stops further normal request-stage evaluation; response and deliver stages are separate. - **A broad API guard can defeat public API TTL:** request `pass` on `/api/` makes a response-stage public JSON TTL irrelevant. Narrow the prefix or use a dedicated public route when desired. diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 1a4e6e6..03aaf3a 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -64,7 +64,7 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se ## Cache and delivery - Shared HTTP cache with a memory tier (HOT) and an optional disk tier (COLD). -- RFC 9111 freshness, validators and `Vary` with conservative header-aware normalization (known comma-list fields, language/encoding/charset qualities and media types), while preserving opaque values and quoted strings; stale-while-revalidate, stale-if-error and request coalescing. Configurable static-extension exception for cookie-independent assets: omit `Vary: Cookie` only for explicitly public cacheable responses, preserving all other Vary dimensions. +- RFC 9111 freshness, validators and `Vary` with conservative header-aware normalization (known comma-list fields, language/encoding/charset qualities and media types), while preserving opaque values and quoted strings; stale-while-revalidate, stale-if-error and request coalescing. Configurable static-extension exception for cookie-independent assets: omit `Vary: Cookie` only for explicitly public cacheable responses, preserving all other Vary dimensions. A central [cache decision](CACHE.md#cache-decision-precedence-explicit-pass-and-public-static-assets) separates security bypasses, explicit VCL `pass`, Cookie/session guards (`cookie_pass`) and backend properties, so public static assets can be HIT for logged-in users without weakening explicit pass rules; Cookie-bearing static fills are stored only when the backend reply is explicitly public. - Varnish-compatible policy option, forced caching rules and per-location cache switches. - Graphical [cache rules](CACHE.md#cache-rules-vcl-style) with global and per-Vhost precedence, terminal VCL pass/hash behavior, ordered safe request-header/cookie/query rewrites, vcl_hash variants, reversible rule-only no-store decisions, backend-response header edits before cache policy, and delivery header overrides; includes a shared, responsive two-section tester in global, ordinary vhost and Docker vhost editors, a scope-aware in-panel VCL guide, and a warning-reporting VCL subset importer. The exact VCL syntax, backend vs deliver `Vary`/header mutations and safety restrictions are listed in [VCL compatibility](VCL.md); the [traffic cookbook](VCL_TRAFFIC_COOKBOOK.md) includes ready-to-import examples and expected live request outcomes. - RFC 9211 `Cache-Status` and optional `X-Cache` diagnostics. diff --git a/docs/VCL.md b/docs/VCL.md index 1c8df16..10a716d 100644 --- a/docs/VCL.md +++ b/docs/VCL.md @@ -1,6 +1,6 @@ # VCL import: supported instructions and exact effects -This guide describes the VCL **subset implemented by RustProxy 0.39.1**, not the full Varnish Configuration Language. It is based on the VCL importer and cache-rule engine. Importing VCL **converts statements into graphical cache rules (which must then be saved)**; RustProxy does not execute arbitrary VCL text at request time. Unsupported instructions may be skipped with warnings or cause a parse error; they are not executed as Varnish code. **In the graphical importer, warnings pause conversion:** no rules are added until you explicitly choose **Add partial import (reviewed)**. Even after adding, you must separately save the configuration. The read-only VCL export is a human-oriented preview, **not** a lossless backup or a guaranteed re-importable VCL program. +This guide describes the VCL **subset implemented by RustProxy 0.39.2**, not the full Varnish Configuration Language. It is based on the VCL importer and cache-rule engine. Importing VCL **converts statements into graphical cache rules (which must then be saved)**; RustProxy does not execute arbitrary VCL text at request time. Unsupported instructions may be skipped with warnings or cause a parse error; they are not executed as Varnish code. **In the graphical importer, warnings pause conversion:** no rules are added until you explicitly choose **Add partial import (reviewed)**. Even after adding, you must separately save the configuration. The read-only VCL export is a human-oriented preview, **not** a lossless backup or a guaranteed re-importable VCL program. For a short operational reference inside the panel, open **Cache & VCL guide** from **Settings → Cache**, the ordinary **Vhost → Cache** editor or **Docker vhosts → Cache**. The same modal works in all three places; example VCL is pasted into the importer of the editor that opened the guide, and the modal labels that scope. The modal shows the current compatibility-mode, fallback-TTL and grace settings, explains `Vary` and header mutations with examples, and identifies unsupported Varnish hooks. It complements this exact syntax reference; it does not execute VCL or save settings. @@ -18,7 +18,8 @@ For the **complete reference to all 42 quick-rule templates** (conditions, stage | Hook | Recognized VCL syntax | Actual effect and limits | |---|---|---| -| `vcl_recv` | `return(pass);` | Stops request processing for the matching path; bypasses shared cache. | +| `vcl_recv` | `return(pass);` | Stops request processing for the matching path; bypasses shared cache. An explicit pass is **never** relaxed by global cache options. | +| `vcl_recv` | `return(cookie_pass);` | **RustProxy extension (Cookie/session guard):** like `return(pass)` for pages, but a GET/HEAD for a configured static extension may still reach the cache when **Ignore request cookies for static files** is on and no other rule would pass the same request. The branch must test `req.http.Cookie` (non-negated); otherwise the import warns and skips it. See [decision precedence](CACHE.md#cache-decision-precedence-explicit-pass-and-public-static-assets). | | `vcl_recv` | `return(hash);` or `return(lookup);` | Stops `vcl_recv` and requests a cache lookup. In compatibility mode, may admit a GET/HEAD carrying `Cookie` (with cookie-partitioned variants); other protections remain. | | `vcl_recv` | `unset req.http.Cookie;` | Removes the **whole** request Cookie header, including what is forwarded to the origin. | | `vcl_recv` | `remove_req_cookies("parent_analytics", "SESS*");` | **RustProxy extension:** removes exact-name cookies or case-sensitive prefixes marked by one trailing `*` before later rules, cache lookup and origin forwarding. Remaining session cookies are not removed and can still trigger BYPASS. Not standard Varnish VCL. | @@ -155,7 +156,7 @@ Use `unset req.http.Cookie;` only when the origin does not need **any** cookies - `varnish_compatible=true` and positive `cache.default_ttl_seconds` (or an explicit positive `set beresp.ttl`) may treat an otherwise eligible origin `Cache-Control: no-cache` as fresh for that TTL, **without requiring `public`**. This is RustProxy's configured override, **not** vanilla Varnish's built-in behavior. - `varnish_compatible=false` honors `no-cache` revalidation, including when a TTL action is present. An explicit *backend header rewrite* removing `no-cache` changes the response policy in both modes; that is a different and potentially unsafe operation. - Backend `private`, `no-store`, `Set-Cookie`, malformed `Vary`, unsupported status, invalid headers and size bounds still block storage **unless an administrator explicitly rewrites the affected cache-policy headers via trusted rules**. Client/request restrictions remain separate. -- **Only HTTP 200 origin responses are storable in RustProxy 0.39.1.** Setting `beresp.ttl` for `404`, `301` or `302` does not create a negative/redirect cache. The misleading 404 TTL template was removed from the graphical editor. Deliver-stage header rules can still edit those responses without making them cacheable. +- **Only HTTP 200 origin responses are storable in RustProxy 0.39.2.** Setting `beresp.ttl` for `404`, `301` or `302` does not create a negative/redirect cache. The misleading 404 TTL template was removed from the graphical editor. Deliver-stage header rules can still edit those responses without making them cacheable. - Hit-for-miss / hit-for-pass and `beresp.keep` are intentionally not imported. RustProxy already coalesces eligible misses and briefly remembers uncacheable fills for its collapse strategy, and independently retains validators for conditional revalidation. These are **not** Varnish-compatible hit-for-miss/pass objects or programmable `keep` semantics. ## Test an imported rule set diff --git a/docs/VCL_SUPPORT_MATRIX.md b/docs/VCL_SUPPORT_MATRIX.md index 5b8546e..5491467 100644 --- a/docs/VCL_SUPPORT_MATRIX.md +++ b/docs/VCL_SUPPORT_MATRIX.md @@ -1,6 +1,6 @@ # VCL capability matrix: implemented, limited and unsupported -**Applies to the RustProxy 0.39.1 source tree with the Docker/Cache/Traffic and CDN-template fixes.** This is an implementation inventory, not a statement of general Varnish compatibility. The authoritative implementation is `src/cache/vcl.rs` (tokenization and import), `src/cache/rules.rs` (validation and rule evaluation), and `src/cache/policy.rs` / `src/cache/lookup.rs` (shared-cache admission and lookup). See [VCL syntax and header semantics](VCL.md) for implementation details, the [VCL traffic cookbook](VCL_TRAFFIC_COOKBOOK.md) for ready-to-import VCL and a request/response scenario matrix, and [HTTP cache](CACHE.md) for cache policy. +**Applies to the RustProxy 0.39.2 source tree with the Docker/Cache/Traffic and CDN-template fixes.** This is an implementation inventory, not a statement of general Varnish compatibility. The authoritative implementation is `src/cache/vcl.rs` (tokenization and import), `src/cache/rules.rs` (validation and rule evaluation), and `src/cache/policy.rs` / `src/cache/lookup.rs` (shared-cache admission and lookup). See [VCL syntax and header semantics](VCL.md) for implementation details, the [VCL traffic cookbook](VCL_TRAFFIC_COOKBOOK.md) for ready-to-import VCL and a request/response scenario matrix, and [HTTP cache](CACHE.md) for cache policy. ## Practical examples and traffic scenarios @@ -79,7 +79,8 @@ Do **not** use an unanchored regex such as `req.http.Cookie ~ "__cf_bm"` with `u | Exact statement form | Status | Rule effect and restrictions | |---|---|---| -| `return(pass);` | Supported | Cache bypass; terminates applicable request-stage rules and skips `vcl_hash`. | +| `return(pass);` | Supported | Cache bypass; terminates applicable request-stage rules and skips `vcl_hash`. Never relaxed by global options. | +| `return(cookie_pass);` | RustProxy extension | Cookie/session guard with the same termination semantics; may be relaxed only for public static assets (see [Cache](CACHE.md#cache-decision-precedence-explicit-pass-and-public-static-assets)). Requires a non-negated `req.http.Cookie` condition. | | `return(hash);`, `return(lookup);` | Supported with safety conditions | Explicit lookup; in Varnish-compatibility mode can admit **Cookie-bearing GET/HEAD** requests, partitioned by their remaining Cookie value and with downstream `Vary: Cookie`. Does not override Authorization, unsafe methods, client privacy or disabled cache. | | `unset req.http.Cookie;` | Supported, risky | Removes **every** Cookie value; never use for a session-bearing Vhost. | | `remove_req_cookies("exact_name", "SESS*");` | Supported, RustProxy extension | Deletes selected exact Cookie names or case-sensitive name prefixes with one trailing `*`; keeps all other cookies for later pass/cache checks. Refuses malformed Cookie fields and rejects `*` alone, prefixes shorter than 3 characters, middle wildcards and general regexes. Not stock Varnish VCL. | diff --git a/docs/VCL_TRAFFIC_COOKBOOK.md b/docs/VCL_TRAFFIC_COOKBOOK.md index b80b860..26014f7 100644 --- a/docs/VCL_TRAFFIC_COOKBOOK.md +++ b/docs/VCL_TRAFFIC_COOKBOOK.md @@ -1,6 +1,6 @@ # VCL cookbook: concrete use cases and HTTP traffic scenarios -**Target:** RustProxy **0.39.1** with the Docker Cache/Traffic and CDN cookie patch. This guide documents the *actual importer* (`src/cache/vcl.rs`), validated cache-rule actions (`src/cache/rules.rs`), and shared-cache admission documented in [Cache](CACHE.md). It is **not** a full Varnish implementation or a promise of exact Varnish semantics. +**Target:** RustProxy **0.39.2** with the Docker Cache/Traffic and CDN cookie patch. This guide documents the *actual importer* (`src/cache/vcl.rs`), validated cache-rule actions (`src/cache/rules.rs`), and shared-cache admission documented in [Cache](CACHE.md). It is **not** a full Varnish implementation or a promise of exact Varnish semantics. Read together with [VCL compatibility](VCL.md) and the [supported/unsupported capability matrix](VCL_SUPPORT_MATRIX.md). The examples are **separate policies**, not one file that should be imported wholesale. Copy one recipe into the correct Vhost scope, then reconcile it with existing global/local rules; **never paste contradictory `return(pass)` policies together without reviewing rule order**. @@ -41,7 +41,7 @@ Read together with [VCL compatibility](VCL.md) and the [supported/unsupported ca | Remove tracking parameters from cache identity | [Query rewrite](#10-tracking-query-normalization-restricted) or graphical Strip query | Drop approved params after URL normalization | Import arbitrary `regsub` or preserve regex URL semantics exactly | | Origin sets irrelevant `Set-Cookie` on public SVG | [Advanced public cookie cleanup](#11-advanced-removing-origin-set-cookie-high-risk) | Remove it before storage | Prove it was not needed for identity/session | | CORS responses differentiated by `Origin` | Origin's `Vary: Origin` | Keep origins separate | Safely collapse all origins into one cached response | -| Cache error pages/redirects (`404`, `301`, `302`) | **Not supported** | No cache storage in 0.39.1 | Invent negative/redirect-cache TTL via VCL | +| Cache error pages/redirects (`404`, `301`, `302`) | **Not supported** | No cache storage in 0.39.2 | Invent negative/redirect-cache TTL via VCL | | IP ranges, backend routing, purge, TLS security | Native ACL/Vhost/Cache API settings | Dedicated supported configuration | Import ACL/director/`return(purge)` as executable VCL | ## C. Copy-and-import VCL recipes @@ -182,13 +182,19 @@ sub vcl_recv { if (req.http.Cookie ~ "^(?:__cf_bm|cf_clearance|_cfuvid|__cfruid|__cfseq|_abck|ak_bmsc|bm_sz|bm_sv)=[^;]*(?:;[ \t]*(?:__cf_bm|cf_clearance|_cfuvid|__cfruid|__cfseq|_abck|ak_bmsc|bm_sz|bm_sv)=[^;]*)*$") { unset req.http.Cookie; } + // Remaining cookies: Cookie/session guard. RustProxy extension + // return(cookie_pass) bypasses pages like return(pass) but lets public + // static assets use the cache when "Ignore request cookies for static + // files" is on. In stock Varnish use return(pass) here. if (req.http.Cookie) { - return(pass); + return(cookie_pass); } return(hash); } ``` +The final guard uses `return(cookie_pass)`: logged-in pages remain `BYPASS` (`cache_rule_cookie`), while public CSS/JS/images/fonts can be shared under the static cookie policy. Use `return(pass)` there to keep the 0.39.1 behavior. See [decision precedence](CACHE.md#cache-decision-precedence-explicit-pass-and-public-static-assets). + ### 5. Static assets and Vary: Cookie **Goal:** Remove all Cookie headers **only** from independently verified public `/assets` images/fonts/scripts/styles. @@ -199,6 +205,8 @@ sub vcl_recv { **Caveat:** VCL does **not** implement an `Ignore Vary: Cookie` instruction. Use **Static & diagnostics** options; these have additional explicit `public`/freshness/no-Set-Cookie/privacy checks. A session-aware image must not use this recipe. +**Without stripping cookies:** if your session guards use `return(cookie_pass)` (or the session templates), you do not need this recipe for logged-in users: with **Ignore request cookies for static files** on, public static assets reach the cache while the Cookie is still forwarded, and storage requires an explicitly public backend reply ([shared-static guard](CACHE.md#public-static-assets-with-a-session-cookie)). + Source: [`examples/vcl/static-assets-public.vcl`](../examples/vcl/static-assets-public.vcl). ```vcl @@ -301,7 +309,7 @@ sub vcl_hash { **Prerequisites:** Use native proxy/WebSocket/stream and backend retry configuration for those separate operations. -**Caveat:** This is not a Varnish `vcl_backend_error`, retry, pipe or stale-if-error implementation. `500` was never eligible for 0.39.1 shared storage anyway. +**Caveat:** This is not a Varnish `vcl_backend_error`, retry, pipe or stale-if-error implementation. `500` was never eligible for 0.39.2 shared storage anyway. Source: [`examples/vcl/stream-and-errors-no-store.vcl`](../examples/vcl/stream-and-errors-no-store.vcl). @@ -473,7 +481,7 @@ The outcomes below describe **decision paths**, not a guaranteed X-Cache label: ### D2. Origin response and `Vary` -| Backend sends | RustProxy 0.39.1 consequence | Safety check | +| Backend sends | RustProxy 0.39.2 consequence | Safety check | |---|---|---| | `200`, public/fresh, no Set-Cookie, valid Vary | Potential shared-store candidate | Response must really be identical for all users. | | `200`, `Cache-Control: private` | Not storable without **dangerous explicit rewrite** | Never rewrite private content to public. | diff --git a/docs/WEB_SERVER.md b/docs/WEB_SERVER.md index d27b1fd..c86fd49 100644 --- a/docs/WEB_SERVER.md +++ b/docs/WEB_SERVER.md @@ -6,7 +6,7 @@ The built-in Web Server serves local files and, optionally, passes PHP scripts t 1. Open **Web Server → New Web Service**. Choose an ID/name and an absolute document root readable by the RustProxy service account. 2. Set index files (default `index.html`, `index.htm`), whether directory listing is allowed (off by default), MIME handling and download extensions. -3. Add `try_files`, rewrites, response headers and cache rules only if your application requires them. +3. Add `try_files`, rewrites and response headers only if your application requires them. VCL-style cache rules (including `pass` / `cookie_pass`) are **not** evaluated for Web Server sources; the static-extension Cookie option and the regular cache policy still apply to local files. 4. Enable PHP only if you have a reachable, protected PHP-FPM endpoint; otherwise static files do not need any PHP runtime. 5. Save, create or edit a **Vhost**, select **Web Server** as source and choose the service ID. 6. Test index files, static assets, missing files, direct directory access, downloads and headers. diff --git a/examples/vcl/cdn-technical-cookies.vcl b/examples/vcl/cdn-technical-cookies.vcl index b79fa4e..7b8bf5d 100644 --- a/examples/vcl/cdn-technical-cookies.vcl +++ b/examples/vcl/cdn-technical-cookies.vcl @@ -16,8 +16,12 @@ sub vcl_recv { if (req.http.Cookie ~ "^(?:__cf_bm|cf_clearance|_cfuvid|__cfruid|__cfseq|_abck|ak_bmsc|bm_sz|bm_sv)=[^;]*(?:;[ \t]*(?:__cf_bm|cf_clearance|_cfuvid|__cfruid|__cfseq|_abck|ak_bmsc|bm_sz|bm_sv)=[^;]*)*$") { unset req.http.Cookie; } + // Remaining cookies: Cookie/session guard. RustProxy extension + // return(cookie_pass) bypasses pages like return(pass) but lets public + // static assets use the cache when "Ignore request cookies for static + // files" is on. In stock Varnish use return(pass) here. if (req.http.Cookie) { - return(pass); + return(cookie_pass); } return(hash); } diff --git a/examples/vcl/drupal6-parent-session-cookies.vcl b/examples/vcl/drupal6-parent-session-cookies.vcl index a90c42f..1a55e02 100644 --- a/examples/vcl/drupal6-parent-session-cookies.vcl +++ b/examples/vcl/drupal6-parent-session-cookies.vcl @@ -1,5 +1,6 @@ // Opt-in example: this Vhost uses "session" while an unrelated Drupal 6 site // at the parent domain sets cookies named SESS or SSESS. +// Requires RustProxy 0.39.2+ (return(cookie_pass); use return(pass) on 0.39.1). // RustProxy 0.39.1 (with prefix selector support) only: remove_req_cookies() // supports exact names and a single trailing '*' for case-sensitive prefixes. // Not standard Varnish VCL. A normal 0.39.1 binary without this patch will @@ -10,9 +11,12 @@ // Keep CDN technical-cookie rules separate and later than this rule. // Retain "CDN: bypass remaining cookies" to protect unknown session cookies. sub vcl_recv { - // Subdomain's OWN login cookie must always skip shared cache. + // Subdomain's OWN login cookie must always skip the shared cache for + // pages. return(cookie_pass) (RustProxy extension) still lets public + // static assets use the cache under the static cookie policy; use + // return(pass) instead if even static files must bypass for this cookie. if (req.http.Cookie ~ "(?:^|;[ \\t]*)session=") { - return(pass); + return(cookie_pass); } if ((req.method == "GET" || req.method == "HEAD") && diff --git a/langs/en_US.json b/langs/en_US.json index 42b943f..8021707 100644 --- a/langs/en_US.json +++ b/langs/en_US.json @@ -1015,11 +1015,11 @@ "vhCacheStaticCookie": "Ignore request cookies for selected static file extensions", "vhCacheStaticCustom": "Use a custom static extension list", "vhCacheStaticExtensions": "Static extensions (one per line, without dot)", - "vhCacheStaticHelp": "Inherited by default. Use cookie-independent static assets only: the global or vhost Vary: Cookie option can remove that field from public cacheable responses. Set-Cookie, private and no-store still prevent storage.", + "vhCacheStaticHelp": "Inherited by default. Use cookie-independent static assets only: Cookie guards (cookie_pass) then let public static assets reach the cache, explicit pass rules still win, and the global or vhost Vary: Cookie option can remove that field from public cacheable responses. Set-Cookie, private, no-store, HTML and missing public freshness still prevent storage of a Cookie-bearing fill.", "cacheStaticTitle": "Static asset cache boost", "cacheStaticCookie": "Ignore request cookies for static files", "cacheStaticExtensions": "Global static extensions (one per line, without dot)", - "cacheStaticHelp": "Only enable these options if static file bytes never depend on a session. With the Vary: Cookie option (on by default), an explicitly public, cacheable response may omit Cookie from Vary while retaining other Vary fields. Set-Cookie, private, no-store and missing freshness still prevent storage.", + "cacheStaticHelp": "Only enable these options if static file bytes never depend on a session. Cookies are then ignored in the cache key of static extensions, and Cookie guards (cookie_pass rules, e.g. the session templates) no longer bypass public static assets; explicit pass rules always win. When a Cookie was sent, the backend reply is stored only if it is explicitly public (public, s-maxage, max-age>0 or Expires), not HTML and without Set-Cookie, private, no-store or Vary: *. With the Vary: Cookie option (on by default), an explicitly public response may omit Cookie from Vary while retaining other Vary fields.", "vhHttp2Enabled": "Enable HTTP/2 for this vhost", "vhFrontendProtocolsHelp": "H2 and H3 are per-vhost opt-outs. A switch is available only when at least one selected listener has that protocol enabled in Settings > Listeners.", "administration": "Administration", @@ -3879,6 +3879,31 @@ "cacheGuideContextDocker": "Docker vhost", "cacheGuideScopeGlobal": "VCL examples are inserted into the global importer. The tester can also include saved rules of a selected vhost.", "cacheGuideScopeVhost": "VCL examples are inserted only into this vhost importer. Vhost rules take priority over saved global rules, which can also be disabled. The TTL above is the global setting.", - "cacheGuideScopeDocker": "VCL examples are inserted only into this Docker vhost importer. Global rules behave the same as for ordinary vhosts unless disabled. The TTL above is the global setting." + "cacheGuideScopeDocker": "VCL examples are inserted only into this Docker vhost importer. Global rules behave the same as for ordinary vhosts unless disabled. The TTL above is the global setting.", + "cacheRuleActionCookiePass": "Bypass for cookies (cookie_pass, session guard)", + "cacheRuleTplWordpressCookies": "WordPress: bypass logged-in cookies", + "cacheRuleTplWoocommerceCookies": "WooCommerce: bypass session cookies", + "cacheRuleCookieGuardHint": "This pass rule depends only on cookies. As an explicit pass it also bypasses public CSS/JS/images/fonts for logged-in users. Converting it to a Cookie guard (cookie_pass) keeps BYPASS for pages but lets public static assets use the cache when \"Ignore request cookies for static files\" is on.", + "cacheRuleCookieGuardConvert": "Convert to Cookie guard", + "cacheRuleCookieGuardConverted": "Converted to cookie_pass. Review and save; purge is not required.", + "cacheRulesResultReasonClass": "Bypass source", + "cacheRulesResultStaticCookie": "Static cookie policy", + "cacheRulesResultStaticCookieRelaxed": "Cookie guard relaxed for a public static asset; storage still requires an explicitly public backend response", + "cacheRulesResultStaticCookieChecked": "Cookie ignored in the cache key; storage requires an explicitly public backend response", + "cacheReasonClass_security": "Security protection", + "cacheReasonClass_configuration": "Configuration", + "cacheReasonClass_vcl_rule": "VCL / cache rule (explicit pass)", + "cacheReasonClass_vcl_cookie_guard": "VCL / cache rule (Cookie guard)", + "cacheReasonClass_cookie": "Built-in Cookie policy", + "cacheReasonClass_request_policy": "Request policy", + "cacheReasonClass_response": "Backend response", + "cacheReasonClass_cache": "Cache state", + "cacheReason_cache_rule": "VCL / cache rule pass", + "cacheReason_cache_rule_cookie": "VCL / cache rule Cookie guard", + "cacheReason_cache_miss_static_cookie": "Static asset miss (Cookie guard relaxed)", + "cacheReason_response_static_not_public": "Static asset with Cookie: backend did not declare public freshness", + "cacheReason_response_static_dynamic": "Static asset with Cookie: HTML/dynamic content type", + "cacheReason_response_vary_cookie": "Vary: Cookie kept (not explicitly public)", + "cacheReason_response_surrogate_control": "Surrogate-Control no-store" } } diff --git a/langs/pl_pl.json b/langs/pl_pl.json index 7a6a19d..e894f1e 100644 --- a/langs/pl_pl.json +++ b/langs/pl_pl.json @@ -1015,11 +1015,11 @@ "vhCacheStaticCookie": "Ignoruj Cookie żądania dla wybranych rozszerzeń statycznych", "vhCacheStaticCustom": "Użyj własnej listy rozszerzeń statycznych", "vhCacheStaticExtensions": "Rozszerzenia statyczne (po jednym w linii, bez kropki)", - "vhCacheStaticHelp": "Domyślnie dziedziczy ustawienia globalne. Stosuj tylko dla plików niezależnych od sesji: opcja Vary: Cookie może usunąć ten nagłówek z publicznych odpowiedzi nadających się do cache. Set-Cookie, private i no-store nadal blokują zapis.", + "vhCacheStaticHelp": "Domyślnie dziedziczy ustawienia globalne. Stosuj tylko dla plików niezależnych od sesji: strażnicy Cookie (cookie_pass) przepuszczają wtedy publiczne statyki do cache, jawne reguły pass nadal wygrywają, a opcja Vary: Cookie może usunąć ten nagłówek z publicznych odpowiedzi. Set-Cookie, private, no-store, HTML i brak publicznej świeżości nadal blokują zapis odpowiedzi pobranej z Cookie.", "cacheStaticTitle": "Cache statycznych zasobów", "cacheStaticCookie": "Ignoruj Cookie żądania dla statycznych plików", "cacheStaticExtensions": "Globalne rozszerzenia statyczne (po jednym w linii, bez kropki)", - "cacheStaticHelp": "Włączaj tylko wtedy, gdy zawartość plików nie zależy od sesji. Opcja Vary: Cookie (domyślnie włączona) usuwa Cookie z Vary jedynie dla publicznych odpowiedzi nadających się do cache, zachowując pozostałe pola Vary. Set-Cookie, private, no-store i brak polityki świeżości nadal blokują zapis.", + "cacheStaticHelp": "Włączaj tylko wtedy, gdy zawartość plików nie zależy od sesji. Cookies są wtedy pomijane w kluczu cache dla rozszerzeń statycznych, a strażnicy Cookie (reguły cookie_pass, np. szablony sesji) nie wymuszają już BYPASS dla publicznych statyków; jawne reguły pass zawsze mają pierwszeństwo. Gdy żądanie niosło Cookie, odpowiedź backendu jest zapisywana tylko, jeśli jest jawnie publiczna (public, s-maxage, max-age>0 lub Expires), nie jest HTML i nie ma Set-Cookie, private, no-store ani Vary: *. Opcja Vary: Cookie (domyślnie włączona) usuwa Cookie z Vary jedynie dla jawnie publicznych odpowiedzi, zachowując pozostałe pola Vary.", "vhHttp2Enabled": "Włącz HTTP/2 dla tego vhosta", "vhFrontendProtocolsHelp": "H2 i H3 są przełącznikami per vhost. Opcja jest aktywna tylko wtedy, gdy co najmniej jeden wybrany listener ma dany protokół włączony w Ustawienia > Listenery.", "administration": "Panel administracyjny", @@ -3879,6 +3879,31 @@ "cacheGuideContextDocker": "Docker vhost", "cacheGuideScopeGlobal": "Przykład VCL zostanie wstawiony do globalnego importera. Tester może dodatkowo uwzględnić zapisane reguły wybranego vhosta.", "cacheGuideScopeVhost": "Przykład VCL zostanie wstawiony tylko do importera tego vhosta. Reguły vhosta mają pierwszeństwo przed zapisanymi globalnymi; można też wyłączyć globalne. TTL pokazany wyżej jest ustawieniem globalnym.", - "cacheGuideScopeDocker": "Przykład VCL zostanie wstawiony tylko do importera tego Docker vhosta. Reguły globalne działają tak samo jak dla zwykłych vhostów, o ile nie są wyłączone. TTL pokazany wyżej jest ustawieniem globalnym." + "cacheGuideScopeDocker": "Przykład VCL zostanie wstawiony tylko do importera tego Docker vhosta. Reguły globalne działają tak samo jak dla zwykłych vhostów, o ile nie są wyłączone. TTL pokazany wyżej jest ustawieniem globalnym.", + "cacheRuleActionCookiePass": "Pomiń cache dla cookies (cookie_pass, strażnik sesji)", + "cacheRuleTplWordpressCookies": "WordPress: pomijaj cookies zalogowanych", + "cacheRuleTplWoocommerceCookies": "WooCommerce: pomijaj cookies sesji", + "cacheRuleCookieGuardHint": "Ta reguła pass zależy wyłącznie od cookies. Jako jawny pass pomija także publiczne CSS/JS/obrazy/fonty dla zalogowanych. Zamiana na strażnika Cookie (cookie_pass) zachowuje BYPASS dla stron, ale pozwala cachować publiczne statyki, gdy włączono „Ignoruj Cookie żądania dla statycznych plików”.", + "cacheRuleCookieGuardConvert": "Zamień na strażnika Cookie", + "cacheRuleCookieGuardConverted": "Zamieniono na cookie_pass. Sprawdź i zapisz; czyszczenie cache nie jest wymagane.", + "cacheRulesResultReasonClass": "Źródło pominięcia", + "cacheRulesResultStaticCookie": "Polityka cookies statyków", + "cacheRulesResultStaticCookieRelaxed": "Strażnik Cookie złagodzony dla publicznego statyku; zapis nadal wymaga jawnie publicznej odpowiedzi backendu", + "cacheRulesResultStaticCookieChecked": "Cookie pominięte w kluczu cache; zapis wymaga jawnie publicznej odpowiedzi backendu", + "cacheReasonClass_security": "Ochrona bezpieczeństwa", + "cacheReasonClass_configuration": "Konfiguracja", + "cacheReasonClass_vcl_rule": "Reguła VCL / cache (jawny pass)", + "cacheReasonClass_vcl_cookie_guard": "Reguła VCL / cache (strażnik Cookie)", + "cacheReasonClass_cookie": "Wbudowana polityka Cookie", + "cacheReasonClass_request_policy": "Polityka żądania", + "cacheReasonClass_response": "Odpowiedź backendu", + "cacheReasonClass_cache": "Stan cache", + "cacheReason_cache_rule": "Reguła VCL / cache: pass", + "cacheReason_cache_rule_cookie": "Reguła VCL / cache: strażnik Cookie", + "cacheReason_cache_miss_static_cookie": "MISS statyku (strażnik Cookie złagodzony)", + "cacheReason_response_static_not_public": "Statyk z Cookie: backend nie zadeklarował publicznej świeżości", + "cacheReason_response_static_dynamic": "Statyk z Cookie: treść HTML/dynamiczna", + "cacheReason_response_vary_cookie": "Zachowano Vary: Cookie (brak jawnego public)", + "cacheReason_response_surrogate_control": "Surrogate-Control no-store" } } diff --git a/src/admin/cache_rules.rs b/src/admin/cache_rules.rs index 9e32b44..a2550c6 100644 --- a/src/admin/cache_rules.rs +++ b/src/admin/cache_rules.rs @@ -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, diff --git a/src/admin/openapi.json b/src/admin/openapi.json index 5ed8e46..0a79acd 100644 --- a/src/admin/openapi.json +++ b/src/admin/openapi.json @@ -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)." diff --git a/src/admin/tests.rs b/src/admin/tests.rs index 70178a2..919c984 100644 --- a/src/admin/tests.rs +++ b/src/admin/tests.rs @@ -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::(&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"); } diff --git a/src/admin/web/cache-rules.js b/src/admin/web/cache-rules.js index c23a8fa..c4a1c0b 100644 --- a/src/admin/web/cache-rules.js +++ b/src/admin/web/cache-rules.js @@ -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); diff --git a/src/cache/policy.rs b/src/cache/policy.rs index 85c5933..56c8079 100644 --- a/src/cache/policy.rs +++ b/src/cache/policy.rs @@ -1,2 +1,3 @@ include!("policy/request.rs"); include!("policy/response.rs"); +include!("policy/decision.rs"); diff --git a/src/cache/policy/decision.rs b/src/cache/policy/decision.rs new file mode 100644 index 0000000..497c7be --- /dev/null +++ b/src/cache/policy/decision.rs @@ -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 { + 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>, +) -> 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::().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 +} diff --git a/src/cache/policy/decision_tests.rs b/src/cache/policy/decision_tests.rs new file mode 100644 index 0000000..ea10899 --- /dev/null +++ b/src/cache/policy/decision_tests.rs @@ -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) -> 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 { + 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()); + } + } +} diff --git a/src/cache/rules.rs b/src/cache/rules.rs index 112c3dc..b3b69d3 100644 --- a/src/cache/rules.rs +++ b/src/cache/rules.rs @@ -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 { .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 { ensure!( crate::config::valid_id(&rule.id), @@ -726,6 +749,13 @@ fn compile_rule(rule: &Rule, origin: RuleOrigin, scope: &str) -> Result, + /// 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, /// 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 = 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; } } diff --git a/src/cache/tests.rs b/src/cache/tests.rs index 570dbbd..93bacc5 100644 --- a/src/cache/tests.rs +++ b/src/cache/tests.rs @@ -24,3 +24,6 @@ include!("varnish_compatible_tests.rs"); #[cfg(test)] include!("rules_tests.rs"); + +#[cfg(test)] +include!("policy/decision_tests.rs"); diff --git a/src/cache/vcl.rs b/src/cache/vcl.rs index da5db35..5f40d3c 100644 --- a/src/cache/vcl.rs +++ b/src/cache/vcl.rs @@ -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(); diff --git a/src/proxy/cache_plan/mod.rs b/src/proxy/cache_plan/mod.rs index be7abbf..a3f6597 100644 --- a/src/proxy/cache_plan/mod.rs +++ b/src/proxy/cache_plan/mod.rs @@ -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, + ), } } } diff --git a/src/proxy/forward/route_cache.rs b/src/proxy/forward/route_cache.rs index fa36aa4..eef4bbb 100644 --- a/src/proxy/forward/route_cache.rs +++ b/src/proxy/forward/route_cache.rs @@ -126,7 +126,18 @@ if let Some(exchange) = request.extensions().get::>() { let mut cache_rule_context: Option> = None; let mut cache_rule_query: Option> = 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, ) } diff --git a/src/proxy/forward/static_cookie_policy_tests.rs b/src/proxy/forward/static_cookie_policy_tests.rs new file mode 100644 index 0000000..b59a341 --- /dev/null +++ b/src/proxy/forward/static_cookie_policy_tests.rs @@ -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, + _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>>, + 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>> = 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!("hello [{}]", 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!("

page for [{}]

", 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 { + 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) -> 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!("

page for [{SESSION}]

")); + // 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; + } +} diff --git a/src/proxy/forward/success_finish.rs b/src/proxy/forward/success_finish.rs index caef9e2..88d4719 100644 --- a/src/proxy/forward/success_finish.rs +++ b/src/proxy/forward/success_finish.rs @@ -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" } diff --git a/src/proxy/forward/success_prepare.rs b/src/proxy/forward/success_prepare.rs index fb95a6e..3c85bd6 100644 --- a/src/proxy/forward/success_prepare.rs +++ b/src/proxy/forward/success_prepare.rs @@ -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) diff --git a/src/proxy/forward/upstream.rs b/src/proxy/forward/upstream.rs index ee41ffc..dcf7c49 100644 --- a/src/proxy/forward/upstream.rs +++ b/src/proxy/forward/upstream.rs @@ -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()) diff --git a/src/proxy/forward_entry.rs b/src/proxy/forward_entry.rs index a325d84..1e76a21 100644 --- a/src/proxy/forward_entry.rs +++ b/src/proxy/forward_entry.rs @@ -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"); diff --git a/src/proxy/mod.rs b/src/proxy/mod.rs index 68c876f..30505bf 100644 --- a/src/proxy/mod.rs +++ b/src/proxy/mod.rs @@ -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"); diff --git a/tools/README.md b/tools/README.md index b1f95a2..972f163 100644 --- a/tools/README.md +++ b/tools/README.md @@ -3,6 +3,7 @@ These files are not required by the running RustProxy proxy process. - `dev/` - local mock services and diagnostic traffic/compression helpers. + - `dev/cache_edge_smoke.py` - black-box cache/VCL edge-case test of the real binary: `local --binary target/release/rust-proxy` (mock origin + headless proxy, 67 checks incl. cross-user leak detection) or read-only `remote --base https://... --static /x.css --page / --cookie '...'` against a vhost with *Expose status* enabled. - `audit/` - explicit operator audit/probe tools. - `legacy/` - retained compatibility/release-test helpers; not the supported production workflow. diff --git a/tools/dev/cache_edge_smoke.py b/tools/dev/cache_edge_smoke.py new file mode 100755 index 0000000..6c4d68e --- /dev/null +++ b/tools/dev/cache_edge_smoke.py @@ -0,0 +1,537 @@ +#!/usr/bin/env python3 +"""Black-box edge-case smoke test for RustProxy cache + VCL-style cache rules. + +Two modes, standard library only: + + local Start a mock origin and the *real* RustProxy binary in headless mode + with the shipped security/session templates, then run ~60 checks + (cookie guards, explicit pass, static policy, Vary, HEAD/Range/304, + compression variants, malformed/split Cookie headers, request + coalescing with concurrent users, ...). + + tools/dev/cache_edge_smoke.py local --binary target/release/rust-proxy + + remote Read-only GET/HEAD checks against a staging/production vhost that + has diagnostic headers enabled (Settings -> Cache -> Expose status). + + tools/dev/cache_edge_smoke.py remote --base https://www.example.com \\ + --static /sites/all/themes/site/style.css --page / \\ + --cookie 'SESSabc=...' [--cookie-b 'SESSdef=...'] + +Global invariant (local mode): a response body tagged ``who=`` by the +origin is only ever delivered to the client holding that session. Any +violation is reported as LEAK and fails the run. + +Exit status: 0 all checks passed, 1 a check failed, 2 setup error. +""" +from __future__ import annotations + +import argparse +import concurrent.futures as futures +import http.client +import http.server +import json +import os +import re +import shutil +import signal +import socket +import subprocess +import sys +import tempfile +import threading +import time +import urllib.parse +from email.utils import formatdate + +RESULTS: list[tuple[str, str, str]] = [] # (status, name, detail) +LOCK = threading.Lock() +WHO = re.compile(r"who=([A-Za-z0-9_\-]+)") + + +def record(ok: bool | None, name: str, detail: str = "") -> bool: + status = "INFO" if ok is None else ("PASS" if ok else "FAIL") + with LOCK: + RESULTS.append((status, name, detail)) + return bool(ok) if ok is not None else True + + +# -------------------------------------------------------------------------- +# HTTP client with exact header control (repeated / non-UTF-8 Cookie fields) +# -------------------------------------------------------------------------- +class Reply: + def __init__(self, status: int, headers: list[tuple[str, str]], body: bytes): + self.status = status + self.headers = headers + self.body = body + + def h(self, name: str) -> str: + values = [v for k, v in self.headers if k.lower() == name.lower()] + return ", ".join(values) + + @property + def cache(self) -> str: + return self.h("x-cache") or "-" + + @property + def reason(self) -> str: + return self.h("x-cache-reason") or "-" + + @property + def text(self) -> str: + return self.body.decode("utf-8", "replace") + + def __repr__(self) -> str: + return f"{self.status} {self.cache}/{self.reason}" + + +def session_of(headers: list[tuple[str, bytes | str]]) -> str | None: + for name, value in headers: + if name.lower() != "cookie": + continue + raw = value.decode("latin-1") if isinstance(value, bytes) else value + match = re.search(r"(?:^|;\s*)(?:session|SESS[0-9a-f]+)=([A-Za-z0-9_\-]+)", raw) + if match: + return match.group(1) + return None + + +class Client: + def __init__(self, base: str, host: str | None = None, check_leaks: bool = True): + parsed = urllib.parse.urlsplit(base) + self.scheme, self.netloc = parsed.scheme, parsed.netloc + self.host = host or parsed.hostname + self.check_leaks = check_leaks + self.leak_exempt: set[str] = set() + + def request(self, method: str, path: str, headers: list[tuple[str, bytes | str]] = (), + body: bytes | None = None) -> Reply: + cls = http.client.HTTPSConnection if self.scheme == "https" else http.client.HTTPConnection + conn = cls(self.netloc, timeout=20) + conn.putrequest(method, path, skip_host=True, skip_accept_encoding=True) + conn.putheader("Host", self.host) + conn.putheader("User-Agent", "rustproxy-cache-edge-smoke/1") + for name, value in headers: + conn.putheader(name, value) + if body is not None: + conn.putheader("Content-Length", str(len(body))) + conn.endheaders(body) + response = conn.getresponse() + data = response.read() + reply = Reply(response.status, response.getheaders(), data) + conn.close() + if self.check_leaks and path.split("?")[0] not in self.leak_exempt: + mine = session_of(list(headers)) + for who in set(WHO.findall(reply.text)): + if who != "-" and who != mine: + record(False, f"LEAK {method} {path}", + f"client session={mine} received body of who={who} ({reply})") + return reply + + def get(self, path: str, *headers: tuple[str, bytes | str]) -> Reply: + return self.request("GET", path, list(headers)) + + +def cookie(value: str) -> tuple[str, str]: + return ("Cookie", value) + + +ALICE, BOB, CAROL = cookie("session=alice"), cookie("session=bob; _ga=GA1.2"), cookie("session=carol") +DRUPAL = cookie("SESS0123456789abcdef0123456789abcd=dave; has_js=1") + + +# -------------------------------------------------------------------------- +# Mock origin +# -------------------------------------------------------------------------- +class Origin(http.server.ThreadingHTTPServer): + daemon_threads = True + hits: dict[str, int] + + +class Handler(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args) -> None: # quiet + pass + + def _respond(self, head: bool) -> None: + path = urllib.parse.urlsplit(self.path).path + with LOCK: + self.server.hits[path] = self.server.hits.get(path, 0) + 1 + who = session_of([("cookie", v) for v in self.headers.get_all("cookie") or []]) or "-" + gzip = "gzip" in (self.headers.get("accept-encoding") or "") + status, ctype, extra, body = 200, "text/css", [], "" + public = [("Cache-Control", "public, max-age=600")] + if path in ("/static/app.css", "/static/APP.CSS", "/static/range.css", "/static/slow-public.css"): + if path == "/static/slow-public.css": + time.sleep(0.4) + extra, body = public + [("Vary", "Accept-Encoding")], "body{color:red}" * 4 + elif path == "/static/app.js": + ctype, extra, body = "application/javascript", [("Cache-Control", "max-age=600")], "var a=1;" + elif path == "/static/drupal.js": + ctype, extra, body = "application/javascript", [("Cache-Control", "max-age=1209600")], "Drupal={};" + elif path == "/static/font.woff2": + ctype, body = "font/woff2", "wOF2" + extra = [("Expires", formatdate(time.time() + 3600, usegmt=True))] + elif path == "/static/enc.css": + extra = public + [("Vary", "Accept-Encoding")] + if gzip: + extra.append(("Content-Encoding", "gzip")) + body = "GZ-BYTES" + else: + body = "PLAIN-BYTES" + elif path == "/static/vary-cookie.css": + extra, body = public + [("Vary", "Cookie")], "shared-by-vary" + elif path == "/static/vary-cookie-personal.css": + extra, body = [("Cache-Control", "max-age=600"), ("Vary", "Cookie")], f"who={who}" + elif path in ("/static/private.png", "/static/slow-private.css"): + if path.endswith(".css"): + time.sleep(0.4) + ctype = "image/png" if path.endswith(".png") else "text/css" + extra, body = [("Cache-Control", "private, max-age=600")], f"who={who}" + elif path == "/static/set-cookie.css": + extra, body = public + [("Set-Cookie", "refresh=1; Path=/")], f"who={who}" + elif path == "/static/spa.js": + ctype, extra, body = "text/html", public, f"who={who}" + elif path == "/index.php/theme.css": + ctype, extra, body = "text/html", public, f"php who={who}" + elif path == "/static/nofresh.css": + extra, body = [("Last-Modified", "Mon, 01 Jan 2024 00:00:00 GMT")], f"who={who}" + elif path == "/static/personal-but-public.css": + extra, body = public, f"who={who}" # misconfigured origin (documented limitation) + elif path == "/account/avatar.png": + if who == "-": + status, ctype, body = 403, "text/plain", "forbidden" + else: + ctype, extra, body = "image/png", public, f"avatar who={who}" + elif path == "/static/missing.css": + status, extra, body = 404, public, "missing" + elif path == "/static/moved.css": + status, extra, body = 301, public + [("Location", "/static/app.css")], "moved" + else: # HTML pages and anything else: personalised + ctype, extra, body = "text/html; charset=utf-8", public, f"

page who={who}

" + data = body.encode() + etag = '"e-%x"' % (hash((path, body)) & 0xFFFFFFFF) + if status == 200 and self.headers.get("if-none-match") == etag: + self.send_response(304) + self.send_header("ETag", etag) + self.send_header("Content-Length", "0") + self.end_headers() + return + self.send_response(status) + self.send_header("Content-Type", ctype) + self.send_header("ETag", etag) + for name, value in extra: + self.send_header(name, value) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + if not head: + self.wfile.write(data) + + def do_GET(self) -> None: + self._respond(False) + + def do_HEAD(self) -> None: + self._respond(True) + + def do_POST(self) -> None: + length = int(self.headers.get("content-length") or 0) + self.rfile.read(length) + self._respond(False) + + +def free_port() -> int: + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +def rule(rid: str, conditions: list, actions: list, stop: bool = False, stage: str = "request") -> dict: + return {"id": rid, "stage": stage, "conditions": conditions, "actions": actions, "stop": stop} + + +def proxy_config(origin_port: int) -> dict: + cookie_header = {"field": "header", "name": "Cookie", "operator": "exists"} + return { + "vhosts": [{ + "id": "edge", + "frontend": {"hosts": ["*"]}, + "backends": [{"id": "o", "url": f"http://127.0.0.1:{origin_port}", "allow_private": True}], + "load_balancing": {"health_check": {"mode": "off"}}, + "cache": {"enabled": True}, + }], + "cache": { + "enabled": True, + "expose_status": True, + "expose_hits": True, + "expose_cache_status": True, + "static_ignore_cookies": True, + "static_ignore_vary_cookie": True, + "collapse_enabled": True, + "rules": [ + rule("methods", [{"field": "method", "operator": "equals", "values": ["GET", "HEAD"], "negate": True}], [{"type": "pass"}], True), + rule("auth", [{"field": "header", "name": "Authorization", "operator": "exists"}], [{"type": "pass"}], True), + rule("private-routes", [{"field": "path", "operator": "regex", "values": ["^/(?:account|admin|user)(?:/|[?]|$)"]}], [{"type": "pass"}], True), + rule("tracking", [], [{"type": "strip_query", "params": ["utm_*", "fbclid"]}]), + rule("drupal", [{"field": "header", "name": "Cookie", "operator": "regex", "values": ["(?:^|;[ \\t]*)(?:S?SESS[a-fA-F0-9]+)="]}], [{"type": "cookie_pass"}], True), + rule("remaining-cookies", [cookie_header], [{"type": "cookie_pass"}], True), + # Explicit pass placed AFTER a terminal Cookie guard. + rule("preview", [{"field": "cookie", "name": "preview", "operator": "exists"}], [{"type": "pass"}]), + ], + }, + } + + +# -------------------------------------------------------------------------- +# Local scenarios +# -------------------------------------------------------------------------- +def expect(name: str, reply: Reply, cache: str | tuple | None = None, reason: str | None = None, + status: int | None = None, body: str | None = None) -> bool: + problems = [] + caches = (cache,) if isinstance(cache, str) else cache + if caches and reply.cache not in caches: + problems.append(f"X-Cache {reply.cache} not in {caches}") + if reason and reply.reason != reason: + problems.append(f"reason {reply.reason} != {reason}") + if status and reply.status != status: + problems.append(f"status {reply.status} != {status}") + if body is not None and reply.text != body: + problems.append(f"body {reply.text!r} != {body!r}") + return record(not problems, name, "; ".join(problems) or repr(reply)) + + +def run_local(binary: str) -> int: + origin_port, proxy_port = free_port(), free_port() + origin = Origin(("127.0.0.1", origin_port), Handler) + origin.hits = {} + threading.Thread(target=origin.serve_forever, daemon=True).start() + work = tempfile.mkdtemp(prefix="rp-edge-") + config_path = os.path.join(work, "config.json") + with open(config_path, "w") as handle: + json.dump(proxy_config(origin_port), handle) + log = open(os.path.join(work, "proxy.log"), "w") + proc = subprocess.Popen( + [binary, "--headless", "--config", config_path, "--data-dir", os.path.join(work, "data"), + "serve", "--proxy-listen", f"127.0.0.1:{proxy_port}"], + stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + try: + for _ in range(100): + try: + socket.create_connection(("127.0.0.1", proxy_port), timeout=0.2).close() + break + except OSError: + if proc.poll() is not None: + break + time.sleep(0.1) + else: + raise RuntimeError("proxy did not start") + if proc.poll() is not None: + log.flush() + print(open(os.path.join(work, "proxy.log")).read()[-3000:]) + return 2 + client = Client(f"http://127.0.0.1:{proxy_port}", "edge.test") + client.leak_exempt.add("/static/personal-but-public.css") + hits = lambda path: origin.hits.get(path, 0) + scenarios(client, hits) + finally: + os.killpg(proc.pid, signal.SIGTERM) + try: + proc.wait(10) + except subprocess.TimeoutExpired: + os.killpg(proc.pid, signal.SIGKILL) + origin.shutdown() + log.close() + shutil.rmtree(work, ignore_errors=True) + return report() + + +def settle() -> None: + time.sleep(0.15) # background body drain for HEAD fills / stream completion + + +def scenarios(c: Client, hits) -> None: + S = "static policy" + # 1. Anonymous then logged-in: one origin fetch, shared object. + expect(f"{S}: anon CSS first fill", c.get("/static/app.css"), "MISS", "cache_miss") + expect(f"{S}: anon CSS reuse", c.get("/static/app.css"), "HIT") + expect(f"{S}: logged CSS reuses anon object", c.get("/static/app.css", ALICE), "HIT") + record(hits("/static/app.css") == 1, f"{S}: CSS fetched once", f"origin={hits('/static/app.css')}") + # 2. Logged-in first (guard relaxed), max-age without public. + expect(f"{S}: logged JS first fill", c.get("/static/app.js", BOB), "MISS", "cache_miss_static_cookie") + expect(f"{S}: other user HIT", c.get("/static/app.js", CAROL), "HIT") + expect(f"{S}: anonymous HIT", c.get("/static/app.js"), "HIT") + # 3. Drupal 6 session + query string. + expect(f"{S}: Drupal6 JS ?v=1 MISS", c.get("/static/drupal.js?v=1", DRUPAL), "MISS") + expect(f"{S}: Drupal6 JS ?v=1 HIT", c.get("/static/drupal.js?v=1", DRUPAL), "HIT") + expect(f"{S}: other version is separate", c.get("/static/drupal.js?v=2", DRUPAL), "MISS") + expect(f"{S}: tracking params normalised into same key", c.get("/static/drupal.js?v=1&utm_source=x&fbclid=y", ALICE), "HIT") + expect("guards: Drupal6 HTML bypass", c.get("/node/1", DRUPAL), "BYPASS", "cache_rule_cookie") + # 4. Expires-only font shared across many cookies. + for index, who in enumerate([ALICE, BOB, DRUPAL, cookie("x=1")]): + expect(f"{S}: font #{index}", c.get("/static/font.woff2", who), "MISS" if index == 0 else "HIT") + # 5. Extension edge cases. + expect(f"{S}: uppercase .CSS is static", c.get("/static/APP.CSS", ALICE), "MISS", "cache_miss_static_cookie") + expect(f"{S}: trailing slash is not static", c.get("/static/app.css/", ALICE), "BYPASS", "cache_rule_cookie") + # Path parameters are rejected by request validation before any cache step. + expect(f"{S}: ;jsessionid path rejected", c.get("/static/app.css;jsessionid=1", ALICE), status=400) + # %2E is normalised to '.', so this is a static candidate; the origin here + # answers with personalised HTML, which the shared-static guard refuses. + expect(f"{S}: %2E-encoded extension, HTML reply not stored", c.get("/static/app%2Ecss", ALICE), + "MISS", "response_static_dynamic") + expect(f"{S}: %2E-encoded extension next user", c.get("/static/app%2Ecss", BOB), "MISS") + r = c.get("/index.php/theme.css", ALICE) + expect(f"{S}: PATH_INFO .css serving HTML not stored", r, "MISS", "response_static_dynamic") + expect(f"{S}: PATH_INFO next user not served", c.get("/index.php/theme.css", BOB), "MISS") + # 6. Refused shared storage. + for path, reason in [("/static/private.png", "response_cache_control"), + ("/static/set-cookie.css", "response_set_cookie"), + ("/static/spa.js", "response_static_dynamic"), + ("/static/nofresh.css", "response_static_not_public")]: + expect(f"storage guard: {path}", c.get(path, ALICE), "MISS", reason) + expect(f"storage guard: {path} next user", c.get(path, BOB), "MISS") + r = c.get(path) + record(r.cache != "HIT" or "who=alice" not in r.text and "who=bob" not in r.text, + f"storage guard: {path} anonymous", repr(r)) + # 7. Vary: Cookie. + expect("vary: public Vary Cookie shared #1", c.get("/static/vary-cookie.css", ALICE), "MISS") + r = c.get("/static/vary-cookie.css", BOB) + expect("vary: public Vary Cookie shared #2", r, "HIT") + record("cookie" not in r.h("vary").lower(), "vary: Cookie removed from public static Vary", r.h("vary")) + for who in (ALICE, BOB, ALICE): + r = c.get("/static/vary-cookie-personal.css", who) + expect(f"vary: non-public Vary Cookie never shared ({session_of([who])})", r, "MISS", + body=f"who={session_of([who])}") + # 8. Compression variants. + gz, ident = ("Accept-Encoding", "gzip"), ("Accept-Encoding", "identity") + expect("encoding: anon gzip fill", c.get("/static/enc.css", gz), "MISS") + expect("encoding: logged gzip HIT", c.get("/static/enc.css", gz, ALICE), "HIT", body="GZ-BYTES") + expect("encoding: logged identity separate", c.get("/static/enc.css", ident, BOB), "MISS", body="PLAIN-BYTES") + expect("encoding: anon identity HIT", c.get("/static/enc.css", ident), "HIT", body="PLAIN-BYTES") + # 9. Explicit pass semantics. + r = c.get("/account/avatar.png", ALICE) + expect("explicit pass: private route image", r, "BYPASS", "cache_rule", body="avatar who=alice") + expect("explicit pass: private route anonymous", c.get("/account/avatar.png"), "BYPASS", status=403) + expect("explicit pass after terminal guard (preview cookie)", + c.get("/static/app.css", cookie("preview=1; session=alice")), "BYPASS") + expect("explicit pass: Authorization", c.get("/static/app.css", ("Authorization", "Bearer x"), ALICE), "BYPASS", "cache_rule") + expect("explicit pass: POST static", c.request("POST", "/static/app.css", [ALICE], b"x=1"), "BYPASS", "cache_rule") + # 10. HTML. + expect("html: anon fill", c.get("/"), "MISS") + expect("html: anon HIT", c.get("/"), "HIT", body="

page who=-

") + expect("html: logged bypass", c.get("/", ALICE), "BYPASS", "cache_rule_cookie", body="

page who=alice

") + # 11. Malformed / split Cookie headers. + expect("cookie: split fields, session in 2nd", c.request("GET", "/", [("Cookie", "_ga=1"), ("Cookie", "session=bob")]), + "BYPASS", body="

page who=bob

") + # A Cookie field that is not valid UTF-8 is dropped before forwarding: the + # backend sees an anonymous request, so the anonymous object is correct. + expect("cookie: non-UTF-8 Cookie treated as anonymous end to end", + c.request("GET", "/", [("Cookie", b"session=x\xff")]), ("HIT", "MISS"), body="

page who=-

") + expect("cookie: empty Cookie header on HTML", c.request("GET", "/", [("Cookie", "")]), ("BYPASS", "HIT")) + # 12. HEAD / Range / conditional / reload. + r = c.request("HEAD", "/static/app.css", [BOB]) + expect("head: logged HEAD on cached object", r, "HIT") + record(r.body == b"", "head: empty body", repr(r.body[:20])) + expect("head: HEAD-first fill (logged)", c.request("HEAD", "/static/range.css", [ALICE]), "MISS") + settle() + expect("head: following GET reuses HEAD fill", c.get("/static/range.css", CAROL), "HIT") + r = c.get("/static/range.css", ("Range", "bytes=0-3"), BOB) + expect("range: logged range from cache", r, "HIT", status=206, body="body") + etag = c.get("/static/app.css").h("etag") + expect("conditional: logged If-None-Match", c.get("/static/app.css", ("If-None-Match", etag), ALICE), "HIT", status=304) + expect("reload: no-cache from logged browser (compat mode)", c.get("/static/app.css", ("Cache-Control", "no-cache"), ALICE), ("HIT", "MISS")) + # 13. Non-200. + for path in ("/static/missing.css", "/static/moved.css"): + c.get(path, ALICE) + expect(f"status: {path} not stored", c.get(path, BOB), "MISS") + # 14. Concurrency with request coalescing (collapse) and mixed users. + users = [cookie(f"session=u{i}") for i in range(12)] + + def fetch(args): + path, who = args + r = c.get(path, who) + return who, r + + with futures.ThreadPoolExecutor(12) as pool: + replies = list(pool.map(fetch, [("/static/slow-private.css", u) for u in users])) + ok = all(r.status == 200 and r.text == f"who={session_of([u])}" for u, r in replies) + record(ok, "concurrency: 12 users on private static each get own body", + ", ".join(sorted({repr(r) for _, r in replies}))) + before = hits("/static/slow-public.css") + with futures.ThreadPoolExecutor(12) as pool: + replies = list(pool.map(fetch, [("/static/slow-public.css", u if i % 2 else ("X-N", "1")) + for i, u in enumerate(users)])) + fetched = hits("/static/slow-public.css") - before + record(all(r.status == 200 for _, r in replies) and fetched <= 2, + "concurrency: 12 mixed anon/logged on public static coalesced", f"origin fetches={fetched}") + # 15. Documented limitation: origin marks a personalised .css public. + c.get("/static/personal-but-public.css", ALICE) + r = c.get("/static/personal-but-public.css", BOB) + record(None, "limitation: personalised body labelled public by origin", + f"BOB got {r.text!r} ({r}); fix such resources at the origin (private/no-store) or with a path pass rule") + + +# -------------------------------------------------------------------------- +# Remote (staging/production) read-only checks +# -------------------------------------------------------------------------- +def run_remote(args) -> int: + c = Client(args.base, args.host, check_leaks=False) + a = cookie(args.cookie) + b = cookie(args.cookie_b) if args.cookie_b else None + probe = c.get(args.static) + if probe.cache == "-": + record(False, "diagnostics", "X-Cache missing: enable Settings -> Cache -> Expose status for this test") + return report() + for path in args.static_list or [args.static]: + first = c.get(path) + second = c.get(path) + expect(f"static {path}: anonymous reuse", second, "HIT") + expect(f"static {path}: logged reuse", c.get(path, a), "HIT") + if b: + expect(f"static {path}: second user reuse", c.get(path, b), "HIT") + expect(f"static {path}: logged HEAD", c.request("HEAD", path, [a]), "HIT") + record(None, f"static {path}: first anonymous", repr(first)) + for page in args.page_list or [args.page]: + r = c.get(page, a) + record(r.cache != "HIT", f"page {page}: logged never HIT", repr(r)) + if b: + r2 = c.get(page, b) + record(r2.cache != "HIT", f"page {page}: second user not HIT", repr(r2)) + return report() + + +def report() -> int: + width = max((len(name) for _, name, _ in RESULTS), default=10) + failed = 0 + for status, name, detail in RESULTS: + failed += status == "FAIL" + print(f"{status:5} {name:<{width}} {detail}") + passed = sum(1 for status, _, _ in RESULTS if status == "PASS") + print(f"\n{passed} passed, {failed} failed, {sum(1 for s, _, _ in RESULTS if s == 'INFO')} info") + return 1 if failed else 0 + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = parser.add_subparsers(dest="mode", required=True) + local = sub.add_parser("local", help="start origin + headless RustProxy and run all edge cases") + local.add_argument("--binary", default="target/release/rust-proxy") + remote = sub.add_parser("remote", help="read-only checks against a deployed vhost") + remote.add_argument("--base", required=True, help="e.g. https://www.example.com") + remote.add_argument("--host", help="Host header if different from --base") + remote.add_argument("--static", required=True, help="public static path, e.g. /theme/style.css") + remote.add_argument("--static-list", nargs="*", help="several static paths") + remote.add_argument("--page", default="/", help="session-dependent HTML path") + remote.add_argument("--page-list", nargs="*") + remote.add_argument("--cookie", required=True, help="logged-in Cookie header value (user A)") + remote.add_argument("--cookie-b", help="Cookie header value of a different user (user B)") + args = parser.parse_args() + try: + code = run_local(args.binary) if args.mode == "local" else run_remote(args) + except Exception as error: # setup problems + print(f"setup error: {error}", file=sys.stderr) + code = 2 + sys.exit(code) + + +if __name__ == "__main__": + main() diff --git a/tools/dev/test_cache_rules_panel.js b/tools/dev/test_cache_rules_panel.js index 7d6fdcb..63ca2fe 100644 --- a/tools/dev/test_cache_rules_panel.js +++ b/tools/dev/test_cache_rules_panel.js @@ -37,4 +37,24 @@ for (const statement of [ ]) assert.ok(vcl.includes(statement), `missing in VCL export: ${statement}`); assert.ok(!vcl.includes("return (lookup);"), "should not generate lookup in recv"); assert.equal((vcl.match(/return \(deliver\);/g) || []).length, 1, "single terminal deliver"); +// Cookie/session guards: templates emit cookie_pass, explicit guards keep pass. +sandbox.t = key => key; +const actionsOf = key => JSON.parse(JSON.stringify(editor.TEMPLATES[key]().map(rule => rule.actions.map(a => a.type).join(",")))); +for (const key of ["cookiepass", "sessioncookies", "django", "laravel", "authjs", "aspnet", "drupal"]) + assert.deepEqual(actionsOf(key), ["cookie_pass"], key); +assert.deepEqual(actionsOf("wordpress"), ["pass", "cookie_pass"]); +assert.deepEqual(actionsOf("woocommerce"), ["pass", "cookie_pass"]); +assert.deepEqual(actionsOf("cdn"), ["pass", "pass", "pass", "strip_cookies", "cookie_pass"]); +for (const key of ["safemethods", "authbypass", "checkout", "preview", "webhooks", "graphql", "signedurls"]) + assert.deepEqual(actionsOf(key), ["pass"], key); +for (const key of ["privateroutes", "privateapi"]) + assert.equal(actionsOf(key)[0], "pass", key); +// Every cookie_pass template rule has a non-negated Cookie condition (server validation). +for (const key of Object.keys(editor.TEMPLATES)) for (const rule of editor.TEMPLATES[key]()) + if (rule.actions.some(a => a.type === "cookie_pass")) + assert.ok(rule.conditions.some(c => !c.negate && (c.field === "cookie" || (c.field === "header" && String(c.name).toLowerCase() === "cookie"))), key); +const guardVcl = editor.exportVcl([{ id: "g", stage: "request", match: "all", conditions: [{ field: "header", name: "Cookie", operator: "exists", values: [] }], actions: [{ type: "cookie_pass" }], stop: true }]); +assert.ok(guardVcl.includes("return (cookie_pass);"), guardVcl); +assert.ok(guardVcl.includes("RustProxy extension (Cookie guard)"), guardVcl); console.log("PASS: cache rules JS export, request headers, store override, vcl_hash and terminal deliver"); +console.log("PASS: cookie_pass templates and VCL export");