diff --git a/AGENTS.md b/AGENTS.md index c9b9311..e179029 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # RustProxy source and documentation maintenance -Current source version: **0.39.0**. The Cargo package and binary are named `rust-proxy`. +Current source version: **0.39.1**. The Cargo package and binary are named `rust-proxy`. Before editing, read [README.md](README.md), the relevant [documentation guide](docs/README.md) and the actual code and tests. Historical release experiments are not current specifications. Use the bundled `src/admin/openapi.json` for API routes and payloads; the source implementation is authoritative for runtime behavior. diff --git a/CHANGELOG.md b/CHANGELOG.md index fe96dd5..3357a93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ Release history focused on **features, settings, default behavior, compatibility and fixes**. Changes to internal code structure and preliminary performance experiments are intentionally omitted. Historical descriptions reflect their respective releases; consult the current documentation for the settings available in the latest release. +## 0.39.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). + +- **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. + ## 0.39.0 — Docker Cache/Traffic and CDN VCL patch (source-only changes) - **Cache and Traffic Docker scopes:** added Docker-generated Vhosts to both selectors, with readable container/hostname/agent labels. Added a Docker-inventory `catalog_version` so refreshes update the list even when the persisted configuration revision is unchanged. Cache purge and invalidation accept these IDs. diff --git a/Cargo.lock b/Cargo.lock index bef80ec..98adbbb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1914,7 +1914,7 @@ dependencies = [ [[package]] name = "rust-proxy" -version = "0.39.0" +version = "0.39.1" dependencies = [ "anyhow", "arc-swap", diff --git a/Cargo.toml b/Cargo.toml index 0906046..1b97860 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rust-proxy" -version = "0.39.0" +version = "0.39.1" edition = "2021" rust-version = "1.99.1" description = "RustProxy - independent reverse proxy with local administration" diff --git a/SHA256SUMS b/SHA256SUMS index 1b0086f..804abec 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -1,10 +1,10 @@ 61bf40a0572889dc8b0dda9eae4e93e44b0de9364b3c798106c85700ffb37c23 .dockerignore 4140a2956264b44f259e6a37fc00ba02097bbe68b09296e04d3d243c1287129b .env.example e76e688874828e3743d03693b1d2872b9633b4db09909673786caf30f7cfe489 .gitignore -d0ee3e0d9956ceb7384430cf12784b4173d9fb4e50d6be3a9ef082b3867ab4db AGENTS.md -0caffb8765928db11df750fada8fa9775663ba5fd236316189852f7bcf282021 CHANGELOG.md -958e2bb62b874e0e81efce99aaf4cf0a37148a698d6f35341bdcd4b733cabefd Cargo.lock -8cc2002d1c5fab90e75a451e55f889d1dce0e6bd1f7df8bdb6c10619e83a359a Cargo.toml +9ba24d43572540c7929cc58005b5a3b5b065ec3b896c76e7fe863c78c59e04a7 AGENTS.md +1e31a29e503e0ba0e77def8b6171df93b750e54a6c7918439aa72e771d9962d7 CHANGELOG.md +9ecd4d4f644cf9a4fdb4a2998a8cfdba270c926ffa93c6bfffa3d7a0adf55e85 Cargo.lock +9566307178ed2b4ab15aea7e5b66614a021634d513fd6f467a846ac8f278bfe9 Cargo.toml 788745d4f70a0382c6280020afbd48844bb2af65e835a826852143f8132cdeca Dockerfile 0d96a4ff68ad6d4b6f1f30f713b18d5184912ba8dd389f86aa7710db079abcb0 LICENSE 82d1dee2fc68158f0ea73259151461e64c8b18d807cd1fecfb1ed99dc30cf5f4 README.md @@ -41,13 +41,13 @@ f30c895df3d7f289f3b7c9a73969009ecf91110f59cb247daa242f68e78aa014 docker-agent/s c0940a4b323d71931cf2ad4ad24d58b6d6bfd49af90c6e3fc91fcbe2b4cf312f docs/ACCESS.md e986cbe1534bbe392b2ce6413fc00ac5bc5d70b40d50c247c5b1b6c7b2760fbe docs/API.md 728b15b9825f547f34c4121219784798dd046fbbdd72ece8906d0cd77e8efc64 docs/BACKUP.md -c3e356829a933b081ef9a359ab71fcd88e073c3c1f64f09a03c1f19589960240 docs/CACHE.md +b0c78b402f79e752d9eff53da0306c08e5aed7e5d4ebb886ac49b693c109dd50 docs/CACHE.md a64f72b95918c24938aa7268ec0a534cb0f28dd1ee0aa325b02c49f3347ccf54 docs/CERTIFICATES.md 6aa83366ad45227d10ebe121ed2c4f690ebcb826939ec2b2eafb40bfd714ac69 docs/CONFIGURATION.md fec29ce846d6705eb45819d85d382f28e28a146b265feab2e4c7cce2a35e5883 docs/CUSTOM_LOCATIONS.md 2f3e005ab01bb48b6a2d74dd8f163159f892d08c35d9ad7162e912e1d4def870 docs/DASHBOARD.md 81bd7a901619092e2a5a5fb7e4edd2157f2b5ce7e0483c24581ec290080446c0 docs/DOCKER_DISCOVERY.md -0a0ed8a27965635c841d80d4b905f996b78dd165d81827712a0d50c011310bbd docs/FEATURES.md +6d183d812d4725d51f4e2fb97e69b6195f33e144a8e084c0c14e6990eae1e963 docs/FEATURES.md f5835144cd2802abbcac3a36c76bdd4ec2f25fa49307facb199efec5bf9e92d3 docs/HEADLESS.md 4282602f0b814841f71282040003bec91c24611e5152b33407b76e62357f8d3a docs/INSTALL.md 6e37859bf0dced99d4a7db93790cb38fcd90191932827946d5223eaa4c784fce docs/LOGS.md @@ -55,17 +55,17 @@ f5835144cd2802abbcac3a36c76bdd4ec2f25fa49307facb199efec5bf9e92d3 docs/HEADLESS. a7717c4ab03417914805527e573ea1dfd5d35295bf7b347d0c098bda6d469850 docs/MONITORING.md 6d3937088eeb67a9f690d44ebe0b6e660b68116dbf69091ac7816bdc52cec2b6 docs/PERFORMANCE.md d5894c07c68ec4230987767198434abee13b0e525842fea21bcbe752fa82742b docs/PHP_FPM.md -36e9108818d2898f9fefd06274c50df8d54f4453f827cd306d7e506616f372a1 docs/README.md +e18a194de2d3f256884622e6e74453b47ff459f1a372944a0241ce1488a11e11 docs/README.md 490a6dbe870f2b1fd4ec7816768dde6c86fa7957fc9de2d2f075e123c9222222 docs/RESPONSE_DELIVERY.md 95ab4786792d5920a2e109b7d196838057f24b512a69d713fb5884dc75c84339 docs/SCREENSHOTS.md 3a48184b36d225757fc5e2d22c629f89bfe5d4007ff087f0be0ce02a5fb04c28 docs/SECURITY.md bbef60ff1771da9f48af812987766e1e479408873ae2f079b13f1d5c62ecc6ff docs/STREAMS.md c9c9a0b401f0565f15b834d855bfdb34edb3eab46bff03d9e0825af204d20bf8 docs/TODO.md 978097cf53314ad573583d7176491d984b9dbb22295df2b00168a28b14184c4a docs/TRANSPORT.md -be6e8af62a7bf958b94ec15e9e3263263e511d1d33abae4e45d114833fa52b07 docs/TROUBLESHOOTING.md -a4ef8aa0c632c79b468f821dc8c900c99898881253473faef7f97c937d315517 docs/VCL.md -66d640c08ea6ff6f05f917113bbc3dbd7bea81148dbd461d1f9d56ec2d9f9eae docs/VCL_SUPPORT_MATRIX.md -ec4acdcff607d3d8db04f7777643fe8cafad778c1fe0ccbcc24f2424912069e2 docs/VCL_TRAFFIC_COOKBOOK.md +1335bc863391858ff4d584eb7f8ad771e270d36708061f2a1bff09de7906a8ab docs/TROUBLESHOOTING.md +411dc0273bcbe17db65fb1272a80bc7fb0e74a3de36224a7510a13e0a3c23963 docs/VCL.md +fe6423cb6d6b1c953102b118e010e994d9d600725963af5707b755923e50e82f docs/VCL_SUPPORT_MATRIX.md +73279816139bec54f5b3c6a72eddff987ccfc46c85d487b413564002d337d9c9 docs/VCL_TRAFFIC_COOKBOOK.md 1169420deeed8f2e8f3a0acfb3ffe16a3419820ba1869059e0b82bb2411e1537 docs/VHOSTS.md e67928a9d044e71b681c3e52f9dd8b151d6b72f965d16d5da8b0eadde98b70e9 docs/WEB_SERVER.md 42822b1c9801bcadb0e2d785cb91883ca2df1da141222631f153030c95f5e197 docs/images/about.png @@ -101,6 +101,7 @@ ecfa04e9f1e9c4f1b1629854798dc432c24414cdd6e80788bceffe37a6716011 examples/vcl/h d055d1d6ee01a567a90a4f2599c276567b4f834203f5c08e23d8da25a66ce918 examples/vcl/private-routes-bypass.vcl 1c97e44b66765616a2756bc01ef1f100f82adcfe330271cde4bd5e7021221558 examples/vcl/public-catalog.vcl 718f6ee134b4d6691284a84ae4dbc2ac5d4c3de61bf1df7889b025f411e2ee43 examples/vcl/public-json-api.vcl +b009b3749233f844acacb9f48663e67d919baed4863bc89d38c1ab9677ef8237 examples/vcl/public-vhost-ignore-cookies.vcl 4f12a9802c0df71d950822c5a8b04afb39da79075bc146b5c72f3148cb47610b examples/vcl/static-assets-public.vcl 8cd3f62c6ffc8339facfbaa390ec88aae465e7e605ef403673be569e3308da02 examples/vcl/stream-and-errors-no-store.vcl 5ca6374c3125b0e1891a1554ab0414f7c5309459b7d79765550ac3ef3bd14fd4 examples/vcl/tracking-query-restricted.vcl @@ -123,8 +124,8 @@ e9cbb0224c4a3d23a6019ba557e0cd568c1ad5e1582ff1e335fb7d99b7a1055d integrations/r 3f092a9ab80221eddd67be4d1a776acbc6e04c1eb6011b588280c28e83b2582f integrations/routeros-oci-build/build-routeros-oci.sh 3f267cafa16006e5456ade78ee2d5fae02cc7ce747839523068ffd8d7c98798a integrations/routeros-oci-build/docker-entrypoint.sh ae2ee2887fcba096d0de25edcc18faa1ffec35759274518db1bf6d6982f7176c langs/README.md -6bd467554bee19d30fcaf92d3b177cfbc25e3937ca5ef3a1a244995e7c1a2e51 langs/en_US.json -b21057d0bc1951f4f284843d6037039572622590a16ce2fa874f4168e2578303 langs/pl_pl.json +a2b5f6d97c55b8aec1b4f30e0a8d27315dd64318b52089961a0d1c87695e2596 langs/en_US.json +9f653ba156a208054d227cbb919f3aaf27d5d41bd0d2c8aa506a3fe1034536f6 langs/pl_pl.json 8ed80f14633970899d56f4ea72684a8d4b1f2843c1c78bfacc4cbb5f7ce9ef4b make_zip.py e830d37dd1f81a4b0aa7d535f5bba69e34e433b0fd99cc8ee0b296786c32379a migrations/0002_admin.sql 20112cc82192098b8d602f1c4f7ca08712e9e1366c845fabb92753187c370d35 migrations/0003_certificate_renewals.sql @@ -162,6 +163,7 @@ a459d95bbb0076f33ade8b273b813308167f9d8d45242b309a2d18320ca0093c scripts/migrat d759315babd9971b354d6f702d4c861eb1cd5c41b1e2e0f1a94ad4d2c2db49a3 scripts/runtime/acme_provider.py e69813fb1d3a4cdcfb7243964cc323fc21a603087bf2e84188fa42b9d3cee4b5 scripts/runtime/acme_rfc2136.py 91c883cfdce94c8c22c98749f611317f538a112d29be4f3fb1fa460b8f29ceaa scripts/start_stream_backends.sh +7ab439d1a9cf3901f93e4d79577bbe6e8a3beaf5b7257e710e697fd9b6bf2084 scripts/test_public_cookie_template.cjs 046b4282550f5cb4e53906665c91c7442be70fc68fd0743466fd832582f7c979 scripts/test_stream_tcp.py f0b48ec0cc4411755cc0b4128eebce710375afa99344cb76198cf31074f8eb63 scripts/test_stream_udp.py 22e880e98c7b9d700c7a4c02b9b1d543e5dbd1f4ecdca42813a1083165b32a19 scripts/version.py @@ -248,7 +250,7 @@ b0930110e4eb7de6826e27b5b46c47e46556449fed6dc505d42da4f5e9c20366 src/admin/web/ b7ead49224a4ec67181d3f24f9d9634bd6d76756f826a4d5d993300637d1d8f3 src/admin/web/app/stream-dashboard.js 7de070cc8cdde45d7e0932259299e341e25b32c9ffbd87e4fcce934d0f090de4 src/admin/web/app/web-overview.js 857a3c49d003a4c3beed98acf404fcffa1b7b127f34579a916196e007e8a2963 src/admin/web/cache-panel.js -730b79e4dadc9b1487888dcd426518a76476aaa254bf4cc3410f35deb75b589e src/admin/web/cache-rules.js +42d6af0fa1d2a0e7366f24c5df5b9a14ab497902329c3d99db9cf3a666be4511 src/admin/web/cache-rules.js 6288b0a8228d828ac2e2535ace2d1aefd1c04011e789eb97f7279129874ac35c src/admin/web/certificate-api.js f554ca7179fe4d97ae24aa004d4bc9ada5f84fc78257891933a7fed728006ef8 src/admin/web/css/00-tokens.css f13fd5486664d9803a99e226321bc84bd571a100c105884e6c68b127071595f1 src/admin/web/css/10-base.css @@ -350,7 +352,7 @@ b75ff512a1c6344483e00d2c67578ceea6b5472c279da0246f3622daa68d7e16 src/cache/cold 7f81a07400ab680a34affa32b63199bb5ca7d4511dd9d58465f68279b32d3232 src/cache/collapse.rs 68e2e4b6fd294f795c13b8984149c628c0abc4e41c8e8e8a5c3656fd58dfbcc9 src/cache/dashboard.rs 302a1db06d8be4cc4f213f25209d2c357ec60e9e73f0dc89703d9eaf957dae57 src/cache/dashboard_tests.rs -847c660e6cb7d752f9dac2807c5045a000172c25b0e437cbade06ad7b101dcba src/cache/fill.rs +da41073d36453135624f6eba80db89e19e5fa2dccff188320acdb5f956113477 src/cache/fill.rs 675d18afb53f25c56cba49bbb431fa39ecd9d7bdd192c7b39b0698225de7a2a2 src/cache/invalidation.rs c1357a13658e1ed5158084d3a41ba9ea906512774a5863ce9c56cb508d3fa6c8 src/cache/invalidation/ban.rs bbd9f372648d89b5e14d5b58029582d37f66a89752caf2c14eb1cbf8f24bb7a0 src/cache/invalidation/http_invalidation_tests.rs @@ -360,7 +362,7 @@ bd831807ca4720b3a41a6ea1d9a6c0ed2d935225e2dacbd9313be064f2e4a20e src/cache/look dd2d3132d4a8d2f453021d27bd8c804159edd86d286d4c3ddf6b47aadca80a09 src/cache/lookup/hot.rs 4148106b9baf70e41eeba24233b1edbe8dd6f927c11f2c7647e89fbbfb60555e src/cache/lookup/hot_hit_034_tests.rs e9c6ab0c2be9f96573f826e6a1b9e4c2b8b526f779e72e95a6463ae07e45ab55 src/cache/lookup/insert.rs -7f02dc8eeb6123cb22307b76985b606afda2d87b7f845894685cfe4a9aee8b2a src/cache/lookup/tiered.rs +891461e5f23264a71c6f220c3a3e872488d2894a4409defda1672d085ab8ead9 src/cache/lookup/tiered.rs 46564e91dde4a3232a62ae56008ae9c6b45fe7c5520b19add5735c7a5a4c2d9d src/cache/mod.rs 0c8b0d550e94d4474dcdf991aa0340228dc5f2f904f39350e6e666a16f16fe87 src/cache/model.rs b96e30ef2b12ad7647915457f087a4d11b6141847bc5e971a75c2739c88c3d8c src/cache/model/cache.rs @@ -376,7 +378,7 @@ e26dce02df9c043329ca164fed215d271781bce8fb03240f528331bf3df6b9d7 src/cache/poli 12a6d5d9d6711e956391b4b952e8149658b8bf64cfcc0a4c59c281f2630a6aac src/cache/policy/scope_tests.rs c3a4300f7cdb6b2b7c16fbc489d49ba2451331bb4a55a2d9f618c684fd61eecb src/cache/range.rs 847fd250a795a554fa10176d439fb4e777d3dc75f90aeafb29b133a313c09eb9 src/cache/rules.rs -99719d4e8c9a27bac460b006aaea7f0f731bfb476003c051f7ebe823517e1d7a src/cache/rules_tests.rs +1e2dc5e75085fd40f7febabaf8154021c9040dfa626346c84b92a96dc0be91b6 src/cache/rules_tests.rs 48344d7dcbbb220d8c16f5aa9bb88d86a6388b226bbf93d0ca92d8dfbf2c8001 src/cache/stats.rs 2981e35a7fbbc2b36214b5518f4ba97d57c1d2e01f4f375175c4b2c6be955927 src/cache/tests.rs b969394b04859b269dcecd8958b1aab40b532709512714e9900f0ecad6b6d0c5 src/cache/tickets.rs @@ -493,7 +495,7 @@ a08ee061e146cb7a08311106f73a04468c89f77b6ad05a2c623621a2ae9faf2a src/proxy/mod. b83b9c30022e8c8fc97654a7d83ee44702c78bc92d2089bd397054e0023c3b7c src/proxy/request_id/mod.rs a57ea795430bf52d550083fef759c739f3821217aac465c0024aa1565b0727d1 src/proxy/request_id/tests.rs 7c676831d20f1f16a95d972b67a76261ee0e6fa839261511d0c796b86471082b src/proxy/types.rs -e44430c54038a7dc26f327b5d7085e965241da2ffef42c1526ebfc5168981f72 src/proxy/upstream_helpers.rs +96dd140a0d62d2ba8084aca1d05dbb0c7016a0e55b39e61cbac02f996ae655f4 src/proxy/upstream_helpers.rs 96d18a85beb9d9492f4d0690eefd9afad9c1c4eabc36f41b447b81861a92ed2a src/proxy/web_cache_revalidation/mod.rs 5522456cc85948228250feac92308d53b130c4a7af98d24f669aca4dfe6999b6 src/proxy/web_cache_revalidation/tests.rs 3d591201595a3b1e928ded20a8736477a47e5acc3bcbde158f7c17547ce155ba src/proxy/websocket.rs @@ -609,7 +611,6 @@ e5f5fbe702f66bfcbcbc1d1f3cd3d89bdbb929bb86aed94868a2a06a4b9e59e3 src/web_server b791762b4ab7a43c3be19df84e523faf3dfb4df055f66d02178f93edb60d2204 src/web_server/serve.rs 714418c86ab241020a561fcf662a8fe324a6a70cc2fd3a313c56d7939c14b9e8 src/web_server/tests.rs f00743af2cf4a5952caef7a1dcf68e7817b5599a252a9973e1c22045517c0b0e tests/fixtures/argon2id.json -9016b3aa11736927b3bc41c722555bc6b89c6b7e79dc829700b3c80d4ab07267 tests/js/cdn-cookie-template.cjs cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 third_party/swagger-ui-5.33.1/LICENSE 0d20d1adef18aee3f40dd258172155521ce702ac445cb5f7b7d60ed32dad2fb2 third_party/swagger-ui-5.33.1/NOTICE 2c9e148b9acd740850aa33ae52878f1ecf19cdc67f6041e2c0a7aab1e95782f2 third_party/swagger-ui-5.33.1/README.md diff --git a/docs/CACHE.md b/docs/CACHE.md index a6edb07..284f156 100644 --- a/docs/CACHE.md +++ b/docs/CACHE.md @@ -13,6 +13,14 @@ The **Static & diagnostics** subtab provides **Ignore request cookies for static 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) + +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. + +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). + +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. + **Do not extend** `Ignore Vary: Cookie for public static assets` to a general "Ignore Vary" control. `Accept-Encoding`, `Accept-Language`, `Accept`, `Origin`, `User-Agent` and custom response-specific dimensions can change bytes, permissions or CORS headers. Keep the response's actual dimensions and use the existing safe normalization of recognized list fields below, or remove an unnecessary `Vary` at the origin only after proving the response is invariant. A VCL `unset beresp.http.Vary` is *possible*, but it is not the equivalent of a guarded static-file optimization. ## `Vary` matching (RFC 9111 §4.1) @@ -152,6 +160,14 @@ done Look for cache reason labels including `request_cookie`, `request_authorization`, `response_cache_control`, `route_disabled` and `cache_hit` when diagnostic headers are enabled. A `MISS` alone does not prove the object was admitted to HOT/COLD. +### Browser differs from curl (HTML, cookies, reloads) + +Compare **two consecutive normal GET navigations** to exactly the same URL and inspect **Network → request headers** and **response headers** in the browser. Use `X-Cache-Reason` to distinguish `request_cookie` (BYPASS) from `request_no_cache` / `request_max_age` (revalidation) and from `cache_miss` (no matching stored variant). A browser may send session/analytics cookies absent from a plain curl request. `Vary: Cookie` is an explicit instruction to partition cached representations by the complete incoming Cookie header; a VCL rule stripping *approved technical cookies* from the request does not remove application cookies or automatically suppress `Vary: Cookie` for HTML. Do not remove the latter or strip session cookies unless the application guarantees that both headers and body are identical for every visitor. + +For a faithful command-line comparison, use **Copy as cURL** for a browser request and repeat the resulting command without changing its Cookie, `Accept-Encoding`, URL or request cache directives. Then test a second invocation with only irrelevant technical cookies omitted, if appropriate. Different compression/`Vary` representations may each have their own initial MISS. For manual reloads, check **Disable cache** in DevTools and `Cache-Control`/`Pragma` on the *request*. With the default `varnish_compatible=true`, only the supported reload directives are ignored for fresh lookup; `no-store`, Cookie bypass and credential policy are not ignored. + +An eligible uncached `HEAD` is forwarded upstream as `GET` and can populate the same cache entry as a future GET. RustProxy returns the HEAD headers and drains the fetched body **without delivering it to the HEAD client**; the fill is asynchronous and bounded by the configured cache object size and a 30-second deadline. A GET requested before this fill has completed may still show MISS or wait for the in-flight fill; if the body exceeds the size/deadline or fails, no object is stored. HEAD responses to requests which bypass the cache are **not** drained by this mechanism. + ### In-panel cache and VCL guide Click **Cache & VCL guide** in **Settings → Cache**, **Vhosts → Cache** or a Docker service's **Cache** editor for the same interactive modal. The example-insertion target is the **editor that opened the modal** (global, ordinary vhost or Docker vhost), not always the global rules. The context badge identifies the destination, and the scope note explains which rules/settings are inherited and which are local. Opening the guide from a vhost does not save or modify global rules. It shows the **current form values** for compatibility mode, fallback TTL and grace, including a warning if the cache is disabled. The form may have unsaved changes; the modal does not apply settings. Example VCL snippets explain how `Cookie`, `Vary`, safe `req.http.*`, `beresp.http.*`, `resp.http.*`, `beresp.uncacheable = false` and `return(hash)` affect cache decisions. The **Insert into VCL importer** buttons copy a starting snippet into that editor's Rules import textarea (without importing or saving the rule) and invalidate older import previews; warnings now require explicit approval of a partial import. The guide warns that only 200 responses can be stored, and that VCL export is an approximate view. Validate the rule tester before saving. The modal explicitly lists unsupported VCL hooks and includes a short HIT/MISS/BYPASS checklist. For complete syntax, use [VCL import](VCL.md). diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 52b5094..eca065e 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -73,6 +73,7 @@ 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. ![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. - 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). diff --git a/docs/README.md b/docs/README.md index 8bbb972..26356d5 100644 --- a/docs/README.md +++ b/docs/README.md @@ -37,7 +37,7 @@ Guides for operating RustProxy: installation, publishing services, security, cer ## Performance and delivery - [Cache](CACHE.md) — scope-aware Cache & VCL help modal from global/Vhost/Docker editors, a compact rule tester, HOT/COLD cache, RFC 9111 `Vary` matching/normalization, safe static-asset cookie exceptions, freshness, `Cache-Status` and invalidation. -- [VCL traffic cookbook](VCL_TRAFFIC_COOKBOOK.md) — 11 ready-to-import examples, public/private HTTP traffic cases, Cookie/`Vary` variants, `curl` verification and failure modes. +- [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. - [Complete VCL support matrix](VCL_SUPPORT_MATRIX.md) — line-by-line supported, restricted, graphical-only, intentionally excluded and missing instructions, with test scenarios. - [VCL compatibility and header overrides](VCL.md) — supported VCL import syntax, safe request-header edits, `beresp.uncacheable` precedence, `Vary`, cookies, approval of partial imports and storage limits. - [Response delivery](RESPONSE_DELIVERY.md) — compression, transformations and response headers. diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 96d11e0..219bc14 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -20,6 +20,7 @@ Start with a reproducible request, its hostname/path and the exact listener. Com | WebSocket handshake fails or disconnects | Vhost WebSockets flag, backend Upgrade support, TLS/frontend protocol path, WebSocket idle limits and auth redirect. | | `403` / `405` / `429` | Applicable IP/ACL/country policy, HTTP methods, rate limit, GeoIP availability, Basic/Tinyauth permissions. | | Cache always BYPASS or MISS | Global + Vhost enablement, cookies/login, origin `Cache-Control`, `Set-Cookie`, `Vary`, TTL, size and exclusion rules. | +| Browser misses cache while curl gets HIT | Inspect browser request `Cookie`, `Authorization`, `Cache-Control`, URL/query and `Accept-Encoding`; read `X-Cache-Reason`. Browser cookie bypass and `Vary: Cookie` variants differ from an anonymous curl GET. Do not strip application cookies from HTML to force sharing. | | Content remains stale | Cache Age/resident age, origin validator, policy changes, matching scheme/Host/query and selected purge scope. | | Static file not found | Document root, process read permissions, index files, symlink policy, `try_files` and rewrite ordering. | | PHP returns errors or another site's PHP settings | FPM endpoint/socket permission, distinct pool/INI settings, pool restart, PHP `PATH_INFO`, application logs. | diff --git a/docs/VCL.md b/docs/VCL.md index 8983216..af9579f 100644 --- a/docs/VCL.md +++ b/docs/VCL.md @@ -1,10 +1,10 @@ # VCL import: supported instructions and exact effects -This guide describes the VCL **subset implemented by RustProxy 0.39.0**, not the full Varnish Configuration Language. It is based on the VCL importer and cache-rule engine. Importing VCL **converts statements into graphical cache rules (which must then be saved)**; RustProxy does not execute arbitrary VCL text at request time. Unsupported instructions may be skipped with warnings or cause a parse error; they are not executed as Varnish code. **In the graphical importer, warnings pause conversion:** no rules are added until you explicitly choose **Add partial import (reviewed)**. Even after adding, you must separately save the configuration. The read-only VCL export is a human-oriented preview, **not** a lossless backup or a guaranteed re-importable VCL program. +This guide describes the VCL **subset implemented by RustProxy 0.39.1**, not the full Varnish Configuration Language. It is based on the VCL importer and cache-rule engine. Importing VCL **converts statements into graphical cache rules (which must then be saved)**; RustProxy does not execute arbitrary VCL text at request time. Unsupported instructions may be skipped with warnings or cause a parse error; they are not executed as Varnish code. **In the graphical importer, warnings pause conversion:** no rules are added until you explicitly choose **Add partial import (reviewed)**. Even after adding, you must separately save the configuration. The read-only VCL export is a human-oriented preview, **not** a lossless backup or a guaranteed re-importable VCL program. For a short operational reference inside the panel, open **Cache & VCL guide** from **Settings → Cache**, the ordinary **Vhost → Cache** editor or **Docker vhosts → Cache**. The same modal works in all three places; example VCL is pasted into the importer of the editor that opened the guide, and the modal labels that scope. The modal shows the current compatibility-mode, fallback-TTL and grace settings, explains `Vary` and header mutations with examples, and identifies unsupported Varnish hooks. It complements this exact syntax reference; it does not execute VCL or save settings. -For an expanded **implemented / restricted / graphical-only / intentionally excluded / not implemented** inventory, consult the [complete VCL support matrix](VCL_SUPPORT_MATRIX.md). For practical production scenarios, **11 copyable VCL examples**, HTTP traffic outcomes, a `curl` validation plan and troubleshooting, use the [VCL traffic cookbook](VCL_TRAFFIC_COOKBOOK.md) (also available from the embedded Reader). It names each supported hook, variable and return action and the deliberate HTTP/security boundaries. +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 @@ -147,14 +147,14 @@ sub vcl_recv { } ``` -Use `unset req.http.Cookie;` only when the origin does not need **any** cookies for that route. 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 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. ## `no-cache` and TTL - `varnish_compatible=true` and positive `cache.default_ttl_seconds` (or an explicit positive `set beresp.ttl`) may treat an otherwise eligible origin `Cache-Control: no-cache` as fresh for that TTL, **without requiring `public`**. This is RustProxy's configured override, **not** vanilla Varnish's built-in behavior. - `varnish_compatible=false` honors `no-cache` revalidation, including when a TTL action is present. An explicit *backend header rewrite* removing `no-cache` changes the response policy in both modes; that is a different and potentially unsafe operation. - Backend `private`, `no-store`, `Set-Cookie`, malformed `Vary`, unsupported status, invalid headers and size bounds still block storage **unless an administrator explicitly rewrites the affected cache-policy headers via trusted rules**. Client/request restrictions remain separate. -- **Only HTTP 200 origin responses are storable in RustProxy 0.39.0.** Setting `beresp.ttl` for `404`, `301` or `302` does not create a negative/redirect cache. The misleading 404 TTL template was removed from the graphical editor. Deliver-stage header rules can still edit those responses without making them cacheable. +- **Only HTTP 200 origin responses are storable in RustProxy 0.39.1.** Setting `beresp.ttl` for `404`, `301` or `302` does not create a negative/redirect cache. The misleading 404 TTL template was removed from the graphical editor. Deliver-stage header rules can still edit those responses without making them cacheable. - Hit-for-miss / hit-for-pass and `beresp.keep` are intentionally not imported. RustProxy already coalesces eligible misses and briefly remembers uncacheable fills for its collapse strategy, and independently retains validators for conditional revalidation. These are **not** Varnish-compatible hit-for-miss/pass objects or programmable `keep` semantics. ## Test an imported rule set diff --git a/docs/VCL_SUPPORT_MATRIX.md b/docs/VCL_SUPPORT_MATRIX.md index 4e1aa43..d0022a3 100644 --- a/docs/VCL_SUPPORT_MATRIX.md +++ b/docs/VCL_SUPPORT_MATRIX.md @@ -1,6 +1,6 @@ # VCL capability matrix: implemented, limited and unsupported -**Applies to the RustProxy 0.39.0 source tree with the Docker/Cache/Traffic and CDN-template fixes.** This is an implementation inventory, not a statement of general Varnish compatibility. The authoritative implementation is `src/cache/vcl.rs` (tokenization and import), `src/cache/rules.rs` (validation and rule evaluation), and `src/cache/policy.rs` / `src/cache/lookup.rs` (shared-cache admission and lookup). See [VCL syntax and header semantics](VCL.md) for implementation details, the [VCL traffic cookbook](VCL_TRAFFIC_COOKBOOK.md) for ready-to-import VCL and a request/response scenario matrix, and [HTTP cache](CACHE.md) for cache policy. +**Applies to the RustProxy 0.39.1 source tree with the Docker/Cache/Traffic and CDN-template fixes.** This is an implementation inventory, not a statement of general Varnish compatibility. The authoritative implementation is `src/cache/vcl.rs` (tokenization and import), `src/cache/rules.rs` (validation and rule evaluation), and `src/cache/policy.rs` / `src/cache/lookup.rs` (shared-cache admission and lookup). See [VCL syntax and header semantics](VCL.md) for implementation details, the [VCL traffic cookbook](VCL_TRAFFIC_COOKBOOK.md) for ready-to-import VCL and a request/response scenario matrix, and [HTTP cache](CACHE.md) for cache policy. ## Practical examples and traffic scenarios @@ -205,6 +205,10 @@ 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. 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 + +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. + ### Included opt-in CDN cookie policy The source file [`examples/vcl/cdn-technical-cookies.vcl`](../examples/vcl/cdn-technical-cookies.vcl) and the **CDN technical cookies** cache-rule template provide the same basic safe policy: bypass unsafe methods, sensitive paths and Authorization; strip Cookie only when **all cookies** are in a known allowlist; otherwise bypass. The list includes Cloudflare (`__cf_bm`, `cf_clearance`, `_cfuvid`, `__cfruid`, `__cfseq`) and Akamai (`_abck`, `ak_bmsc`, `bm_sz`, `bm_sv`). Review the list for your origin and CDN challenge flow: some technical/security cookies are needed by the origin and **must not** be stripped in those deployments. This policy is **opt-in**; it does not change the default behavior of existing Vhosts. diff --git a/docs/VCL_TRAFFIC_COOKBOOK.md b/docs/VCL_TRAFFIC_COOKBOOK.md index c60845c..9e05b19 100644 --- a/docs/VCL_TRAFFIC_COOKBOOK.md +++ b/docs/VCL_TRAFFIC_COOKBOOK.md @@ -1,6 +1,6 @@ # VCL cookbook: concrete use cases and HTTP traffic scenarios -**Target:** RustProxy **0.39.0** with the Docker Cache/Traffic and CDN cookie patch. This guide documents the *actual importer* (`src/cache/vcl.rs`), validated cache-rule actions (`src/cache/rules.rs`), and shared-cache admission documented in [Cache](CACHE.md). It is **not** a full Varnish implementation or a promise of exact Varnish semantics. +**Target:** RustProxy **0.39.1** with the Docker Cache/Traffic and CDN cookie patch. This guide documents the *actual importer* (`src/cache/vcl.rs`), validated cache-rule actions (`src/cache/rules.rs`), and shared-cache admission documented in [Cache](CACHE.md). It is **not** a full Varnish implementation or a promise of exact Varnish semantics. Read together with [VCL compatibility](VCL.md) and the [supported/unsupported capability matrix](VCL_SUPPORT_MATRIX.md). The examples are **separate policies**, not one file that should be imported wholesale. Copy one recipe into the correct Vhost scope, then reconcile it with existing global/local rules; **never paste contradictory `return(pass)` policies together without reviewing rule order**. @@ -31,6 +31,7 @@ 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 | | 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 | +| 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 | | Cloudflare/Akamai technical cookies | [CDN cookie allowlist](#4-cdn-technical-cookies-without-dropping-sessions) | Strip an **entire** allowlisted Cookie header | Partially delete one Cookie from a mixed list | | Public CSS, JS, fonts, images | [Static assets](#5-static-assets-and-vary-cookie) + native static settings | Strip request Cookie if proven safe; optional **conditional** `Vary: Cookie` treatment | Override any other arbitrary `Vary` dimension | | Multilingual catalog | [Language variants](#6-language-specific-representations) | Preserve origin `Vary: Accept-Language` and separate variants | Automatically translate or change language | @@ -40,7 +41,7 @@ Read together with [VCL compatibility](VCL.md) and the [supported/unsupported ca | Remove tracking parameters from cache identity | [Query rewrite](#10-tracking-query-normalization-restricted) or graphical Strip query | Drop approved params after URL normalization | Import arbitrary `regsub` or preserve regex URL semantics exactly | | Origin sets irrelevant `Set-Cookie` on public SVG | [Advanced public cookie cleanup](#11-advanced-removing-origin-set-cookie-high-risk) | Remove it before storage | Prove it was not needed for identity/session | | CORS responses differentiated by `Origin` | Origin's `Vary: Origin` | Keep origins separate | Safely collapse all origins into one cached response | -| Cache error pages/redirects (`404`, `301`, `302`) | **Not supported** | No cache storage in 0.39.0 | Invent negative/redirect-cache TTL via VCL | +| Cache error pages/redirects (`404`, `301`, `302`) | **Not supported** | No cache storage in 0.39.1 | Invent negative/redirect-cache TTL via VCL | | IP ranges, backend routing, purge, TLS security | Native ACL/Vhost/Cache API settings | Dedicated supported configuration | Import ACL/director/`return(purge)` as executable VCL | ## C. Copy-and-import VCL recipes @@ -300,7 +301,7 @@ sub vcl_hash { **Prerequisites:** Use native proxy/WebSocket/stream and backend retry configuration for those separate operations. -**Caveat:** This is not a Varnish `vcl_backend_error`, retry, pipe or stale-if-error implementation. `500` was never eligible for 0.39.0 shared storage anyway. +**Caveat:** This is not a Varnish `vcl_backend_error`, retry, pipe or stale-if-error implementation. `500` was never eligible for 0.39.1 shared storage anyway. Source: [`examples/vcl/stream-and-errors-no-store.vcl`](../examples/vcl/stream-and-errors-no-store.vcl). @@ -402,6 +403,42 @@ sub vcl_backend_response { } ``` +### 12. Public Vhost: inherited cookies (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. + +**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. + +**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. + +**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. + +Source: [`examples/vcl/public-vhost-ignore-cookies.vcl`](../examples/vcl/public-vhost-ignore-cookies.vcl). + +```vcl +// OPT-IN: use ONLY on an HTTP reverse-proxy Vhost with fully public, +// cookie-independent GET/HEAD content. Import into that Vhost, NOT globally. +// Useful when a parent domain sets Domain=.example.test cookies that a public +// sibling subdomain neither needs nor should forward to the backend. +// +// Cookie does not include the cookie's Domain attribute. It is IMPOSSIBLE +// to distinguish inherited cookies from host-only cookies in vcl_recv. +// This deliberately strips ALL cookies on permitted public paths; verify +// that users do not need login, preferences, locale, cart or affinity there. +// Customize the excluded path list to fit your application before enabling. +// 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 { + 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)(/|[?]|$)") { + unset req.http.Cookie; + return(hash); + } +} +``` + ## D. Real HTTP traffic: what is handled and what is not The outcomes below describe **decision paths**, not a guaranteed X-Cache label: proxy route exclusions, access checks, configuration, origin responses, object sizes, validators, time, and storage limits still apply. The word **eligible** means the request may look up or populate cache if all other conditions succeed. @@ -423,6 +460,9 @@ 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; session=b` | CDN cookie allowlist | PASS | Even one non-allowlisted name prevents removal. | | Two physical Cookie fields, one technical and one session | CDN cookie allowlist | PASS | Patched matcher examines combined cookie values. | +| `GET /catalog`, Cookie from parent domain | Public-Vhost opt-in | Strip all Cookie; eligible | Only on verified cookie-independent pages with reviewed exclusions. | +| `GET /account`, parent-domain Cookie | Public-Vhost opt-in | Ordinary bypass/auth rules | Protected-path guard leaves Cookie untouched. | +| `GET /catalog`, Cookie plus Authorization | Public-Vhost opt-in | 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/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`. | @@ -432,7 +472,7 @@ The outcomes below describe **decision paths**, not a guaranteed X-Cache label: ### D2. Origin response and `Vary` -| Backend sends | RustProxy 0.39.0 consequence | Safety check | +| Backend sends | RustProxy 0.39.1 consequence | Safety check | |---|---|---| | `200`, public/fresh, no Set-Cookie, valid Vary | Potential shared-store candidate | Response must really be identical for all users. | | `200`, `Cache-Control: private` | Not storable without **dangerous explicit rewrite** | Never rewrite private content to public. | @@ -507,6 +547,11 @@ curl -sS -o /dev/null -D - "$BASE/catalog/item/1" curl -sS -o /dev/null -D - -H 'Cookie: session=test' "$BASE/catalog/item/1" curl -sS -o /dev/null -D - -H 'Authorization: Bearer test' "$BASE/catalog/item/1" +# Optional public-Vhost template (after explicitly enabling and reviewing paths): +# browser-equivalent Cookie is removed for genuinely public pages. +curl -sS -o /dev/null -D - -H 'Cookie: parent_session=abc' "$BASE/catalog/item/1" +curl -sS -o /dev/null -D - -H 'Cookie: parent_session=abc' "$BASE/catalog/item/1" + # Technical-only cookies vs mixed cookies: inspect origin logs as well. curl -sS -o /dev/null -D - -H 'Cookie: __cf_bm=test' "$BASE/catalog/item/1" curl -sS -o /dev/null -D - -H 'Cookie: __cf_bm=test; session=test' "$BASE/catalog/item/1" diff --git a/examples/vcl/public-vhost-ignore-cookies.vcl b/examples/vcl/public-vhost-ignore-cookies.vcl new file mode 100644 index 0000000..25dd4aa --- /dev/null +++ b/examples/vcl/public-vhost-ignore-cookies.vcl @@ -0,0 +1,21 @@ +// OPT-IN: use ONLY on an HTTP reverse-proxy Vhost with fully public, +// cookie-independent GET/HEAD content. Import into that Vhost, NOT globally. +// Useful when a parent domain sets Domain=.example.test cookies that a public +// sibling subdomain neither needs nor should forward to the backend. +// +// Cookie does not include the cookie's Domain attribute. It is IMPOSSIBLE +// to distinguish inherited cookies from host-only cookies in vcl_recv. +// This deliberately strips ALL cookies on permitted public paths; verify +// that users do not need login, preferences, locale, cart or affinity there. +// Customize the excluded path list to fit your application before enabling. +// 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 { + 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)(/|[?]|$)") { + unset req.http.Cookie; + return(hash); + } +} diff --git a/langs/en_US.json b/langs/en_US.json index b36290f..d44caa8 100644 --- a/langs/en_US.json +++ b/langs/en_US.json @@ -3573,6 +3573,7 @@ "cacheRuleTplCdnAuth": "CDN: bypass Authorization", "cacheRuleTplCdnStrip": "CDN: remove ONLY technical cookies", "cacheRuleTplCdnRemaining": "CDN: bypass remaining cookies", + "cacheRuleTplPubliccookies": "Public vhost: ignore inherited cookies (enable after review)", "cacheRuleTplTracking": "Ignore tracking parameters (utm_*, fbclid, gclid)", "cacheRuleTplApi": "API: bypass cache", "cacheRuleTplLanguage": "Separate cache per language cookie", diff --git a/langs/pl_pl.json b/langs/pl_pl.json index 2dba0d5..ca463b0 100644 --- a/langs/pl_pl.json +++ b/langs/pl_pl.json @@ -3573,6 +3573,7 @@ "cacheRuleTplCdnAuth": "CDN: omijaj Authorization", "cacheRuleTplCdnStrip": "CDN: usuwaj tylko ciasteczka techniczne", "cacheRuleTplCdnRemaining": "CDN: pomijaj pozostałe ciasteczka", + "cacheRuleTplPubliccookies": "Publiczny vhost: ignoruj odziedziczone cookies (wymaga włączenia)", "cacheRuleTplTracking": "Ignoruj parametry śledzące (utm_*, fbclid, gclid)", "cacheRuleTplApi": "API: pomiń cache", "cacheRuleTplLanguage": "Osobny cache dla ciasteczka języka", diff --git a/scripts/test_public_cookie_template.cjs b/scripts/test_public_cookie_template.cjs new file mode 100644 index 0000000..d7578fd --- /dev/null +++ b/scripts/test_public_cookie_template.cjs @@ -0,0 +1,41 @@ +// Source-level UI template contract test; does not execute the Rust proxy. +'use strict'; +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const path = require('node:path'); +const root = path.resolve(__dirname, '..'); +const ui = fs.readFileSync(path.join(root, 'src/admin/web/cache-rules.js'), 'utf8'); +const sandbox = { window: {}, t: key => key }; +vm.runInNewContext(ui, sandbox, { filename: 'cache-rules.js' }); +const tpl = sandbox.window.rustProxyCacheRules.TEMPLATES.publiccookies; +assert.equal(typeof tpl, 'function', 'new template is registered'); +const rules = JSON.parse(JSON.stringify(tpl())); +assert.equal(rules.length, 1); +const rule = rules[0]; +assert.equal(rule.enabled, false, 'operator must opt in explicitly'); +assert.equal(rule.stage, 'request'); +assert.equal(rule.match, 'all'); +assert.equal(rule.stop, true); +assert.deepEqual(rule.actions, [{ type: 'strip_cookies', keep: [] }, { type: 'lookup' }]); +const method = rule.conditions.find(c => c.field === 'method'); +assert.deepEqual(method.values, ['GET', 'HEAD']); +const cookie = rule.conditions.find(c => c.name === 'Cookie'); +assert.equal(cookie.operator, 'exists'); +const auth = rule.conditions.find(c => c.name === 'Authorization'); +assert.equal(auth.operator, 'exists'); +assert.equal(auth.negate, true); +const restricted = rule.conditions.find(c => c.field === 'path'); +assert.equal(restricted.negate, true); +const rex = new RegExp(restricted.values[0]); +for (const path of ['/admin', '/admin/orders', '/api/public', '/konto', '/login?next=/']) + assert.ok(rex.test(path), `protect ${path}`); +for (const path of ['/', '/rezerwa/15', '/catalog', '/stories/article']) + assert.ok(!rex.test(path), `public ${path}`); +assert.match(ui, /filter\(key => scope === "vhost" \|\| key !== "publiccookies"\)/, + 'dangerous opt-in template is unavailable in global editor'); +const vcl = fs.readFileSync(path.join(root, 'examples/vcl/public-vhost-ignore-cookies.vcl'), 'utf8'); +assert.ok(vcl.includes(restricted.values[0]), 'VCL and UI use the same excluded paths'); +for (const line of ['unset req.http.Cookie;', 'return(hash);', 'req.http.Cookie', '!req.http.Authorization']) + assert.ok(vcl.includes(line), `${line} is in example VCL`); +console.log('Public-cookie graphical template/VCL contract: OK'); diff --git a/src/admin/web/cache-rules.js b/src/admin/web/cache-rules.js index 3a5e4eb..de5b268 100644 --- a/src/admin/web/cache-rules.js +++ b/src/admin/web/cache-rules.js @@ -177,6 +177,19 @@ window.rustProxyCacheRules = (() => { { name: t("cacheRuleTplCdnRemaining"), stage: "request", match: "all", conditions: [{ field: "header", name: "Cookie", operator: "exists" }], actions: [{ type: "pass" }], stop: true }, ]; }, + // Opt-in for a verified public vhost. Do not try to infer the Cookie + // Domain: it is absent from the HTTP Cookie request header. Disabled by + // default; the operator must review the private-path exclusions first. + publiccookies: () => [{ + name: t("cacheRuleTplPubliccookies"), enabled: false, stage: "request", match: "all", + conditions: [ + { field: "method", operator: "equals", values: ["GET", "HEAD"] }, + { field: "header", name: "Cookie", operator: "exists" }, + { field: "header", name: "Authorization", operator: "exists", negate: true }, + { field: "path", operator: "regex", values: ["^/(admin|api|auth|login|logout|account|profile|user|settings|dashboard|cart|checkout|panel|konto|wp-admin|wp-login[.]php)(/|[?]|$)"], negate: true }, + ], + actions: [{ type: "strip_cookies", keep: [] }, { type: "lookup" }], stop: true, + }], tracking: () => [{ name: t("cacheRuleTplTracking"), stage: "request", match: "all", conditions: [], actions: [{ type: "strip_query", params: ["utm_*", "fbclid", "gclid", "msclkid", "mc_cid", "mc_eid", "_ga"] }] }], api: () => [{ name: t("cacheRuleTplApi"), stage: "request", match: "all", conditions: [{ field: "path", operator: "prefix", values: ["/api/"] }], actions: [{ type: "pass" }] }], language: () => [{ name: t("cacheRuleTplLanguage"), stage: "request", match: "all", conditions: [], actions: [{ type: "hash_cookie", name: "lang" }] }], @@ -274,7 +287,7 @@ window.rustProxyCacheRules = (() => { helpLinks.append(guide, docs); root.append(helpLinks); } - const templates = select([["", t("cacheRulesTemplates")], ...Object.keys(TEMPLATES).map(key => [key, t(`cacheRuleTpl${key[0].toUpperCase()}${key.slice(1)}`)])], "", t("cacheRulesTemplates")); + const templates = select([["", t("cacheRulesTemplates")], ...Object.keys(TEMPLATES).filter(key => scope === "vhost" || key !== "publiccookies").map(key => [key, t(`cacheRuleTpl${key[0].toUpperCase()}${key.slice(1)}`)])], "", t("cacheRulesTemplates")); templates.classList.add("cache-rules-templates"); const importButton = el("button", t("cacheRulesImportVcl"), "outline"); importButton.type = "button"; const exportButton = el("button", t("cacheRulesExportVcl"), "outline"); exportButton.type = "button"; diff --git a/src/cache/fill.rs b/src/cache/fill.rs index d54075c..f282e45 100644 --- a/src/cache/fill.rs +++ b/src/cache/fill.rs @@ -190,6 +190,13 @@ impl Candidate { } } +/// A response body still owns an active cache fill. The proxy uses this +/// marker to finish filling a cacheable HEAD miss without sending a body. +#[derive(Clone, Copy)] +pub(crate) struct PendingFill { + pub max_body_bytes: usize, +} + struct FillBody { inner: Body, candidate: Option, diff --git a/src/cache/lookup/tiered.rs b/src/cache/lookup/tiered.rs index 221421f..6702a79 100644 --- a/src/cache/lookup/tiered.rs +++ b/src/cache/lookup/tiered.rs @@ -205,13 +205,20 @@ impl Cache { candidate.finish(); return Response::from_parts(parts, body); } - Response::from_parts( + // A HEAD miss is fetched upstream as GET. The proxy must still consume + // the GET body to publish this candidate before stripping the body for + // the HEAD client. Mark *only* responses with a live fill candidate. + let mut response = Response::from_parts( parts, Body::new(FillBody { inner: body, candidate: Some(candidate), done: false, }), - ) + ); + response.extensions_mut().insert(PendingFill { + max_body_bytes: settings.max_object_bytes, + }); + response } } diff --git a/src/cache/rules_tests.rs b/src/cache/rules_tests.rs index 64673b1..3c3b6ec 100644 --- a/src/cache/rules_tests.rs +++ b/src/cache/rules_tests.rs @@ -1061,4 +1061,70 @@ sub vcl_deliver { post.method = Method::POST; assert!(compiled.evaluate_request(&post, false).pass.is_some()); } + + #[test] + fn vcl_public_vhost_template_strips_inherited_cookies_only_on_public_get_head() { + let vcl = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/examples/vcl/public-vhost-ignore-cookies.vcl" + )); + let imported = import_vcl(vcl).unwrap(); + assert!(imported.warnings.is_empty(), "{:?}", imported.warnings); + assert!(!imported.rules.is_empty()); + validate_rules(&imported.rules, false).unwrap(); + let compiled = CompiledRules::compile("public", &imported.rules, &[], false).unwrap(); + + for cookie in [ + "sso_session=secret", + "sso_session=secret; marketing_id=xyz", + "tracking=one; unknown=two", + ] { + let input = request("/rezerwa/15", None, &[("cookie", cookie)]); + let outcome = compiled.evaluate_request(&input, false); + assert!(outcome.pass.is_none(), "unexpected pass on {cookie}"); + assert!(outcome.lookup.is_some(), "missing hash on {cookie}"); + let mut forwarded = input.headers.clone(); + outcome.rewrite_cookies(&mut forwarded); + assert!(!forwarded.contains_key(http::header::COOKIE), "{cookie}"); + } + // Cookie can be split across fields; both must be dropped only here. + let split = request("/", None, &[ + ("cookie", "parent_session=one"), + ("cookie", "preference=two"), + ]); + let outcome = compiled.evaluate_request(&split, false); + let mut forwarded = split.headers.clone(); + outcome.rewrite_cookies(&mut forwarded); + assert!(!forwarded.contains_key(http::header::COOKIE)); + + let anonymous = request("/rezerwa/15", None, &[]); + assert!(compiled.evaluate_request(&anonymous, false).lookup.is_none()); + for path in [ + "/admin", "/admin/users", "/api/orders", "/auth/callback", + "/login", "/login/callback", "/account", "/profile", + "/checkout", "/cart", "/konto", "/wp-admin", + ] { + let input = request(path, None, &[("cookie", "session=secret")]); + let outcome = compiled.evaluate_request(&input, false); + assert!(outcome.lookup.is_none(), "private path must not hash: {path}"); + assert!(outcome.strip_cookies.is_none(), "private cookie stripped: {path}"); + } + let with_auth = request("/rezerwa/15", None, &[ + ("cookie", "session=secret"), ("authorization", "Bearer access"), + ]); + let outcome = compiled.evaluate_request(&with_auth, false); + assert!(outcome.lookup.is_none()); + assert!(outcome.strip_cookies.is_none()); + for method in [Method::POST, Method::PUT, Method::DELETE] { + let mut input = request("/rezerwa/15", None, &[("cookie", "session=secret")]); + input.method = method; + let outcome = compiled.evaluate_request(&input, false); + assert!(outcome.lookup.is_none()); + assert!(outcome.strip_cookies.is_none()); + } + let mut head = request("/rezerwa/15", None, &[("cookie", "parent=secret")]); + head.method = Method::HEAD; + assert!(compiled.evaluate_request(&head, false).lookup.is_some()); + } + } diff --git a/src/proxy/upstream_helpers.rs b/src/proxy/upstream_helpers.rs index a40e0df..6358cf9 100644 --- a/src/proxy/upstream_helpers.rs +++ b/src/proxy/upstream_helpers.rs @@ -41,6 +41,38 @@ fn should_replace_error_page(response: &Response, minimal_welcome: bool) -> bool .is_none() } +// A cacheable HEAD miss is sent to the origin as GET. The resulting body +// must be read to EOF for FillBody to publish the entry; dropping it here +// would turn every cold HEAD into another MISS. Only drain bodies explicitly +// marked by the cache layer. Enforce byte and wall-clock limits so a broken +// origin cannot leave unbounded detached work after the HEAD response. +fn strip_head_response_body(response: &mut Response) { + let fill = response.extensions_mut().remove::(); + let body = std::mem::replace(response.body_mut(), Body::empty()); + if let Some(fill) = fill { + tokio::spawn(async move { + let _ = tokio::time::timeout(Duration::from_secs(30), async move { + let mut body = body; + let mut received = 0usize; + while let Some(frame) = body.frame().await { + match frame { + Ok(frame) => { + if let Some(data) = frame.data_ref() { + received = received.saturating_add(data.len()); + if received > fill.max_body_bytes { + break; + } + } + } + Err(_) => break, + } + } + }) + .await; + }); + } +} + async fn observe(state: Arc, mut request: Request) -> Response { let snapshot = state.config.load_full(); let selected = response_context(&snapshot, &request); @@ -478,7 +510,7 @@ async fn observe(state: Arc, mut request: Request) -> Response { .fetch_add(1, Ordering::Relaxed); } if is_head { - *response.body_mut() = Body::empty(); + strip_head_response_body(&mut response); } let response_read_timeout = frontend_context .as_ref() @@ -518,6 +550,101 @@ fn effective_host(request: &Request, tls: bool) -> Result { } } +#[cfg(test)] +mod head_cache_fill_tests { + use super::*; + + #[tokio::test] + async fn head_miss_finishes_cache_fill_without_delivering_body() { + let cache = crate::cache::Cache::new(1); + let settings = crate::cache::Settings { + enabled: true, + varnish_compatible: false, + ..Default::default() + }; + let ticket = cache + .ticket(1, "https", "example.test", "app", "/head", &HeaderMap::new()) + .expect("valid cache ticket"); + let mut origin = Response::new(Body::from("cached from HEAD")); + origin.headers_mut().insert( + ::http::header::CACHE_CONTROL, + HeaderValue::from_static("public, max-age=60"), + ); + origin.headers_mut().insert( + ::http::header::CONTENT_LENGTH, + HeaderValue::from_static("16"), + ); + let plan = crate::cache::plan( + StatusCode::OK, + origin.headers(), + &settings, + Duration::ZERO, + ) + .expect("cacheable GET representation"); + let mut head = cache.wrap(origin, ticket.clone(), plan, &settings); + assert!(head.extensions().get::().is_some()); + strip_head_response_body(&mut head); + assert_eq!(head.headers()[::http::header::CONTENT_LENGTH], "16"); + assert!(head.body().is_end_stream(), "HEAD must have no response body"); + assert!(head.extensions().get::().is_none()); + + // The cache fill is detached from the HEAD response. It must finish + // independently, allowing a later GET or HEAD to reuse this object. + let hit = tokio::time::timeout(Duration::from_secs(2), async { + loop { + if let Some(hit) = cache.get(&ticket) { + break hit; + } + tokio::task::yield_now().await; + } + }) + .await + .expect("HEAD fill should populate cache"); + assert_eq!( + hit.response.into_body().collect().await.unwrap().to_bytes(), + Bytes::from_static(b"cached from HEAD") + ); + } + + #[tokio::test] + async fn oversized_head_fill_is_not_published() { + let cache = crate::cache::Cache::new(1); + let settings = crate::cache::Settings { + enabled: true, + varnish_compatible: false, + max_object_bytes: 1024, + ..Default::default() + }; + let ticket = cache + .ticket(1, "https", "example.test", "app", "/too-big", &HeaderMap::new()) + .expect("valid cache ticket"); + let mut origin = Response::new(Body::from(Bytes::from(vec![b'x'; 1025]))); + origin.headers_mut().insert( + ::http::header::CACHE_CONTROL, + HeaderValue::from_static("public, max-age=60"), + ); + let plan = crate::cache::plan( + StatusCode::OK, + origin.headers(), + &settings, + Duration::ZERO, + ) + .expect("cacheable headers, unknown body length"); + let mut head = cache.wrap(origin, ticket.clone(), plan, &settings); + strip_head_response_body(&mut head); + assert!(head.body().is_end_stream()); + tokio::time::sleep(Duration::from_millis(20)).await; + assert!(cache.get(&ticket).is_none(), "oversized HEAD must not be cached"); + } + + #[tokio::test] + async fn head_without_cache_fill_drops_body() { + let mut response = Response::new(Body::from("not cacheable")); + strip_head_response_body(&mut response); + assert!(response.body().is_end_stream()); + } +} + #[cfg(test)] mod auth_provider_page_interception_tests { use super::*;