diff --git a/AGENTS.md b/AGENTS.md index 4d5807e..3c3c6a0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # RustProxy source and documentation maintenance -Current source version: **0.41.4**. The Cargo package and binary are named `rust-proxy`. +Current source version: **0.42.0**. 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 9322e74..24683cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ 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.42.0 — HTTP policy rules with VCL cooperation + +- **Source cleanup:** the preflight script now only checks the four core project files and never modifies the source tree. Removed legacy repair logic and commands/references to absent development tools. VCL test type aliases fix strict Clippy `type_complexity` diagnostics without suppressing warnings. +- **VCL branch fixes:** imported `if`/`elsif`/`else` chains retain the selected branch when an action changes or removes a guard header. Nested and remaining actions still execute; independent later conditions read the updated headers. Canonical control-flow groups are validated and preserved by the editor. Existing flat conversions retain their old semantics and must be replaced by a fresh import of the original VCL to gain the fix; native graphical rules keep their existing behavior. +- **Credential cache fix:** unsafe forced caching partitions the full Cookie/Authorization combination before lookup, including missing and empty fields; explicit VCL/policy lookup similarly partitions Cookie without allowing Authorization. A versioned key namespace isolates older incomplete HOT/COLD variants. Required `Vary` dimensions remain explicit, foreground `304` uses the correct variant, and credential-partitioned fills avoid anonymous proactive refresh. +- **Optional HTTP policies:** global, Vhost, Docker-assignment and custom-location `policy` objects provide named ACLs, nested AND/OR/NOT, full-header and comma-list samples/counts, numeric/CIDR/regex conditions, converters, inline maps and request-scoped `txn.*` variables. Rules compile with the configuration; missing policy objects preserve previous behavior. +- **Staged actions:** explicit `pre_route`, `request`, `backend_request`, `backend_response`, `deliver` and `after_response` stages support conditional header operations, safe token-list normalization/merging, variables, validated target rewrites, selection of configured backend members, local responses and cache/compression decisions. Final `Vary` normalization preserves all dimensions and `*`; the original duplicate-field ACL scenario is included as JSON and importable text. +- **VCL compatibility:** existing VCL import, Vhost-before-Global precedence, header ownership and terminal pass/hash behavior remain intact. Policy request mutations are visible to VCL; backend-response policy follows existing `beresp` edits before cache planning; delivery policy follows VCL, with a final stage after compression and legacy dynamic headers. Explicit pass/no-store remains restrictive, VCL TTL/grace takes precedence, and per-client backend-response changes or backend-request customization conservatively bypass shared storage. +- **Cache validation:** foreground `304` refreshes honor policy no-store/TTL and VCL TTL/grace precedence; explicit header hashing retains Cookie partitioning even with static cookie sharing. Configured backend-response policies and explicit policy hash dimensions use synchronous expired-object validation and disable proactive background refresh so rules keep the live transaction context and hash inputs; fresh HITs remain available. +- **Configuration and panel:** a strict HAProxy **subset** importer rejects unsupported source instead of activating partial rules. JSON remains the saved representation. Draft policy testing exposes matches and applied actions; global policies have a revisioned configuration section. Existing Headers, Cache/VCL and location settings remain available. +- **Documentation and verification:** embedded [HTTP policy guide](docs/POLICY.md), configuration examples, Rust regression tests and DOM editor tests cover policy/VCL cooperation and configuration handling. + ## 0.41.4 — Responsive backend charts and table layout fix - **Backends table:** optional **Columns → Responsive charts** expands and shrinks the Requests, Latency and Traffic mini charts with the available width and UI scale. Defaults to off; saved per administrator. Error causes now retain native table-cell layout, removing the misaligned internal row border. No change to metrics or proxy behavior. Rebuild and run regression tests before deployment. diff --git a/Cargo.lock b/Cargo.lock index 2341291..4718008 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1914,7 +1914,7 @@ dependencies = [ [[package]] name = "rust-proxy" -version = "0.41.4" +version = "0.42.0" dependencies = [ "anyhow", "arc-swap", diff --git a/Cargo.toml b/Cargo.toml index e3acdc6..4bb4cd8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rust-proxy" -version = "0.41.4" +version = "0.42.0" edition = "2021" rust-version = "1.99.1" description = "RustProxy - independent reverse proxy with local administration" diff --git a/README.md b/README.md index c000dbc..fbc96b1 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ | Certificates | PEM import, ACME HTTP-01 and DNS-01 (Cloudflare, OVH, RFC 2136), automatic renewal, external Certbot files, hot reload | | Access | IP/CIDR, DNS/DDNS and country rules, ACL profiles, rate limits, method and Content-Type policies, Basic Auth, Tinyauth, Authelia, authentik, OIDC | | Delivery | Shared memory and disk cache, `Cache-Status`, purge/ban, gzip/Brotli/Zstandard compression, asset minification | +| HTTP policies | Named ACLs, nested conditions, maps, transaction variables and staged header/routing/cache actions; HAProxy subset import and cooperation with existing VCL | | Monitoring | Live dashboard, per-Vhost statistics, live and stored logs, Prometheus exporter, JSON metrics, Grafana and Nagios | | Operations | Configuration history and restore, encrypted backups, Docker discovery, Nginx Proxy Manager import, REST API with OpenAPI | diff --git a/SHA256SUMS b/SHA256SUMS index 0f9729f..296b573 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -1,18 +1,18 @@ 61bf40a0572889dc8b0dda9eae4e93e44b0de9364b3c798106c85700ffb37c23 .dockerignore 4140a2956264b44f259e6a37fc00ba02097bbe68b09296e04d3d243c1287129b .env.example 0a5e87541831edca0e7164c6469dba01a8a7053ab14dbfb8019c83e4db10edc2 .gitignore -fdd8a547e8ab715bdd227b7280320c509bd7659d31e61aa8212fd7a32308aa6e AGENTS.md -3ee40d0f4181b5ebdde703cc8ef5453e9b1ec5679f1927dc9a3ff2ee9511e933 CHANGELOG.md -4f02d7725c286a546f8e6e272318a0c01c4e9d4de7226b93ce6f7e881e197723 Cargo.lock -d84476e0fe880b9c930a4eb7c0c4da690683b70ce1c20590b6ce2e739c08f69d Cargo.toml +e0fb5e3c9802fa95f8fcfecee18f5bed936e7c93c15ae81a20006a1c883bb70a AGENTS.md +6a3d09a98ed3cd62fd0a50897d8d00709f4d56e585a788b9edffaa9738bd747b CHANGELOG.md +5ea6dce0bfe8db7e5e12807edbd0804e0269894f6648083a25e56d34c19ca527 Cargo.lock +9240c31771784cb86f24f194ba79f594dbb898823a6a41705932acae48885177 Cargo.toml 788745d4f70a0382c6280020afbd48844bb2af65e835a826852143f8132cdeca Dockerfile 0d96a4ff68ad6d4b6f1f30f713b18d5184912ba8dd389f86aa7710db079abcb0 LICENSE -82d1dee2fc68158f0ea73259151461e64c8b18d807cd1fecfb1ed99dc30cf5f4 README.md +97dadb97158d0d7eccb11f9e882218a9496cd585f8fb28cf9c6a31a79114f4c2 README.md da8311e3db945290666324a2f24bf4521b365272d7ac3f862ded1be993eea646 UPDATE_CHECK.toml 120609370b79e192c9a2a72c1706225aa5da06c5806efa26a010b733e120322b build.rs 95ececaba550a4bcfd6754073877ba0633373b1e1451521b9ac905a51e8ca6eb deploy/README.md 13d514de5042a230cacf8c10abe1ef183c94ac799a89b8e2c111152ac7c69b48 deploy/rustproxy.service -c111f5b20484707b80efb7dd9176acbaa27b63ac78db497261ac234821e1fade dev.sh +f743b9e61528453ecedc637678ab42d2d4415a8b0923de15df5335110e1d1777 dev.sh e8996fdf05a0a9e317e0ab5cd4139d037c6ca272173b7b5d30d2da7256feafd4 docker-agent/README.md e9f18b358a740f1fe16e369ed16ee37581b8ce4c94ddeb34a1a37b89a49b5a06 docker-agent/certificate.go 600d5aebc8557d6987158969d494bade1ba46ccf9d1cd573d357d0106db26b2b docker-agent/cli_test.go @@ -39,36 +39,37 @@ f30c895df3d7f289f3b7c9a73969009ecf91110f59cb247daa242f68e78aa014 docker-agent/s 20313df0c14a1696d099ed881b159fe854e92538a60548a1729f92babaead881 docker-agent/system.go 188b74ec4f58da1b46d86925a67b6a590c92fb4fd7516e8d03d43871bc3b4542 docker-agent/system_test.go c0940a4b323d71931cf2ad4ad24d58b6d6bfd49af90c6e3fc91fcbe2b4cf312f docs/ACCESS.md -31600bb19ee6c655eb1aad4b59bccff49e1864e986c4cb8db15af8b471543099 docs/API.md +74046c96c7c28e5d0f5d81ee9cf223a6519dad8abc0945959b78eab750815480 docs/API.md 728b15b9825f547f34c4121219784798dd046fbbdd72ece8906d0cd77e8efc64 docs/BACKUP.md -96c01362bad3a6218c0b8795f2e76aac220cc5526e257208e14817bc532752e4 docs/CACHE.md +bfe96dd91dfc6e07918a662d98b036f12ceb011a5aa8381b3778bd0c964b19ab docs/CACHE.md 51d34823d139ff3b0b8e1cf1a31850746be5ed7da847a2cca51be36fd5f7733a docs/CACHE_TEMPLATE_LIBRARY.md 31285f000cf725d018a926023fe608fec983b959053f7a55e0954b962a8bc20c docs/CERTIFICATES.md -6aa83366ad45227d10ebe121ed2c4f690ebcb826939ec2b2eafb40bfd714ac69 docs/CONFIGURATION.md -08fd05b08c7b0a749ebf2337e4243f6aba6f654eaee5398a3f478c720df4e4dd docs/CUSTOM_LOCATIONS.md +81df6715e2f07617fe0bbb0960c4d5bdac28cf665ce7297fa3768118e6ab28ba docs/CONFIGURATION.md +209664f5937d88c857aab2db3ced9fdfc264b526671ef59b999a00c5d7678aa3 docs/CUSTOM_LOCATIONS.md 16d4510e38d43c3bbde9b7dab7af3aeb0cb837dc2f1956cfaad7a9a11bea3bfc docs/DASHBOARD.md -81bd7a901619092e2a5a5fb7e4edd2157f2b5ce7e0483c24581ec290080446c0 docs/DOCKER_DISCOVERY.md -b43a03fa804b1dbc4ee64f8f17fd9fa5c2f76306af3c8897897668cea2069c97 docs/FEATURES.md -5e12c541648ca382366f999e93b8ae434603e5c750f6fad3bd6a8df81e3724a1 docs/HEADLESS.md +53cb0ce7db5ce25e4c2381de3a6e875d212deeed08861da63050de6c51a442bd docs/DOCKER_DISCOVERY.md +ffb639a56c2d4d14a6e8c2a0f95a4cf6baca9062363386ac9c30e1609e14fa33 docs/FEATURES.md +f7bb59821e0d6c45ae2a1789086fd9dab33d91c0ceae784ae68f64bd13b5f496 docs/HEADLESS.md 4282602f0b814841f71282040003bec91c24611e5152b33407b76e62357f8d3a docs/INSTALL.md 3268808766ad66263e465f251dce18cff2e7ede355638dc2b0975870b1a5eead docs/LOAD_BALANCING.md 425f1ca32172d987b6fabbd08076bbd091101193e103e9fe5452e0709159a2bd docs/LOGS.md -0e9ae9509a78d00951d2c7c3f13eaf518d1f3448a29b048f5933e1f5f8440275 docs/MIGRATION.md +3b889851ba3405247861391aefbcfcaa5a96cf9b09b3e0e0e412ec2f54e11b1a docs/MIGRATION.md 48105c4303401aa99ffff00d3ebaf3024535a492a4a7b883c6803e4732b37434 docs/MONITORING.md 6d3937088eeb67a9f690d44ebe0b6e660b68116dbf69091ac7816bdc52cec2b6 docs/PERFORMANCE.md d5894c07c68ec4230987767198434abee13b0e525842fea21bcbe752fa82742b docs/PHP_FPM.md -f6ff6dc567870fc3a03b7d51f8b53a262402cbfac08dcecf2d6f0b62cebe868b docs/README.md -b731219c844841c925abc522c7e09432795f591dd5bddd49ffafe013b550f736 docs/RESPONSE_DELIVERY.md +46e8d3017f644d8bd293d2ccca2555aa83e4261f743a64c47552022ee5a6bfd8 docs/POLICY.md +eb1876d1a2f76108be40a6e8745ec9c41437024ab2ae8374e11c319d3ec0741f docs/README.md +e90842a75459ddb5892334f66a4139d9301280b4d0c17077d211749bd7c90d80 docs/RESPONSE_DELIVERY.md 95ab4786792d5920a2e109b7d196838057f24b512a69d713fb5884dc75c84339 docs/SCREENSHOTS.md 3a48184b36d225757fc5e2d22c629f89bfe5d4007ff087f0be0ce02a5fb04c28 docs/SECURITY.md -bbef60ff1771da9f48af812987766e1e479408873ae2f079b13f1d5c62ecc6ff docs/STREAMS.md +a1f69782b08d395a9672250eaac4595ffb1465b66a7a62901781a01a9030c6a0 docs/STREAMS.md c9c9a0b401f0565f15b834d855bfdb34edb3eab46bff03d9e0825af204d20bf8 docs/TODO.md c4407cbd70d181e87f64e8d1736624d7b8b59a04b915ad3464f0e1f16d474e99 docs/TRANSPORT.md 1335bc863391858ff4d584eb7f8ad771e270d36708061f2a1bff09de7906a8ab docs/TROUBLESHOOTING.md -cf3d53cd628428c4a69eb09f3e09dc8c08f21c113b992a30b34c3dc6de1b9488 docs/VCL.md -847368584ef1778ccf741b2cef6fdb4b1477aa101e2a06274399c0af5ae9ff9f docs/VCL_SUPPORT_MATRIX.md +a9bd4c63756ec7021a437bc361b32ba8721167140e14473aed8df1bd58b165db docs/VCL.md +0656fb488d6c9ff449ff0205ee22287e488267a82e7f9cf9d0e4dff44925b76f docs/VCL_SUPPORT_MATRIX.md 382e084a1f9e35627ccb43eaf451c18fb6d0cc752397c2178108d71de592a931 docs/VCL_TRAFFIC_COOKBOOK.md -26a00c60a1cb3ecb0a46d92ef18209135d0138a7e2286e998ada4426ef90e135 docs/VHOSTS.md +8d65c10ac7be9a315c788cacd0ddb0b02433a7774f0567c6574d92e0cd69f2da docs/VHOSTS.md 495c9977cb24995acb8cc846bd18cedc3957ab262c5134362bb0e9c9d2246680 docs/WEB_SERVER.md 42822b1c9801bcadb0e2d785cb91883ca2df1da141222631f153030c95f5e197 docs/images/about.png deff2393a987ac7102179dc85b48baf2c4a3882291bb8c7c584d760cc497c631 docs/images/api.png @@ -97,6 +98,9 @@ e31ac05a99615e4ea6c4c9a8b2e090968583fe3959f838a600b5740cb170f8c5 examples/confi 695cc7621aa403148fcd0868f351b6e9ccc076fe35610e779af4a72f94d7d5f4 examples/http3-vhost.json b26833cb4251f9390a44192ecc827ff7f052fd19016a5ccf7498c94503ab4ce3 examples/mock-vhost.json a6b835dc07defc12b8f0e48491d5f413843c8be2ba4501d7c28140a2822b034f examples/oidc-vhost.json +b8b27d5faab93b4d277dfadc14315111ceca9cec5913bd1df202ed1d0fc36a45 examples/policy-vary.haproxy +16e12a7160ba51ed65be6ffdc411ef899e4c8382b3354ef3d31c94f404c32a25 examples/policy-vary.json +4ac5aa7eae19a70c16b0cda7762383987cb95341e5fcd6bbf8d919e7a611953d examples/policy-vcl-cooperation.json 134d4a59727b27accb3141d4cee26a4a74157d236de4996bfd682e639462b2b5 examples/tinyauth-vhost.json 5a8f3a8a054abc89c6e78896b9fe2f903212199a24dc3d2d2bcbd0696a31bcde examples/transport.json 07fef8fb9d20f9d6db1520625f17283a1b598a07e3bd10c1ecbb964923899bc2 examples/vcl/advanced-set-cookie-removal.vcl @@ -132,9 +136,9 @@ e9cbb0224c4a3d23a6019ba557e0cd568c1ad5e1582ff1e335fb7d99b7a1055d integrations/r 3f092a9ab80221eddd67be4d1a776acbc6e04c1eb6011b588280c28e83b2582f integrations/routeros-oci-build/build-routeros-oci.sh 3f267cafa16006e5456ade78ee2d5fae02cc7ce747839523068ffd8d7c98798a integrations/routeros-oci-build/docker-entrypoint.sh ae2ee2887fcba096d0de25edcc18faa1ffec35759274518db1bf6d6982f7176c langs/README.md -74112fd556f321382627294f9adf140855201326cdfc40eb21fa184402f048f1 langs/en_US.json -bfc84663e9e0ad666cc5daefed920927ae53cd2365dbcf8cea95935f8e6d176f langs/pl_pl.json -8ed80f14633970899d56f4ea72684a8d4b1f2843c1c78bfacc4cbb5f7ce9ef4b make_zip.py +1bc02d07b52899120c019d071d09d40e2a0676479bbe6dcd7075386f332c8ade langs/en_US.json +00bd1ce68b5dedbb0ed1fc0d55b07bdcbeed7977a8669fc90873c65cfa5c1b3b langs/pl_pl.json +38773ed251a8c24af353f4744e498ae2bc7d4151df7927e942c4ac223f6008e1 make_zip.py e830d37dd1f81a4b0aa7d535f5bba69e34e433b0fd99cc8ee0b296786c32379a migrations/0002_admin.sql 20112cc82192098b8d602f1c4f7ca08712e9e1366c845fabb92753187c370d35 migrations/0003_certificate_renewals.sql 5c62da30fa9db594a4d656c77ae676d3c388072b6a85f91170ec7d911d7cde43 migrations/0004_admin_preferences.sql @@ -153,7 +157,7 @@ ee50f38c037765fab742e888d4b9fc4d874c31c785c6064d4eca3d2c4d24d944 nagios/check_r 1465396cf1358067e9fe48b3d61f28fd4ac65c577b67c502950ce6b42ecbe3b3 nagios/check_rustproxy_latency 6e036f736a2b40feb78eec17bf34871771524190f283591d1c89e48e6d2271e6 nagios/check_rustproxy_queues 7458b2d74495e6fb1c1edeea4d5a793705476431dadb60627187111f91441e13 rust-toolchain.toml -fd1c34599f725ad5f7c3c0cc89e08b11917baef02c83af054ac8528b2e01dd8e scripts/README.md +5611ed0aecdd6411597a6869af5d1a0382d08c3a167dfd054f606be7db0603fa scripts/README.md 1d63e9cea61a744f1bf2085cbb7c3d8755b3eda1569c8532574dd4fb6a840678 scripts/__init__.py 292c65ad2a7f0ca13da4a00a836df17c3192728dc02034b75a6a70eb6b5eb25c scripts/audit_css_usage.py 5a942edcf2b5549042fe88b6d2704139abab5820607f7afdd7ea72cef1a83bf2 scripts/build-release.sh @@ -167,11 +171,10 @@ a59587ce8ad41b1bbb431356b58398f9c8ff7cb96a613a91752e907a70e10c2e scripts/deploy 2cc658faaa610b21b48942c59b955525539ad4503fd60f2a49c7e626a22faaff scripts/migration/migrate_npm.py a459d95bbb0076f33ade8b273b813308167f9d8d45242b309a2d18320ca0093c scripts/migration/migrate_npm_api.py 4c905a387f210c30fbf12a7738676fd39819bc96bc4a272da1db5f18a2d3013e scripts/migration/migrate_npm_core.py -960fdf97ec899107a567405e9b9c2b70ee16951d5ea26c37d885a7920f7b3aa1 scripts/preflight.py +be88ca2163d84913e0d9ee97f95d3217d4a92fc7df122927336deae5f8fcfb3d scripts/preflight.py 3d6a0503afc25beab79ddc86864bcbb15248ded7368d33aa64321b8cdff59933 scripts/resolve_dependencies_0312.sh 2a95ee85848d347b419dcc2c3a1c65b62d491081a554f5fb50623770a5c15b80 scripts/runtime/acme_provider.py e69813fb1d3a4cdcfb7243964cc323fc21a603087bf2e84188fa42b9d3cee4b5 scripts/runtime/acme_rfc2136.py -91c883cfdce94c8c22c98749f611317f538a112d29be4f3fb1fa460b8f29ceaa scripts/start_stream_backends.sh 22e880e98c7b9d700c7a4c02b9b1d543e5dbd1f4ecdca42813a1083165b32a19 scripts/version.py 78efae6c43732c0f5527d467bf07d1f890da361925416c89b58bc449d852fc2b src/acl.rs 1d55ecb2e104be1d3b19623a1380584724c106ed234d2e79fd2a2fef1d891ee3 src/acl/dynamic/mod.rs @@ -196,34 +199,36 @@ f73678bfa4c4f92779cf4e8ae2feb37419de320fb1b53111c982539d5761dbcf src/admin/aler 4a8b6406a44508b8ba102fef0d8309e871dbe0cbdbee1e6c8721baaca0c1aee1 src/admin/certificate_inspection_tests.rs 6baad2543021bcbe64688a2f58f78a5f5b83b8b189ad9ee7415adf5566bdd4be src/admin/certificates.rs 521ac794501570cfa2e8e50c3a5cec2ca08ee4dbce8ac9c0e0310c09612f1062 src/admin/config_reload.rs -7cac90d705a201b764d283e06774744e4b358eb157a8c492357bfc21aed37543 src/admin/config_sections.rs +11f1501574e4042fab7a97f18a19c8a69856e157933a56baaf4c7cc9d2da9a8c src/admin/config_sections.rs c51f725075b5c4fc3fb7fb8b8b5f73987bff698a400e8950e968068b97a77631 src/admin/dashboard_presets.rs aae1ca0e70d987830bd63948d431f54302083148177c1b551565be12df7fe771 src/admin/documentation.rs -de085220a500bc27c454eb042dc9a5beb47b441c602b92696344c9e809f36b76 src/admin/documentation/documents.rs -b9c2952e3fcfca540d0ad64f2d3acc5c1f5240e707f4f23ef4d452f46fcb520f src/admin/documentation/tests.rs +4191044a22ec0013937dda3241837b2ac9a03b615717f09996566de7eb1a22d3 src/admin/documentation/documents.rs +f9b2c8fe62cc92d7693e46145b2543b12dd6d4943fe2d52c67ed6958d4af83de src/admin/documentation/tests.rs 1ce779b84aa8f47bdb3c34f83593c1f2f06d2235f0319847096cfcd035434168 src/admin/file_log_search.rs 2805c7d1c08fed6a54711b8b5d51078ba8c2daecae431b6c7c39fe0345b6cecc src/admin/file_logs.rs 737876e72c315987515d259de84d46c22780e89f19ed3102fc5c4f55d0e2951b src/admin/file_logs_io.rs e2253599b5e39510946729920d240711403a3889cc495eb49824296228f1d080 src/admin/file_logs_query.rs 1594c8666991c1d07487a6a718211ef404cf49114721960f7e119bb7f605e3d2 src/admin/logging_api.rs -51228956c33358278ebed62941da273e1e87d0b5c5d1c40cc0d2c91aec9d7362 src/admin/mod.rs -a53150853e1fffc086a915365f83726e2185bf09e78cf5a50484dc978367dd7f src/admin/openapi.json +781fd5f176dd8f2372f75bd90edcf160708e2d0a8d6a115ba4b283c0cd49eb2d src/admin/mod.rs +0639c54b11b6ca908244c0d0b11c81383d0299ba58eb6644bb41314d3817679d src/admin/openapi.json 9f8842cdec27d703d1795dd6eb37d9420e9f5a2e56a0df93278c92bace5d1f4c src/admin/operations.rs 257d93a29d0bda96462bcf695aba8d0ec0f9412c379e066ec46ae8ee034e3a53 src/admin/panel_assets.rs f5127855c2994d052678865df36d703b74f4a0afc633daf7718b10da18d26e37 src/admin/panel_content.rs +a051fb9f67d4d9dac1c05327006639b3dfcd7d25172e48f457bb2724c1ead9ba src/admin/policy.rs +db7ea754ad1b06c52165b51726999d8f72c23279632ff66a43e9a47b34e8f527 src/admin/policy_access_tests.rs 229bbdf33d54bda51950358aff812f4a90944f13147c1225c23eff855bf8bb69 src/admin/preferences.rs f3635b624cf48598d68274a470d84d15ef9f6070d56e437a0031afa724471d5e src/admin/preferences_columns.rs ea202c67d9acb7614046f153beecdff10d5822b3d5627eaf2ebda33954b36474 src/admin/preferences_tests.rs 62ecbae5dee00aeeca3eb806e2605372471dfab971cde8f66f11e711df8fcea1 src/admin/public/mod.rs 7a00e4ab943f74d2b1bdcbfab7f9cd3f584e9f59536b4aca6c4c31f5f5508d12 src/admin/public/tests.rs 6930b4f4b45257772b321b20a9becdf9bc4610274852948ba38c2d0cdf02dfaf src/admin/refresh_preferences.rs -37c71fbed3792f1cb0c3fb7e9f17eeabde601ef694cc5c2f99763017f4c4f0be src/admin/router.rs +9085350f0859101249cbb1356a60234c747b10a92557f3781cdfdab29df8fe09 src/admin/router.rs fba52102e77ca8871a42f97c91be8f10a9aa4f997868652d550fff3fbd41b66e src/admin/session.rs 1c4d04b14a508fca7537f54e660124f4dae1964b48d7bd3b878ec4faa7156805 src/admin/status.rs 9b5bc1a439c5e5611c47732fe86097877b50b09b10a0838d9813314ea6232d0c src/admin/status_live.rs c20f214e2ec2a14d8a88d07a63a27d9396a7a6bf9446f6ee31dbd77b12e4b585 src/admin/status_system.rs ea1d0b8ff69157215f9358f0de35b91462ab2bf1fb97f9ce9b37846d0432c56b src/admin/tail.rs -df5a27217dddb114fa7612332232f6315bad7870112e5686b2613ba293614f83 src/admin/tests.rs +b4bcfb9fc989d5586ca3d82e8b5777c306e9a6720f9ec011d09bd786db9faf49 src/admin/tests.rs d6c7ef48325c8f4f7ae7504827c0255c263b41c838f61960381907ca78eb9b95 src/admin/web/acl-picker.js 1e46ac359a11a85374d93936fb849864bea43021c20770fff5076acd846e8859 src/admin/web/acme.js 30a71c399e9a2cd9a4c1830568e4767f219ce09bca35f6d5fd22424f1a6617ac src/admin/web/admin_origin_rejected.html @@ -252,12 +257,12 @@ b0930110e4eb7de6826e27b5b46c47e46556449fed6dc505d42da4f5e9c20366 src/admin/web/ 3b8e566d81a5b94ef21c73e7805ae128454f085554de9358040de266bcbdb0e0 src/admin/web/app/refresh.js 66de066418464669f9d47c6f61b0333b13b95e188a90bb964c7851acb3bc3cbf src/admin/web/app/runtime.js 31201586925e6f4792071d7d03fb05dcc4a69a03c02a4e85eb0746f45af68074 src/admin/web/app/session-resume.js -65e46879e94f13e8271d4105246f29d820903fe68b9efe2dbe4a4ff661ca9dfc src/admin/web/app/settings.js +7870ccf4d8868c7f72328d2144dfed3c855e62d9b4649b9ec87045afef3e3794 src/admin/web/app/settings.js 2281f06990f86acd3ff12fa368e1b73e4c83601e20245f24abbce389dfccb77f src/admin/web/app/sidebar.js b7ead49224a4ec67181d3f24f9d9634bd6d76756f826a4d5d993300637d1d8f3 src/admin/web/app/stream-dashboard.js 7de070cc8cdde45d7e0932259299e341e25b32c9ffbd87e4fcce934d0f090de4 src/admin/web/app/web-overview.js ba22ff211f408052aee0aa75a5a52734b1c257247e7112972aff75a9646faf22 src/admin/web/cache-panel.js -fe7982223b9b3ba70a18c28a09659884cd7277f8d152c851f4db1d482ab5ea04 src/admin/web/cache-rules.js +433f5ccf0a4df1c4452f746f7b2f351f6712ee73873cb07204638c205e4f2c88 src/admin/web/cache-rules.js 6288b0a8228d828ac2e2535ace2d1aefd1c04011e789eb97f7279129874ac35c src/admin/web/certificate-api.js f554ca7179fe4d97ae24aa004d4bc9ada5f84fc78257891933a7fed728006ef8 src/admin/web/css/00-tokens.css fd33db7132f8d6f98c46b60e882d1521cdae905176900fc50cfc7cc58d22d7b3 src/admin/web/css/10-base.css @@ -265,15 +270,16 @@ fd33db7132f8d6f98c46b60e882d1521cdae905176900fc50cfc7cc58d22d7b3 src/admin/web/ 5c2b8f73624d83801ad7f408680e93f7761749f221791995da52f0bb475c9037 src/admin/web/css/30-overview.css 585c5146f86c5bb91e0e5167c57cbc441bb4d46bffcaa01bf34ff636af70672d src/admin/web/css/40-editors.css 53ceb0dc4b958f1eded1e1a0e58e585ef13e4ebb45b797ba1b8534b552ea6c16 src/admin/web/css/50-settings.css +80df922a015bc6a390652ca74d5eeea726af32678b453ec8bec0e5d5ff8d30e6 src/admin/web/css/55-policy.css 6c369dc95db9f60680f38218fb504eb552bb05da3e819eeca44527f14a23d51e src/admin/web/css/60-monitoring.css 5ca5f911d7ded39a34c5c65980f82cc4d39cfa911cb9554550dfc78bba48461d src/admin/web/css/70-responsive.css -8009afdb04d5170687816730cc930a22fead1fe0248835ca7e8de81d6907395d src/admin/web/css/README.md -8241bd9489dfed082863948829a44a49bf0a8e9cd63c55809655109e393e0918 src/admin/web/css/manifest.json +2b17a65d83ce699a25bc74142e02f0aeb2d849004d7479dda158501029ad23fb src/admin/web/css/README.md +ea08fbe1a616042f2dab32d829dba837660a5facb068bb9d5a9b3abdb5c00717 src/admin/web/css/manifest.json 7d3c09f13e3026e3230f35472a9d163b790c7c68b672127ed9fb0e66b26e3d70 src/admin/web/dashboard-builtin-presets.json 78bf6179f769b68d518028464697e50dea5d75e33ecb1b89d88e2c2b01e86bf2 src/admin/web/dashboard-defaults.json 355046ecb80ce6adb73ceabd29825b0cf79ca364771070cedd5eb44760fae890 src/admin/web/dashboard-widgets.json 50d1ebcbaf4d0b2968da23bb943fc3f67131c5d32df3f61d23ff37aad9da5b81 src/admin/web/demo.html -155c0ba1e7cb7168e8b4c37ab7653eea84f0214645fa16d10193ec3277b50480 src/admin/web/docker.js +fb2800f2bcbe06d1cd933d5f0e8082e2b098aee41cedb00850b4371560650fe3 src/admin/web/docker.js 8bf5d1f4f06d6e87536d808a680bf3d3a0c90c1637df0e58da667fd22ad4782d src/admin/web/docs.css aeffd403fa1823df7d9fa4c48280b4033b2d15e4cb9f66608caff89290de0a52 src/admin/web/docs.html 306db8db9e4d651a85e09dbc15464e7f920d7fe5bd9ec9d1d8068321eb0106ab src/admin/web/docs.js @@ -294,7 +300,7 @@ e6c4d91d1542d0a5b47bb8736f9539d43a6713df5a473b635519d5b7eac2eb9c src/admin/web/ 0a5fff35555153f59d4346933030a67b6e1a8768cee7a47cfa2fcf1a2c564f63 src/admin/web/favicon.svg e0f0b302092ced1c84ef7e99864984444f0e9d4e3b7d85e74d3507d566952a7f src/admin/web/file-logs.js 85f54ce519140a38e31fb1b3d5974585748d7162f0499aa63703c1db56334b2c src/admin/web/host404.js -25885b9c756fd9ade8b99cf8b89cad8c89d208205f905d37d1d484d46f1187d1 src/admin/web/index.html +45cb6a2228e412226d23b1598ce0c4fe5b5f7f102fc8c9196a0dc63401164a0e src/admin/web/index.html be9999a001c59630963d60539e860b59999dcf74c5ff0087b12a6fb69b4e7bd2 src/admin/web/integrations.js 7a12f020fc587205694978ab41b660e9a80487d413fbf6e34fc525eabc58308f src/admin/web/login-keys.json ac9f667273918e18406df06cb2613c923f50a88897693a03a18f500e22dc6ec2 src/admin/web/login.html @@ -302,19 +308,23 @@ c2e5f554810b8e34fb47361fb90a01073a2e332ee26d82e030956fad3ec1f83e src/admin/web/ 6185182b81273372dbd506fa57281ee81d3cd1233ac328640a7f33794f754e1b src/admin/web/management.js 1f3d10e389c9c20e6eb019509fa6e82b50c6b43bbf988c1210a4d42bb73985d0 src/admin/web/partials/overview-charts.html bd94e61e051a6bebe0afbda0a21aa36349c2067516b974986765555ed47455cc src/admin/web/partials/overview-metrics.html +f8173daf375c43f9356bf19c7290ca8d17db3a735f6922ce82a6603ca5acd85e src/admin/web/policy.js 80d6eb03f204a90f7b140c5b053d0fd8facb350b1c96b74fa1402e2a35d4fb10 src/admin/web/prometheus-token.js b2d4b67fb65c55003e516e23dd783de55b0f00278035f16589f156a4659b7a54 src/admin/web/redirects.js -f8c3424d17bb94f80f00a7f8f4fac7ac3c8718141e975ccf5b42cc8686a00082 src/admin/web/settings.js +86700d2cb268ecf6eae8292acc6513b9c650810a5290823e7e2d69f836ba3537 src/admin/web/settings.js 8eadbada619b15087783dcfa0e889a81f88e78034d084c5ab616f7912b835940 src/admin/web/status_200.html 6322e589c449eee6db9c3499bb5643d6261f5fc3a5d730cff12cef70d5699fa2 src/admin/web/streams.js 14ef42dec556c5fa62ff4ed4d6865d28f322e8e963dc43e3a714ef9d0af12ac6 src/admin/web/system-info.js +cb125143a071c89a686be2f8fb684ed73c350bd2e2423c34e640fb33236686f4 src/admin/web/tests/cache-rules.dom.test.cjs +9896ce1af9e1793b33e555c283e83e7956eaa03263805e0fd074bfdb1b455214 src/admin/web/tests/policy.dom.test.cjs +af19ed0f3545b7f8184e4ff73ab3e654d15223813df197dac887e91e0154b287 src/admin/web/tests/policy.test.cjs 12db5600c14cadbbbe7676b170b058e9695108d2661d9cd6b61fe91d355ac731 src/admin/web/tls-configurator.js 336cc5b2a3e5e2514b6b15eed5f2b1ba714458d0e3e913d6f9ad7c870623c758 src/admin/web/traffic-panel.js 675ea169d4cc55fda5e291af536338b882bede1eaa6c9d5cc7dfde0779c7c4d1 src/admin/web/transform-panel.js c30373b0f2dc5672f88bc6fad0ffd5f6d85496d75da8fae83c6aa306e4e0f676 src/admin/web/vhosts/balancing.js -b2944b302f4abe21f649ec7abced34d2d49f97e1e01d9f26ae4d4b29b7a8538d src/admin/web/vhosts/core.js -72badbb336422bb6216881861849c50f678f7868df3e70d3586562f67028b9b0 src/admin/web/vhosts/editor.js -3562bca612223ed9c5586fe14ef238c7b475766f83d832e062a84af22d3a747d src/admin/web/vhosts/headers-tab.js +fd3bb828c0daeb06ca7bdc108c7e471c7ac4421b02caacbf8563e80ad6ec7b9f src/admin/web/vhosts/core.js +786f89e025e9273a9c550b128871f0539789129c118220e52ed6201a0affd418 src/admin/web/vhosts/editor.js +f082588c35d981fc689542d4c12a7614638279335220d587fdee5d3fff822e80 src/admin/web/vhosts/headers-tab.js 3776f72d7051af86ac5fbdd4581040dd88a424c0c6cde789301b032b159094d8 src/admin/web/vhosts/health.js b3239e67901f1796d7a974ade0796f2e3590ff8064628a5629b78c7f6ce2f32e src/admin/web/vhosts/protocol.js 8c3da49973c62333559b0e3588c02beb0b425c025eac5cfa82a1bb968f70d9dd src/admin/web/vhosts/rates.js @@ -353,7 +363,7 @@ d789bf40cf9433e2fd16409d112210fe93154588b1ac9bddc9c7f78e1db14426 src/balance/po a361c341932ffd186c0b21356c91ab1fe8043f5020d40798266d15ae896a114e src/balance/tests.rs ae06d238b1451328c751a511476ef39c012f3a397393f939ca02f96ecd0119a6 src/basic_auth/mod.rs 9a8858b7ff461a4d961ba701ca3ed6eaec15c3f7f05eef8e0e30edc63617605a src/basic_auth/tests.rs -b8285ffc316fa6214faea25fa5cf17128c2b378d6a246a15e4707c606fc8f035 src/cache/cache_regression_tests.rs +d9c44f9be9e3855c2339d4867c164b35938474b0a970de887d3990f33779b03b src/cache/cache_regression_tests.rs 7def03ace07dc38a4806277d75b6ce673d33ddaaf1c4855fa0a3372be1cf9489 src/cache/cold.rs b75ff512a1c6344483e00d2c67578ceea6b5472c279da0246f3622daa68d7e16 src/cache/cold/cleanup.rs 640a0f11bf3c77e44f276ba300bdb645465621b2015a32e215e416faaaf65b18 src/cache/cold/cold_tier_tests.rs @@ -373,8 +383,8 @@ 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 -24d2eb7afae4296b0e8fd938b54ba806153417e4770eeac359e525f84d1e875e src/cache/lookup/tiered.rs -46564e91dde4a3232a62ae56008ae9c6b45fe7c5520b19add5735c7a5a4c2d9d src/cache/mod.rs +61948af2ff78cd587fa4993594b2dbbb1bb5e865137eb420cf578c4d83e38ebb src/cache/lookup/tiered.rs +37c02f0c2ab6204c985797ed37e78d1ffa8dd15d374ba08307a2a05ee93989fa src/cache/mod.rs 0c8b0d550e94d4474dcdf991aa0340228dc5f2f904f39350e6e666a16f16fe87 src/cache/model.rs b96e30ef2b12ad7647915457f087a4d11b6141847bc5e971a75c2739c88c3d8c src/cache/model/cache.rs 0ec4f6d0adea1ed80a3ca17c68c9c85502491da2904d9d690b4169ab9b025b21 src/cache/model/cold_metadata.rs @@ -385,30 +395,32 @@ ff1c3a1a3bc0d26218dcc943ef951c2a212c180bbf6e4bf1c542ffbf12a9f150 src/cache/mode 14f3f8ae5252a2dc13fcf9556523ffb945b77ee92a5fb4939cd27e113fc61660 src/cache/model/views.rs b9e4b05ff1dfac993d40f926937243e6281621c9cf82ee6c03f47695f4712e8d src/cache/policy.rs b0c4486a25383ecf82bcdad3527649ea510a16ef07276810b8574644c045f7b3 src/cache/policy/decision.rs -6b79c12d9d520f940a38d5dc9a3af6e83061d683bccf8dc1aece441975105750 src/cache/policy/decision_tests.rs +5f525f97b3519117eb504f70fc57055ef33c41d1bf75636cbfbd8c6d8a0c7fec src/cache/policy/decision_tests.rs 1f74f1830beab307e6865d5691126c65eff153ce04d17e95cf478ee75df39205 src/cache/policy/request.rs 20d4af129be642f727f3de694abe9404210dd0210dc56124028d62c2f8dd4649 src/cache/policy/response.rs 12a6d5d9d6711e956391b4b952e8149658b8bf64cfcc0a4c59c281f2630a6aac src/cache/policy/scope_tests.rs c3a4300f7cdb6b2b7c16fbc489d49ba2451331bb4a55a2d9f618c684fd61eecb src/cache/range.rs -291a24b130b3e46cc060717e39ca5a29a89187a266b0d6e66d71697b217277cf src/cache/rules.rs -a58e1d696b75e404aef05c1eb980893a8ce0c0d5afd6765c4ae21ff2ce4b7194 src/cache/rules_tests.rs +2ff1a7c42eba61aa3a9d168169c295409b57e9b4dd4cf3b5c9fb88ca073daa61 src/cache/rules.rs +06ce13ef3ed6745883353f6b6406c64cf60ef81d38a1edebbb980a155cd18417 src/cache/rules_tests.rs 48344d7dcbbb220d8c16f5aa9bb88d86a6388b226bbf93d0ca92d8dfbf2c8001 src/cache/stats.rs 65b9776786a904d5ac72fa7d85dd56e3185e29201e34b0ed9b95aaf21d058f89 src/cache/tests.rs b969394b04859b269dcecd8958b1aab40b532709512714e9900f0ecad6b6d0c5 src/cache/tickets.rs a1132b980833b1b4ce2bba9aa681ff255a0e2d61faaa65a316860da503ea1e27 src/cache/v022_cache_tests.rs adac3b8de21a73f32d784b3fd2240d17309e8fce022163710e781d44ef590117 src/cache/varnish_compatible_tests.rs -588fd2468317fe706569ad11352165fab5ba998f0bf9d84e90a492700e1260bf src/cache/vcl.rs +82ec8b24ce07cf61c0724173464df8567c19db2f87c14e9b9efa16441439eef5 src/cache/vcl.rs +9a32ecb664c7f9469357c0b32b95e78e977bf92e91dc7bd92fbae7448b24c2ad src/cache/vcl_matrix_tests.rs 1a2eb6684d9ea4a7e90970d936c75f7c8bbec46a4181fdf273be9bdac8eec847 src/compression/mod.rs 8de82d9188c9c337690c6ec4afdad9fff20651c358e34602a93d8bb8c3d2489a src/compression/tests.rs -af4063c1ee7478aa92b9d82cd20901581a0f6aecc865a710b4bf3099219698bb src/config.rs +7f249b08c93309cf987eaf9c5730110850a334d3b3ebcf20b7731250dbbd27ea src/config.rs e0542812b82c31481e18de2bf50e0f00ec0608be47c48aeb4b2b8429dd9a6e39 src/config/backend.rs -43c8d59e5a6f8907cae7dcd28673ff8833abba8d76740fc6e5061147a4e1048d src/config/compile.rs +13cc76bd39e6e0df6b0f1c69c5aaded3ccc876a2324f3e462961dc41ed44a432 src/config/compile.rs +f3c56e803e09ae2fa7af96d4a1f84fa32492c1070cff06e41368feeeb1f4c5dd src/config/http_policy_tests.rs fbea01fea1213d98aea812c1b78d5db289e09200b98ae514d742235cd3fa70e1 src/config/internal_routing.rs -b7b67eb1ea9c15745123c7a844597d91deea03669ef6229f4c100f4dd912046c src/config/model.rs +a3bd297d160b3bad25bb362de848f182b7ec9807943c5c4537dafbc2a1e299d8 src/config/model.rs 75839458ddbc7480ec4492a95eeb67b617ba7d62f7b67e7a767a3453b74dbcbc src/config/route_policy_tests.rs -4703a2a2e94b6fded2350b7c1f30c2cd91ba5daf09446eb78c91c34766231ed2 src/config/routing.rs +caf688a85edc57e92d9ab0cd480282d4a3ecffe210473cf7e3abaccf8c8cd7ce src/config/routing.rs 4ba1998de8b8b7d43548d0a6708db59e05654c0ed5a999152885668246bd69d7 src/config/routing_conditions_tests.rs -4ad23b97df94257b06d499ddeceaec4c29312b947ada06fea8603d03530b9e5f src/config/snapshot.rs +29bdb73b679cf45ae0833b9b13ea86923690397c1a7a17c0ce364bc182bb2801 src/config/snapshot.rs e79c79ffb6b8db04bf0e7581b217d3fd2cd88f23fc2b7e3874dca0eef19423bb src/config/tests.rs f35de0ee1516ece6bbfd2b2a7db7d1e0f5048b0ec47cf2a3765dffb799abfd93 src/config/transport_tests.rs a09f361d70510d6226f4dd6785e649c3dc01ccafc70a4c8b0dcd098e224129b7 src/db.rs @@ -421,8 +433,8 @@ dada314e1709e960eb2e225b4d10c3cd12606c62c4bc2c0220aec1ba133e4ade src/demo.rs d2ef07d1565569f520a6a8eb01f4ea9bb673499d038018d52e65fe95e800bb27 src/diagnostics.rs 045593a42a6e4f632e5052c655788f0843faa313fc929265b89509f6dfff91ed src/docker.rs ea041859335219773748acbb479f83245ecdd3301108972fc0e0c1ea4c95717f src/docker/client.rs -8b65a469995b97b92a2dcd97aabfdd6d4370638b6faf5dd99e7a8ade6c924c63 src/docker/model.rs -7b902b2b42a20d8f1419d97cb428ca2cf65cb0108f3d27456ba735077dc809e3 src/docker/reconcile.rs +c312cfa95759722c56e441feb6c261fe69944e8aaccb4cf90aa7ad5f4d321c89 src/docker/model.rs +06c888e80b562a7b63bba1227715975da928453f724696c32aeabed5fe527311 src/docker/reconcile.rs ab62df22bbedfe84b10a498c023c2a15628bf466cb84b58c3a98c571a6b3758d src/docker/tests.rs 34eb55a240928e98bd34e790ac63096b9ca8bf7a3008676dbbd11e1a392b8541 src/forward_auth/mod.rs 6c25951cf69e972c47cdf815f22a5062916b2b768e39d55a26a5fc9e625a2344 src/forward_auth/tests.rs @@ -445,7 +457,7 @@ f54f29bb923c7101a0da4d9a0a322447a8ebd4c59c5954d9b2b30b0dad13b5e0 src/hex.rs 49ce4452ef7973cafa2e4071e2e14be0e16000e931a6501e4dc613652e49e230 src/http3/identity.rs 10cb1574ceabc40502255e616d787a24b763439fb201ae38f0c56713278a6a94 src/http3/settings.rs 58cb53c10e6993340433bab1decc3491297ea2bdaf60ad4dbf5145ba076637ca src/http3/tests.rs -be8ea083564d0c7780409fdd8843842f84144cdde3cb30bbdf1d4b68a1ae43d0 src/lib.rs +c61bfe0292111990586dbc765361788b80b599e25101f5cb3d1afc090688f884 src/lib.rs e8399753a6ff49b7de19edb0a268bf871c9979a518354160cf07b4669051fcbb src/logging.rs 3635b2b915f2c055d118596a26569fe93c44e2c0fac34d135e47c538f0f4457a src/logging/error_runtime.rs 4fd439ad1f0357fd859bd02ce10cbb476f8c4e03ee432ff1687abd4c453dfed9 src/logging/format.rs @@ -472,6 +484,13 @@ c4dbe0f8ded237d45b6a3977bdc7544296e4408996815cae9e28af028419d0b7 src/oidc/tests 992f49379e44361d98088d8f8ca1013d62846a54a5a35c089a5e0e1a9488e08d src/oidc/token.rs eb95c68c8639ce3ae658eea3334795cdb5e129fb2ba10955f7dffe06d8909b57 src/pages/mod.rs d09dc18863b0508a5e8d54a5305904170f3e8f12857b7a0d5393a11849541e50 src/pages/tests.rs +9840ec5b3786661084fefdced6694f3c099fef1e872e28fab9ef9a5cef29d141 src/policy/compile.rs +420d3e1133621a6bab8c15523cbd81712ea4b5d36c1390d52d5ef703164850c9 src/policy/engine.rs +12440a52f0a90f0f853f4a1273aef20b4b95137709dcf48345707aeef291df90 src/policy/expression.rs +8cd479954224d1b873070a36a63ca6bc852bd1b4a4deebf845857178ea34d2a3 src/policy/haproxy.rs +12232e72df429ae867e7b8d41ce61be2b94941237a3b18b223dbd07df2b42dab src/policy/mod.rs +9e47c71ee45a01fb00b3d1da0e7363db25247604038f24b40796a02bdc76223f src/policy/model.rs +25ec6a58cbb066b59480015eec1fb7535c0f9bddf71c59d687dbac2cb36cf386 src/policy/tests.rs 5650a3f70162abd97021e0a51a92cac2c4dd39004426ef99dff36cbb0741aeac src/prometheus.rs b9d71633703469d1d14e89c4d8a7698f4d354e5111cfe6ed3b2587566d0e2333 src/prometheus/core.rs 8595f0a7d1b075ec825a4a4b55b71dabda3d7be450718e9d7e7f554b3ef1c695 src/prometheus/docker_misc.rs @@ -486,32 +505,36 @@ f882bd071bf83a71e6786dd426a62b3a11ab022715d14f2f95b956b0ccee757b src/proxy/body 1af4712b76c5fd1f1248db8f3aa32a53019e20aeb1d62a34792ee539ed8e5d80 src/proxy/cache_helpers.rs 2d39552aa01ce3d048560944975243d0a58ae762d838e547f5fa65007d871dc4 src/proxy/cache_http_invalidation.rs a86b10ce0707b51e925e11ea14f7f40fa108a196166f62cf40007a97f9e17203 src/proxy/cache_http_invalidation_tests.rs -b2c4e168f63767008bda51eac4bd070be853e4de232af78588a61d5b182d9b51 src/proxy/cache_plan/mod.rs +235388904f138367e30ea4c1d2123133d1d00591fd351f32f963fec3453aaf7d src/proxy/cache_plan/credential_tests.rs +19e3e0157c139cb05cd199ee8ea0d5f212a9b6c14aeb641bad81a7c456792f6a src/proxy/cache_plan/mod.rs 811a00b55b24638b4bf8a6bea9ed7c0ffe2a758f76bfe63a95e1d31bce1c2c9c src/proxy/cache_plan/tests.rs -1f6077e2c2755a12f70f60f94fcf364d0a1b2c69e28d9b9b97f87f3e491eb233 src/proxy/error_fallback.rs +2e1d34ff66f8c580f2058438ae4395813fe39df49899884da51940c64362e898 src/proxy/error_fallback.rs +8d6edb93bd7e82577639509a675c6a387e04ea2d8a01a8ededf834995a42d54a src/proxy/error_fallback_policy_tests.rs ff525886feef76d5fafcdfc68799a47b1c6a72651e6848ace7c3e5609793cbef src/proxy/forward/cache_fast_path_tests.rs -cc5e6effcc7fd8ac63a88569bc4af10abae605714e1160b282ea711d8d291f90 src/proxy/forward/cache_lookup.rs +fdb3d0c1604a3cd829b1313dbeea20cc875ac5cd3fbff3686b37a2066ac6fb01 src/proxy/forward/cache_lookup.rs 287012c81144d8f15af4a148ce3ca911d431bc59adff44e697567561aa372bb3 src/proxy/forward/h3_navigation_tests.rs a2a097852d126851fc7191c2fda65764dc842745ad657b970399c1f906caf114 src/proxy/forward/response.rs -06f3809ff7423182b5f61ec576b6be520741cf8153ae9d66f6bade12443f1781 src/proxy/forward/route_cache.rs +e56339212d8fe4eca45e76dd0e6372ea009ac4becdf7220c41eb9061f19d8e9b src/proxy/forward/route_cache.rs ccecf3077cebe96320f1cef9b8df17253a9dde314d57b2f9a62a6af754406105 src/proxy/forward/static_cookie_policy_tests.rs -06212b670d561ecbc991ef1f3775553a04d9257ad783365b747d713bc0665641 src/proxy/forward/success_finish.rs -0f05a023829d8a0d5af7df7dde6dd502b817f628fecef0781ab4f5d54fc5baab src/proxy/forward/success_prepare.rs -45bd21104a1555a7d5e404263a395f22643c9c404520ffa6f14c5741b60f0cbb src/proxy/forward/upstream.rs -226ab8d3bc9d523e51bbb0715c47da6efbf116762ce1f519eebfe70d9e06235f src/proxy/forward/web_source.rs -11f7fb8a74dcd3a2d684878af63b36a160d16a59575891ee280861fa5dbb544b src/proxy/forward_entry.rs +ab27174e36fabe0b4e610a96be4a81de4b9d173ec60736ce5d6b51c1a8fa9826 src/proxy/forward/success_finish.rs +8beccb28fbee2a7d7df5991ce93a8610f7d92bd1d4abed8679b968861ebd8a1f src/proxy/forward/success_prepare.rs +a91d0bdc5740beec921df50ad14a4e85de0a73d46c9626c9cfd37a7f8baca317 src/proxy/forward/upstream.rs +03961ad0d386759ca2016d2dde37e124453514650d19a7feeaaa931f1ba81fc8 src/proxy/forward/vcl_policy_matrix_tests.rs +ca4b59cee7eefaedcdb30f3b60ea982b9f4e1df6cf03b7580bd4a53bcbf18ca4 src/proxy/forward/web_source.rs +3df1cd933c77e5390066e0bf3a4671a053b97ec1948c4a4204004312a3572c9d src/proxy/forward_entry.rs 9b25f5e3ea4443a63ee6f45d12e1957dd316fe8e85325fc00ea416faaab1025a src/proxy/h2_graceful.rs fc61c3f81d0bd8d91dab2a72267d497404e45e10e5cfc6000af16a254f888148 src/proxy/headers/authority_tests.rs e87437ccf80e50e0159d204dfdd1f8dc0739b6e375be192fce0af749810258cf src/proxy/headers/mod.rs af9b044761a56e8a6dc57f9d760b289ff4a6bf37db11dbfcd3ec4da5b8f426b6 src/proxy/headers/tests.rs 2bc63579975387c92a9459a9677b4a49e76df382b1ee19de12c8341a3ead57e8 src/proxy/identity.rs -8b94adbbf4823a85470edcc38473978fef1e1369ced47f04662534c13d360d04 src/proxy/mod.rs +dc7feedaad70ab28e461ff4d8df17fda7f68f80e759e321a973c1bb67abe59ba src/proxy/mod.rs +5ecc4d3db24f3e72318a6dca2088ff1c1f5ff84652cd3e674ad50e23ea0d2c93 src/proxy/policy.rs 92806ce1802da9b6771ece474d91a3458eba3f6ed19b0817b897e828a02e7e32 src/proxy/redirect_helpers.rs b83b9c30022e8c8fc97654a7d83ee44702c78bc92d2089bd397054e0023c3b7c src/proxy/request_id/mod.rs a57ea795430bf52d550083fef759c739f3821217aac465c0024aa1565b0727d1 src/proxy/request_id/tests.rs 16f9ed2ff51879095e6f1a818b03a76a03072b4c8c30d55201cb3d8bf229bf1d src/proxy/types.rs -8f8d38de8756ab88c40d2e9b91121478b71ee0816a7ae9e1859ffadff9638349 src/proxy/upstream_helpers.rs -96d18a85beb9d9492f4d0690eefd9afad9c1c4eabc36f41b447b81861a92ed2a src/proxy/web_cache_revalidation/mod.rs +15df425be6c7ad379920399e9f4674e126668157d64c67f5055a2b7931d8dc48 src/proxy/upstream_helpers.rs +02b56b5a7133e08ab47c9da0fdf1a807d054b2ff95efa0936a0c1d690474ce87 src/proxy/web_cache_revalidation/mod.rs 5522456cc85948228250feac92308d53b130c4a7af98d24f669aca4dfe6999b6 src/proxy/web_cache_revalidation/tests.rs 3d591201595a3b1e928ded20a8736477a47e5acc3bcbde158f7c17547ce155ba src/proxy/websocket.rs aa58bacc35458ac615680e774a235191f80abf0db978b68095571fce94c2b502 src/proxy/websocket/handshake.rs @@ -524,7 +547,7 @@ a44421714aab37f7ceda19e3ec2512c645d2a3ce5dcb3da5bc7a0d87a442d6a8 src/proxy/webs c85c9f05dac65cde6878bef3ef7258eb9de79ca14c26ca2492e0e13839c40fc3 src/rate_limit/tests.rs db254128c8013adaad7280f40a0edd8b196083afef299cd9e193e6db1d698b82 src/redirect/mod.rs 811c83ae9fd0f5a13d35b5443cd37843f82b9d600bee4bb136ba9b87732a5347 src/redirect/tests.rs -5a55cb0d8b72cdbe36cbdb76775765b28523f03fbac34143e44ebbb309f1d60c src/runtime.rs +0f925fc391cebaeabaf845efa4b9eaca45cf8b5149db132e0761cd62d2629625 src/runtime.rs e2a5367eb4e9b35e58acacb2390cc859e7ee5b59379b79e302018737028a90a7 src/runtime/certificates.rs d9017b6ca3a624b6883f696337471d513fbf2e96a90c92b184a895c72a16ccf0 src/runtime/constructors.rs a868442930930eeb71aeb2e14274bb69497ecbc4d844879e3666b636c7c993d9 src/runtime/docker.rs @@ -533,8 +556,9 @@ a868442930930eeb71aeb2e14274bb69497ecbc4d844879e3666b636c7c993d9 src/runtime/do e7c21dbabb9d89058cd9e767f83a3e9217865fa87ab6c07bbf96826fe154ff52 src/runtime/headless_tls.rs e524ebd53e83c1f660cb1525e1d458b24423063d69984ffad0fa0d9d2dd9e2e0 src/runtime/headless_tls_tests.rs 728d7736eeb916c231a1016454529dfec452666a2f42faf21a69de252ade7b02 src/runtime/health_endpoint.rs +da6eaa5cfe3b6111367743229be5c1891011fa397059b63e520f12b6930ca819 src/runtime/policy_revision_tests.rs 4275bb507e5e7f52fe1b5b011db2770890217ce99530b6d8f620ccd894cafe3d src/runtime/tests.rs -b70815e83a2b92d3b71df4227f08c9bb919d117c5f3297712b82c3eef7d5a1e7 src/runtime/types.rs +f626bdeb9f2f9a1bad87c8894d68c478a4767496d66225dbca1a10f83290dddb src/runtime/types.rs 2cc3e9fcd0464828b99aec1d334646eca7729267734a74d53bd38c67f27f5ba9 src/runtime/updates.rs e3dbd60953db5a976985dd796e4268b41a0f3df59764c4664015bd41e2578058 src/secret_store/mod.rs b0c4a46b40b09794fd8a037afca380ee3b95941bf75a0e1102a4e520a4bd8be3 src/secret_store/tests.rs @@ -599,10 +623,10 @@ ae880b40197454ea3fbf4d2113984dc372098b2e54b97e87c83cc319de253377 src/upstream/t 3fca10e85c6b936c142f4f0c32e642fa92fd4ad792af8cb05514fc8f19002714 src/vhost.rs f8b3f8e45306b13ee925f5cb54f8e2de1934314e2c590f14be7ca3814438f4af src/vhost/conditions.rs 846707452ccf10962f1763be66b8f56c050b0398b48968015fb799dac289c0d6 src/vhost/error_fallback.rs -53f329688ef4f1d68a9ed2446f0d726a58c44687c4d88de293b3aeb600d08a67 src/vhost/model.rs +a7b789d92cda754ba74f6b2c8de0693626b311112cf50b6a73fbe3f52dbeade5 src/vhost/model.rs fc8af7342a3b147921e9040116af5dfe680b3df910db2416ada18198bbeea7df src/vhost/redirect.rs 5a5768740e9a486436f6bb4e285ed99fd445cabbc21f317a47dc32c1f7091385 src/vhost/tests.rs -6dcedaa0e97dcd21f373cfae0914a1f119fabe910f77ba37f148d8c2e93725e8 src/vhost/validation.rs +34ffb202075c9fa720d2a23c6d901471655befe583a6335d778391d467cc8186 src/vhost/validation.rs 8d1eff4b24f01d137414ef5419f75dd281879228adb70409645b11b3c78c20e9 src/web_server/config.rs 9744e8c29ae72a4d9fbc9a76166a97f8292c4c312295ea40d1cb699e03d80a9d src/web_server/config/compile.rs 5ed79fa5b9c53f95ca200d89a9ba927dda816b61fbdf3b852bd3c9670e3d2d4f src/web_server/config/model.rs @@ -638,12 +662,62 @@ f51b881c441fe8cab388c744911671ff925694b650e5ae7a5072cfdceb9ddaa4 third_party/sw 050bc415ee7048dcd881682678f720264e7da5e373f7461d7c58c755305255f7 third_party/swagger-ui-5.33.1/swagger-ui-bundle.js 63818894e4b04cd0e3180d9cb20761e227a939121e7484f8e1d528227c756f89 third_party/swagger-ui-5.33.1/swagger-ui-bundle.js.LICENSE.txt 1ac324f7dcd27e4b9386b4bd6421271ec147e922a22c05ba24b11515e9aa6321 third_party/swagger-ui-5.33.1/swagger-ui.css -758351c494333d103c39c90afa44dcd2d59d2018b88e8f0947d2b02c317a7a34 tools/README.md -e6ee754a853d70e5a12b9884bfc813f63f83cdaf253590059b8b795e6caca4f0 tools/dev/backend_overview_smoke.py -3abb2bc94709baae3b962242a7f7322a7264a35365dd8559e9f6a7d59b33bb51 tools/dev/cache_edge_smoke.py -7c30c280d0b0a8bf855eeffab583ca34dc161255f7ef6124148aa979c17c26d3 tools/dev/memory_load.py -d1418f8e574a7390fd45a2aa879bdf5720b773162d65e295ab0350506aa5220a tools/dev/mock_auth.py -2d3ff92300b09ce9cecbbaaa9309b4d33160fa4b2291c9952b784e8cfb599ab5 tools/dev/mock_server.py +17dc0de6612ec8129f6e63728185349354e37d9be953bcd1c193b39064588091 tools/README.md +a30710fd54f897b1d2afe44265b2690d39e17aa8bc2df610884de7ea19ec51cc tools/dev/fixtures/vcl_regression/README.md +6c6e01d69acb45cf30d1ebc29af871bb918a527d2c0f62f80d256e1e07fb5fb9 tools/dev/fixtures/vcl_regression/beresp_controls.candidate.json +ca2f8867d6e08d8e7c2555e7b9da7ccc2369e1a18d2ead540b73008550c4cd1e tools/dev/fixtures/vcl_regression/beresp_controls.json +7e2a7a87a3af93b91831310a0c568190ec670953bcf6bc62bfbbe05882da0a65 tools/dev/fixtures/vcl_regression/beresp_controls.vcl +82127df41dff99d386e9941db6f2cac4797aa3967cf56be8c0bd1eae18ba34e6 tools/dev/fixtures/vcl_regression/branches.candidate.json +0ddf8df7d931fca6ba26f9bea9a02011d9a9df5324b0097886b5c736603170b8 tools/dev/fixtures/vcl_regression/branches.json +4dda6bc065769b82143ebaf21baed732efb7a4e50743e47dcbeb06011c8153d2 tools/dev/fixtures/vcl_regression/branches.vcl +60318a1da517cc371c023073dfb5dca6a921cfe6dff8396b37a5499bb3949450 tools/dev/fixtures/vcl_regression/cookie_hash.candidate.json +b3894ca9618ca38181369006d53fef28ad3af5d12f6d0793c9cf8f741c70bc0f tools/dev/fixtures/vcl_regression/cookie_hash.json +9a65da06be7481c042f8a1943829a11e5fa24a5a1ff0663af2a11c72b1af6e00 tools/dev/fixtures/vcl_regression/cookie_hash.vcl +8a0a83fd0b7575ed8d407610b015d7cbb71d1f2ee5860c4c8009c5ac55300a26 tools/dev/fixtures/vcl_regression/cookie_pass.candidate.json +68e5cc3a6c97e2b8afb1aad45b4b13db3ecde82af18fd546b7402d877ac41f77 tools/dev/fixtures/vcl_regression/cookie_pass.json +7339b2412ebc4cc46b686f82a0327d56511ac12f252040ca46226a5629b3e02b tools/dev/fixtures/vcl_regression/cookie_pass.vcl +616fc28e32ddc9947780b98074d58ef994e441c1670254790ca087f147cf87b2 tools/dev/fixtures/vcl_regression/cookie_strip.candidate.json +5b1536ecedf603aec37de50a96050295dc06a0b3c7cc3185dd0d8745029733f1 tools/dev/fixtures/vcl_regression/cookie_strip.json +8b8a9e9291a5d20d33a28c9fa12a12dede23916d4a4396e4270b076de9c0de50 tools/dev/fixtures/vcl_regression/cookie_strip.vcl +82613c95327ecd6d441ca7b2d38e6d560981426fc3edfcc14a21182873d7c601 tools/dev/fixtures/vcl_regression/cookie_unset.candidate.json +7e8c7e21280aef29f9b68c6d89994f8d941b428d9c40e7f50685cef0012c73a2 tools/dev/fixtures/vcl_regression/cookie_unset.json +597802d72924559418cf28eb515a7d681edb01db6968690dfa69e0da62afb8ec tools/dev/fixtures/vcl_regression/cookie_unset.vcl +c0d39961a001d2a1010a1b09a2f3764632835f48e51f9d3674c4ca42e01d4851 tools/dev/fixtures/vcl_regression/global.candidate.json +c185b5d62be7302fe5e96da56990815da886f981b256d93b21c817b44a73a1c3 tools/dev/fixtures/vcl_regression/global.json +18db9c47502143567a046ae0ac83660111c1729d9d00d281de408ac51428c629 tools/dev/fixtures/vcl_regression/global.vcl +d22e0e66183b23b0029b31530056b4766659a8b328d6cda8042a589ee5d5c265 tools/dev/fixtures/vcl_regression/header_stages.candidate.json +6233e8f5e46ab1ede96cf6f2e7871aa40479c37ed1f5a4ab4765c36a17194363 tools/dev/fixtures/vcl_regression/header_stages.json +0372a27543672e2f0281251b7c4a436efb3be45332e85345e1fce6b00a85c4e1 tools/dev/fixtures/vcl_regression/header_stages.vcl +a04c1d4d5ed3d521ac3dd544d55de2ba16352ed3eced5c0469a210f7d59eeb83 tools/dev/fixtures/vcl_regression/legacy_mutating_branch.candidate.json +727effe1010271f6558cea46e0cbede7fcecf5cbf6987085e93bee8b36603f13 tools/dev/fixtures/vcl_regression/legacy_mutating_branch.json +561256fc344ec46f855a02c7deb6035dd7facdd0f81512a4d09c7e44c5107628 tools/dev/fixtures/vcl_regression/legacy_mutating_branch.vcl +7a8a2db8d698ab8f26aedd09adc6454f2775e488bac3e2540226715e5374f16c tools/dev/fixtures/vcl_regression/legacy_mutating_nested.candidate.json +dbad9d425a74a6e946428922e89d61b272cbcb6da892d2e925751fa1d1a5a943 tools/dev/fixtures/vcl_regression/legacy_mutating_nested.json +8a12896acadca9330a1f9accf904f94b75f727f04d57fe854d385ac39b13829d tools/dev/fixtures/vcl_regression/legacy_mutating_nested.vcl +396f5b0a9ffec2c5bf2facf1e700fb2df42cf354f5743dcfa686f93a2a28f7b7 tools/dev/fixtures/vcl_regression/rejected_protected.candidate.json +d0607fca2a36693f218b39dc5ba9d81be87899538563547a0fb30bbec9d899b7 tools/dev/fixtures/vcl_regression/rejected_protected.json +aab60afe1d16bc5c891663e9b28decdd9a8d8e9417f6d35b8b621c4ca1fdd95e tools/dev/fixtures/vcl_regression/rejected_protected.vcl +abb93fd2fc47a1da1267aa6410cc8a8d0e617ee8d0e1aa0bebbb278e9ba2f17a tools/dev/fixtures/vcl_regression/rejected_unclosed.candidate.json +abb93fd2fc47a1da1267aa6410cc8a8d0e617ee8d0e1aa0bebbb278e9ba2f17a tools/dev/fixtures/vcl_regression/rejected_unclosed.json +676ffb7953d5154a233010a9f842091f5e735b58dfc0fb916fd25b9abdfa995e tools/dev/fixtures/vcl_regression/rejected_unclosed.vcl +f988dcc6f3896c5aca7c71fcc4d857bd669f2d106a4b55f58cf95d2a3793560d tools/dev/fixtures/vcl_regression/terminal_hash.candidate.json +c2f8fd3cca6660d9f03efbd222f64c706fd573b20eabc9abb2e13e820d3f8fb1 tools/dev/fixtures/vcl_regression/terminal_hash.json +28b2bb68f7d13575161e7cc3ebe19a108d3f3db30195a1b361b404cec3d0479f tools/dev/fixtures/vcl_regression/terminal_hash.vcl +d652724cfecf834753154fe568058115d84d402e91e948c9f145810414db9739 tools/dev/fixtures/vcl_regression/terminal_pass.candidate.json +586ed9cfd97e97adcf46e9e2c0b49847dee21d53136b8c9a9675929b68e85522 tools/dev/fixtures/vcl_regression/terminal_pass.json +0ef4ab809abeb9e9abd033f1f9bc89876d2d43d07c0192fa8e2c10e34b859ca8 tools/dev/fixtures/vcl_regression/terminal_pass.vcl +606761d665b4bf0a66d97e92e4c7496e98a7a548a4ef2203ba86c922c1675dfa tools/dev/fixtures/vcl_regression/ttl_grace.candidate.json +4ea54b96dda9ca5311bcc58fcd5b17ecfac1b0137c1f61dae6a8c9a41abdf261 tools/dev/fixtures/vcl_regression/ttl_grace.json +5aa192d1dbc949436713b593991f2a9fdbba299c13fa32cfd65e894c8229c4cc tools/dev/fixtures/vcl_regression/ttl_grace.vcl +ef2caa796e7d52cbefb7c65c3f6d5ce1b1e5b84ddcd70faadce708cf0d2902f9 tools/dev/fixtures/vcl_regression/vary_backend.candidate.json +0c3c28ca8a7e13af59170f1c8cda92f1ed0e7a3bbab200cb0accfc0b8cd12444 tools/dev/fixtures/vcl_regression/vary_backend.json +0ef5209cd337a713bf8014733a090c26b2e3c6e97d301b58930987a7cf898863 tools/dev/fixtures/vcl_regression/vary_backend.vcl +67813f8548a3917f13d4e243824f48962a85381ee8417c7925c0262dfd5fd731 tools/dev/fixtures/vcl_regression/vary_deliver.candidate.json +dc57d461e14ac7451f6c78fd2f6c3769dbbb4f613e0fc05348711548ee408175 tools/dev/fixtures/vcl_regression/vary_deliver.json +92a9fae7763637d50717c253191d2f4c92add36692558f15f4cc8754d5d26ac1 tools/dev/fixtures/vcl_regression/vary_deliver.vcl +06da8cc54d0b530f444f5569abd31df5cbfdff80e4fc3cd49419d32483d94465 tools/dev/fixtures/vcl_regression/vary_unset.candidate.json +3bed9706943de42e0bab8ee810035a279e54271b1adcd69184a4d01779da81c9 tools/dev/fixtures/vcl_regression/vary_unset.json +b440bf533bad7e6f6478c5964c30aa490d9ce0661477d8e2fda3ad6cd1d5a492 tools/dev/fixtures/vcl_regression/vary_unset.vcl c711154a9df425a56607bd88f03815ffb408213a31a2b66ed1c1c9a6301a2fc6 tools/legacy/backup.py 5421082e24f3794356331157e30b428f3221a0d74c0b5d060bd4d3989e0bcf3a update.sh 56c702111022e1ca2c8f6b72c635c749b05936ffe6387bdb0a202691614cbc96 upgrade.sh diff --git a/dev.sh b/dev.sh index 5c18557..307afce 100755 --- a/dev.sh +++ b/dev.sh @@ -37,17 +37,13 @@ RustProxy ${RUSTPROXY_VERSION} Deploy an externally issued pair to an existing manual certificate id ./dev.sh tls reload Re-read and hot-apply configured certificate files without changing config revision ./dev.sh config reload Revalidate the current runtime configuration - ./dev.sh repair Preserve known legacy files; no compilation required - ./dev.sh doctor Check source layout and show available build tools + ./dev.sh doctor Check core source files and show available build tools ./dev.sh token Compatibility alias for admin setup-token ./dev.sh config get Export the running desired config as JSON ./dev.sh config apply FILE Validate, persist and hot-apply a JSON document ./dev.sh config validate FILE Validate only; works without a running server ./dev.sh backup DIRECTORY Back up SQLite and configured certificates using Python 3 - ./dev.sh mock [--port 9001] Start a random-data HTTP origin (Python only; Ctrl+C to stop) - ./dev.sh mock-auth [--port 9300] - Start a LOOPBACK-ONLY fake Tinyauth peer (never production) ./dev.sh acme --doctor Check local Certbot availability without network access ./dev.sh acme --cert-dir DIR Read provider request JSON from stdin; stage PEM files ./dev.sh test Check all Rust targets and run Rust tests @@ -63,20 +59,20 @@ Set RUST_PROXY_DEMO=1 to explicitly start a diagnostic origin and seed a NEW dat Configuration options: .env.example, README.md, docs/API.md, ./dev.sh run --help. HELP exit 0 ;; - run|admin|token|config|tls|repair|doctor|backup|test|build|release|fmt|check|mock|mock-auth|acme) ;; + run|admin|token|config|tls|doctor|backup|test|build|release|fmt|check|acme) ;; *) printf 'Unknown command: %s. Use ./dev.sh help\n' "$mode" >&2; exit 2 ;; esac if [[ "$mode" == "backup" ]]; then exec python3 tools/legacy/backup.py --data-dir "${RUST_PROXY_DATA_DIR:-$ROOT/data}" "$@" fi if ! command -v python3 >/dev/null 2>&1; then - printf 'Python 3.10+ is required for source preflight and upgrade safety checks.\n' >&2 + printf 'Python 3.10+ is required for build assets.\n' >&2 exit 127 fi python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3, 10) else "Python 3.10+ is required.")' if [[ "$mode" == "doctor" ]]; then python3 scripts/preflight.py - printf 'Source layout: OK\n' + printf 'Core source files: OK\n' for tool in cargo rustc cc python3; do printf '%s: ' "$tool" command -v "$tool" || printf 'NOT FOUND\n' @@ -84,10 +80,7 @@ if [[ "$mode" == "doctor" ]]; then exit 0 fi if [[ "$mode" == "acme" ]]; then exec python3 scripts/runtime/acme_provider.py "$@"; fi -if [[ "$mode" == "mock-auth" ]]; then exec python3 tools/dev/mock_auth.py "$@"; fi -if [[ "$mode" == "mock" ]]; then exec python3 tools/dev/mock_server.py "$@"; fi -python3 scripts/preflight.py --repair-known -if [[ "$mode" == "repair" ]]; then printf 'Source preflight: OK\n'; exit 0; fi +python3 scripts/preflight.py if ! command -v cargo >/dev/null 2>&1; then cat >&2 <<'MISSING' Rust/Cargo is not installed or not in PATH. diff --git a/docs/API.md b/docs/API.md index fffdfa3..f288c07 100644 --- a/docs/API.md +++ b/docs/API.md @@ -16,12 +16,14 @@ The current bundled `src/admin/openapi.json` declares these operations (among ot | `POST /api/config/reload` | Revalidate and hot-reload manually changed `--config` JSON; revision-aware. | | `GET/POST /api/api-tokens` · `DELETE /api/api-tokens/{id}` | List/generate/revoke general RO/RW API tokens (browser-admin-only). | | `GET/POST/DELETE /api/prometheus-token` | Inspect/generate/rotate/revoke a standalone Prometheus scrape token (browser-admin-only). | -| `GET /api/config/{section}` · `PUT /api/config/{section}` | Read or atomically replace one of 23 supported configuration sections. | +| `GET /api/config/{section}` · `PUT /api/config/{section}` | Read or atomically replace a supported configuration section, including `policy` since 0.42.0. | | `POST /api/config/geoip/update` | Run a GeoIP download/check/reload immediately using already-saved GeoIP settings; does not change revision. | | `GET /api/config/history` · `POST /api/config/history/restore` | Review/restore retained configuration snapshots. | | `GET /api/status` · `GET /api/backends` | Operational status and backend observations. | | `GET /api/cache` · `POST /api/cache/purge` · `POST /api/cache/invalidate` | Cache observations and authenticated invalidation. `GET` supports the lightweight `view=live` polling view. | | `GET /api/cache/rules/stats` · `GET /api/cache/rules/targets` · `POST /api/cache/rules/test` · `POST /api/cache/rules/import-vcl` | Cache rule match counters, the vhosts a rule can target (ordinary and generated Docker vhosts), simulation of saved or draft rules for a test request/response (also for Docker vhosts), and conversion of a VCL subset into rules (nothing is saved). See [Cache rules](CACHE.md#cache-rules-vcl-style) and the [supported VCL import matrix](VCL.md). | +| `POST /api/policy/import-haproxy` · `POST /api/policy/test` | Convert a strictly supported HAProxy snippet into a policy draft, or evaluate policy rules against a supplied fixture with a trace. Neither endpoint saves configuration. See [HTTP policy rules](POLICY.md). | +| `GET /api/policy/stats` | Match/action-error counters for active policy rules by scope; reset on configuration recompilation. Draft tests do not affect the counters. | | `GET /api/transform` | Transform observations and resource usage. Supports the lightweight `view=live` polling view. | | `GET /api/logs` · `GET /api/live-logs` | Recent and streaming request logs. | | `GET /api/file-logs` · `GET /api/file-logs/query` | Stored-log exploration. Source metadata includes `domains` (current configured hostnames/aliases, empty when not applicable); source and group IDs remain stable. | @@ -94,6 +96,7 @@ The section name in the URL and its corresponding JSON member in a full configur | `transform` | `transform` | | `forwarding` | `forwarding` | | `headers` | `headers` | +| `policy` | `policy` | | `prometheus` | `prometheus` | | `geoip` | `geoip_updates` | | `administration` | `administration` | diff --git a/docs/CACHE.md b/docs/CACHE.md index f984645..e631cf3 100644 --- a/docs/CACHE.md +++ b/docs/CACHE.md @@ -119,6 +119,25 @@ With the policy enabled, the middle request stays `HIT` if the entry is fresh. C In **Vhosts → Cache**, overrides for static extensions, bypass path prefixes and unsafe force targets each place the enable/override checkbox immediately above the associated multiline list. The fields are disabled while their individual override is off; their saved values and cache policy are unchanged. Never enable unsafe forced caching for personalized responses. +In corrected 0.42.0, forced-cache keys always partition by both `Cookie` and +`Authorization` **before lookup**. Missing, empty and nonempty fields remain +distinct, including when one credential appears only after another variant was +cached. Explicit VCL/HTTP-policy lookup partitions Cookie in the same way; +Authorization still bypasses unless the separate force option admits it. +The forwarded values after the existing credential filter and supported request +edits are used. An entirely empty input Cookie field is still removed by the +admin-cookie filter; a valid empty cookie such as `session=` remains distinct +from no Cookie. Responses add the corresponding `Vary` dimensions even when the +request lacks those fields. Explicit later delivery-header overrides retain +their documented behavior and must preserve dimensions needed downstream. + +These keys use a new internal namespace, so older forced/VCL-lookup HOT/COLD +entries cannot satisfy the corrected lookups; they may remain on disk until +normal eviction or cleanup. Other cache keys and the COLD file format remain +compatible. Credential-partitioned fills do not schedule proactive background +refresh; ordinary foreground validation retains the matching request context. +Response privacy exclusions and explicit VCL `return(pass)` still apply. + ## Cache decision precedence, explicit `pass` and public static assets **Applies to RustProxy 0.39.2.** Every reason that keeps a request away from the HOT/COLD cache is classified by one central decision (`src/cache/policy/decision.rs`), used by live traffic and by **Test a request**. Reasons are evaluated strongest first: diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index dedb7e5..e6eec35 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -109,6 +109,14 @@ Appearance settings, Dashboard Presets and Overview cards belong to the administ ## Sample files and safe changes +Since 0.42.0, the optional `policy` member configures [HTTP policy rules](POLICY.md) +globally; Vhosts, Docker assignments and locations can carry their own policy. +Each object contains `acls`, `maps` and `rules`. Omitting it is a no-op. Policies +are compiled with the configuration and apply live after successful validation; +an invalid rule rejects the update. Existing `headers` and `cache.rules` remain +valid and preserve their previous ordering. The global section endpoint is +`GET/PUT /api/config/policy`. + Example JSON is in `examples/`. Treat it as a starting point: addresses, certificates, paths, backend health endpoints and service IDs must match your installation. The API uses full validated settings and rejects unknown fields; it is **not** a generic patch store. Use the current authenticated `/docs → API` OpenAPI reference to inspect field schemas. For planned changes, export configuration, create an encrypted backup, make one logical change, save, verify real traffic and confirm metrics/logs. Revert via configuration history only when rollback of the config (not filesystem/secrets) is sufficient. diff --git a/docs/CUSTOM_LOCATIONS.md b/docs/CUSTOM_LOCATIONS.md index 63f9c4f..86b8c46 100644 --- a/docs/CUSTOM_LOCATIONS.md +++ b/docs/CUSTOM_LOCATIONS.md @@ -18,6 +18,13 @@ Encoded `/` separators (`%2F` / `%2f`) are normalized to real `/` only for locat ## Request conditions (routing by header, cookie, IP…) +Since 0.42.0, a location can also carry a `policy` object for +[HTTP policy actions](POLICY.md) after it has been selected. These policies do +not replace the path/condition selector below. Location `pre_route` rules are +rejected; use a global or Vhost `pre_route` policy when the request must change +before selection. Location policies run after global and Vhost policy at the +same stage, without changing existing VCL precedence. + A location can require extra **conditions** besides its path — the RustProxy equivalent of HAProxy ACLs in `use_backend if `. Each condition tests one request attribute: | `source` | `name` | Operators | Notes | diff --git a/docs/DOCKER_DISCOVERY.md b/docs/DOCKER_DISCOVERY.md index ef2c79d..70ce334 100644 --- a/docs/DOCKER_DISCOVERY.md +++ b/docs/DOCKER_DISCOVERY.md @@ -2,6 +2,12 @@ RustProxy discovers published Docker services through a **separate read-only Docker agent** on each Docker host. The RustProxy core does not need Docker-socket access. The agent observes Docker containers; RustProxy turns enabled assignments into dynamic, ordinary HTTP Vhosts. +Since 0.42.0, a configured Docker assignment can persist an optional +[HTTP policy](POLICY.md) alongside its other Vhost settings. The generated Vhost +inherits that policy, including its location policies. Edit the assignment +through the Docker Vhost configuration; changing a transient discovered Vhost +does not replace the assignment as the source of configuration. + ## Set up a Docker host Install the **optional Docker agent on each Linux Docker host**, not on the RustProxy server. It is distributed as a separate `rustproxy-docker-agent` DEB/RPM package and is **not built as FreeBSD `pkg`**. Docker Engine **or Podman**, systemd and access to the container API socket (`/var/run/docker.sock`, `/run/podman/podman.sock` or a rootless `$XDG_RUNTIME_DIR/podman/podman.sock`) are required at runtime. The agent detects the socket automatically (`RUSTPROXY_DOCKER_SOCKET=auto`); see [docker-agent/README.md](../docker-agent/README.md#podman) for Podman socket permissions. diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 3a555b5..135bbba 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -16,6 +16,7 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se | Custom locations | Prefix, exact and regex paths, path rewriting, per-location backends, Web Services, local responses, redirects and internal error fallbacks | | WebSockets | HTTP/1.1 Upgrade, RFC 8441 (HTTP/2) and RFC 9220 (HTTP/3) Extended CONNECT | | Forwarding headers | `X-Forwarded-*`, `Forwarded`, `X-Real-IP`, trusted proxy ranges, Cloudflare client IP and country | +| HTTP policies | Optional global, Vhost, Docker-assignment and location policies: named ACLs, nested AND/OR/NOT, typed samples, maps, transaction variables, header/list operations and explicit request/response stages. Strict HAProxy subset importer, draft tester and [VCL cooperation](POLICY.md) with legacy precedence preserved. | | Redirects and pages | Redirect hosts, canonical host and HTTPS redirects, 404 hosts, custom error pages and direct-IP pages | | TCP/UDP Streams | Layer-4 forwarding with backend pools, health checks, session limits and idle timeouts | @@ -65,7 +66,8 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se - Shared HTTP cache with a memory tier (HOT) and an optional disk tier (COLD). - RFC 9111 freshness, validators and `Vary` with conservative header-aware normalization (known comma-list fields, language/encoding/charset qualities and media types), while preserving opaque values and quoted strings; stale-while-revalidate, stale-if-error and request coalescing. Configurable static-extension exception for cookie-independent assets: omit `Vary: Cookie` only for explicitly public cacheable responses, preserving all other Vary dimensions. A central [cache decision](CACHE.md#cache-decision-precedence-explicit-pass-and-public-static-assets) separates security bypasses, explicit VCL `pass`, Cookie/session guards (`cookie_pass`) and backend properties, so public static assets can be HIT for logged-in users without weakening explicit pass rules; Cookie-bearing static fills are stored only when the backend reply is explicitly public. -- Varnish-compatible policy option, forced caching rules and per-location cache switches. +- Varnish-compatible policy option, forced caching rules and per-location cache switches. Forced caching partitions Cookie/Authorization before HOT/COLD lookup, including absent and empty effective values; explicit VCL lookup partitions Cookie while retaining the Authorization bypass. +- Structured VCL imports retain `if`/`elsif`/`else` selection through header mutations and nested actions. The editor preserves whole control-flow groups; older flat conversions can be replaced by re-importing their original VCL source. - Graphical [cache rules](CACHE.md#cache-rules-vcl-style) with global and per-Vhost precedence, terminal VCL pass/hash behavior, ordered safe request-header/cookie/query rewrites, vcl_hash variants, reversible rule-only no-store decisions, backend-response header edits before cache policy, and delivery header overrides; includes a shared, responsive two-section tester in global, ordinary vhost and Docker vhost editors, a scope-aware in-panel VCL guide, and a warning-reporting VCL subset importer. The exact VCL syntax, backend vs deliver `Vary`/header mutations and safety restrictions are listed in [VCL compatibility](VCL.md); the [traffic cookbook](VCL_TRAFFIC_COOKBOOK.md) includes ready-to-import examples and expected live request outcomes. - RFC 9211 `Cache-Status` and optional `X-Cache` diagnostics. - Purge and ban from the panel, the API or HTTP PURGE/BAN from allowlisted addresses. diff --git a/docs/HEADLESS.md b/docs/HEADLESS.md index c51446d..ea7ff46 100644 --- a/docs/HEADLESS.md +++ b/docs/HEADLESS.md @@ -53,6 +53,14 @@ The file can contain secrets: Docker agent tokens, client secrets of login provi ## Minimal configuration +The optional [HTTP policy](POLICY.md) format also works in headless mode. See +[`examples/policy-vary.json`](../examples/policy-vary.json) for the duplicate +`Vary` ACL case and +[`examples/policy-vcl-cooperation.json`](../examples/policy-vcl-cooperation.json) +for policy classification consumed by existing VCL-style cache rules. JSON is +the saved format; use the panel importer/API to convert supported HAProxy text +before placing the resulting `policy` object in a headless configuration. + The smallest useful file is a single vhost ([`examples/headless-minimal.json`](../examples/headless-minimal.json)). `"*"` as the host makes it answer every hostname and IP address that no other vhost claims, so no domain is needed: ```json diff --git a/docs/MIGRATION.md b/docs/MIGRATION.md index 74a17da..fc00b8b 100644 --- a/docs/MIGRATION.md +++ b/docs/MIGRATION.md @@ -17,6 +17,8 @@ A managed install uses `update.sh`; an unmanaged source-tree install must follow | Change area | What to review | |---|---| | **Cache** | Operational Vhost saves aim to retain compatible HOT/COLD cache. Content-affecting changes invalidate a scope; older disk cache objects can require refilling. Validate actual behavior before rollout. | +| **0.42.0 VCL imports** | Fresh imports preserve branch selection with validated `vcl_flow` metadata. Existing flat conversions keep their old behavior; re-import the original source and replace the old rules to fix branches that mutate their own conditions. Keep a pre-upgrade configuration for rollback; do not strip the new metadata. See [VCL upgrade guidance](VCL.md#recognized-conditions-and-expressions). | +| **0.42.0 credential variants** | Corrected force-cache/VCL-lookup keys use a new internal namespace, so older entries in those modes require a refill. Unaffected cache keys and the COLD file format stay compatible. Normal credential bypass and explicit pass remain in force. | | **Web Server** | `sendfile=auto` is an optional Linux cleartext HTTP/1.1 path; default is `off`. No existing service needs to enable it. | | **0.32.x origin protocols** | Legacy backend `http2` remains compatible on TLS (H2/H1) and H2C for plain HTTP. New strict `h2` must be set explicitly. | | **0.33.x Overview** | Dashboard presets/layouts are per administrator, independent from Vhost configuration; existing preferences should be retained and new widgets may remain hidden. | diff --git a/docs/POLICY.md b/docs/POLICY.md new file mode 100644 index 0000000..a40ae9f --- /dev/null +++ b/docs/POLICY.md @@ -0,0 +1,313 @@ +# HTTP policy rules and VCL cooperation + +Since 0.42.0, an optional `policy` object provides named ACLs, nested conditions, +sample expressions, transaction variables, maps and ordered HTTP actions. It is +available globally, on a Vhost (including a configured Docker assignment), and on +a custom location. Existing configurations need no conversion: omitting `policy` +keeps the previous behavior. + +The JSON model is authoritative. The HAProxy importer converts a **supported +subset** into that model; it does not run HAProxy or load a complete HAProxy +configuration. The existing VCL importer and cache rules retain their semantics. +Policy hooks share the request and response with VCL at the explicit boundaries +below. VCL remains the owner of its existing cache-rule precedence and terminal +`return(pass)` / `return(hash)` behavior. + +## Configure and activate + +- In the panel, open **Settings → Rules & headers → HTTP policies** globally, + **Vhost → Headers → HTTP policies**, the location's **HTTP policies** section, + or the Docker assignment's policy section. The shared editor offers a rule + builder, a JSON view, import preview and a draft tester. Reordering uses the + visible rule order; switching views preserves the same policy object. +- Set `policy` in the complete configuration, `vhosts[].policy`, or + `vhosts[].routes[].policy`. A Docker assignment stores its policy with that + assignment so discovery does not discard the customization. +- A policy contains `acls` and `maps` objects and an ordered `rules` array. Each + rule has a unique `id`, a `stage`, optional `when`, and an `actions` array. + `name` is descriptive, `enabled` defaults to `true`, and `stop` defaults to + `false`. An omitted condition matches every request reaching that stage. +- Validate and save through the normal configuration path. Compilation checks + field names, expressions, available stages, action arguments and bounds before + activation. Existing connections retain their configuration snapshot. +- Headless mode uses the same fields. Validate with + `rust-proxy --headless config validate config.json`, then reload using + the normal headless reload or watch mechanism. + +The complete [Vary example](../examples/policy-vary.json) is suitable for a local +headless test after adjusting its backend address. The +[cooperation example](../examples/policy-vcl-cooperation.json) demonstrates a +request classification consumed by VCL-style cache rules. + +## Stages and existing rules + +| Stage | Runs when | Relationship to VCL and existing headers | +|---|---|---| +| `pre_route` | After global and host access checks, before final location selection | Global and Vhost policies only. URL rewrites are restricted to this stage; the resulting target goes through normal routing and access validation. | +| `request` | After route access/authentication, before source handling and cache request rules | Header changes are visible to existing `vcl_recv` and `vcl_hash` rules. | +| `backend_request` | When sending a request to a selected reverse-proxy backend | After existing custom request headers; trusted identity and transport headers remain protected. Configuring this stage conservatively bypasses shared cache. | +| `backend_response` | On a reverse-proxy origin response, before the cache plan | After existing `beresp` header edits. New rules can inspect those edits. Explicit VCL TTL/grace retain precedence over policy TTL/grace. | +| `deliver` | On the response leaving source handling | After existing `vcl_deliver`, before outer compression and final diagnostic/custom headers. Applies to cache HIT, MISS and BYPASS when a policy context exists. | +| `after_response` | At final delivery | After compression and existing dynamic custom headers. Suitable for final `Vary` normalization and per-request diagnostic headers. Local-response no-cache enforcement still applies afterward. | + +Administrative/control-plane traffic, the minimal welcome response and protected +authentication-provider responses are excluded. Backend stages do not run on a +cache HIT. A location cannot declare a `pre_route` rule: location selection has +not occurred at that point, so validation rejects it. + +Within each stage, new policies run **Global → Vhost → Location**; each scope +retains array order. Later rules see earlier header/variable changes. `stop` or +the `stop` action ends the current scope's chain, not the other scopes or later +stages. A terminal response ends request processing. + +This does **not** reorder legacy VCL: its local rules still run before global +rules, with local ownership of conflicting headers/settings. Existing Custom +Headers keep their Global → Vhost → Location order and their static/dynamic +separation. Use the stage table when both mechanisms edit the same header. + +## Exact duplicate `Vary` rule + +This policy matches two complete `Vary` fields, one containing exactly +`Accept-Encoding` and another containing either spelling of the combined value: + +```json +{ + "acls": { + "vary_duplicate": {"fetch": "res.fhdr_cnt(Vary)", "operator": "eq", "values": ["2"]}, + "vary_encoding": {"fetch": "res.fhdr(Vary)", "operator": "equals", "ignore_case": true, "values": ["Accept-Encoding"]}, + "vary_combined": {"fetch": "res.fhdr(Vary)", "operator": "equals", "ignore_case": true, "values": ["Accept,Accept-Encoding", "Accept, Accept-Encoding"]} + }, + "rules": [ + { + "id": "combine-duplicate-vary", + "stage": "backend_response", + "when": {"all": [{"acl": "vary_duplicate"}, {"acl": "vary_encoding"}, {"acl": "vary_combined"}]}, + "actions": [{"type": "set_header", "name": "Vary", "value": "Accept, Accept-Encoding"}] + } + ] +} +``` + +Put that object under the desired `policy` member. The equivalent import source +is [policy-vary.haproxy](../examples/policy-vary.haproxy). A single field +`Vary: Accept, Accept-Encoding` has a full-field count of **one**, not two. +Adding a third `Vary` field makes the exact rule fail instead of erasing an +unrelated dimension. + +For general cleanup, prefer a semantic operation: + +```json +{ + "id": "normalize-final-vary", + "stage": "after_response", + "actions": [{"type": "normalize_header", "name": "Vary"}] +} +``` + +It combines valid field lists and removes duplicate tokens while preserving +first occurrence order and required dimensions. When `*` occurs, canonical +`Vary: *` covers all dimensions and remains uncacheable. Malformed values are left +unchanged; normalization does not make them cacheable. It does not collapse +`Set-Cookie` into a comma list. List actions support `Vary`, `Allow`, +`Accept-Encoding`, `Content-Language`, `Access-Control-Allow-Methods`, +`Access-Control-Allow-Headers` and `Access-Control-Expose-Headers`. Parameterized +or quoted values outside the token-list grammar are left unchanged. + +## Conditions, samples and maps + +Conditions use `all`, `any`, `not`, `acl`, or a comparison with `fetch`, +`operator`, `values` and optional `ignore_case`. A comparison matches when any +returned sample matches any configured value. Numeric operands are strings in +the JSON `values` array. `exists` takes no values. ACLs are named expressions in +the same policy; unknown references and cycles are rejected. + +| Sample family | Examples | +|---|---| +| Request identity | `method`, `path`, `url`, `query`, `host`; aliases `req.method`, `req.path`, `req.url`, `req.host` | +| Request and response fields | `req.fhdr(Name)`, `res.fhdr(Name)` for complete field values; `req.hdr(Name)`, `res.hdr(Name)` for list members | +| Counts and occurrences | `res.fhdr_cnt(Vary)` counts complete fields; `res.hdr_cnt(Vary)` counts list members; `res.fhdr(Vary,1)` selects the first field, `-1` the last | +| Cookies and query | `req.cook(name)`, `res.cook(name)`, `url_param(name)` / `req.query(name)` | +| Client/context | `src` / `client_ip`, `country`, `ssl_fc` / `tls`, `vhost`, `location`, `req_id` | +| Response/backend | `status` / `res.status`, `cache_status`, `srv_id`, `srv_url`, `backend_time`, `lb_algorithm`, `hash_key` | +| Variables/literals | `var(txn.name)`, `str(value)`, `int(42)` | + +Response fields require a response stage. `cache_status` and `backend_time` are +available at delivery; selected-backend fields are unavailable before backend +selection. Location is unavailable in `pre_route`. Invalid stage/sample +combinations are rejected when saving, not deferred to live traffic. + +Text operators are `equals`, `contains`, `prefix`, `suffix`, `regex`, and +`exists`; IP/CIDR tests use `cidr`. Integer comparisons are `eq`, `ne`, `gt`, +`ge`, `lt`, `le`. Negate an expression using `not`. + +Header/action values support `%[sample]`, including converter chains such as +`%[req.fhdr(User-Agent),lower]`. Supported converters are `lower`, `upper`, +`trim`, `length`, `map(name[,fallback])` and `regsub(pattern,replacement)`. +Conditions inspect all returned samples; a value template selects the last +sample unless an occurrence is explicit. A missing sample renders as `-`. +The replacement converter uses the Rust regex syntax and performs replacement +globally; do not assume every HAProxy regex/converter form is interchangeable. + +Maps are declared inline, without filesystem reads during requests: + +```json +{ + "maps": { + "plans": { + "kind": "exact", + "ignore_case": true, + "entries": [{"key": "premium", "value": "priority"}], + "default": "standard" + } + }, + "rules": [ + { + "id": "classify-plan", + "stage": "request", + "actions": [{"type": "set_var", "name": "txn.plan", "value": "%[req.fhdr(X-Plan),map(plans)]"}] + }, + { + "id": "show-plan", + "stage": "after_response", + "actions": [{"type": "set_header", "name": "X-Plan-Class", "value": "%[var(txn.plan)]"}] + } + ] +} +``` + +Maps support `exact`, `prefix`, `regex` and `ip`. Prefix/IP maps prefer the most +specific prefix; regex maps retain entry order. Variables are restricted to +`txn.*`, belong to one request and are never stored in cached objects. Classifying +a client header does not make it a trusted authentication claim. + +## Actions and cache boundaries + +| Area | JSON action types | +|---|---| +| Headers | `set_header`, `append_header`, `remove_header`, `set_if_missing`, `replace_header`, `replace_value` | +| Token lists | `normalize_header`, `merge_header`, `remove_value` | +| Variables | `set_var`, `unset_var` | +| Request target | `set_path`, `set_query` in `pre_route` | +| Configured backend | `use_backend` selects an existing backend member; it is not an arbitrary URL fetch | +| Local response | `deny` in `pre_route`/`request`; `return` and `redirect` only in `request`, after route access/authentication | +| Cache | `pass`, `lookup`, `no_store`, `set_ttl`, `set_grace`, `hash_header` | +| Delivery/control | `disable_compression`, `stop` | + +The compiler checks each action against its stage. Transport, framing and trusted +identity headers remain protected. A rendered header must be valid HTTP; CR/LF +injection and oversized values are rejected or skipped with a trace warning. +Successful/redirect local responses cannot terminate `pre_route` processing +before the selected location's access and authentication checks. + +Cache behavior is deliberately explicit: + +1. A policy `pass` and a VCL `return(pass)` both win over any lookup request. + Existing authorization, method, route and disabled-cache checks remain in + force. A lookup does not grant permission to store a private response. +2. Existing VCL `return(hash)` still ends `vcl_recv` and still runs `vcl_hash`. + Policy request-header changes are visible to that hash phase. Adding an + internal hash dimension does not automatically add downstream `Vary`. That + field must name the real client attributes that select a representation: the + cooperation example merges `User-Agent` into `Vary`, since its `X-Device` + header is created inside the proxy and is absent from browser requests. +3. Backend-response edits run before storage policy. A VCL TTL/grace assignment + wins over a conflicting policy assignment; no-store decisions accumulate. + These decisions also apply to foreground `304` validation. A no-store + decision can serve the validated body for that request while discarding the + object instead of publishing a refreshed cache entry. +4. Backend-request customization, policy backend selection, and backend-response + policies dependent on per-client state conservatively bypass shared storage. + This includes request headers/cookies, client identity, transaction variables, + method, TLS and balancing hash samples. Put purely diagnostic, per-client + response headers in a delivery stage. +5. Delivery changes do not rewrite the stored object, its key, TTL or variants. + Every new policy edit to `Vary` in `deliver` or `after_response`, including + generic set/remove/replace, must retain the existing dimensions and `*`. + An edit that removes one or creates malformed `Vary` is skipped atomically + and counted as an action error; the tester includes a warning. Manual + `backend_response` edits can replace the field before cache planning, so the + operator must preserve every dimension on which the origin actually varies. + These new guards do not silently change legacy VCL/Custom Header semantics. + +When any `backend_response` policy is configured in the applicable scopes, or a +request adds an explicit policy `hash_header` dimension, expired +stale-while-revalidate entries are validated synchronously and proactive +background refresh is disabled. This ensures the rules run in the current +request's policy context and preserves the original hash inputs. Fresh cache +HITs and existing explicit `max-stale` / +`only-if-cached` behavior remain available. This release does not run these rules +in an independent background policy context. + +## HAProxy import and API + +`POST /api/policy/import-haproxy` converts supported ACL/action text into a +policy draft. Unsupported or invalid syntax rejects the import with its line +number; no partially understood policy is activated. In the panel, **Validate +and preview import** shows the converted JSON and warnings; **Add imported rules +to draft** updates the unsaved editor. Save that scope separately to activate +it. Full HAProxy `global`, `defaults`, `frontend`, `backend`, stick tables, +Lua and external files are not a supported configuration format. + +The `http-request`, `http-response` and `http-after-response` prefixes map to +request-side, backend-response and final-response policy stages. Their exact +supported commands are checked by the importer. RustProxy-specific actions such +as `normalize-header` are extensions, not a promise of HAProxy compatibility. +Use JSON for the full native model, including inline maps and explicit stages. + +| Imported form | Supported subset / difference | +|---|---| +| `acl name fetch ...` | `-i`, `-m str/sub/beg/end/reg/int/bool/ip/found`, numeric comparisons and multiple patterns; repeated definitions of one ACL are ORed | +| Conditions | `if`, `unless`, adjacent AND, `&&`, `or`/`\|\|`, `!`, inline `{ ... }`, and separated parenthesis tokens | +| Header commands | `set-header`, `add-header`, `del-header`, `replace-header`, `replace-value`; HAProxy replacement references `\1` are converted to the native regex replacement form | +| Target rewrite | `set-path`, `set-query`; imported request rewrites move to `pre_route` with an ordering warning | +| Backend target | `use_backend`, `use-server`, or extension `use-backend`; a target is a configured RustProxy member ID, and selection bypasses shared cache | +| Local response | `deny [deny_status N]`, `return status N [string BODY]`, `redirect location URL [code N]` | +| Variables/control | `set-var(txn.name) SAMPLE`, `set-var-fmt(txn.name) FORMAT`, `unset-var(txn.name)`, `allow` (ends the current scope's chain) | +| RustProxy extensions | `http-pre-route`, `http-backend-request`, `http-deliver`; `set-header-if-missing`, `normalize-header`, `merge-header`, `remove-value`, `cache-pass`, `cache-lookup`, `cache-no-store`, `cache-ttl`, `cache-grace`, `cache-hash-header`, `disable-compression`, `stop` | + +Comments, quoted strings and continued lines are supported. Extension and +rewrite warnings must be reviewed before applying the returned draft. + +`POST /api/policy/test` evaluates a supplied draft and request/response fixture +with the same compiled engine, returning matched/skipped rules and actions. +It does not contact a backend or store responses. Supply repeated headers as +separate fixture entries when testing full-field counts. A policy-only trace is +not a complete simulation of authentication, VCL, cache, routing or compression; +verify those interactions with real traffic. + +The global policy is available at `GET/PUT /api/config/policy`, with the normal +configuration revision guard and administrator/API-token permissions. Import and +test endpoints use the normal administration authentication; they are not public +proxy routes. See [API](API.md) and the bundled OpenAPI for exact payloads. + +`GET /api/policy/stats` returns active rules by scope with match and action-error +counts. The tester does not increment live counters. Counts reset when the +configuration recompiles; they are not a persistent traffic history. + +Bounds per scope include 128 rules, 128 named ACLs, 16 maps, 1,024 total map +entries, 128 regex patterns and 256 KiB of serialized policy. A rule has 1–16 +actions; condition groups have at most 32 children and nesting is bounded at 16. +Expression/regex expansion and transaction storage have additional limits. +The complete configuration still has its existing 2 MiB bound. + +## Verification and upgrade + +Configurations without `policy` preserve the existing VCL and header behavior. +An older binary rejects the new key: remove policy objects before downgrading, +or restore a pre-upgrade configuration snapshot. No cache format change is +required by the policy model. Changing a global policy invalidates applicable +cached representations; changing a Vhost/location policy changes that scope's +cache identity. An invalid reload leaves the previous complete configuration +active. + +Run the Rust checks and regression tests from the source root: + +```bash +./dev.sh check +./dev.sh test +cargo clippy --locked --all-targets -- -D warnings +``` + +Passing a policy fixture or a mock-origin unit test alone does not establish +production readiness. Test the built binary with your authentication provider, +protocols, existing VCL and actual origin responses before deployment. diff --git a/docs/README.md b/docs/README.md index 42b2911..6e06209 100644 --- a/docs/README.md +++ b/docs/README.md @@ -16,6 +16,7 @@ Guides for operating RustProxy: installation, publishing services, security, cer - [Installation and updates](INSTALL.md) — packages, source build, Docker image, first administrator, systemd and updates. - [Configuration](CONFIGURATION.md) — SQLite or JSON configuration source, configuration map and changes that need a restart. +- [HTTP policy rules](POLICY.md) — named ACLs, maps, variables, HAProxy subset import, header/list operations, stage order and cooperation with existing VCL. - [Headless mode](HEADLESS.md) — proxy and load balancer configured only from a JSON file, without the panel. - [Troubleshooting](TROUBLESHOOTING.md) — symptom-based checks and a rollout checklist. diff --git a/docs/RESPONSE_DELIVERY.md b/docs/RESPONSE_DELIVERY.md index 5b60b43..0aaa9d4 100644 --- a/docs/RESPONSE_DELIVERY.md +++ b/docs/RESPONSE_DELIVERY.md @@ -35,6 +35,21 @@ Transformations can run on eligible reverse-proxy and Web Server responses. When ## Custom and security headers +For conditional operations, named ACLs, full-field counts, regex replacement or +safe `Vary` list normalization, use [HTTP policy rules](POLICY.md) (0.42.0). +`backend_response` changes origin headers before cache planning; `deliver` runs +after VCL delivery and before compression; `after_response` runs after +compression and the existing dynamic header rules. Existing Custom Headers keep +their behavior. A normalization rule preserves all variant dimensions instead +of replacing them with a fixed list. + +Configuring a `backend_response` policy, or adding a policy `hash_header` +dimension to a request, makes expired stale-while-revalidate objects use +foreground validation and disables proactive background refresh for that +request. Fresh HITs remain available. Foreground `304` validation uses +the same policy no-store/TTL decisions and existing VCL TTL/grace precedence. +See the policy guide for request-dependent cache bypass and explicit stale rules. + Configure global response headers, Vhost-specific policies and Web Server/location headers at the appropriate scope. Header rules can set, append or remove allowed names. Certain routing, forwarding, framing, cache diagnostics and security-sensitive fields are protected or subject to extra validation. Review especially HSTS, CSP, CORS and application-specific cookies before using a broad rule. ### Variables in header values (diagnostic headers) diff --git a/docs/STREAMS.md b/docs/STREAMS.md index 4018802..b9a6c87 100644 --- a/docs/STREAMS.md +++ b/docs/STREAMS.md @@ -25,6 +25,6 @@ The backend editor groups connection/capacity settings separately from active he Stream views/Overview include sessions, connections, traffic, rejected/errors and backend health/capacity when enabled. Counter reset or no-data state after service restart is normal. -The source package includes `scripts/start_stream_backends.sh`, `scripts/test_stream_tcp.py` and `scripts/test_stream_udp.py` for isolated test networks. Their mock selftests alone do **not** establish that RustProxy forwarding works; run end-to-end client traffic through the configured Stream listener. +Run end-to-end client traffic through the configured Stream listener in an isolated test network. Verify data transfer, idle timeouts and backend failover for the selected protocol. If clients cannot connect, inspect listen IP/port, host firewall, TCP vs UDP selection, routing to the chosen backend, backend health and stream logs. See [Security](SECURITY.md) and [Monitoring](MONITORING.md). diff --git a/docs/VCL.md b/docs/VCL.md index 10a716d..319e688 100644 --- a/docs/VCL.md +++ b/docs/VCL.md @@ -1,6 +1,6 @@ # VCL import: supported instructions and exact effects -This guide describes the VCL **subset implemented by RustProxy 0.39.2**, not the full Varnish Configuration Language. It is based on the VCL importer and cache-rule engine. Importing VCL **converts statements into graphical cache rules (which must then be saved)**; RustProxy does not execute arbitrary VCL text at request time. Unsupported instructions may be skipped with warnings or cause a parse error; they are not executed as Varnish code. **In the graphical importer, warnings pause conversion:** no rules are added until you explicitly choose **Add partial import (reviewed)**. Even after adding, you must separately save the configuration. The read-only VCL export is a human-oriented preview, **not** a lossless backup or a guaranteed re-importable VCL program. +This guide describes the VCL **subset implemented by RustProxy 0.42.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 for ordinary flat rules is a human-oriented preview, **not** a lossless backup or a guaranteed re-importable VCL program. Structured VCL imports use a JSON preview/export that preserves their control flow. 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. @@ -8,6 +8,16 @@ For the **complete reference to all 42 quick-rule templates** (conditions, stage ## Where to import, rule order and activation +Since 0.42.0, optional [HTTP policy rules](POLICY.md) can cooperate with these +rules. Policy request edits run before `vcl_recv`/`vcl_hash`, policy backend +response edits run after existing `beresp` edits but before cache planning, +policy delivery runs after `vcl_deliver`, and `after_response` runs after +compression and legacy dynamic headers. Existing VCL order, local-over-global +priority and terminal return semantics are unchanged. Either engine's explicit +pass wins over lookup; existing VCL TTL/grace assignments take precedence over +policy assignments. New policy Global → Vhost → Location ordering does not +replace the VCL ordering described below. + - **Settings -> Cache -> Rules**: global cache rules, optionally targeted to particular vhosts. - **Vhosts -> Cache -> Cache rules for this vhost**: rules for one vhost (ordinary or Docker-generated). **Ignore global cache rules** disables the global rules for that vhost. - Imported rules and graphical rules use the same engine. Within each stage, **vhost rules run first**, followed by applicable global rules. A vhost edit to the same header or supported scalar setting wins over a conflicting global edit. In one scope, later matching edits win unless `stop`/`return(...)` terminates the stage. @@ -63,17 +73,62 @@ The query-removal conversion accepts only the supported captured-separator `regs ## Recognized conditions and expressions +The corrected 0.42.0 importer records explicit branch selection. Each +`if`/`elsif`/`else` chain chooses its branch once when execution reaches it. +Changing or unsetting a condition's header inside that branch does not enter +its `else` or skip the remaining nested/tail statements. A later, independent +condition still reads the current, possibly modified headers. The same rule +applies in request, hash, backend-response and delivery hooks. + +**Upgrade existing imports:** saved flat rules from an older importer retain +their existing behavior. Their JSON no longer contains enough information to +recover the original branch boundaries. Re-import the original VCL with 0.42.0, +review the draft tester, replace the old converted rules and save. Do not append +the new import while leaving the old actions enabled. Native graphical rules +do not require conversion. + | Form | Example | Notes | |---|---|---| | URL, method, request headers | `req.url ~ "^/assets/"`, `req.method == "GET"`, `req.http.Cookie` | `req.url` includes path and query; an unqualified request header tests presence. `bereq.url` and `bereq.http.X` are accepted as rule-request aliases. | | Backend/delivery status and headers | `beresp.status == 200`, `beresp.http.Content-Type ~ "^text/"`, `resp.http.X-Flag` | Evaluated against the response at the relevant stage; earlier supported header mutations are visible to subsequent conditions. | | Comparisons | `==`, `!=`, `~`, `!~` | Equality and regex matching for supported request/response variables. | | Status comparisons | `beresp.status >= 500`, `resp.status < 400` | Also accepts `>`, `<=`, `==`, `!=`. | -| Branching | `if`, `elsif`, `else`, nested blocks, `&&`, `||`, `!`, parentheses | Branch guards are preserved in the generated rules, subject to the rule/condition limits. | +| Branching | `if`, `elsif`, `else`, nested blocks, `&&`, `||`, `!`, parentheses | The selected branch is retained in the generated control-flow group; independent later conditions observe earlier edits. Subject to rule/condition limits. | `client.ip` with a Varnish ACL is **not imported**; the graphical rules have a client IP/CIDR condition instead. `include`, external modules, backend/ACL/probe definitions and custom subroutines are not loaded as executable configuration. Arbitrary functions, variables, string concatenation, dynamic header expressions, `pipe`, `restart`, `purge`, `synth` and hit-for-miss/hit-for-pass behavior are **not** implemented. Import is a conversion, not a promise of runtime Varnish equivalence. -Limits include a maximum VCL source of 256 KiB; the compiled cache-rule lists are limited to 128 rules, 16 conditions and 16 actions per rule. A complex boolean expression may expand to too many rules and be skipped with a warning. Use the graphical tester to verify the imported behavior. +Limits include 256 KiB of VCL source, 128 canonical rules per list (including +branch-entry markers), and 16 actions per rule. A branch has up to 128 OR +alternatives with 16 conditions each; an `if` chain has at most 16 branches. +A group permits 16 enclosing branch guards and 2,048 condition nodes in total. +The parser also limits nested blocks and unary/grouped expressions to depth 64. +Unsupported or excessive branches are skipped with warnings or rejected at +parsing/validation; review partial imports and use the graphical tester before +saving. + +### Saved control flow and editor operations + +Fresh imports carry optional `vcl_flow` metadata on their canonical cache rules. +The importer generates a versioned group ID, a zero-based `index`, the total +`count`, and references to earlier branch selections in `guards`. A branch-entry +rule has no actions; its `branches[].any` contains OR alternatives, each an AND +list of ordinary rule conditions. A final `[[]]` predicate represents `else`. +Action rules use the selected branch without re-evaluating its original guard. +Selection is private to the request, hook and configured scope, including when +the same import is used locally and globally. + +Keep the complete import together. The panel moves, copies, enables, disables, +removes and assigns Vhosts to the whole group. Copies receive fresh group IDs. +Branch structure is read-only in the graphical editor; edit the original VCL +and replace its import to change that structure. The JSON preview/export keeps +the metadata, whereas the ordinary flat-rule VCL preview cannot represent it. +Configuration validation rejects incomplete or reordered groups, cross-hook +references, mixed enable/scope states and invalid branch ancestry before +activation. Rules without `vcl_flow` retain independent sequential evaluation. + +New control-flow configurations require 0.42.0 or newer. For rollback, restore +the pre-upgrade configuration; deleting metadata would make guarded actions +unconditional. Keep the original VCL source alongside a full JSON backup. ## `Vary`: before or after the cache? diff --git a/docs/VCL_SUPPORT_MATRIX.md b/docs/VCL_SUPPORT_MATRIX.md index 5491467..75b27d3 100644 --- a/docs/VCL_SUPPORT_MATRIX.md +++ b/docs/VCL_SUPPORT_MATRIX.md @@ -4,6 +4,11 @@ ## Practical examples and traffic scenarios +The VCL subset below is preserved in 0.42.0. Optional [HTTP policy rules](POLICY.md) +add named ACLs, header counts, maps, variables and staged operations alongside +VCL, with explicit integration points. Those native capabilities are not new +VCL syntax and do not imply full Varnish compatibility. + The companion [VCL traffic cookbook](VCL_TRAFFIC_COOKBOOK.md) contains **12 VCL recipes and an additional Drupal 6 parent-domain example** (including an intentionally restricted importer example and a high-risk advanced example), an HTTP request/response behavior matrix, `curl` checks, expected `PASS`/`MISS`/`HIT` behavior and troubleshooting. The standalone source files are in [`examples/vcl/`](../examples/vcl/). They cover public catalogs, JSON APIs, private routes, CDN cookies, public static files, multilingual responses, A/B variants, SSE/webhooks/errors, safe header changes, query normalization and highly restricted Set-Cookie removal. Each example states its origin/privacy contract and importer limitations. | Goal | Available through imported VCL | Native GUI/API required or not supported | @@ -152,6 +157,12 @@ The shared cache stores **HTTP status 200** responses only in this release. A po ## 7. Graphical actions without a faithful imported VCL equivalent +The corrected 0.42.0 importer preserves selected branches when their headers +are changed or removed; forced cache also separates missing, empty and present +Cookie/Authorization values before lookup. Older flat VCL +conversions need re-import from their original source to gain branch selection; +native graphical rules keep their existing evaluation order. + These capabilities exist in RustProxy's JSON/graphical cache rules but should **not** be inferred to work by pasting arbitrary VCL syntax: | Graphical rule/setting | VCL import limitation | diff --git a/docs/VHOSTS.md b/docs/VHOSTS.md index 340bbd9..5882fec 100644 --- a/docs/VHOSTS.md +++ b/docs/VHOSTS.md @@ -1,5 +1,10 @@ # Vhosts, domains and backends +Since 0.42.0, Vhosts and their custom locations can define optional +[HTTP policy rules](POLICY.md) for conditional headers, named ACLs, maps, +transaction variables and staged actions. These cooperate with existing VCL +and Custom Headers; their stage and scope order are documented separately. + A **Vhost** publishes one or more hostnames on named HTTP/HTTPS listeners. Its source can be an HTTP reverse-proxy backend pool or a reusable local Web Service. Use **Vhosts → Add** in the panel. ## Publish a site diff --git a/examples/policy-vary.haproxy b/examples/policy-vary.haproxy new file mode 100644 index 0000000..dfb9b58 --- /dev/null +++ b/examples/policy-vary.haproxy @@ -0,0 +1,6 @@ +# Import this snippet in the HTTP policy editor, then save the resulting draft. +acl vary_duplicate res.fhdr_cnt(Vary) eq 2 +acl vary_encoding res.fhdr(Vary) -i Accept-Encoding +acl vary_combined res.fhdr(Vary) -i "Accept,Accept-Encoding" "Accept, Accept-Encoding" + +http-response set-header Vary "Accept, Accept-Encoding" if vary_duplicate vary_encoding vary_combined diff --git a/examples/policy-vary.json b/examples/policy-vary.json new file mode 100644 index 0000000..7ad1a68 --- /dev/null +++ b/examples/policy-vary.json @@ -0,0 +1,25 @@ +{ + "vhosts": [ + { + "id": "app", + "frontend": {"hosts": ["*"]}, + "backends": [{"id": "origin", "url": "http://127.0.0.1:9000", "allow_private": true}], + "load_balancing": {"health_check": {"mode": "off"}}, + "policy": { + "acls": { + "vary_duplicate": {"fetch": "res.fhdr_cnt(Vary)", "operator": "eq", "values": ["2"]}, + "vary_encoding": {"fetch": "res.fhdr(Vary)", "operator": "equals", "ignore_case": true, "values": ["Accept-Encoding"]}, + "vary_combined": {"fetch": "res.fhdr(Vary)", "operator": "equals", "ignore_case": true, "values": ["Accept,Accept-Encoding", "Accept, Accept-Encoding"]} + }, + "rules": [ + { + "id": "combine-duplicate-vary", + "stage": "backend_response", + "when": {"all": [{"acl": "vary_duplicate"}, {"acl": "vary_encoding"}, {"acl": "vary_combined"}]}, + "actions": [{"type": "set_header", "name": "Vary", "value": "Accept, Accept-Encoding"}] + } + ] + } + } + ] +} diff --git a/examples/policy-vcl-cooperation.json b/examples/policy-vcl-cooperation.json new file mode 100644 index 0000000..e04f36b --- /dev/null +++ b/examples/policy-vcl-cooperation.json @@ -0,0 +1,50 @@ +{ + "cache": {"enabled": true, "expose_status": true}, + "policy": { + "rules": [ + { + "id": "normalize-final-vary", + "stage": "after_response", + "actions": [{"type": "normalize_header", "name": "Vary"}] + } + ] + }, + "vhosts": [ + { + "id": "app", + "frontend": {"hosts": ["*"]}, + "backends": [{"id": "origin", "url": "http://127.0.0.1:9000", "allow_private": true}], + "load_balancing": {"health_check": {"mode": "off"}}, + "policy": { + "acls": { + "mobile": {"fetch": "req.fhdr(User-Agent)", "operator": "contains", "values": ["mobile"], "ignore_case": true} + }, + "rules": [ + {"id": "default-device", "stage": "request", "actions": [{"type": "set_header", "name": "X-Device", "value": "desktop"}]}, + {"id": "mobile-device", "stage": "request", "when": {"acl": "mobile"}, "actions": [{"type": "set_header", "name": "X-Device", "value": "mobile"}]}, + {"id": "downstream-device-variant", "stage": "backend_response", "actions": [{"type": "merge_header", "name": "Vary", "value": "User-Agent"}]}, + {"id": "cache-diagnostic", "stage": "after_response", "actions": [{"type": "set_header", "name": "X-Policy-Cache", "value": "%[cache_status]"}]} + ] + }, + "cache": { + "enabled": true, + "rules": [ + { + "id": "private-api", + "stage": "request", + "conditions": [{"field": "path", "operator": "prefix", "values": ["/api/"]}], + "actions": [{"type": "pass"}], + "stop": true + }, + { + "id": "device-variant", + "stage": "request", + "hash_stage": true, + "conditions": [], + "actions": [{"type": "hash_header", "name": "X-Device"}] + } + ] + } + } + ] +} diff --git a/langs/en_US.json b/langs/en_US.json index 711ed1e..63f2a95 100644 --- a/langs/en_US.json +++ b/langs/en_US.json @@ -3446,11 +3446,22 @@ "cacheRuleTplGroupOther": "Other", "cacheRulesImportVcl": "Import VCL", "cacheRulesExportVcl": "Copy as VCL", + "cacheRulesExportJson": "Copy rule JSON", + "cacheRulesJsonPreview": "Rule JSON with VCL structure", + "cacheRulesFlowHelp": "Imported VCL keeps each branch decision for the selected block. Move, enable, duplicate and remove whole blocks. Actions remain editable; change the branch structure by importing VCL again. The JSON export preserves the complete structure.", + "cacheRulesFlowInvalid": "The imported VCL block containing '{rule}' is incomplete or structurally changed. Restore or import the complete block again.", + "cacheRulesFlowExportJson": "This imported VCL cannot be exported as flat rules without losing its branch structure. Use the complete JSON export.", + "cacheRulesFlowMove": "Move VCL block", + "cacheRulesFlowDuplicate": "Duplicate block", + "cacheRulesFlowRemove": "Remove block", + "cacheRuleFlowBranch": "Branch decision (if / elsif / else)", + "cacheRuleFlowPart": "VCL block · step {index}/{count}. Row controls affect the whole block.", + "cacheRulesFlowStructureLocked": "The VCL branch structure is preserved. To change conditions, stages or returns, import the VCL block again.", "cacheRulesAdd": "New rule", "cacheRulesIgnoreGlobal": "Ignore global cache rules for this vhost", "cacheRulesEmpty": "No cache rules yet. Add one or start from a template.", "cacheRulesEmptyVhost": "No vhost-specific cache rules. Global rules still apply unless ignored.", - "cacheRulesImportHelp": "Paste VCL (vcl_recv, vcl_hash, vcl_backend_response, vcl_deliver). Supported statements become rules; everything else is listed as a warning. Imported rules are added below and saved with the form.", + "cacheRulesImportHelp": "Paste VCL (vcl_recv, vcl_hash, vcl_backend_response, vcl_deliver). Supported statements become one structured block; unsupported statements are listed as warnings. The complete block is added below and saved with the form. Keep the original VCL to edit its branch structure later.", "cacheRulesImportRun": "Convert to rules", "cacheRulesImportDone": "Imported {count} rules. Review them and save.", "cacheRulesImportWarnings": "Import warnings: some statements were skipped or approximated:", @@ -3880,7 +3891,7 @@ "cacheGuideUncacheableDifference": "RustProxy's beresp.uncacheable = false only reverses an earlier cache-rule restriction; this differs from Varnish. Origin private/no-store and Set-Cookie still prevent storage unless separately and deliberately rewritten by a trusted rule.", "cacheGuideBuiltInHash": "hash_data(req.url) and hash_data(req.http.Host) are already included in the internal cache key. vcl_hash can add one extra req.http.* header, but does not automatically generate the matching Vary response header.", "cacheGuideStatusRestriction": "RustProxy currently stores only HTTP 200 responses. A TTL rule for 404/301 does not enable caching of those statuses; the former 404 template was removed to avoid suggesting otherwise.", - "cacheGuideVclPreviewWarning": "VCL export is a readable preview, not a lossless round-trip. If import reports warnings, rules are not added until you explicitly accept the partial result. Editing the source or closing the importer discards any pending import.", + "cacheGuideVclPreviewWarning": "Ordinary rules have a VCL preview, not a lossless export. Imported VCL blocks use a complete JSON export to preserve branch structure. If import reports warnings, rules are not added until you explicitly accept the partial result. Editing the source or closing the importer discards any pending import.", "cacheRulesTesterRequestTitle": "HTTP request", "cacheRulesTesterResponseTitle": "Backend response", "cacheRulesTesterHelpGlobal": "Preview: unsaved global rules plus saved rules of the selected vhost. No backend traffic or counter updates.", @@ -4104,6 +4115,134 @@ "fileLogsSummaryScanned": "{lines} lines / {bytes}", "fileLogsSummarySkipped": "The newest records are complete; {count} older file(s) were not read within the scan limit. Choose one in “File” to browse it.", "fileLogsSummaryTruncated": "Scan limit reached: older records in these files were not read. Narrow the period or choose a single file.", - "fileLogsSummaryPeriod": "{count} older file(s) skipped: they are entirely before the selected period." + "fileLogsSummaryPeriod": "{count} older file(s) skipped: they are entirely before the selected period.", + "policyTitle": "HTTP policies", + "policySave": "Apply HTTP policies", + "policyIntro": "Ordered HTTP rules with named ACLs, maps, transaction variables and HAProxy import. Changes are a draft until you save this configuration.", + "policyCompatibility": "New policies run Global → Vhost → Location. Existing VCL retains its order and priorities. Stop ends this scope’s policy stage only. Backend response changes affect cache admission; delivery changes do not alter stored objects.", + "policyVisual": "Rule builder", + "policyJson": "Policy JSON", + "policyInvalid": "Invalid policy configuration. Expected an object with rules, acls and maps.", + "policyHeaderInvalid": "Invalid header on line {line}. Use one Name: value per line; repeated names are allowed.", + "policyImportCollision": "Import conflicts with existing ACL or map: {name}. Rename it in the source before importing.", + "policyPresetVary": "Fix duplicate Vary (exact match)", + "policyPresetNormalize": "Normalize Vary (preserve dimensions)", + "policyAction": "Action", + "policyAdvancedAction": "Action JSON", + "policyMoveUp": "Move up", + "policyMoveDown": "Move down", + "policyRuleName": "Rule name", + "policyRuleId": "Rule ID", + "policyStage": "Execution stage", + "policyStop": "Stop this scope’s stage after matching", + "policyConditions": "Conditions (AND / OR / NOT / named ACL)", + "policyConditionJson": "Condition expression (JSON)", + "policyFetch": "Sample fetch", + "policyOperator": "Comparison", + "policyValues": "Values (one per line)", + "policyIgnoreCase": "Ignore ASCII letter case", + "policyCombine": "Combine conditions with", + "policyAddCondition": "Add condition", + "policyConditionsHelp": "An empty all group always matches. Values within a comparison are alternatives. Use full-header fetches (fhdr) to preserve commas and fhdr_cnt to count field occurrences. Named ACL: {\"acl\":\"name\"}.", + "policyActions": "Actions in order", + "policyAddAction": "Add action", + "policyActionLimit": "A rule can contain at most 16 actions.", + "policyRuleLimit": "A scope can contain at most 128 rules.", + "policyNewRule": "New HTTP rule", + "policyAddRule": "Add HTTP rule", + "policyEmpty": "No HTTP policies in this scope. Existing header and VCL rules continue to work.", + "policyDefinitions": "Named ACLs and maps", + "policyAcls": "Named ACL definitions (JSON object)", + "policyMaps": "Map definitions (JSON object)", + "policyDefinitionsHelp": "ACL names and maps belong to this policy scope. Maps use kind exact/prefix/regex/ip and entries [{\"key\":\"…\",\"value\":\"…\"}]. Values can use %[fetch,lower,map(name)]. Transaction variables are available to later stages.", + "policyImport": "Import HAProxy rules", + "policyHaproxySource": "HAProxy source", + "policyImportAdd": "Add imported rules to draft", + "policyImportAdded": "Rules added to this draft. Save the enclosing configuration to activate them.", + "policyImportPreview": "Validate and preview import", + "policyImportReady": "Import validated. Review the stages, conditions and actions below before adding.", + "policyImportHelp": "The documented HTTP/ACL subset is supported. Unsupported instructions reject the whole import. Import adds to existing rules; conflicting ACL/map names are rejected. normalize-header is a RustProxy extension.", + "policyTest": "Test draft and show trace", + "policyTestHelp": "Runs this draft at one stage using the live Rust evaluator. It does not contact an origin or simulate VCL, inherited scopes, authentication, compression or legacy Custom Headers. Enter duplicate headers on separate lines.", + "policyMethod": "Method", + "policyHost": "Host", + "policyPath": "Path", + "policyQuery": "Query (without ?)", + "policyClientIp": "Client IP", + "policyCountry": "Country code", + "policyTls": "HTTPS connection", + "policyStatus": "Response status", + "policyCacheStatus": "Cache result", + "policyBackend": "Backend ID (if known)", + "policyRequestHeaders": "Request headers (one field per line)", + "policyResponseHeaders": "Response headers (one field per line)", + "policyVariables": "Transaction variables (JSON string values)", + "policyRunTest": "Run test", + "policyVariablesInvalid": "Every transaction variable must have a string value.", + "policyTestStale": "The draft or test input changed during evaluation. Run the test again.", + "policyMatched": "Matched", + "policyYes": "Yes", + "policyNo": "No", + "policyNoStageRules": "No enabled rules ran at the selected stage.", + "policyRequestResult": "Resulting request headers", + "policyResponseResult": "Resulting response headers", + "policyFullResult": "Complete result and decisions (JSON)", + "policyLocationStage": "The pre_route stage is available only globally and at Vhost scope.", + "policyHeaderPreviewHelp": "Conditional HTTP policies have a separate server-side tester below. This header preview shows the existing Custom Headers and diagnostics only.", + "policyStagePreRoute": "Before routing", + "policyStageHelpPreRoute": "Before location selection. Path/query rewrites and deny are available here; only Global and Vhost scopes. Return and redirect require the request stage.", + "policyStageRequest": "Request / cache policy", + "policyStageHelpRequest": "After access checks and authentication. Request classification, return/redirect and cache decisions; existing VCL still runs with its original priorities.", + "policyStageBackendRequest": "Request to backend", + "policyStageHelpBackendRequest": "Request sent to a selected backend. Do not change representation dimensions after the cache key has been chosen.", + "policyStageBackendResponse": "Backend response / before cache", + "policyStageHelpBackendResponse": "After VCL backend-response edits, before cache admission. VCL TTL/grace settings keep priority; a no-store decision from either system wins.", + "policyStageDeliver": "Delivery / after VCL", + "policyStageHelpDeliver": "After VCL delivery, before compression and legacy dynamic response headers. Changes affect delivery, not the stored object.", + "policyStageAfterResponse": "Final response / after compression", + "policyStageHelpAfterResponse": "After compression and legacy dynamic headers. Local-response cache and protocol safety controls remain enforced. Preserve every Vary dimension.", + "policyFieldName": "Header / variable name", + "policyFieldValue": "Value / template", + "policyFieldPattern": "Regular expression", + "policyFieldReplacement": "Replacement", + "policyFieldId": "Configured backend ID", + "policyFieldStatus": "HTTP status", + "policyFieldBody": "Response body", + "policyFieldLocation": "Redirect location", + "policyFieldSeconds": "Seconds", + "policyActionSetHeader": "Set header", + "policyActionAppendHeader": "Append header field", + "policyActionRemoveHeader": "Remove header", + "policyActionSetIfMissing": "Set missing header", + "policyActionNormalizeHeader": "Normalize header list", + "policyActionMergeHeader": "Merge list values", + "policyActionRemoveValue": "Remove list value", + "policyActionReplaceHeader": "Replace header by regex", + "policyActionSetVar": "Set transaction variable", + "policyActionUnsetVar": "Remove transaction variable", + "policyActionSetPath": "Set request path", + "policyActionSetQuery": "Set query string", + "policyActionUseBackend": "Select configured backend", + "policyActionDeny": "Deny request", + "policyActionReturn": "Return local response", + "policyActionRedirect": "Redirect", + "policyActionPass": "Bypass cache", + "policyActionLookup": "Request cache lookup", + "policyActionNoStore": "Prevent cache storage", + "policyActionSetTtl": "Set cache TTL default", + "policyActionSetGrace": "Set cache grace default", + "policyActionHashHeader": "Add cache key header", + "policyActionDisableCompression": "Disable compression", + "policyActionStop": "Stop this scope’s stage", + "policyActionReplaceValue": "Replace list values by regex", + "policyPrivateResponse": "This policy uses client-specific facts in backend-response rules. The runtime prevents shared cache storage for these responses.", + "policyCounters": "Saved policy counters", + "policyCountersHelp": "Read-only counters for all scopes in the currently saved configuration. Counters reset when configuration is compiled. Draft tests do not increment live counters.", + "policyRefreshCounters": "Refresh live counters", + "policySavedRevision": "Saved configuration revision", + "policyScope": "Scope / Vhost / location", + "policyMatches": "Matches", + "policyErrors": "Action errors", + "policyCountersEmpty": "No enabled policy rules in the saved configuration." } } diff --git a/langs/pl_pl.json b/langs/pl_pl.json index 9066e4a..26603bd 100644 --- a/langs/pl_pl.json +++ b/langs/pl_pl.json @@ -3446,11 +3446,22 @@ "cacheRuleTplGroupOther": "Pozostałe", "cacheRulesImportVcl": "Import VCL", "cacheRulesExportVcl": "Kopiuj jako VCL", + "cacheRulesExportJson": "Kopiuj JSON reguł", + "cacheRulesJsonPreview": "JSON reguł ze strukturą VCL", + "cacheRulesFlowHelp": "Import VCL zachowuje wybór gałęzi w danym bloku. Przenoszenie, włączanie, kopiowanie i usuwanie obejmuje cały blok. Akcje można edytować; zmianę struktury warunków wprowadź przez ponowny import VCL. Eksport JSON zachowuje pełną strukturę.", + "cacheRulesFlowInvalid": "Blok VCL zawierający regułę „{rule}” jest niepełny lub ma zmienioną strukturę. Przywróć go albo ponownie zaimportuj cały blok.", + "cacheRulesFlowExportJson": "Eksport tego VCL jako płaskich reguł utraciłby strukturę warunków. Użyj pełnego eksportu JSON.", + "cacheRulesFlowMove": "Przenieś blok VCL", + "cacheRulesFlowDuplicate": "Powiel blok", + "cacheRulesFlowRemove": "Usuń blok", + "cacheRuleFlowBranch": "Wybór gałęzi (if / elsif / else)", + "cacheRuleFlowPart": "Blok VCL · krok {index}/{count}. Przyciski wiersza dotyczą całego bloku.", + "cacheRulesFlowStructureLocked": "Struktura warunków VCL jest zachowana. Warunki, etapy i zakończenia zmień przez ponowny import bloku VCL.", "cacheRulesAdd": "Nowa reguła", "cacheRulesIgnoreGlobal": "Ignoruj globalne reguły cache w tym vhoście", "cacheRulesEmpty": "Brak reguł cache. Dodaj regułę albo zacznij od szablonu.", "cacheRulesEmptyVhost": "Brak reguł cache dla tego vhosta. Reguły globalne nadal działają, chyba że je zignorujesz.", - "cacheRulesImportHelp": "Wklej VCL (vcl_recv, vcl_hash, vcl_backend_response, vcl_deliver). Obsługiwane instrukcje staną się regułami, resztę wypiszemy jako ostrzeżenia. Zaimportowane reguły zostaną dodane poniżej i zapisane z formularzem.", + "cacheRulesImportHelp": "Wklej VCL (vcl_recv, vcl_hash, vcl_backend_response, vcl_deliver). Obsługiwane instrukcje utworzą jeden blok ze strukturą warunków; pozostałe zgłosimy jako ostrzeżenia. Cały blok zostanie dodany poniżej i zapisany z formularzem. Zachowaj oryginalny VCL do późniejszej zmiany struktury warunków.", "cacheRulesImportRun": "Zamień na reguły", "cacheRulesImportDone": "Zaimportowano reguł: {count}. Sprawdź je i zapisz.", "cacheRulesImportWarnings": "Ostrzeżenia importu: część instrukcji pominięto lub przetłumaczono w przybliżeniu:", @@ -3880,7 +3891,7 @@ "cacheGuideUncacheableDifference": "W RustProxy beresp.uncacheable = false cofa tylko wcześniejszy zakaz zapisu z reguły cache — inaczej niż w Varnishu. Nagłówki private/no-store i Set-Cookie nadal blokują zapis, chyba że zaufana reguła świadomie je nadpisze.", "cacheGuideBuiltInHash": "hash_data(req.url) i hash_data(req.http.Host) są już uwzględnione w wewnętrznym kluczu cache. vcl_hash może dodać dodatkowy nagłówek req.http.*, ale nie tworzy automatycznie odpowiedniego nagłówka Vary.", "cacheGuideStatusRestriction": "RustProxy zapisuje obecnie tylko odpowiedzi HTTP 200. Reguła TTL dla 404/301 nie uruchomi cache tych statusów; usunięto szablon 404, aby nie sugerował inaczej.", - "cacheGuideVclPreviewWarning": "Eksport VCL to podgląd, a nie bezstratny zapis konfiguracji. Gdy importer zwraca ostrzeżenia, reguły zostaną dodane dopiero po wyraźnej akceptacji częściowego wyniku. Edycja kodu lub zamknięcie importera anuluje oczekujący import.", + "cacheGuideVclPreviewWarning": "Zwykłe reguły mają podgląd VCL, który nie jest bezstratnym eksportem. Importowane bloki VCL korzystają z pełnego eksportu JSON zachowującego strukturę warunków. Gdy importer zgłasza ostrzeżenia, reguły zostaną dodane dopiero po wyraźnej akceptacji częściowego wyniku. Edycja kodu lub zamknięcie importera anuluje oczekujący import.", "cacheRulesTesterRequestTitle": "Żądanie HTTP", "cacheRulesTesterResponseTitle": "Odpowiedź backendu", "cacheRulesTesterHelpGlobal": "Symulacja: niezapisane reguły globalne i zapisane reguły wybranego vhosta. Bez ruchu do backendu i zmiany liczników.", @@ -4104,6 +4115,134 @@ "fileLogsSummaryScanned": "{lines} linii / {bytes}", "fileLogsSummarySkipped": "Najnowsze wpisy są kompletne; {count} starszych plików nie przeczytano w limicie skanowania. Wybierz plik w polu „Plik”, aby go przejrzeć.", "fileLogsSummaryTruncated": "Osiągnięto limit skanowania: starsze wpisy z tych plików nie zostały przeczytane. Zawęź okres albo wybierz jeden plik.", - "fileLogsSummaryPeriod": "Pominięto {count} starszych plików: w całości są sprzed wybranego okresu." + "fileLogsSummaryPeriod": "Pominięto {count} starszych plików: w całości są sprzed wybranego okresu.", + "policyTitle": "Reguły HTTP", + "policySave": "Zastosuj reguły HTTP", + "policyIntro": "Uporządkowane reguły HTTP z nazwanymi ACL, mapami, zmiennymi transakcji i importem HAProxy. Zmiany działają dopiero po zapisaniu konfiguracji.", + "policyCompatibility": "Nowe reguły działają w kolejności Global → Vhost → Lokalizacja. VCL zachowuje swoją kolejność i priorytety. Stop kończy tylko dany etap reguł w tym zakresie. Zmiany odpowiedzi backendu wpływają na cache; zmiany przy dostarczaniu nie zmieniają zapisanych obiektów.", + "policyVisual": "Edytor reguł", + "policyJson": "JSON reguł HTTP", + "policyInvalid": "Nieprawidłowa konfiguracja. Oczekiwany obiekt z polami rules, acls i maps.", + "policyHeaderInvalid": "Nieprawidłowy nagłówek w wierszu {line}. Podaj Nazwa: wartość; powtarzające się nazwy są dozwolone.", + "policyImportCollision": "Import koliduje z istniejącą ACL lub mapą: {name}. Zmień nazwę w źródle przed importem.", + "policyPresetVary": "Napraw duplikat Vary (dokładne dopasowanie)", + "policyPresetNormalize": "Normalizuj Vary (zachowaj wymiary)", + "policyAction": "Akcja", + "policyAdvancedAction": "JSON akcji", + "policyMoveUp": "W górę", + "policyMoveDown": "W dół", + "policyRuleName": "Nazwa reguły", + "policyRuleId": "ID reguły", + "policyStage": "Etap wykonania", + "policyStop": "Zakończ etap w tym zakresie po dopasowaniu", + "policyConditions": "Warunki (AND / OR / NOT / nazwana ACL)", + "policyConditionJson": "Wyrażenie warunkowe (JSON)", + "policyFetch": "Źródło wartości", + "policyOperator": "Porównanie", + "policyValues": "Wartości (każda w osobnym wierszu)", + "policyIgnoreCase": "Ignoruj wielkość liter ASCII", + "policyCombine": "Łącz warunki przez", + "policyAddCondition": "Dodaj warunek", + "policyConditionsHelp": "Pusta grupa all pasuje zawsze. Wartości jednego porównania są alternatywami. fhdr zachowuje przecinki, a fhdr_cnt zlicza wystąpienia pola. Nazwana ACL: {\"acl\":\"nazwa\"}.", + "policyActions": "Akcje w kolejności", + "policyAddAction": "Dodaj akcję", + "policyActionLimit": "Reguła może zawierać najwyżej 16 akcji.", + "policyRuleLimit": "Zakres może zawierać najwyżej 128 reguł.", + "policyNewRule": "Nowa reguła HTTP", + "policyAddRule": "Dodaj regułę HTTP", + "policyEmpty": "Brak reguł HTTP w tym zakresie. Dotychczasowe reguły nagłówków i VCL nadal działają.", + "policyDefinitions": "Nazwane ACL i mapy", + "policyAcls": "Definicje nazwanych ACL (obiekt JSON)", + "policyMaps": "Definicje map (obiekt JSON)", + "policyDefinitionsHelp": "Nazwy ACL i map należą do tego zakresu. Mapy używają kind exact/prefix/regex/ip i entries [{\"key\":\"…\",\"value\":\"…\"}]. Wartości obsługują %[fetch,lower,map(nazwa)]. Zmienne transakcji są dostępne w dalszych etapach.", + "policyImport": "Importuj reguły HAProxy", + "policyHaproxySource": "Źródło HAProxy", + "policyImportAdd": "Dodaj zaimportowane reguły do szkicu", + "policyImportAdded": "Reguły dodano do szkicu. Zapisz konfigurację, aby je aktywować.", + "policyImportPreview": "Sprawdź i pokaż import", + "policyImportReady": "Import sprawdzony. Przejrzyj poniższe etapy, warunki i akcje przed dodaniem.", + "policyImportHelp": "Obsługiwany jest udokumentowany podzbiór HTTP/ACL. Nieobsługiwane instrukcje odrzucają cały import. Import dodaje reguły; kolidujące nazwy ACL/map są odrzucane. normalize-header jest rozszerzeniem RustProxy.", + "policyTest": "Testuj szkic i pokaż przebieg", + "policyTestHelp": "Uruchamia ten szkic na jednym etapie przy użyciu silnika Rust. Nie łączy się z backendem ani nie symuluje VCL, dziedziczenia, uwierzytelniania, kompresji i dotychczasowych Custom Headers. Powtórzone nagłówki podaj w osobnych wierszach.", + "policyMethod": "Metoda", + "policyHost": "Host", + "policyPath": "Ścieżka", + "policyQuery": "Parametry (bez ?)", + "policyClientIp": "IP klienta", + "policyCountry": "Kod kraju", + "policyTls": "Połączenie HTTPS", + "policyStatus": "Status odpowiedzi", + "policyCacheStatus": "Wynik cache", + "policyBackend": "ID backendu (jeśli znane)", + "policyRequestHeaders": "Nagłówki żądania (jedno pole w wierszu)", + "policyResponseHeaders": "Nagłówki odpowiedzi (jedno pole w wierszu)", + "policyVariables": "Zmienne transakcji (wartości tekstowe JSON)", + "policyRunTest": "Uruchom test", + "policyVariablesInvalid": "Każda zmienna transakcji musi mieć wartość tekstową.", + "policyTestStale": "Szkic lub dane testowe zmieniły się podczas oceny. Uruchom test ponownie.", + "policyMatched": "Dopasowanie", + "policyYes": "Tak", + "policyNo": "Nie", + "policyNoStageRules": "Na wybranym etapie nie wykonano aktywnych reguł.", + "policyRequestResult": "Wynikowe nagłówki żądania", + "policyResponseResult": "Wynikowe nagłówki odpowiedzi", + "policyFullResult": "Pełny wynik i decyzje (JSON)", + "policyLocationStage": "Etap pre_route jest dostępny tylko globalnie i na poziomie Vhost.", + "policyHeaderPreviewHelp": "Warunkowe reguły HTTP mają poniżej osobny tester. Ten podgląd przedstawia dotychczasowe Custom Headers i nagłówki diagnostyczne.", + "policyStagePreRoute": "Przed routingiem", + "policyStageHelpPreRoute": "Przed wyborem lokalizacji. Tutaj dostępne są zmiany ścieżki i parametrów oraz deny; tylko zakres Global i Vhost. Return i redirect wymagają etapu request.", + "policyStageRequest": "Żądanie / polityka cache", + "policyStageHelpRequest": "Po kontroli dostępu i uwierzytelnieniu. Klasyfikacja żądania, return/redirect i decyzje cache; VCL nadal działa z dotychczasowymi priorytetami.", + "policyStageBackendRequest": "Żądanie do backendu", + "policyStageHelpBackendRequest": "Żądanie wysyłane do wybranego backendu. Nie zmieniaj wymiarów reprezentacji po wybraniu klucza cache.", + "policyStageBackendResponse": "Odpowiedź backendu / przed cache", + "policyStageHelpBackendResponse": "Po zmianach VCL odpowiedzi backendu, przed przyjęciem do cache. TTL/grace z VCL mają priorytet; no-store z dowolnego systemu blokuje zapis.", + "policyStageDeliver": "Dostarczanie / po VCL", + "policyStageHelpDeliver": "Po VCL deliver, przed kompresją i dotychczasowymi dynamicznymi nagłówkami. Zmiany dotyczą dostarczanej odpowiedzi, a nie zapisanego obiektu.", + "policyStageAfterResponse": "Końcowa odpowiedź / po kompresji", + "policyStageHelpAfterResponse": "Po kompresji i dotychczasowych dynamicznych nagłówkach. Zabezpieczenia odpowiedzi lokalnych i protokołu pozostają aktywne. Zachowuj wszystkie wymiary Vary.", + "policyFieldName": "Nazwa nagłówka / zmiennej", + "policyFieldValue": "Wartość / szablon", + "policyFieldPattern": "Wyrażenie regularne", + "policyFieldReplacement": "Zastąpienie", + "policyFieldId": "ID skonfigurowanego backendu", + "policyFieldStatus": "Status HTTP", + "policyFieldBody": "Treść odpowiedzi", + "policyFieldLocation": "Adres przekierowania", + "policyFieldSeconds": "Sekundy", + "policyActionSetHeader": "Ustaw nagłówek", + "policyActionAppendHeader": "Dodaj pole nagłówka", + "policyActionRemoveHeader": "Usuń nagłówek", + "policyActionSetIfMissing": "Ustaw brakujący nagłówek", + "policyActionNormalizeHeader": "Normalizuj listę nagłówka", + "policyActionMergeHeader": "Scal wartości listy", + "policyActionRemoveValue": "Usuń wartość z listy", + "policyActionReplaceHeader": "Zastąp nagłówek przez regex", + "policyActionSetVar": "Ustaw zmienną transakcji", + "policyActionUnsetVar": "Usuń zmienną transakcji", + "policyActionSetPath": "Ustaw ścieżkę żądania", + "policyActionSetQuery": "Ustaw parametry żądania", + "policyActionUseBackend": "Wybierz skonfigurowany backend", + "policyActionDeny": "Odrzuć żądanie", + "policyActionReturn": "Zwróć odpowiedź lokalną", + "policyActionRedirect": "Przekieruj", + "policyActionPass": "Pomiń cache", + "policyActionLookup": "Zażądaj odczytu cache", + "policyActionNoStore": "Zablokuj zapis do cache", + "policyActionSetTtl": "Ustaw domyślny TTL cache", + "policyActionSetGrace": "Ustaw domyślny grace cache", + "policyActionHashHeader": "Dodaj nagłówek do klucza cache", + "policyActionDisableCompression": "Wyłącz kompresję", + "policyActionStop": "Zakończ etap w tym zakresie", + "policyActionReplaceValue": "Zastąp wartości listy przez regex", + "policyPrivateResponse": "Ta polityka używa danych klienta w regułach odpowiedzi backendu. Silnik blokuje współdzielony zapis tych odpowiedzi w cache.", + "policyCounters": "Liczniki zapisanych reguł", + "policyCountersHelp": "Liczniki wszystkich zakresów aktualnie zapisanej konfiguracji, tylko do odczytu. Liczniki zerują się przy kompilacji konfiguracji. Testy szkiców nie zwiększają liczników ruchu.", + "policyRefreshCounters": "Odśwież liczniki ruchu", + "policySavedRevision": "Rewizja zapisanej konfiguracji", + "policyScope": "Zakres / Vhost / lokalizacja", + "policyMatches": "Dopasowania", + "policyErrors": "Błędy akcji", + "policyCountersEmpty": "Brak aktywnych reguł HTTP w zapisanej konfiguracji." } } diff --git a/make_zip.py b/make_zip.py index 1ef5000..d819ae7 100755 --- a/make_zip.py +++ b/make_zip.py @@ -96,8 +96,7 @@ def main() -> None: f'{hashlib.sha256(path.read_bytes()).hexdigest()} {path.relative_to(ROOT).as_posix()}\n' for path in paths ) - #checksum.write_text(sums, encoding='utf-8', newline='\n') - checksum.write_text(sums, encoding='utf-8') + checksum.write_text(sums, encoding='utf-8', newline='\n') timestamp = release_datetime() output.parent.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(output, 'w') as archive: diff --git a/scripts/README.md b/scripts/README.md index 9e00e46..abac725 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -10,6 +10,15 @@ External development and QA helpers live under `tools/`; external platform integ Keep these paths stable because Rust source, `build.rs` and shell entry points reference them directly. +## Source check + +`python3 scripts/preflight.py` checks that `Cargo.toml`, `build.rs`, `src/lib.rs` +and `src/main.rs` exist as files. Use `--root PATH` to check another source tree. +It does not modify files. Cargo and the build helpers validate Rust modules, +embedded documentation and generated assets during compilation. + +`bash dev.sh doctor` runs this check and shows the available build tools. + ## Panel stylesheet sources The dashboard stylesheet lives in `src/admin/web/css/`, with its complete cascade @@ -22,11 +31,10 @@ needed. The documentation page retains its separate `src/admin/web/docs.css`. ```bash python3 scripts/build/panel_css.py --check -python3 tools/dev/test_panel_css.py python3 scripts/audit_css_usage.py --strict ``` -The first two commands use only the Python standard library. The optional +The stylesheet check uses only the Python standard library. The optional selector/structure audit needs `tinycss2` and `cssselect2`; it checks all manifest modules together and reviews the documentation stylesheet separately. Use `--json PATH` for selector references and `--structure-json PATH` for repeated @@ -38,25 +46,16 @@ standard/WebKit/Gecko rules only when joining them would create an incompatible vendor selector list. Choose shared-rule placement by checking the cascade, not by mechanically moving every matching block to the beginning of a module. -Preflight rejects missing, repeated or unlisted CSS modules and stale monolithic -`style.css` files. `./dev.sh repair` backs up only the exact original 0.34.9 -monolith; custom or unknown content requires manual review and is never moved -or discarded automatically. Rebuild the Rust binary after changing CSS. +The stylesheet helper rejects missing, repeated or unlisted CSS modules. +Rebuild the Rust binary after changing CSS. Keep `scripts/__init__.py` and `scripts/build/__init__.py` in the source package. -They keep preflight, audit, tests and packaging imports local even when unrelated -Python packages named `scripts` or `build` are installed. An older CSS-refactor -archive without the build marker can fail -with `ModuleNotFoundError: No module named 'build.panel_css'`; restore the marker -from the complete source archive and run `bash dev.sh repair` again. Installing -another Python package is not required. +They keep audit and packaging imports local even when unrelated Python packages +named `scripts` or `build` are installed. ### Missing generated CSS during Rust compilation -`panel-style.css` is generated inside Cargo's `OUT_DIR`. `bash dev.sh repair` -validates the source layout and preserves known obsolete files; it does not -generate Cargo outputs. Preflight also checks that the current `build.rs` calls -the panel generator from `main` and reports a mixed source tree before Cargo. +`panel-style.css` is generated inside Cargo's `OUT_DIR` by `build.rs`. After overlaying a source ZIP onto a previously built checkout, a compiler error for a missing `OUT_DIR/panel-style.css` can indicate an old cached build script @@ -64,7 +63,7 @@ or a `build.rs` from another source version. Restore the complete matching archive, including the root `build.rs`, then run from the project root: ```bash -bash dev.sh repair +python3 scripts/build/panel_css.py --check touch build.rs bash dev.sh build ``` @@ -73,14 +72,8 @@ The source ZIP uses reproducible timestamps. Cargo's [build-script change detection](https://doc.rust-lang.org/cargo/reference/build-scripts.html#change-detection) uses file modification times, so refreshing `build.rs` forces regeneration after an archive overlay. This works with the target directory selected by `dev.sh`. -The generator now also registers its output as a watched Cargo dependency and +The generator also registers its output as a watched Cargo dependency and recreates a removed bundle. An identical bundle keeps its modification time. The Rust build script rejects a missing, empty or non-file output immediately after the helper returns. -## Stream TCP/UDP test helpers - -- `start_stream_backends.sh` — launches two TCP echo mocks (9101, 9102) and two UDP echo/probe mocks (9201, 9202), defaulting to loopback, and terminates all on Ctrl+C. -- `test_stream_tcp.py`, `test_stream_udp.py` — independent `server`, `client` and `selftest` modes. See `docs/STREAMS.md` for RustProxy listener setup and test commands. - -The selftests test only Python mock peers, **not** RustProxy forwarding. diff --git a/scripts/preflight.py b/scripts/preflight.py index 8c4d901..16a43d2 100755 --- a/scripts/preflight.py +++ b/scripts/preflight.py @@ -1,188 +1,21 @@ #!/usr/bin/env python3 -"""Detect mixed source trees and preserve the known obsolete 0.0.1 auth module.""" -from __future__ import annotations +"""Check core source files before invoking Cargo.""" + import argparse -import hashlib -import re from pathlib import Path -import sys - -LEGACY_AUTH = "4df9d473c9214365d91c83072f97aafab6ede4edcf4e1369b5c3679ded5cff85" -LEGACY_PANEL_CSS = "38716fae968aeb8f6a8510f28bb9054a73a438a969c3b69f9c9d921acfed6e06" - - -def validate_panel_css_build(root: Path) -> None: - """Check this project's build.rs startup contract, not arbitrary Rust code.""" - source = (root / "build.rs").read_text(encoding="utf-8") - # Ignore ordinary strings and comments, including nested block comments. - # The required call precedes the first nested block in the shipped main(). - code: list[str] = [] - position = 0 - token = re.compile(r'"(?:\\.|[^"\\])*"|//[^\n]*|/\*', re.DOTALL) - while match := token.search(source, position): - code.extend((source[position:match.start()], " ")) - position = match.end() - if match.group() == "/*": - depth = 1 - while depth: - boundary = re.search(r'/\*|\*/', source[position:]) - if boundary is None: - position = len(source) - break - depth += 1 if boundary.group() == "/*" else -1 - position += boundary.end() - code.append(source[position:]) - main = re.search(r'\bfn\s+main\s*\(\s*\)[^{]*\{([^{}]*)', "".join(code)) - if main is None or re.search( - r'\bpanel_styles\s*\(\s*&root\s*,\s*&out\s*,?\s*\)\s*\?\s*;', - main.group(1), - ) is None: - raise ValueError( - "Mixed modular panel CSS source tree: build.rs is missing the expected " - "panel_styles(&root, &out)? call in main's startup block. Restore build.rs " - "from the complete matching source archive, preserving your local edits, " - "then run 'touch build.rs' and retry ./dev.sh. " - "Automatic repair does not rewrite build.rs." - ) - - -def preserve_legacy_panel_css(root: Path, repair_known: bool = False) -> list[str]: - old = root / "src/admin/web/style.css" - manifest = root / "src/admin/web/css/manifest.json" - if not manifest.is_file() or not (old.exists() or old.is_symlink()): - return [] - if old.is_symlink() or hashlib.sha256(old.read_bytes()).hexdigest() != LEGACY_PANEL_CSS: - raise ValueError( - "Obsolete src/admin/web/style.css remains beside the modular CSS sources and " - "contains unknown/custom content. Preserve it outside src/admin/web, review " - "your changes and port them into the CSS modules before rebuilding. " - "Automatic repair does not move or discard custom styles." - ) - if not repair_known: - raise ValueError( - "Known obsolete 0.34.9 src/admin/web/style.css remains beside the modular CSS sources. " - "Run ./dev.sh repair to preserve it under .upgrade-backup/panel-css/." - ) - target = root / ".upgrade-backup/panel-css/style.css.0.34.9" - if target.exists() or target.is_symlink(): - if target.is_symlink() or target.read_bytes() != old.read_bytes(): - raise ValueError("Legacy CSS backup already contains different data; refusing to overwrite it") - old.unlink() # The exact original is already backed up. - else: - target.parent.mkdir(parents=True, exist_ok=True) - old.rename(target) - return [f"Preserved obsolete panel CSS as {target.relative_to(root)}"] - - -def check(root: Path, repair_known: bool = False) -> list[str]: - messages: list[str] = preserve_legacy_panel_css(root, repair_known) - obsolete_split_files = ( - "src/admin/web/app.js", - "src/admin/web/vhosts.js", - "src/web_server.rs", - ) - split_markers = { - "src/admin/web/app.js": "src/admin/web/app/core.js", - "src/admin/web/vhosts.js": "src/admin/web/vhosts/core.js", - "src/web_server.rs": "src/web_server/mod.rs", - } - for relative in obsolete_split_files: - obsolete = root / relative - marker = root / split_markers[relative] - if not obsolete.exists() or not marker.is_file(): - continue - if not repair_known: - raise ValueError( - f"Obsolete 0.25.0 source monolith {relative} remains beside the 0.25.1 split tree. " - "Run ./dev.sh repair (or any normal ./dev.sh command) to preserve it under .upgrade-backup/." - ) - backup_root = root / ".upgrade-backup" / "0.25.1-split" - target = backup_root / relative - target.parent.mkdir(parents=True, exist_ok=True) - if target.exists(): - if target.read_bytes() != obsolete.read_bytes(): - raise ValueError( - f"Backup target {target.relative_to(root)} already contains different data; " - f"move {relative} outside the source tree manually before rebuilding." - ) - obsolete.unlink() - else: - obsolete.rename(target) - messages.append( - f"Preserved obsolete {relative} as {target.relative_to(root)}" - ) - - legacy = root / "src/auth.rs" - if legacy.exists() and (root / "src/auth/mod.rs").is_file(): - if legacy.is_symlink() or hashlib.sha256(legacy.read_bytes()).hexdigest() != LEGACY_AUTH: - raise ValueError("Both src/auth.rs and src/auth/mod.rs exist. The single-file module is not the known 0.0.1 file. Preserve your edits and move it outside src before rebuilding. See docs/MIGRATION.md.") - if not repair_known: - raise ValueError("Known obsolete src/auth.rs from 0.0.1 found. Run ./dev.sh repair or start ./dev.sh to preserve it in .upgrade-backup/legacy-auth/.") - directory = root / ".upgrade-backup/legacy-auth" - directory.mkdir(parents=True, exist_ok=True) - target = directory / "auth.rs.0.0.1" - if target.exists(): - if hashlib.sha256(target.read_bytes()).hexdigest() != LEGACY_AUTH: - raise ValueError("Legacy backup path contains a different file; refusing to overwrite it.") - legacy.unlink() # Byte-identical content was already preserved. - else: - legacy.rename(target) - messages.append("Preserved obsolete src/auth.rs as .upgrade-backup/legacy-auth/auth.rs.0.0.1") - for module in (root / "src").rglob("mod.rs"): - flat = module.parent.with_suffix(".rs") - if flat.is_file(): - raise ValueError(f"Conflicting Rust modules: {flat.relative_to(root)} and {module.relative_to(root)}") - for path in ["src/auth/mod.rs", "src/auth/store.rs", "src/backup/snapshot.rs", "src/upstream.rs", "src/tls.rs", "src/config/internal_routing.rs", "src/proxy/websocket.rs", "src/proxy/error_fallback.rs", "src/cache/mod.rs", "src/cache/model.rs", "src/cache/lifecycle.rs", "src/cache/cold.rs", "src/cache/dashboard.rs", "src/cache/tickets.rs", "src/cache/lookup.rs", "src/cache/policy.rs", "src/cache/fill.rs", "src/cache/tests.rs", "src/settings.rs", "src/compression/mod.rs", "src/diagnostics.rs", "src/traffic/mod.rs", "src/system_stats/mod.rs", "src/system_stats/linux/mod.rs", "src/vhost.rs", "src/vhost/error_fallback.rs", "src/web_server/mod.rs", "src/web_server/config.rs", "src/web_server/filesystem.rs", "src/web_server/security.rs", "src/web_server/response.rs", "src/web_server/request.rs", "src/web_server/routing.rs", "src/web_server/fastcgi.rs", "src/web_server/htaccess.rs", "src/web_server/serve.rs", "src/web_server/tests.rs", "src/balance.rs", "src/security/mod.rs", "src/admin/web/vhosts/core.js", "src/admin/web/vhosts/rates.js", "src/admin/web/vhosts/health.js", "src/admin/web/vhosts/editor.js", "src/admin/web/vhosts/render.js", "src/admin/web/web-server.js", "src/admin/web/streams.js", "src/admin/web/host404.js", "src/admin/web/app/core.js", "src/admin/web/app/icons.js", "src/admin/web/app/session-resume.js", "src/admin/web/app/preferences.js", "src/admin/web/app/config-history.js", "src/admin/web/app/runtime.js", "src/admin/web/app/settings.js", "src/admin/web/management.js", "src/admin/web/drafts.js", "src/pages/mod.rs", "tools/dev/mock_server.py", "tools/dev/mock_auth.py", "src/forwarding.rs", "src/tinyauth/mod.rs", "src/http3.rs", "src/stream.rs", "src/admin/web/integrations.js", "src/admin/web/traffic-panel.js", "src/prometheus.rs", "src/admin/web/settings.js", "src/admin/web/docker.js", "src/docker.rs", "docker-agent/main.go", "docker-agent/model.go", "docker-agent/docker.go", "docker-agent/network.go", "docker-agent/certificate.go", "docker-agent/server.go", "docker-agent/main_test.go", "docker-agent/rustproxy-docker-agent.service", "docker-agent/install.sh", "docs/DOCKER_DISCOVERY.md", "docs/WEB_SERVER.md", "docs/PHP_FPM.md", "docs/README.md", "CHANGELOG.md", "LICENSE", "docs/FEATURES.md", "docs/PERFORMANCE.md", "scripts/runtime/acme_provider.py", "src/basic_auth/mod.rs", "scripts/deploy/deploy.py", "scripts/deploy/deploy_core.py", "scripts/deploy/deploy_runtime.py", "scripts/migration/migrate_npm.py", "scripts/migration/migrate_npm_core.py", "scripts/migration/migrate_npm_api.py", "docs/MIGRATION.md", "docs/STREAMS.md", "install.sh", "install-debian13.sh", "update.sh", "build.rs", "scripts/build/swagger_assets.py", "src/admin/documentation.rs", "src/admin/openapi.json", "langs/en_US.json", "langs/pl_pl.json", "Dockerfile", ".dockerignore", "docs/INSTALL.md", "docs/MONITORING.md", "docs/CUSTOM_LOCATIONS.md", "grafana/rustproxy-overview.json"]: - if not (root / path).is_file(): - raise ValueError(f"Incomplete RustProxy 0.34.2 source tree: missing {path}") - for path in ("scripts/__init__.py", "scripts/build/__init__.py", "scripts/build/panel_css.py", "src/admin/web/css/manifest.json"): - if not (root / path).is_file(): - raise ValueError(f"Incomplete modular panel CSS source tree: missing {path}") - validate_panel_css_build(root) - for path in ("src/admin/web/app/path-permissions.js", "src/admin/web/app/certificate-inspection.js"): - if not (root / path).is_file(): - raise ValueError(f"Incomplete RustProxy 0.34.10 path-permissions source tree: missing {path}") - if __package__: - from .build.panel_css import bundle - else: - from build.panel_css import bundle - bundle(root) # Validate the manifest and every module without generating files. - registry = root / "src/admin/documentation/documents.rs" - if not registry.is_file(): - raise ValueError("Incomplete RustProxy 0.34.2 source tree: missing src/admin/documentation/documents.rs") - embedded_docs = set(re.findall( - r'"(docs/[A-Za-z0-9_.-]+\.md)"', registry.read_text(encoding="utf-8") - )) - for doc_path in sorted(embedded_docs): - if not (root / doc_path).is_file(): - raise ValueError(f"Missing embedded Reader document: {doc_path}; restore the file or remove its Reader registration") - for parent in (root / "src").rglob("*.rs"): - source = parent.read_text(encoding="utf-8") - for relative in re.findall(r'\binclude!\s*\(\s*"([^"\n]+\.rs)"\s*\)', source): - fragment = parent.parent / relative - if not fragment.is_file(): - raise ValueError(f"Missing included Rust source: {fragment.relative_to(root)}") - if fragment.read_text(encoding="utf-8").lstrip().startswith(("//!", "/*!")): - raise ValueError( - f"{fragment.relative_to(root)} starts with an inner doc comment; " - "replace //! with // or /// (Rust E0753)" - ) - text = (root / "src/lib.rs").read_text(encoding="utf-8") - if '#[path = "auth/mod.rs"]' not in text: - raise ValueError("src/lib.rs does not match the expected entry point; extract the complete package, not individual files.") - return messages def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) - parser.add_argument("--repair-known", action="store_true") - args = parser.parse_args() - try: - for line in check(args.root.resolve(), args.repair_known): - print(line, file=sys.stderr) - except (OSError, ValueError) as error: - parser.exit(2, f"Source preflight failed: {error}\n") + root = parser.parse_args().root.resolve() + missing = [ + name + for name in ("Cargo.toml", "build.rs", "src/lib.rs", "src/main.rs") + if not (root / name).is_file() + ] + if missing: + parser.exit(2, f"Source preflight failed: missing {', '.join(missing)}\n") if __name__ == "__main__": diff --git a/src/admin/config_sections.rs b/src/admin/config_sections.rs index af7db16..c70912c 100644 --- a/src/admin/config_sections.rs +++ b/src/admin/config_sections.rs @@ -8,6 +8,7 @@ enum ConfigSection { Transform, Forwarding, Headers, + Policy, Prometheus, Geoip, Administration, @@ -37,6 +38,7 @@ impl ConfigSection { "transform" => Some(Self::Transform), "forwarding" => Some(Self::Forwarding), "headers" => Some(Self::Headers), + "policy" => Some(Self::Policy), "prometheus" => Some(Self::Prometheus), "geoip" => Some(Self::Geoip), "administration" => Some(Self::Administration), @@ -67,6 +69,7 @@ impl ConfigSection { Self::Transform => json!(&config.transform), Self::Forwarding => json!(&config.forwarding), Self::Headers => json!(&config.headers), + Self::Policy => json!(&config.policy), Self::Prometheus => json!(&config.prometheus), Self::Geoip => json!(&config.geoip_updates), Self::Administration => json!(&config.administration), @@ -128,6 +131,10 @@ impl ConfigSection { config.forwarding = serde_json::from_value(value).map_err(|error| invalid_section(name, error))? } + Self::Policy => { + config.policy = + serde_json::from_value(value).map_err(|error| invalid_section(name, error))? + } Self::Headers => { config.headers = serde_json::from_value(value).map_err(|error| invalid_section(name, error))? diff --git a/src/admin/documentation/documents.rs b/src/admin/documentation/documents.rs index 871fddf..d889cae 100644 --- a/src/admin/documentation/documents.rs +++ b/src/admin/documentation/documents.rs @@ -17,6 +17,7 @@ pub(super) static READER_DOCUMENTS: &[(&str, &str, &str)] = &[ reader_doc!("docs/SCREENSHOTS.md", "guides"), reader_doc!("docs/INSTALL.md", "guides"), reader_doc!("docs/CONFIGURATION.md", "guides"), + reader_doc!("docs/POLICY.md", "guides"), reader_doc!("docs/HEADLESS.md", "guides"), reader_doc!("docs/VHOSTS.md", "guides"), reader_doc!("docs/CUSTOM_LOCATIONS.md", "guides"), diff --git a/src/admin/documentation/tests.rs b/src/admin/documentation/tests.rs index 424dd2a..64fb474 100644 --- a/src/admin/documentation/tests.rs +++ b/src/admin/documentation/tests.rs @@ -10,6 +10,7 @@ mod tests { .iter() .any(|doc| doc["path"] == "docs/WEB_SERVER.md")); assert!(documents.iter().any(|doc| doc["path"] == "docs/PHP_FPM.md")); + assert!(documents.iter().any(|doc| doc["path"] == "docs/POLICY.md")); assert!(documents .iter() .any(|doc| doc["path"] == "docs/FEATURES.md")); diff --git a/src/admin/mod.rs b/src/admin/mod.rs index 7a82e30..b7dd03f 100644 --- a/src/admin/mod.rs +++ b/src/admin/mod.rs @@ -13,6 +13,7 @@ include!("file_logs.rs"); include!("file_log_search.rs"); include!("operations.rs"); include!("cache_rules.rs"); +include!("policy.rs"); include!("alerts.rs"); include!("certificate_api.rs"); include!("certificates.rs"); diff --git a/src/admin/openapi.json b/src/admin/openapi.json index 10f23cd..54ef74d 100644 --- a/src/admin/openapi.json +++ b/src/admin/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.0.3", "info": { "title": "RustProxy Administration API", - "version": "0.41.4", + "version": "0.42.0", "description": "Administration API for the active panel origin. Sign in through the panel; the same-origin HttpOnly cookie authenticates all private operations. Mutations also require the exact Origin, X-RustProxy-Request: 1 and a session-bound X-CSRF-Token. Loopback HTTP is the default; Settings can enable HTTPS before using a non-loopback administration bind. This document contains no live configuration or credentials. Object schemas marked extensible are summaries: full configuration validation is authoritative in Rust. The API also permits explicitly scoped GeneralApiBearer tokens on a narrow route allowlist, with RO/RW and source CIDR checks; API-token management and Prometheus-token management are browser-session-only." }, "servers": [ @@ -460,6 +460,9 @@ } ], "nullable": true + }, + "policy": { + "$ref": "#/components/schemas/HttpPolicy" } }, "additionalProperties": false, @@ -971,6 +974,9 @@ "type": "boolean", "default": false, "description": "Explicit, persistent administrator opt-in: allow assigning a named public certificate to hostnames not covered by its DNS SAN. This does not suppress TLS client warnings, validate the certificate less during agent polling, or disable backend TLS verification. Requires a named certificate." + }, + "policy": { + "$ref": "#/components/schemas/HttpPolicy" } }, "additionalProperties": true, @@ -1353,6 +1359,9 @@ "default": 95 } } + }, + "policy": { + "$ref": "#/components/schemas/HttpPolicy" } }, "additionalProperties": false, @@ -1986,12 +1995,29 @@ "type": "object", "description": "Mutually exclusive final public HTTP request outcomes since process start. Requests awaiting response headers are not counted yet; early rejects and cancellations without a final response are OTHER.", "additionalProperties": false, - "required": ["hits", "misses", "bypasses", "other"], + "required": [ + "hits", + "misses", + "bypasses", + "other" + ], "properties": { - "hits": {"type": "integer", "minimum": 0}, - "misses": {"type": "integer", "minimum": 0}, - "bypasses": {"type": "integer", "minimum": 0}, - "other": {"type": "integer", "minimum": 0} + "hits": { + "type": "integer", + "minimum": 0 + }, + "misses": { + "type": "integer", + "minimum": 0 + }, + "bypasses": { + "type": "integer", + "minimum": 0 + }, + "other": { + "type": "integer", + "minimum": 0 + } } }, "Cache": { @@ -3573,6 +3599,9 @@ "nullable": true, "default": null, "description": "Since 0.38.3. Same format as the vhost basic_auth: enabled, realm, require_tls, forward_credentials and users with Argon2id password_hash from POST /api/basic-auth/hash; null = no login." + }, + "policy": { + "$ref": "#/components/schemas/HttpPolicy" } }, "required": [ @@ -7099,7 +7128,14 @@ }, "scope": { "type": "string", - "enum": ["vhost", "redirect", "host404", "unmatched", "access", "error"] + "enum": [ + "vhost", + "redirect", + "host404", + "unmatched", + "access", + "error" + ] }, "site": { "type": "string", @@ -7107,7 +7143,9 @@ }, "domains": { "type": "array", - "items": { "type": "string" }, + "items": { + "type": "string" + }, "description": "Current configured hostnames and aliases for this site, including Docker publications. Empty for shared, unmatched or no longer configured sites. Identical for all rotations." } }, @@ -8881,17 +8919,20 @@ }, "CacheRule": { "type": "object", - "description": "Cache rule (since 0.37.1, extended in 0.38.8). Request rules run in vcl_recv then vcl_hash after return(hash); response rules run before origin cache admission; deliver rules run before sending headers. Vhost rules precede global rules and own their mutated header fields. Later assignments in the same scope take precedence unless a terminal return stops the stage. VCL import is a supported subset and returns warnings for unsupported operations.", + "description": "Cache rule (since 0.37.1, extended in 0.38.8). Request rules run in vcl_recv then vcl_hash after return(hash); response rules run before origin cache admission; deliver rules run before sending headers. Vhost rules precede global rules and own their mutated header fields. Later assignments in the same scope take precedence unless a terminal return stops the stage. VCL import is a supported subset and returns warnings for unsupported operations. Since 0.42.0, each fresh VCL import carries vcl_flow metadata: branch decisions are evaluated once on entry, and later header mutations do not re-evaluate the selected branch. Existing rules without this metadata keep their independent graphical-rule semantics. Keep every imported group complete and contiguous; move, enable, target, duplicate or delete it as one block.", "required": [ "id", "actions" ], "properties": { "id": { - "type": "string" + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,64}$" }, "name": { - "type": "string" + "type": "string", + "maxLength": 96, + "description": "At most 96 UTF-8 bytes, without control characters." }, "enabled": { "type": "boolean", @@ -8918,51 +8959,7 @@ "type": "array", "maxItems": 16, "items": { - "type": "object", - "properties": { - "field": { - "type": "string", - "enum": [ - "host", - "url", - "path", - "extension", - "method", - "query", - "header", - "cookie", - "client_ip", - "status", - "content_type", - "response_header" - ] - }, - "name": { - "type": "string" - }, - "operator": { - "type": "string", - "enum": [ - "equals", - "prefix", - "suffix", - "contains", - "glob", - "regex", - "exists", - "cidr" - ] - }, - "values": { - "type": "array", - "items": { - "type": "string" - } - }, - "negate": { - "type": "boolean" - } - } + "$ref": "#/components/schemas/CacheRuleCondition" } }, "actions": { @@ -8971,10 +8968,10 @@ "maxItems": 16, "items": { "type": "object", - "description": "type: pass (explicit VCL return(pass); never relaxed), cookie_pass (Cookie/session guard, VCL return(cookie_pass) RustProxy extension; needs a non-negated Cookie condition; may be relaxed only for public static assets when static_ignore_cookies is on and no other rule bypasses the request), lookup (VCL return(hash), Cookie exception in Varnish-compatible mode), strip_cookies{keep}, remove_named_cookies{names} (exact names or trailing-* prefixes; remaining cookies, including application sessions, survive), strip_query{params,keep_only}, hash_header{name}, hash_cookie{name}, set_request_header{name,value}, remove_request_header{name} (request; protected auth/cache/framing headers cannot be changed); ttl{seconds}, grace{seconds}, no_store, allow_store (reverses rule no_store only; origin restrictions remain), ignore_cache_control, strip_set_cookie, set_backend_header{name,value}, remove_backend_header{name} (response, applied before cacheability and forwarded headers); set_header{name,value}, default_header{name,value}, remove_header{name} (deliver, including cache-disabled responses).", + "description": "type: pass (explicit VCL return(pass); never relaxed), cookie_pass (Cookie/session guard, VCL return(cookie_pass) RustProxy extension; needs a non-negated Cookie condition, or an imported branch guaranteed to require Cookie; may be relaxed only for public static assets when static_ignore_cookies is on and no other rule bypasses the request), lookup (VCL return(hash), Cookie exception in Varnish-compatible mode), strip_cookies{keep}, remove_named_cookies{names} (exact names or trailing-* prefixes; remaining cookies, including application sessions, survive), strip_query{params,keep_only}, hash_header{name}, hash_cookie{name}, set_request_header{name,value}, remove_request_header{name} (request; protected auth/cache/framing headers cannot be changed); ttl{seconds}, grace{seconds}, no_store, allow_store (reverses rule no_store only; origin restrictions remain), ignore_cache_control, strip_set_cookie, set_backend_header{name,value}, remove_backend_header{name} (response, applied before cacheability and forwarded headers); set_header{name,value}, default_header{name,value}, remove_header{name} (deliver, including cache-disabled responses).", "additionalProperties": true }, - "description": "Zero actions allowed only with stop=true (terminal return)." + "description": "Zero actions are allowed with stop=true (terminal return), or on an imported VCL branch-entry marker with nonempty vcl_flow.branches and stop=false. Other rows need 1-16 actions." }, "stop": { "type": "boolean" @@ -8990,8 +8987,12 @@ "type": "boolean", "default": false, "description": "Run this request-stage rule in vcl_hash, after vcl_recv. Imported VCL sets this automatically." + }, + "vcl_flow": { + "$ref": "#/components/schemas/CacheVclFlow" } - } + }, + "additionalProperties": false }, "CacheRuleTestRequest": { "type": "object", @@ -9251,6 +9252,1082 @@ "description": "Case-insensitive comparison for header, cookie and query values. Host, method and country always compare case-insensitively." } } + }, + "HttpPolicyStage": { + "type": "string", + "enum": [ + "pre_route", + "request", + "backend_request", + "backend_response", + "deliver", + "after_response" + ], + "description": "Explicit execution stage. Location policies cannot use pre_route. Legacy VCL stages retain their ordering and precedence." + }, + "HttpPolicyCondition": { + "oneOf": [ + { + "type": "object", + "additionalProperties": false, + "properties": { + "all": { + "type": "array", + "items": { + "$ref": "#/components/schemas/HttpPolicyCondition" + }, + "maxItems": 32 + } + }, + "required": [ + "all" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "any": { + "type": "array", + "items": { + "$ref": "#/components/schemas/HttpPolicyCondition" + }, + "maxItems": 32 + } + }, + "required": [ + "any" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "not": { + "$ref": "#/components/schemas/HttpPolicyCondition" + } + }, + "required": [ + "not" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "acl": { + "type": "string" + } + }, + "required": [ + "acl" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "fetch": { + "type": "string" + }, + "operator": { + "type": "string", + "enum": [ + "equals", + "contains", + "prefix", + "suffix", + "regex", + "exists", + "cidr", + "eq", + "ne", + "gt", + "ge", + "lt", + "le" + ] + }, + "values": { + "type": "array", + "items": { + "type": "string" + }, + "maxItems": 64 + }, + "ignore_case": { + "type": "boolean", + "default": false + } + }, + "required": [ + "fetch", + "operator" + ] + } + ] + }, + "HttpPolicyAction": { + "oneOf": [ + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "set_header" + ] + }, + "name": { + "type": "string", + "maxLength": 128 + }, + "value": { + "type": "string", + "maxLength": 8192 + } + }, + "required": [ + "type", + "name", + "value" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "append_header" + ] + }, + "name": { + "type": "string", + "maxLength": 128 + }, + "value": { + "type": "string", + "maxLength": 8192 + } + }, + "required": [ + "type", + "name", + "value" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "set_if_missing" + ] + }, + "name": { + "type": "string", + "maxLength": 128 + }, + "value": { + "type": "string", + "maxLength": 8192 + } + }, + "required": [ + "type", + "name", + "value" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "merge_header" + ] + }, + "name": { + "type": "string", + "maxLength": 128 + }, + "value": { + "type": "string", + "maxLength": 8192 + } + }, + "required": [ + "type", + "name", + "value" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "remove_value" + ] + }, + "name": { + "type": "string", + "maxLength": 128 + }, + "value": { + "type": "string", + "maxLength": 8192 + } + }, + "required": [ + "type", + "name", + "value" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "remove_header" + ] + }, + "name": { + "type": "string", + "maxLength": 128 + } + }, + "required": [ + "type", + "name" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "normalize_header" + ] + }, + "name": { + "type": "string", + "maxLength": 128 + } + }, + "required": [ + "type", + "name" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "hash_header" + ] + }, + "name": { + "type": "string", + "maxLength": 128 + } + }, + "required": [ + "type", + "name" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "replace_header" + ] + }, + "name": { + "type": "string" + }, + "pattern": { + "type": "string" + }, + "replacement": { + "type": "string" + } + }, + "required": [ + "type", + "name", + "pattern", + "replacement" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "set_var" + ] + }, + "name": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": [ + "type", + "name", + "value" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "unset_var" + ] + }, + "name": { + "type": "string" + } + }, + "required": [ + "type", + "name" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "set_path" + ] + }, + "value": { + "type": "string" + } + }, + "required": [ + "type", + "value" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "set_query" + ] + }, + "value": { + "type": "string" + } + }, + "required": [ + "type", + "value" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "use_backend" + ] + }, + "id": { + "type": "string" + } + }, + "required": [ + "type", + "id" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "deny" + ] + }, + "status": { + "type": "integer", + "default": 403 + } + }, + "required": [ + "type" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "return" + ] + }, + "status": { + "type": "integer" + }, + "body": { + "type": "string", + "default": "" + } + }, + "required": [ + "type", + "status" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "redirect" + ] + }, + "status": { + "type": "integer", + "default": 302 + }, + "location": { + "type": "string" + } + }, + "required": [ + "type", + "location" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "pass" + ] + } + }, + "required": [ + "type" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "lookup" + ] + } + }, + "required": [ + "type" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "no_store" + ] + } + }, + "required": [ + "type" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "disable_compression" + ] + } + }, + "required": [ + "type" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "stop" + ] + } + }, + "required": [ + "type" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "set_ttl" + ] + }, + "seconds": { + "type": "integer", + "minimum": 0, + "maximum": 31536000 + } + }, + "required": [ + "type", + "seconds" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "set_grace" + ] + }, + "seconds": { + "type": "integer", + "minimum": 0, + "maximum": 31536000 + } + }, + "required": [ + "type", + "seconds" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "replace_value" + ] + }, + "name": { + "type": "string" + }, + "pattern": { + "type": "string" + }, + "replacement": { + "type": "string" + } + }, + "required": [ + "type", + "name", + "pattern", + "replacement" + ] + } + ], + "description": "Allowed actions depend on the stage. Protected transport, identity and authentication headers cannot be changed. Final Vary edits must preserve existing dimensions." + }, + "HttpPolicyRule": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string", + "maxLength": 128 + }, + "name": { + "type": "string", + "maxLength": 256 + }, + "enabled": { + "type": "boolean", + "default": true + }, + "stage": { + "$ref": "#/components/schemas/HttpPolicyStage" + }, + "when": { + "$ref": "#/components/schemas/HttpPolicyCondition" + }, + "actions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/HttpPolicyAction" + }, + "minItems": 1, + "maxItems": 16 + }, + "stop": { + "type": "boolean", + "default": false + } + }, + "required": [ + "id", + "actions" + ] + }, + "HttpPolicyMap": { + "type": "object", + "additionalProperties": false, + "properties": { + "kind": { + "type": "string", + "enum": [ + "exact", + "prefix", + "regex", + "ip" + ], + "default": "exact" + }, + "entries": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "key": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": [ + "key", + "value" + ] + } + }, + "default": { + "type": "string", + "nullable": true + }, + "ignore_case": { + "type": "boolean", + "default": false + } + } + }, + "HttpPolicy": { + "type": "object", + "additionalProperties": false, + "properties": { + "acls": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/HttpPolicyCondition" + } + }, + "maps": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/HttpPolicyMap" + } + }, + "rules": { + "type": "array", + "items": { + "$ref": "#/components/schemas/HttpPolicyRule" + }, + "maxItems": 128 + } + }, + "description": "Optional compiled HTTP policies; defaults empty. New scopes execute Global, Vhost, Location. Existing VCL and Custom Headers are not converted or reordered." + }, + "HttpPolicyHeader": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": [ + "name", + "value" + ] + }, + "HttpPolicyTestRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "policy": { + "$ref": "#/components/schemas/HttpPolicy" + }, + "stage": { + "$ref": "#/components/schemas/HttpPolicyStage" + }, + "request": { + "type": "object", + "additionalProperties": false, + "properties": { + "method": { + "type": "string", + "default": "GET" + }, + "host": { + "type": "string", + "default": "example.test" + }, + "path": { + "type": "string" + }, + "query": { + "type": "string", + "nullable": true + }, + "headers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/HttpPolicyHeader" + }, + "maxItems": 128 + }, + "client_ip": { + "type": "string", + "nullable": true + }, + "country": { + "type": "string", + "nullable": true + }, + "tls": { + "type": "boolean", + "default": false + } + }, + "required": [ + "path" + ] + }, + "response": { + "type": "object", + "additionalProperties": false, + "properties": { + "status": { + "type": "integer", + "minimum": 100, + "maximum": 599 + }, + "headers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/HttpPolicyHeader" + }, + "maxItems": 128 + } + }, + "required": [ + "status" + ] + }, + "variables": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "cache_status": { + "type": "string", + "nullable": true + }, + "srv_id": { + "type": "string", + "nullable": true + }, + "srv_url": { + "type": "string", + "nullable": true + }, + "backend_time": { + "type": "string", + "nullable": true + }, + "location": { + "type": "string", + "nullable": true + }, + "vhost": { + "type": "string", + "nullable": true + }, + "req_id": { + "type": "string", + "nullable": true + }, + "lb_algorithm": { + "type": "string", + "nullable": true + }, + "hash_key": { + "type": "string", + "nullable": true + } + }, + "required": [ + "policy", + "stage", + "request" + ] + }, + "HttpPolicyImportRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "source": { + "type": "string", + "maxLength": 262144 + } + }, + "required": [ + "source" + ] + }, + "CacheRuleCondition": { + "type": "object", + "properties": { + "field": { + "type": "string", + "enum": [ + "host", + "url", + "path", + "extension", + "method", + "query", + "header", + "cookie", + "client_ip", + "status", + "content_type", + "response_header" + ] + }, + "name": { + "type": "string", + "nullable": true + }, + "operator": { + "type": "string", + "enum": [ + "equals", + "prefix", + "suffix", + "contains", + "glob", + "regex", + "exists", + "cidr" + ] + }, + "values": { + "type": "array", + "items": { + "type": "string", + "maxLength": 512, + "description": "At most 512 UTF-8 bytes, without control characters." + }, + "maxItems": 64, + "default": [] + }, + "negate": { + "type": "boolean", + "default": false + } + }, + "additionalProperties": false, + "required": [ + "field", + "operator" + ] + }, + "CacheVclFlow": { + "type": "object", + "additionalProperties": false, + "description": "Versioned structure of one VCL import. A group has count contiguous rows in index order 0..count-1, with the same enabled state and vhosts. Every row has match=all and conditions=[]. A branch-entry marker has nonempty branches, actions=[] and stop=false; an action row has no branches and needs actions or stop=true. Guards reference earlier, still-open markers in the same stage/hash_stage; each referenced marker has exactly the preceding guard ancestry. Sibling branches must remain in order and cannot be re-entered. The group contains at most 2048 condition nodes. Complete-group operations preserve semantics; rule IDs and display names may change independently.", + "required": [ + "version", + "group", + "index", + "count" + ], + "properties": { + "version": { + "type": "integer", + "enum": [ + 1 + ] + }, + "group": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,64}$", + "description": "Unique within this configured rules array. Fresh imports use vcl- followed by 32 random hexadecimal characters; duplicates require a new group ID." + }, + "index": { + "type": "integer", + "minimum": 0, + "maximum": 127 + }, + "count": { + "type": "integer", + "minimum": 1, + "maximum": 128 + }, + "guards": { + "type": "array", + "maxItems": 16, + "default": [], + "items": { + "$ref": "#/components/schemas/CacheVclGuard" + } + }, + "branches": { + "type": "array", + "maxItems": 16, + "default": [], + "items": { + "$ref": "#/components/schemas/CacheVclBranch" + } + } + }, + "nullable": true + }, + "CacheVclGuard": { + "type": "object", + "additionalProperties": false, + "required": [ + "entry", + "branch" + ], + "properties": { + "entry": { + "type": "integer", + "minimum": 0, + "maximum": 127, + "description": "Index of an earlier branch-entry marker in this group." + }, + "branch": { + "type": "integer", + "minimum": 0, + "maximum": 15, + "description": "Selected branch index of that marker." + } + } + }, + "CacheVclBranch": { + "type": "object", + "additionalProperties": false, + "required": [ + "any" + ], + "description": "OR of AND clauses. The first matching branch is selected when its marker runs. Only the final branch may be unconditional, represented exactly by any:[[]] for else.", + "properties": { + "any": { + "type": "array", + "minItems": 1, + "maxItems": 128, + "items": { + "type": "array", + "maxItems": 16, + "items": { + "$ref": "#/components/schemas/CacheRuleCondition" + } + } + } + } + }, + "CacheVclImportResponse": { + "type": "object", + "additionalProperties": false, + "required": [ + "rules", + "warnings" + ], + "properties": { + "rules": { + "type": "array", + "maxItems": 128, + "items": { + "$ref": "#/components/schemas/CacheRule" + } + }, + "warnings": { + "type": "array", + "items": { + "type": "string" + } + } + } } } }, @@ -12300,7 +13377,7 @@ } } }, - "description": "Replaces the named section in one revision-checked, validated, durable configuration update; unrelated sections are preserved. This is a full section replacement, not a merge/patch. Use GET /api/config/{section} to read the exact value shape before PUT. logging requires {logging, error_log}; response requires {server_header, diagnostic_headers, compression}; global-security requires one GlobalSecurity object containing user_agent_blocking. The legacy standalone user-agent-blocking section and standalone error_log are not writable. Global revision conflicts return 409, even for writes to different sections; retry after fetching a new revision. PUT returns the complete updated {revision, config} envelope so the UI can refresh all sections. Origin-dependent cache policy changes still invalidate incompatible cached objects; unrelated logging/listener/administration updates do not purge the cache. See x-rustproxy-section-fields for canonical JSON field mapping.", + "description": "Replaces the named section in one revision-checked, validated, durable configuration update; unrelated sections are preserved. This is a full section replacement, not a merge/patch. Use GET /api/config/{section} to read the exact value shape before PUT. logging requires {logging, error_log}; response requires {server_header, diagnostic_headers, compression}; global-security requires one GlobalSecurity object containing user_agent_blocking. The legacy standalone user-agent-blocking section and standalone error_log are not writable. Global revision conflicts return 409, even for writes to different sections; retry after fetching a new revision. PUT returns the complete updated {revision, config} envelope so the UI can refresh all sections. Origin-dependent cache policy changes still invalidate incompatible cached objects; unrelated logging/listener/administration updates do not purge the cache. See x-rustproxy-section-fields for canonical JSON field mapping. The policy section stores HttpPolicy settings.", "parameters": [ { "name": "section", @@ -12332,7 +13409,8 @@ "global-security", "web-services", "php-fpm-profiles", - "alerts" + "alerts", + "policy" ] }, "description": "Configuration section to replace." @@ -12457,7 +13535,7 @@ }, "get": { "summary": "Read one revisioned configuration section", - "description": "Returns {revision, section, value}. The value is the complete canonical section payload accepted by PUT /api/config/{section}, not a partial patch. logging groups logging + error_log, response groups the three response controls, and global-security contains user_agent_blocking and all other global security rules. No storage paths are returned by this endpoint. See x-rustproxy-section-fields for the exact Config property mapping of all supported names.", + "description": "Returns {revision, section, value}. The value is the complete canonical section payload accepted by PUT /api/config/{section}, not a partial patch. logging groups logging + error_log, response groups the three response controls, and global-security contains user_agent_blocking and all other global security rules. No storage paths are returned by this endpoint. See x-rustproxy-section-fields for the exact Config property mapping of all supported names. The policy section stores HttpPolicy settings.", "tags": [ "Configuration" ], @@ -12493,7 +13571,8 @@ "global-security", "web-services", "php-fpm-profiles", - "alerts" + "alerts", + "policy" ] }, "description": "Exactly one supported configuration section." @@ -16525,7 +17604,7 @@ "Cache" ], "operationId": "post_api_cache_rules_import_vcl", - "description": "Parses vcl_recv/vcl_hash, vcl_backend_response/vcl_fetch and vcl_deliver and converts supported statements into cache rules. Unsupported statements are returned as warnings; nothing is saved.", + "description": "Parses vcl_recv/vcl_hash, vcl_backend_response/vcl_fetch and vcl_deliver and converts supported statements into cache rules. Unsupported statements are returned as warnings; nothing is saved. Since 0.42.0, every fresh import is returned as a complete vcl_flow group preserving if/elsif/else selection and nested branch execution. Preserve all returned rows and their metadata together. Warnings still require review before accepting a partial import; no rules are saved by this endpoint. JSON is the lossless export format for these groups.", "parameters": [ { "name": "Origin", @@ -16569,6 +17648,397 @@ "responses": { "200": { "description": "Imported rules and warnings", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CacheVclImportResponse" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Authentication required or revoked", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Host, origin or CSRF validation failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request exceeds the endpoint body limit", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Configuration/input validation failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Bounded worker/session/rate limit", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Control-plane storage/worker unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/api/policy/test": { + "post": { + "summary": "Simulate one HTTP policy stage", + "tags": [ + "HTTP Policy" + ], + "operationId": "post_api_policy_test", + "description": "Runs the same compiled engine as live traffic with duplicate-preserving header arrays. Returns rewritten headers, variables, effects and per-rule trace. Does not simulate VCL, inherited scopes, backend traffic or activate configuration.", + "parameters": [ + { + "name": "Origin", + "in": "header", + "required": true, + "schema": { + "type": "string" + }, + "description": "Exact http://HOST:ADMIN_PORT. Set automatically by same-origin browser POST/PUT/DELETE." + }, + { + "name": "X-RustProxy-Request", + "in": "header", + "required": true, + "schema": { + "type": "string", + "enum": [ + "1" + ] + } + }, + { + "name": "X-CSRF-Token", + "in": "header", + "required": true, + "schema": { + "type": "string" + }, + "description": "Session-bound CSRF token." + } + ], + "security": [ + { + "AdminSession": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HttpPolicyTestRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Simulation result", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Authentication required or revoked", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Host, origin or CSRF validation failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request exceeds the endpoint body limit", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Configuration/input validation failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Bounded worker/session/rate limit", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Control-plane storage/worker unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/api/policy/import-haproxy": { + "post": { + "summary": "Import supported HAProxy HTTP rules", + "tags": [ + "HTTP Policy" + ], + "operationId": "post_api_policy_import_haproxy", + "description": "Converts supported ACL and HTTP action directives to an unsaved policy. Invalid or unsupported directives reject the entire import with line context; no partial activation. This is an explicitly supported subset, not a full HAProxy configuration parser.", + "parameters": [ + { + "name": "Origin", + "in": "header", + "required": true, + "schema": { + "type": "string" + }, + "description": "Exact http://HOST:ADMIN_PORT. Set automatically by same-origin browser POST/PUT/DELETE." + }, + { + "name": "X-RustProxy-Request", + "in": "header", + "required": true, + "schema": { + "type": "string", + "enum": [ + "1" + ] + } + }, + { + "name": "X-CSRF-Token", + "in": "header", + "required": true, + "schema": { + "type": "string" + }, + "description": "Session-bound CSRF token." + } + ], + "security": [ + { + "AdminSession": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HttpPolicyImportRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Simulation result", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": false, + "properties": { + "policy": { + "$ref": "#/components/schemas/HttpPolicy" + }, + "warnings": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "policy", + "warnings" + ] + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Authentication required or revoked", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Host, origin or CSRF validation failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request exceeds the endpoint body limit", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Configuration/input validation failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Bounded worker/session/rate limit", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Control-plane storage/worker unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/api/policy/stats": { + "get": { + "summary": "Read live HTTP policy counters", + "tags": [ + "HTTP Policy" + ], + "operationId": "get_api_policy_stats", + "description": "Per-rule match and runtime action error counters for the current compiled configuration. Draft tests do not increment counters; recompilation resets them. Does not expose sampled header values or variables.", + "parameters": [], + "security": [ + { + "AdminSession": [] + } + ], + "responses": { + "200": { + "description": "Simulation result", "content": { "application/json": { "schema": { @@ -16652,5 +18122,10 @@ } } }, - "tags": [] -} \ No newline at end of file + "tags": [ + { + "name": "HTTP Policy", + "description": "Compiled HTTP policies, HAProxy subset import and deterministic stage tests." + } + ] +} diff --git a/src/admin/policy.rs b/src/admin/policy.rs new file mode 100644 index 0000000..6aeb29a --- /dev/null +++ b/src/admin/policy.rs @@ -0,0 +1,281 @@ +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct PolicyImportInput { + source: String, +} + +async fn policy_import_haproxy( + Json(input): Json, +) -> Result, ApiError> { + crate::policy::import_haproxy(&input.source) + .map(Json) + .map_err(|error| ApiError(StatusCode::UNPROCESSABLE_ENTITY, format!("{error:#}"))) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct PolicyTestHeader { + name: String, + value: String, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct PolicyTestRequest { + #[serde(default = "cache_rule_test_method")] + method: String, + #[serde(default)] + host: String, + path: String, + #[serde(default)] + query: Option, + #[serde(default)] + headers: Vec, + #[serde(default)] + client_ip: Option, + #[serde(default)] + country: Option, + #[serde(default)] + tls: bool, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct PolicyTestResponse { + status: u16, + #[serde(default)] + headers: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct PolicyTestInput { + policy: crate::policy::Settings, + stage: crate::policy::Stage, + request: PolicyTestRequest, + #[serde(default)] + response: Option, + #[serde(default)] + variables: std::collections::BTreeMap, + #[serde(default)] + cache_status: Option, + #[serde(default)] + srv_id: Option, + #[serde(default)] + srv_url: Option, + #[serde(default)] + backend_time: Option, + #[serde(default)] + location: Option, + #[serde(default)] + vhost: Option, + #[serde(default)] + req_id: Option, + #[serde(default)] + lb_algorithm: Option, + #[serde(default)] + hash_key: Option, +} + +fn policy_test_error(message: impl Into) -> ApiError { + ApiError(StatusCode::UNPROCESSABLE_ENTITY, message.into()) +} + +fn policy_test_headers(input: Vec) -> Result { + if input.len() > 128 + || input + .iter() + .map(|header| header.name.len() + header.value.len()) + .sum::() + > 64 * 1024 + { + return Err(policy_test_error("test headers exceed 128 fields / 64 KiB")); + } + let mut headers = http::HeaderMap::new(); + for item in input { + let name = http::HeaderName::from_bytes(item.name.as_bytes()) + .map_err(|_| policy_test_error("invalid test header name"))?; + let value = http::HeaderValue::from_str(&item.value) + .map_err(|_| policy_test_error("invalid test header value"))?; + headers.append(name, value); + } + Ok(headers) +} + +fn policy_headers_json(headers: &http::HeaderMap) -> Vec { + headers + .iter() + .map(|(name, value)| { + json!({ + "name": name.as_str(), "value": value.to_str().unwrap_or("[non-text header]"), + }) + }) + .collect() +} + +fn evaluate_policy_test(input: PolicyTestInput) -> Result { + let policy = input + .policy + .compile() + .map_err(|error| policy_test_error(format!("{error:#}")))?; + let request = input.request; + if request.path.len() > 8192 + || request + .query + .as_ref() + .is_some_and(|query| query.len() > 8192) + || !request.path.starts_with('/') + || request.path.starts_with("//") + || request.path.contains(['?', '#']) + || crate::acl::routing_path_view(&request.path).is_err() + { + return Err(policy_test_error("invalid test request path")); + } + let method = http::Method::from_bytes(request.method.as_bytes()) + .map_err(|_| policy_test_error("invalid test method"))?; + let host = if request.host.is_empty() { + "example.test".to_owned() + } else { + crate::config::request_host(&request.host) + .map_err(|_| policy_test_error("invalid test hostname"))? + }; + let client_ip = request + .client_ip + .as_deref() + .filter(|value| !value.is_empty()) + .map(|value| value.parse()) + .transpose() + .map_err(|_| policy_test_error("invalid test client IP"))?; + if request.country.as_ref().is_some_and(|value| { + value.len() != 2 || !value.bytes().all(|byte| byte.is_ascii_alphabetic()) + }) { + return Err(policy_test_error("test country must be a two-letter code")); + } + if input.variables.len() > 64 + || input.variables.iter().any(|(name, value)| { + name.len() > 128 + || !name.starts_with("txn.") + || value.len() > 8192 + || value.chars().any(char::is_control) + }) + || input + .variables + .iter() + .map(|(name, value)| name.len() + value.len()) + .sum::() + > 64 * 1024 + { + return Err(policy_test_error( + "invalid or oversized transaction variables", + )); + } + for value in [ + &input.cache_status, + &input.srv_id, + &input.srv_url, + &input.backend_time, + &input.location, + &input.vhost, + &input.req_id, + &input.lb_algorithm, + &input.hash_key, + ] + .into_iter() + .flatten() + { + if value.len() > 8192 || value.chars().any(char::is_control) { + return Err(policy_test_error("invalid or oversized test metadata")); + } + } + let mut context = crate::policy::Context { + request_headers: policy_test_headers(request.headers)?, + method: method.as_str().to_owned(), + path: request.path, + query: request.query, + host, + client_ip, + country: request.country.map(|value| value.to_ascii_uppercase()), + tls: request.tls, + variables: input.variables, + cache_status: input.cache_status, + srv_id: input.srv_id, + srv_url: input.srv_url, + backend_time: input.backend_time, + location: input.location, + vhost: input.vhost, + req_id: input.req_id, + lb_algorithm: input.lb_algorithm, + hash_key: input.hash_key, + ..Default::default() + }; + if let Some(response) = input.response { + if !(100..=599).contains(&response.status) { + return Err(policy_test_error("invalid test response status")); + } + context.status = Some(response.status); + context.response_headers = policy_test_headers(response.headers)?; + } else if input.stage.response() { + return Err(policy_test_error( + "a response is required to test a response stage", + )); + } + let outcome = policy.apply(input.stage, &mut context, true); + Ok(json!({ + "request": {"method": context.method, "host": context.host, "path": context.path, + "query": context.query, "headers": policy_headers_json(&context.request_headers)}, + "response": context.status.map(|status| json!({"status":status,"headers":policy_headers_json(&context.response_headers)})), + "variables": context.variables, + "trace": outcome.trace, "terminal": outcome.terminal, "backend": outcome.backend, + "cache": outcome.cache, "disable_compression": outcome.disable_compression, "stopped": outcome.stopped, + "requires_private_response": policy.requires_private_response(), + "scope": "single_policy_stage", + })) +} + +async fn policy_test(Json(input): Json) -> Result, ApiError> { + evaluate_policy_test(input).map(Json) +} + +async fn policy_stats(State(state): State>) -> Json { + Json(state.config.load_full().http_policy_statistics()) +} + +#[cfg(test)] +mod policy_api_tests { + use super::*; + + #[test] + fn tester_keeps_duplicate_header_fields_and_uses_runtime_engine() { + let input = serde_json::from_value(json!({ + "policy": {"rules":[{"id":"vary","stage":"after_response", "when":{ + "fetch":"res.fhdr_cnt(Vary)","operator":"eq","values":["2"]}, + "actions":[{"type":"normalize_header","name":"Vary"}]}]}, + "stage":"after_response", "request":{"path":"/"}, + "response":{"status":200,"headers":[{"name":"Vary","value":"Accept-Encoding"}, + {"name":"Vary","value":"Accept, Accept-Encoding"}]} + })) + .unwrap(); + let result = evaluate_policy_test(input).unwrap(); + assert_eq!(result["trace"][0]["matched"], true); + let headers = result["response"]["headers"].as_array().unwrap(); + assert_eq!(headers.len(), 1); + assert!(headers[0]["value"] + .as_str() + .unwrap() + .to_ascii_lowercase() + .contains("accept")); + } + + #[test] + fn tester_rejects_missing_response_and_unknown_configuration() { + let input = serde_json::from_value( + json!({"policy":{},"stage":"after_response","request":{"path":"/"}}), + ) + .unwrap(); + assert!(evaluate_policy_test(input).is_err()); + assert!(serde_json::from_value::( + json!({"policy":{"unknown":1},"stage":"request","request":{"path":"/"}}) + ) + .is_err()); + } +} diff --git a/src/admin/policy_access_tests.rs b/src/admin/policy_access_tests.rs new file mode 100644 index 0000000..854f88e --- /dev/null +++ b/src/admin/policy_access_tests.rs @@ -0,0 +1,95 @@ +#[tokio::test] +async fn http_policy_endpoints_require_session_and_csrf_and_never_save_drafts() { + let (router, store, _dir, secret, csrf) = fixture().await; + let cookie = format!("{}={secret}", auth::COOKIE_NAME); + for (path, body) in [ + ( + "/api/policy/import-haproxy", + json!({"source":"http-after-response set-header X-Test yes"}), + ), + ( + "/api/policy/test", + json!({"policy":{},"stage":"request","request":{"path":"/"}}), + ), + ] { + let send = |cookie_value: Option<&str>, csrf_value: Option<&str>| { + let mut builder = request(path) + .method("POST") + .header("origin", "http://127.0.0.1:9090") + .header("x-rustproxy-request", "1") + .header("content-type", "application/json"); + if let Some(cookie) = cookie_value { + builder = builder.header("cookie", cookie); + } + if let Some(csrf) = csrf_value { + builder = builder.header("x-csrf-token", csrf); + } + builder.body(Body::from(body.to_string())).unwrap() + }; + let response = router.clone().oneshot(send(None, None)).await.unwrap(); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED, "{path}"); + let response = router + .clone() + .oneshot(send(Some(&cookie), None)) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::FORBIDDEN, "{path}"); + let response = router + .clone() + .oneshot(send(Some(&cookie), Some(&csrf))) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK, "{path}"); + assert!(!general_api_token_allowed(&Method::POST, path, "rw")); + } + let response = router + .clone() + .oneshot( + request("/api/config/policy") + .header("cookie", &cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let current = json_body(response).await; + assert!(current.to_string().contains("\"rules\":[]"), "{current}"); + let stats = router + .clone() + .oneshot(request("/api/policy/stats").body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(stats.status(), StatusCode::UNAUTHORIZED); + let stats = router + .clone() + .oneshot( + request("/api/policy/stats") + .header("cookie", &cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(stats.status(), StatusCode::OK); + assert!(json_body(stats).await["scopes"].is_array()); + store.close().await; +} + +#[test] +fn http_policy_openapi_matches_models_and_private_endpoints() { + let schema: Value = serde_json::from_str(include_str!("openapi.json")).unwrap(); + for path in ["/api/policy/import-haproxy", "/api/policy/test"] { + assert_eq!( + schema["paths"][path]["post"]["security"], + json!([{"AdminSession":[]}]) + ); + } + for name in ["Config", "Vhost", "DockerAssignment"] { + assert_eq!( + schema["components"]["schemas"][name]["properties"]["policy"]["$ref"], + "#/components/schemas/HttpPolicy" + ); + } + assert_eq!(schema["info"]["version"], env!("CARGO_PKG_VERSION")); +} diff --git a/src/admin/router.rs b/src/admin/router.rs index f5f9206..88e6190 100644 --- a/src/admin/router.rs +++ b/src/admin/router.rs @@ -93,6 +93,7 @@ fn admin_app_javascript() -> &'static str { include_str!("web/integrations.js"), include_str!("web/acl-picker.js"), include_str!("web/cache-rules.js"), + include_str!("web/policy.js"), admin_vhosts_javascript(), include_str!("web/web-server-profiles.js"), include_str!("web/web-server.js"), @@ -270,6 +271,15 @@ pub fn router(state: Arc) -> Router { "/api/cache/rules/import-vcl", post(cache_rules_import_vcl).layer(DefaultBodyLimit::max(300 * 1024)), ) + .route( + "/api/policy/import-haproxy", + post(policy_import_haproxy).layer(DefaultBodyLimit::max(300 * 1024)), + ) + .route( + "/api/policy/test", + post(policy_test).layer(DefaultBodyLimit::max(300 * 1024)), + ) + .route("/api/policy/stats", get(policy_stats)) .route("/api/cache/bans/{id}", delete(cache_ban_delete)) .route("/api/tunnels", get(active_tunnels)) .route( diff --git a/src/admin/tests.rs b/src/admin/tests.rs index 65e48a2..2fff8ae 100644 --- a/src/admin/tests.rs +++ b/src/admin/tests.rs @@ -4793,4 +4793,5 @@ mod tests { include!("certificate_inspection_tests.rs"); include!("preferences_tests.rs"); + include!("policy_access_tests.rs"); } diff --git a/src/admin/web/app/settings.js b/src/admin/web/app/settings.js index 89039e3..1f899c0 100644 --- a/src/admin/web/app/settings.js +++ b/src/admin/web/app/settings.js @@ -1,4 +1,5 @@ let cacheRulesEditor = null, cacheRulesRendered = ""; +let globalPolicyEditor = null, globalPolicyRendered = ""; function renderSettings() { if (!envelope) return; const config = envelope.config; window.rustProxySettings?.render(); if (!settingsDirty.has("listeners-form")) window.rustProxyIntegrations?.renderListeners(); @@ -83,6 +84,14 @@ function renderSettings() { $("error-log-status").textContent = errorSink ? `${t("loggingQueue")}: ${fmt(errorSink.queue_dropped)} ${t("loggingDropped")} / ${fmt(errorSink.written)} ${t("loggingSent")} / ${fmt(errorSink.errors)} ${t("errors")} · ${t("loggingCapacity")}: ${fmt(errorSink.queue_capacity)}` : ""; if (!settingsDirty.has("forwarding-form")) { $("trusted-proxies").value = (config.forwarding?.trusted_proxies || []).join("\n"); $("trusted-proto").checked = !!config.forwarding?.trust_forwarded_proto; } if (!settingsDirty.has("headers-form")) { for (const direction of ["request", "response"]) renderHeaderRules(direction, config.headers?.[direction] || []); } + if (!settingsDirty.has("policy-form") && window.rustProxyPolicy) { + const policyJson = JSON.stringify(config.policy || {}); + if (!globalPolicyEditor || policyJson !== globalPolicyRendered) { + globalPolicyEditor = window.rustProxyPolicy.create({ value: config.policy || {}, scope: "global", onChange: () => setSettingsDirty("policy-form") }); + globalPolicyRendered = policyJson; + $("global-policy-rules-root")?.replaceChildren(globalPolicyEditor.node); + } + } const global = config.global_security || {}; if (!settingsDirty.has("global-security-form")) { const country = global.country_access || {}, methods = global.method_policy || {}, content = global.content_type_policy || {}, rate = global.rate_limit || {}; @@ -471,6 +480,7 @@ bindSettingsForm("error-log-form", next => { }, "logging", selectLoggingSection); bindSettingsForm("forwarding-form", next => { next.forwarding = { trusted_proxies: $("trusted-proxies").value.split(/[\n,]/).map(s => s.trim()).filter(Boolean), trust_forwarded_proto: $("trusted-proto").checked }; }, "forwarding"); bindSettingsForm("headers-form", next => { next.headers = { request: collectHeaderRules("request"), response: collectHeaderRules("response") }; }, "headers"); +bindSettingsForm("policy-form", next => { next.policy = globalPolicyEditor ? globalPolicyEditor.read() : (next.policy || {}); }, "policy"); $("log-format-preset").addEventListener("change", event => applyLoggingPreset(event.target.value)); $("error-log-enabled").addEventListener("change", syncErrorLogMode); $("log-format-open").addEventListener("click", openLoggingBuilder); diff --git a/src/admin/web/cache-rules.js b/src/admin/web/cache-rules.js index c4a1c0b..dd2f2ff 100644 --- a/src/admin/web/cache-rules.js +++ b/src/admin/web/cache-rules.js @@ -40,14 +40,71 @@ window.rustProxyCacheRules = (() => { return { id, name: t("cacheRuleNewName"), enabled: true, stage, match: "all", conditions: [], actions: [{ type: ACTIONS[stage][0] }], stop: false, vhosts: [] }; } function normalize(rule) { - return { id: rule.id, name: rule.name || "", enabled: rule.enabled !== false, stage: rule.stage || "request", match: rule.match || "all", conditions: (rule.conditions || []).map(c => ({ ...c, values: [...(c.values || [])] })), actions: (rule.actions || []).map(a => ({ ...a })), stop: !!rule.stop, hash_stage: !!rule.hash_stage, vhosts: [...(rule.vhosts || [])] }; + return { ...structuredClone(rule), id: rule.id, name: rule.name || "", enabled: rule.enabled !== false, stage: rule.stage || "request", match: rule.match || "all", conditions: (rule.conditions || []).map(c => ({ ...structuredClone(c), values: [...(c.values || [])] })), actions: structuredClone(rule.actions || []), stop: !!rule.stop, hash_stage: !!rule.hash_stage, vhosts: [...(rule.vhosts || [])] }; } function clean(rule, global) { - const out = { id: rule.id, name: rule.name, enabled: rule.enabled, stage: rule.stage, match: rule.match, conditions: rule.conditions.map(c => { const item = { field: c.field, operator: c.operator, values: c.operator === "exists" ? [] : c.values }; if (FIELDS[c.field]?.name) item.name = c.name || ""; if (c.negate) item.negate = true; return item; }), actions: rule.actions.map(a => ({ ...a })), stop: rule.stop }; + const out = { ...structuredClone(rule), id: rule.id, name: rule.name, enabled: rule.enabled, stage: rule.stage, match: rule.match, conditions: rule.conditions.map(c => { const item = { ...structuredClone(c), field: c.field, operator: c.operator, values: c.operator === "exists" ? [] : [...c.values] }; if (FIELDS[c.field]?.name) item.name = c.name || ""; if (c.negate) item.negate = true; return item; }), actions: structuredClone(rule.actions), stop: rule.stop }; + delete out.hash_stage; + delete out.vhosts; if (rule.hash_stage) out.hash_stage = true; - if (global && rule.vhosts.length) out.vhosts = rule.vhosts; + if (global && rule.vhosts.length) out.vhosts = [...rule.vhosts]; return out; } + const flowMarker = rule => Array.isArray(rule.vcl_flow?.branches) && rule.vcl_flow.branches.length > 0; + function flowFailure(rule) { return new Error(t("cacheRulesFlowInvalid").replace("{rule}", rule?.name || rule?.id || "VCL")); } + // Structural checks only. Conditions/actions are evaluated and validated by + // Rust; this prevents UI operations from splitting or silently flattening a + // saved imported program before it reaches that compiler. + function validateFlow(rules) { + const groups = new Map(); + rules.forEach((rule, position) => { + const flow = rule.vcl_flow; + if (!flow) return; + if (flow.version !== 1 || typeof flow.group !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(flow.group) || + !Number.isInteger(flow.index) || flow.index < 0 || flow.index >= MAX_RULES || !Number.isInteger(flow.count) || flow.count < 1 || flow.count > MAX_RULES || + !Array.isArray(flow.guards || []) || (flow.guards || []).length > 16 || + !Array.isArray(flow.branches || []) || (flow.branches || []).length > 16) throw flowFailure(rule); + if (!groups.has(flow.group)) groups.set(flow.group, []); + groups.get(flow.group).push({ rule, position }); + }); + for (const members of groups.values()) { + const first = members[0], count = first.rule.vcl_flow.count; + if (members.length !== count) throw flowFailure(first.rule); + let conditionCount = 0; + const activeEntries = new Set(), lastBranches = new Map(); + members.forEach(({ rule, position }, index) => { + const flow = rule.vcl_flow, guards = flow.guards || []; + if (position !== first.position + index || flow.index !== index || flow.count !== count || + rule.enabled !== first.rule.enabled || JSON.stringify(rule.vhosts) !== JSON.stringify(first.rule.vhosts) || + rule.conditions.length || rule.match !== "all") throw flowFailure(rule); + if (flowMarker(rule) && (rule.actions.length || rule.stop)) throw flowFailure(rule); + guards.forEach((guard, depth) => { + if (!guard || !Number.isInteger(guard.entry) || !Number.isInteger(guard.branch)) throw flowFailure(rule); + const entry = members[guard.entry]?.rule; + const ancestors = entry?.vcl_flow?.guards || []; + if (guard.entry < 0 || guard.entry >= index || !activeEntries.has(guard.entry) || guard.branch < 0 || !entry || !flowMarker(entry) || + guard.branch >= entry.vcl_flow.branches.length || rule.stage !== entry.stage || rule.hash_stage !== entry.hash_stage || + ancestors.length !== depth || ancestors.some((ancestor, i) => ancestor.entry !== guards[i].entry || ancestor.branch !== guards[i].branch) || + guard.branch < (lastBranches.get(guard.entry) ?? 0)) throw flowFailure(rule); + lastBranches.set(guard.entry, guard.branch); + }); + for (const entry of activeEntries) if (!guards.some(guard => guard.entry === entry)) activeEntries.delete(entry); + if (flowMarker(rule)) activeEntries.add(index); + (flow.branches || []).forEach((branch, branchIndex, branches) => { + if (!branch || !Array.isArray(branch.any) || !branch.any.length || branch.any.length > 128 || + branch.any.some(clause => !Array.isArray(clause) || clause.length > 16)) throw flowFailure(rule); + if (branch.any.some(clause => !clause.length) && (branch.any.length !== 1 || branchIndex !== branches.length - 1)) throw flowFailure(rule); + conditionCount += branch.any.reduce((sum, clause) => sum + clause.length, 0); + if (conditionCount > 2048) throw flowFailure(rule); + }); + }); + } + } + function newFlowGroup(taken) { + let group; + do { group = `vcl-${Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, "0")).join("")}`; } while (taken.has(group)); + taken.add(group); return group; + } const esc = value => String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"'); const reEsc = value => String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const globRe = value => String(value).split("*").map(reEsc).join(".*"); @@ -132,6 +189,7 @@ window.rustProxyCacheRules = (() => { return conditions.length ? `${description}\nif (${joined}) {\n${body}\n}` : `${description}\n${body.replace(/^ {4}/gm, "")}`; } function exportVcl(rules) { + if (rules.some(rule => rule.vcl_flow)) throw new Error(t("cacheRulesFlowExportJson")); const subs = { request: "vcl_recv", response: "vcl_backend_response", deliver: "vcl_deliver" }; const blocks = [ "vcl 4.1;", @@ -502,12 +560,29 @@ window.rustProxyCacheRules = (() => { 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(); }); function taken() { return new Set(rules.map(rule => rule.id)); } + function unit(index) { + const group = rules[index]?.vcl_flow?.group; + if (!group) return { start: index, length: 1, members: [rules[index]] }; + const start = rules.findIndex(rule => rule.vcl_flow?.group === group); + const members = rules.filter(rule => rule.vcl_flow?.group === group); + return { start, length: members.length, members }; + } + function safelyEditFlow(action) { + try { validateFlow(rules); action(); } catch (error) { render(); toast(error.message, true); } + } + function updateExport() { + const hasFlow = rules.some(rule => rule.vcl_flow); + exportButton.textContent = t(hasFlow ? "cacheRulesExportJson" : "cacheRulesExportVcl"); + exportSummary.textContent = t(hasFlow ? "cacheRulesJsonPreview" : "cacheRulesVclPreview"); + exportPre.textContent = hasFlow ? JSON.stringify(rules.map(rule => clean(rule, scope === "global")), null, 2) : exportVcl(rules); + } if (scope === "global") { void loadTargets(); document.addEventListener("rustproxy-cache-targets", () => { if (root.isConnected && open.size) render(); }); } function renderNotices() { notices.replaceChildren(); + if (rules.some(rule => rule.vcl_flow)) notices.append(el("p", t("cacheRulesFlowHelp"), "fine cache-rules-notice")); if (scope !== "vhost") return; const globals = applicableGlobals(vhostId); if (ignoreGlobal) { if (globals.length) notices.append(el("p", t("cacheRulesGlobalSkipped").replace("{count}", globals.length), "fine cache-rules-notice")); return; } @@ -524,11 +599,21 @@ window.rustProxyCacheRules = (() => { list.replaceChildren(...rules.map((rule, index) => ruleCard(rule, index))); empty.hidden = rules.length > 0; addButton.disabled = rules.length >= MAX_RULES; - exportPre.textContent = exportVcl(rules); + updateExport(); renderNotices(); } - function move(from, to) { if (to < 0 || to >= rules.length) return; const [item] = rules.splice(from, 1); rules.splice(to, 0, item); render(); changed(); } + function move(from, to) { + if (from < 0 || from >= rules.length || to < 0 || to >= rules.length) return; + safelyEditFlow(() => { + const source = unit(from), target = unit(to); + if (source.start === target.start) return; + const destination = source.start < target.start ? target.start + target.length - source.length : target.start; + const moved = rules.splice(source.start, source.length); + rules.splice(destination, 0, ...moved); render(); changed(); + }); + } function ruleCard(rule, index) { + const grouped = !!rule.vcl_flow, block = unit(index); const card = el("div", undefined, `cache-rule${rule.enabled ? "" : " is-disabled"}${open.has(rule.id) ? " is-open" : ""}`); card.draggable = true; card.dataset.index = index; card.addEventListener("dragstart", event => { event.dataTransfer.setData("text/plain", String(index)); card.classList.add("is-dragging"); }); card.addEventListener("dragend", () => card.classList.remove("is-dragging")); @@ -536,23 +621,36 @@ window.rustProxyCacheRules = (() => { card.addEventListener("dragleave", () => card.classList.remove("is-drop")); card.addEventListener("drop", event => { event.preventDefault(); card.classList.remove("is-drop"); const from = Number(event.dataTransfer.getData("text/plain")); if (Number.isInteger(from) && from !== index) move(from, index); }); const head = el("div", undefined, "cache-rule-head"); - const grip = el("span", "⠿", "cache-rule-grip"); grip.title = t("cacheRulesDrag"); + const grip = el("span", "⠿", "cache-rule-grip"); grip.title = t(grouped ? "cacheRulesFlowMove" : "cacheRulesDrag"); const toggle = el("input", undefined, "switch"); toggle.type = "checkbox"; toggle.checked = rule.enabled; toggle.setAttribute("aria-label", t("enabled")); - toggle.addEventListener("change", () => { rule.enabled = toggle.checked; card.classList.toggle("is-disabled", !rule.enabled); exportPre.textContent = exportVcl(rules); changed(); }); + toggle.addEventListener("change", () => safelyEditFlow(() => { for (const item of block.members) item.enabled = toggle.checked; render(); changed(); })); const title = el("button", undefined, "cache-rule-title"); title.type = "button"; title.dataset.uiIconName = "none"; - title.append(el("b", rule.name || rule.id), el("span", t(STAGE_KEYS[rule.stage]), "pill cache-rule-stage"), el("span", summary(rule), "fine cache-rule-summary")); + title.append(el("b", rule.name || rule.id), el("span", t(STAGE_KEYS[rule.stage]), "pill cache-rule-stage"), el("span", flowMarker(rule) ? t("cacheRuleFlowBranch") : summary(rule), "fine cache-rule-summary")); title.addEventListener("click", () => { if (open.has(rule.id)) open.delete(rule.id); else open.add(rule.id); render(); }); const hitKey = scope === "vhost" ? `vhost:${vhostId}:${rule.id}` : `global:${rule.id}`; const hitCount = el("span", hits[hitKey] != null ? t("cacheRulesHits").replace("{count}", fmt(hits[hitKey])) : "", "fine cache-rule-hits"); hitCount.dataset.hitKey = hitKey; const actions = el("span", undefined, "cache-rule-actions"); - const up = el("button", "↑", "quiet"); up.type = "button"; up.disabled = index === 0; up.setAttribute("aria-label", t("cacheRulesMoveUp")); up.addEventListener("click", () => move(index, index - 1)); - const down = el("button", "↓", "quiet"); down.type = "button"; down.disabled = index === rules.length - 1; down.setAttribute("aria-label", t("cacheRulesMoveDown")); down.addEventListener("click", () => move(index, index + 1)); - const copy = el("button", t("cacheRulesDuplicate"), "quiet"); copy.type = "button"; copy.addEventListener("click", () => { if (rules.length >= MAX_RULES) return; const clone = normalize(structuredClone(rule)); clone.id = slug(`${rule.id}-copy`, taken()); clone.name = `${rule.name || rule.id} (${t("cacheRulesCopySuffix")})`; rules.splice(index + 1, 0, clone); open.add(clone.id); render(); changed(); }); - const remove = el("button", t("remove"), "quiet danger"); remove.type = "button"; remove.addEventListener("click", () => { rules.splice(index, 1); open.delete(rule.id); render(); changed(); }); + const up = el("button", "↑", "quiet"); up.type = "button"; up.disabled = block.start === 0; up.setAttribute("aria-label", t("cacheRulesMoveUp")); up.addEventListener("click", () => move(index, block.start - 1)); + const down = el("button", "↓", "quiet"); down.type = "button"; down.disabled = block.start + block.length === rules.length; down.setAttribute("aria-label", t("cacheRulesMoveDown")); down.addEventListener("click", () => move(index, block.start + block.length)); + const copy = el("button", t(grouped ? "cacheRulesFlowDuplicate" : "cacheRulesDuplicate"), "quiet"); copy.type = "button"; copy.disabled = rules.length + block.length > MAX_RULES; + copy.addEventListener("click", () => safelyEditFlow(() => { + if (rules.length + block.length > MAX_RULES) { toast(t("cacheRulesLimit"), true); return; } + const ids = taken(), group = grouped ? newFlowGroup(new Set(rules.map(item => item.vcl_flow?.group).filter(Boolean))) : null; + const copies = block.members.map(item => { + const clone = normalize(item); clone.id = slug(`${item.id}-copy`, ids); ids.add(clone.id); + clone.name = `${item.name || item.id} (${t("cacheRulesCopySuffix")})`; + if (group) clone.vcl_flow.group = group; + return clone; + }); + rules.splice(block.start + block.length, 0, ...copies); open.add(copies[0].id); render(); changed(); + })); + const remove = el("button", t(grouped ? "cacheRulesFlowRemove" : "remove"), "quiet danger"); remove.type = "button"; + remove.addEventListener("click", () => safelyEditFlow(() => { rules.splice(block.start, block.length); for (const item of block.members) open.delete(item.id); render(); changed(); })); actions.append(up, down, copy, remove); head.append(grip, toggle, title, hitCount, actions); card.append(head); + if (grouped) card.append(el("p", t("cacheRuleFlowPart").replace("{index}", rule.vcl_flow.index + 1).replace("{count}", rule.vcl_flow.count), "fine cache-rules-notice cache-rule-note")); if (scope === "global") for (const note of globalOverrideNotes(rule)) card.append(el("p", note, "fine cache-rules-notice cache-rule-note")); if (cookieOnlyPass(rule)) { // Controlled migration: an explicit pass is never relaxed automatically. @@ -568,16 +666,19 @@ window.rustProxyCacheRules = (() => { } function ruleEditor(rule) { const body = el("div", undefined, "cache-rule-body"); + const grouped = !!rule.vcl_flow, marker = flowMarker(rule); const grid = el("div", undefined, "cache-rule-grid"); const name = textInput(rule.name, t("cacheRuleNamePlaceholder")); name.maxLength = 96; name.addEventListener("input", () => { rule.name = name.value; changed(); syncPreview(); }); const id = textInput(rule.id, "", "mono"); id.maxLength = 64; id.pattern = "[A-Za-z0-9_\\-]{1,64}"; id.addEventListener("change", () => { const value = id.value.trim(); if (!/^[A-Za-z0-9_-]{1,64}$/.test(value) || (value !== rule.id && taken().has(value))) { id.value = rule.id; toast(t("cacheRuleIdInvalid"), true); return; } open.delete(rule.id); rule.id = value; open.add(value); changed(); }); const stage = select(STAGES.map(value => [value, t(STAGE_KEYS[value])]), rule.stage, t("cacheRuleStage")); - stage.addEventListener("change", () => { rule.stage = stage.value; if (rule.stage !== "request") rule.hash_stage = false; rule.actions = rule.actions.filter(a => ACTIONS[rule.stage].includes(a.type)); if (!rule.actions.length && !rule.stop) rule.actions = [{ type: ACTIONS[rule.stage][0] }]; rule.conditions = rule.conditions.filter(c => FIELDS[c.field].stages.includes(rule.stage)); render(); changed(); }); + stage.disabled = grouped; + stage.addEventListener("change", () => { if (grouped) { stage.value = rule.stage; toast(t("cacheRulesFlowStructureLocked"), true); return; } rule.stage = stage.value; if (rule.stage !== "request") rule.hash_stage = false; rule.actions = rule.actions.filter(a => ACTIONS[rule.stage].includes(a.type)); if (!rule.actions.length && !rule.stop) rule.actions = [{ type: ACTIONS[rule.stage][0] }]; rule.conditions = rule.conditions.filter(c => FIELDS[c.field].stages.includes(rule.stage)); render(); changed(); }); const match = select([["all", t("cacheRuleMatchAll")], ["any", t("cacheRuleMatchAny")]], rule.match, t("cacheRuleMatch")); - match.addEventListener("change", () => { rule.match = match.value; changed(); syncPreview(); }); - const stop = el("input", undefined, "switch"); stop.type = "checkbox"; stop.checked = rule.stop; stop.addEventListener("change", () => { rule.stop = stop.checked; changed(); }); + match.disabled = grouped; + match.addEventListener("change", () => { if (grouped) { match.value = rule.match; toast(t("cacheRulesFlowStructureLocked"), true); return; } rule.match = match.value; changed(); syncPreview(); }); + const stop = el("input", undefined, "switch"); stop.type = "checkbox"; stop.checked = rule.stop; stop.disabled = grouped; stop.addEventListener("change", () => { if (grouped) { stop.checked = rule.stop; toast(t("cacheRulesFlowStructureLocked"), true); return; } rule.stop = stop.checked; changed(); }); const labeled = (key, control, help) => { const label = el("label", undefined, "cache-rule-field"); label.append(el("span", t(key)), control); if (help) label.append(el("small", t(help), "fine")); return label; }; const stopLabel = el("label", undefined, "check cache-rule-stop"); stopLabel.append(stop, el("span", t("cacheRuleStop"))); grid.append(labeled("cacheRuleName", name), labeled("cacheRuleId", id), labeled("cacheRuleStage", stage, `cacheRuleStageHelp${rule.stage[0].toUpperCase()}${rule.stage.slice(1)}`), labeled("cacheRuleMatch", match), stopLabel); @@ -585,32 +686,40 @@ window.rustProxyCacheRules = (() => { if (scope === "global") { const vhostItems = targetList().map(target => ({ id: target.id, title: targetTitle(target), detail: target.docker ? target.id : (target.hosts || []).slice(0, 3).join(", "), search: (target.hosts || []).join(" "), badge: target.docker ? "Docker" : "", badgeClass: "is-allow" })); const picker = window.rustProxyChoicePicker.create({ className: "cache-rule-vhosts", selected: rule.vhosts, items: vhostItems, limit: 64, labels: { choose: "cacheRuleVhostsAll", selected: "cacheRuleVhostsSelected", none: "cacheRuleVhostsNone", empty: "cacheRuleVhostsEmpty" } }); - picker.addEventListener("choicechange", event => { rule.vhosts = event.detail || []; exportPre.textContent = exportVcl(rules); }); - picker.addEventListener("change", changed); + picker.addEventListener("choicechange", event => { + if (grouped) safelyEditFlow(() => { for (const item of unit(rules.indexOf(rule)).members) item.vhosts = [...(event.detail || [])]; render(); changed(); }); + else { rule.vhosts = event.detail || []; updateExport(); } + }); + picker.addEventListener("change", () => { if (!grouped) changed(); }); const field = el("div", undefined, "cache-rule-field cache-rule-vhosts-field"); field.append(el("span", t("cacheRuleVhosts")), picker, el("small", t("cacheRuleVhostsHelp"), "fine")); body.append(field); } const conditions = el("div", undefined, "cache-rule-section"); conditions.append(el("h4", t("cacheRuleConditions"))); const conditionRows = el("div", undefined, "cache-rule-rows"); - rule.conditions.forEach((condition, index) => conditionRows.append(conditionRow(rule, condition, index))); - if (!rule.conditions.length) conditionRows.append(el("p", t("cacheRuleNoConditions"), "fine")); + if (grouped) { + conditionRows.append(el("p", t("cacheRulesFlowStructureLocked"), "fine"), el("pre", JSON.stringify(rule.vcl_flow, null, 2), "metrics-example mono cache-rule-flow")); + } else { + rule.conditions.forEach((condition, index) => conditionRows.append(conditionRow(rule, condition, index))); + if (!rule.conditions.length) conditionRows.append(el("p", t("cacheRuleNoConditions"), "fine")); + } const addCondition = el("button", t("cacheRuleAddCondition"), "outline"); addCondition.type = "button"; - addCondition.disabled = rule.conditions.length >= 16; - addCondition.addEventListener("click", () => { rule.conditions.push({ field: "path", operator: "prefix", values: [] }); render(); changed(); }); + addCondition.disabled = grouped || rule.conditions.length >= 16; + addCondition.addEventListener("click", () => { if (grouped) return; rule.conditions.push({ field: "path", operator: "prefix", values: [] }); render(); changed(); }); conditions.append(conditionRows, addCondition); const actionsSection = el("div", undefined, "cache-rule-section"); actionsSection.append(el("h4", t("cacheRuleActions"))); const actionRows = el("div", undefined, "cache-rule-rows"); rule.actions.forEach((action, index) => actionRows.append(actionRow(rule, action, index))); const addAction = el("button", t("cacheRuleAddAction"), "outline"); addAction.type = "button"; - addAction.disabled = rule.actions.length >= 16; - addAction.addEventListener("click", () => { const used = new Set(rule.actions.map(a => a.type)); rule.actions.push({ type: ACTIONS[rule.stage].find(type => !used.has(type)) || ACTIONS[rule.stage][0] }); render(); changed(); }); + addAction.disabled = marker || rule.actions.length >= 16; + addAction.addEventListener("click", () => { if (marker) return; const used = new Set(rule.actions.map(a => a.type)); rule.actions.push({ type: ACTIONS[rule.stage].find(type => !used.has(type)) || ACTIONS[rule.stage][0] }); render(); changed(); }); + if (marker) actionRows.append(el("p", t("cacheRuleFlowBranch"), "fine")); actionsSection.append(actionRows, addAction); const preview = el("pre", "", "metrics-example mono cache-rule-vcl"); - const syncPreview = () => { preview.textContent = ruleVcl(rule); exportPre.textContent = exportVcl(rules); }; + const syncPreview = () => { preview.textContent = grouped ? JSON.stringify(clean(rule, scope === "global"), null, 2) : ruleVcl(rule); updateExport(); }; body.addEventListener("input", syncPreview); body.addEventListener("change", syncPreview); - const previewWrap = el("div", undefined, "cache-rule-section"); previewWrap.append(el("h4", t("cacheRuleVcl")), preview); + const previewWrap = el("div", undefined, "cache-rule-section"); previewWrap.append(el("h4", t(grouped ? "cacheRulesJsonPreview" : "cacheRuleVcl")), preview); body.append(conditions, actionsSection, previewWrap); syncPreview(); return body; @@ -745,10 +854,18 @@ window.rustProxyCacheRules = (() => { } function addRules(items, templateKey = "") { if (rules.length + items.length > MAX_RULES) { toast(t("cacheRulesLimit"), true); return 0; } - const ids = taken(); + const ids = taken(), groups = new Set(rules.map(rule => rule.vcl_flow?.group).filter(Boolean)), remappedGroups = new Map(); const addedRules = items.map(item => { const rule = normalize({ ...item, id: slug(item.id || item.name, ids), vhosts: scope === "global" ? item.vhosts || [] : [] }); ids.add(rule.id); + if (rule.vcl_flow) { + const original = rule.vcl_flow.group; + if (!remappedGroups.has(original)) { + const group = groups.has(original) ? newFlowGroup(groups) : original; + remappedGroups.set(original, group); groups.add(group); + } + rule.vcl_flow.group = remappedGroups.get(original); + } return rule; }); // The parent-name rule must execute before the independent CDN cookie @@ -756,8 +873,10 @@ window.rustProxyCacheRules = (() => { 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" || a.type === "cookie_pass")) : -1; - if (cdnIndex >= 0) rules.splice(cdnIndex, 0, ...addedRules); - else rules.push(...addedRules); + const candidate = [...rules]; + candidate.splice(cdnIndex >= 0 ? unit(cdnIndex).start : candidate.length, 0, ...addedRules); + validateFlow(candidate); + rules = candidate; if (addedRules.length) open.add(addedRules[0].id); render(); if (addedRules.length) changed(); @@ -766,7 +885,9 @@ window.rustProxyCacheRules = (() => { function addTemplate(key) { const make = TEMPLATES[key]; if (!make || !templateAvailable(key, scope)) return; - const items = make(), added = addRules(items, key); + const items = make(); + let added; + try { added = addRules(items, key); } catch (error) { toast(error.message, true); return; } if (!added) return; const needsReview = items.some(item => item.enabled === false); toast(t(needsReview ? "cacheRuleCatalogAddedDisabled" : "cacheRulesTemplateAdded").replace("{count}", added)); @@ -843,15 +964,19 @@ window.rustProxyCacheRules = (() => { }); importApply.addEventListener("click", () => { if (!pendingImport) return; - const added = addRules(pendingImport); - resetImportPreview(); - importResult.append(el("p", t("cacheRulesImportDone").replace("{count}", added), "fine is-ok")); + try { + const added = addRules(pendingImport); + if (!added) return; + resetImportPreview(); + importResult.append(el("p", t("cacheRulesImportDone").replace("{count}", added), "fine is-ok")); + } catch (error) { importResult.append(el("p", error.message, "fine is-error")); } }); exportButton.addEventListener("click", async () => { exportBox.open = true; exportBox.scrollIntoView?.({ block: "nearest", behavior: "smooth" }); try { await navigator.clipboard.writeText(exportPre.textContent); toast(t("copied")); } catch { } }); ignoreBox.addEventListener("change", () => { ignoreGlobal = ignoreBox.checked; renderNotices(); changed(); }); function read() { + validateFlow(rules); for (const rule of rules) { - if (!rule.actions.length && !rule.stop) throw new Error(t("cacheRuleNeedsAction").replace("{rule}", rule.name || rule.id)); + if (!rule.actions.length && !rule.stop && !flowMarker(rule)) throw new Error(t("cacheRuleNeedsAction").replace("{rule}", rule.name || rule.id)); for (const c of rule.conditions) { if (FIELDS[c.field].name && !c.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id)); if (c.operator !== "exists" && !(c.values || []).length) throw new Error(t("cacheRuleNeedsValue").replace("{rule}", rule.name || rule.id)); diff --git a/src/admin/web/css/55-policy.css b/src/admin/web/css/55-policy.css new file mode 100644 index 0000000..02618d6 --- /dev/null +++ b/src/admin/web/css/55-policy.css @@ -0,0 +1,96 @@ +/* Shared global, vhost, Docker and location HTTP policy editor. */ +.http-policy-editor, +.policy-visual, +.policy-rules, +.policy-detail-body, +.policy-actions, +.policy-test-output { + display: grid; + gap: 12px; + min-width: 0; +} +.http-policy-editor { width: 100%; margin-top: 10px; } +.http-policy-editor p, +.http-policy-editor h4 { margin: 0; } +.http-policy-editor [hidden] { display: none !important; } +.policy-toolbar, +.policy-row-controls, +.policy-rule-heading { + display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: center; +} +.policy-toolbar > button, +.policy-row-controls > button { width: auto; } +.policy-toolbar > [aria-pressed="true"] { border-color: var(--accent); color: var(--accent); } +.policy-guide { margin-left: auto; } +.policy-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; min-width: 0; } +.policy-wide { grid-column: 1 / -1; } +.policy-field { display: grid; gap: 5px; min-width: 0; color: var(--muted); font-size: 12px; } +.policy-field > :is(input, select, textarea) { min-width: 0; width: 100%; margin: 0; } +.policy-field > textarea { resize: vertical; font-family: ui-monospace, monospace; font-size: 12px; line-height: 1.5; } +.policy-check { display: flex; gap: 8px; align-items: center; } +.policy-check > input { width: auto; flex: 0 0 auto; } +.policy-rule { + display: grid; + gap: 14px; + min-width: 0; + padding: 16px; + border: 1px solid var(--line); + border-left: 3px solid var(--accent); + background: var(--panel2); + border-radius: var(--rp-radius-surface, 0px); +} +.policy-rule.is-disabled { border-left-color: var(--muted); } +.policy-rule.is-disabled .policy-order { color: var(--muted); } +.policy-rule-heading > .policy-field:not(.policy-check) { flex: 1 1 180px; } +.policy-order { color: var(--accent); } +.policy-action { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(155px, 1fr)); + gap: 10px; + align-items: end; + padding: 12px; + background: var(--panel); + border: 1px solid var(--line); + min-width: 0; +} +.policy-action > .policy-row-controls { grid-column: 1 / -1; justify-content: flex-end; } +.http-policy-editor details { min-width: 0; border: 1px solid var(--line); border-radius: var(--rp-radius-surface, 0px); } +.http-policy-editor details > summary { padding: 10px 12px; cursor: pointer; color: var(--text); font-weight: 600; } +.policy-detail-body { padding: 12px; border-top: 1px solid var(--line); } +.policy-rule > button, +.policy-detail-body > button { justify-self: start; } +.policy-result { + margin: 0; + padding: 12px; + max-height: 420px; + overflow: auto; + white-space: pre-wrap; + overflow-wrap: anywhere; + background: var(--code-bg); + border: 1px solid var(--line); + color: var(--text); + font-size: 12px; + line-height: 1.5; +} +.policy-message { padding: 10px; border: 1px solid var(--line); white-space: pre-wrap; } +.policy-message.is-error { color: var(--red); border-color: var(--danger-line-strong); } +.policy-trace { width: 100%; border-collapse: collapse; font-size: 12px; table-layout: fixed; } +.policy-trace th, +.policy-trace td { padding: 8px; text-align: left; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; white-space: pre-wrap; } +.policy-trace .is-matched td:first-child { color: var(--green); } +.policy-trace .is-skipped { color: var(--muted); } +.policy-counter-scroll { overflow: auto; display: grid; gap: 10px; } +.policy-counter-scroll > table { min-width: 520px; } +.docker-policy-editor { margin: 12px 0; border: 1px solid var(--line); padding: 12px; } +.docker-policy-editor > summary { cursor: pointer; font-weight: 600; } +@media (max-width: 760px) { + .policy-grid { grid-template-columns: 1fr; } + .policy-rule { padding: 12px; } + .policy-rule-heading > .policy-row-controls { width: 100%; justify-content: flex-end; } + .policy-action { grid-template-columns: minmax(0, 1fr); } + .policy-toolbar > button { flex: 1 1 auto; } + .policy-guide { margin: 0; } +} diff --git a/src/admin/web/css/README.md b/src/admin/web/css/README.md index aa9274e..61327bb 100644 --- a/src/admin/web/css/README.md +++ b/src/admin/web/css/README.md @@ -62,14 +62,12 @@ From the repository root: ```bash python3 scripts/build/panel_css.py --check -python3 tools/dev/test_panel_css.py -python3 scripts/preflight.py python3 scripts/audit_css_usage.py --strict bash dev.sh check bash dev.sh test ``` -The first three commands require only Python 3.10+. The optional CSS audit +The stylesheet check requires only Python 3.10+. The optional CSS audit requires `tinycss2` and `cssselect2`; install them in a development environment, not on the deployed server. `--structure-json PATH` records repeated selectors, conditional blocks, properties and identical declaration blocks. `--json PATH` diff --git a/src/admin/web/css/manifest.json b/src/admin/web/css/manifest.json index 71586cb..ab91c72 100644 --- a/src/admin/web/css/manifest.json +++ b/src/admin/web/css/manifest.json @@ -6,6 +6,7 @@ "30-overview.css", "40-editors.css", "50-settings.css", + "55-policy.css", "60-monitoring.css", "70-responsive.css" ] diff --git a/src/admin/web/docker.js b/src/admin/web/docker.js index 1c67fb7..0939fa4 100644 --- a/src/admin/web/docker.js +++ b/src/admin/web/docker.js @@ -882,6 +882,11 @@ grid.append(checkboxField("vhTimingHeaders", box("docker-timing-headers", assignment?.timing_headers)), checkboxField("vhBackendHeader", box("docker-backend-header", assignment?.backend_header)), checkboxField("vhBackendTimingHeader", box("docker-backend-timing-header", assignment?.backend_timing_header))); details.append(grid); return details; } + function policyEditor(assignment, row) { + const details = el("details", undefined, "docker-policy-editor"); details.append(el("summary", t("policyTitle"))); + const policy = window.rustProxyPolicy.create({ value: assignment?.policy || {}, scope: "vhost", onChange: () => row.classList.add("is-dirty") }); + details.append(policy.node); row._readPolicy = () => policy.read(); return details; + } function collectDiagnostics(row) { const on = cls => row.querySelector(cls)?.checked === true; return { timing_headers: on(".docker-timing-headers"), backend_header: on(".docker-backend-header"), backend_timing_header: on(".docker-backend-timing-header") }; @@ -903,7 +908,7 @@ allow_certificate_mismatch: row.querySelector(".docker-cert-mismatch")?.checked === true, acl: inline && row.querySelector(".docker-acl-public")?.checked !== true ? { default: row.querySelector(".docker-acl-default").value, rules: parseRules(row.querySelector(".docker-acl-rules").value) } : null, proxy_timeouts: { connect_timeout_seconds: Number(row.querySelector(".docker-proxy-connect").value), response_header_timeout_seconds: Number(row.querySelector(".docker-proxy-header").value), read_timeout_seconds: Number(row.querySelector(".docker-proxy-read").value), send_timeout_seconds: Number(row.querySelector(".docker-proxy-send").value) }, - health_check: collectHealth(row), passive_health: collectPassiveHealth(row) + health_check: collectHealth(row), passive_health: collectPassiveHealth(row), policy: row._readPolicy?.() || {} }; } async function saveAssignment(agentId, row, publish) { @@ -1063,7 +1068,7 @@ protocolOptions.append(h1, checkboxField("dockerHttp2Enabled", h2Enabled), checkboxField("dockerHttp3Enabled", h3Enabled)); protocolBox.append(protocolSummary, protocolOptions); route.append(hostField, aliases.node, backendIpSettings, labeled("dockerBackendScheme", scheme), switches); syncHostHelp(); - editor.append(route, protocolBox, aclEditor(assignment, agent), securityEditor(assignment), cacheEditor(assignment, agent, key, cacheEnabled, () => expandedHost(host.value.trim() || technical, domainSelect.value)), diagnosticsEditor(assignment), timeoutEditor(assignment), healthEditor(assignment), passiveHealthEditor(assignment)); + editor.append(route, protocolBox, aclEditor(assignment, agent), securityEditor(assignment), cacheEditor(assignment, agent, key, cacheEnabled, () => expandedHost(host.value.trim() || technical, domainSelect.value)), diagnosticsEditor(assignment), policyEditor(assignment, row), timeoutEditor(assignment), healthEditor(assignment), passiveHealthEditor(assignment)); const actions = el("div", undefined, "docker-service-actions"); apply = el("button", t("dockerApplyService"), "outline docker-apply"); apply.type = "button"; apply.disabled = !publish.checked; apply.addEventListener("click", async () => { apply.disabled = true; try { await saveAssignment(agent.id, row, true); } catch (error) { toast(error.message, true); } finally { if (row.isConnected) apply.disabled = !publish.checked; } }); actions.append(apply); editor.append(actions); function updateHint() { syncCertificateHint(); editorHint.textContent = hintFor({ hostname: host.value.trim(), domain: domainSelect.value, targetLabel: target.selectedOptions?.[0]?.textContent || t("dockerBackendIpAuto"), scheme: scheme.value, h2: h2Enabled.checked, h3: h3Enabled.checked, aliasCount: aliases.count() }); } updateHint(); for (const control of [host, aliases.input, target, scheme]) { control.addEventListener("input", updateHint); control.addEventListener("change", updateHint); } diff --git a/src/admin/web/index.html b/src/admin/web/index.html index 6fb80ed..a3f5372 100644 --- a/src/admin/web/index.html +++ b/src/admin/web/index.html @@ -2513,6 +2513,8 @@ data-i18n="globalSecurityHeaders" type="button">Security headers + @@ -2726,6 +2728,16 @@ type="submit">Apply header rules +