From 15425fb803b8ed02d328457abd0c9791083bec5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Gruszczy=C5=84ski?= Date: Fri, 20 Nov 2026 17:18:02 +0100 Subject: [PATCH] v0.39.0 --- CHANGELOG.md | 7 + SHA256SUMS | 54 +- docs/API.md | 2 +- docs/CACHE.md | 8 +- docs/DOCKER_DISCOVERY.md | 13 + docs/FEATURES.md | 4 +- docs/README.md | 2 + docs/VCL.md | 2 + docs/VCL_SUPPORT_MATRIX.md | 212 +++++++ docs/VCL_TRAFFIC_COOKBOOK.md | 587 +++++++++++++++++++ examples/vcl/advanced-set-cookie-removal.vcl | 9 + examples/vcl/cdn-technical-cookies.vcl | 23 + examples/vcl/experiment-variants.vcl | 22 + examples/vcl/headers-and-diagnostics.vcl | 15 + examples/vcl/language-catalog.vcl | 21 + examples/vcl/private-routes-bypass.vcl | 16 + examples/vcl/public-catalog.vcl | 21 + examples/vcl/public-json-api.vcl | 21 + examples/vcl/static-assets-public.vcl | 16 + examples/vcl/stream-and-errors-no-store.vcl | 17 + examples/vcl/tracking-query-restricted.vcl | 9 + langs/en_US.json | 10 + langs/pl_pl.json | 10 + src/admin/documentation/documents.rs | 2 + src/admin/logging_api.rs | 88 ++- src/admin/openapi.json | 63 +- src/admin/operations.rs | 18 +- src/admin/web/cache-panel.js | 21 +- src/admin/web/cache-rules.js | 12 + src/admin/web/index.html | 31 + src/admin/web/traffic-panel.js | 20 +- src/cache/rules.rs | 16 + src/cache/rules_tests.rs | 68 +++ src/docker/tests.rs | 72 +++ 34 files changed, 1423 insertions(+), 89 deletions(-) create mode 100644 docs/VCL_SUPPORT_MATRIX.md create mode 100644 docs/VCL_TRAFFIC_COOKBOOK.md create mode 100644 examples/vcl/advanced-set-cookie-removal.vcl create mode 100644 examples/vcl/cdn-technical-cookies.vcl create mode 100644 examples/vcl/experiment-variants.vcl create mode 100644 examples/vcl/headers-and-diagnostics.vcl create mode 100644 examples/vcl/language-catalog.vcl create mode 100644 examples/vcl/private-routes-bypass.vcl create mode 100644 examples/vcl/public-catalog.vcl create mode 100644 examples/vcl/public-json-api.vcl create mode 100644 examples/vcl/static-assets-public.vcl create mode 100644 examples/vcl/stream-and-errors-no-store.vcl create mode 100644 examples/vcl/tracking-query-restricted.vcl diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ec440a..fe96dd5 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.0 — Docker Cache/Traffic and CDN VCL patch (source-only changes) + +- **Cache and Traffic Docker scopes:** added Docker-generated Vhosts to both selectors, with readable container/hostname/agent labels. Added a Docker-inventory `catalog_version` so refreshes update the list even when the persisted configuration revision is unchanged. Cache purge and invalidation accept these IDs. +- **CDN technical-cookie rules:** optional VCL example and graphical template for Cloudflare/Akamai cookies. Only a complete Cookie-header allowlist is stripped; other cookies, Authorization, sensitive paths and non-GET/HEAD methods bypass cache. Matching now checks multiple physical Cookie header lines as one logical condition, preventing accidental session-cookie removal. +- **VCL implementation reference:** new exhaustive support/limitation matrix and operational guidance for Docker configuration persistence and safe `Vary` handling. Added a source-reviewed **VCL traffic cookbook** with 11 ready-to-import examples, a request/response behavior matrix, operational `curl` checks and troubleshooting. The guide is included in the embedded Reader, and standalone VCL examples are under `examples/vcl/`. No general-purpose `Ignore Vary` override was introduced. +- **Verification:** Node template checks added; Rust importer tests added but require a Rust toolchain and real proxy tests before production use. + ## 0.39.0 — Dependency security refresh and compatibility fixes (source release) ### Changed diff --git a/SHA256SUMS b/SHA256SUMS index da6c03b..1b0086f 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ 4140a2956264b44f259e6a37fc00ba02097bbe68b09296e04d3d243c1287129b .env.example e76e688874828e3743d03693b1d2872b9633b4db09909673786caf30f7cfe489 .gitignore d0ee3e0d9956ceb7384430cf12784b4173d9fb4e50d6be3a9ef082b3867ab4db AGENTS.md -ba2ed47c08764410eba014e9216f4ddd0fdd179f6be7855d719980340c24a1e2 CHANGELOG.md +0caffb8765928db11df750fada8fa9775663ba5fd236316189852f7bcf282021 CHANGELOG.md 958e2bb62b874e0e81efce99aaf4cf0a37148a698d6f35341bdcd4b733cabefd Cargo.lock 8cc2002d1c5fab90e75a451e55f889d1dce0e6bd1f7df8bdb6c10619e83a359a Cargo.toml 788745d4f70a0382c6280020afbd48844bb2af65e835a826852143f8132cdeca Dockerfile @@ -39,15 +39,15 @@ f30c895df3d7f289f3b7c9a73969009ecf91110f59cb247daa242f68e78aa014 docker-agent/s 20313df0c14a1696d099ed881b159fe854e92538a60548a1729f92babaead881 docker-agent/system.go 188b74ec4f58da1b46d86925a67b6a590c92fb4fd7516e8d03d43871bc3b4542 docker-agent/system_test.go c0940a4b323d71931cf2ad4ad24d58b6d6bfd49af90c6e3fc91fcbe2b4cf312f docs/ACCESS.md -d44ffd1651afe1f2059f53907736aa1b74047d54512897532d746f98f5af689b docs/API.md +e986cbe1534bbe392b2ce6413fc00ac5bc5d70b40d50c247c5b1b6c7b2760fbe docs/API.md 728b15b9825f547f34c4121219784798dd046fbbdd72ece8906d0cd77e8efc64 docs/BACKUP.md -d03da7b844a28d2e8bdb72690c571f5f46ba8bb254d801aad3f2e7e64afa09d0 docs/CACHE.md +c3e356829a933b081ef9a359ab71fcd88e073c3c1f64f09a03c1f19589960240 docs/CACHE.md a64f72b95918c24938aa7268ec0a534cb0f28dd1ee0aa325b02c49f3347ccf54 docs/CERTIFICATES.md 6aa83366ad45227d10ebe121ed2c4f690ebcb826939ec2b2eafb40bfd714ac69 docs/CONFIGURATION.md fec29ce846d6705eb45819d85d382f28e28a146b265feab2e4c7cce2a35e5883 docs/CUSTOM_LOCATIONS.md 2f3e005ab01bb48b6a2d74dd8f163159f892d08c35d9ad7162e912e1d4def870 docs/DASHBOARD.md -a7cfdc1a0fb1d2aaaa194587d5f168a212b4fad6045156e84228e99358ae3195 docs/DOCKER_DISCOVERY.md -e8d65d6afb9b857c95c918811cb48e59888c7adb4c2bf39d576a3c5953ebccae docs/FEATURES.md +81bd7a901619092e2a5a5fb7e4edd2157f2b5ce7e0483c24581ec290080446c0 docs/DOCKER_DISCOVERY.md +0a0ed8a27965635c841d80d4b905f996b78dd165d81827712a0d50c011310bbd docs/FEATURES.md f5835144cd2802abbcac3a36c76bdd4ec2f25fa49307facb199efec5bf9e92d3 docs/HEADLESS.md 4282602f0b814841f71282040003bec91c24611e5152b33407b76e62357f8d3a docs/INSTALL.md 6e37859bf0dced99d4a7db93790cb38fcd90191932827946d5223eaa4c784fce docs/LOGS.md @@ -55,7 +55,7 @@ f5835144cd2802abbcac3a36c76bdd4ec2f25fa49307facb199efec5bf9e92d3 docs/HEADLESS. a7717c4ab03417914805527e573ea1dfd5d35295bf7b347d0c098bda6d469850 docs/MONITORING.md 6d3937088eeb67a9f690d44ebe0b6e660b68116dbf69091ac7816bdc52cec2b6 docs/PERFORMANCE.md d5894c07c68ec4230987767198434abee13b0e525842fea21bcbe752fa82742b docs/PHP_FPM.md -a84096680ede9b56de31c336f14122f91f8bf3c5a1ed9a292e66eeddd4dcce9f docs/README.md +36e9108818d2898f9fefd06274c50df8d54f4453f827cd306d7e506616f372a1 docs/README.md 490a6dbe870f2b1fd4ec7816768dde6c86fa7957fc9de2d2f075e123c9222222 docs/RESPONSE_DELIVERY.md 95ab4786792d5920a2e109b7d196838057f24b512a69d713fb5884dc75c84339 docs/SCREENSHOTS.md 3a48184b36d225757fc5e2d22c629f89bfe5d4007ff087f0be0ce02a5fb04c28 docs/SECURITY.md @@ -63,7 +63,9 @@ bbef60ff1771da9f48af812987766e1e479408873ae2f079b13f1d5c62ecc6ff docs/STREAMS.m c9c9a0b401f0565f15b834d855bfdb34edb3eab46bff03d9e0825af204d20bf8 docs/TODO.md 978097cf53314ad573583d7176491d984b9dbb22295df2b00168a28b14184c4a docs/TRANSPORT.md be6e8af62a7bf958b94ec15e9e3263263e511d1d33abae4e45d114833fa52b07 docs/TROUBLESHOOTING.md -47abed11fd4f0370ee887fb2e5e4ee777af2cad194db5638ad65714a9c07218d docs/VCL.md +a4ef8aa0c632c79b468f821dc8c900c99898881253473faef7f97c937d315517 docs/VCL.md +66d640c08ea6ff6f05f917113bbc3dbd7bea81148dbd461d1f9d56ec2d9f9eae docs/VCL_SUPPORT_MATRIX.md +ec4acdcff607d3d8db04f7777643fe8cafad778c1fe0ccbcc24f2424912069e2 docs/VCL_TRAFFIC_COOKBOOK.md 1169420deeed8f2e8f3a0acfb3ffe16a3419820ba1869059e0b82bb2411e1537 docs/VHOSTS.md e67928a9d044e71b681c3e52f9dd8b151d6b72f965d16d5da8b0eadde98b70e9 docs/WEB_SERVER.md 42822b1c9801bcadb0e2d785cb91883ca2df1da141222631f153030c95f5e197 docs/images/about.png @@ -91,6 +93,17 @@ b26833cb4251f9390a44192ecc827ff7f052fd19016a5ccf7498c94503ab4ce3 examples/mock- a6b835dc07defc12b8f0e48491d5f413843c8be2ba4501d7c28140a2822b034f examples/oidc-vhost.json 134d4a59727b27accb3141d4cee26a4a74157d236de4996bfd682e639462b2b5 examples/tinyauth-vhost.json 5a8f3a8a054abc89c6e78896b9fe2f903212199a24dc3d2d2bcbd0696a31bcde examples/transport.json +07fef8fb9d20f9d6db1520625f17283a1b598a07e3bd10c1ecbb964923899bc2 examples/vcl/advanced-set-cookie-removal.vcl +56747aae2bc970ea0a8cf2e97232201c01fc7ac7748de90dcb23c62254f404f3 examples/vcl/cdn-technical-cookies.vcl +9de59289bc83e1bb607263a41be3738321dddb9896dc30a483f2c7b18b70859a examples/vcl/experiment-variants.vcl +ecfa04e9f1e9c4f1b1629854798dc432c24414cdd6e80788bceffe37a6716011 examples/vcl/headers-and-diagnostics.vcl +33366f6ff579e50e727aabc552db08fe25e7471f5c52041f55c96493c88c362e examples/vcl/language-catalog.vcl +d055d1d6ee01a567a90a4f2599c276567b4f834203f5c08e23d8da25a66ce918 examples/vcl/private-routes-bypass.vcl +1c97e44b66765616a2756bc01ef1f100f82adcfe330271cde4bd5e7021221558 examples/vcl/public-catalog.vcl +718f6ee134b4d6691284a84ae4dbc2ac5d4c3de61bf1df7889b025f411e2ee43 examples/vcl/public-json-api.vcl +4f12a9802c0df71d950822c5a8b04afb39da79075bc146b5c72f3148cb47610b examples/vcl/static-assets-public.vcl +8cd3f62c6ffc8339facfbaa390ec88aae465e7e605ef403673be569e3308da02 examples/vcl/stream-and-errors-no-store.vcl +5ca6374c3125b0e1891a1554ab0414f7c5309459b7d79765550ac3ef3bd14fd4 examples/vcl/tracking-query-restricted.vcl d242de9614fbb52933b4accd32f4715ca94107abe4a3b1d7e088362b07a6ba60 examples/vhosts-balanced.json af2bdb1343a8141069e94ccd2c7f92574ad848437e2f9fdb5c7576a9a18ef4a5 examples/vhosts-private.json 716dd2ba150e3813116d2a8c568865b1e315f2fd29c6e636dcd72709dd444837 grafana/README.md @@ -110,8 +123,8 @@ e9cbb0224c4a3d23a6019ba557e0cd568c1ad5e1582ff1e335fb7d99b7a1055d integrations/r 3f092a9ab80221eddd67be4d1a776acbc6e04c1eb6011b588280c28e83b2582f integrations/routeros-oci-build/build-routeros-oci.sh 3f267cafa16006e5456ade78ee2d5fae02cc7ce747839523068ffd8d7c98798a integrations/routeros-oci-build/docker-entrypoint.sh ae2ee2887fcba096d0de25edcc18faa1ffec35759274518db1bf6d6982f7176c langs/README.md -8dd0d83f0abcb18d66fb195aa233f599bf444846aaab7c3d3a48bd6bb002cc36 langs/en_US.json -85f37488fcc0d38622fc1b089ea05fdfdd238b64e8b6cc299fdaf43f03b8bda4 langs/pl_pl.json +6bd467554bee19d30fcaf92d3b177cfbc25e3937ca5ef3a1a244995e7c1a2e51 langs/en_US.json +b21057d0bc1951f4f284843d6037039572622590a16ce2fa874f4168e2578303 langs/pl_pl.json 8ed80f14633970899d56f4ea72684a8d4b1f2843c1c78bfacc4cbb5f7ce9ef4b make_zip.py e830d37dd1f81a4b0aa7d535f5bba69e34e433b0fd99cc8ee0b296786c32379a migrations/0002_admin.sql 20112cc82192098b8d602f1c4f7ca08712e9e1366c845fabb92753187c370d35 migrations/0003_certificate_renewals.sql @@ -177,16 +190,16 @@ aefbef9839f9914ba05ea62bceff1463da3042b52ee851181ee39d4fbf7b91c3 src/admin/cert 7cac90d705a201b764d283e06774744e4b358eb157a8c492357bfc21aed37543 src/admin/config_sections.rs c51f725075b5c4fc3fb7fb8b8b5f73987bff698a400e8950e968068b97a77631 src/admin/dashboard_presets.rs aae1ca0e70d987830bd63948d431f54302083148177c1b551565be12df7fe771 src/admin/documentation.rs -950cd7f14c061838311b0d4babfb82bc0901b918691b633bba9772b8a8dfddfb src/admin/documentation/documents.rs +e55d4cea1711abadad14d7e65e1d1fa479daa0a28eaa7651c9600a776a2ca3c2 src/admin/documentation/documents.rs b9c2952e3fcfca540d0ad64f2d3acc5c1f5240e707f4f23ef4d452f46fcb520f src/admin/documentation/tests.rs 1ce779b84aa8f47bdb3c34f83593c1f2f06d2235f0319847096cfcd035434168 src/admin/file_log_search.rs 059218501907355b22bc84e7e0c41ec72565af283f5e97170ce7707ea5874009 src/admin/file_logs.rs d58a2ed83319176de4e66790ed292447c9497ae031464ec55cfe27174acb639a src/admin/file_logs_io.rs 77b8c05645969834cc8a58e249a7b60a57d6c47ad1c5cd92ffa5e4a9b5a8e73c src/admin/file_logs_query.rs -13f885b119b79c44cba69c67bdda5a69670d3179472487379edd0a05199486fa src/admin/logging_api.rs +e287399bfef114028b8831cb854db2323c0e1b61e3503ef409ebb2c5cdbc2a8c src/admin/logging_api.rs 51228956c33358278ebed62941da273e1e87d0b5c5d1c40cc0d2c91aec9d7362 src/admin/mod.rs -320d3ad9554cfd43959411cb7a84bc2a48c54acbf376b5fa084de6dca48ae5a7 src/admin/openapi.json -f7a356109786635dd58cba590c71c796dbf36b47f25845190c75ee5c6a9fcb86 src/admin/operations.rs +6263ee9b5b5478160b028ff05ed6dc9a6a679fb9c92d6a3467508533b4934610 src/admin/openapi.json +9f8842cdec27d703d1795dd6eb37d9420e9f5a2e56a0df93278c92bace5d1f4c src/admin/operations.rs 257d93a29d0bda96462bcf695aba8d0ec0f9412c379e066ec46ae8ee034e3a53 src/admin/panel_assets.rs f5127855c2994d052678865df36d703b74f4a0afc633daf7718b10da18d26e37 src/admin/panel_content.rs 77a23c54a9dc7ac2c2525d223fc4656e3c447b7ba32c96dd698b3ffb18ef1a69 src/admin/preferences.rs @@ -234,8 +247,8 @@ b0930110e4eb7de6826e27b5b46c47e46556449fed6dc505d42da4f5e9c20366 src/admin/web/ 2281f06990f86acd3ff12fa368e1b73e4c83601e20245f24abbce389dfccb77f src/admin/web/app/sidebar.js b7ead49224a4ec67181d3f24f9d9634bd6d76756f826a4d5d993300637d1d8f3 src/admin/web/app/stream-dashboard.js 7de070cc8cdde45d7e0932259299e341e25b32c9ffbd87e4fcce934d0f090de4 src/admin/web/app/web-overview.js -1de54408b1a0c131fcb636f39cd4cf080d11da3188c42dd55bffbd1ef71f2322 src/admin/web/cache-panel.js -cd0585403a82e7b30d56d674497ec8a6322f6662537d19be942816c0652d7f07 src/admin/web/cache-rules.js +857a3c49d003a4c3beed98acf404fcffa1b7b127f34579a916196e007e8a2963 src/admin/web/cache-panel.js +730b79e4dadc9b1487888dcd426518a76476aaa254bf4cc3410f35deb75b589e src/admin/web/cache-rules.js 6288b0a8228d828ac2e2535ace2d1aefd1c04011e789eb97f7279129874ac35c src/admin/web/certificate-api.js f554ca7179fe4d97ae24aa004d4bc9ada5f84fc78257891933a7fed728006ef8 src/admin/web/css/00-tokens.css f13fd5486664d9803a99e226321bc84bd571a100c105884e6c68b127071595f1 src/admin/web/css/10-base.css @@ -272,7 +285,7 @@ e6c4d91d1542d0a5b47bb8736f9539d43a6713df5a473b635519d5b7eac2eb9c src/admin/web/ 0a5fff35555153f59d4346933030a67b6e1a8768cee7a47cfa2fcf1a2c564f63 src/admin/web/favicon.svg 1430936eef78ab81db57e8e9273dd0bc7d3398c8cad39acede051852d9a728f4 src/admin/web/file-logs.js 85f54ce519140a38e31fb1b3d5974585748d7162f0499aa63703c1db56334b2c src/admin/web/host404.js -b3b9720a6737c0867596fb089d7a2462782c34dc453ffe8e94bace8c871b60a3 src/admin/web/index.html +f45921560aa1dc37333348b53840bc4005bc28cf99143e28b65ed491eb33e627 src/admin/web/index.html c5cc91382ddcf47dcff9f422ef2f94c1ebe45362c14f119c1a55b582d71443c7 src/admin/web/integrations.js 7a12f020fc587205694978ab41b660e9a80487d413fbf6e34fc525eabc58308f src/admin/web/login-keys.json ac9f667273918e18406df06cb2613c923f50a88897693a03a18f500e22dc6ec2 src/admin/web/login.html @@ -287,7 +300,7 @@ f8c3424d17bb94f80f00a7f8f4fac7ac3c8718141e975ccf5b42cc8686a00082 src/admin/web/ 6322e589c449eee6db9c3499bb5643d6261f5fc3a5d730cff12cef70d5699fa2 src/admin/web/streams.js 14ef42dec556c5fa62ff4ed4d6865d28f322e8e963dc43e3a714ef9d0af12ac6 src/admin/web/system-info.js 12db5600c14cadbbbe7676b170b058e9695108d2661d9cd6b61fe91d355ac731 src/admin/web/tls-configurator.js -dd697c7c46e40da006b61220a90ed9579c3c08c1484a96dc746314d5b4c4f3ea src/admin/web/traffic-panel.js +336cc5b2a3e5e2514b6b15eed5f2b1ba714458d0e3e913d6f9ad7c870623c758 src/admin/web/traffic-panel.js 675ea169d4cc55fda5e291af536338b882bede1eaa6c9d5cc7dfde0779c7c4d1 src/admin/web/transform-panel.js a49da8cd65b1db4a96ff6a4f101629d3ed036798d5f14f5d8297036fb7f6c75a src/admin/web/vhosts/core.js d0d0507ee2067fa95d0c7e7e2edc4ca9cb416ce040a7bc548bd07d4fbdc94556 src/admin/web/vhosts/editor.js @@ -362,8 +375,8 @@ e26dce02df9c043329ca164fed215d271781bce8fb03240f528331bf3df6b9d7 src/cache/poli 20d4af129be642f727f3de694abe9404210dd0210dc56124028d62c2f8dd4649 src/cache/policy/response.rs 12a6d5d9d6711e956391b4b952e8149658b8bf64cfcc0a4c59c281f2630a6aac src/cache/policy/scope_tests.rs c3a4300f7cdb6b2b7c16fbc489d49ba2451331bb4a55a2d9f618c684fd61eecb src/cache/range.rs -37d077a35f34e3ed76601838ffc3a9596a452727ce7cbfc82d024fb70b6b5fa4 src/cache/rules.rs -77414809d3f128781d9c665dc52a454db2f3f93f59f164384881ca7c1cc75d8c src/cache/rules_tests.rs +847fd250a795a554fa10176d439fb4e777d3dc75f90aeafb29b133a313c09eb9 src/cache/rules.rs +99719d4e8c9a27bac460b006aaea7f0f731bfb476003c051f7ebe823517e1d7a src/cache/rules_tests.rs 48344d7dcbbb220d8c16f5aa9bb88d86a6388b226bbf93d0ca92d8dfbf2c8001 src/cache/stats.rs 2981e35a7fbbc2b36214b5518f4ba97d57c1d2e01f4f375175c4b2c6be955927 src/cache/tests.rs b969394b04859b269dcecd8958b1aab40b532709512714e9900f0ecad6b6d0c5 src/cache/tickets.rs @@ -394,7 +407,7 @@ d2ef07d1565569f520a6a8eb01f4ea9bb673499d038018d52e65fe95e800bb27 src/diagnostic ea041859335219773748acbb479f83245ecdd3301108972fc0e0c1ea4c95717f src/docker/client.rs 8b65a469995b97b92a2dcd97aabfdd6d4370638b6faf5dd99e7a8ade6c924c63 src/docker/model.rs 7b902b2b42a20d8f1419d97cb428ca2cf65cb0108f3d27456ba735077dc809e3 src/docker/reconcile.rs -adbab0ce3e8c0d0e42c8993f9352082ed6bb2f63605e573c55e1a8583b86bd45 src/docker/tests.rs +ab62df22bbedfe84b10a498c023c2a15628bf466cb84b58c3a98c571a6b3758d src/docker/tests.rs 34eb55a240928e98bd34e790ac63096b9ca8bf7a3008676dbbd11e1a392b8541 src/forward_auth/mod.rs 6c25951cf69e972c47cdf815f22a5062916b2b768e39d55a26a5fc9e625a2344 src/forward_auth/tests.rs 5d32cf9177a33d6fb50452541805b10ae1b0833e709d833f5bd1fc6907193ffb src/forwarding.rs @@ -596,6 +609,7 @@ e5f5fbe702f66bfcbcbc1d1f3cd3d89bdbb929bb86aed94868a2a06a4b9e59e3 src/web_server b791762b4ab7a43c3be19df84e523faf3dfb4df055f66d02178f93edb60d2204 src/web_server/serve.rs 714418c86ab241020a561fcf662a8fe324a6a70cc2fd3a313c56d7939c14b9e8 src/web_server/tests.rs f00743af2cf4a5952caef7a1dcf68e7817b5599a252a9973e1c22045517c0b0e tests/fixtures/argon2id.json +9016b3aa11736927b3bc41c722555bc6b89c6b7e79dc829700b3c80d4ab07267 tests/js/cdn-cookie-template.cjs cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 third_party/swagger-ui-5.33.1/LICENSE 0d20d1adef18aee3f40dd258172155521ce702ac445cb5f7b7d60ed32dad2fb2 third_party/swagger-ui-5.33.1/NOTICE 2c9e148b9acd740850aa33ae52878f1ecf19cdc67f6041e2c0a7aab1e95782f2 third_party/swagger-ui-5.33.1/README.md diff --git a/docs/API.md b/docs/API.md index 66771c8..dc839b6 100644 --- a/docs/API.md +++ b/docs/API.md @@ -37,7 +37,7 @@ The current bundled `src/admin/openapi.json` declares these operations (among ot Some paths have additional DELETE/PATCH operations, job-status resources, query parameters or restricted actions. Use OpenAPI for the **actual fields/methods**, not guesses based on a table. `GET /metrics` here is not a replacement for the separate Prometheus exporter. -For browser polling, `GET /api/cache?view=live`, `GET /api/transform?view=live` and `GET /api/traffic?view=live` omit static response members that do not need to be retransmitted on every interval. Their `revision` identifies the active configuration; when it changes, clients should fetch the corresponding endpoint without `view=live` and refresh their cached static fields. Requests without `view=live` remain the complete compatibility form. Cache live responses contain metrics/dashboard/bans, Transform live responses contain resources/metrics, and Traffic live responses retain current settings/GeoIP/analytics while omitting the static Vhost list. Unknown `view` values are rejected. +For browser polling, `GET /api/cache?view=live`, `GET /api/transform?view=live` and `GET /api/traffic?view=live` omit static response members that do not need to be retransmitted on every interval. Their `revision` identifies the active configuration; Cache and Traffic additionally return `catalog_version` (a fingerprint of the effective Vhost list, including Docker publications). If either revision or this fingerprint changes, clients should fetch the corresponding endpoint without `view=live` and refresh their cached static fields. Requests without `view=live` remain the complete compatibility form. Cache live responses contain metrics/dashboard/bans, Transform live responses contain resources/metrics, and Traffic live responses retain current settings/GeoIP/analytics while omitting the static Vhost list. Full Cache and Traffic responses provide readable `vhosts[].label` and `vhosts[].docker` together with the stable `id`; Docker-generated IDs are valid cache purge/invalidation and analytics scopes. Unknown `view` values are rejected. Certificate inspection accepts `{ "cert_file": "filename.pem" }` for a managed file or an absolute external path and returns `{ "cert_file": "...", "covered_hosts": ["example.com"] }`. It applies the existing certificate-file trust and size checks and reads no private key. It makes no configuration or permission changes. This POST requires the signed-in administrator's normal Origin, request-marker and CSRF checks; general RO/RW API tokens and certificate-only credentials cannot call it. diff --git a/docs/CACHE.md b/docs/CACHE.md index da36783..a6edb07 100644 --- a/docs/CACHE.md +++ b/docs/CACHE.md @@ -9,6 +9,12 @@ The **Static & diagnostics** subtab provides **Ignore request cookies for static **Safety requirement:** use both options only when the complete static response (body **and headers**) is identical for all visitors regardless of Cookie. `Vary: Cookie` is a declaration that content may vary, so overriding it on a genuinely session-dependent file can expose one user's cached variant to another. RustProxy applies this override only to responses with an explicit `Cache-Control: public` directive, positive remaining freshness (without mandatory revalidation) and no `Set-Cookie`, `private`, `no-store` or invalid Vary. A zero-TTL response, including `public` with no configured fallback TTL, retains `Vary: Cookie` even if it can be stored for later revalidation. If the response is not cacheable, `Vary: Cookie` is passed through unchanged. Do not enable this optimization for user-specific downloads, generated PDFs, account JSON, or any path where Flask or another origin changes content according to a session cookie; prefer removing the needless `Vary: Cookie` at the origin where possible. +### CDN security cookies (opt-in VCL template) + +The cache rules template menu now includes **CDN technical cookies** for Cloudflare (`__cf_bm`, `cf_clearance`, `_cfuvid`, `__cfruid`, `__cfseq`) and Akamai (`_abck`, `ak_bmsc`, `bm_sz`, `bm_sv`). It bypasses non-GET/HEAD methods, restricted application paths and `Authorization`. It strips the entire Cookie header **only if all Cookie fields contain allowlisted technical cookies**, and bypasses any request with a remaining Cookie (for example `session`, `wordpress_logged_in_*`, CSRF tokens or other personalized cookies). The source equivalent is [`examples/vcl/cdn-technical-cookies.vcl`](../examples/vcl/cdn-technical-cookies.vcl). Import it only after reviewing warnings; enable the graphical template only on tested public Vhosts. Some challenge cookies (especially `cf_clearance`, `_abck` and `ak_bmsc`) are important to specific origin/CDN configurations; removing them can break a challenge flow. **This is not turned on automatically for existing Vhosts.** + +**Do not extend** `Ignore Vary: Cookie for public static assets` to a general "Ignore Vary" control. `Accept-Encoding`, `Accept-Language`, `Accept`, `Origin`, `User-Agent` and custom response-specific dimensions can change bytes, permissions or CORS headers. Keep the response's actual dimensions and use the existing safe normalization of recognized list fields below, or remove an unnecessary `Vary` at the origin only after proving the response is invariant. A VCL `unset beresp.http.Vary` is *possible*, but it is not the equivalent of a guarded static-file optimization. + ## `Vary` matching (RFC 9111 §4.1) Cached variants use the response's `Vary` field names together with the original request's nominated fields. Reuse requires a match in **every** retained `Vary` dimension; `Vary: *` is never reusable. An absent request field is not equivalent to a present but empty field. @@ -60,7 +66,7 @@ Imported VCL is compiled into the **same rule engine** as the global and per-Vho ### Complete VCL support and `Vary`/header overrides -See [VCL compatibility and header overrides](VCL.md) for a statement-by-statement compatibility matrix, global/per-Vhost priority, stage timing, exact `set`/`unset` support, `Vary` behavior and protected headers. **`beresp.http.Vary` affects cache variants; `resp.http.Vary` only affects the outgoing header.** Unsetting either can break downstream cache correctness. `set/unset beresp.http.Cache-Control` changes cache admission policy, while deliver-stage header edits do not. A deliberately rewritten `private`/`no-store` header or removed `Set-Cookie` no longer protects the representation, so use these actions only for public content. +See the [practical VCL traffic cookbook](VCL_TRAFFIC_COOKBOOK.md) for examples, expected request outcomes and curl tests; [VCL compatibility and header overrides](VCL.md) and the [exhaustive support matrix](VCL_SUPPORT_MATRIX.md) for a statement-by-statement compatibility matrix, global/per-Vhost priority, stage timing, exact `set`/`unset` support, `Vary` behavior and protected headers. **`beresp.http.Vary` affects cache variants; `resp.http.Vary` only affects the outgoing header.** Unsetting either can break downstream cache correctness. `set/unset beresp.http.Cache-Control` changes cache admission policy, while deliver-stage header edits do not. A deliberately rewritten `private`/`no-store` header or removed `Set-Cookie` no longer protects the representation, so use these actions only for public content. ### Explicit Cookie lookup with imported VCL diff --git a/docs/DOCKER_DISCOVERY.md b/docs/DOCKER_DISCOVERY.md index 283322b..ef2c79d 100644 --- a/docs/DOCKER_DISCOVERY.md +++ b/docs/DOCKER_DISCOVERY.md @@ -177,6 +177,19 @@ For each published Docker Vhost, **Live logs** appears directly beside **Open ap These are **HTTP requests processed by RustProxy**, not the application's Docker container stdout/stderr. The viewer uses RustProxy's bounded in-memory live request history; requests appear when completed, not as a container terminal stream. Stored Docker stdout/stderr are not retrieved from the agent. The dialog is administrator-only, and no Docker log-reading endpoint is exposed. +### Cache and Traffic scopes for generated Docker Vhosts + +The **Cache** and **Traffic** pages list **all effectively compiled reverse-proxy vhosts**, including active Docker publications; they do not limit the selector to Vhosts saved in the ordinary-Vhosts configuration. Selectors display **container name — hostname (Docker: agent name)** when observed, and retain the stable generated Vhost ID as the underlying API value and tooltip. A temporarily missing container falls back to its saved hostname; it is not shown as an opaque Docker hash in the normal selector. Cache scope counters, per-service effective cache settings, object lists, purge and invalidation use the same generated ID. The full API responses include `vhosts[].label`, `vhosts[].docker` and `catalog_version`; the last changes when Docker publication inventory changes even if the persisted configuration `revision` does not. Polling clients use `catalog_version` to reload the full scope list. If a label-only publication disappears while selected, the Cache/Traffic panel resets the invalid scope to **All Vhosts** instead of repeatedly polling a now-unknown ID. + +### If a Docker container temporarily disappears + +- **Manually published service**: its assignment (`service_key`, hostname, cache/VCL rules, security options, certificate/listener selection and other per-app settings) is stored in RustProxy configuration; the absence of a Docker inventory entry **does not delete it**. A newly compiled generated Vhost can have no usable backend and return **503** during the gap. Once the same service key and network binding reappear and the agent reports them, the assignment is used again automatically. +- **Publish-from-labels only**: the generated publication is derived from the *current* agent inventory and container labels; when the service disappears from a successful inventory it is absent from the effective configuration. It will be generated again if the service reappears with a matching, valid label configuration and no hostname conflict. There is no saved per-service manual state unless **Apply changes** was used (which converts it to a persisted manual assignment). +- **Agent temporarily unreachable**: the Docker polling layer can retain its last successful inventory; a failed poll is not proof that a container disappeared. Do not use missing status alone to delete an assignment. +- **Identity changes**: changing a Compose/service name, key, or selected publication labels can yield a *different* service key, so automatic recovery of a manually saved mapping is not guaranteed until you select the correct service again. Stable service names and persistent manual assignments are preferable when keeping settings matters. + +These guarantees concern **configuration**, not persistence of in-memory Traffic history, cache HIT counters or old cached objects across unrelated process restarts. Back up RustProxy's persistent configuration separately. + ### Per-vhost traffic statistics Every published vhost on an enabled Docker agent has a **Traffic statistics** disclosure directly below **Configure vhost**. It starts collapsed, uses the same six status/requests/active/errors/latency/traffic-per-second tiles and **Lifetime request rate** chart as an ordinary Vhost, and can be opened individually. The **Expand all statistics / Collapse all statistics** toolbar button toggles every published Docker vhost at once (including rows hidden by search or the local Hide action). The chosen disclosure state survives live list refreshes during the current panel session; it resets on sign-out. diff --git a/docs/FEATURES.md b/docs/FEATURES.md index f250692..52b5094 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -66,13 +66,14 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se - 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. - 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). +- 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. - Purge and ban from the panel, the API or HTTP PURGE/BAN from allowlisted addresses. - Live compression with gzip, Brotli, Zstandard and deflate. - Optional minification of JavaScript, CSS, HTML, SVG and JSON with memory budgets. ![Cache](images/cache.png) +- CDN security-cookie template (Cloudflare and Akamai) that strips whole Cookie headers only when every cookie is allowlisted, with session/Authorization/path bypass; opt-in for verified public content. The [VCL support matrix](VCL_SUPPORT_MATRIX.md) documents supported and deliberately excluded constructs. - **VCL subset only:** graphical rules are the canonical configuration. Partial imports require review; the VCL text shown in the editor is an approximate preview. Cache storage is restricted to HTTP 200 (non-200 responses can still receive deliver-header rules). See [VCL import](VCL.md). ## Monitoring and logs @@ -84,6 +85,7 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se - Live request log in the browser and in the terminal (`--livelogs`). - Stored JSON access logs with search syntax, per-Vhost log files and an error log. - Prometheus exporter with token/CIDR protection, JSON metrics and a compact summary endpoint. +- Cache and Traffic scope selectors include Docker-generated Vhosts with readable container/domain/agent labels and a Docker-inventory fingerprint, even when the saved configuration revision is unchanged. - Lightweight revision-aware polling views for Cache, Traffic and Transform keep the administration panel responsive without repeatedly transferring static configuration. - Grafana dashboard and Nagios checks included. diff --git a/docs/README.md b/docs/README.md index bd2b7d8..8bbb972 100644 --- a/docs/README.md +++ b/docs/README.md @@ -37,6 +37,8 @@ Guides for operating RustProxy: installation, publishing services, security, cer ## Performance and delivery - [Cache](CACHE.md) — scope-aware Cache & VCL help modal from global/Vhost/Docker editors, a compact rule tester, HOT/COLD cache, RFC 9111 `Vary` matching/normalization, safe static-asset cookie exceptions, freshness, `Cache-Status` and invalidation. +- [VCL traffic cookbook](VCL_TRAFFIC_COOKBOOK.md) — 11 ready-to-import examples, public/private HTTP traffic cases, Cookie/`Vary` variants, `curl` verification and failure modes. +- [Complete VCL support matrix](VCL_SUPPORT_MATRIX.md) — line-by-line supported, restricted, graphical-only, intentionally excluded and missing instructions, with test scenarios. - [VCL compatibility and header overrides](VCL.md) — supported VCL import syntax, safe request-header edits, `beresp.uncacheable` precedence, `Vary`, cookies, approval of partial imports and storage limits. - [Response delivery](RESPONSE_DELIVERY.md) — compression, transformations and response headers. diff --git a/docs/VCL.md b/docs/VCL.md index 67afe0f..8983216 100644 --- a/docs/VCL.md +++ b/docs/VCL.md @@ -4,6 +4,8 @@ This guide describes the VCL **subset implemented by RustProxy 0.39.0**, not the 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. +For an expanded **implemented / restricted / graphical-only / intentionally excluded / not implemented** inventory, consult the [complete VCL support matrix](VCL_SUPPORT_MATRIX.md). For practical production scenarios, **11 copyable VCL examples**, HTTP traffic outcomes, a `curl` validation plan and troubleshooting, use the [VCL traffic cookbook](VCL_TRAFFIC_COOKBOOK.md) (also available from the embedded Reader). It names each supported hook, variable and return action and the deliberate HTTP/security boundaries. + ## Where to import, rule order and activation - **Settings -> Cache -> Rules**: global cache rules, optionally targeted to particular vhosts. diff --git a/docs/VCL_SUPPORT_MATRIX.md b/docs/VCL_SUPPORT_MATRIX.md new file mode 100644 index 0000000..4e1aa43 --- /dev/null +++ b/docs/VCL_SUPPORT_MATRIX.md @@ -0,0 +1,212 @@ +# VCL capability matrix: implemented, limited and unsupported + +**Applies to the RustProxy 0.39.0 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 + +The companion [VCL traffic cookbook](VCL_TRAFFIC_COOKBOOK.md) contains **11 complete VCL examples** (including an intentionally restricted importer example and a high-risk advanced example), an HTTP request/response behavior matrix, `curl` checks, expected `PASS`/`MISS`/`HIT` behavior and troubleshooting. The standalone source files are in [`examples/vcl/`](../examples/vcl/). They cover public catalogs, JSON APIs, private routes, CDN cookies, public static files, multilingual responses, A/B variants, SSE/webhooks/errors, safe header changes, query normalization and highly restricted Set-Cookie removal. Each example states its origin/privacy contract and importer limitations. + +| Goal | Available through imported VCL | Native GUI/API required or not supported | +|---|---|---| +| Bypass admin/session/credentialed requests | `vcl_recv` with `return(pass)` | Authentication and access policy remain native | +| Cache public GET JSON/catalog | `return(hash)` plus conditional `beresp.ttl` | Global/Vhost cache must already be enabled; only 200 can be stored | +| Strip CDN technical cookies | Entire Cookie header removal after an exact allowlist | Removing one cookie by name from a mixed header: graphical action only | +| Safely ignore `Vary: Cookie` on public static | VCL can remove request Cookie, but **not** safely override `Vary` | Narrow native static-asset settings, not a general Ignore Vary feature | +| Multilingual/CORS/encoded responses | Preserve origin `Vary`; optional internal `vcl_hash` dimension | Origin must emit the complete downstream `Vary` dimensions | +| Webhooks, SSE, transient errors | PASS, `beresp.uncacheable=true` | Retries, stale-if-error, streaming and backend failures are native behaviors | +| Query tracking normalization | Recognized `regsuball` pattern, **with warning** | Prefer graphical Strip query params; arbitrary regex rewriting unsupported | +| Negative cache, full VMOD, `vcl_hit`/`vcl_purge` | **No** | Not implemented as VCL in this release | + +## Read this before deploying VCL + +1. RustProxy **does not run a VCL interpreter**. `POST /api/cache/rules/import-vcl` parses a limited source document and returns **graphical rules plus warnings**. A rule runs only after it is accepted and the configuration is saved. +2. A syntactically accepted VCL instruction can have **different runtime behavior** from Varnish. In particular, `return(hash)` does not disable RustProxy's authorization and privacy safeguards, and `return(hit_for_pass)` does not create a hit-for-pass object. +3. **Warnings are significant.** The editor will not add a partial import automatically; choose **Add partial import (reviewed)** only if you have checked every skipped instruction and the resulting graph. An import that fails with a parser error creates no rule set. +4. VCL support is **limited to reverse-proxy HTTP Vhosts**. It does not provide Varnish behavior for the built-in static Web Server, PHP or the administration API. The same rule editor is available for manually configured and Docker-generated reverse-proxy Vhosts. +5. Cache rules do not enable caching by themselves. Both global and effective per-Vhost cache policy must permit it. Request rewrites can still be relevant on a cache-disabled reverse-proxy route. + +## Status terminology + +| Status | Exact interpretation | +|---|---| +| **Supported** | Converted into a validated RustProxy cache rule; the documented effect is implemented. | +| **Restricted** | Converted only for the listed syntax, stage or constant form; alternatives warn and are skipped. | +| **Graphical only** | RustProxy has an equivalent or related rule editor action, but VCL source does **not** import it exactly. | +| **Unsupported (intentional boundary)** | Not part of the importer/runtime by design of a graph-based, safety-constrained proxy, or intentionally not implemented as Varnish semantics. Do not assume it will be added. | +| **Not implemented** | No corresponding VCL conversion/runtime functionality exists in this version; roadmap and future support are unspecified. | + +## 1. Hooks and program structure + +| Varnish construct | Status | What RustProxy actually does | +|---|---|---| +| `sub vcl_recv { ... }` | Supported subset | Request-stage rules, in statement order; may bypass cache, request lookup, strip cookies or perform safe rewrites. | +| `sub vcl_hash { ... }` | Restricted | Becomes a separate request hash stage. Runs after `vcl_recv` with a hash/lookup decision, but not after `return(pass)`. | +| `sub vcl_backend_response { ... }` | Supported subset | Response-stage changes run against the origin response before shared-cache admission. | +| `sub vcl_fetch { ... }` | Supported alias | Maps to response-stage behavior, not a historical Varnish backend state machine. | +| `sub vcl_deliver { ... }` | Supported subset | Changes outgoing response headers. Does not alter stored variants/TTL. | +| Other hooks: `vcl_init`, `vcl_fini`, `vcl_hit`, `vcl_miss`, `vcl_pass`, `vcl_pipe`, `vcl_synth`, `vcl_backend_fetch`, `vcl_backend_error`, `vcl_purge` | Not implemented | Unrecognized subroutine names generate an import warning; their body is not executed. | +| `sub my_helper { ... }` and `call my_helper;` | Unsupported (intentional boundary) | No custom executable subroutines, VCL callbacks or extension language. | +| Top-level `vcl`, `import`, `include` directives | Restricted | Lexer accepts them and skips to the terminating semicolon. **It does not load a module or another file.** | +| Top-level `backend`, `acl`, `probe` definitions | Restricted | Blocks are skipped with warnings. Use RustProxy backend, health-check and ACL configuration. | +| Arbitrary top-level statements | Not implemented | The importer reports an error instead of executing unknown declarations. | +| `#`, `//`, `/* ... */` comments | Supported | Comments discarded; unclosed block comment is a parsing error. | +| Short `"..."` and VCL long `{ " ... " }` string forms | Restricted | String tokenization is supported. Only specific instructions accept a string value; long strings do not make arbitrary VCL code executable. | + +## 2. Branches, variables and comparisons + +| Syntax or variable | Status | Rules and caveats | +|---|---|---| +| `if (...) { ... }`, `elsif (...)`, `else`, nested `if` | Supported | Branch guards and previous-branch exclusions are converted; not a runtime scripting language. | +| `&&`, `||`, `!`, parentheses | Supported with limits | Conditions expand to sets of graphical rule guards. Very complex expressions may exceed rule limits and are skipped with warnings. | +| `req.url`, `bereq.url` | Supported for comparisons | Match path **and query** together. These aliases do not permit arbitrary URL rewrite. | +| `req.method`, `req.request`, `bereq.method` | Supported | Comparisons to constant values. | +| `req.http.
`, `bereq.http.
` | Supported | Header existence, equality and regex comparison; `req.http.Host` is mapped to normalized host scope. | +| `beresp.status`, `resp.status`, `obj.status` | Supported in response/deliver | Numeric code comparisons: `==`, `!=`, `<`, `<=`, `>`, `>=`. They compile to one status or a bounded range. | +| `beresp.http.
`, `resp.http.
`, `obj.http.
` | Supported in response/deliver | Response-header existence, equality and regex matching. Content-Type has a dedicated canonicalized condition. | +| `==`, `!=`, `~`, `!~` | Supported | For appropriate recognized request/response fields; regex is Rust regex matching rather than arbitrary Varnish/PCRE execution. | +| `client.ip ~ my_acl` | Not implemented for VCL | The importer warns. The **graphical** editor can match client IP/CIDR (see below). | +| `std.*`, `server.*`, `req.backend_hint`, `req.url.path`, `req.url.qs`, `bereq.retries`, `beresp.backend.*`, `obj.hits`, `now`, TLS-specific VCL vars and VMOD variables | Not implemented | Unsupported variable/condition warning; they are not silently assigned live values. | +| Arithmetic, regex capture substitution in conditions, concatenation, functions, assignments within `if`, lists/dictionaries/objects | Not implemented | Only supported simple atomic comparisons and boolean operations are converted. | +| Bare `req.http.Cookie`, `req.http.Authorization` | Supported | Tests header presence. A nonempty header name variable is not a test of cookie *content*. | + +### Header-field nuance + +`req.http.Cookie ~ "^(?:__cf_bm|...)=[^;]*$"` is safe as an **entire-header** technical-cookie allowlist only if every physical `Cookie` header field is examined. The rule matcher in this patched source joins multiple Cookie fields with `; ` for header-condition evaluation, so a second field containing `session=...` defeats the anchored allowlist. An invalid UTF-8 Cookie value is treated as *present*, preventing the subsequent `if (req.http.Cookie) { return(pass); }` from accidentally treating it as absent. + +Do **not** use an unanchored regex such as `req.http.Cookie ~ "__cf_bm"` with `unset req.http.Cookie;`: that would discard a session cookie merely because a technical cookie was also present. + +## 3. Request-stage statements (`vcl_recv`) + +| Exact statement form | Status | Rule effect and restrictions | +|---|---|---| +| `return(pass);` | Supported | Cache bypass; terminates applicable request-stage rules and skips `vcl_hash`. | +| `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 | Removes **every** Cookie value before subsequent rules, origin forwarding and cache key generation. No per-name deletion in imported VCL. | +| `set req.http.X-Name = "literal";` | Supported with protected-name list | Changes a safe request header to a constant string. Origin sees the change. Dynamic/compound expressions are not recognized. | +| `unset req.http.X-Name;` | Supported with protected-name list | Removes all values of an allowed request header. | +| `set req.url = regsuball(req.url, "...", "\\1");` | Restricted | Only a pattern that matches a captured query separator plus a known parameter-name list is converted to `strip_query`; importer warns about separator/empty-value differences. See [VCL details](VCL.md#request-header-changes-scope-and-safeguards). | +| `set req.http.Cookie = regsuball(...)`, single-cookie deletion, `regsub()` on cookies | Not implemented | Use graphical **Strip cookies / Keep these cookies** instead. An imported VCL expression will **not** safely delete one cookie from a list. | +| `set req.backend_hint`, `set req.method`, `set req.hash`, `set req.http.Authorization` | Unsupported (intentional boundary) | Request origin selection, security identity, method, HTTP framing and credentials remain controlled by RustProxy's normal Vhost/route/auth machinery. | +| `return(pipe)`, `return(purge)`, `return(synth(...))`, `return(restart)` | Not implemented | Warnings, not equivalents to `pass` or other rules. | +| `return(deliver)` in `vcl_recv` | Not implemented | This is not a supported return target in the request stage. | + +**Protected general request-header edits** include `Authorization`, `Cookie` (except dedicated whole-header removal), `Cache-Control`, `Pragma`, `Host`, `Range`, `If-*`, `Forwarded`, `Via`, `X-Forwarded-*`, `X-Real-IP`, `X-Client-IP`, `True-Client-IP`, `CF-Connecting-IP`, `Proxy-*`, `Sec-*`, `X-RustProxy-*`, `Content-Type`, `Expect` and the framing/proxy headers in section 6. Such edits are rejected on rule validation, including in imported VCL; valid neighboring actions are still imported. + +## 4. Hash-stage statements (`vcl_hash`) + +| Exact statement | Status | Effect | +|---|---|---| +| `hash_data(req.url);` | Supported no-op | URL including query already participates in RustProxy's base key. | +| `hash_data(req.http.Host);` | Supported no-op | Normalized request authority and vhost isolation already participate in the cache key. | +| `hash_data(req.http.X-Device);` | Supported | Adds a request-header value to the internal variant key; `Vary: X-Device` is **not** automatically emitted. | +| `hash_data(regsub(req.http.Cookie, ...))` | Not implemented | The graphical editor has a separate **Hash cookie** action; it is not a faithful VCL expression importer. | +| `hash_data(client.ip)`, arithmetic/concatenation, VMOD expressions or multiple arguments | Not implemented | Generates warning. | +| `hash_data(...)` inside `vcl_recv` | Not implemented | Warns: this instruction is only accepted in `vcl_hash`. | + +## 5. Backend-response stage (`vcl_backend_response`, `vcl_fetch`) + +| Statement | Status | Cache/storage effect | +|---|---|---| +| `set beresp.ttl = 30s;` | Supported | Freshness override in seconds, bounded by configured limits; recognized units `ms`, `s`, `m`, `h`, `d`, `w`, `y`, plus bare seconds. Rounded to full seconds. Does **not** rewrite `Cache-Control` for browsers. | +| `set beresp.grace = 5m;` | Supported | Grace override, within RustProxy limits; not Varnish's complete grace/keep lifecycle. | +| `set beresp.uncacheable = true;` | Supported | Prohibits shared storage for the matching response. | +| `set beresp.uncacheable = false;` | Supported, RustProxy-specific | Reverses **an earlier cache-rule-induced** no-store action. Does not nullify origin `private`, `no-store`, `Set-Cookie` or another admission barrier. | +| `set beresp.http.X-Name = "literal";` | Supported with protected-name list | Overwrites the origin header **before** storage planning and before delivery. May affect admission if the header is `Cache-Control` or `Vary`. | +| `unset beresp.http.X-Name;` | Supported with protected-name list | Removes a header before storage; deleting `Cache-Control: private/no-store` intentionally discards origin policy and can expose sensitive content. | +| `unset beresp.http.Set-Cookie;` | Supported, dedicated dangerous exception | Removes upstream `Set-Cookie` before storage policy. Do not use for session-dependent responses. | +| `return(pass);`, `return(hit_for_pass);`, `return(uncacheable);` | Restricted conversion | Prevents storage; **no Varnish hit-for-pass object** is created. | +| `return(deliver);` | Supported | Stops later rules in the backend-response hook. | +| `beresp.keep`, `beresp.do_stream`, `beresp.do_gzip`, `beresp.storage`, `beresp.backend`, `beresp.status`, `beresp.reason`, `beresp.http.Set-Cookie = ...` | Not implemented as VCL assignments | No equivalent imported instruction. HTTP storage/encoding and upstream selection have separate RustProxy controls. | +| `return(retry)`, `return(abandon)`, `return(error)`, `return(synth)` | Not implemented | Unsupported return warning. | + +The shared cache stores **HTTP status 200** responses only in this release. A positive TTL for `404`, `301`, `302` or `500` does **not** enable negative/redirect/error-response caching. Requests with `Authorization`, no-store signals, disallowed methods, access restrictions or invalid response headers are not made cacheable simply by a VCL lookup decision. + +## 6. Deliver-stage statements and header protection + +| Statement | Status | Effect | +|---|---|---| +| `set resp.http.X-Name = "literal";` | Supported with protected-name list | Replaces outgoing header on HIT, MISS or BYPASS. Does not alter the stored metadata or variant. | +| `unset resp.http.X-Name;` | Supported with protected-name list | Removes outgoing header only. | +| `return(deliver);` | Supported | Stops the remaining deliver-stage rule chain. | +| `set resp.status`, `set resp.reason`, dynamic `resp.http.* = req.http.*`, `regsub` on resp headers | Not implemented | No response-body/status rewriting or dynamic expressions through imported VCL. | +| `return(synth)`, `return(restart)` | Not implemented | Not equivalent to sending a synthetic response or reprocessing the request. | + +**Headers protected from general backend and deliver edits:** `Connection`, `Content-Length`, `Content-Encoding`, `Content-Range`, `Date`, `Keep-Alive`, `Proxy-Authenticate`, `Proxy-Authorization`, `Set-Cookie`, `TE`, `Trailer`, `Transfer-Encoding`, `Upgrade`, `Host`, `Alt-Svc`. The **only** exception is the dedicated `unset beresp.http.Set-Cookie` action. Other subsystems can regenerate or normalize headers after rules have run. Header names compare case-insensitively; `set` replaces the entire repeated field and `unset` removes all occurrences. `set ... = ""` is not the same as `unset`. + +### `Vary` is supported but phase-sensitive + +| Operation | Internal cache variants | Delivered response | Recommendation | +|---|---|---|---| +| Origin `Vary: Accept-Encoding, Accept-Language` | Both dimensions retained | Passed downstream | Safe default. | +| `set beresp.http.Vary = "Accept-Language";` | **Replaces** all origin dimensions before variant planning | Sends new field unless overridden later | Only if origin truly varies solely by language. | +| `unset beresp.http.Vary;` | Removes variation requirements **before** admission | Usually removed downstream | Unsafe for personalized/encoded variants. | +| `set resp.http.Vary = "Accept-Language";` | **No change** to stored variants | Overrides outgoing field only | Avoid mismatch with the actual storage key. | +| `unset resp.http.Vary;` | **No change** to stored variants | Removes outgoing field | Can cause downstream CDN/browser variant leakage. | +| Global `static_ignore_vary_cookie` on a public static extension | May remove **Cookie only**, after public/fresh/no-Set-Cookie/privacy checks | Qualifying response no longer varies by Cookie | Do not extend to arbitrary Vary dimensions. | + +`Vary: *` is not reusable. All other retained dimensions must match, including the distinction between absent and present-but-empty headers. RustProxy safely normalizes selected list headers (`Accept-Language`, `Accept-Encoding`, `Accept-Charset`, `Accept`), preserving required semantics; it does not treat opaque `User-Agent`, `Origin`, `Cookie` or custom headers as interchangeable. See [RFC 9111 matching](CACHE.md#vary-matching-rfc-9111-41). + +**Do not add a global “Ignore Vary” switch.** It risks wrong content under different encodings, languages, CORS origins, user-agent-specific responses or authenticated contexts. The existing narrowly scoped `Ignore Vary: Cookie for public static assets` option should remain restricted; fix unnecessary `Vary` at the origin when possible. + +## 7. Graphical actions without a faithful imported VCL equivalent + +These capabilities exist in RustProxy's JSON/graphical cache rules but should **not** be inferred to work by pasting arbitrary VCL syntax: + +| Graphical rule/setting | VCL import limitation | +|---|---| +| Client IP/CIDR condition | `client.ip ~ acl` not imported. | +| Path, extension and query-param conditions | Graphical matching is supported; some exported VCL examples are approximations, not guaranteed round-trip. | +| Match a cookie by name/value | `req.http.Cookie` regex supports header testing, but the graphical dedicated cookie condition is not a generic VCL parser feature. | +| **Strip cookies, keep** selected names | VCL importer accepts only `unset req.http.Cookie` for whole-header removal. | +| **Strip query params** or **keep only** listed params | Only a specific tracking-parameter `regsuball(req.url,...)` form is imported, always with a warning. | +| **Hash cookie** by name | Graphical-only; `hash_data(regsub(...))` is not imported. | +| **Default header** (set if absent) | Available graphically; VCL `if (!resp.http.X) set ...` may import through basic header-existence guards, but exact graphical ownership/precedence is not guaranteed as a round trip. | +| **Ignore backend Cache-Control** | Graphical storage-policy override; not the same as a plain VCL `unset beresp.http.Cache-Control`. | +| Scoped global rules, per-Vhost rules, ignore global rules | Stored in RustProxy config, not in VCL source text; imported VCL uses the editor's scope. | +| Global/per-vhost static Cookie/`Vary` options | Configuration switches, not VCL statements. | + +## 8. Intentionally excluded and otherwise missing Varnish functionality + +| Feature | Classification | Rationale / alternative | +|---|---|---| +| Full VCL execution engine and arbitrary VMODs/C modules | **Intentional architectural boundary** | Only validated JSON cache rules execute. Configure supported proxy features through their native Settings/Vhost editor. | +| Mutating authentication, identity, transport framing and protected request headers through cache VCL | **Intentional safety boundary** | Prevents bypassing access control, spoofing, cache-policy restrictions or invalid HTTP framing. | +| Rewriting raw `Cookie` by broad regex or partially deleting cookies through imported VCL | **Intentional narrow importer** | No unsafe best-effort translation; use full-header `unset` only after an anchored allowlist, or use the graphical cookie-allowlist action for a reviewed policy. | +| Varnish hit-for-pass / hit-for-miss objects and `beresp.keep` | **Intentionally not imported** | RustProxy has its own miss collapsing, revalidation and temporary uncacheable-fill handling; these are not Varnish object types. | +| Custom backend/ACL/probe definitions in imported VCL | **Intentional configuration boundary** | Configure those as RustProxy backends/ACL profiles/health checks. The source blocks are explicitly warned/skipped. | +| Unsafe or unsupported `return(pipe/restart/purge/synth)` | **Not implemented by VCL importer** | HTTP tunneling, administrative purge, synthetic responses and routing use separate native mechanisms, where available. | +| Storing 3xx, 4xx and 5xx as shared cache objects | **Not implemented** | Status 200 only; no negative-cache guarantee. | +| Varnish ESI, VCL body manipulation, edge includes, custom streaming hooks | **Not implemented** | No VCL capability to parse/modify response bodies. Use separate native transforms only where explicitly supported. | +| Varnish backend retries, directors, storage stevedores, clustering/sharding via VCL | **Not implemented as VCL** | RustProxy has independent load balancing/upstream pools and HOT/COLD storage. | +| Dynamic expressions, direct filesystem calls, networking from VCL, custom system functions | **Not implemented by design of the rule model** | No executable user-defined code or side effects at the VCL layer. | +| Exact VCL export/import round-trip | **Not supported** | Export is an explanatory preview. Back up canonical JSON/configuration instead. | + +The labels above distinguish explicit product limits from missing work; **not implemented** does *not* assert that a future release will implement a feature. + +## 9. Limits, validation and test plan + +| Limit/condition | Implemented boundary | +|---|---| +| VCL source length | **256 KiB** maximum. | +| Rules | **128** compiled rules per applicable rule list. | +| Rule conditions/actions | Up to **16** conditions and **16** actions per rule. Long supported action sequences are split as needed; branch expansion can hit limits earlier. | +| Rule values | Up to **64** values per condition, **512 bytes** each. | +| Regex program budget | Up to **512 bytes per condition value**; compiled regex builder has **1 MiB** NFA/DFA budgets (`64 KiB × 16`). Invalid/overcomplex expressions are rejected. | +| TTL/grace | Whole-second setting subject to maximum **365 days** and effective cache settings. | +| Origin status | **200** required for shared storage. Other responses can still receive appropriate header edits. | +| Import warnings | Need explicit review and acceptance in the UI; never treat warnings as a successful, equivalent conversion. | + +### Regression checklist for a deployment + +1. Import the candidate VCL and require **no unexpected warnings**. Inspect the generated rules in the appropriate global/Vhost/Docker scope. +2. Test GET/HEAD with no Cookie, only technical CDN cookies, mixed technical + `session`, multiple physical Cookie lines, and `Authorization`. +3. Test protected paths, POST/PUT, invalid Vary, `Vary: *`, `Set-Cookie`, `Cache-Control: private/no-store/no-cache` and responses other than 200. +4. Verify both **cached** and **delivered** `Vary` behavior for `Accept-Encoding`, `Accept-Language`, `Origin` and any origin-defined custom dimension. +5. On a real, authorized test origin send two identical requests to compare MISS/HIT and a changed Vary dimension to ensure distinct variants. The rule tester **cannot replace** this test. +6. For Docker services, repeat after a container disappears and returns, checking the same saved Vhost assignment and the Cache/Traffic scope labels. + +### Included opt-in CDN cookie policy + +The source file [`examples/vcl/cdn-technical-cookies.vcl`](../examples/vcl/cdn-technical-cookies.vcl) and the **CDN technical cookies** cache-rule template provide the same basic safe policy: bypass unsafe methods, sensitive paths and Authorization; strip Cookie only when **all cookies** are in a known allowlist; otherwise bypass. The list includes Cloudflare (`__cf_bm`, `cf_clearance`, `_cfuvid`, `__cfruid`, `__cfseq`) and Akamai (`_abck`, `ak_bmsc`, `bm_sz`, `bm_sv`). Review the list for your origin and CDN challenge flow: some technical/security cookies are needed by the origin and **must not** be stripped in those deployments. This policy is **opt-in**; it does not change the default behavior of existing Vhosts. + +The source contains a Rust regression test (`src/cache/rules_tests.rs`) exercising import and per-request evaluation, plus a Node frontend template contract test (`tests/js/cdn-cookie-template.cjs`). A JavaScript-only test is **not** evidence that the Rust executable compiled or that a real proxy backend was tested. diff --git a/docs/VCL_TRAFFIC_COOKBOOK.md b/docs/VCL_TRAFFIC_COOKBOOK.md new file mode 100644 index 0000000..c60845c --- /dev/null +++ b/docs/VCL_TRAFFIC_COOKBOOK.md @@ -0,0 +1,587 @@ +# VCL cookbook: concrete use cases and HTTP traffic scenarios + +**Target:** RustProxy **0.39.0** 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**. + +## A. How to use the recipes + +1. Pick a **reverse-proxy HTTP Vhost** (ordinary Vhost or Docker vhost). Open its **Cache rules** editor. For site-wide rules use **Settings → Cache → Rules**, but prefer a local scope for policies about one application. +2. Enable the global cache and, where intended, the effective per-Vhost cache policy. Check fallback TTL, Varnish-compatible vs strict RFC mode, static-cookie settings, origin response headers and maximum object size. A VCL `return(hash)` **cannot** enable a disabled cache. +3. Import the VCL file in the **VCL import** dialog. RustProxy translates it to graphical rules. It does **not** execute a VCL interpreter. Review every generated rule and warning. The importer pauses on warnings; **Add partial import (reviewed)** is a separate explicit step, and the configuration still needs to be saved. +4. Use **Test a request** with method, URL, request headers and simulated backend status/headers; confirm which rule matched and whether a terminal `return(pass)` was produced. Test both **global** and **local** rule precedence. A rule preview is **not** a live cache HIT test. +5. Run two real identical GET requests through the proxy. Inspect `Cache-Status` (RFC 9211), optionally `X-Cache`/`X-Cache-Reason`, and the delivered `Vary`/`Cache-Control`. Warm a disposable test URL; remove cached objects after changing privacy rules. + +### Terminology in this guide + +| Label | Meaning | +|---|---| +| **PASS / BYPASS** | Request uses the backend without shared-cache lookup (or fails normal eligibility checks). A response-stage no-store rule can also prevent a MISS from being stored. | +| **MISS** | Eligible lookup found no reusable fresh object; origin response is fetched. A MISS does **not** prove that the response was stored. | +| **HIT** | An eligible subsequent request uses a fresh matching object, if admission, freshness, storage, and `Vary` conditions all succeeded. | +| **STALE / REVALIDATED** | RustProxy's independent grace/stale/conditional machinery may respond without a fresh HIT. Availability and labeling depend on configuration. | +| **Origin contract** | Conditions the application must guarantee (public identical body/headers, required `Vary`, validators, no session dependence). VCL does not verify that promise. | + +**Always preserve:** authentication and authorization, session boundaries, private/no-store responses, `Set-Cookie`, client request cache-control and true representation dimensions. If a backend decides which user sees which data, use **PASS** instead of trying to cache it by Cookie or an untrusted synthetic header. + +## B. Choose an appropriate policy + +| Traffic/application | Recommended recipe or native setting | What it can do | What it does **not** do | +|---|---|---|---| +| CMS articles or a public catalog | [Public catalog](#2-public-catalog-with-explicit-short-ttl) | Cache genuinely shared 200 GETs, set TTL/grace | Force storage of `private`, `Set-Cookie` or 404 | +| Public JSON endpoint for prices/stock | [Public JSON API](#3-public-get-json-api) | Short-lived shared cache | Cache credentialed/private API responses | +| Admin, login, checkout, user dashboard | [Private routes](#1-exclude-private-routes-and-unsafe-methods) | Bypass shared cache | Replace ACL, OIDC, Basic Auth, app permissions | +| Cloudflare/Akamai technical cookies | [CDN cookie allowlist](#4-cdn-technical-cookies-without-dropping-sessions) | Strip an **entire** allowlisted Cookie header | Partially delete one Cookie from a mixed list | +| Public CSS, JS, fonts, images | [Static assets](#5-static-assets-and-vary-cookie) + native static settings | Strip request Cookie if proven safe; optional **conditional** `Vary: Cookie` treatment | Override any other arbitrary `Vary` dimension | +| Multilingual catalog | [Language variants](#6-language-specific-representations) | Preserve origin `Vary: Accept-Language` and separate variants | Automatically translate or change language | +| Low-cardinality public A/B content | [A/B variants](#7-low-cardinality-public-ab-variants) | Add internal header dimension via `vcl_hash` | Write `Vary` for downstream caches | +| Server-sent events, webhook traffic, transient errors | [No-store](#8-streaming-webhooks-and-origin-errors) | PASS streaming paths and prevent storage | Retry origins, stream hooks, generate synthetic errors | +| Remove internal diagnostics from the response | [Header hygiene](#9-safe-request-and-delivery-header-edits) | Change permitted request/delivery headers | Modify body, protected headers or cache admission at delivery | +| 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.0 | 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 + +All full examples below use only source syntax understood by the RustProxy importer, **except recipe 10, whose restricted conversion deliberately emits a warning**. The advanced Set-Cookie example is syntactically supported but dangerous without a verified public origin contract. + +### 1. Exclude private routes and unsafe methods + +**Goal:** Keep administration, accounts, cart, checkout, webhooks, cookies and credentials away from shared cache. + +**Expected traffic:** `POST /webhook` and `GET /account/orders` → PASS; `GET /catalog` with a session Cookie → PASS. + +**Prerequisites:** Apply to relevant HTTP reverse-proxy Vhosts; configure app authentication separately. + +**Caveat:** There is no final `return(hash)`; other eligible routes retain normal RustProxy policy and any other saved rules. + +Source: [`examples/vcl/private-routes-bypass.vcl`](../examples/vcl/private-routes-bypass.vcl). + +```vcl +// Defensive exclusions for an existing HTTP reverse-proxy vhost. +// Does not opt in to caching for other routes. +sub vcl_recv { + if (req.method != "GET" && req.method != "HEAD") { + return(pass); + } + if (req.url ~ "^/(admin|api/private|account|auth|login|logout|checkout|cart|dashboard|webhook)(/|[?]|$)") { + return(pass); + } + if (req.http.Authorization) { + return(pass); + } + if (req.http.Cookie) { + return(pass); + } +} +``` + +### 2. Public catalog with explicit short TTL + +**Goal:** Allow only anonymous GET/HEAD for `/catalog`, with 120-second origin-response freshness and 20-second grace. + +**Expected traffic:** First eligible GET is typically MISS; a repeated fresh identical GET may be HIT. `POST /catalog` and `GET /catalog` with a Cookie → PASS. + +**Prerequisites:** The origin returns an actually public representation with `Cache-Control: public, max-age=120`, HTTP 200, no `Set-Cookie` and correct `Vary`. + +**Caveat:** The TTL rule may override a shorter origin TTL. Avoid deploying against pages with fluctuating stock, sessions, authorization or incorrectly marked public content. + +Source: [`examples/vcl/public-catalog.vcl`](../examples/vcl/public-catalog.vcl). + +```vcl +// Cache only demonstrably public catalog pages. The origin must supply +// Cache-Control: public, max-age=120 and must not vary by user/session. +sub vcl_recv { + if (req.method != "GET" && req.method != "HEAD") { + return(pass); + } + if (req.http.Authorization || req.http.Cookie) { + return(pass); + } + if (req.url ~ "^/catalog(/|[?]|$)") { + return(hash); + } + return(pass); +} + +sub vcl_backend_response { + if (bereq.url ~ "^/catalog(/|[?]|$)" && beresp.status == 200 && beresp.http.Cache-Control ~ "(^|,) *public(,|$)") { + set beresp.ttl = 120s; + set beresp.grace = 20s; + } +} +``` + +### 3. Public GET JSON API + +**Goal:** Cache a controlled, anonymous JSON API for 15 seconds, with 5-second grace. + +**Expected traffic:** `GET /api/public/list` can MISS→HIT; `GET /api/private/me`, `POST /api/public/list` or a request with `Authorization` bypasses. + +**Prerequisites:** Origin returns JSON, 200 and explicit `Cache-Control: public`, with no session dependence; all important `Vary` fields remain intact. + +**Caveat:** A response such as `private`, `no-store`, `Set-Cookie` or invalid `Vary` remains ineligible. Do not treat public API as all API endpoints. + +Source: [`examples/vcl/public-json-api.vcl`](../examples/vcl/public-json-api.vcl). + +```vcl +// GET-only shared caching for /api/public. Other API routes bypass. +// The origin must mark genuinely public JSON responses as such. +sub vcl_recv { + if (req.method != "GET" && req.method != "HEAD") { + return(pass); + } + if (req.http.Authorization || req.http.Cookie) { + return(pass); + } + if (req.url ~ "^/api/public(/|[?]|$)") { + return(hash); + } + return(pass); +} + +sub vcl_backend_response { + if (bereq.url ~ "^/api/public(/|[?]|$)" && beresp.status == 200 && beresp.http.Content-Type ~ "^application/json" && beresp.http.Cache-Control ~ "(^|,) *public(,|$)") { + set beresp.ttl = 15s; + set beresp.grace = 5s; + } +} +``` + +### 4. CDN technical cookies without dropping sessions + +**Goal:** Ignore only known technical Cloudflare/Akamai cookies while keeping real sessions out of shared cache. + +**Expected traffic:** `Cookie: __cf_bm=a; _cfuvid=b` → remove Cookie, eligible for lookup; `Cookie: __cf_bm=a; session=s` → PASS. + +**Prerequisites:** Review the allowlisted names with your CDN provider and origin. Verify the origin does not need these cookie values for bot/challenge flow. + +**Caveat:** Whole-header anchored matching is intentional. Do not replace it with an unanchored test for `__cf_bm`. Do not add load-balancer affinity, challenge, or application cookies automatically. + +Source: [`examples/vcl/cdn-technical-cookies.vcl`](../examples/vcl/cdn-technical-cookies.vcl). + +```vcl +// Optional template: only shared/public content independent of these cookies. +// Cloudflare: __cf_bm, cf_clearance, _cfuvid, __cfruid, __cfseq +// Akamai: _abck, ak_bmsc, bm_sz, bm_sv +// Security cookies can be needed for bot challenges; review before enabling. +sub vcl_recv { + if (req.method != "GET" && req.method != "HEAD") { + return(pass); + } + if (req.url ~ "^/(admin|api|auth|login|logout|panel|konto|dashboard)(/|[?]|$)") { + return(pass); + } + if (req.http.Authorization) { + return(pass); + } + // Match the complete Cookie header, not one cookie within it. + 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; + } + if (req.http.Cookie) { + return(pass); + } + return(hash); +} +``` + +### 5. Static assets and Vary: Cookie + +**Goal:** Remove all Cookie headers **only** from independently verified public `/assets` images/fonts/scripts/styles. + +**Expected traffic:** `GET /assets/site.css` with Cookie may use a shared key; other paths remain subject to their original cache policy. + +**Prerequisites:** Every byte and relevant response header is the same for guests and logged-in users; origin produces public 200 and valid freshness. + +**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. + +Source: [`examples/vcl/static-assets-public.vcl`](../examples/vcl/static-assets-public.vcl). + +```vcl +// Optional: remove ALL request cookies for public, identity-independent +// assets under /assets. Origin must never use a session for these assets. +// Vary: Cookie removal is NOT accomplished by this VCL. Configure the +// native "Ignore Vary: Cookie for public static assets" setting separately. +sub vcl_recv { + if (req.method != "GET" && req.method != "HEAD") { + return(pass); + } + if (req.url ~ "^/assets/.*[.](css|js|png|jpg|jpeg|svg|woff2)([?]|$)") { + if (req.http.Authorization) { + return(pass); + } + unset req.http.Cookie; + return(hash); + } +} +``` + +### 6. Language-specific representations + +**Goal:** Preserve the origin-defined language dimension rather than flattening it with a header rewrite. + +**Expected traffic:** `Accept-Language: pl` and `Accept-Language: en` are distinct variants **if the origin sends `Vary: Accept-Language`**. + +**Prerequisites:** The backend really changes representations by language and sends `Vary: Accept-Language` **plus** any other dimensions (e.g. `Accept-Encoding`). + +**Caveat:** Do not set `beresp.http.Vary = "Accept-Language"` if the origin also varies by compression, Origin, device or another header. + +Source: [`examples/vcl/language-catalog.vcl`](../examples/vcl/language-catalog.vcl). + +```vcl +// Origin responsibility: return Vary: Accept-Language (plus any other real +// dimensions such as Accept-Encoding), public freshness and no Set-Cookie. +// Do not replace the origin Vary list with a single dimension. +sub vcl_recv { + if (req.method != "GET" && req.method != "HEAD") { + return(pass); + } + if (req.http.Authorization || req.http.Cookie) { + return(pass); + } + if (req.url ~ "^/translations(/|[?]|$)") { + return(hash); + } + return(pass); +} + +sub vcl_backend_response { + if (bereq.url ~ "^/translations(/|[?]|$)" && beresp.status == 200 && beresp.http.Cache-Control ~ "(^|,) *public(,|$)") { + set beresp.ttl = 60s; + } +} +``` + +### 7. Low-cardinality public A/B variants + +**Goal:** Demonstrate `vcl_hash` with one explicit request-header value for public A/B experiment content. + +**Expected traffic:** `X-Experiment: A` and `X-Experiment: B` should partition the internal key; any other value bypasses. + +**Prerequisites:** Clients send the header themselves (also to downstream caches); the origin returns `Vary: X-Experiment` and does not personalize by user. + +**Caveat:** `hash_data` does not send `Vary` to clients; missing Vary can leak a variant through another cache. Keep a strict finite value list to avoid unbounded cardinality. + +Source: [`examples/vcl/experiment-variants.vcl`](../examples/vcl/experiment-variants.vcl). + +```vcl +// Controlled, PUBLIC A/B variants: client sends X-Experiment: A or B. +// Origin must also return Vary: X-Experiment, preserve other Vary fields, +// and never associate this header with credentials or private data. +sub vcl_recv { + if (req.method != "GET" && req.method != "HEAD") { + return(pass); + } + if (req.http.Authorization || req.http.Cookie) { + return(pass); + } + if (req.url ~ "^/experiment(/|[?]|$)") { + if (req.http.X-Experiment ~ "^(A|B)$") { + return(hash); + } + return(pass); + } + return(pass); +} + +sub vcl_hash { + hash_data(req.http.X-Experiment); +} +``` + +### 8. Streaming, webhooks and origin errors + +**Goal:** Avoid caching event streams/webhooks and mark SSE/error responses as uncacheable in the response stage. + +**Expected traffic:** `GET /events` → PASS; an unrelated response with `Content-Type: text/event-stream` → NoStore; status 5xx → NoStore. + +**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.0 shared storage anyway. + +Source: [`examples/vcl/stream-and-errors-no-store.vcl`](../examples/vcl/stream-and-errors-no-store.vcl). + +```vcl +// Defense in depth for streaming and transient backend responses. +// Does not implement retries, synthetic error handling or stale-if-error. +sub vcl_recv { + if (req.url ~ "^/(events|stream|webhook)(/|[?]|$)") { + return(pass); + } +} + +sub vcl_backend_response { + if (beresp.http.Content-Type ~ "^text/event-stream") { + set beresp.uncacheable = true; + return(deliver); + } + if (beresp.status >= 500) { + set beresp.uncacheable = true; + } +} +``` + +### 9. Safe request and delivery header edits + +**Goal:** Remove a non-essential request header, set a constant origin-visible marker, remove an internal response header and tag delivery. + +**Expected traffic:** `GET /catalog` forwards `X-Edge-Policy: catalog-v1`; a downstream response no longer exposes `X-Debug`. + +**Prerequisites:** Changes only use permitted header names. Test both Cache HIT and MISS and the origin request. + +**Caveat:** Deliver-stage edits happen after cache selection; they cannot rescue an ineligible response or safely delete `Vary` for all downstream caches. + +Source: [`examples/vcl/headers-and-diagnostics.vcl`](../examples/vcl/headers-and-diagnostics.vcl). + +```vcl +// Request header sanitation (safe, ordinary representation headers only). +// Deliver mutations do not change the object stored in cache. +sub vcl_recv { + if (req.url ~ "^/catalog(/|[?]|$)") { + unset req.http.X-Marketing-Source; + set req.http.X-Edge-Policy = "catalog-v1"; + } +} + +sub vcl_deliver { + if (req.url ~ "^/catalog(/|[?]|$)") { + unset resp.http.X-Debug; + set resp.http.X-Edge-Policy = "catalog-v1"; + } +} +``` + +### 10. Tracking-query normalization (restricted) + +**Goal:** Normalize a small allowlist of proven non-semantic tracking parameters on `/landing`. + +**Expected traffic:** `GET /landing?utm_source=ad` can map to a query-stripped cache target after rule conversion. + +**Prerequisites:** The application guarantees these parameters never affect body, localization, cookies or redirects; inspect the exact generated Strip query rule. + +**Caveat:** **An import warning is expected.** RustProxy converts the recognized `regsuball` to a native query action with potentially different separators/empty-value behavior. Review before **Add partial import (reviewed)**. Prefer the graphical action for repeatable configuration. + +Source: [`examples/vcl/tracking-query-restricted.vcl`](../examples/vcl/tracking-query-restricted.vcl). + +```vcl +// Demonstrates the ONLY recognized req.url regsuball form. +// Import WILL WARN: converted to native strip_query with potentially +// different URL separator/empty-value normalization. Review and accept +// partial import only if the original URL parameters have no origin impact. +sub vcl_recv { + if (req.url ~ "^/landing([?]|$)") { + set req.url = regsuball(req.url, "([?&])(utm_source|utm_medium|gclid)=[^&]*", "\1"); + } +} +``` + +### 11. Advanced: removing origin Set-Cookie (high risk) + +**Goal:** Demonstrate the dedicated backend `unset beresp.http.Set-Cookie` escape hatch for one verified public SVG. + +**Expected traffic:** `GET /public/banner.svg` may become storable if that was its only storage barrier and all other checks permit it. + +**Prerequisites:** You have independently verified that the exact URL, body and response headers are identical for every visitor and that removing the cookie will not affect session, security or challenge behavior. + +**Caveat:** **Never apply globally.** Removing the origin cookie and thereby enabling public storage can disclose personalized content. A rule that adds TTL does not bypass other privacy barriers. + +Source: [`examples/vcl/advanced-set-cookie-removal.vcl`](../examples/vcl/advanced-set-cookie-removal.vcl). + +```vcl +// ADVANCED / HIGH RISK. Only for a verified identical public representation. +// Removes Set-Cookie before storage and before forwarding the origin response. +// NEVER apply to login, accounts, cart, personalized JSON or CSRF flows. +sub vcl_backend_response { + if (bereq.url ~ "^/public/banner[.]svg([?]|$)" && beresp.status == 200 && beresp.http.Cache-Control ~ "(^|,) *public(,|$)") { + unset beresp.http.Set-Cookie; + set beresp.ttl = 1h; + } +} +``` + +## D. Real HTTP traffic: what is handled and what is not + +The outcomes below describe **decision paths**, not a guaranteed X-Cache label: proxy route exclusions, access checks, configuration, origin responses, object sizes, validators, time, and storage limits still apply. The word **eligible** means the request may look up or populate cache if all other conditions succeed. + +### D1. Requests, cookies and authorization + +| Incoming request | Example policy | Decision | Important detail | +|---|---|---|---| +| `GET /catalog/item/1` (anonymous) | Public catalog | Eligible lookup | First fetch usually MISS; second may HIT. | +| `HEAD /catalog/item/1` | Public catalog | Eligible method | Verify real HEAD behavior rather than assuming it fills the same object as GET. | +| `POST /catalog/item/1` | Public catalog | PASS | VCL does not override unsafe-method restriction. | +| `PUT /api/public/item/1` | Public API | PASS | Mutations do not become cacheable. | +| `GET /account/orders` | Private routes | PASS | Authentication and authorization are enforced outside VCL. | +| `GET /api/public/list` without credentials | Public API | Eligible lookup | Only public JSON 200 has the example 15-second TTL. | +| `GET /api/private/me` | Public API | PASS | Path excluded even without Cookie. | +| `GET /catalog`, `Authorization: Bearer ...` | Catalog | PASS | Credentialed requests are excluded by code and cache safety checks. | +| `GET /catalog`, `Cookie: session=abc` | Catalog/CDN | PASS | No session cookie stripping. | +| `GET /catalog`, `Cookie: __cf_bm=a` | CDN cookie allowlist | Strip Cookie; eligible | Origin receives no Cookie; confirm CDN challenge behavior. | +| `Cookie: __cf_bm=a; cf_clearance=b` | CDN cookie allowlist | Strip whole Cookie header | Only exact allowlisted cookie names pass. | +| `Cookie: __cf_bm=a; session=b` | CDN cookie allowlist | PASS | Even one non-allowlisted name prevents removal. | +| Two physical Cookie fields, one technical and one session | CDN cookie allowlist | PASS | Patched matcher examines combined cookie values. | +| `GET /assets/site.css`, arbitrary Cookie | Public static | Strip Cookie **if verified safe** | Separate native `Vary: Cookie` setting has additional conditions. | +| `GET /assets/user-avatar.png`, Cookie | Do **not** use static bypass | PASS recommended | Do not remove session personalization merely due to extension. | +| `GET /experiment`, `X-Experiment: A` | A/B variants | Eligible A partition | Origin must emit downstream `Vary: X-Experiment`. | +| `GET /experiment`, `X-Experiment: C` | A/B variants | PASS | Unrecognized dimension value intentionally rejected. | +| `POST /webhook` | Private / stream | PASS | Rules do not replace request authentication/signature verification. | +| `GET /events`, SSE | Stream no-store | PASS | No VCL body streaming/rewrite support. | + +### D2. Origin response and `Vary` + +| Backend sends | RustProxy 0.39.0 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. | +| `200`, `Cache-Control: no-store` | Not storable without **dangerous explicit rewrite** | Do not use header removal to bypass origin policy. | +| `200`, `Set-Cookie: session=...` | Not storable normally | Dedicated Set-Cookie removal is high risk. | +| `200`, `Vary: Accept-Encoding` | Distinct encoding variants | Do not unset `Vary` to increase HIT rate. | +| `200`, `Vary: Accept-Language, Accept-Encoding` | Both dimensions preserved | An overwrite with only language loses encoding correctness. | +| `200`, `Vary: Origin` | Different CORS-Origin variants | Do not collapse different allowed origins. | +| `200`, `Vary: Cookie` on genuinely public static | Native exception **may** remove Cookie member | Requires configured extension, public positive freshness, no privacy blockers. | +| `200`, `Vary: Cookie` on personalized JSON | Preserve or bypass | No universal Ignore Vary switch. | +| `200`, `Vary: *` | No reusable cached variant | Rewrite at application if appropriate; do not force-drop. | +| `200`, malformed `Vary` | No reusable cached variant | Fix origin response. | +| `200`, `no-cache` and validator | Conditional behavior depends on compatibility/fallback | Do not assume TTL or forced HIT. | +| `200`, `no-cache` without validator | Compatibility fallback may differ from strict mode | See [Cache mode](CACHE.md); verify selected global/per-Vhost settings. | +| `200`, `Content-Type: text/event-stream` | NoStore if SSE recipe applies | No synthetic stream buffering in VCL. | +| `200`, `Cache-Control: public, max-age=0` | Not fresh solely because `public` | Short-TTL overrides are a deliberate independent administrative decision. | +| `301` / `302` redirect | Not storable | TTL recipe cannot enable redirect caching. | +| `404` / `410` missing asset | Not storable | Negative caching not implemented. | +| `500` / `502` / `503` error | Not storable | Independently configured stale-if-error may use an **earlier** stored object. | +| `304` response to revalidation | Native conditional revalidation | Not a programmable `vcl_hit` / `vcl_miss` callback. | + +### D3. Deployment, Docker, and other edge conditions + +| Situation | Suggested handling | Boundary | +|---|---|---| +| Docker container restarts and returns | Keep saved per-vhost rules and verify discovered routing after recovery | VCL does not start/recreate containers. | +| Docker container disappears | Native health/routing logic; observe possible 503 or eligible stale-if-error | `vcl_backend_error` and VCL retry are unsupported. | +| Same path on two unrelated domains | Per-vhost configuration and normalized Host isolation | No cross-vhost shared object or `hash_data(Host)` requirement. | +| Cache for only some Docker services | Apply rule to the selected Docker vhost or scoped global rules | Do not paste one global `return(hash)` for all apps. | +| Static file served by the **built-in** Web Server or PHP | Use those components' native settings | VCL rule importer is for HTTP reverse-proxy Vhosts. | +| Source checks for `Authorization` or TLS client identity | Native auth, ACL and transport security | These cannot be rewritten in cache VCL. | +| `Range`, `If-*`, request `Cache-Control: no-store` | Native conditional/range/privacy logic | Request-rule header mutations cannot override protected headers. | +| IP/CIDR based cache eligibility | Graphical cache-rule `client_ip` condition or native security ACL | `client.ip ~ my_acl` is **not** importable. | +| Tracking params (`utm_*`, `gclid`) | Graphical **Strip query params** with an explicit allowlist | VCL `regsuball` is limited and emits a warning. | +| Debug counters and Cache/Traffic lists | Native Cache/Traffic UI and HTTP cache diagnostics | VCL has no log writing, metrics API or custom VMOD. | + +## E. `Vary` decisions: prefer correctness over HIT ratio + +1. **Keep origin `Vary`** unless you can prove it is wrong. RustProxy compares retained dimensions, including `Accept-Language`, `Accept-Encoding`, `Origin`, custom headers and Cookie. It normalizes selected list-valued headers but does not generally discard dimensions. +2. If the origin emits an unnecessary `Vary: Cookie` for truly public `.css`/`.png`/`.woff2` files, first try fixing the origin. Otherwise use the **narrow native static-asset option** (configured extensions + public freshness + no Set-Cookie/privacy); do not use `unset beresp.http.Vary`. +3. When a service responds differently by language, compression, device, origin or experiment, **retain every actual dimension**. `set beresp.http.Vary = "Accept-Language"` overwrites the whole field; `set resp.http.Vary` changes only delivery and can mislead downstream caches. +4. `hash_data(req.http.X-Experiment)` is **internal** to RustProxy. The backend still must send `Vary: X-Experiment` to downstream caches, and clients must actually supply the header to those caches. A header known only to RustProxy cannot safely stand in for a public `Vary` contract. +5. Never apply a general `Ignore Vary` switch or remove `Vary: Cookie` for account/avatar, session-protected files, locale-by-Cookie or CORS-by-Origin variants. + +### Example: correctly declared language and encoding variants + +```http +GET /translations/home HTTP/1.1 +Host: public.example.test +Accept-Language: pl +Accept-Encoding: gzip + +HTTP/1.1 200 OK +Cache-Control: public, max-age=60 +Vary: Accept-Language, Accept-Encoding +Content-Type: text/html; charset=utf-8 +``` + +A second request with **identical relevant headers** may HIT after a successful fill; changing language or encoding must select a different object or fetch it from the origin. If the origin also varies by `Origin`, the response must include that member too. + +## F. Inspect behavior with curl (staging environment) + +Run against your **own test site** through the configured TLS listener. The hostname, paths and proxy must be replaced with actual test values. These commands use GET (`-o /dev/null -D -`) so the result does not depend on the HEAD method's implementation. Enable RustProxy cache diagnostics if you want `X-Cache` and reason fields; otherwise inspect `Cache-Status` and response headers. + +```sh +BASE='https://public.example.test' +# Warm a public resource: watch the first response and the repeated one. +curl -sS -o /dev/null -D - "$BASE/catalog/item/1" +curl -sS -o /dev/null -D - "$BASE/catalog/item/1" + +# Login/session and credential-bearing requests must not be served from shared cache. +curl -sS -o /dev/null -D - -H 'Cookie: session=test' "$BASE/catalog/item/1" +curl -sS -o /dev/null -D - -H 'Authorization: Bearer test' "$BASE/catalog/item/1" + +# Technical-only cookies vs mixed cookies: inspect origin logs as well. +curl -sS -o /dev/null -D - -H 'Cookie: __cf_bm=test' "$BASE/catalog/item/1" +curl -sS -o /dev/null -D - -H 'Cookie: __cf_bm=test; session=test' "$BASE/catalog/item/1" + +# Private path and non-GET should be bypassed. +curl -sS -o /dev/null -D - "$BASE/account/orders" +curl -sS -o /dev/null -D - -X POST "$BASE/api/public/list" + +# Check separate language variants, using an endpoint that really sets Vary. +curl -sS -o /dev/null -D - -H 'Accept-Language: pl' "$BASE/translations/home" +curl -sS -o /dev/null -D - -H 'Accept-Language: pl' "$BASE/translations/home" +curl -sS -o /dev/null -D - -H 'Accept-Language: en' "$BASE/translations/home" + +# A/B: only if the origin varies by X-Experiment and this is genuinely public. +curl -sS -o /dev/null -D - -H 'X-Experiment: A' "$BASE/experiment" +curl -sS -o /dev/null -D - -H 'X-Experiment: B' "$BASE/experiment" +``` + +**If a command prints no diagnostic header**, do not assume a HIT or PASS. Re-run with diagnostics enabled or inspect Cache/Traffic counters and origin access logs. Compare two requests to the **same scheme, host, path, query and `Vary` header values**. Changing an identity, method or URL changes the result. Avoid `curl -k` as a testing habit: verify the real TLS certificate. + +### Minimal scenario matrix for the graphical rule tester + +| Test | Request input | Mock origin response | Expected rule-level decision | +|---|---|---|---| +| Catalog lookup | `GET /catalog/item/1` | `200`, `Cache-Control: public, max-age=120` | Request lookup; backend TTL=120, grace=20. | +| Logged-in user | `GET /catalog/item/1`, Cookie `session=abc` | `200`, `Cache-Control: private` | Request PASS; no public storage. | +| CDN-only | `GET /catalog/item/1`, Cookie `__cf_bm=abc` | `200`, public | After CDN recipe: Cookie removed; lookup eligible. | +| Mixed cookies | `GET /catalog/item/1`, Cookie `__cf_bm=abc; session=abc` | `200`, public | Request PASS; session preserved. | +| Public API | `GET /api/public/list` | `200`, JSON, public | Lookup; backend TTL 15 and grace 5. | +| Private API | `GET /api/private/me` | `200`, private | Request PASS. | +| API mutation | `POST /api/public/list` | `200`, JSON, public | Request PASS. | +| Multi-language | `GET /translations/home`, Accept-Language `pl` | `200`, public, Vary: Accept-Language | Eligible variant for `pl`. | +| SSE | `GET /events` | `200`, text/event-stream | PASS. | +| 404 | `GET /catalog/missing` | `404` | TTL rule not enough to store. | +| Backend failure | `GET /catalog/item/1` | `503` | 503 not storable; separate stale policy may apply. | +| Tracking-query source | `GET /landing?utm_source=x` | `200`, public | Restricted import warning; review stripped query representation. | + +The tester previews the *cache rules*, including unsaved rules in the active editor. It does not simulate all unsaved global/per-Vhost cache configuration, is not connected to the origin and cannot prove a real HIT. + +## G. Common mistakes and missing functionality + +| Symptom or attempted VCL | Why it fails or is dangerous | Correct approach | +|---|---|---| +| Import looks successful but nothing changes | Import previews rules; warnings require manual acceptance, and rules still need saving | Inspect converted graph, approve reviewed warnings, save, test live | +| `return(hash)` but every request is BYPASS | Cache disabled, credential/route restriction, response no-store/Set-Cookie, request policy, size limits, etc. | Check global + Vhost flags and actual response headers | +| A MISS never becomes HIT | MISS may not be stored; TTL 0, invalid Vary, origin private, Set-Cookie, status != 200 | Inspect reason and origin headers; do not force public without proof | +| `unset req.http.Cookie` on a header containing session | Removes **all** cookies, including session identity | Use anchored **entire-header** technical allowlist or PASS | +| `set req.http.Cookie = regsuball(...)` | Not imported | Graphical **Strip cookies / Keep** names with reviewed scope | +| `set req.url = regsub(...)` with arbitrary pattern | Not implemented | Use native path/location routing or the graphical query action | +| `client.ip ~ my_acl`, `return(purge)`, `return(synth)` | Unsupported VCL importer actions | Use native ACL/security/purge/route/error configuration | +| `set beresp.ttl = 1h` for a 404 | Storage only supports HTTP 200 | No negative-cache feature in this version | +| `unset resp.http.Vary` to merge variants | Changes client response, not stored key; breaks downstream caches | Fix origin `Vary` or use strict native public-static Cookie exception | +| `unset beresp.http.Cache-Control` or `Set-Cookie` to force HIT | Can turn private data into shared content | Restore origin privacy; do not rewrite session responses | +| `hash_data` on request header without downstream Vary | RustProxy partition and client/CDN partition differ | Have the origin send all true `Vary` members | +| Need request-body parsing, ESI, backend directors, VMOD, cache-specific custom logging | No VCL interpreter/VMOD/body hook | Configure native features where supported or handle at origin | +| Docker vhost does not appear in global scope | Discovery/configuration may have changed; cache target list depends on active inventories | Recheck Docker agent inventory, publish/assignment and Cache target scope | + +## H. Change-management checklist + +- [ ] Select global, manual Vhost or Docker Vhost scope; compare inherited and local rule precedence. +- [ ] Confirm backend privacy contract for every URL and Cookie combination. +- [ ] Confirm only GET/HEAD are eligible; session and Authorization requests bypass. +- [ ] Check HTTP 200 status, freshness, validators, size, response `Cache-Control`, `Set-Cookie` and complete `Vary`. +- [ ] Import without unexpected warnings; separately approve any restricted conversion after inspecting graph. +- [ ] Save the rules, then test real requests and variants (not only the rule tester). +- [ ] Recheck after upstream changes, CDN changes, Docker container recreation and caching-mode changes. +- [ ] Invalidate affected existing cache objects when changing privacy, key or `Vary` policy. + +## Further references + +- [Exact VCL support matrix](VCL_SUPPORT_MATRIX.md): supported, restricted, graphical-only, intentional exclusions and absent features. +- [VCL import semantics](VCL.md): stage order, header edits, syntactic limits, strict vs compatible behavior. +- [HTTP cache](CACHE.md): freshness, static options, `Vary` matching, diagnostics, HOT/COLD, purge and stale handling. +- [Docker discovery](DOCKER_DISCOVERY.md): Docker inventory and saved vhost publication lifecycle. +- [Cache API](API.md): configuration and cache endpoints. + +**Validation scope:** These are source-reviewed operator examples, not evidence of a full Rust compiler/proxy traffic test. Revalidate against the actual binary and origin before production use. + diff --git a/examples/vcl/advanced-set-cookie-removal.vcl b/examples/vcl/advanced-set-cookie-removal.vcl new file mode 100644 index 0000000..941463e --- /dev/null +++ b/examples/vcl/advanced-set-cookie-removal.vcl @@ -0,0 +1,9 @@ +// ADVANCED / HIGH RISK. Only for a verified identical public representation. +// Removes Set-Cookie before storage and before forwarding the origin response. +// NEVER apply to login, accounts, cart, personalized JSON or CSRF flows. +sub vcl_backend_response { + if (bereq.url ~ "^/public/banner[.]svg([?]|$)" && beresp.status == 200 && beresp.http.Cache-Control ~ "(^|,) *public(,|$)") { + unset beresp.http.Set-Cookie; + set beresp.ttl = 1h; + } +} diff --git a/examples/vcl/cdn-technical-cookies.vcl b/examples/vcl/cdn-technical-cookies.vcl new file mode 100644 index 0000000..b79fa4e --- /dev/null +++ b/examples/vcl/cdn-technical-cookies.vcl @@ -0,0 +1,23 @@ +// Optional template: only shared/public content independent of these cookies. +// Cloudflare: __cf_bm, cf_clearance, _cfuvid, __cfruid, __cfseq +// Akamai: _abck, ak_bmsc, bm_sz, bm_sv +// Security cookies can be needed for bot challenges; review before enabling. +sub vcl_recv { + if (req.method != "GET" && req.method != "HEAD") { + return(pass); + } + if (req.url ~ "^/(admin|api|auth|login|logout|panel|konto|dashboard)(/|[?]|$)") { + return(pass); + } + if (req.http.Authorization) { + return(pass); + } + // Match the complete Cookie header, not one cookie within it. + 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; + } + if (req.http.Cookie) { + return(pass); + } + return(hash); +} diff --git a/examples/vcl/experiment-variants.vcl b/examples/vcl/experiment-variants.vcl new file mode 100644 index 0000000..77e45f4 --- /dev/null +++ b/examples/vcl/experiment-variants.vcl @@ -0,0 +1,22 @@ +// Controlled, PUBLIC A/B variants: client sends X-Experiment: A or B. +// Origin must also return Vary: X-Experiment, preserve other Vary fields, +// and never associate this header with credentials or private data. +sub vcl_recv { + if (req.method != "GET" && req.method != "HEAD") { + return(pass); + } + if (req.http.Authorization || req.http.Cookie) { + return(pass); + } + if (req.url ~ "^/experiment(/|[?]|$)") { + if (req.http.X-Experiment ~ "^(A|B)$") { + return(hash); + } + return(pass); + } + return(pass); +} + +sub vcl_hash { + hash_data(req.http.X-Experiment); +} diff --git a/examples/vcl/headers-and-diagnostics.vcl b/examples/vcl/headers-and-diagnostics.vcl new file mode 100644 index 0000000..740b218 --- /dev/null +++ b/examples/vcl/headers-and-diagnostics.vcl @@ -0,0 +1,15 @@ +// Request header sanitation (safe, ordinary representation headers only). +// Deliver mutations do not change the object stored in cache. +sub vcl_recv { + if (req.url ~ "^/catalog(/|[?]|$)") { + unset req.http.X-Marketing-Source; + set req.http.X-Edge-Policy = "catalog-v1"; + } +} + +sub vcl_deliver { + if (req.url ~ "^/catalog(/|[?]|$)") { + unset resp.http.X-Debug; + set resp.http.X-Edge-Policy = "catalog-v1"; + } +} diff --git a/examples/vcl/language-catalog.vcl b/examples/vcl/language-catalog.vcl new file mode 100644 index 0000000..fc0fcdb --- /dev/null +++ b/examples/vcl/language-catalog.vcl @@ -0,0 +1,21 @@ +// Origin responsibility: return Vary: Accept-Language (plus any other real +// dimensions such as Accept-Encoding), public freshness and no Set-Cookie. +// Do not replace the origin Vary list with a single dimension. +sub vcl_recv { + if (req.method != "GET" && req.method != "HEAD") { + return(pass); + } + if (req.http.Authorization || req.http.Cookie) { + return(pass); + } + if (req.url ~ "^/translations(/|[?]|$)") { + return(hash); + } + return(pass); +} + +sub vcl_backend_response { + if (bereq.url ~ "^/translations(/|[?]|$)" && beresp.status == 200 && beresp.http.Cache-Control ~ "(^|,) *public(,|$)") { + set beresp.ttl = 60s; + } +} diff --git a/examples/vcl/private-routes-bypass.vcl b/examples/vcl/private-routes-bypass.vcl new file mode 100644 index 0000000..c2f8f43 --- /dev/null +++ b/examples/vcl/private-routes-bypass.vcl @@ -0,0 +1,16 @@ +// Defensive exclusions for an existing HTTP reverse-proxy vhost. +// Does not opt in to caching for other routes. +sub vcl_recv { + if (req.method != "GET" && req.method != "HEAD") { + return(pass); + } + if (req.url ~ "^/(admin|api/private|account|auth|login|logout|checkout|cart|dashboard|webhook)(/|[?]|$)") { + return(pass); + } + if (req.http.Authorization) { + return(pass); + } + if (req.http.Cookie) { + return(pass); + } +} diff --git a/examples/vcl/public-catalog.vcl b/examples/vcl/public-catalog.vcl new file mode 100644 index 0000000..b78f61e --- /dev/null +++ b/examples/vcl/public-catalog.vcl @@ -0,0 +1,21 @@ +// Cache only demonstrably public catalog pages. The origin must supply +// Cache-Control: public, max-age=120 and must not vary by user/session. +sub vcl_recv { + if (req.method != "GET" && req.method != "HEAD") { + return(pass); + } + if (req.http.Authorization || req.http.Cookie) { + return(pass); + } + if (req.url ~ "^/catalog(/|[?]|$)") { + return(hash); + } + return(pass); +} + +sub vcl_backend_response { + if (bereq.url ~ "^/catalog(/|[?]|$)" && beresp.status == 200 && beresp.http.Cache-Control ~ "(^|,) *public(,|$)") { + set beresp.ttl = 120s; + set beresp.grace = 20s; + } +} diff --git a/examples/vcl/public-json-api.vcl b/examples/vcl/public-json-api.vcl new file mode 100644 index 0000000..43f6905 --- /dev/null +++ b/examples/vcl/public-json-api.vcl @@ -0,0 +1,21 @@ +// GET-only shared caching for /api/public. Other API routes bypass. +// The origin must mark genuinely public JSON responses as such. +sub vcl_recv { + if (req.method != "GET" && req.method != "HEAD") { + return(pass); + } + if (req.http.Authorization || req.http.Cookie) { + return(pass); + } + if (req.url ~ "^/api/public(/|[?]|$)") { + return(hash); + } + return(pass); +} + +sub vcl_backend_response { + if (bereq.url ~ "^/api/public(/|[?]|$)" && beresp.status == 200 && beresp.http.Content-Type ~ "^application/json" && beresp.http.Cache-Control ~ "(^|,) *public(,|$)") { + set beresp.ttl = 15s; + set beresp.grace = 5s; + } +} diff --git a/examples/vcl/static-assets-public.vcl b/examples/vcl/static-assets-public.vcl new file mode 100644 index 0000000..cb27450 --- /dev/null +++ b/examples/vcl/static-assets-public.vcl @@ -0,0 +1,16 @@ +// Optional: remove ALL request cookies for public, identity-independent +// assets under /assets. Origin must never use a session for these assets. +// Vary: Cookie removal is NOT accomplished by this VCL. Configure the +// native "Ignore Vary: Cookie for public static assets" setting separately. +sub vcl_recv { + if (req.method != "GET" && req.method != "HEAD") { + return(pass); + } + if (req.url ~ "^/assets/.*[.](css|js|png|jpg|jpeg|svg|woff2)([?]|$)") { + if (req.http.Authorization) { + return(pass); + } + unset req.http.Cookie; + return(hash); + } +} diff --git a/examples/vcl/stream-and-errors-no-store.vcl b/examples/vcl/stream-and-errors-no-store.vcl new file mode 100644 index 0000000..0933e57 --- /dev/null +++ b/examples/vcl/stream-and-errors-no-store.vcl @@ -0,0 +1,17 @@ +// Defense in depth for streaming and transient backend responses. +// Does not implement retries, synthetic error handling or stale-if-error. +sub vcl_recv { + if (req.url ~ "^/(events|stream|webhook)(/|[?]|$)") { + return(pass); + } +} + +sub vcl_backend_response { + if (beresp.http.Content-Type ~ "^text/event-stream") { + set beresp.uncacheable = true; + return(deliver); + } + if (beresp.status >= 500) { + set beresp.uncacheable = true; + } +} diff --git a/examples/vcl/tracking-query-restricted.vcl b/examples/vcl/tracking-query-restricted.vcl new file mode 100644 index 0000000..c664dea --- /dev/null +++ b/examples/vcl/tracking-query-restricted.vcl @@ -0,0 +1,9 @@ +// Demonstrates the ONLY recognized req.url regsuball form. +// Import WILL WARN: converted to native strip_query with potentially +// different URL separator/empty-value normalization. Review and accept +// partial import only if the original URL parameters have no origin impact. +sub vcl_recv { + if (req.url ~ "^/landing([?]|$)") { + set req.url = regsuball(req.url, "([?&])(utm_source|utm_medium|gclid)=[^&]*", "\1"); + } +} diff --git a/langs/en_US.json b/langs/en_US.json index b2e050e..b36290f 100644 --- a/langs/en_US.json +++ b/langs/en_US.json @@ -3370,6 +3370,10 @@ "cancel": "Cancel", "cacheTabRules": "Rules", "cacheVarnishCompatibleVclHelp": "Use return(pass) for session cookies before return(hash) for selected public routes. In Rules, the Cache & VCL guide explains Vary, header edits and importer limits. Per-vhost overrides take precedence.", + "cacheGuideCdnTitle": "Cloudflare and Akamai technical Cookie template", + "cacheGuideCdnText": "Strips Cookie only when every cookie is a known CDN technical cookie. An unknown or session cookie, Authorization, private path or non-GET/HEAD method bypasses cache.", + "cacheGuideCdnWarning": "Opt-in only. Some CDN challenge cookies are required at the origin. Test the challenge flow and confirm content is public before importing.", + "cacheGuideDocsMatrix": "VCL support: implemented vs unsupported", "cacheGuideInsert": "Insert into VCL importer", "cacheGuideImporterUnavailable": "Open Cache → Rules after the configuration has loaded and try again.", "cacheGuideOpen": "Cache & VCL guide", @@ -3563,6 +3567,12 @@ "cacheRuleTplStatic": "Static files: no cookies, 30 days", "cacheRuleTplStaticCookies": "Static files: remove cookies", "cacheRuleTplStaticTtl": "Static files: TTL 30 days", + "cacheRuleTplCdn": "CDN: safely ignore technical cookies (Cloudflare, Akamai)", + "cacheRuleTplCdnMethods": "CDN: bypass non-GET/HEAD", + "cacheRuleTplCdnPrivate": "CDN: bypass private paths", + "cacheRuleTplCdnAuth": "CDN: bypass Authorization", + "cacheRuleTplCdnStrip": "CDN: remove ONLY technical cookies", + "cacheRuleTplCdnRemaining": "CDN: bypass remaining cookies", "cacheRuleTplTracking": "Ignore tracking parameters (utm_*, fbclid, gclid)", "cacheRuleTplApi": "API: bypass cache", "cacheRuleTplLanguage": "Separate cache per language cookie", diff --git a/langs/pl_pl.json b/langs/pl_pl.json index fcf4f08..2dba0d5 100644 --- a/langs/pl_pl.json +++ b/langs/pl_pl.json @@ -3370,6 +3370,10 @@ "cancel": "Anuluj", "cacheTabRules": "Reguły", "cacheVarnishCompatibleVclHelp": "Użyj return(pass) dla cookies sesyjnych przed return(hash) na wybranych trasach publicznych. Poradnik Cache i VCL w Regułach opisuje Vary, zmiany nagłówków i ograniczenia importera. Nadpisania per-vhost mają pierwszeństwo.", + "cacheGuideCdnTitle": "Szablon cookies operatorów Cloudflare i Akamai", + "cacheGuideCdnText": "Usuwa Cookie tylko wtedy, gdy wszystkie ciasteczka są techniczne. Ciasteczka sesyjne, Authorization, prywatne ścieżki i metody inne niż GET/HEAD omijają cache.", + "cacheGuideCdnWarning": "Opcjonalne. Niektóre ciasteczka ochronne CDN są potrzebne serwerowi. Przetestuj weryfikację i potwierdź, że treść jest publiczna.", + "cacheGuideDocsMatrix": "VCL: co działa, a co nie jest obsługiwane", "cacheGuideInsert": "Wstaw do importera VCL", "cacheGuideImporterUnavailable": "Otwórz Cache → Reguły po załadowaniu konfiguracji i spróbuj ponownie.", "cacheGuideOpen": "Poradnik cache i VCL", @@ -3563,6 +3567,12 @@ "cacheRuleTplStatic": "Pliki statyczne: bez ciasteczek, 30 dni", "cacheRuleTplStaticCookies": "Pliki statyczne: usuń ciasteczka", "cacheRuleTplStaticTtl": "Pliki statyczne: TTL 30 dni", + "cacheRuleTplCdn": "CDN: ignoruj tylko ciasteczka techniczne (Cloudflare, Akamai)", + "cacheRuleTplCdnMethods": "CDN: pomijaj metody inne niż GET/HEAD", + "cacheRuleTplCdnPrivate": "CDN: pomijaj prywatne ścieżki", + "cacheRuleTplCdnAuth": "CDN: omijaj Authorization", + "cacheRuleTplCdnStrip": "CDN: usuwaj tylko ciasteczka techniczne", + "cacheRuleTplCdnRemaining": "CDN: pomijaj pozostałe ciasteczka", "cacheRuleTplTracking": "Ignoruj parametry śledzące (utm_*, fbclid, gclid)", "cacheRuleTplApi": "API: pomiń cache", "cacheRuleTplLanguage": "Osobny cache dla ciasteczka języka", diff --git a/src/admin/documentation/documents.rs b/src/admin/documentation/documents.rs index 98123e2..657d98f 100644 --- a/src/admin/documentation/documents.rs +++ b/src/admin/documentation/documents.rs @@ -25,6 +25,8 @@ pub(super) static READER_DOCUMENTS: &[(&str, &str, &str)] = &[ reader_doc!("docs/PHP_FPM.md", "guides"), reader_doc!("docs/CACHE.md", "guides"), reader_doc!("docs/VCL.md", "guides"), + reader_doc!("docs/VCL_SUPPORT_MATRIX.md", "guides"), + reader_doc!("docs/VCL_TRAFFIC_COOKBOOK.md", "guides"), reader_doc!("docs/RESPONSE_DELIVERY.md", "guides"), reader_doc!("docs/TRANSPORT.md", "guides"), reader_doc!("docs/STREAMS.md", "guides"), diff --git a/src/admin/logging_api.rs b/src/admin/logging_api.rs index 8d30788..48949a7 100644 --- a/src/admin/logging_api.rs +++ b/src/admin/logging_api.rs @@ -238,6 +238,50 @@ async fn events( .into_response()) } +/// List the effective (compiled) reverse-proxy vhosts, including Docker +/// assignments. The persisted config deliberately excludes generated routes. +/// Catalog fingerprints also change when Docker inventory changes without +/// increasing the persisted configuration revision. +fn monitored_vhost_catalog(state: &Arc) -> (Vec, Vec, String) { + let snapshot = state.config.load_full(); + let desired = &snapshot.envelope.config; + let observed = state.docker.latest(); + let (publications, _) = crate::docker::label_publications(desired, &observed); + let mut docker_labels = std::collections::HashMap::new(); + for agent in &desired.docker_agents.agents { + let inventory = observed.get(&agent.id).and_then(|item| item.inventory.as_ref()); + let assignments = agent.assignments.iter().filter(|assignment| assignment.enabled) + .chain(publications.iter().filter(|entry| entry.agent_id == agent.id) + .map(|entry| &entry.assignment)); + for assignment in assignments { + let service = inventory.and_then(|inventory| inventory.services.iter() + .find(|service| service.key == assignment.service_key)); + let name = service.map(|service| service.container_name.as_str()) + .filter(|name| !name.is_empty()) + .unwrap_or(assignment.hostname.as_str()); + docker_labels.insert(crate::docker::generated_id(&agent.id, &assignment.service_key), + (name.to_owned(), agent.name.clone())); + } + } + let vhosts: Vec<_> = cache_rule_vhosts(state).into_iter() + .filter(|vhost| snapshot.vhost_metrics.contains_key(&vhost.id)) + .collect(); + let options: Vec = vhosts.iter().map(|vhost| { + let host = vhost.frontend.hosts.first().map(String::as_str).unwrap_or(&vhost.id); + let docker = docker_labels.get(&vhost.id); + let label = match docker { + Some((name, agent)) => format!("{name} - {host} (Docker: {agent})"), + None => format!("{} / {}", vhost.id, vhost.frontend.hosts.join(", ")), + }; + json!({"id": vhost.id, "hosts": vhost.frontend.hosts, + "docker": docker.is_some(), "label": label}) + }).collect(); + let bytes = serde_json::to_vec(&options).unwrap_or_default(); + let digest = ::digest(&bytes); + let catalog_version: String = digest[..12].iter().map(|byte| format!("{byte:02x}")).collect(); + (vhosts, options, catalog_version) +} + #[derive(Default, Deserialize)] #[serde(default, deny_unknown_fields)] struct TrafficQuery { @@ -259,23 +303,16 @@ async fn traffic_status( } }; let snapshot = state.config.load_full(); + let (vhosts, options, catalog_version) = monitored_vhost_catalog(&state); if query.vhost.as_ref().is_some_and(|id| { - id != "*" - && !snapshot - .envelope - .config - .vhosts - .iter() - .any(|vhost| &vhost.id == id) + id != "*" && !vhosts.iter().any(|vhost| &vhost.id == id) }) { - return Err(ApiError( - StatusCode::NOT_FOUND, - "unknown vhost traffic scope".into(), - )); + return Err(ApiError(StatusCode::NOT_FOUND, "unknown vhost traffic scope".into())); } let scope = query.vhost.as_deref().unwrap_or("*"); let mut payload = json!({ "revision": snapshot.envelope.revision, + "catalog_version": catalog_version, "scope": scope, "since": "process_start", "settings": { @@ -288,13 +325,7 @@ async fn traffic_status( if live { return Ok(Json(payload)); } - payload["vhosts"] = json!(snapshot - .envelope - .config - .vhosts - .iter() - .map(|vhost| json!({"id": vhost.id, "hosts": vhost.frontend.hosts})) - .collect::>()); + payload["vhosts"] = json!(options); Ok(Json(payload)) } @@ -321,15 +352,9 @@ async fn cache_status( } }; let snapshot = state.config.load_full(); - if query - .vhost - .as_ref() - .is_some_and(|id| !snapshot.envelope.config.vhosts.iter().any(|v| &v.id == id)) - { - return Err(ApiError( - StatusCode::NOT_FOUND, - "unknown vhost cache scope".into(), - )); + let (vhosts, options, catalog_version) = monitored_vhost_catalog(&state); + if query.vhost.as_ref().is_some_and(|id| !vhosts.iter().any(|vhost| &vhost.id == id)) { + return Err(ApiError(StatusCode::NOT_FOUND, "unknown vhost cache scope".into())); } let dashboard = state.cache.dashboard( query.vhost.as_deref(), @@ -338,6 +363,7 @@ async fn cache_status( ); let mut payload = json!({ "revision": snapshot.envelope.revision, + "catalog_version": catalog_version, "metrics": state.cache.view(), "dashboard": dashboard, "bans": state.cache.bans() @@ -346,9 +372,11 @@ async fn cache_status( return Ok(Json(payload)); } payload["settings"] = json!(snapshot.envelope.config.cache); - payload["vhosts"] = json!(snapshot.envelope.config.vhosts.iter().map(|vhost| { - json!({"id":vhost.id, "hosts":vhost.frontend.hosts, "metrics":state.cache.scope_view(&vhost.id), - "settings":vhost.cache.resolve(&snapshot.envelope.config.cache).ok()}) + payload["vhosts"] = json!(vhosts.iter().zip(options.iter()).map(|(vhost, option)| { + let mut item = option.clone(); + item["metrics"] = json!(state.cache.scope_view(&vhost.id)); + item["settings"] = json!(vhost.cache.resolve(&snapshot.envelope.config.cache).ok()); + item }).collect::>()); Ok(Json(payload)) } diff --git a/src/admin/openapi.json b/src/admin/openapi.json index f7231de..40f9893 100644 --- a/src/admin/openapi.json +++ b/src/admin/openapi.json @@ -1961,9 +1961,7 @@ "vhosts": { "type": "array", "items": { - "type": "object", - "properties": {}, - "additionalProperties": true + "$ref": "#/components/schemas/VhostScopeCatalogItem" } }, "dashboard": { @@ -1976,6 +1974,10 @@ "items": { "$ref": "#/components/schemas/CacheBan" } + }, + "catalog_version": { + "type": "string", + "description": "Fingerprint of effective Vhost scope catalog, including Docker publications. Check on view=live even when revision is unchanged." } }, "additionalProperties": false @@ -6961,9 +6963,12 @@ "vhosts": { "type": "array", "items": { - "type": "object", - "additionalProperties": true + "$ref": "#/components/schemas/VhostScopeCatalogItem" } + }, + "catalog_version": { + "type": "string", + "description": "Fingerprint of effective Vhost scope catalog, including Docker publications. Check on view=live even when revision is unchanged." } } }, @@ -8959,6 +8964,42 @@ "maxLength": 262144 } } + }, + "VhostScopeCatalogItem": { + "type": "object", + "description": "Effective reverse-proxy Vhost, including generated Docker publications. The stable ID remains the API scope; the label is presentation-only.", + "additionalProperties": true, + "properties": { + "id": { + "type": "string", + "description": "Stable Vhost scope ID, also used in cache purge/invalidation and Traffic analytics." + }, + "hosts": { + "type": "array", + "items": { + "type": "string" + } + }, + "docker": { + "type": "boolean", + "description": "True for a generated Docker Vhost." + }, + "label": { + "type": "string", + "description": "Human-readable Vhost description; Docker entries include container/domain/agent where available." + }, + "metrics": { + "type": "object", + "additionalProperties": true, + "description": "Only in full Cache responses." + }, + "settings": { + "type": "object", + "additionalProperties": true, + "nullable": true, + "description": "Resolved effective cache settings; only in full Cache responses." + } + } } } }, @@ -11025,7 +11066,7 @@ "operationId": "get_api_cache", "responses": { "200": { - "description": "Full response by default. view=live omits static settings/vhost configuration while retaining revision, live metrics, dashboard objects/domains and BAN rules.", + "description": "Full response by default, including ordinary and generated Docker Vhost scopes (with human labels, resolved cache settings and metrics). view=live omits static settings/vhost definitions but retains revision, catalog_version, metrics, dashboard and BAN rules.", "content": { "application/json": { "schema": { @@ -11080,7 +11121,7 @@ "name": "vhost", "in": "query", "required": false, - "description": "Configured vhost ID. Omit to select all scopes.", + "description": "Ordinary or generated Docker Vhost ID. Omit to select all scopes.", "schema": { "type": "string" } @@ -11111,7 +11152,7 @@ "name": "view", "in": "query", "required": false, - "description": "Set to live for polling. Omits static settings and vhost configuration; refetch the full view when revision changes.", + "description": "Set to live for polling. Omits static settings/vhost catalog; refetch full view when revision or catalog_version changes.", "schema": { "type": "string", "enum": [ @@ -14212,7 +14253,7 @@ "name": "vhost", "in": "query", "required": false, - "description": "Configured vhost ID or * for all vhosts.", + "description": "Ordinary or generated Docker Vhost ID, or * for all Vhosts.", "schema": { "type": "string", "default": "*" @@ -14222,7 +14263,7 @@ "name": "view", "in": "query", "required": false, - "description": "Set to live for polling. Omits the static vhost list; refetch the full view when revision changes.", + "description": "Set to live for polling. Omits static Vhost list; refetch full view when revision or catalog_version changes.", "schema": { "type": "string", "enum": [ @@ -14233,7 +14274,7 @@ ], "responses": { "200": { - "description": "Full response by default. view=live omits the static vhost list while retaining revision, current settings, GeoIP state and analytics.", + "description": "Full response includes ordinary and generated Docker Vhost scope IDs with readable labels. view=live omits the static Vhost list while retaining revision, catalog_version, settings, GeoIP state and analytics.", "content": { "application/json": { "schema": { diff --git a/src/admin/operations.rs b/src/admin/operations.rs index 6f9dfd3..2e3f51f 100644 --- a/src/admin/operations.rs +++ b/src/admin/operations.rs @@ -62,14 +62,7 @@ async fn cache_purge( Query(scope): Query, ) -> Result, ApiError> { if let Some(id) = &scope.vhost { - if !state - .config - .load() - .envelope - .config - .vhosts - .iter() - .any(|host| &host.id == id) + if !cache_rule_vhosts(&state).iter().any(|host| &host.id == id) { return Err(ApiError( StatusCode::NOT_FOUND, @@ -119,14 +112,7 @@ async fn cache_invalidate( ) -> Result, ApiError> { let Json(request) = input.map_err(public::invalid_json)?; if let Some(id) = &request.vhost { - if !state - .config - .load() - .envelope - .config - .vhosts - .iter() - .any(|host| &host.id == id) + if !cache_rule_vhosts(&state).iter().any(|host| &host.id == id) { return Err(ApiError( StatusCode::NOT_FOUND, diff --git a/src/admin/web/cache-panel.js b/src/admin/web/cache-panel.js index f7d8f56..d1dd3cf 100644 --- a/src/admin/web/cache-panel.js +++ b/src/admin/web/cache-panel.js @@ -135,7 +135,7 @@ } function configure() { const selected = scope(); const items = [el("option", t("logAllVhosts"))]; items[0].value = "*"; - for (const host of envelope?.config.vhosts || []) { const item = el("option", `${host.id} / ${host.frontend.hosts.join(", ")}`); item.value = host.id; items.push(item); } + for (const host of staticData?.vhosts || []) { const item = el("option", host.label || `${host.id} / ${(host.hosts || []).join(", ")}`); item.value = host.id; item.title = host.id; items.push(item); } $("cache-scope").replaceChildren(...items); $("cache-scope").value = items.some(e => e.value === selected) ? selected : "*"; } function render(data) { @@ -255,11 +255,24 @@ try { const base = `/api/cache?${query}`; if (staticData) query.set("view", "live"); - let data = await api(`/api/cache?${query}`, { signal }); - if (staticData && data.revision !== staticRevision) data = await api(base, { signal }); + let data; + try { + data = await api(`/api/cache?${query}`, { signal }); + } catch (error) { + // A label-only Docker publication can disappear from the + // effective catalog. Recover from its now-invalid scope. + if (error?.status !== 404 || scope() === "*") throw error; + $("cache-scope").value = "*"; + offset = 0; resetLiveChart("*"); + staticData = null; staticRevision = null; + query.delete("vhost"); query.delete("view"); query.set("offset", "0"); + data = await api(`/api/cache?${query}`, { signal }); + } + if (staticData && (data.revision !== staticRevision || data.catalog_version !== staticData.catalog_version)) data = await api(base, { signal }); if (data.settings && Array.isArray(data.vhosts)) { - staticData = { settings: data.settings, vhosts: data.vhosts }; + staticData = { settings: data.settings, vhosts: data.vhosts, catalog_version: data.catalog_version }; staticRevision = data.revision; + configure(); // Effective Docker vhosts can change without a saved config revision. } else if (staticData) { data = { ...staticData, ...data }; } diff --git a/src/admin/web/cache-rules.js b/src/admin/web/cache-rules.js index 28991c1..3a5e4eb 100644 --- a/src/admin/web/cache-rules.js +++ b/src/admin/web/cache-rules.js @@ -165,6 +165,18 @@ window.rustProxyCacheRules = (() => { { 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" }] }, ], + // Opt-in CDN cookie policy. Never strip a mixed Cookie header: it may + // contain session/authentication state required by the origin. + cdn: () => { + const technical = "(?:__cf_bm|cf_clearance|_cfuvid|__cfruid|__cfseq|_abck|ak_bmsc|bm_sz|bm_sv)"; + return [ + { name: t("cacheRuleTplCdnMethods"), stage: "request", match: "all", conditions: [{ field: "method", operator: "equals", values: ["GET", "HEAD"], negate: true }], actions: [{ type: "pass" }], stop: true }, + { 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 }, + ]; + }, tracking: () => [{ name: t("cacheRuleTplTracking"), stage: "request", match: "all", conditions: [], actions: [{ type: "strip_query", params: ["utm_*", "fbclid", "gclid", "msclkid", "mc_cid", "mc_eid", "_ga"] }] }], api: () => [{ name: t("cacheRuleTplApi"), stage: "request", match: "all", conditions: [{ field: "path", operator: "prefix", values: ["/api/"] }], actions: [{ type: "pass" }] }], language: () => [{ name: t("cacheRuleTplLanguage"), stage: "request", match: "all", conditions: [], actions: [{ type: "hash_cookie", name: "lang" }] }], diff --git a/src/admin/web/index.html b/src/admin/web/index.html index 298aff7..39ec1f0 100644 --- a/src/admin/web/index.html +++ b/src/admin/web/index.html @@ -4224,6 +4224,36 @@ sub vcl_backend_response {

Authorization, Cookie (except dedicated unset), Cache-Control and forwarding/transport headers are protected in request rules. Complex URL rewrites are warned about, not guessed. Always review import warnings.

RustProxy's beresp.uncacheable = false applies only to a previous cache-rule restriction; this is not Varnish's exact behavior. The backend's private/no-store and Set-Cookie protections remain unless deliberately rewritten by a separate trusted rule.

+
+

Cloudflare and Akamai technical Cookie template

+

Only strip the Cookie header when every cookie is a known technical CDN cookie. Any session or unknown cookie, Authorization, private path or non-GET/HEAD method bypasses cache.

+
// Optional template: only shared/public content independent of these cookies.
+// Cloudflare: __cf_bm, cf_clearance, _cfuvid, __cfruid, __cfseq
+// Akamai: _abck, ak_bmsc, bm_sz, bm_sv
+// Security cookies can be needed for bot challenges; review before enabling.
+sub vcl_recv {
+    if (req.method != "GET" && req.method != "HEAD") {
+        return(pass);
+    }
+    if (req.url ~ "^/(admin|api|auth|login|logout|panel|konto|dashboard)(/|[?]|$)") {
+        return(pass);
+    }
+    if (req.http.Authorization) {
+        return(pass);
+    }
+    // Match the complete Cookie header, not one cookie within it.
+    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;
+    }
+    if (req.http.Cookie) {
+        return(pass);
+    }
+    return(hash);
+}
+ +

Optional policy: some CDN challenge cookies are required at the origin. Verify public pages and the challenge flow before using this template. It does not override Cache-Control and Vary admission safeguards.

+

VCL stages and rule precedence

vcl_recv handles pass/hash and request rewrites; vcl_hash supports selected hash_data(req.http.X); vcl_backend_response handles TTL, grace and backend headers; vcl_deliver edits final headers, even on HIT or BYPASS.

@@ -4245,6 +4275,7 @@ curl -sS -D - -o /dev/null \ diff --git a/src/admin/web/traffic-panel.js b/src/admin/web/traffic-panel.js index faae1e1..04f8dbc 100644 --- a/src/admin/web/traffic-panel.js +++ b/src/admin/web/traffic-panel.js @@ -31,8 +31,8 @@ const selected = scope(), options = [el("option", t("logAllVhosts"))]; options[0].value = "*"; for (const vhost of data.vhosts || []) { - const option = el("option", `${vhost.id} / ${(vhost.hosts || []).join(", ")}`); - option.value = vhost.id; options.push(option); + const option = el("option", vhost.label || `${vhost.id} / ${(vhost.hosts || []).join(", ")}`); + option.value = vhost.id; option.title = vhost.id; options.push(option); } $("traffic-scope").replaceChildren(...options); $("traffic-scope").value = options.some(option => option.value === selected) ? selected : "*"; @@ -117,12 +117,22 @@ loading = true; try { const base = `/api/traffic?vhost=${encodeURIComponent(scope())}`; - let data = await api(staticData ? `${base}&view=live` : base, { signal }); - if (staticData && data.revision !== staticRevision) { + let data; + try { + data = await api(staticData ? `${base}&view=live` : base, { signal }); + } catch (error) { + // Labels are inventory-derived. If the selected publication + // vanished, fall back to All rather than polling a stale ID. + if (error?.status !== 404 || scope() === "*") throw error; + $("traffic-scope").value = "*"; + staticData = null; staticRevision = null; + data = await api("/api/traffic?vhost=*", { signal }); + } + if (staticData && (data.revision !== staticRevision || data.catalog_version !== staticData.catalog_version)) { data = await api(base, { signal }); } if (Array.isArray(data.vhosts)) { - staticData = { vhosts: data.vhosts }; + staticData = { vhosts: data.vhosts, catalog_version: data.catalog_version }; staticRevision = data.revision; } else if (staticData) { data = { ...staticData, ...data }; diff --git a/src/cache/rules.rs b/src/cache/rules.rs index a97ce19..e4432ff 100644 --- a/src/cache/rules.rs +++ b/src/cache/rules.rs @@ -848,6 +848,22 @@ impl CompiledCondition { .header .as_ref() .map(|header| { + if header.as_str() == http::header::COOKIE.as_str() { + // Cookie can appear in several field lines. An anchored + // allowlist must match all of them, not just one. Bad + // UTF-8 or an empty field must still count as present + // so subsequent `if (req.http.Cookie) return(pass)` + // remains fail-closed. + let mut parts = Vec::new(); + for value in request.headers.get_all(header).iter() { + match value.to_str() { + Ok(text) => parts.push(text), + Err(_) => return vec![Cow::Borrowed("")], + } + } + return if parts.is_empty() { Vec::new() } + else { vec![Cow::Owned(parts.join("; "))] }; + } request .headers .get_all(header) diff --git a/src/cache/rules_tests.rs b/src/cache/rules_tests.rs index 8425e7a..64673b1 100644 --- a/src/cache/rules_tests.rs +++ b/src/cache/rules_tests.rs @@ -993,4 +993,72 @@ sub vcl_deliver { assert!(import_vcl("sub vcl_recv { set req.http.X-A = \"missing; }").is_err()); assert!(import_vcl("sub vcl_recv { /* missing */ set req.http.X-A = \"x\"; /*").is_err()); } + + #[test] + fn vcl_cdn_template_strips_only_complete_technical_cookie_headers() { + let vcl = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/examples/vcl/cdn-technical-cookies.vcl" + )); + let imported = import_vcl(vcl).unwrap(); + assert!(imported.warnings.is_empty(), "{:?}", imported.warnings); + assert!(!imported.rules.is_empty()); + validate_rules(&imported.rules, true).unwrap(); + let compiled = CompiledRules::compile("shop", &[], &imported.rules, false).unwrap(); + + for cookie in [ + "__cf_bm=token", + "cf_clearance=token; _cfuvid=id", + "_abck=abc; ak_bmsc=def; bm_sz=xyz", + "__cfseq=token; __cfruid=other; bm_sv=third", + ] { + let input = request("/", None, &[("cookie", cookie)]); + let result = compiled.evaluate_request(&input, false); + assert!(result.pass.is_none(), "unexpected pass on {cookie}"); + assert!(result.lookup.is_some(), "missing lookup on {cookie}"); + let mut forwarded = input.headers.clone(); + result.rewrite_cookies(&mut forwarded); + assert!(!forwarded.contains_key(http::header::COOKIE), "{cookie}"); + } + for cookie in [ + "session=secret", + "__cf_bm=token; session=secret", + "session=secret; cf_clearance=token", + "__cf_bm=token; XSRF-TOKEN=csrf", + "cf_clearance=token; unknown_cookie=x", + ] { + let input = request("/", None, &[("cookie", cookie)]); + let result = compiled.evaluate_request(&input, false); + assert!(result.pass.is_some(), "missing pass on {cookie}"); + let mut forwarded = input.headers.clone(); + result.rewrite_cookies(&mut forwarded); + assert_eq!(forwarded.get(http::header::COOKIE).unwrap(), cookie); + } + // Cookie may be split across multiple HTTP header field lines. + // Matching any single field line would discard a real session cookie. + let split = request("/", None, &[ + ("cookie", "__cf_bm=token"), + ("cookie", "session=secret"), + ]); + let result = compiled.evaluate_request(&split, false); + assert!(result.pass.is_some()); + assert!(result.strip_cookies.is_none()); + + let mut invalid_cookie = request("/", None, &[]); + invalid_cookie.headers.insert(http::header::COOKIE, + HeaderValue::from_bytes(b"__cf_bm=\xff").unwrap()); + let result = compiled.evaluate_request(&invalid_cookie, false); + assert!(result.pass.is_some()); + assert!(result.strip_cookies.is_none()); + + for path in ["/admin", "/admin/settings", "/login", "/api/profile", "/konto"] { + let input = request(path, None, &[("cookie", "__cf_bm=token")]); + assert!(compiled.evaluate_request(&input, false).pass.is_some(), "{path}"); + } + let input = request("/", None, &[("Authorization", "Bearer test")]); + assert!(compiled.evaluate_request(&input, false).pass.is_some()); + let mut post = request("/", None, &[]); + post.method = Method::POST; + assert!(compiled.evaluate_request(&post, false).pass.is_some()); + } } diff --git a/src/docker/tests.rs b/src/docker/tests.rs index 65bf938..dbcda95 100644 --- a/src/docker/tests.rs +++ b/src/docker/tests.rs @@ -367,6 +367,59 @@ mod tests { assert!(route.backend.is_none()); } + #[test] + fn docker_cache_settings_and_id_survive_container_disappearance_and_return() { + let mut desired = crate::config::demo_config("127.0.0.1:9000".parse().unwrap()); + desired.vhosts.clear(); + desired.docker_agents.agents.push(Agent { + id: "node1".into(), + name: "Node 1".into(), + base_domain: "docker1.lab.local".into(), + listener_ids: vec!["http".into()], + assignments: vec![Assignment { + service_key: "container:app:8080/tcp".into(), + hostname: "app".into(), + cache_enabled: true, + cache_default_ttl_seconds: Some(180), + cache_rules: vec![serde_json::from_value(serde_json::json!({ + "id": "no-admin-cache", + "conditions": [{"field": "path", "operator": "prefix", "values": ["/admin"]}], + "actions": [{"type": "pass"}] + })).unwrap()], + ..Default::default() + }], + ..Default::default() + }); + let persisted = serde_json::to_value(&desired.docker_agents.agents[0].assignments[0]) + .unwrap(); + let restored: Assignment = serde_json::from_value(persisted).unwrap(); + assert_eq!(restored.cache_default_ttl_seconds, Some(180)); + assert_eq!(restored.cache_rules.len(), 1); + + let found = observation(service(), vec![HostAddress { + ip: "10.2.3.4".into(), + source: "interface".into(), + interface: "eth0".into(), + scope: "private".into(), + }]); + let before = effective_config(desired.clone(), &found).unwrap(); + assert!(!before.vhosts[0].transient_unavailable); + + let mut missing = found.clone(); + missing.get_mut("node1").unwrap().inventory.as_mut().unwrap().services.clear(); + let offline = effective_config(desired.clone(), &missing).unwrap(); + assert_eq!(offline.vhosts.len(), 1); + assert!(offline.vhosts[0].transient_unavailable); + assert_eq!(offline.vhosts[0].id, before.vhosts[0].id); + assert_eq!(offline.vhosts[0].cache.default_ttl_seconds, Some(180)); + assert_eq!(offline.vhosts[0].cache.rules.len(), 1); + + let returned = effective_config(desired, &found).unwrap(); + assert!(!returned.vhosts[0].transient_unavailable); + assert_eq!(returned.vhosts[0].id, before.vhosts[0].id); + assert_eq!(returned.vhosts[0].cache.rules.len(), 1); + } + #[test] fn failed_agent_observation_with_last_inventory_keeps_backend_materialized() { let mut desired = crate::config::demo_config("127.0.0.1:9000".parse().unwrap()); @@ -932,6 +985,25 @@ mod tests { .any(|item| item.assignment.service_key == "container:web:80/tcp")); } + #[test] + fn label_only_publications_reappear_without_becoming_persisted_assignments() { + let (desired, found) = label_config(vec![labelled( + "web", 80, &[("rustproxy.enable", "true"), ("rustproxy.host", "web")], + )]); + assert!(desired.docker_agents.agents[0].assignments.is_empty()); + let before = effective_config(desired.clone(), &found).unwrap(); + assert_eq!(before.vhosts.len(), 1); + + let mut missing = found.clone(); + missing.get_mut("node1").unwrap().inventory.as_mut().unwrap().services.clear(); + assert!(effective_config(desired.clone(), &missing).unwrap().vhosts.is_empty()); + + let again = effective_config(desired.clone(), &found).unwrap(); + assert_eq!(again.vhosts.len(), 1); + assert_eq!(again.vhosts[0].id, before.vhosts[0].id); + assert!(desired.docker_agents.agents[0].assignments.is_empty()); + } + #[test] fn alerts_cover_offline_resources_missing_and_unhealthy_services() { let unhealthy = Service {