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

No files matched your search

+3 -1
View File
@@ -4,7 +4,9 @@ Release history focused on **features, settings, default behavior, compatibility
## 0.39.1 — HEAD cache-fill and public Vhost cookie template (source-only changes) ## 0.39.1 — HEAD cache-fill and public Vhost cookie template (source-only changes)
- **Public Vhost inherited-cookie opt-in template:** added a disabled-by-default per-Vhost graphical rule and importable VCL example for entirely public, cookie-independent GET/HEAD pages receiving unrelated cookies from a parent domain. A combined method/Cookie/no-Authorization/non-private-path guard drops the incoming Cookie before cache lookup and origin forwarding, retaining normal origin privacy and Vary rules. No global template is offered. Documented the unavoidable limitation that HTTP Cookie contains no setting Domain, and recommended host-only `Set-Cookie` at the issuer as the primary fix. Added source-level JS and Rust VCL importer regression tests (Rust compilation pending). - **Quick cache/VCL rule gallery (0.39.1, no version bump):** added a grouped template dropdown and searchable one-click scenario browser in global, ordinary Vhost and Docker Vhost editors. The independent CDN/parent-cookie presets remain separate. Added safe pass/no-store patterns for sessions, WordPress/WooCommerce, Django, Laravel, Auth.js, ASP.NET, Drupal, private routes, API, GraphQL, signed URLs, SSE and webhooks. Added disabled-by-default public TTL, assets and staging-header examples, with EN/PL descriptions and a dedicated embedded Reader guide. Multi-rule templates are inserted together or not at all if the rule limit is exceeded; parent-cookie rules are placed before matching existing CDN cookie guards. No cache format, runtime rule engine, API or version change; Rust/toolchain and live-origin tests still required.
- **Separate parent-cookie and CDN templates:** replaced the risky all-cookie public-Vhost template with a disabled-by-default per-Vhost rule that removes **only** operator-listed exact cookie names using a new `remove_named_cookies` action and RustProxy VCL extension `remove_req_cookies()`. Unlisted cookies, including app sessions, survive to the *unchanged, separate* CDN template and its `bypass remaining cookies` check. No forced hash or terminal action. The Cookie header cannot identify the issuing Domain; use host-only cookies where possible. Existing previously saved broad strip-all rules must be removed manually. Source-only change; Rust compilation pending.
- **HEAD on a cold cache:** when HEAD is forwarded as GET for a cache-eligible response, keep consuming the upstream body asynchronously so HOT/COLD can publish the object. Return an empty HEAD body immediately; limit detached reads by the cache object size and a 30-second deadline. Non-cacheable HEAD requests are not drained. This fixes an incomplete cache fill on HEAD without weakening request privacy, Cookie, or Vary safeguards. - **HEAD on a cold cache:** when HEAD is forwarded as GET for a cache-eligible response, keep consuming the upstream body asynchronously so HOT/COLD can publish the object. Return an empty HEAD body immediately; limit detached reads by the cache object size and a 30-second deadline. Non-cacheable HEAD requests are not drained. This fixes an incomplete cache fill on HEAD without weakening request privacy, Cookie, or Vary safeguards.
- **Regression coverage and diagnostics:** added tests for HEAD filling vs non-cacheable HEAD bodies, and documented why browser requests with Cookie, reload directives or distinct `Vary` dimensions differ from anonymous curl GETs. Rust binary and real-origin verification are still required before production use. - **Regression coverage and diagnostics:** added tests for HEAD filling vs non-cacheable HEAD bodies, and documented why browser requests with Cookie, reload directives or distinct `Vary` dimensions differ from anonymous curl GETs. Rust binary and real-origin verification are still required before production use.
+21 -18
View File
@@ -2,7 +2,7 @@
4140a2956264b44f259e6a37fc00ba02097bbe68b09296e04d3d243c1287129b .env.example 4140a2956264b44f259e6a37fc00ba02097bbe68b09296e04d3d243c1287129b .env.example
e76e688874828e3743d03693b1d2872b9633b4db09909673786caf30f7cfe489 .gitignore e76e688874828e3743d03693b1d2872b9633b4db09909673786caf30f7cfe489 .gitignore
9ba24d43572540c7929cc58005b5a3b5b065ec3b896c76e7fe863c78c59e04a7 AGENTS.md 9ba24d43572540c7929cc58005b5a3b5b065ec3b896c76e7fe863c78c59e04a7 AGENTS.md
1e31a29e503e0ba0e77def8b6171df93b750e54a6c7918439aa72e771d9962d7 CHANGELOG.md 92e812d0cdb476acc3318ff3168c1731d55dae644030883f61f7bb866aa5c13b CHANGELOG.md
9ecd4d4f644cf9a4fdb4a2998a8cfdba270c926ffa93c6bfffa3d7a0adf55e85 Cargo.lock 9ecd4d4f644cf9a4fdb4a2998a8cfdba270c926ffa93c6bfffa3d7a0adf55e85 Cargo.lock
9566307178ed2b4ab15aea7e5b66614a021634d513fd6f467a846ac8f278bfe9 Cargo.toml 9566307178ed2b4ab15aea7e5b66614a021634d513fd6f467a846ac8f278bfe9 Cargo.toml
788745d4f70a0382c6280020afbd48844bb2af65e835a826852143f8132cdeca Dockerfile 788745d4f70a0382c6280020afbd48844bb2af65e835a826852143f8132cdeca Dockerfile
@@ -41,13 +41,14 @@ f30c895df3d7f289f3b7c9a73969009ecf91110f59cb247daa242f68e78aa014 docker-agent/s
c0940a4b323d71931cf2ad4ad24d58b6d6bfd49af90c6e3fc91fcbe2b4cf312f docs/ACCESS.md c0940a4b323d71931cf2ad4ad24d58b6d6bfd49af90c6e3fc91fcbe2b4cf312f docs/ACCESS.md
e986cbe1534bbe392b2ce6413fc00ac5bc5d70b40d50c247c5b1b6c7b2760fbe docs/API.md e986cbe1534bbe392b2ce6413fc00ac5bc5d70b40d50c247c5b1b6c7b2760fbe docs/API.md
728b15b9825f547f34c4121219784798dd046fbbdd72ece8906d0cd77e8efc64 docs/BACKUP.md 728b15b9825f547f34c4121219784798dd046fbbdd72ece8906d0cd77e8efc64 docs/BACKUP.md
b0c78b402f79e752d9eff53da0306c08e5aed7e5d4ebb886ac49b693c109dd50 docs/CACHE.md af2d37a1d21fb62def072e3c0b7b4ec9e6d45bff669e3a090fb5874eb32c351f docs/CACHE.md
89952bbe069fb6ed969e8b336bac09b73ccbea42dc8d1e4ab63f4f8e1d14dc33 docs/CACHE_TEMPLATE_LIBRARY.md
a64f72b95918c24938aa7268ec0a534cb0f28dd1ee0aa325b02c49f3347ccf54 docs/CERTIFICATES.md a64f72b95918c24938aa7268ec0a534cb0f28dd1ee0aa325b02c49f3347ccf54 docs/CERTIFICATES.md
6aa83366ad45227d10ebe121ed2c4f690ebcb826939ec2b2eafb40bfd714ac69 docs/CONFIGURATION.md 6aa83366ad45227d10ebe121ed2c4f690ebcb826939ec2b2eafb40bfd714ac69 docs/CONFIGURATION.md
fec29ce846d6705eb45819d85d382f28e28a146b265feab2e4c7cce2a35e5883 docs/CUSTOM_LOCATIONS.md fec29ce846d6705eb45819d85d382f28e28a146b265feab2e4c7cce2a35e5883 docs/CUSTOM_LOCATIONS.md
2f3e005ab01bb48b6a2d74dd8f163159f892d08c35d9ad7162e912e1d4def870 docs/DASHBOARD.md 2f3e005ab01bb48b6a2d74dd8f163159f892d08c35d9ad7162e912e1d4def870 docs/DASHBOARD.md
81bd7a901619092e2a5a5fb7e4edd2157f2b5ce7e0483c24581ec290080446c0 docs/DOCKER_DISCOVERY.md 81bd7a901619092e2a5a5fb7e4edd2157f2b5ce7e0483c24581ec290080446c0 docs/DOCKER_DISCOVERY.md
6d183d812d4725d51f4e2fb97e69b6195f33e144a8e084c0c14e6990eae1e963 docs/FEATURES.md 657115a35dd67574aff70f78a157c0e9c08858a059a006aa704711a403edbaff docs/FEATURES.md
f5835144cd2802abbcac3a36c76bdd4ec2f25fa49307facb199efec5bf9e92d3 docs/HEADLESS.md f5835144cd2802abbcac3a36c76bdd4ec2f25fa49307facb199efec5bf9e92d3 docs/HEADLESS.md
4282602f0b814841f71282040003bec91c24611e5152b33407b76e62357f8d3a docs/INSTALL.md 4282602f0b814841f71282040003bec91c24611e5152b33407b76e62357f8d3a docs/INSTALL.md
6e37859bf0dced99d4a7db93790cb38fcd90191932827946d5223eaa4c784fce docs/LOGS.md 6e37859bf0dced99d4a7db93790cb38fcd90191932827946d5223eaa4c784fce docs/LOGS.md
@@ -55,7 +56,7 @@ f5835144cd2802abbcac3a36c76bdd4ec2f25fa49307facb199efec5bf9e92d3 docs/HEADLESS.
a7717c4ab03417914805527e573ea1dfd5d35295bf7b347d0c098bda6d469850 docs/MONITORING.md a7717c4ab03417914805527e573ea1dfd5d35295bf7b347d0c098bda6d469850 docs/MONITORING.md
6d3937088eeb67a9f690d44ebe0b6e660b68116dbf69091ac7816bdc52cec2b6 docs/PERFORMANCE.md 6d3937088eeb67a9f690d44ebe0b6e660b68116dbf69091ac7816bdc52cec2b6 docs/PERFORMANCE.md
d5894c07c68ec4230987767198434abee13b0e525842fea21bcbe752fa82742b docs/PHP_FPM.md d5894c07c68ec4230987767198434abee13b0e525842fea21bcbe752fa82742b docs/PHP_FPM.md
e18a194de2d3f256884622e6e74453b47ff459f1a372944a0241ce1488a11e11 docs/README.md 37ad8b2fc720394e831dce5cc72388ff308bdb27bf3fc09ea9af6f6ff424b3fe docs/README.md
490a6dbe870f2b1fd4ec7816768dde6c86fa7957fc9de2d2f075e123c9222222 docs/RESPONSE_DELIVERY.md 490a6dbe870f2b1fd4ec7816768dde6c86fa7957fc9de2d2f075e123c9222222 docs/RESPONSE_DELIVERY.md
95ab4786792d5920a2e109b7d196838057f24b512a69d713fb5884dc75c84339 docs/SCREENSHOTS.md 95ab4786792d5920a2e109b7d196838057f24b512a69d713fb5884dc75c84339 docs/SCREENSHOTS.md
3a48184b36d225757fc5e2d22c629f89bfe5d4007ff087f0be0ce02a5fb04c28 docs/SECURITY.md 3a48184b36d225757fc5e2d22c629f89bfe5d4007ff087f0be0ce02a5fb04c28 docs/SECURITY.md
@@ -63,9 +64,9 @@ bbef60ff1771da9f48af812987766e1e479408873ae2f079b13f1d5c62ecc6ff docs/STREAMS.m
c9c9a0b401f0565f15b834d855bfdb34edb3eab46bff03d9e0825af204d20bf8 docs/TODO.md c9c9a0b401f0565f15b834d855bfdb34edb3eab46bff03d9e0825af204d20bf8 docs/TODO.md
978097cf53314ad573583d7176491d984b9dbb22295df2b00168a28b14184c4a docs/TRANSPORT.md 978097cf53314ad573583d7176491d984b9dbb22295df2b00168a28b14184c4a docs/TRANSPORT.md
1335bc863391858ff4d584eb7f8ad771e270d36708061f2a1bff09de7906a8ab docs/TROUBLESHOOTING.md 1335bc863391858ff4d584eb7f8ad771e270d36708061f2a1bff09de7906a8ab docs/TROUBLESHOOTING.md
411dc0273bcbe17db65fb1272a80bc7fb0e74a3de36224a7510a13e0a3c23963 docs/VCL.md f842f10c90520c30071c74ad9f42e59385e1cc95d34fd29bfdb0bbd6dca87e59 docs/VCL.md
fe6423cb6d6b1c953102b118e010e994d9d600725963af5707b755923e50e82f docs/VCL_SUPPORT_MATRIX.md f0d5d9d4eed779245615223c06945fea47d2c27aa1fe721dc7193a788e3fa4bd docs/VCL_SUPPORT_MATRIX.md
73279816139bec54f5b3c6a72eddff987ccfc46c85d487b413564002d337d9c9 docs/VCL_TRAFFIC_COOKBOOK.md 167eac6f7a4044051e81fd957109575dcf6cdbef20e9ad2c334d153f133e7b1a docs/VCL_TRAFFIC_COOKBOOK.md
1169420deeed8f2e8f3a0acfb3ffe16a3419820ba1869059e0b82bb2411e1537 docs/VHOSTS.md 1169420deeed8f2e8f3a0acfb3ffe16a3419820ba1869059e0b82bb2411e1537 docs/VHOSTS.md
e67928a9d044e71b681c3e52f9dd8b151d6b72f965d16d5da8b0eadde98b70e9 docs/WEB_SERVER.md e67928a9d044e71b681c3e52f9dd8b151d6b72f965d16d5da8b0eadde98b70e9 docs/WEB_SERVER.md
42822b1c9801bcadb0e2d785cb91883ca2df1da141222631f153030c95f5e197 docs/images/about.png 42822b1c9801bcadb0e2d785cb91883ca2df1da141222631f153030c95f5e197 docs/images/about.png
@@ -101,7 +102,7 @@ ecfa04e9f1e9c4f1b1629854798dc432c24414cdd6e80788bceffe37a6716011 examples/vcl/h
d055d1d6ee01a567a90a4f2599c276567b4f834203f5c08e23d8da25a66ce918 examples/vcl/private-routes-bypass.vcl d055d1d6ee01a567a90a4f2599c276567b4f834203f5c08e23d8da25a66ce918 examples/vcl/private-routes-bypass.vcl
1c97e44b66765616a2756bc01ef1f100f82adcfe330271cde4bd5e7021221558 examples/vcl/public-catalog.vcl 1c97e44b66765616a2756bc01ef1f100f82adcfe330271cde4bd5e7021221558 examples/vcl/public-catalog.vcl
718f6ee134b4d6691284a84ae4dbc2ac5d4c3de61bf1df7889b025f411e2ee43 examples/vcl/public-json-api.vcl 718f6ee134b4d6691284a84ae4dbc2ac5d4c3de61bf1df7889b025f411e2ee43 examples/vcl/public-json-api.vcl
b009b3749233f844acacb9f48663e67d919baed4863bc89d38c1ab9677ef8237 examples/vcl/public-vhost-ignore-cookies.vcl 13c010c8ed4f06cc7177c09f216ba3d3e62e1664e61408384c31163232447b13 examples/vcl/public-vhost-remove-parent-cookies.vcl
4f12a9802c0df71d950822c5a8b04afb39da79075bc146b5c72f3148cb47610b examples/vcl/static-assets-public.vcl 4f12a9802c0df71d950822c5a8b04afb39da79075bc146b5c72f3148cb47610b examples/vcl/static-assets-public.vcl
8cd3f62c6ffc8339facfbaa390ec88aae465e7e605ef403673be569e3308da02 examples/vcl/stream-and-errors-no-store.vcl 8cd3f62c6ffc8339facfbaa390ec88aae465e7e605ef403673be569e3308da02 examples/vcl/stream-and-errors-no-store.vcl
5ca6374c3125b0e1891a1554ab0414f7c5309459b7d79765550ac3ef3bd14fd4 examples/vcl/tracking-query-restricted.vcl 5ca6374c3125b0e1891a1554ab0414f7c5309459b7d79765550ac3ef3bd14fd4 examples/vcl/tracking-query-restricted.vcl
@@ -124,8 +125,8 @@ e9cbb0224c4a3d23a6019ba557e0cd568c1ad5e1582ff1e335fb7d99b7a1055d integrations/r
3f092a9ab80221eddd67be4d1a776acbc6e04c1eb6011b588280c28e83b2582f integrations/routeros-oci-build/build-routeros-oci.sh 3f092a9ab80221eddd67be4d1a776acbc6e04c1eb6011b588280c28e83b2582f integrations/routeros-oci-build/build-routeros-oci.sh
3f267cafa16006e5456ade78ee2d5fae02cc7ce747839523068ffd8d7c98798a integrations/routeros-oci-build/docker-entrypoint.sh 3f267cafa16006e5456ade78ee2d5fae02cc7ce747839523068ffd8d7c98798a integrations/routeros-oci-build/docker-entrypoint.sh
ae2ee2887fcba096d0de25edcc18faa1ffec35759274518db1bf6d6982f7176c langs/README.md ae2ee2887fcba096d0de25edcc18faa1ffec35759274518db1bf6d6982f7176c langs/README.md
a2b5f6d97c55b8aec1b4f30e0a8d27315dd64318b52089961a0d1c87695e2596 langs/en_US.json d3cbdaed42261a49f9262dca5cfaa95ff0da3c42908bc2aacca39015a23289de langs/en_US.json
9f653ba156a208054d227cbb919f3aaf27d5d41bd0d2c8aa506a3fe1034536f6 langs/pl_pl.json ff8e97d98eec09b815314bc5fbd213f06d5ffb6e7349b0e34d8e607ffb307340 langs/pl_pl.json
8ed80f14633970899d56f4ea72684a8d4b1f2843c1c78bfacc4cbb5f7ce9ef4b make_zip.py 8ed80f14633970899d56f4ea72684a8d4b1f2843c1c78bfacc4cbb5f7ce9ef4b make_zip.py
e830d37dd1f81a4b0aa7d535f5bba69e34e433b0fd99cc8ee0b296786c32379a migrations/0002_admin.sql e830d37dd1f81a4b0aa7d535f5bba69e34e433b0fd99cc8ee0b296786c32379a migrations/0002_admin.sql
20112cc82192098b8d602f1c4f7ca08712e9e1366c845fabb92753187c370d35 migrations/0003_certificate_renewals.sql 20112cc82192098b8d602f1c4f7ca08712e9e1366c845fabb92753187c370d35 migrations/0003_certificate_renewals.sql
@@ -163,7 +164,9 @@ a459d95bbb0076f33ade8b273b813308167f9d8d45242b309a2d18320ca0093c scripts/migrat
d759315babd9971b354d6f702d4c861eb1cd5c41b1e2e0f1a94ad4d2c2db49a3 scripts/runtime/acme_provider.py d759315babd9971b354d6f702d4c861eb1cd5c41b1e2e0f1a94ad4d2c2db49a3 scripts/runtime/acme_provider.py
e69813fb1d3a4cdcfb7243964cc323fc21a603087bf2e84188fa42b9d3cee4b5 scripts/runtime/acme_rfc2136.py e69813fb1d3a4cdcfb7243964cc323fc21a603087bf2e84188fa42b9d3cee4b5 scripts/runtime/acme_rfc2136.py
91c883cfdce94c8c22c98749f611317f538a112d29be4f3fb1fa460b8f29ceaa scripts/start_stream_backends.sh 91c883cfdce94c8c22c98749f611317f538a112d29be4f3fb1fa460b8f29ceaa scripts/start_stream_backends.sh
7ab439d1a9cf3901f93e4d79577bbe6e8a3beaf5b7257e710e697fd9b6bf2084 scripts/test_public_cookie_template.cjs 6c137b3183a0581383f18e4c5407c4309abd083c6cec975f203406f5371aeddd scripts/test_cache_rule_catalog_ui.cjs
dbbd69f582a761430c6da17ecbadec0384a9a0258f74bbba2d7f758885850413 scripts/test_cache_rule_template_catalog.cjs
82aac95d7e22bdb887f2e33635467942712c0e7c74d10226427944e91fabe97f scripts/test_public_cookie_template.cjs
046b4282550f5cb4e53906665c91c7442be70fc68fd0743466fd832582f7c979 scripts/test_stream_tcp.py 046b4282550f5cb4e53906665c91c7442be70fc68fd0743466fd832582f7c979 scripts/test_stream_tcp.py
f0b48ec0cc4411755cc0b4128eebce710375afa99344cb76198cf31074f8eb63 scripts/test_stream_udp.py f0b48ec0cc4411755cc0b4128eebce710375afa99344cb76198cf31074f8eb63 scripts/test_stream_udp.py
22e880e98c7b9d700c7a4c02b9b1d543e5dbd1f4ecdca42813a1083165b32a19 scripts/version.py 22e880e98c7b9d700c7a4c02b9b1d543e5dbd1f4ecdca42813a1083165b32a19 scripts/version.py
@@ -192,7 +195,7 @@ aefbef9839f9914ba05ea62bceff1463da3042b52ee851181ee39d4fbf7b91c3 src/admin/cert
7cac90d705a201b764d283e06774744e4b358eb157a8c492357bfc21aed37543 src/admin/config_sections.rs 7cac90d705a201b764d283e06774744e4b358eb157a8c492357bfc21aed37543 src/admin/config_sections.rs
c51f725075b5c4fc3fb7fb8b8b5f73987bff698a400e8950e968068b97a77631 src/admin/dashboard_presets.rs c51f725075b5c4fc3fb7fb8b8b5f73987bff698a400e8950e968068b97a77631 src/admin/dashboard_presets.rs
aae1ca0e70d987830bd63948d431f54302083148177c1b551565be12df7fe771 src/admin/documentation.rs aae1ca0e70d987830bd63948d431f54302083148177c1b551565be12df7fe771 src/admin/documentation.rs
e55d4cea1711abadad14d7e65e1d1fa479daa0a28eaa7651c9600a776a2ca3c2 src/admin/documentation/documents.rs efaa7cdfd3031eeb7ed8bc3e2cb51e966c97900cb0d6e6100a72fc5e99d78969 src/admin/documentation/documents.rs
b9c2952e3fcfca540d0ad64f2d3acc5c1f5240e707f4f23ef4d452f46fcb520f src/admin/documentation/tests.rs b9c2952e3fcfca540d0ad64f2d3acc5c1f5240e707f4f23ef4d452f46fcb520f src/admin/documentation/tests.rs
1ce779b84aa8f47bdb3c34f83593c1f2f06d2235f0319847096cfcd035434168 src/admin/file_log_search.rs 1ce779b84aa8f47bdb3c34f83593c1f2f06d2235f0319847096cfcd035434168 src/admin/file_log_search.rs
059218501907355b22bc84e7e0c41ec72565af283f5e97170ce7707ea5874009 src/admin/file_logs.rs 059218501907355b22bc84e7e0c41ec72565af283f5e97170ce7707ea5874009 src/admin/file_logs.rs
@@ -200,7 +203,7 @@ d58a2ed83319176de4e66790ed292447c9497ae031464ec55cfe27174acb639a src/admin/file
77b8c05645969834cc8a58e249a7b60a57d6c47ad1c5cd92ffa5e4a9b5a8e73c src/admin/file_logs_query.rs 77b8c05645969834cc8a58e249a7b60a57d6c47ad1c5cd92ffa5e4a9b5a8e73c src/admin/file_logs_query.rs
e287399bfef114028b8831cb854db2323c0e1b61e3503ef409ebb2c5cdbc2a8c src/admin/logging_api.rs e287399bfef114028b8831cb854db2323c0e1b61e3503ef409ebb2c5cdbc2a8c src/admin/logging_api.rs
51228956c33358278ebed62941da273e1e87d0b5c5d1c40cc0d2c91aec9d7362 src/admin/mod.rs 51228956c33358278ebed62941da273e1e87d0b5c5d1c40cc0d2c91aec9d7362 src/admin/mod.rs
6263ee9b5b5478160b028ff05ed6dc9a6a679fb9c92d6a3467508533b4934610 src/admin/openapi.json 02e5c4aed681479e73a06217eb109bfd3a1eb28d8b36bcca889af009c07c3fc3 src/admin/openapi.json
9f8842cdec27d703d1795dd6eb37d9420e9f5a2e56a0df93278c92bace5d1f4c src/admin/operations.rs 9f8842cdec27d703d1795dd6eb37d9420e9f5a2e56a0df93278c92bace5d1f4c src/admin/operations.rs
257d93a29d0bda96462bcf695aba8d0ec0f9412c379e066ec46ae8ee034e3a53 src/admin/panel_assets.rs 257d93a29d0bda96462bcf695aba8d0ec0f9412c379e066ec46ae8ee034e3a53 src/admin/panel_assets.rs
f5127855c2994d052678865df36d703b74f4a0afc633daf7718b10da18d26e37 src/admin/panel_content.rs f5127855c2994d052678865df36d703b74f4a0afc633daf7718b10da18d26e37 src/admin/panel_content.rs
@@ -250,14 +253,14 @@ b0930110e4eb7de6826e27b5b46c47e46556449fed6dc505d42da4f5e9c20366 src/admin/web/
b7ead49224a4ec67181d3f24f9d9634bd6d76756f826a4d5d993300637d1d8f3 src/admin/web/app/stream-dashboard.js b7ead49224a4ec67181d3f24f9d9634bd6d76756f826a4d5d993300637d1d8f3 src/admin/web/app/stream-dashboard.js
7de070cc8cdde45d7e0932259299e341e25b32c9ffbd87e4fcce934d0f090de4 src/admin/web/app/web-overview.js 7de070cc8cdde45d7e0932259299e341e25b32c9ffbd87e4fcce934d0f090de4 src/admin/web/app/web-overview.js
857a3c49d003a4c3beed98acf404fcffa1b7b127f34579a916196e007e8a2963 src/admin/web/cache-panel.js 857a3c49d003a4c3beed98acf404fcffa1b7b127f34579a916196e007e8a2963 src/admin/web/cache-panel.js
42d6af0fa1d2a0e7366f24c5df5b9a14ab497902329c3d99db9cf3a666be4511 src/admin/web/cache-rules.js 38616483ae2f5f779473ff7e7cf02fc43d920d0926e623a3ec195569ad22fb0d src/admin/web/cache-rules.js
6288b0a8228d828ac2e2535ace2d1aefd1c04011e789eb97f7279129874ac35c src/admin/web/certificate-api.js 6288b0a8228d828ac2e2535ace2d1aefd1c04011e789eb97f7279129874ac35c src/admin/web/certificate-api.js
f554ca7179fe4d97ae24aa004d4bc9ada5f84fc78257891933a7fed728006ef8 src/admin/web/css/00-tokens.css f554ca7179fe4d97ae24aa004d4bc9ada5f84fc78257891933a7fed728006ef8 src/admin/web/css/00-tokens.css
f13fd5486664d9803a99e226321bc84bd571a100c105884e6c68b127071595f1 src/admin/web/css/10-base.css f13fd5486664d9803a99e226321bc84bd571a100c105884e6c68b127071595f1 src/admin/web/css/10-base.css
e360478a3dc3a3b316cc94712480f8c5cb1f8e78e5240613deda240ac4c16abe src/admin/web/css/20-shell.css e360478a3dc3a3b316cc94712480f8c5cb1f8e78e5240613deda240ac4c16abe src/admin/web/css/20-shell.css
0d4e3b1de575b886a8614d682a94fd43fa88a6a3ed85dfa5a5d940a622add5cb src/admin/web/css/30-overview.css 0d4e3b1de575b886a8614d682a94fd43fa88a6a3ed85dfa5a5d940a622add5cb src/admin/web/css/30-overview.css
46103ca55fe2fcb888a0e2ad7f53c75b8a908805c30412a994cc083bef85aefc src/admin/web/css/40-editors.css 46103ca55fe2fcb888a0e2ad7f53c75b8a908805c30412a994cc083bef85aefc src/admin/web/css/40-editors.css
ae86be4089f4d64336cb054cb4283bfebff35ecfe1f47520c5e7f9a3a0b7a9a3 src/admin/web/css/50-settings.css 53ceb0dc4b958f1eded1e1a0e58e585ef13e4ebb45b797ba1b8534b552ea6c16 src/admin/web/css/50-settings.css
dc1fcfcd9b53b97b6683e804c45433cd53236f97b6e80fccef40884f304f986b src/admin/web/css/60-monitoring.css dc1fcfcd9b53b97b6683e804c45433cd53236f97b6e80fccef40884f304f986b src/admin/web/css/60-monitoring.css
10099d160c4fd1ed153d085dd4267661bc1ae119594a650354a93b5dd0f60e16 src/admin/web/css/70-responsive.css 10099d160c4fd1ed153d085dd4267661bc1ae119594a650354a93b5dd0f60e16 src/admin/web/css/70-responsive.css
8009afdb04d5170687816730cc930a22fead1fe0248835ca7e8de81d6907395d src/admin/web/css/README.md 8009afdb04d5170687816730cc930a22fead1fe0248835ca7e8de81d6907395d src/admin/web/css/README.md
@@ -377,14 +380,14 @@ e26dce02df9c043329ca164fed215d271781bce8fb03240f528331bf3df6b9d7 src/cache/poli
20d4af129be642f727f3de694abe9404210dd0210dc56124028d62c2f8dd4649 src/cache/policy/response.rs 20d4af129be642f727f3de694abe9404210dd0210dc56124028d62c2f8dd4649 src/cache/policy/response.rs
12a6d5d9d6711e956391b4b952e8149658b8bf64cfcc0a4c59c281f2630a6aac src/cache/policy/scope_tests.rs 12a6d5d9d6711e956391b4b952e8149658b8bf64cfcc0a4c59c281f2630a6aac src/cache/policy/scope_tests.rs
c3a4300f7cdb6b2b7c16fbc489d49ba2451331bb4a55a2d9f618c684fd61eecb src/cache/range.rs c3a4300f7cdb6b2b7c16fbc489d49ba2451331bb4a55a2d9f618c684fd61eecb src/cache/range.rs
847fd250a795a554fa10176d439fb4e777d3dc75f90aeafb29b133a313c09eb9 src/cache/rules.rs 617294b2d3aba5857f640ea88afcaf2ed41f624145559266de4d121af805364c src/cache/rules.rs
1e2dc5e75085fd40f7febabaf8154021c9040dfa626346c84b92a96dc0be91b6 src/cache/rules_tests.rs 20451b3e662b6d7b2a58a838c0cb60814458bd1d662de36c5b505ef099985eac src/cache/rules_tests.rs
48344d7dcbbb220d8c16f5aa9bb88d86a6388b226bbf93d0ca92d8dfbf2c8001 src/cache/stats.rs 48344d7dcbbb220d8c16f5aa9bb88d86a6388b226bbf93d0ca92d8dfbf2c8001 src/cache/stats.rs
2981e35a7fbbc2b36214b5518f4ba97d57c1d2e01f4f375175c4b2c6be955927 src/cache/tests.rs 2981e35a7fbbc2b36214b5518f4ba97d57c1d2e01f4f375175c4b2c6be955927 src/cache/tests.rs
b969394b04859b269dcecd8958b1aab40b532709512714e9900f0ecad6b6d0c5 src/cache/tickets.rs b969394b04859b269dcecd8958b1aab40b532709512714e9900f0ecad6b6d0c5 src/cache/tickets.rs
a1132b980833b1b4ce2bba9aa681ff255a0e2d61faaa65a316860da503ea1e27 src/cache/v022_cache_tests.rs a1132b980833b1b4ce2bba9aa681ff255a0e2d61faaa65a316860da503ea1e27 src/cache/v022_cache_tests.rs
adac3b8de21a73f32d784b3fd2240d17309e8fce022163710e781d44ef590117 src/cache/varnish_compatible_tests.rs adac3b8de21a73f32d784b3fd2240d17309e8fce022163710e781d44ef590117 src/cache/varnish_compatible_tests.rs
978397b19719afa6f27e17ec88fcbf02d770a73d72950499157c3ef6fa1fc0da src/cache/vcl.rs b89d95622389915e355976fd62488bdaa188e9bf0feca2965e29634925e91dca src/cache/vcl.rs
1a2eb6684d9ea4a7e90970d936c75f7c8bbec46a4181fdf273be9bdac8eec847 src/compression/mod.rs 1a2eb6684d9ea4a7e90970d936c75f7c8bbec46a4181fdf273be9bdac8eec847 src/compression/mod.rs
8de82d9188c9c337690c6ec4afdad9fff20651c358e34602a93d8bb8c3d2489a src/compression/tests.rs 8de82d9188c9c337690c6ec4afdad9fff20651c358e34602a93d8bb8c3d2489a src/compression/tests.rs
e695079333ebdc2a6e7b3337cfabef171b3a0a01da0597b77feff70d417f833e src/config.rs e695079333ebdc2a6e7b3337cfabef171b3a0a01da0597b77feff70d417f833e src/config.rs
+15 -4
View File
@@ -9,17 +9,28 @@ 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. **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.
### Ready-made quick rules library
The **Add from template** dropdown is grouped by scenario. **Browse scenarios** opens a searchable panel with descriptions and one-click **Add** buttons for ready-made request, response and delivery rules. The library includes common application sessions, WordPress/WooCommerce, Django, Laravel, Auth.js, API and private routes, SSE/webhooks, TTL for verified public content and defensive headers. Some scenarios add multiple rules. Templates with a risk of unexpected shared-cache reuse are **disabled until reviewed**. The CDN and exact-name parent-domain cookie templates stay separate. See [Quick rules template library](CACHE_TEMPLATE_LIBRARY.md) for categories, order, defaults and tests. Adding rules changes the draft; save settings before relying on them.
### CDN security cookies (opt-in VCL template) ### 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.** 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.**
### Inherited cookies on public Vhosts (opt-in, disabled by default) ### Parent-domain cookies: opt-in per-Vhost name filtering
A parent domain may set `Set-Cookie: name=value; Domain=.example.test`, causing browsers to send it to *all* subdomains. A received `Cookie` header contains only names and values: RustProxy **cannot determine the source Domain** or whether a cookie was set by the current subdomain. The preferred fix is to make the cookie host-only at the issuing application (omit `Domain`), if it is not meant for sibling hosts. A parent domain may set `Set-Cookie: name=value; Domain=.example.test`, making browsers send it to subdomains. The incoming `Cookie` header **does not include the Domain attribute**: RustProxy cannot distinguish the parent cookie from a cookie with the same name set by this Vhost. Prefer configuring host-only cookies (omit `Domain`) at the issuing application.
For a subdomain that serves **exclusively public, cookie-independent GET/HEAD pages**, the Vhost **Cache rules → Add from template → Public vhost: ignore inherited cookies** template is available. It is deliberately **disabled when added**, absent from the global template menu, and must be reviewed before enabling. The template strips **all incoming request cookies** before lookup **and** before forwarding to the origin, only for GET/HEAD with Cookie, without `Authorization`, and outside its conservative private-path exclusion regex. The path regex is only an example; adapt it to the application. Do not use on logged-in pages, language/session-dependent pages, checkout, downloads, CSRF or custom authenticated paths. A public page must return identical body and headers regardless of Cookie; otherwise do not enable the rule. The independently importable VCL equivalent is [`examples/vcl/public-vhost-ignore-cookies.vcl`](../examples/vcl/public-vhost-ignore-cookies.vcl). Two **separate** opt-in templates remain available in the Vhost cache-rule editor:
This rule does not remove an origin `Vary: Cookie` header. Since Cookie has been removed from the request before lookup and the backend fetch, all eligible requests compare the **absent** Cookie variant. RustProxy still requires normal response eligibility: `Cache-Control` privacy, `Set-Cookie`, response `Vary`, authentication and route checks remain active. If the origin emits an unnecessary `Vary: Cookie` for a truly public page, correct it at the origin rather than unsetting all `Vary` in a deliver-stage rule. Avoid installing the new template *after* a same-scope early `pass` rule for Cookie: stop/return prevents later rules running. Prefer the **per-Vhost editor** and verify `X-Cache-Reason` with a real browser Cookie before rollout. 1. **Vhost: remove selected parent-domain cookies** (inserted **disabled**): the operator supplies an exact comma-separated list of **non-session** cookie names in the `Remove only named cookies` action, replacing `REPLACE_WITH_VERIFIED_PARENT_COOKIE_NAME`. Only those names are removed from incoming GET/HEAD requests; every other cookie, including the application's session, stays intact. The rule has **no** `return(hash)` and **does not stop** subsequent cache rules. It excludes Authorization and example private paths; review the path list for your application. The example is [`examples/vcl/public-vhost-remove-parent-cookies.vcl`](../examples/vcl/public-vhost-remove-parent-cookies.vcl).
2. **CDN technical cookies** (independent, unchanged): its safe-method/private-path/Authorization guards, its anchored whole-header CDN cookie allowlist and **CDN: bypass remaining cookies** continue to run after parent cookie removal. It never treats a remaining session cookie as a CDN cookie. See [`examples/vcl/cdn-technical-cookies.vcl`](../examples/vcl/cdn-technical-cookies.vcl).
**Order:** place the parent-name rule **above** `CDN: remove ONLY technical cookies` and especially **above** `CDN: bypass remaining cookies`; leave the CDN guard rules active at the top. **Delete/disable any old `Public vhost: ignore inherited cookies` rule that uses `strip_cookies: keep=[]` + `lookup`**. Updating the binary does not remove existing saved rules. Never add an application session cookie, login token, CSRF token, locale/personalization cookie or sticky-session identifier to the parent-name list. Do not wildcard cookie names. If the same cookie name can belong to the parent **and** this application, use host-only cookies at the issuer instead of the removal rule.
Resulting request behavior on public pages: `Cookie: parent_marketing=1` (listed) → stripped → cache eligible; `Cookie: parent_marketing=1; __cf_bm=2` → parent removed by this rule, then CDN removed by its separate template → eligible; `Cookie: parent_marketing=1; app_session=abc` → only parent removed, session retained → CDN remaining-cookie rule **BYPASS**; POST, Authorization and private paths are not rewritten by the new template. Verify each using **Cache rule tester** and live `X-Cache-Reason` headers. Responses with `Set-Cookie`, `private` or `no-store` still cannot enter shared storage. The origin's `Vary: Cookie` stays intact and is evaluated against the **remaining** Cookie value. Configure logged-in origin responses as `private, no-store` as defense in depth.
The import syntax `remove_req_cookies("name1", "name2");` is a **RustProxy-specific VCL extension**, not stock Varnish syntax. It performs exact, case-sensitive name matching, preserves other cookies, and refuses to rewrite malformed Cookie fields. A graphical `Remove only named cookies` action uses the same implementation. This new action is not the dangerous `Strip cookies` / "keep" operation, which can remove other cookies.
**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. **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.
+163
View File
@@ -0,0 +1,163 @@
# Cache rule template library: all 42 scenarios
**Applies to RustProxy 0.39.1.** This reference documents the 42 scenarios shipped by the graphical **Add from template...** and **Browse scenarios** controls. It describes the rules actually generated by `src/admin/web/cache-rules.js`, including their initial enabled state, exact matching scope, effects and limitations. The seven sections below follow the panel's category order.
These are **graphical cache rules**, not scripts executed by a Varnish VCL engine. The panel can export a readable VCL preview, but that export is not a lossless rule backup. For the VCL import subset, see [VCL.md](VCL.md); for copyable VCL examples, see the [traffic cookbook](VCL_TRAFFIC_COOKBOOK.md).
## Add, configure and activate a template
1. Open **Vhost -> Cache -> Cache rules** (including a Docker-generated Vhost), or **Settings -> Cache -> Rules** for global rules. Only Vhost editors offer the parent-domain cookie template.
2. Choose **Add from template...**, or open **Browse scenarios**, search by name/description and click **Add**. A scenario inserts **one or more ordinary rules**. Adding does not save the configuration.
3. Expand the new rules. Check the match mode (**all** vs **any**), paths, cookie names, headers and TTL. Enable rules marked **Off** only after adaptation. Review their order relative to other Vhost and global rules.
4. Use **Test a request** with anonymous, session-cookie, `Authorization` and sensitive-path examples. Save the settings, test with real GET requests and inspect `X-Cache`, `X-Cache-Reason`, `Age` and `Cache-Status`.
5. **Purge existing cache entries** after changing privacy or representation boundaries. New no-store or BYPASS rules cannot retrospectively remove already-stored objects.
A template is **On** if its generated rule(s) are enabled when inserted; **Off** means deliberate opt-in is required. **Request** rules alter or bypass a request before cache lookup; **response** rules control backend response storage; **deliver** rules change outgoing response headers, including on HIT. **Deliver-only `Cache-Control: no-store` does not disable RustProxy's shared cache.** Multi-rule scenarios insert all their rules together; exceeding the 128-rule limit rejects the group.
## 1. Security and private content (15 scenarios)
| Template (internal key) | Rules / default | Match and precise behavior | Configuration / caveat |
|---|---|---|---|
| **Methods other than GET/HEAD** (`safemethods`) | 1 request, **On** | Method is not GET or HEAD -> `pass` (BYPASS). | Usually a safe guard for forms and writes. Other method restrictions still come from RustProxy's normal cache policy. |
| **Authorization** (`authbypass`) | 1 request, **On** | An `Authorization` request header exists -> `pass`. | Applies to any route. Do not try to compensate by removing the header. |
| **Any Cookie** (`cookiepass`) | 1 request, **On** | Any `Cookie` header exists -> `pass`. | Conservative for unknown apps; place **after** a selective parent-domain/CDN cleanup if those cookies should be ignored. |
| **Common session cookies** (`sessioncookies`) | 1 request, **On** | Cookie header contains an exact cookie-name boundary for `session`, `sessionid`, `PHPSESSID`, `laravel_session`, `connect.sid` or `sid` -> `pass`. | Not an exhaustive session list. Add app-specific names or use **Any Cookie** as a fallback. |
| **Private account routes** (`privateroutes`) | 3: request + response + deliver, **On** | Paths starting with a complete segment `admin`, `auth`, `login`, `logout`, `user`, `users`, `account`, `profile`, `settings`, `dashboard`, `cart`, `checkout`, `orders`, `billing` or `payment`: `pass`, block storage and deliver `Cache-Control: private, no-store`. | Review locale prefixes, custom account URLs and API routes. Purge previously cached responses. |
| **Preview or draft links** (`preview`) | 1 request, **On** | Path segment `/preview` or `/draft`, **or** a `preview`/`draft` query parameter -> `pass`. | Add other preview token names as needed. A query parameter's mere presence is sufficient. |
| **Cart / checkout / payments** (`checkout`) | 1 request, **On** | `/cart`, `/checkout`, `/payment`, `/billing`, `/order`, `/orders` (and descendants) -> `pass`. | Does not by itself send browser no-store; configure application/private responses accordingly. |
| **Webhooks / callbacks** (`webhooks`) | 1 request, **On** | `/webhook`, `/webhooks`, `/callback`, `/callbacks` or `/hooks` (and descendants) -> `pass`. | Adapt nonstandard callback endpoints. This changes cache routing, not webhook authentication. |
| **Health and metrics** (`healthchecks`) | 1 request, **On** | `/health`, `/healthz`, `/readyz`, `/livez`, `/metrics`, `/status` -> `pass`. | Does not block public access to those endpoints; protect sensitive metrics separately. |
| **GraphQL** (`graphql`) | 1 request, **On** | `/graphql` and descendants -> `pass` even for GET requests. | Conservative when GraphQL queries can depend on the user. Other GraphQL endpoint paths need separate rules. |
| **SSE and WebSocket** (`streaming`) | 1 request, **On** | `Accept` contains `text/event-stream` **or** an `Upgrade` request header exists -> `pass`. | Streaming/upgrades should not be served from a normal HTTP object cache. |
| **Signed query URLs** (`signedurls`) | 1 request, **On** | Query contains any of `token`, `access_token`, `signature`, `sig`, `auth_token` -> `pass`. | Update the list for the app's signed parameter names. The rule matches name presence, not token validity. |
| **All HTML no-store** (`nocachehtml`) | 2: response + deliver, **On** | Backend `Content-Type` begins `text/html`: prevent shared-cache storage and deliver browser `Cache-Control: no-store`. | **No request-stage pass** is added. Purge old HTML objects to avoid serving pre-existing HITs. |
| **Private API** (`privateapi`) | 3: request + response + deliver, **On** | Path starts with `/api/private/`: `pass`, prevent storage and send `Cache-Control: private, no-store`. | Does not automatically cover `/api/private` without `/`, `/v1/...` or other private API prefixes. |
| **Private downloads** (`privatedownloads`) | 2: request + deliver, **Off** | Example prefix `/private-downloads/`: `pass` plus browser `Cache-Control: private, no-store`. | **Replace the sample prefix**, enable both rules and purge older objects. It adds no response-stage `no_store` rule. |
These templates are **cache protections, not authentication or authorization**. The origin must still enforce access control, and should return `Cache-Control: private, no-store` for user-specific responses.
## 2. CMS and framework sessions (7 scenarios)
All seven insert a **request-stage `pass` rule, enabled by default**. They **retain** cookies and forward them to the backend; none rewrites a session cookie.
| Template (internal key) | Trigger | Use and adjustments |
|---|---|---|
| **WordPress** (`wordpress`) | Path begins `/wp-admin`, `/wp-login.php`, `/xmlrpc.php` or `/wp-json`; **or** Cookie contains `wordpress_logged_in_`, `comment_author_`, `woocommerce_items_in_cart` or `wp-postpass_`. | Protects dashboard, login, REST endpoints and common session/comment cookies. Check custom login and REST routes. |
| **WooCommerce** (`woocommerce`) | `/cart`, `/checkout`, `/my-account`; **or** Cookie has `wordpress_logged_in_*`, `woocommerce_items_in_cart`, `wp_woocommerce_session_*` or `woocommerce_cart_hash`. | Protect cart/account/session traffic. Add localized/custom checkout routes and session-cookie names. |
| **Django** (`django`) | Named Cookie `sessionid` exists. | Adjust the exact name if the application overrides `SESSION_COOKIE_NAME`. Does not match a differently named session. |
| **Laravel / PHP** (`laravel`) | Cookie `laravel_session` or `PHPSESSID` exists. | Account for custom PHP/Laravel session names; may need CSRF/private-path rules. |
| **Auth.js / NextAuth** (`authjs`) | Cookie `authjs.session-token` or `next-auth.session-token`, optionally prefixed with `__Secure-`. | Extend for other Auth.js token/session cookie names and custom prefixes. |
| **ASP.NET** (`aspnet`) | Cookie `.AspNetCore.Cookies` or `ASP.NET_SessionId` exists. | Adapt to the app's authentication scheme/custom cookie names. |
| **Drupal** (`drupal`) | Cookie name has `SESS` or `SSESS` followed by one or more hexadecimal characters. | Captures common Drupal session names; confirm site-specific prefixes and authenticated routes. |
A framework template recognizes only the listed paths or cookie names. Where a session could use **any other cookie name**, keep the conservative **Any Cookie** guard (after any verified cookie cleanup) until the app has been audited.
## 3. CDN and inherited cookies (2 independent scenarios)
| Template (internal key) | Rules / default | Exact effect | Deployment notes |
|---|---|---|---|
| **CDN technical cookies** (`cdn`) | 5 request rules, all **On** | `pass` non-GET/HEAD; `pass` `/admin`, `/api`, `/auth`, `/login`, `/logout`, `/panel`, `/konto`, `/dashboard`; `pass` `Authorization`; strip **the entire Cookie header only if every cookie name** belongs to the fixed Cloudflare/Akamai technical list; then `pass` if any Cookie remains. | Do not replace the anchored allowlist with a contains/substring match. Cookie names: `__cf_bm`, `cf_clearance`, `_cfuvid`, `__cfruid`, `__cfseq`, `_abck`, `ak_bmsc`, `bm_sz`, `bm_sv`. Use only if those values are irrelevant to the origin's representation. |
| **Selected parent-domain cookies** (`publiccookies`) | 1 request rule, **Off**; **Vhost-only** | Only on GET/HEAD with Cookie, without Authorization and outside specified private prefixes: remove **only exact cookie names** entered by the operator; no forced cache lookup and no `stop`. | Replace `REPLACE_WITH_VERIFIED_PARENT_COOKIE_NAME` with verified, nonsession names. Other cookies remain and can trigger the CDN remaining-cookie `pass` guard. |
**Safe order for a Vhost using both:**
1. CDN method, private-path and Authorization `pass` guards.
2. **Selected parent-domain cookies** (only verified names; enabled after review).
3. CDN technical-cookie stripping (only technical-only Cookie headers).
4. CDN **BYPASS remaining cookies** guard.
A separate **Any Cookie** guard should also follow the cookie cleanup if used. The parent-domain template is automatically inserted before existing CDN stripping/remaining-cookie rules **within the same editor**; it does not rearrange saved rules in another scope. Vhost-stage rules are evaluated ahead of applicable global rules. Never enable an old **ignore all inherited cookies** rule that calls `strip_cookies` for every name and then forces lookup.
**Why names must be verified:** request `Cookie` carries *names and values*, not the `Domain` attribute that originally set the cookie. RustProxy cannot automatically tell whether it came from a parent host. If the parent site and application use the **same** cookie name for different purposes, name-based deletion is unsafe. Prefer host-only cookies at the issuer or an explicit per-route design instead. Removing a Cookie changes both the cache decision **and** what the backend receives.
For copyable VCL syntax, see [parent-domain cookie removal](VCL_TRAFFIC_COOKBOOK.md#12-parent-domain-cookies-remove-selected-names-opt-in), [`public-vhost-remove-parent-cookies.vcl`](../examples/vcl/public-vhost-remove-parent-cookies.vcl) and [`cdn-technical-cookies.vcl`](../examples/vcl/cdn-technical-cookies.vcl). The selective `remove_req_cookies(...)` instruction is a **RustProxy extension**, not standard Varnish VCL.
## 4. Public content and cache TTL (10 scenarios)
Response-stage TTL rules only affect *otherwise eligible* responses. They do not override private/no-store cache policy, `Set-Cookie`, `Vary`, authentication, object limits or the **HTTP 200 only** storage restriction in RustProxy 0.39.1. They do not necessarily change `Cache-Control` seen by a browser.
| Template (internal key) | Rules / default | Match and actions | Enable only when... |
|---|---|---|---|
| **Public JSON API** (`publicjson`) | 1 response, **Off** | Prefix `/api/public/`, status 200 and `Content-Type: application/json*` -> TTL **60 s**, grace **30 s**. | API payload is identical for all eligible users and its `Vary`/cache headers are correct. |
| **Blog / catalog HTML** (`publicpages`) | 1 response, **Off** | `/blog`, `/news`, `/articles`, `/catalog`, `/products` and descendants; status 200, `text/html*` -> TTL **300 s**, grace **60 s**. | Pages do not contain per-user names, carts, account data or other personalized fragments. |
| **RSS / Atom** (`feeds`) | 1 response, **Off** | `/feed`, `/rss`, `/rss.xml`, `/atom.xml` and descendants; status 200 -> TTL **600 s**. | Feeds are public; review any authenticated/custom feed endpoints. |
| **Sitemap XML** (`sitemap`) | 1 response, **Off** | `/sitemap.xml`, `/sitemap_index.xml` or `/sitemap/...`; status 200 -> TTL **3600 s**. | Sitemap URLs are stable/public and updates can tolerate up to an hour of caching. |
| **Filename-hashed assets** (`hashedassets`) | 1 response, **Off** | Under `/assets/`, `/static/`, `/build/` with a hash-like filename segment (at least 8 allowed characters), known JS/CSS/image/font extension and status 200 -> TTL **31,536,000 s** (1 year). | Filenames really change on content updates; the pattern itself cannot prove immutability. |
| **Images** (`imagecache`) | 1 response, **Off** | Extensions `png`, `jpg`, `jpeg`, `webp`, `avif`, `gif`, `svg`; status 200 -> TTL **86,400 s** (1 day). | No private avatars, signed assets or user-specific image URLs are matched. |
| **Fonts** (`fontcache`) | 1 response, **Off** | Extensions `woff`, `woff2`, `ttf`, `otf`; status 200 -> TTL **2,592,000 s** (30 days). | Font files and licensing/access requirements allow public reuse. |
| **Search results** (`searchttl`) | 1 response, **Off** | Path starts with `/search` and status 200 -> TTL **15 s**. | Responses are genuinely public. Prefix also matches similar paths such as `/searchable`; narrow it if needed. |
| **Static files: strip cookies + TTL** (`static`) | 2: request + response, **On** | Known static extensions: remove **all request cookies**. On status 200 set TTL **2,592,000 s** (30 days) and remove backend `Set-Cookie`. | **Audit carefully:** this existing template changes what the origin receives and can be unsafe for protected/downloaded resources whose path looks static. |
| **Remove tracking query params** (`tracking`) | 1 request, **On** | Remove `utm_*`, `fbclid`, `gclid`, `msclkid`, `mc_cid`, `mc_eid`, `_ga` from the request URL/cache key. | The backend never uses those parameters to choose response contents, permissions or redirects. |
**Important distinction:** the `static` and `tracking` legacy templates start **On**, unlike the eight newly introduced TTL scenarios. Review them when the Vhost serves protected or parameter-dependent resources.
## 5. Cache-key variants (1 scenario)
| Template (internal key) | Rules / default | Behavior | Limitation |
|---|---|---|---|
| **Language cookie** (`language`) | 1 request, **On** | Add the named `lang` cookie to RustProxy's internal cache variant key (`hash_cookie`). | This does **not** bypass the ordinary request-cookie restriction and does **not** automatically generate downstream `Vary: Cookie`. Align the origin's representation policy and actual language cookie name. |
## 6. Outgoing response headers (6 scenarios)
These run at the **deliver** stage. Unless accompanied by request/response rules, they do not affect whether RustProxy reads or writes shared cache objects.
| Template (internal key) | Rules / default | Match and action | Limitations |
|---|---|---|---|
| **Hide X-Powered-By** (`headers`) | 1 deliver, **On** | Remove outgoing `X-Powered-By` for every response. | Does not change a header already stored in the cache object or remove other information leaks. |
| **Browser-cache static assets** (`browser`) | 1 deliver, **On** | Known CSS/JS/image/font extensions, status 200 -> `Cache-Control: public, max-age=2592000` (30 days). | This also changes outgoing headers on BYPASS. Use only for genuinely public static resources. |
| **No browser cache for HTML/admin** (`nobrowser`) | 1 deliver, **On** | **Any** of: `Content-Type` starts `text/html`, path starts `/admin` or path starts `/account` -> `Cache-Control: no-store`. | **Only browser cache** is affected. Add response `no_store` or a request `pass` rule to prevent shared-cache reuse. |
| **Default security headers** (`security`) | 1 deliver, **On** | If absent, set `X-Content-Type-Options: nosniff` and `Referrer-Policy: strict-origin-when-cross-origin`. | Does not overwrite existing origin values. Review security policy with the application. |
| **Staging noindex** (`stagingnoindex`) | 1 deliver, **Off** | If absent, set `X-Robots-Tag: noindex, nofollow` on all responses. | Preventing search indexing is **not** access control; enable only on staging/private search surfaces after review. |
| **Frame protection** (`frameguard`) | 1 deliver, **Off** | If absent, set `X-Frame-Options: SAMEORIGIN` on all responses. | May break legitimate embedding or iframe flows; adapt to the site's CSP and embedding requirements. |
## 7. Other / broad API protection (1 scenario)
| Template (internal key) | Rules / default | Behavior | Limitations |
|---|---|---|---|
| **API: bypass cache** (`api`) | 1 request, **On** | Path starts `/api/` -> `pass`. | Covers both private and public API endpoints. It does not send browser `no-store`; for public JSON caching remove or narrow this broad pass guard first. |
## Rule-order pitfalls
- **`pass` takes precedence over later request edits:** if **Any Cookie** or **CDN BYPASS remaining cookies** runs first, a later parent-name cleanup rule never gets a chance to remove irrelevant cookies. This is the typical reason a browser shows `X-Cache: BYPASS` with `X-Cache-Reason: cache_rule` while a cookie-free `curl` gets HIT.
- **A `pass` after selective cleanup still sees app sessions:** `parent_analytics=1; app_session=abc` must become `app_session=abc`, and the remaining-cookie guard must BYPASS. Never force `lookup` to override this.
- **Global vs Vhost scope matters:** matching Vhost rules run before applicable global rules. Ordering controls in one list do not reorder the other list. A terminal request action stops further normal request-stage evaluation; response and deliver stages are separate.
- **A broad API guard can defeat public API TTL:** request `pass` on `/api/` makes a response-stage public JSON TTL irrelevant. Narrow the prefix or use a dedicated public route when desired.
- **Browser `Cache-Control` is not proxy cache policy:** a deliver-only `no-store` or `public` header can differ from RustProxy's internal HIT/MISS decision. Protect user-specific content in request/response stages and at the origin.
- **`Vary` matters:** a response with `Vary: Cookie` or `Vary: Accept-Encoding` can legitimately produce separate variants. A browser refresh can send `Cache-Control: no-cache` or `max-age=0`; inspect the original request headers before concluding the cache is broken.
## Verification matrix
Use the panel's **Test a request** first, then verify with repeated real GET requests. Expected results below assume the relevant templates are enabled and ordered as described:
| Request | Expected behavior |
|---|---|
| Anonymous `GET /catalog` | Normal cache eligibility; first GET can be MISS, next can be HIT. |
| `GET /catalog` with **only** a verified parent cookie | Exact name removed; lookup may proceed. |
| Same URL with `parent_analytics=1; app_session=abc` | Parent cookie removed, session retained -> later BYPASS. |
| Cookie header containing only listed CDN technical cookies | CDN template may remove the entire technical-only header; lookup may proceed. |
| Mixed CDN technical cookie and session | CDN filter does **not** strip the mixed header -> BYPASS. |
| `GET /account/orders` | Private-path rule -> BYPASS, backend no-store, browser `private, no-store`. |
| `GET /api/private/me` | Private API rule -> BYPASS and no-store. |
| `GET /?preview=1` | Preview rule -> BYPASS. |
| `GET /graphql` | GraphQL rule -> BYPASS. |
| `POST /checkout` | Non-GET/HEAD or checkout rule -> BYPASS. |
| Anonymous `GET /api/public/items` with public 200 JSON | Potential TTL 60 s only if public JSON was enabled **and** no broader `/api/` pass rule matched. |
Example HTTP test (use **the same URL and GET method** repeatedly):
```bash
URL="https://example.com/catalog"
for i in 1 2 3; do
curl -sS -o /dev/null -D - "$URL" \
| grep -Ei '^(HTTP/|x-cache:|x-cache-reason:|age:|cache-status:)'
done
# Separate expected BYPASS test for an app session cookie:
curl -sS -o /dev/null -D - \
-H 'Cookie: app_session=example' "$URL" \
| grep -Ei '^(x-cache:|x-cache-reason:|cache-status:)'
```
In case of unexpected results, compare the browser's **request** `Cookie`, `Authorization`, `Cache-Control`, exact URL, method and `Accept-Encoding` against curl. Use the tester's matched-rule names; check Vhost vs global scope and the placement of any terminal `pass`. Check the backend's `Cache-Control`, `Set-Cookie`, status and `Vary` before changing storage rules.
See also [Cache](CACHE.md), [VCL support matrix](VCL_SUPPORT_MATRIX.md), [VCL traffic cookbook](VCL_TRAFFIC_COOKBOOK.md) and [Security](SECURITY.md).
+2 -1
View File
@@ -73,7 +73,8 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se
- Optional minification of JavaScript, CSS, HTML, SVG and JSON with memory budgets. - Optional minification of JavaScript, CSS, HTML, SVG and JSON with memory budgets.
![Cache](images/cache.png) ![Cache](images/cache.png)
- Opt-in disabled-by-default per-Vhost template for fully public pages to ignore all inherited parent-domain cookies on GET/HEAD (with Authorization/private-path guards); no global cookie strip or source-domain guessing. - Searchable **quick-rule template gallery** in global/Vhost/Docker cache editors: grouped ready-made session/privacy, CMS/framework, CDN/parent-cookie, API/GraphQL, public TTL, static assets and response-header scenarios. Risky cache-acceleration templates are disabled until reviewed; examples are documented in [Quick rules library](CACHE_TEMPLATE_LIBRARY.md).
- Separate disabled-by-default per-Vhost template for exact-name removal of verified non-session parent-domain cookies; unrelated/session cookies survive and the unchanged CDN template can independently strip CDN-only cookies or bypass remaining sessions. No automatic cookie Domain detection.
- 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. - 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). - **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).
+2 -1
View File
@@ -37,7 +37,8 @@ Guides for operating RustProxy: installation, publishing services, security, cer
## Performance and delivery ## 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. - [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) — 12 ready-to-import examples, public/private HTTP traffic cases, Cookie/`Vary` variants, `curl` verification and failure modes. - [Quick rules template library](CACHE_TEMPLATE_LIBRARY.md) — searchable grouped scenarios for sessions, CDN/parent cookies, frameworks, public APIs, assets, no-store and security headers; defaults, risks and smoke tests.
- [VCL traffic cookbook](VCL_TRAFFIC_COOKBOOK.md) — 12 ready-to-import examples, separate name-selective parent-domain and CDN cookie rules, 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. - [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. - [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. - [Response delivery](RESPONSE_DELIVERY.md) — compression, transformations and response headers.
+4 -3
View File
@@ -4,7 +4,7 @@ This guide describes the VCL **subset implemented by RustProxy 0.39.1**, 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 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, **12 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. For the **complete reference to all 42 quick-rule templates** (conditions, stages, defaults, cookie/session safety, TTL and testing), see the [Cache rule template library](CACHE_TEMPLATE_LIBRARY.md). These graphical presets are distinct from directly importable VCL. 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, **12 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 ## Where to import, rule order and activation
@@ -21,6 +21,7 @@ For an expanded **implemented / restricted / graphical-only / intentionally excl
| `vcl_recv` | `return(pass);` | Stops request processing for the matching path; bypasses shared cache. | | `vcl_recv` | `return(pass);` | Stops request processing for the matching path; bypasses shared cache. |
| `vcl_recv` | `return(hash);` or `return(lookup);` | Stops `vcl_recv` and requests a cache lookup. In compatibility mode, may admit a GET/HEAD carrying `Cookie` (with cookie-partitioned variants); other protections remain. | | `vcl_recv` | `return(hash);` or `return(lookup);` | Stops `vcl_recv` and requests a cache lookup. In compatibility mode, may admit a GET/HEAD carrying `Cookie` (with cookie-partitioned variants); other protections remain. |
| `vcl_recv` | `unset req.http.Cookie;` | Removes the **whole** request Cookie header, including what is forwarded to the origin. | | `vcl_recv` | `unset req.http.Cookie;` | Removes the **whole** request Cookie header, including what is forwarded to the origin. |
| `vcl_recv` | `remove_req_cookies("parent_analytics");` | **RustProxy extension:** removes only the specified exact-name cookie(s) from the request before later rules, cache lookup and origin forwarding. Remaining session cookies are not removed and can still trigger BYPASS. Not standard Varnish VCL. |
| `vcl_recv` | `set req.http.X-Device = "mobile";` / `unset req.http.X-Tracking;` | Sets/removes a **safe request header** before later conditions, `vcl_hash`, cache policy and the forwarded origin request. Assignments are constant strings, and a per-vhost edit takes priority over a conflicting global edit. Authentication, identity, request cache policy and transport headers are protected (see below). | | `vcl_recv` | `set req.http.X-Device = "mobile";` / `unset req.http.X-Tracking;` | Sets/removes a **safe request header** before later conditions, `vcl_hash`, cache policy and the forwarded origin request. Assignments are constant strings, and a per-vhost edit takes priority over a conflicting global edit. Authentication, identity, request cache policy and transport headers are protected (see below). |
| `vcl_recv` | `set req.url = regsuball(req.url, "([?&])(utm_[^=&]*|gclid)=[^&]*", "\1");` | **Restricted conversion only:** recognizes the specific captured-separator, query-parameter-removal pattern. Other `regsub` / `regsuball` rewrites are skipped with warnings; arbitrary URL regex replacement is not supported. | | `vcl_recv` | `set req.url = regsuball(req.url, "([?&])(utm_[^=&]*|gclid)=[^&]*", "\1");` | **Restricted conversion only:** recognizes the specific captured-separator, query-parameter-removal pattern. Other `regsub` / `regsuball` rewrites are skipped with warnings; arbitrary URL regex replacement is not supported. |
| `vcl_hash` | `hash_data(req.http.X-Name);` | Adds one request header's value to RustProxy's **internal** variant key. It does not automatically add `Vary` for downstream caches. | | `vcl_hash` | `hash_data(req.http.X-Name);` | Adds one request header's value to RustProxy's **internal** variant key. It does not automatically add `Vary` for downstream caches. |
@@ -55,7 +56,7 @@ sub vcl_hash {
Both header edits are visible to later matching rules, the hash calculation and the origin. They also run on cache-disabled reverse-proxy routes (without enabling cache). They **do not** rewrite the client's original `Vary` requirements: if the response varies by `X-Device`, include it in `beresp.http.Vary` or configure it at the origin. A later `unset` is different from setting an empty string. Both header edits are visible to later matching rules, the hash calculation and the origin. They also run on cache-disabled reverse-proxy routes (without enabling cache). They **do not** rewrite the client's original `Vary` requirements: if the response varies by `X-Device`, include it in `beresp.http.Vary` or configure it at the origin. A later `unset` is different from setting an empty string.
Protected request headers cannot be set or removed by general request rules: `Authorization`, `Cookie` (except the existing dedicated whole-header `unset`), `Cache-Control`, `Pragma`, `Host`, range/precondition headers (`If-*`, `Range`), forwarding and origin identity headers (`Forwarded`, `Via`, `X-Forwarded-*`, `X-Real-IP`, `X-Client-IP`, `CF-Connecting-IP`, `True-Client-IP`), `Proxy-*`, `Sec-*`, `X-RustProxy-*`, `Content-Type`, `Expect` and the protected transport/body header list below. Rejected edits are warned about and never silently applied. Do not assume imported VCL can change authentication or request-cache restrictions. Protected request headers cannot be set or removed by general request rules: `Authorization`, `Cookie` (except dedicated whole-header `unset` or exact-name `remove_req_cookies(...)` actions), `Cache-Control`, `Pragma`, `Host`, range/precondition headers (`If-*`, `Range`), forwarding and origin identity headers (`Forwarded`, `Via`, `X-Forwarded-*`, `X-Real-IP`, `X-Client-IP`, `CF-Connecting-IP`, `True-Client-IP`), `Proxy-*`, `Sec-*`, `X-RustProxy-*`, `Content-Type`, `Expect` and the protected transport/body header list below. Rejected edits are warned about and never silently applied. Do not assume imported VCL can change authentication or request-cache restrictions.
The query-removal conversion accepts only the supported captured-separator `regsuball` pattern. **Every such conversion emits a warning**, because removing parameters with RustProxy's parser can normalize separators differently from a regex replacement. Variable-name classes such as `utm_[a-z]+` are approximated by a prefix wildcard; value patterns ending in `[^&]+` may preserve empty values that `strip_query` removes. **Review generated parameters and warnings** if byte-exact URL behavior matters. Other URL rewrites are deliberately **not** guessed from keywords such as `utm_`. The query-removal conversion accepts only the supported captured-separator `regsuball` pattern. **Every such conversion emits a warning**, because removing parameters with RustProxy's parser can normalize separators differently from a regex replacement. Variable-name classes such as `utm_[a-z]+` are approximated by a prefix wildcard; value patterns ending in `[^&]+` may preserve empty values that `strip_query` removes. **Review generated parameters and warnings** if byte-exact URL behavior matters. Other URL rewrites are deliberately **not** guessed from keywords such as `utm_`.
@@ -147,7 +148,7 @@ sub vcl_recv {
} }
``` ```
Use `unset req.http.Cookie;` only when the origin does not need **any** cookies for that route. For a public Vhost that receives cookies from its parent domain, see the [opt-in inherited-cookie recipe](VCL_TRAFFIC_COOKBOOK.md#12-public-vhost-inherited-cookies-opt-in). `Cookie` does not disclose the setting `Domain`, so this is an intentional all-cookie removal, not automatic recognition of inherited cookies. A graphical **Strip cookies** action can keep an allowlist (not imported from arbitrary VCL cookie rewriting). In strict RFC mode (`cache.varnish_compatible=false`), `return(hash)` does not bypass the request Cookie restriction. `Authorization`, non-GET/HEAD traffic, request `no-store`, access/authentication and sticky-session checks still apply. Use `unset req.http.Cookie;` only when the origin does not need **any** cookies for that route. For a Vhost that receives cookies from a parent domain, prefer the [name-selective opt-in recipe](VCL_TRAFFIC_COOKBOOK.md#12-parent-domain-cookies-remove-selected-names-opt-in): `remove_req_cookies("exact_cookie_name");` is a **RustProxy-specific extension** that removes only named cookies, preserving session and other cookies for later rules. The separate CDN technical-cookie policy still has its own anchored allowlist and remaining-cookie pass. `Cookie` does not disclose the setting `Domain`, so a name must be verified outside RustProxy; avoid removing a name also used by this Vhost. A graphical **Strip cookies** action keeps an allowlist but is not equivalent to selective removal. In strict RFC mode (`cache.varnish_compatible=false`), `return(hash)` does not bypass the request Cookie restriction. `Authorization`, non-GET/HEAD traffic, request `no-store`, access/authentication and sticky-session checks still apply.
## `no-cache` and TTL ## `no-cache` and TTL
+5 -4
View File
@@ -81,11 +81,12 @@ Do **not** use an unanchored regex such as `req.http.Cookie ~ "__cf_bm"` with `u
|---|---|---| |---|---|---|
| `return(pass);` | Supported | Cache bypass; terminates applicable request-stage rules and skips `vcl_hash`. | | `return(pass);` | Supported | Cache bypass; terminates applicable request-stage rules and skips `vcl_hash`. |
| `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. | | `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. | | `unset req.http.Cookie;` | Supported, risky | Removes **every** Cookie value; never use for a session-bearing Vhost. |
| `remove_req_cookies("exact_name", "another_name");` | Supported, RustProxy extension | Deletes **only** selected exact Cookie names on the request, retaining other cookies for later pass/cache checks; refused on malformed Cookie fields. Not stock Varnish 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. | | `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. | | `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.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.http.Cookie = regsuball(...)`, `regsub()` on cookies | Not implemented | Arbitrary Cookie regex rewrites are unsafe and not imported; use `remove_req_cookies()` or graphical **Remove only named cookies** for selective removal. |
| `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. | | `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(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. | | `return(deliver)` in `vcl_recv` | Not implemented | This is not a supported return target in the request stage. |
@@ -205,9 +206,9 @@ The labels above distinguish explicit product limits from missing work; **not im
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. 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. 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 public-Vhost inherited-cookie policy ### Included opt-in parent-domain cookie rule (separate from CDN)
The graphical **Public vhost: ignore inherited cookies** template (`src/admin/web/cache-rules.js`) is available only in local Vhost/Docker Vhost rule editors and inserted disabled. It deliberately drops the **entire** Cookie header on public GET/HEAD requests, and only if the request does not carry Authorization and the path does not match the operator-reviewed private-path exclusions. It also asks for lookup and stops later request-stage rules. The VCL equivalent is [`examples/vcl/public-vhost-ignore-cookies.vcl`](../examples/vcl/public-vhost-ignore-cookies.vcl). The normal request/response eligibility guards still apply; no shared-cache use of private/no-store or Set-Cookie responses is authorized. The issuing application's host-only `Set-Cookie` is preferable whenever possible. The original cookie's Domain is not transmitted in HTTP Cookie and cannot be inferred; this is a broad, high-impact opt-in rule, not an automatic safe way to discard only parent-domain cookies. The **Vhost: remove selected parent-domain cookies** graphical rule is available only in local Vhost/Docker Vhost editors, inserted disabled. It uses the **Remove only named cookies** action and an operator-edited exact list, not `Strip cookies` / whole-header removal. It applies to GET/HEAD without Authorization and outside example private paths, does **not** return(hash) and does **not** stop later request rules. The equivalent RustProxy-specific VCL `remove_req_cookies("cookie_name");` is imported as `remove_named_cookies`. When a request has parent and session cookies, the session remains; later CDN's `bypass remaining cookies` or RustProxy's default request-cookie guard prevents shared-cache reuse. The operator must verify that the listed name is never used by this Vhost; `Cookie` does not carry the originating Domain. The old whole-header public-Vhost template is no longer offered; remove any already-saved unsafe copy manually.
### Included opt-in CDN cookie policy ### Included opt-in CDN cookie policy
+25 -24
View File
@@ -31,8 +31,8 @@ Read together with [VCL compatibility](VCL.md) and the [supported/unsupported ca
| 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 | | 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 | | 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 | | Admin, login, checkout, user dashboard | [Private routes](#1-exclude-private-routes-and-unsafe-methods) | Bypass shared cache | Replace ACL, OIDC, Basic Auth, app permissions |
| Cookies inherited from a parent domain on a **fully public** Vhost | [Public Vhost inherited cookies](#12-public-vhost-inherited-cookies-opt-in) | Remove **all** Cookie for eligible GET/HEAD after operator review | Detect which cookies came from a parent domain; guarantee safe login/personalization routes | | Cookies set broadly by a parent domain | [Selective parent cookie removal](#12-parent-domain-cookies-remove-selected-names-opt-in) | Remove only **verified exact cookie names**, leaving application sessions intact | Infer which Domain set them; safely delete an overlapping session cookie name |
| 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 | | Cloudflare/Akamai technical cookies | [CDN cookie allowlist](#4-cdn-technical-cookies-without-dropping-sessions) | Strip an **entire** CDN-only Cookie header; separate from parent cookie rule | Treat unknown or session cookies as CDN cookies |
| 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 | | 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 | | 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 | | 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 |
@@ -403,38 +403,37 @@ sub vcl_backend_response {
} }
``` ```
### 12. Public Vhost: inherited cookies (opt-in) ### 12. Parent-domain cookies: remove selected names (opt-in)
**Goal:** Keep cache working on a completely public site when a browser includes unrelated cookies set with `Domain=.example.test` by another host. This is generic for any hostname; **it cannot detect the cookie's original Domain**, which is not part of the HTTP `Cookie` request header. **Goal:** A subdomain receives an unrelated, verified cookie set by a parent domain. Remove only this cookie's *name*, keeping any session/CSRF/authentication cookies for later `BYPASS` rules. The HTTP Cookie request header **does not identify the issuing Domain**. The recommended long-term fix is a host-only `Set-Cookie` at the issuing app.
**Expected traffic:** `GET /catalog`, `Cookie: parent_session=x; analytics=y` → Cookie stripped before cache lookup and before origin forwarding. The origin serves its anonymous public representation; an eligible repeat GET may HIT. `GET /account` or a request with `Authorization` keeps its cookies and follows normal bypass/auth policies. POST is unaffected. **Expected traffic:** `GET /catalog` with `parent_marketing=1; app_session=abc` → remove `parent_marketing`, preserve `app_session`, and then the separate CDN **remaining cookies** rule causes `BYPASS`. With only `parent_marketing=1`, RustProxy may cache eligible anonymous content. With `parent_marketing=1; __cf_bm=2`, the parent rule removes the first and the separate CDN rule removes the second; this allows normal cache lookup. POST, protected paths and Authorization are unaffected.
**Prerequisites:** Use the per-Vhost cache rule editor, confirm that the *entire eligible area* is public for guests and logged-in users, and extend the excluded path regex to cover **all** private routes of the application. The graphical template is **disabled by default** until manually enabled. Avoid installing it globally or after existing terminal Cookie `pass` rules. The safest fix is often to remove the broad `Domain` attribute from `Set-Cookie` at the issuing application so browsers no longer send unrelated cookies to siblings. **Prerequisites:** On the Vhost, add **Vhost: remove selected parent-domain cookies**, replace `REPLACE_WITH_VERIFIED_PARENT_COOKIE_NAME` with the actual verified cookie names in **Remove only named cookies**, review sensitive paths, then enable. Keep the CDN template as its **own group of rules**, with this new rule above `CDN: remove ONLY technical cookies` and `CDN: bypass remaining cookies`. Do not enable a previous **ignore ALL inherited cookies** rule: it could strip login sessions and force cache lookup. Removing that old rule from existing saved configurations is manual.
**Caveat:** This deliberately removes **every** cookie on the allowed public pages, not just analytics or inherited cookies. It can break logins, preferences, locale choice, cart, stickiness or security challenge behavior, and may serve anonymous content to a logged-in user. Never apply it to personalized content. It does not rewrite origin `Vary: Cookie`, `Set-Cookie` or `Cache-Control` and does not bypass RustProxy response privacy checks. Use [`docs/CACHE.md`](CACHE.md#inherited-cookies-on-public-vhosts-opt-in-disabled-by-default) for configuration and risk details. **Caveat:** A cookie name may be shared by both the parent and the application; if so, do not strip it by name. This is a RustProxy-specific VCL extension rather than standard Varnish VCL. Origin privacy guards, `Set-Cookie`, and `Vary` remain active. See [Cache](CACHE.md#parent-domain-cookies-opt-in-per-vhost-name-filtering).
Source: [`examples/vcl/public-vhost-ignore-cookies.vcl`](../examples/vcl/public-vhost-ignore-cookies.vcl). Source: [`examples/vcl/public-vhost-remove-parent-cookies.vcl`](../examples/vcl/public-vhost-remove-parent-cookies.vcl).
```vcl ```vcl
// OPT-IN: use ONLY on an HTTP reverse-proxy Vhost with fully public, // Opt-in Vhost-only rule, SEPARATE from the CDN technical-cookie template.
// cookie-independent GET/HEAD content. Import into that Vhost, NOT globally. // RustProxy VCL extension: remove_req_cookies() is NOT standard Varnish VCL.
// Useful when a parent domain sets Domain=.example.test cookies that a public // Replace REPLACE_WITH_VERIFIED_PARENT_COOKIE_NAME with exact, verified names
// sibling subdomain neither needs nor should forward to the backend. // that this Vhost NEVER uses for login, user state, language, cart, etc.
// Cookie headers do NOT reveal Domain; a name may also belong to this Vhost.
// Never list a session cookie that could be valid for this Vhost.
// //
// Cookie does not include the cookie's Domain attribute. It is IMPOSSIBLE // Install ABOVE "CDN: remove ONLY technical cookies" and
// to distinguish inherited cookies from host-only cookies in vcl_recv. // "CDN: bypass remaining cookies", which must stay as separate rules.
// This deliberately strips ALL cookies on permitted public paths; verify // DO NOT use the old strip-all inherited-cookie rule in parallel.
// that users do not need login, preferences, locale, cart or affinity there. // This rule has no return(hash): remaining cookies and sessions still pass
// Customize the excluded path list to fit your application before enabling. // through the CDN/normal cache safety checks.
// Backend must return an eligible PUBLIC response (no private/no-store or
// Set-Cookie); this does not override response cache privacy or Vary.
sub vcl_recv { sub vcl_recv {
if ((req.method == "GET" || req.method == "HEAD") && if ((req.method == "GET" || req.method == "HEAD") &&
req.http.Cookie && req.http.Cookie &&
!req.http.Authorization && !req.http.Authorization &&
req.url !~ "^/(admin|api|auth|login|logout|account|profile|user|settings|dashboard|cart|checkout|panel|konto|wp-admin|wp-login[.]php)(/|[?]|$)") { req.url !~ "^/(admin|api|auth|login|logout|account|profile|user|settings|dashboard|cart|checkout|panel|konto|wp-admin|wp-login[.]php)(/|[?]|$)") {
unset req.http.Cookie; remove_req_cookies("REPLACE_WITH_VERIFIED_PARENT_COOKIE_NAME");
return(hash);
} }
} }
``` ```
@@ -460,9 +459,11 @@ The outcomes below describe **decision paths**, not a guaranteed X-Cache label:
| `Cookie: __cf_bm=a; cf_clearance=b` | CDN cookie allowlist | Strip whole Cookie header | Only exact allowlisted cookie names pass. | | `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. | | `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. | | Two physical Cookie fields, one technical and one session | CDN cookie allowlist | PASS | Patched matcher examines combined cookie values. |
| `GET /catalog`, Cookie from parent domain | Public-Vhost opt-in | Strip all Cookie; eligible | Only on verified cookie-independent pages with reviewed exclusions. | | `GET /catalog`, `parent_marketing=a` (listed) | Parent-name template | Remove only listed cookie; eligible | The operator must verify the name is not used for app sessions. |
| `GET /account`, parent-domain Cookie | Public-Vhost opt-in | Ordinary bypass/auth rules | Protected-path guard leaves Cookie untouched. | | `parent_marketing=a; __cf_bm=b` | Parent-name + separate CDN templates | Both removed in order; eligible | Keep the parent rule before the CDN remaining-cookie bypass. |
| `GET /catalog`, Cookie plus Authorization | Public-Vhost opt-in | Native auth/bypass | The template does not remove Cookie with Authorization. | | `parent_marketing=a; app_session=b` | Parent-name + separate CDN templates | Preserve `app_session`; BYPASS | Never force lookup for remaining unknown/session cookies. |
| `GET /account`, parent-domain Cookie | Parent-name template | Ordinary bypass/auth rules | Protected-path guard leaves Cookie untouched. |
| `GET /catalog`, Cookie plus Authorization | Parent-name template | Native auth/bypass | The template does not remove Cookie with Authorization. |
| `GET /assets/site.css`, arbitrary Cookie | Public static | Strip Cookie **if verified safe** | Separate native `Vary: Cookie` setting has additional conditions. | | `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 /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: A` | A/B variants | Eligible A partition | Origin must emit downstream `Vary: X-Experiment`. |
@@ -0,0 +1,20 @@
// Opt-in Vhost-only rule, SEPARATE from the CDN technical-cookie template.
// RustProxy VCL extension: remove_req_cookies() is NOT standard Varnish VCL.
// Replace REPLACE_WITH_VERIFIED_PARENT_COOKIE_NAME with exact, verified names
// that this Vhost NEVER uses for login, user state, language, cart, etc.
// Cookie headers do NOT reveal Domain; a name may also belong to this Vhost.
// Never list a session cookie that could be valid for this Vhost.
//
// Install ABOVE "CDN: remove ONLY technical cookies" and
// "CDN: bypass remaining cookies", which must stay as separate rules.
// DO NOT use the old strip-all inherited-cookie rule in parallel.
// This rule has no return(hash): remaining cookies and sessions still pass
// through the CDN/normal cache safety checks.
sub vcl_recv {
if ((req.method == "GET" || req.method == "HEAD") &&
req.http.Cookie &&
!req.http.Authorization &&
req.url !~ "^/(admin|api|auth|login|logout|account|profile|user|settings|dashboard|cart|checkout|panel|konto|wp-admin|wp-login[.]php)(/|[?]|$)") {
remove_req_cookies("REPLACE_WITH_VERIFIED_PARENT_COOKIE_NAME");
}
}
+101 -1
View File
@@ -3418,6 +3418,21 @@
"vhCacheRulesTitle": "Cache rules for this vhost", "vhCacheRulesTitle": "Cache rules for this vhost",
"vhCacheRulesHelp": "Run before the global rules from Settings → Cache → Rules. When both set the same thing (TTL, grace, pass, no store) the vhost rule wins.", "vhCacheRulesHelp": "Run before the global rules from Settings → Cache → Rules. When both set the same thing (TTL, grace, pass, no store) the vhost rule wins.",
"cacheRulesTemplates": "Add from template…", "cacheRulesTemplates": "Add from template…",
"cacheRuleCatalogBrowse": "Browse scenarios",
"cacheRuleCatalogTitle": "Ready-made cache and VCL scenarios",
"cacheRuleCatalogHelp": "Search and add a rule or a complete group. Review paths, cookies, rule order and the disabled templates before saving. Changes are not active until you save the vhost or cache settings.",
"cacheRuleCatalogSearch": "Find a scenario (session, WordPress, API, HTML…)",
"cacheRuleCatalogAdd": "Add",
"cacheRuleCatalogReview": "Disabled until reviewed and enabled",
"cacheRuleCatalogAddedDisabled": "Added {count} disabled rule(s). Review and enable them before saving.",
"cacheRuleCatalogEmpty": "No matching scenario.",
"cacheRuleTplGroupPrivacy": "Security and private content",
"cacheRuleTplGroupFrameworks": "CMS and application sessions",
"cacheRuleTplGroupCookies": "CDN and parent-domain cookies",
"cacheRuleTplGroupPublic": "Public content and TTL",
"cacheRuleTplGroupVariants": "Cache key and variants",
"cacheRuleTplGroupDelivery": "Browser and response headers",
"cacheRuleTplGroupOther": "Other",
"cacheRulesImportVcl": "Import VCL", "cacheRulesImportVcl": "Import VCL",
"cacheRulesExportVcl": "Copy as VCL", "cacheRulesExportVcl": "Copy as VCL",
"cacheRulesAdd": "New rule", "cacheRulesAdd": "New rule",
@@ -3526,6 +3541,7 @@
"cacheRuleActionPass": "Bypass cache (pass)", "cacheRuleActionPass": "Bypass cache (pass)",
"cacheRuleActionLookup": "Allow Cookie cache lookup (hash)", "cacheRuleActionLookup": "Allow Cookie cache lookup (hash)",
"cacheRuleActionStripCookies": "Remove cookies", "cacheRuleActionStripCookies": "Remove cookies",
"cacheRuleActionRemoveNamedCookies": "Remove only named cookies",
"cacheRuleActionStripQuery": "Remove query parameters", "cacheRuleActionStripQuery": "Remove query parameters",
"cacheRuleActionSetRequestHeader": "Set request header", "cacheRuleActionSetRequestHeader": "Set request header",
"cacheRuleActionRemoveRequestHeader": "Remove request header", "cacheRuleActionRemoveRequestHeader": "Remove request header",
@@ -3548,6 +3564,7 @@
"cacheRuleActionHelpIgnoreCacheControl": "Caches even with no-cache, private or no-store from the backend (uses the TTL action or the default TTL). Responses with Set-Cookie still need Remove Set-Cookie.", "cacheRuleActionHelpIgnoreCacheControl": "Caches even with no-cache, private or no-store from the backend (uses the TTL action or the default TTL). Responses with Set-Cookie still need Remove Set-Cookie.",
"cacheRuleActionHelpStripSetCookie": "Removes Set-Cookie from the backend response (stored and delivered), like unset beresp.http.Set-Cookie.", "cacheRuleActionHelpStripSetCookie": "Removes Set-Cookie from the backend response (stored and delivered), like unset beresp.http.Set-Cookie.",
"cacheRuleKeepCookies": "keep cookies (empty = remove all)", "cacheRuleKeepCookies": "keep cookies (empty = remove all)",
"cacheRuleRemoveNamedCookies": "Exact cookie names to ignore on this vhost (comma separated)",
"cacheRuleKeepOnly": "keep only these", "cacheRuleKeepOnly": "keep only these",
"cacheRuleQueryParams": "utm_*, fbclid (empty = all)", "cacheRuleQueryParams": "utm_*, fbclid (empty = all)",
"cacheRuleHeaderValue": "value", "cacheRuleHeaderValue": "value",
@@ -3573,7 +3590,90 @@
"cacheRuleTplCdnAuth": "CDN: bypass Authorization", "cacheRuleTplCdnAuth": "CDN: bypass Authorization",
"cacheRuleTplCdnStrip": "CDN: remove ONLY technical cookies", "cacheRuleTplCdnStrip": "CDN: remove ONLY technical cookies",
"cacheRuleTplCdnRemaining": "CDN: bypass remaining cookies", "cacheRuleTplCdnRemaining": "CDN: bypass remaining cookies",
"cacheRuleTplPubliccookies": "Public vhost: ignore inherited cookies (enable after review)", "cacheRuleTplPubliccookies": "Vhost: remove selected parent-domain cookies (opt-in)",
"cacheRuleTplSafemethods": "Security: bypass methods other than GET/HEAD",
"cacheRuleTplAuthbypass": "Security: bypass Authorization header",
"cacheRuleTplCookiepass": "Sessions: bypass every Cookie-bearing request",
"cacheRuleTplSessioncookies": "Sessions: bypass common session cookie names",
"cacheRuleTplPrivateroutes": "Private paths: bypass + no-store + browser no-store",
"cacheRuleTplPrivateroutesPass": "Private routes: bypass cache",
"cacheRuleTplPrivateroutesStore": "Private routes: do not store backend response",
"cacheRuleTplPrivateroutesBrowser": "Private routes: browser private, no-store",
"cacheRuleTplPreview": "Previews and draft links: bypass",
"cacheRuleTplCheckout": "Cart, checkout and payments: bypass",
"cacheRuleTplWebhooks": "Webhooks and callbacks: bypass",
"cacheRuleTplHealthchecks": "Health checks and /metrics: bypass",
"cacheRuleTplGraphql": "GraphQL endpoint: bypass",
"cacheRuleTplStreaming": "SSE and WebSocket upgrade: bypass",
"cacheRuleTplSignedurls": "Signed/authenticated query tokens: bypass",
"cacheRuleTplWoocommerce": "WooCommerce: protect cart and sessions",
"cacheRuleTplDjango": "Django: bypass sessionid cookie",
"cacheRuleTplLaravel": "Laravel/PHP: bypass session cookies",
"cacheRuleTplAuthjs": "Auth.js/NextAuth: bypass session cookies",
"cacheRuleTplAspnet": "ASP.NET: bypass common session cookies",
"cacheRuleTplDrupal": "Drupal: bypass SESS/SSESS cookies",
"cacheRuleTplPublicjson": "Public JSON API: 60 s TTL, 30 s grace",
"cacheRuleTplPublicpages": "Public blog/catalog HTML: 5 min TTL",
"cacheRuleTplFeeds": "Public RSS/Atom feed: 10 min TTL",
"cacheRuleTplSitemap": "Public sitemap XML: 1 h TTL",
"cacheRuleTplHashedassets": "Versioned assets with filename hash: 1 year TTL",
"cacheRuleTplImagecache": "Public images: 1 day TTL",
"cacheRuleTplFontcache": "Public fonts: 30 days TTL",
"cacheRuleTplSearchttl": "Public search responses: 15 s TTL",
"cacheRuleTplNocachehtml": "HTML: never store on proxy or in browser",
"cacheRuleTplNocachehtmlResponse": "HTML: disallow shared-cache storage",
"cacheRuleTplNocachehtmlDeliver": "HTML: browser Cache-Control no-store",
"cacheRuleTplPrivateapi": "Private API: bypass + no-store",
"cacheRuleTplPrivateapiPass": "Private API: bypass cache",
"cacheRuleTplPrivateapiStore": "Private API: disallow storage",
"cacheRuleTplPrivateapiBrowser": "Private API: browser private, no-store",
"cacheRuleTplPrivatedownloads": "Private downloads: bypass + browser no-store",
"cacheRuleTplPrivatedownloadsPass": "Private downloads: bypass cache",
"cacheRuleTplPrivatedownloadsBrowser": "Private downloads: browser private, no-store",
"cacheRuleTplStagingnoindex": "Staging site: X-Robots-Tag noindex",
"cacheRuleTplFrameguard": "Security: X-Frame-Options SAMEORIGIN",
"cacheRuleTplHelpWordpress": "Protect wp-admin/login, REST API and common logged-in WordPress cookies; review paths for plugins.",
"cacheRuleTplHelpStatic": "Removes all cookies for static extensions and sets 30-day TTL; only if files are identical for guests and logged-in users.",
"cacheRuleTplHelpCdn": "Separate Cloudflare/Akamai technical-cookie policy; leaves mixed session cookies for BYPASS.",
"cacheRuleTplHelpPubliccookies": "Disabled by default. Replace the placeholder with verified exact cookie names inherited from a parent domain. Never list app sessions.",
"cacheRuleTplHelpTracking": "Remove known tracking-only query parameters from cache lookup and origin URL; review attribution impact.",
"cacheRuleTplHelpApi": "Bypass /api/ on all methods, including otherwise cacheable GET; adjust the API prefix.",
"cacheRuleTplHelpLanguage": "Add a language cookie dimension to the key; cache still bypasses real sessions and must honor origin Vary.",
"cacheRuleTplHelpHeaders": "Remove X-Powered-By from delivered responses; does not alter cache admission.",
"cacheRuleTplHelpBrowser": "Set 30-day browser Cache-Control on static 200 responses; only for verified public assets.",
"cacheRuleTplHelpNobrowser": "Set browser no-store on HTML and /admin; does not disable RustProxy shared-cache lookup.",
"cacheRuleTplHelpSecurity": "Add nosniff and Referrer-Policy only if missing; leaves application headers intact.",
"cacheRuleTplHelpSafemethods": "Bypass requests whose method is not GET or HEAD; independent of the CDN policy.",
"cacheRuleTplHelpAuthbypass": "Always bypass requests with Authorization; tokens are forwarded to the origin.",
"cacheRuleTplHelpCookiepass": "Conservative option: any Cookie causes BYPASS, including parent-domain tracking cookies.",
"cacheRuleTplHelpSessioncookies": "Bypass common session cookie names; unknown application session names still need protection.",
"cacheRuleTplHelpPrivateroutes": "Three rules: bypass sensitive routes, prevent shared storage and set browser private/no-store. Review route list.",
"cacheRuleTplHelpPreview": "Preview/draft paths or query parameters must not reuse public cached objects.",
"cacheRuleTplHelpCheckout": "Bypass cart, checkout, payments, billing and order paths; customize for your store.",
"cacheRuleTplHelpWebhooks": "Bypass webhook/callback paths; keep replay, signatures and ACLs in the application.",
"cacheRuleTplHelpHealthchecks": "Keep /health, /status, /metrics and readiness checks out of shared cache.",
"cacheRuleTplHelpGraphql": "Bypass /graphql, including GET queries that may depend on user identity.",
"cacheRuleTplHelpStreaming": "Bypass SSE via Accept or WebSocket Upgrade; streaming must not use shared cached responses.",
"cacheRuleTplHelpSignedurls": "Bypass URLs containing authentication/signature query parameters; check your parameter names.",
"cacheRuleTplHelpWoocommerce": "Protect cart, checkout, my-account and WooCommerce/WordPress login cookies.",
"cacheRuleTplHelpDjango": "Pass when the Django sessionid cookie exists; verify custom SESSION_COOKIE_NAME.",
"cacheRuleTplHelpLaravel": "Pass on laravel_session or PHPSESSID; verify custom session cookie names.",
"cacheRuleTplHelpAuthjs": "Pass on common Auth.js/NextAuth session cookie names; review secure prefix and app settings.",
"cacheRuleTplHelpAspnet": "Pass on common ASP.NET session/auth cookies; review custom cookie names.",
"cacheRuleTplHelpDrupal": "Pass on Drupal SESS/SSESS session cookie names; review any custom authentication cookies.",
"cacheRuleTplHelpPublicjson": "Disabled: only for truly public 200 JSON under /api/public/. Review privacy, Vary and freshness.",
"cacheRuleTplHelpPublicpages": "Disabled: public 200 HTML under selected blog/catalog paths; no personalized content.",
"cacheRuleTplHelpFeeds": "Disabled: cache verified public RSS/Atom feed for 10 minutes.",
"cacheRuleTplHelpSitemap": "Disabled: cache public sitemap XML for one hour.",
"cacheRuleTplHelpHashedassets": "Disabled: match files with version hashes under /assets, /static or /build; adjust pattern.",
"cacheRuleTplHelpImagecache": "Disabled: 1-day TTL only for images identical for all visitors; private images must stay uncached.",
"cacheRuleTplHelpFontcache": "Disabled: 30-day TTL only for public fonts; do not override authenticated downloads.",
"cacheRuleTplHelpSearchttl": "Disabled: 15-second TTL on public /search; verify query and session do not personalize results.",
"cacheRuleTplHelpNocachehtml": "Prevent storing all HTML and tell browsers no-store. Purge previously cached HTML objects.",
"cacheRuleTplHelpPrivateapi": "Three rules protecting /api/private/: bypass, no-store, and browser private/no-store.",
"cacheRuleTplHelpPrivatedownloads": "Disabled: set real private download prefix before enabling bypass and browser no-store.",
"cacheRuleTplHelpStagingnoindex": "Disabled: add X-Robots-Tag noindex,nofollow to staging; not an access-control mechanism.",
"cacheRuleTplHelpFrameguard": "Disabled: SAMEORIGIN blocks framing by other origins; review embeds and login redirects.",
"cacheRuleTplTracking": "Ignore tracking parameters (utm_*, fbclid, gclid)", "cacheRuleTplTracking": "Ignore tracking parameters (utm_*, fbclid, gclid)",
"cacheRuleTplApi": "API: bypass cache", "cacheRuleTplApi": "API: bypass cache",
"cacheRuleTplLanguage": "Separate cache per language cookie", "cacheRuleTplLanguage": "Separate cache per language cookie",
+101 -1
View File
@@ -3418,6 +3418,21 @@
"vhCacheRulesTitle": "Reguły cache tego vhosta", "vhCacheRulesTitle": "Reguły cache tego vhosta",
"vhCacheRulesHelp": "Działają przed regułami globalnymi z Ustawienia → Cache → Reguły. Gdy obie ustawiają to samo (TTL, grace, pominięcie cache, brak zapisu), wygrywa reguła vhosta.", "vhCacheRulesHelp": "Działają przed regułami globalnymi z Ustawienia → Cache → Reguły. Gdy obie ustawiają to samo (TTL, grace, pominięcie cache, brak zapisu), wygrywa reguła vhosta.",
"cacheRulesTemplates": "Dodaj z szablonu…", "cacheRulesTemplates": "Dodaj z szablonu…",
"cacheRuleCatalogBrowse": "Przeglądaj scenariusze",
"cacheRuleCatalogTitle": "Gotowe scenariusze cache i VCL",
"cacheRuleCatalogHelp": "Wyszukaj i dodaj regułę lub zestaw. Przed zapisaniem sprawdź ścieżki, cookies, kolejność oraz wyłączone szablony. Zmiany wejdą w życie dopiero po zapisaniu vhosta lub ustawień cache.",
"cacheRuleCatalogSearch": "Szukaj scenariusza (sesja, WordPress, API, HTML…)",
"cacheRuleCatalogAdd": "Dodaj",
"cacheRuleCatalogReview": "Wyłączony do czasu sprawdzenia i włączenia",
"cacheRuleCatalogAddedDisabled": "Dodano {count} wyłączonych reguł. Sprawdź i włącz je przed zapisaniem.",
"cacheRuleCatalogEmpty": "Brak pasujących scenariuszy.",
"cacheRuleTplGroupPrivacy": "Bezpieczeństwo i treści prywatne",
"cacheRuleTplGroupFrameworks": "CMS i sesje aplikacji",
"cacheRuleTplGroupCookies": "Cookies CDN i domeny nadrzędnej",
"cacheRuleTplGroupPublic": "Treści publiczne i TTL",
"cacheRuleTplGroupVariants": "Klucz cache i warianty",
"cacheRuleTplGroupDelivery": "Cache przeglądarki i nagłówki",
"cacheRuleTplGroupOther": "Pozostałe",
"cacheRulesImportVcl": "Import VCL", "cacheRulesImportVcl": "Import VCL",
"cacheRulesExportVcl": "Kopiuj jako VCL", "cacheRulesExportVcl": "Kopiuj jako VCL",
"cacheRulesAdd": "Nowa reguła", "cacheRulesAdd": "Nowa reguła",
@@ -3526,6 +3541,7 @@
"cacheRuleActionPass": "Pomiń cache (pass)", "cacheRuleActionPass": "Pomiń cache (pass)",
"cacheRuleActionLookup": "Dopuść cache żądania z Cookie (hash)", "cacheRuleActionLookup": "Dopuść cache żądania z Cookie (hash)",
"cacheRuleActionStripCookies": "Usuń ciasteczka", "cacheRuleActionStripCookies": "Usuń ciasteczka",
"cacheRuleActionRemoveNamedCookies": "Usuń tylko wskazane ciasteczka",
"cacheRuleActionStripQuery": "Usuń parametry zapytania", "cacheRuleActionStripQuery": "Usuń parametry zapytania",
"cacheRuleActionSetRequestHeader": "Ustaw nagłówek żądania", "cacheRuleActionSetRequestHeader": "Ustaw nagłówek żądania",
"cacheRuleActionRemoveRequestHeader": "Usuń nagłówek żądania", "cacheRuleActionRemoveRequestHeader": "Usuń nagłówek żądania",
@@ -3548,6 +3564,7 @@
"cacheRuleActionHelpIgnoreCacheControl": "Zapisuje mimo no-cache, private lub no-store z backendu (TTL z akcji TTL albo domyślny). Odpowiedzi z Set-Cookie wymagają też Usuń Set-Cookie.", "cacheRuleActionHelpIgnoreCacheControl": "Zapisuje mimo no-cache, private lub no-store z backendu (TTL z akcji TTL albo domyślny). Odpowiedzi z Set-Cookie wymagają też Usuń Set-Cookie.",
"cacheRuleActionHelpStripSetCookie": "Usuwa Set-Cookie z odpowiedzi backendu (zapisywanej i wysyłanej), jak unset beresp.http.Set-Cookie.", "cacheRuleActionHelpStripSetCookie": "Usuwa Set-Cookie z odpowiedzi backendu (zapisywanej i wysyłanej), jak unset beresp.http.Set-Cookie.",
"cacheRuleKeepCookies": "zostaw ciasteczka (puste = usuń wszystkie)", "cacheRuleKeepCookies": "zostaw ciasteczka (puste = usuń wszystkie)",
"cacheRuleRemoveNamedCookies": "Nazwy cookies do pominięcia na tym vhoście (oddziel przecinkami)",
"cacheRuleKeepOnly": "zostaw tylko te", "cacheRuleKeepOnly": "zostaw tylko te",
"cacheRuleQueryParams": "utm_*, fbclid (puste = wszystkie)", "cacheRuleQueryParams": "utm_*, fbclid (puste = wszystkie)",
"cacheRuleHeaderValue": "wartość", "cacheRuleHeaderValue": "wartość",
@@ -3573,7 +3590,90 @@
"cacheRuleTplCdnAuth": "CDN: omijaj Authorization", "cacheRuleTplCdnAuth": "CDN: omijaj Authorization",
"cacheRuleTplCdnStrip": "CDN: usuwaj tylko ciasteczka techniczne", "cacheRuleTplCdnStrip": "CDN: usuwaj tylko ciasteczka techniczne",
"cacheRuleTplCdnRemaining": "CDN: pomijaj pozostałe ciasteczka", "cacheRuleTplCdnRemaining": "CDN: pomijaj pozostałe ciasteczka",
"cacheRuleTplPubliccookies": "Publiczny vhost: ignoruj odziedziczone cookies (wymaga włączenia)", "cacheRuleTplPubliccookies": "Vhost: usuń wskazane cookies domeny nadrzędnej (opcjonalnie)",
"cacheRuleTplSafemethods": "Ochrona: pomijaj metody inne niż GET/HEAD",
"cacheRuleTplAuthbypass": "Ochrona: pomijaj żądania z Authorization",
"cacheRuleTplCookiepass": "Sesje: pomijaj każde żądanie z Cookie",
"cacheRuleTplSessioncookies": "Sesje: pomijaj typowe nazwy cookies sesyjnych",
"cacheRuleTplPrivateroutes": "Prywatne ścieżki: BYPASS + no-store + przeglądarka",
"cacheRuleTplPrivateroutesPass": "Prywatne ścieżki: pomiń cache",
"cacheRuleTplPrivateroutesStore": "Prywatne ścieżki: nie zapisuj odpowiedzi",
"cacheRuleTplPrivateroutesBrowser": "Prywatne ścieżki: nagłówek private, no-store",
"cacheRuleTplPreview": "Podglądy i wersje robocze: pomiń cache",
"cacheRuleTplCheckout": "Koszyk, płatności i zamówienia: pomiń cache",
"cacheRuleTplWebhooks": "Webhooki i callbacki: pomiń cache",
"cacheRuleTplHealthchecks": "Health check i /metrics: pomiń cache",
"cacheRuleTplGraphql": "GraphQL: pomiń cache",
"cacheRuleTplStreaming": "SSE i WebSocket upgrade: pomiń cache",
"cacheRuleTplSignedurls": "Tokeny i podpisane URL: pomiń cache",
"cacheRuleTplWoocommerce": "WooCommerce: chroń koszyk i sesje",
"cacheRuleTplDjango": "Django: pomiń cookie sessionid",
"cacheRuleTplLaravel": "Laravel/PHP: pomiń cookies sesyjne",
"cacheRuleTplAuthjs": "Auth.js/NextAuth: pomiń cookies sesyjne",
"cacheRuleTplAspnet": "ASP.NET: pomiń typowe cookies sesyjne",
"cacheRuleTplDrupal": "Drupal: pomiń cookies SESS/SSESS",
"cacheRuleTplPublicjson": "Publiczne API JSON: TTL 60 s, grace 30 s",
"cacheRuleTplPublicpages": "Publiczny blog/katalog HTML: TTL 5 min",
"cacheRuleTplFeeds": "Publiczny RSS/Atom: TTL 10 min",
"cacheRuleTplSitemap": "Publiczny sitemap XML: TTL 1 h",
"cacheRuleTplHashedassets": "Pliki z hashem w nazwie: TTL 1 rok",
"cacheRuleTplImagecache": "Publiczne obrazy: TTL 1 dzień",
"cacheRuleTplFontcache": "Publiczne fonty: TTL 30 dni",
"cacheRuleTplSearchttl": "Publiczne wyniki wyszukiwania: TTL 15 s",
"cacheRuleTplNocachehtml": "HTML: bez cache w proxy i przeglądarce",
"cacheRuleTplNocachehtmlResponse": "HTML: blokuj zapis do współdzielonego cache",
"cacheRuleTplNocachehtmlDeliver": "HTML: Cache-Control no-store w przeglądarce",
"cacheRuleTplPrivateapi": "Prywatne API: BYPASS + no-store",
"cacheRuleTplPrivateapiPass": "Prywatne API: pomiń cache",
"cacheRuleTplPrivateapiStore": "Prywatne API: nie zapisuj",
"cacheRuleTplPrivateapiBrowser": "Prywatne API: nagłówek private, no-store",
"cacheRuleTplPrivatedownloads": "Prywatne pobrania: BYPASS + no-store",
"cacheRuleTplPrivatedownloadsPass": "Prywatne pobrania: pomiń cache",
"cacheRuleTplPrivatedownloadsBrowser": "Prywatne pobrania: nagłówek private, no-store",
"cacheRuleTplStagingnoindex": "Środowisko testowe: X-Robots-Tag noindex",
"cacheRuleTplFrameguard": "Ochrona: X-Frame-Options SAMEORIGIN",
"cacheRuleTplHelpWordpress": "Chroni panel, logowanie, REST API i typowe cookies zalogowanych; sprawdź ścieżki wtyczek.",
"cacheRuleTplHelpStatic": "Usuwa wszystkie cookies dla rozszerzeń statycznych i ustawia TTL 30 dni; tylko gdy pliki są identyczne dla wszystkich.",
"cacheRuleTplHelpCdn": "Osobne reguły cookies technicznych Cloudflare/Akamai; cookies sesyjne nadal powodują BYPASS.",
"cacheRuleTplHelpPubliccookies": "Domyślnie wyłączony. Wpisz dokładne nazwy nieistotnych cookies z domeny nadrzędnej; nigdy cookies sesyjnych.",
"cacheRuleTplHelpTracking": "Usuwa wybrane parametry marketingowe z URL i klucza cache; sprawdź wpływ na analitykę.",
"cacheRuleTplHelpApi": "Pomija całą ścieżkę /api/, również GET; dopasuj prefiks API.",
"cacheRuleTplHelpLanguage": "Dodaje językowe cookie do klucza; sesje nadal muszą omijać cache, a Vary backendu jest obowiązujący.",
"cacheRuleTplHelpHeaders": "Usuwa X-Powered-By z odpowiedzi; nie zmienia decyzji o cache.",
"cacheRuleTplHelpBrowser": "Ustawia Cache-Control 30 dni dla statycznych odpowiedzi 200; tylko dla publicznych plików.",
"cacheRuleTplHelpNobrowser": "Ustawia no-store w przeglądarce dla HTML i /admin; NIE blokuje cache współdzielonego w RustProxy.",
"cacheRuleTplHelpSecurity": "Dodaje nosniff i Referrer-Policy tylko gdy ich brakuje; zachowuje nagłówki aplikacji.",
"cacheRuleTplHelpSafemethods": "Pomija metody inne niż GET i HEAD; działa niezależnie od CDN.",
"cacheRuleTplHelpAuthbypass": "Zawsze pomija żądania z Authorization; token zostaje przekazany do backendu.",
"cacheRuleTplHelpCookiepass": "Konserwatywnie: dowolny Cookie daje BYPASS, także cookies marketingowe domeny nadrzędnej.",
"cacheRuleTplHelpSessioncookies": "Pomija znane nazwy cookies sesyjnych; inne nazwy musisz zabezpieczyć osobno.",
"cacheRuleTplHelpPrivateroutes": "Trzy reguły: BYPASS ścieżek prywatnych, blokada zapisu i private/no-store w przeglądarce. Sprawdź listę ścieżek.",
"cacheRuleTplHelpPreview": "Podglądy i wersje robocze w ścieżce lub query muszą omijać publiczny cache.",
"cacheRuleTplHelpCheckout": "Pomija koszyk, płatności, faktury i zamówienia; dopasuj do sklepu.",
"cacheRuleTplHelpWebhooks": "Pomija webhooki/callbacki; walidacja podpisu i ACL pozostaje w aplikacji.",
"cacheRuleTplHelpHealthchecks": "Wyłącza cache dla /health, /status, /metrics i endpointów gotowości.",
"cacheRuleTplHelpGraphql": "Pomija /graphql, również zapytania GET zależne od użytkownika.",
"cacheRuleTplHelpStreaming": "Pomija SSE na podstawie Accept i WebSocket Upgrade; nie przechowuje streamów.",
"cacheRuleTplHelpSignedurls": "Pomija URL-e z tokenem/podpisem w query; sprawdź nazwy parametrów.",
"cacheRuleTplHelpWoocommerce": "Chroni koszyk, płatności, konto oraz cookies sesji WooCommerce/WordPress.",
"cacheRuleTplHelpDjango": "BYPASS przy sessionid; sprawdź własne SESSION_COOKIE_NAME.",
"cacheRuleTplHelpLaravel": "BYPASS przy laravel_session lub PHPSESSID; sprawdź własne nazwy.",
"cacheRuleTplHelpAuthjs": "BYPASS dla typowych cookies sesji Auth.js/NextAuth; sprawdź prefiks i konfigurację.",
"cacheRuleTplHelpAspnet": "BYPASS dla typowych cookies ASP.NET; sprawdź własne nazwy.",
"cacheRuleTplHelpDrupal": "BYPASS dla cookies sesyjnych Drupal SESS/SSESS; sprawdź inne cookies autoryzacyjne.",
"cacheRuleTplHelpPublicjson": "Wyłączony: tylko publiczne JSON 200 w /api/public/. Sprawdź prywatność, Vary i TTL.",
"cacheRuleTplHelpPublicpages": "Wyłączony: publiczny HTML 200 w blogu/katalogu; bez personalizacji.",
"cacheRuleTplHelpFeeds": "Wyłączony: cache wyłącznie publicznego RSS/Atom na 10 minut.",
"cacheRuleTplHelpSitemap": "Wyłączony: cache publicznej mapy XML na godzinę.",
"cacheRuleTplHelpHashedassets": "Wyłączony: dopasowuje pliki z hashem pod /assets, /static lub /build; dopasuj wzorzec.",
"cacheRuleTplHelpImagecache": "Wyłączony: TTL 1 dzień tylko dla obrazów wspólnych wszystkim; obrazy prywatne pomijaj.",
"cacheRuleTplHelpFontcache": "Wyłączony: TTL 30 dni tylko dla publicznych fontów; nie dla pobrań po zalogowaniu.",
"cacheRuleTplHelpSearchttl": "Wyłączony: TTL 15 s dla publicznego /search; sprawdź query i personalizację.",
"cacheRuleTplHelpNocachehtml": "Blokuje zapis HTML w RustProxy i przeglądarce. Usuń wcześniej zapisane HTML z cache.",
"cacheRuleTplHelpPrivateapi": "Trzy reguły dla /api/private/: BYPASS, no-store i private/no-store w przeglądarce.",
"cacheRuleTplHelpPrivatedownloads": "Wyłączony: ustaw prawidłowy prefiks prywatnych plików przed włączeniem BYPASS i no-store.",
"cacheRuleTplHelpStagingnoindex": "Wyłączony: dodaje X-Robots-Tag noindex,nofollow w środowisku testowym; to nie ACL.",
"cacheRuleTplHelpFrameguard": "Wyłączony: SAMEORIGIN blokuje osadzanie z innych domen; sprawdź iframe i integracje.",
"cacheRuleTplTracking": "Ignoruj parametry śledzące (utm_*, fbclid, gclid)", "cacheRuleTplTracking": "Ignoruj parametry śledzące (utm_*, fbclid, gclid)",
"cacheRuleTplApi": "API: pomiń cache", "cacheRuleTplApi": "API: pomiń cache",
"cacheRuleTplLanguage": "Osobny cache dla ciasteczka języka", "cacheRuleTplLanguage": "Osobny cache dla ciasteczka języka",
-137
View File
@@ -1,137 +0,0 @@
#!/usr/bin/env python3
"""TCP Stream black-box test: use against a running RustProxy and mock backends.
The 'selftest' mode validates this harness only; it does NOT run RustProxy.
All traffic uses loopback by default. Do not point it at a production service.
"""
from __future__ import annotations
import argparse
from collections import Counter
from concurrent.futures import ThreadPoolExecutor, as_completed
import secrets
import socket
import socketserver
import sys
import threading
import time
MAX_LINE = 1024
class TCPServer(socketserver.ThreadingTCPServer):
allow_reuse_address = True
daemon_threads = True
request_queue_size = 128
class TCPBackend(socketserver.StreamRequestHandler):
def handle(self) -> None:
self.request.settimeout(10)
backend_id = self.server.backend_id.encode('ascii')
try:
while True:
line = self.rfile.readline(MAX_LINE + 1)
if not line or len(line) > MAX_LINE or not line.endswith(b'\n'):
return
self.wfile.write(backend_id + b'|' + line)
self.wfile.flush()
except (OSError, TimeoutError):
return
def run_server(host: str, port: int, backend_id: str) -> None:
with TCPServer((host, port), TCPBackend) as server:
server.backend_id = backend_id
print(f'TCP mock {backend_id} listening on {server.server_address}', flush=True)
try:
server.serve_forever(poll_interval=0.1)
except KeyboardInterrupt:
pass
def check_one(index: int, host: str, port: int, messages: int, timeout: float, hold_ms: float, nonce: str) -> str:
backend = None
with socket.create_connection((host, port), timeout=timeout) as connection:
connection.settimeout(timeout)
with connection.makefile('rb') as reader:
for seq in range(messages):
payload = f'rp-tcp:{nonce}:{index}:{seq}\n'.encode('ascii')
connection.sendall(payload)
response = reader.readline(MAX_LINE + 1)
try:
observed, echoed = response.split(b'|', 1)
except ValueError as exc:
raise AssertionError(f'session {index}: missing mock backend response: {response!r}') from exc
assert echoed == payload, f'session {index}: response mismatch: {response!r}'
assert observed, f'session {index}: empty backend ID'
if backend is None:
backend = observed
assert observed == backend, f'session {index}: TCP backend changed during connection'
if hold_ms and seq != messages - 1:
time.sleep(hold_ms / 1000)
return backend.decode('ascii')
def run_client(host: str, port: int, sessions: int, messages: int, parallel: int, timeout: float,
hold_ms: float, min_backends: int) -> Counter:
nonce = secrets.token_hex(8)
started = time.monotonic()
counts: Counter[str] = Counter()
with ThreadPoolExecutor(max_workers=parallel) as pool:
futures = [pool.submit(check_one, i, host, port, messages, timeout, hold_ms, nonce)
for i in range(sessions)]
for future in as_completed(futures):
counts[future.result()] += 1
assert len(counts) >= min_backends, f'observed {len(counts)} backend(s), required {min_backends}: {dict(counts)}'
print(f'TCP PASS: {sessions} sessions, {sessions * messages} messages, '
f'{len(counts)} backend(s), {time.monotonic() - started:.2f}s; assignments={dict(sorted(counts.items()))}')
return counts
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='mode', required=True)
server = sub.add_parser('server', help='run a local TCP mock backend')
server.add_argument('--host', default='127.0.0.1')
server.add_argument('--port', type=int, required=True)
server.add_argument('--backend-id', required=True, help='unique ASCII marker (e.g. node-a)')
client = sub.add_parser('client', help='test forwarding via an already-running RustProxy listener')
client.add_argument('--host', default='127.0.0.1', help='RustProxy TCP listener host')
client.add_argument('--port', type=int, required=True, help='RustProxy TCP listener port')
client.add_argument('--sessions', type=int, default=24)
client.add_argument('--messages', type=int, default=3)
client.add_argument('--parallel', type=int, default=8)
client.add_argument('--timeout', type=float, default=4.0)
client.add_argument('--hold-ms', type=float, default=20.0, help='pause between messages to keep TCP sessions alive')
client.add_argument('--min-backends', type=int, default=1, help='minimum distinct backend IDs observed')
sub.add_parser('selftest', help='test mock peer + harness directly, WITHOUT RustProxy')
args = parser.parse_args()
if args.mode == 'server':
if not args.backend_id.isascii() or not args.backend_id or '|' in args.backend_id or '\n' in args.backend_id:
parser.error('--backend-id must be nonempty ASCII without | or newline')
run_server(args.host, args.port, args.backend_id)
elif args.mode == 'client':
if min(args.port, args.sessions, args.messages, args.parallel, args.min_backends) < 1 or args.port > 65535 or args.timeout <= 0 or args.hold_ms < 0:
parser.error('invalid port, count, timeout or hold delay')
run_client(args.host, args.port, args.sessions, args.messages, args.parallel,
args.timeout, args.hold_ms, args.min_backends)
else:
with TCPServer(('127.0.0.1', 0), TCPBackend) as server:
server.backend_id = 'local-mock'
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
run_client('127.0.0.1', server.server_address[1], 8, 3, 4, 2.0, 5, 1)
print('SELFTEST PASS: tested mock TCP peer, not RustProxy')
finally:
server.shutdown()
thread.join(timeout=2)
if __name__ == '__main__':
try:
main()
except (OSError, AssertionError, UnicodeError) as exc:
print(f'TCP FAIL: {exc}', file=sys.stderr)
sys.exit(1)
-135
View File
@@ -1,135 +0,0 @@
#!/usr/bin/env python3
"""UDP Stream black-box test: sends multiple packets from each stable client socket.
Start separately labeled mock backends and target an existing RustProxy UDP
listener. 'selftest' only validates this Python harness, NOT RustProxy.
By default, the server responds PONG to PING for an explicitly configured probe.
"""
from __future__ import annotations
import argparse
from collections import Counter
from concurrent.futures import ThreadPoolExecutor, as_completed
import secrets
import socket
import socketserver
import sys
import threading
import time
MAX_DATAGRAM = 1024
class UDPServer(socketserver.UDPServer):
allow_reuse_address = True
class UDPBackend(socketserver.BaseRequestHandler):
def handle(self) -> None:
data, connection = self.request
if data == b'PING':
reply = b'PONG'
elif data and len(data) <= MAX_DATAGRAM:
reply = self.server.backend_id.encode('ascii') + b'|' + data
else:
return
connection.sendto(reply, self.client_address)
def run_server(host: str, port: int, backend_id: str) -> None:
with UDPServer((host, port), UDPBackend) as server:
server.backend_id = backend_id
print(f'UDP mock {backend_id} listening on {server.server_address}; health probe PING -> PONG', flush=True)
try:
server.serve_forever(poll_interval=0.1)
except KeyboardInterrupt:
pass
def check_one(index: int, host: str, port: int, messages: int, timeout: float, pause_ms: float, nonce: str) -> str:
info = socket.getaddrinfo(host, port, type=socket.SOCK_DGRAM)[0]
family, sock_type, proto, _, address = info
backend = None
# One socket = one stable client identity for the entire UDP Stream session.
with socket.socket(family, sock_type, proto) as connection:
connection.settimeout(timeout)
for seq in range(messages):
payload = f'rp-udp:{nonce}:{index}:{seq}'.encode('ascii')
connection.sendto(payload, address)
response, _ = connection.recvfrom(MAX_DATAGRAM + 128)
try:
observed, echoed = response.split(b'|', 1)
except ValueError as exc:
raise AssertionError(f'session {index}: missing mock backend response: {response!r}') from exc
assert echoed == payload, f'session {index}: response mismatch {response!r}'
assert observed, f'session {index}: empty backend ID'
if backend is None:
backend = observed
assert observed == backend, f'session {index}: UDP backend changed for the same client socket'
if pause_ms and seq != messages - 1:
time.sleep(pause_ms / 1000)
return backend.decode('ascii')
def run_client(host: str, port: int, sessions: int, messages: int, parallel: int, timeout: float,
pause_ms: float, min_backends: int) -> Counter:
nonce = secrets.token_hex(8)
started = time.monotonic()
counts: Counter[str] = Counter()
with ThreadPoolExecutor(max_workers=parallel) as pool:
futures = [pool.submit(check_one, i, host, port, messages, timeout, pause_ms, nonce)
for i in range(sessions)]
for future in as_completed(futures):
counts[future.result()] += 1
assert len(counts) >= min_backends, f'observed {len(counts)} backend(s), required {min_backends}: {dict(counts)}'
print(f'UDP PASS: {sessions} client sockets, {sessions * messages} datagrams, '
f'{len(counts)} backend(s), {time.monotonic() - started:.2f}s; assignments={dict(sorted(counts.items()))}')
return counts
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='mode', required=True)
server = sub.add_parser('server', help='run local UDP echo and optional PING/PONG probe responder')
server.add_argument('--host', default='127.0.0.1')
server.add_argument('--port', type=int, required=True)
server.add_argument('--backend-id', required=True, help='unique ASCII marker (e.g. node-a)')
client = sub.add_parser('client', help='test forwarding via an already-running RustProxy UDP listener')
client.add_argument('--host', default='127.0.0.1', help='RustProxy UDP listener host')
client.add_argument('--port', type=int, required=True, help='RustProxy UDP listener port')
client.add_argument('--sessions', type=int, default=24)
client.add_argument('--messages', type=int, default=3)
client.add_argument('--parallel', type=int, default=8)
client.add_argument('--timeout', type=float, default=4.0)
client.add_argument('--pause-ms', type=float, default=20.0, help='pause between datagrams on each stable client socket')
client.add_argument('--min-backends', type=int, default=1, help='minimum distinct backend IDs observed')
sub.add_parser('selftest', help='test mock peer + harness directly, WITHOUT RustProxy')
args = parser.parse_args()
if args.mode == 'server':
if not args.backend_id.isascii() or not args.backend_id or '|' in args.backend_id or '\n' in args.backend_id:
parser.error('--backend-id must be nonempty ASCII without | or newline')
run_server(args.host, args.port, args.backend_id)
elif args.mode == 'client':
if min(args.port, args.sessions, args.messages, args.parallel, args.min_backends) < 1 or args.port > 65535 or args.timeout <= 0 or args.pause_ms < 0:
parser.error('invalid port, count, timeout or pause delay')
run_client(args.host, args.port, args.sessions, args.messages, args.parallel,
args.timeout, args.pause_ms, args.min_backends)
else:
with UDPServer(('127.0.0.1', 0), UDPBackend) as server:
server.backend_id = 'local-mock'
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
run_client('127.0.0.1', server.server_address[1], 8, 3, 4, 2.0, 5, 1)
print('SELFTEST PASS: tested mock UDP peer, not RustProxy')
finally:
server.shutdown()
thread.join(timeout=2)
if __name__ == '__main__':
try:
main()
except (OSError, AssertionError, UnicodeError) as exc:
print(f'UDP FAIL: {exc}', file=sys.stderr)
sys.exit(1)
+1
View File
@@ -24,6 +24,7 @@ pub(super) static READER_DOCUMENTS: &[(&str, &str, &str)] = &[
reader_doc!("docs/WEB_SERVER.md", "guides"), reader_doc!("docs/WEB_SERVER.md", "guides"),
reader_doc!("docs/PHP_FPM.md", "guides"), reader_doc!("docs/PHP_FPM.md", "guides"),
reader_doc!("docs/CACHE.md", "guides"), reader_doc!("docs/CACHE.md", "guides"),
reader_doc!("docs/CACHE_TEMPLATE_LIBRARY.md", "guides"),
reader_doc!("docs/VCL.md", "guides"), reader_doc!("docs/VCL.md", "guides"),
reader_doc!("docs/VCL_SUPPORT_MATRIX.md", "guides"), reader_doc!("docs/VCL_SUPPORT_MATRIX.md", "guides"),
reader_doc!("docs/VCL_TRAFFIC_COOKBOOK.md", "guides"), reader_doc!("docs/VCL_TRAFFIC_COOKBOOK.md", "guides"),
+1 -1
View File
@@ -8865,7 +8865,7 @@
"maxItems": 16, "maxItems": 16,
"items": { "items": {
"type": "object", "type": "object",
"description": "type: pass, lookup (VCL return(hash), Cookie exception in Varnish-compatible mode), strip_cookies{keep}, strip_query{params,keep_only}, hash_header{name}, hash_cookie{name}, set_request_header{name,value}, remove_request_header{name} (request; protected auth/cache/framing headers cannot be changed); ttl{seconds}, grace{seconds}, no_store, allow_store (reverses rule no_store only; origin restrictions remain), ignore_cache_control, strip_set_cookie, set_backend_header{name,value}, remove_backend_header{name} (response, applied before cacheability and forwarded headers); set_header{name,value}, default_header{name,value}, remove_header{name} (deliver, including cache-disabled responses).", "description": "type: pass, lookup (VCL return(hash), Cookie exception in Varnish-compatible mode), strip_cookies{keep}, remove_named_cookies{names} (exact-name removal; sessions and unknown cookies remain), strip_query{params,keep_only}, hash_header{name}, hash_cookie{name}, set_request_header{name,value}, remove_request_header{name} (request; protected auth/cache/framing headers cannot be changed); ttl{seconds}, grace{seconds}, no_store, allow_store (reverses rule no_store only; origin restrictions remain), ignore_cache_control, strip_set_cookie, set_backend_header{name,value}, remove_backend_header{name} (response, applied before cacheability and forwarded headers); set_header{name,value}, default_header{name,value}, remove_header{name} (deliver, including cache-disabled responses).",
"additionalProperties": true "additionalProperties": true
}, },
"description": "Zero actions allowed only with stop=true (terminal return)." "description": "Zero actions allowed only with stop=true (terminal return)."
+222 -20
View File
@@ -18,11 +18,11 @@ window.rustProxyCacheRules = (() => {
response_header: { ops: ["exists", "equals", "contains", "regex"], name: true, stages: ["response", "deliver"] }, response_header: { ops: ["exists", "equals", "contains", "regex"], name: true, stages: ["response", "deliver"] },
}; };
const ACTIONS = { const ACTIONS = {
request: ["pass", "lookup", "strip_cookies", "strip_query", "hash_header", "hash_cookie", "set_request_header", "remove_request_header"], request: ["pass", "lookup", "strip_cookies", "remove_named_cookies", "strip_query", "hash_header", "hash_cookie", "set_request_header", "remove_request_header"],
response: ["ttl", "grace", "no_store", "allow_store", "ignore_cache_control", "strip_set_cookie", "set_backend_header", "remove_backend_header"], response: ["ttl", "grace", "no_store", "allow_store", "ignore_cache_control", "strip_set_cookie", "set_backend_header", "remove_backend_header"],
deliver: ["set_header", "default_header", "remove_header"], deliver: ["set_header", "default_header", "remove_header"],
}; };
const ASPECTS = { pass: "request_routing", lookup: "request_routing", strip_cookies: "request_cookies", strip_query: "request_query", ttl: "ttl", grace: "grace", no_store: "store", allow_store: "store" }; const ASPECTS = { pass: "request_routing", lookup: "request_routing", strip_cookies: "request_cookies", remove_named_cookies: "request_cookies", strip_query: "request_query", ttl: "ttl", grace: "grace", no_store: "store", allow_store: "store" };
const tk = (prefix, value) => t(`${prefix}${String(value).split("_").map(part => part[0].toUpperCase() + part.slice(1)).join("")}`); const tk = (prefix, value) => t(`${prefix}${String(value).split("_").map(part => part[0].toUpperCase() + part.slice(1)).join("")}`);
const fieldLabel = field => tk("cacheRuleField", field); const fieldLabel = field => tk("cacheRuleField", field);
const opLabel = op => tk("cacheRuleOp", op); const opLabel = op => tk("cacheRuleOp", op);
@@ -84,6 +84,7 @@ window.rustProxyCacheRules = (() => {
case "pass": return "return (pass);"; case "pass": return "return (pass);";
case "lookup": return rule.hash_stage ? "return (lookup);" : "return (hash);"; case "lookup": return rule.hash_stage ? "return (lookup);" : "return (hash);";
case "strip_cookies": return a.keep?.length ? `# keep only cookies: ${a.keep.join(", ")}\nset req.http.Cookie = regsuball(req.http.Cookie, "(^|;\\s*)(?!(${a.keep.map(reEsc).join("|")})=)[^;=]+=[^;]*", "");` : "unset req.http.Cookie;"; case "strip_cookies": return a.keep?.length ? `# keep only cookies: ${a.keep.join(", ")}\nset req.http.Cookie = regsuball(req.http.Cookie, "(^|;\\s*)(?!(${a.keep.map(reEsc).join("|")})=)[^;=]+=[^;]*", "");` : "unset req.http.Cookie;";
case "remove_named_cookies": return `remove_req_cookies(${(a.names || []).map(name => `"${esc(name)}"`).join(", ")});`;
case "strip_query": return a.keep_only ? `# keep only query parameters: ${(a.params || []).join(", ")}` : (a.params?.length ? `set req.url = regsuball(req.url, "([?&])(${a.params.map(p => globRe(p).replace(/\.\*/g, "[^=&]*")).join("|")})=[^&]*", "\\1");` : `set req.url = regsub(req.url, "\\?.*$", "");`); case "strip_query": return a.keep_only ? `# keep only query parameters: ${(a.params || []).join(", ")}` : (a.params?.length ? `set req.url = regsuball(req.url, "([?&])(${a.params.map(p => globRe(p).replace(/\.\*/g, "[^=&]*")).join("|")})=[^&]*", "\\1");` : `set req.url = regsub(req.url, "\\?.*$", "");`);
case "hash_header": return `hash_data(req.http.${a.name});`; case "hash_header": return `hash_data(req.http.${a.name});`;
case "hash_cookie": return `hash_data(regsub(req.http.Cookie, "^.*(?:^|;\\s*)${reEsc(a.name)}=([^;]*).*$", "\\1"));`; case "hash_cookie": return `hash_data(regsub(req.http.Cookie, "^.*(?:^|;\\s*)${reEsc(a.name)}=([^;]*).*$", "\\1"));`;
@@ -121,6 +122,8 @@ window.rustProxyCacheRules = (() => {
limits.push("One or more graphical conditions have no guaranteed VCL import round-trip."); limits.push("One or more graphical conditions have no guaranteed VCL import round-trip.");
if (rule.actions.some(a => ["hash_cookie", "strip_query", "strip_cookies", "default_header", "ignore_cache_control"].includes(a.type))) if (rule.actions.some(a => ["hash_cookie", "strip_query", "strip_cookies", "default_header", "ignore_cache_control"].includes(a.type)))
limits.push("One or more graphical actions are only approximated in this VCL display."); limits.push("One or more graphical actions are only approximated in this VCL display.");
if (rule.actions.some(a => a.type === "remove_named_cookies"))
limits.push("remove_req_cookies() is a RustProxy extension, not standard Varnish VCL.");
const notes = limits.map(limit => `# PREVIEW LIMITATION: ${limit}`).join("\n"); const notes = limits.map(limit => `# PREVIEW LIMITATION: ${limit}`).join("\n");
const description = notes ? `${head}\n${notes}` : head; const description = notes ? `${head}\n${notes}` : head;
return conditions.length ? `${description}\nif (${joined}) {\n${body}\n}` : `${description}\n${body.replace(/^ {4}/gm, "")}`; return conditions.length ? `${description}\nif (${joined}) {\n${body}\n}` : `${description}\n${body.replace(/^ {4}/gm, "")}`;
@@ -148,6 +151,7 @@ window.rustProxyCacheRules = (() => {
const actions = rule.actions.map(a => { const actions = rule.actions.map(a => {
if (a.type === "ttl" || a.type === "grace") return `${actionLabel(a.type)} ${fmtDuration(a.seconds)}`; if (a.type === "ttl" || a.type === "grace") return `${actionLabel(a.type)} ${fmtDuration(a.seconds)}`;
if (a.type === "strip_query") return `${actionLabel(a.type)}${a.params?.length ? `: ${a.params.join(", ")}` : ""}`; if (a.type === "strip_query") return `${actionLabel(a.type)}${a.params?.length ? `: ${a.params.join(", ")}` : ""}`;
if (a.type === "remove_named_cookies") return `${actionLabel(a.type)}: ${(a.names || []).join(", ")}`;
if (a.type === "set_header" || a.type === "default_header" || a.type === "set_backend_header" || a.type === "set_request_header") return `${actionLabel(a.type)}: ${a.name || "-"}${a.value ? ` = ${a.value}` : ""}`; if (a.type === "set_header" || a.type === "default_header" || a.type === "set_backend_header" || a.type === "set_request_header") return `${actionLabel(a.type)}: ${a.name || "-"}${a.value ? ` = ${a.value}` : ""}`;
if (a.type === "remove_header" || a.type === "remove_backend_header" || a.type === "remove_request_header" || a.type === "hash_header" || a.type === "hash_cookie") return `${actionLabel(a.type)}: ${a.name || "-"}`; if (a.type === "remove_header" || a.type === "remove_backend_header" || a.type === "remove_request_header" || a.type === "hash_header" || a.type === "hash_cookie") return `${actionLabel(a.type)}: ${a.name || "-"}`;
return actionLabel(a.type); return actionLabel(a.type);
@@ -159,6 +163,21 @@ window.rustProxyCacheRules = (() => {
for (const [unit, size] of [...durationUnits].reverse()) if (seconds >= size && seconds % size === 0) return `${seconds / size}${unit}`; for (const [unit, size] of [...durationUnits].reverse()) if (seconds >= size && seconds % size === 0) return `${seconds / size}${unit}`;
return `${seconds}s`; return `${seconds}s`;
} }
// These are ordinary graphical rules, not a separate VCL engine. Keep
// privacy boundaries fail-closed: rules which can increase cache reuse or
// alter downstream caching start disabled until the operator reviews them.
const templatePass = (label, conditions, match = "all") => ({
name: t(label), stage: "request", match, conditions,
actions: [{ type: "pass" }], stop: true,
});
const templatePath = (value) => ({ field: "path", operator: "regex", values: [value] });
const templateResponse = (label, conditions, actions, enabled = false) => ({
name: t(label), stage: "response", match: "all", conditions, actions, enabled,
});
const templateDeliver = (label, conditions, actions, enabled = true) => ({
name: t(label), stage: "deliver", match: "all", conditions, actions, enabled,
});
const protectedPaths = "^/(?:admin|auth|login|logout|user|users|account|profile|settings|dashboard|cart|checkout|orders|billing|payment)(?:/|[?]|$)";
const TEMPLATES = { const TEMPLATES = {
wordpress: () => [{ name: t("cacheRuleTplWordpress"), stage: "request", match: "any", conditions: [{ field: "path", operator: "regex", values: ["^/(wp-admin|wp-login\\.php|xmlrpc\\.php|wp-json)"] }, { field: "header", name: "cookie", operator: "regex", values: ["wordpress_logged_in_|comment_author_|woocommerce_items_in_cart|wp-postpass_"] }], actions: [{ type: "pass" }] }], wordpress: () => [{ name: t("cacheRuleTplWordpress"), stage: "request", match: "any", conditions: [{ field: "path", operator: "regex", values: ["^/(wp-admin|wp-login\\.php|xmlrpc\\.php|wp-json)"] }, { field: "header", name: "cookie", operator: "regex", values: ["wordpress_logged_in_|comment_author_|woocommerce_items_in_cart|wp-postpass_"] }], actions: [{ type: "pass" }] }],
static: () => [ static: () => [
@@ -177,9 +196,9 @@ window.rustProxyCacheRules = (() => {
{ name: t("cacheRuleTplCdnRemaining"), stage: "request", match: "all", conditions: [{ field: "header", name: "Cookie", operator: "exists" }], actions: [{ type: "pass" }], stop: true }, { name: t("cacheRuleTplCdnRemaining"), stage: "request", match: "all", conditions: [{ field: "header", name: "Cookie", operator: "exists" }], actions: [{ type: "pass" }], stop: true },
]; ];
}, },
// Opt-in for a verified public vhost. Do not try to infer the Cookie // Separate from the CDN template: remove only explicitly named cookies
// Domain: it is absent from the HTTP Cookie request header. Disabled by // confirmed to be irrelevant to this Vhost. HTTP Cookie has no Domain
// default; the operator must review the private-path exclusions first. // attribute, so no origin inference or wildcard session-cookie removal.
publiccookies: () => [{ publiccookies: () => [{
name: t("cacheRuleTplPubliccookies"), enabled: false, stage: "request", match: "all", name: t("cacheRuleTplPubliccookies"), enabled: false, stage: "request", match: "all",
conditions: [ conditions: [
@@ -188,7 +207,7 @@ window.rustProxyCacheRules = (() => {
{ field: "header", name: "Authorization", operator: "exists", negate: true }, { field: "header", name: "Authorization", operator: "exists", negate: true },
{ field: "path", operator: "regex", values: ["^/(admin|api|auth|login|logout|account|profile|user|settings|dashboard|cart|checkout|panel|konto|wp-admin|wp-login[.]php)(/|[?]|$)"], negate: true }, { field: "path", operator: "regex", values: ["^/(admin|api|auth|login|logout|account|profile|user|settings|dashboard|cart|checkout|panel|konto|wp-admin|wp-login[.]php)(/|[?]|$)"], negate: true },
], ],
actions: [{ type: "strip_cookies", keep: [] }, { type: "lookup" }], stop: true, actions: [{ type: "remove_named_cookies", names: ["REPLACE_WITH_VERIFIED_PARENT_COOKIE_NAME"] }], stop: false,
}], }],
tracking: () => [{ name: t("cacheRuleTplTracking"), stage: "request", match: "all", conditions: [], actions: [{ type: "strip_query", params: ["utm_*", "fbclid", "gclid", "msclkid", "mc_cid", "mc_eid", "_ga"] }] }], 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" }] }], api: () => [{ name: t("cacheRuleTplApi"), stage: "request", match: "all", conditions: [{ field: "path", operator: "prefix", values: ["/api/"] }], actions: [{ type: "pass" }] }],
@@ -199,7 +218,110 @@ window.rustProxyCacheRules = (() => {
browser: () => [{ name: t("cacheRuleTplBrowser"), stage: "deliver", match: "all", conditions: [{ field: "extension", operator: "equals", values: ["css", "js", "mjs", "png", "jpg", "jpeg", "gif", "webp", "avif", "svg", "ico", "woff", "woff2"] }, { field: "status", operator: "equals", values: ["200"] }], actions: [{ type: "set_header", name: "Cache-Control", value: "public, max-age=2592000" }] }], browser: () => [{ name: t("cacheRuleTplBrowser"), stage: "deliver", match: "all", conditions: [{ field: "extension", operator: "equals", values: ["css", "js", "mjs", "png", "jpg", "jpeg", "gif", "webp", "avif", "svg", "ico", "woff", "woff2"] }, { field: "status", operator: "equals", values: ["200"] }], actions: [{ type: "set_header", name: "Cache-Control", value: "public, max-age=2592000" }] }],
nobrowser: () => [{ name: t("cacheRuleTplNoBrowser"), stage: "deliver", match: "any", conditions: [{ field: "content_type", operator: "prefix", values: ["text/html"] }, { field: "path", operator: "prefix", values: ["/admin", "/account"] }], actions: [{ type: "set_header", name: "Cache-Control", value: "no-store" }] }], nobrowser: () => [{ name: t("cacheRuleTplNoBrowser"), stage: "deliver", match: "any", conditions: [{ field: "content_type", operator: "prefix", values: ["text/html"] }, { field: "path", operator: "prefix", values: ["/admin", "/account"] }], actions: [{ type: "set_header", name: "Cache-Control", value: "no-store" }] }],
security: () => [{ name: t("cacheRuleTplSecurity"), stage: "deliver", match: "all", conditions: [], actions: [{ type: "default_header", name: "X-Content-Type-Options", value: "nosniff" }, { type: "default_header", name: "Referrer-Policy", value: "strict-origin-when-cross-origin" }] }], security: () => [{ name: t("cacheRuleTplSecurity"), stage: "deliver", match: "all", conditions: [], actions: [{ type: "default_header", name: "X-Content-Type-Options", value: "nosniff" }, { type: "default_header", name: "Referrer-Policy", value: "strict-origin-when-cross-origin" }] }],
// Safety and authenticated traffic. No rule below removes unknown cookies.
safemethods: () => [templatePass("cacheRuleTplSafemethods", [{ field: "method", operator: "equals", values: ["GET", "HEAD"], negate: true }])],
authbypass: () => [templatePass("cacheRuleTplAuthbypass", [{ field: "header", name: "Authorization", operator: "exists" }])],
cookiepass: () => [templatePass("cacheRuleTplCookiepass", [{ field: "header", name: "Cookie", operator: "exists" }])],
sessioncookies: () => [templatePass("cacheRuleTplSessioncookies", [{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:session|sessionid|PHPSESSID|laravel_session|connect[.]sid|sid)="] }])],
privateroutes: () => [
templatePass("cacheRuleTplPrivateroutesPass", [templatePath(protectedPaths)]),
templateResponse("cacheRuleTplPrivateroutesStore", [templatePath(protectedPaths)], [{ type: "no_store" }], true),
templateDeliver("cacheRuleTplPrivateroutesBrowser", [templatePath(protectedPaths)], [{ type: "set_header", name: "Cache-Control", value: "private, no-store" }]),
],
preview: () => [templatePass("cacheRuleTplPreview", [
templatePath("^/(?:preview|draft)(?:/|[?]|$)"),
{ field: "query", name: "preview", operator: "exists" },
{ field: "query", name: "draft", operator: "exists" },
], "any")],
checkout: () => [templatePass("cacheRuleTplCheckout", [templatePath("^/(?:cart|checkout|payment|billing|orders?)(?:/|[?]|$)")])],
webhooks: () => [templatePass("cacheRuleTplWebhooks", [templatePath("^/(?:webhooks?|callbacks?|hooks)(?:/|[?]|$)")])],
healthchecks: () => [templatePass("cacheRuleTplHealthchecks", [templatePath("^/(?:health|healthz|readyz|livez|metrics|status)(?:/|[?]|$)")])],
graphql: () => [templatePass("cacheRuleTplGraphql", [templatePath("^/graphql(?:/|[?]|$)")])],
streaming: () => [templatePass("cacheRuleTplStreaming", [
{ field: "header", name: "Accept", operator: "contains", values: ["text/event-stream"] },
{ field: "header", name: "Upgrade", operator: "exists" },
], "any")],
signedurls: () => [templatePass("cacheRuleTplSignedurls", [
...["token", "access_token", "signature", "sig", "auth_token"].map(name => ({ field: "query", name, operator: "exists" })),
], "any")],
// Framework-specific guards are independent from the CDN allowlist.
woocommerce: () => [templatePass("cacheRuleTplWoocommerce", [
templatePath("^/(?:cart|checkout|my-account)(?:/|[?]|$)"),
{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:wordpress_logged_in_[^=;]*|woocommerce_items_in_cart|wp_woocommerce_session_[^=;]*|woocommerce_cart_hash)="] },
], "any")],
django: () => [templatePass("cacheRuleTplDjango", [{ field: "cookie", name: "sessionid", operator: "exists" }])],
laravel: () => [templatePass("cacheRuleTplLaravel", [{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:laravel_session|PHPSESSID)="] }])],
authjs: () => [templatePass("cacheRuleTplAuthjs", [{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:__Secure-)?(?:next-auth[.]session-token|authjs[.]session-token)="] }])],
aspnet: () => [templatePass("cacheRuleTplAspnet", [{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:[.]AspNetCore[.]Cookies|ASP[.]NET_SessionId)="] }])],
drupal: () => [templatePass("cacheRuleTplDrupal", [{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:S?SESS[a-fA-F0-9]+)="] }])],
// Cache acceleration must be opt-in: names, routes, representation privacy,
// Vary, and origin Cache-Control must be checked before activation.
publicjson: () => [templateResponse("cacheRuleTplPublicjson", [
{ field: "path", operator: "prefix", values: ["/api/public/"] },
{ field: "status", operator: "equals", values: ["200"] },
{ field: "content_type", operator: "prefix", values: ["application/json"] },
], [{ type: "ttl", seconds: 60 }, { type: "grace", seconds: 30 }])],
publicpages: () => [templateResponse("cacheRuleTplPublicpages", [
templatePath("^/(?:blog|news|articles|catalog|products)(?:/|[?]|$)"),
{ field: "status", operator: "equals", values: ["200"] },
{ field: "content_type", operator: "prefix", values: ["text/html"] },
], [{ type: "ttl", seconds: 300 }, { type: "grace", seconds: 60 }])],
feeds: () => [templateResponse("cacheRuleTplFeeds", [
templatePath("^/(?:feed|rss|rss[.]xml|atom[.]xml)(?:/|[?]|$)"),
{ field: "status", operator: "equals", values: ["200"] },
], [{ type: "ttl", seconds: 600 }])],
sitemap: () => [templateResponse("cacheRuleTplSitemap", [
templatePath("^/(?:sitemap(?:_index)?[.]xml|sitemap/)") ,
{ field: "status", operator: "equals", values: ["200"] },
], [{ type: "ttl", seconds: 3600 }])],
hashedassets: () => [templateResponse("cacheRuleTplHashedassets", [
templatePath("^/(?:assets|static|build)/[^?]*[.-][a-zA-Z0-9_-]{8,}[.](?:js|mjs|css|png|webp|avif|svg|woff2?)(?:[?]|$)"),
{ field: "status", operator: "equals", values: ["200"] },
], [{ type: "ttl", seconds: 31536000 }])],
imagecache: () => [templateResponse("cacheRuleTplImagecache", [
{ field: "extension", operator: "equals", values: ["png", "jpg", "jpeg", "webp", "avif", "gif", "svg"] },
{ field: "status", operator: "equals", values: ["200"] },
], [{ type: "ttl", seconds: 86400 }])],
fontcache: () => [templateResponse("cacheRuleTplFontcache", [
{ field: "extension", operator: "equals", values: ["woff", "woff2", "ttf", "otf"] },
{ field: "status", operator: "equals", values: ["200"] },
], [{ type: "ttl", seconds: 2592000 }])],
searchttl: () => [templateResponse("cacheRuleTplSearchttl", [
{ field: "path", operator: "prefix", values: ["/search"] },
{ field: "status", operator: "equals", values: ["200"] },
], [{ type: "ttl", seconds: 15 }])],
// Cache blocking AND browser no-store are separate stages: a deliver rule
// alone cannot prevent a shared-cache HIT. Purge old objects on activation.
nocachehtml: () => [
templateResponse("cacheRuleTplNocachehtmlResponse", [{ field: "content_type", operator: "prefix", values: ["text/html"] }], [{ type: "no_store" }], true),
templateDeliver("cacheRuleTplNocachehtmlDeliver", [{ field: "content_type", operator: "prefix", values: ["text/html"] }], [{ type: "set_header", name: "Cache-Control", value: "no-store" }]),
],
privateapi: () => [
templatePass("cacheRuleTplPrivateapiPass", [{ field: "path", operator: "prefix", values: ["/api/private/"] }]),
templateResponse("cacheRuleTplPrivateapiStore", [{ field: "path", operator: "prefix", values: ["/api/private/"] }], [{ type: "no_store" }], true),
templateDeliver("cacheRuleTplPrivateapiBrowser", [{ field: "path", operator: "prefix", values: ["/api/private/"] }], [{ type: "set_header", name: "Cache-Control", value: "private, no-store" }]),
],
privatedownloads: () => [
{ ...templatePass("cacheRuleTplPrivatedownloadsPass", [{ field: "path", operator: "prefix", values: ["/private-downloads/"] }]), enabled: false },
templateDeliver("cacheRuleTplPrivatedownloadsBrowser", [{ field: "path", operator: "prefix", values: ["/private-downloads/"] }], [{ type: "set_header", name: "Cache-Control", value: "private, no-store" }], false),
],
stagingnoindex: () => [templateDeliver("cacheRuleTplStagingnoindex", [], [{ type: "default_header", name: "X-Robots-Tag", value: "noindex, nofollow" }], false)],
frameguard: () => [templateDeliver("cacheRuleTplFrameguard", [], [{ type: "default_header", name: "X-Frame-Options", value: "SAMEORIGIN" }], false)],
}; };
// Display order is deliberate. Parent-domain cookie cleanup stays a
// distinct template and can be inserted before CDN strip/pass guards.
const TEMPLATE_GROUPS = [
{ id: "privacy", keys: ["safemethods", "authbypass", "cookiepass", "sessioncookies", "privateroutes", "preview", "checkout", "webhooks", "healthchecks", "graphql", "streaming", "signedurls", "nocachehtml", "privateapi", "privatedownloads"] },
{ id: "frameworks", keys: ["wordpress", "woocommerce", "django", "laravel", "authjs", "aspnet", "drupal"] },
{ id: "cookies", keys: ["cdn", "publiccookies"] },
{ id: "public", keys: ["publicjson", "publicpages", "feeds", "sitemap", "hashedassets", "imagecache", "fontcache", "searchttl", "static", "tracking"] },
{ id: "variants", keys: ["language"] },
{ id: "delivery", keys: ["headers", "browser", "nobrowser", "security", "stagingnoindex", "frameguard"] },
{ id: "other", keys: ["api"] },
];
const templateName = key => t(key === "nobrowser" ? "cacheRuleTplNoBrowser" : `cacheRuleTpl${key[0].toUpperCase()}${key.slice(1)}`);
const templateHelp = key => t(`cacheRuleTplHelp${key[0].toUpperCase()}${key.slice(1)}`);
const templateAvailable = (key, scope) => scope === "vhost" || key !== "publiccookies";
function applicableGlobals(vhostId) { function applicableGlobals(vhostId) {
return (envelope?.config?.cache?.rules || []).filter(rule => rule.enabled !== false && (!rule.vhosts?.length || rule.vhosts.includes(vhostId))); return (envelope?.config?.cache?.rules || []).filter(rule => rule.enabled !== false && (!rule.vhosts?.length || rule.vhosts.includes(vhostId)));
} }
@@ -287,15 +409,42 @@ window.rustProxyCacheRules = (() => {
helpLinks.append(guide, docs); helpLinks.append(guide, docs);
root.append(helpLinks); root.append(helpLinks);
} }
const templates = select([["", t("cacheRulesTemplates")], ...Object.keys(TEMPLATES).filter(key => scope === "vhost" || key !== "publiccookies").map(key => [key, t(`cacheRuleTpl${key[0].toUpperCase()}${key.slice(1)}`)])], "", t("cacheRulesTemplates")); const templates = el("select");
const placeholder = el("option", t("cacheRulesTemplates")); placeholder.value = "";
templates.append(placeholder);
for (const group of TEMPLATE_GROUPS) {
const visible = group.keys.filter(key => templateAvailable(key, scope));
if (!visible.length) continue;
const optgroup = document.createElement("optgroup");
optgroup.label = t(`cacheRuleTplGroup${group.id[0].toUpperCase()}${group.id.slice(1)}`);
for (const key of visible) {
const option = el("option", templateName(key));
option.value = key;
option.title = templateHelp(key);
optgroup.append(option);
}
templates.append(optgroup);
}
templates.setAttribute("aria-label", t("cacheRulesTemplates"));
templates.classList.add("cache-rules-templates"); templates.classList.add("cache-rules-templates");
const browseButton = el("button", t("cacheRuleCatalogBrowse"), "outline");
browseButton.type = "button"; browseButton.setAttribute("aria-expanded", "false");
const importButton = el("button", t("cacheRulesImportVcl"), "outline"); importButton.type = "button"; const importButton = el("button", t("cacheRulesImportVcl"), "outline"); importButton.type = "button";
const exportButton = el("button", t("cacheRulesExportVcl"), "outline"); exportButton.type = "button"; const exportButton = el("button", t("cacheRulesExportVcl"), "outline"); exportButton.type = "button";
const addButton = el("button", t("cacheRulesAdd"), "primary"); addButton.type = "button"; const addButton = el("button", t("cacheRulesAdd"), "primary"); addButton.type = "button";
toolbar.append(templates, importButton, exportButton, addButton); toolbar.append(templates, browseButton, importButton, exportButton, addButton);
const ignoreWrap = el("label", undefined, "check cache-rules-ignore"), ignoreBox = el("input", undefined, "switch"); ignoreBox.type = "checkbox"; ignoreBox.checked = ignoreGlobal; if (options.ignoreId !== "") ignoreBox.id = options.ignoreId || "vh-cache-ignore-global-rules"; const ignoreWrap = el("label", undefined, "check cache-rules-ignore"), ignoreBox = el("input", undefined, "switch"); ignoreBox.type = "checkbox"; ignoreBox.checked = ignoreGlobal; if (options.ignoreId !== "") ignoreBox.id = options.ignoreId || "vh-cache-ignore-global-rules";
ignoreWrap.append(ignoreBox, el("span", t("cacheRulesIgnoreGlobal"))); ignoreWrap.append(ignoreBox, el("span", t("cacheRulesIgnoreGlobal")));
const notices = el("div", undefined, "cache-rules-notices"); const notices = el("div", undefined, "cache-rules-notices");
const catalog = el("section", undefined, "cache-rule-catalog"); catalog.hidden = true;
const catalogHeading = el("h4", t("cacheRuleCatalogTitle"));
const catalogNote = el("p", t("cacheRuleCatalogHelp"), "fine");
const catalogSearch = el("input", undefined, "cache-rule-catalog-search");
catalogSearch.type = "search";
catalogSearch.placeholder = t("cacheRuleCatalogSearch");
catalogSearch.setAttribute("aria-label", t("cacheRuleCatalogSearch"));
const catalogGroups = el("div", undefined, "cache-rule-catalog-groups");
catalog.append(catalogHeading, catalogNote, catalogSearch, catalogGroups);
const list = el("div", undefined, "cache-rules-list"); const list = el("div", undefined, "cache-rules-list");
const empty = el("p", t(scope === "vhost" ? "cacheRulesEmptyVhost" : "cacheRulesEmpty"), "fine cache-rules-empty"); const empty = el("p", t(scope === "vhost" ? "cacheRulesEmptyVhost" : "cacheRulesEmpty"), "fine cache-rules-empty");
const importBox = el("div", undefined, "cache-rules-import"); importBox.hidden = true; const importBox = el("div", undefined, "cache-rules-import"); importBox.hidden = true;
@@ -322,8 +471,8 @@ window.rustProxyCacheRules = (() => {
const tester = buildTester(); const tester = buildTester();
root.append(toolbar); root.append(toolbar);
if (scope === "vhost") root.append(ignoreWrap); if (scope === "vhost") root.append(ignoreWrap);
root.append(notices, importBox, list, empty, exportBox, tester.node); root.append(notices, catalog, importBox, list, empty, exportBox, tester.node);
for (const isolated of [tester.node, importBox]) for (const type of ["input", "change"]) isolated.addEventListener(type, event => event.stopPropagation()); for (const isolated of [tester.node, importBox, catalog]) for (const type of ["input", "change"]) isolated.addEventListener(type, event => event.stopPropagation());
root.addEventListener("keydown", event => { if (event.key === "Enter" && event.target.matches?.("input:not([type=checkbox])")) event.preventDefault(); }); root.addEventListener("keydown", event => { if (event.key === "Enter" && event.target.matches?.("input:not([type=checkbox])")) event.preventDefault(); });
function taken() { return new Set(rules.map(rule => rule.id)); } function taken() { return new Set(rules.map(rule => rule.id)); }
if (scope === "global") { if (scope === "global") {
@@ -462,6 +611,7 @@ window.rustProxyCacheRules = (() => {
const nameInput = placeholder => { const node = textInput(action.name, placeholder); node.addEventListener("input", () => { action.name = node.value.trim(); changed(); }); return node; }; const nameInput = placeholder => { const node = textInput(action.name, placeholder); node.addEventListener("input", () => { action.name = node.value.trim(); changed(); }); return node; };
switch (action.type) { switch (action.type) {
case "strip_cookies": params.append(listInput("keep", t("cacheRuleKeepCookies"))); break; case "strip_cookies": params.append(listInput("keep", t("cacheRuleKeepCookies"))); break;
case "remove_named_cookies": params.append(listInput("names", t("cacheRuleRemoveNamedCookies"))); break;
case "strip_query": { case "strip_query": {
const keepOnly = el("label", undefined, "check"), box = el("input", undefined, "switch"); box.type = "checkbox"; box.checked = !!action.keep_only; keepOnly.append(box, el("span", t("cacheRuleKeepOnly"))); const keepOnly = el("label", undefined, "check"), box = el("input", undefined, "switch"); box.type = "checkbox"; box.checked = !!action.keep_only; keepOnly.append(box, el("span", t("cacheRuleKeepOnly")));
box.addEventListener("change", () => { action.keep_only = box.checked; changed(); }); box.addEventListener("change", () => { action.keep_only = box.checked; changed(); });
@@ -554,17 +704,69 @@ window.rustProxyCacheRules = (() => {
node.append(bodyWrap); node.append(bodyWrap);
return { node }; return { node };
} }
function addRules(items) { function addRules(items, templateKey = "") {
const ids = taken(); let added = 0; if (rules.length + items.length > MAX_RULES) { toast(t("cacheRulesLimit"), true); return 0; }
for (const item of items) { const ids = taken();
if (rules.length >= MAX_RULES) { toast(t("cacheRulesLimit"), true); break; } const addedRules = items.map(item => {
const rule = normalize({ ...item, id: slug(item.id || item.name, ids), vhosts: scope === "global" ? item.vhosts || [] : [] }); const rule = normalize({ ...item, id: slug(item.id || item.name, ids), vhosts: scope === "global" ? item.vhosts || [] : [] });
ids.add(rule.id); rules.push(rule); added++; ids.add(rule.id);
} return rule;
render(); if (added) changed(); });
return added; // The parent-name rule must execute before the independent CDN cookie
// strip / remaining-cookie pass checks; never move or merge CDN rules.
const cdnIndex = templateKey === "publiccookies" ? rules.findIndex(rule =>
/^CDN:/.test(rule.name || "") && rule.conditions.some(c => c.field === "header" && String(c.name || "").toLowerCase() === "cookie") &&
rule.actions.some(a => a.type === "strip_cookies" || a.type === "pass")) : -1;
if (cdnIndex >= 0) rules.splice(cdnIndex, 0, ...addedRules);
else rules.push(...addedRules);
if (addedRules.length) open.add(addedRules[0].id);
render();
if (addedRules.length) changed();
return addedRules.length;
} }
templates.addEventListener("change", () => { const make = TEMPLATES[templates.value]; templates.value = ""; if (!make) return; const added = addRules(make()); if (added) toast(t("cacheRulesTemplateAdded").replace("{count}", added)); }); function addTemplate(key) {
const make = TEMPLATES[key];
if (!make || !templateAvailable(key, scope)) return;
const items = make(), added = addRules(items, key);
if (!added) return;
const needsReview = items.some(item => item.enabled === false);
toast(t(needsReview ? "cacheRuleCatalogAddedDisabled" : "cacheRulesTemplateAdded").replace("{count}", added));
}
function renderCatalog() {
catalogGroups.replaceChildren();
const query = catalogSearch.value.trim().toLocaleLowerCase();
let shown = 0;
for (const group of TEMPLATE_GROUPS) {
const matches = group.keys.filter(key => templateAvailable(key, scope) &&
(!query || `${templateName(key)} ${templateHelp(key)} ${t(`cacheRuleTplGroup${group.id[0].toUpperCase()}${group.id.slice(1)}`)}`.toLocaleLowerCase().includes(query)));
if (!matches.length) continue;
const section = el("section", undefined, "cache-rule-catalog-group");
section.append(el("h5", t(`cacheRuleTplGroup${group.id[0].toUpperCase()}${group.id.slice(1)}`)));
for (const key of matches) {
const card = el("div", undefined, "cache-rule-catalog-card");
const copy = el("div", undefined, "cache-rule-catalog-card-copy");
const heading = el("strong", templateName(key));
const description = el("p", templateHelp(key), "fine");
copy.append(heading, description);
if (TEMPLATES[key]().some(rule => rule.enabled === false))
copy.append(el("span", t("cacheRuleCatalogReview"), "cache-rule-catalog-review"));
const add = el("button", t("cacheRuleCatalogAdd"), "outline");
add.type = "button";
add.setAttribute("aria-label", `${t("cacheRuleCatalogAdd")}: ${templateName(key)}`);
add.addEventListener("click", () => addTemplate(key));
card.append(copy, add); section.append(card); shown++;
}
catalogGroups.append(section);
}
if (!shown) catalogGroups.append(el("p", t("cacheRuleCatalogEmpty"), "fine"));
}
browseButton.addEventListener("click", () => {
catalog.hidden = !catalog.hidden;
browseButton.setAttribute("aria-expanded", String(!catalog.hidden));
if (!catalog.hidden) { renderCatalog(); catalogSearch.focus(); }
});
catalogSearch.addEventListener("input", renderCatalog);
templates.addEventListener("change", () => { const key = templates.value; templates.value = ""; addTemplate(key); });
addButton.addEventListener("click", () => { const rule = blankRule(taken()); rules.push(rule); open.add(rule.id); render(); changed(); list.lastElementChild?.scrollIntoView?.({ block: "nearest", behavior: "smooth" }); }); addButton.addEventListener("click", () => { const rule = blankRule(taken()); rules.push(rule); open.add(rule.id); render(); changed(); list.lastElementChild?.scrollIntoView?.({ block: "nearest", behavior: "smooth" }); });
importButton.addEventListener("click", () => { importBox.hidden = !importBox.hidden; if (importBox.hidden) resetImportPreview(); else importText.focus(); }); importButton.addEventListener("click", () => { importBox.hidden = !importBox.hidden; if (importBox.hidden) resetImportPreview(); else importText.focus(); });
importCancel.addEventListener("click", () => { importBox.hidden = true; resetImportPreview(); }); importCancel.addEventListener("click", () => { importBox.hidden = true; resetImportPreview(); });
@@ -627,5 +829,5 @@ window.rustProxyCacheRules = (() => {
if (options.autoLoadHits !== false) void refreshHits(); if (options.autoLoadHits !== false) void refreshHits();
return { node: root, read, ignoreGlobal: () => ignoreGlobal, set(next) { rules = (next || []).map(normalize); open = new Set(); render(); }, refreshHits }; return { node: root, read, ignoreGlobal: () => ignoreGlobal, set(next) { rules = (next || []).map(normalize); open = new Set(); render(); }, refreshHits };
} }
return { create, exportVcl, TEMPLATES }; return { create, exportVcl, TEMPLATES, TEMPLATE_GROUPS };
})(); })();
+59
View File
@@ -2470,6 +2470,65 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
margin-left: auto; margin-left: auto;
} }
/* Searchable, grouped one-click cache/VCL rule library. The native select
above remains for quick keyboard access and existing editor workflows. */
.cache-rule-catalog {
display: grid;
gap: 10px;
padding: 14px;
border: 1px solid var(--line);
border-radius: var(--rp-radius-surface, 0px);
background: var(--panel2);
min-width: 0;
}
.cache-rule-catalog>h4,
.cache-rule-catalog>p,
.cache-rule-catalog-card p { margin: 0; }
.cache-rule-catalog-search { width: min(100%, 480px); }
.cache-rule-catalog-groups {
max-height: 540px;
overflow: auto;
display: grid;
gap: 14px;
padding-right: 4px;
}
.cache-rule-catalog-group { display: grid; gap: 7px; min-width: 0; }
.cache-rule-catalog-group>h5 { margin: 0; font-size: 13px; }
.cache-rule-catalog-card {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 9px 11px;
border: 1px solid var(--line);
border-radius: var(--rp-radius-surface, 0px);
background: var(--panel);
min-width: 0;
}
.cache-rule-catalog-card-copy {
display: grid;
gap: 3px;
min-width: 0;
overflow-wrap: anywhere;
}
.cache-rule-catalog-card-copy strong { font-size: 13px; line-height: 1.4; }
.cache-rule-catalog-card-copy p { font-size: 12px; }
.cache-rule-catalog-review { color: var(--accent); font-size: 11px; }
.cache-rule-catalog-card>button { flex: 0 0 auto; }
@media (max-width: 540px) {
.cache-rule-catalog { padding: 9px; }
.cache-rule-catalog-card { align-items: flex-start; }
}
.cache-rules-notices { .cache-rules-notices {
display: grid; display: grid;
gap: 4px; gap: 4px;
+66 -17
View File
@@ -154,6 +154,8 @@ pub enum RuleAction {
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]
keep: Vec<String>, keep: Vec<String>,
}, },
/// Remove only explicitly named cookies; retain unknown/session cookies.
RemoveNamedCookies { names: Vec<String> },
StripQuery { StripQuery {
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]
params: Vec<String>, params: Vec<String>,
@@ -201,6 +203,7 @@ impl RuleAction {
| Self::SetRequestHeader { .. } | Self::SetRequestHeader { .. }
| Self::RemoveRequestHeader { .. } | Self::RemoveRequestHeader { .. }
| Self::StripCookies { .. } | Self::StripCookies { .. }
| Self::RemoveNamedCookies { .. }
| Self::StripQuery { .. } | Self::StripQuery { .. }
| Self::HashHeader { .. } | Self::HashHeader { .. }
| Self::HashCookie { .. } => RuleStage::Request, | Self::HashCookie { .. } => RuleStage::Request,
@@ -220,7 +223,7 @@ impl RuleAction {
fn aspect(&self) -> Option<&'static str> { fn aspect(&self) -> Option<&'static str> {
match self { match self {
Self::Pass | Self::Lookup => Some("request_routing"), Self::Pass | Self::Lookup => Some("request_routing"),
Self::StripCookies { .. } => Some("request_cookies"), Self::StripCookies { .. } | Self::RemoveNamedCookies { .. } => Some("request_cookies"),
Self::StripQuery { .. } => Some("request_query"), Self::StripQuery { .. } => Some("request_query"),
Self::Ttl { .. } => Some("ttl"), Self::Ttl { .. } => Some("ttl"),
Self::Grace { .. } => Some("grace"), Self::Grace { .. } => Some("grace"),
@@ -578,6 +581,12 @@ fn validate_action(action: &RuleAction) -> Result<()> {
"invalid cookie name" "invalid cookie name"
); );
} }
RuleAction::RemoveNamedCookies { names } => {
ensure!(!names.is_empty() && names.len() <= MAX_RULE_VALUES,
"remove_named_cookies requires 1 to 64 exact cookie names");
ensure!(names.iter().all(|name| valid_cookie_name(name)),
"invalid cookie name");
}
RuleAction::StripQuery { params, keep_only } => { RuleAction::StripQuery { params, keep_only } => {
ensure!( ensure!(
!params.is_empty() || !keep_only, !params.is_empty() || !keep_only,
@@ -960,6 +969,8 @@ pub struct RequestRuleOutcome {
/// to the rule evaluation copy. /// to the rule evaluation copy.
pub header_edits: Vec<BackendHeaderEdit>, pub header_edits: Vec<BackendHeaderEdit>,
pub strip_cookies: Option<Vec<String>>, pub strip_cookies: Option<Vec<String>>,
/// Exact names removed without discarding unrelated session cookies.
pub remove_named_cookies: Vec<String>,
pub query_edits: Vec<(Vec<String>, bool)>, pub query_edits: Vec<(Vec<String>, bool)>,
pub hash: Vec<String>, pub hash: Vec<String>,
pub matched: Vec<RuleMatchInfo>, pub matched: Vec<RuleMatchInfo>,
@@ -1142,6 +1153,14 @@ impl CompiledRules {
} }
outcome.rewrite_cookies(&mut current.headers); outcome.rewrite_cookies(&mut current.headers);
} }
RuleAction::RemoveNamedCookies { names } => {
for name in names {
if !outcome.remove_named_cookies.contains(name) {
outcome.remove_named_cookies.push(name.clone());
}
}
outcome.rewrite_cookies(&mut current.headers);
}
RuleAction::StripQuery { params, keep_only } => { RuleAction::StripQuery { params, keep_only } => {
outcome.query_edits.push((params.clone(), *keep_only)); outcome.query_edits.push((params.clone(), *keep_only));
if let Some(rewritten) = outcome.rewrite_query(current.query.as_deref()) { if let Some(rewritten) = outcome.rewrite_query(current.query.as_deref()) {
@@ -1325,24 +1344,54 @@ impl RequestRuleOutcome {
} }
} }
pub fn rewrite_cookies(&self, headers: &mut HeaderMap) { pub fn rewrite_cookies(&self, headers: &mut HeaderMap) {
let Some(keep) = &self.strip_cookies else { if self.remove_named_cookies.is_empty() {
return; // Preserve the pre-existing keep-list behavior for unchanged rules.
}; let Some(keep) = &self.strip_cookies else { return; };
let kept: Vec<String> = cookie_values(headers) let kept: Vec<String> = cookie_values(headers)
.filter(|(name, _)| keep.iter().any(|item| item == name)) .filter(|(name, _)| keep.iter().any(|item| item == name))
.map(|(name, value)| { .map(|(name, value)| {
if value.is_empty() { if value.is_empty() { name.to_owned() }
name.to_owned() else { format!("{name}={value}") }
} else { })
format!("{name}={value}") .collect();
headers.remove(http::header::COOKIE);
if !kept.is_empty() {
if let Ok(value) = HeaderValue::from_str(&kept.join("; ")) {
headers.insert(http::header::COOKIE, value);
} }
})
.collect();
headers.remove(http::header::COOKIE);
if !kept.is_empty() {
if let Ok(value) = HeaderValue::from_str(&kept.join("; ")) {
headers.insert(http::header::COOKIE, value);
} }
return;
}
// Fail closed: never delete an unknown or malformed Cookie field while
// removing selected parent-domain names. Leave it for later pass rules
// or RustProxy's request_cookie policy to reject.
let mut kept = Vec::new();
for header in headers.get_all(http::header::COOKIE).iter() {
let Ok(raw) = header.to_str() else { return; };
for part in raw.split(';') {
let Some((name, value)) = part.trim().split_once('=') else { return; };
// Do not normalize whitespace *inside* a cookie name: a
// malformed/lookalike name must stay present and bypass.
if !valid_cookie_name(name) { return; }
if self.remove_named_cookies.iter().any(|removed| removed == name) {
continue;
}
if self.strip_cookies.as_ref().is_some_and(|allow| !allow.iter().any(|item| item == name)) {
continue;
}
kept.push(format!("{name}={value}"));
}
}
let replacement = if kept.is_empty() { None } else {
match HeaderValue::from_str(&kept.join("; ")) {
Ok(value) => Some(value),
Err(_) => return,
}
};
headers.remove(http::header::COOKIE);
if let Some(value) = replacement {
headers.insert(http::header::COOKIE, value);
} }
} }
pub fn rewrite_query(&self, query: Option<&str>) -> Option<Option<String>> { pub fn rewrite_query(&self, query: Option<&str>) -> Option<Option<String>> {
+92 -40
View File
@@ -1063,68 +1063,120 @@ sub vcl_deliver {
} }
#[test] #[test]
fn vcl_public_vhost_template_strips_inherited_cookies_only_on_public_get_head() { fn vcl_parent_cookie_names_run_before_separate_cdn_template_without_losing_sessions() {
let vcl = include_str!(concat!( let parent = include_str!(concat!(env!("CARGO_MANIFEST_DIR"),
env!("CARGO_MANIFEST_DIR"), "/examples/vcl/public-vhost-remove-parent-cookies.vcl"))
"/examples/vcl/public-vhost-ignore-cookies.vcl" .replace("REPLACE_WITH_VERIFIED_PARENT_COOKIE_NAME", "parent_marketing");
)); let cdn = include_str!(concat!(env!("CARGO_MANIFEST_DIR"),
let imported = import_vcl(vcl).unwrap(); "/examples/vcl/cdn-technical-cookies.vcl"));
assert!(imported.warnings.is_empty(), "{:?}", imported.warnings); let imported_parent = import_vcl(&parent).unwrap();
assert!(!imported.rules.is_empty()); assert!(imported_parent.warnings.is_empty(), "{:?}", imported_parent.warnings);
validate_rules(&imported.rules, false).unwrap(); validate_rules(&imported_parent.rules, false).unwrap();
let compiled = CompiledRules::compile("public", &imported.rules, &[], false).unwrap(); assert!(imported_parent.rules.iter().any(|rule| rule.actions.iter().any(|action|
matches!(action, RuleAction::RemoveNamedCookies { names }
if names.len() == 1 && names[0] == "parent_marketing"))));
assert!(!imported_parent.rules.iter().any(|rule|
rule.actions.iter().any(|action| matches!(action, RuleAction::Lookup | RuleAction::StripCookies { .. }))));
for cookie in [ // Combine the *separate* examples in the same Vhost rule order. A
"sso_session=secret", // parent+CDN mix must cache, while a parent+session mix must pass.
"sso_session=secret; marketing_id=xyz", let combined = import_vcl(&format!("{parent}\n{cdn}")).unwrap();
"tracking=one; unknown=two", assert!(combined.warnings.is_empty(), "{:?}", combined.warnings);
validate_rules(&combined.rules, false).unwrap();
let compiled = CompiledRules::compile("public", &combined.rules, &[], false).unwrap();
for (cookie, forwarded_cookie, bypass) in [
("parent_marketing=1", None, false),
("parent_marketing=1; __cf_bm=2", None, false),
("__cf_bm=2; parent_marketing=1", None, false),
("parent_marketing=1; app_session=abc", Some("app_session=abc"), true),
("__cf_bm=2; parent_marketing=1; app_session=abc", Some("__cf_bm=2; app_session=abc"), true),
("app_session=abc", Some("app_session=abc"), true),
("unknown=1", Some("unknown=1"), true),
("__cf_bm=2", None, false),
] { ] {
let input = request("/rezerwa/15", None, &[("cookie", cookie)]); let input = request("/rezerwa/15", None, &[("cookie", cookie)]);
let outcome = compiled.evaluate_request(&input, false); let outcome = compiled.evaluate_request(&input, false);
assert!(outcome.pass.is_none(), "unexpected pass on {cookie}"); assert_eq!(outcome.pass.is_some(), bypass, "Cookie: {cookie}");
assert!(outcome.lookup.is_some(), "missing hash on {cookie}"); assert_eq!(outcome.lookup.is_some(), !bypass, "Cookie: {cookie}");
let mut forwarded = input.headers.clone(); let mut forwarded = input.headers.clone();
outcome.rewrite_cookies(&mut forwarded); outcome.rewrite_cookies(&mut forwarded);
assert!(!forwarded.contains_key(http::header::COOKIE), "{cookie}"); assert_eq!(forwarded.get("cookie").and_then(|value| value.to_str().ok()),
forwarded_cookie, "Cookie: {cookie}");
} }
// Cookie can be split across fields; both must be dropped only here.
let split = request("/", None, &[ // Multiple physical Cookie fields are handled without deleting sessions.
("cookie", "parent_session=one"), let split = request("/rezerwa/15", None, &[
("cookie", "preference=two"), ("cookie", "parent_marketing=1"),
("cookie", "app_session=abc"),
]); ]);
let outcome = compiled.evaluate_request(&split, false); let outcome = compiled.evaluate_request(&split, false);
assert!(outcome.pass.is_some());
let mut forwarded = split.headers.clone(); let mut forwarded = split.headers.clone();
outcome.rewrite_cookies(&mut forwarded); outcome.rewrite_cookies(&mut forwarded);
assert!(!forwarded.contains_key(http::header::COOKIE)); assert_eq!(forwarded.get("cookie").unwrap(), "app_session=abc");
let anonymous = request("/rezerwa/15", None, &[]); // Malformed or non-UTF8 Cookie fields must be preserved and bypassed.
assert!(compiled.evaluate_request(&anonymous, false).lookup.is_none()); for malformed in [&b"parent_marketing=1; BROKEN"[..],
for path in [ &b"parent_marketing=1;"[..],
"/admin", "/admin/users", "/api/orders", "/auth/callback", &b"parent_marketing =1"[..],
"/login", "/login/callback", "/account", "/profile", &b"parent_marketing=1; app_session=\xff"[..]] {
"/checkout", "/cart", "/konto", "/wp-admin", let mut input = request("/rezerwa/15", None, &[]);
] { input.headers.insert(http::header::COOKIE, HeaderValue::from_bytes(malformed).unwrap());
let input = request(path, None, &[("cookie", "session=secret")]);
let outcome = compiled.evaluate_request(&input, false); let outcome = compiled.evaluate_request(&input, false);
assert!(outcome.lookup.is_none(), "private path must not hash: {path}"); assert!(outcome.pass.is_some());
assert!(outcome.strip_cookies.is_none(), "private cookie stripped: {path}"); let mut forwarded = input.headers.clone();
outcome.rewrite_cookies(&mut forwarded);
assert_eq!(forwarded.get("cookie"), input.headers.get("cookie"));
}
for path in ["/admin", "/admin/users", "/api/orders", "/auth/callback",
"/login", "/account", "/profile", "/checkout", "/cart", "/konto"] {
let input = request(path, None, &[("cookie", "parent_marketing=1")]);
let outcome = compiled.evaluate_request(&input, false);
assert!(outcome.pass.is_some(), "{path}");
assert!(outcome.remove_named_cookies.is_empty(), "{path}");
} }
let with_auth = request("/rezerwa/15", None, &[ let with_auth = request("/rezerwa/15", None, &[
("cookie", "session=secret"), ("authorization", "Bearer access"), ("cookie", "parent_marketing=1"), ("authorization", "Bearer access"),
]); ]);
let outcome = compiled.evaluate_request(&with_auth, false); let outcome = compiled.evaluate_request(&with_auth, false);
assert!(outcome.lookup.is_none()); assert!(outcome.pass.is_some());
assert!(outcome.strip_cookies.is_none()); assert!(outcome.remove_named_cookies.is_empty());
for method in [Method::POST, Method::PUT, Method::DELETE] { for method in [Method::POST, Method::PUT, Method::DELETE] {
let mut input = request("/rezerwa/15", None, &[("cookie", "session=secret")]); let mut input = request("/rezerwa/15", None, &[("cookie", "parent_marketing=1")]);
input.method = method; input.method = method;
let outcome = compiled.evaluate_request(&input, false); let outcome = compiled.evaluate_request(&input, false);
assert!(outcome.lookup.is_none()); assert!(outcome.pass.is_some());
assert!(outcome.strip_cookies.is_none()); assert!(outcome.remove_named_cookies.is_empty());
} }
let mut head = request("/rezerwa/15", None, &[("cookie", "parent=secret")]); let mut head = request("/rezerwa/15", None, &[("cookie", "parent_marketing=1")]);
head.method = Method::HEAD; head.method = Method::HEAD;
assert!(compiled.evaluate_request(&head, false).lookup.is_some()); let outcome = compiled.evaluate_request(&head, false);
assert!(outcome.lookup.is_some());
let mut forwarded = head.headers.clone();
outcome.rewrite_cookies(&mut forwarded);
assert!(!forwarded.contains_key(http::header::COOKIE));
}
#[test]
fn selective_cookie_remove_vcl_import_rejects_bad_grammar_and_names() {
for vcl in [
"sub vcl_recv { remove_req_cookies(); }",
"sub vcl_recv { remove_req_cookies(parent); }",
r#"sub vcl_recv { remove_req_cookies("parent",); }"#,
r#"sub vcl_recv { remove_req_cookies("parent" "other"); }"#,
] {
let result = import_vcl(vcl).unwrap();
assert!(!result.warnings.is_empty(), "{vcl}");
assert!(result.rules.is_empty(), "{vcl}");
}
for bad in [serde_json::json!({"id": "bad", "actions": [{"type": "remove_named_cookies", "names": []}]}),
serde_json::json!({"id": "bad", "actions": [{"type": "remove_named_cookies", "names": ["bad;name"]}]})] {
assert!(validate_rules(&[rule(bad)], false).is_err());
}
let good = import_vcl(r#"sub vcl_recv { remove_req_cookies("parent_a", "parent_b"); }"#).unwrap();
assert!(good.warnings.is_empty());
validate_rules(&good.rules, false).unwrap();
} }
} }
+25
View File
@@ -606,6 +606,31 @@ fn vcl_actions(
Err(format!("set {target} is not supported")) Err(format!("set {target} is not supported"))
} }
} }
// RustProxy-specific, safe exact-name Cookie removal (not stock Varnish VCL).
(RuleStage::Request, "remove_req_cookies") => {
if tokens.len() < 4
|| !matches!(tokens.get(1), Some(VclToken::Sym("(")))
|| !matches!(tokens.last(), Some(VclToken::Sym(")")))
{
return Err("remove_req_cookies requires quoted cookie names".into());
}
let args = &tokens[2..tokens.len() - 1];
if args.len() % 2 == 0 {
return Err("remove_req_cookies expects comma-separated quoted names".into());
}
let mut names = Vec::new();
for (index, arg) in args.iter().enumerate() {
if index % 2 == 0 {
match arg {
VclToken::Str(name) => names.push(name.clone()),
_ => return Err("remove_req_cookies names must be quoted".into()),
}
} else if !matches!(arg, VclToken::Sym(",")) {
return Err("remove_req_cookies expects commas".into());
}
}
Ok(vec![RuleAction::RemoveNamedCookies { names }])
}
(RuleStage::Request, "hash_data") => match tokens { (RuleStage::Request, "hash_data") => match tokens {
[VclToken::Ident(_), VclToken::Sym("("), VclToken::Ident(value), VclToken::Sym(")")] [VclToken::Ident(_), VclToken::Sym("("), VclToken::Ident(value), VclToken::Sym(")")]
if value.eq_ignore_ascii_case("req.url") => if value.eq_ignore_ascii_case("req.url") =>