From 51631810e1e3347d63efc297f01983629647b9c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Gruszczy=C5=84ski?= Date: Fri, 27 Nov 2026 13:56:59 +0100 Subject: [PATCH] v0.42.4_fixes --- CHANGELOG.md | 5 +- SHA256SUMS | 55 ++- docs/DASHBOARD.md | 2 + docs/FASTCGI.md | 2 +- docs/MIGRATION.md | 4 +- docs/PHP_FPM.md | 2 + langs/en_US.json | 2 + langs/pl_pl.json | 2 + scripts/resolve_dependencies_0312.sh | 28 -- src/acl/dynamic/mod.rs | 37 +- src/acl/dynamic/tests.rs | 12 +- src/admin/openapi.json | 2 +- src/admin/web/app/preferences.js | 84 +++- src/admin/web/css/10-base.css | 21 + src/admin/web/file-logs.js | 98 +++-- src/admin/web/management.js | 28 +- src/admin/web/vhosts/render.js | 135 ++++++- src/admin/web/web-server-profiles.js | 10 +- src/basic_auth/mod.rs | 2 +- src/basic_auth/tests.rs | 2 +- src/db.rs | 87 ++-- src/db/tests.rs | 139 +++++++ src/pages/mod.rs | 18 +- src/proxy/headers/authority_tests.rs | 231 +++++++---- src/proxy/web_cache_revalidation/tests.rs | 2 +- src/web_server/htaccess/parse.rs | 4 +- src/web_server/mod.rs | 4 +- src/web_server/serve.rs | 99 +++-- src/web_server/tests.rs | 469 ++++++++++++++++++---- 29 files changed, 1192 insertions(+), 394 deletions(-) delete mode 100755 scripts/resolve_dependencies_0312.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index ebfb6ee..9938b79 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,10 @@ Release history focused on **features, settings, default behavior, compatibility - **Web Server:** distinguish RustProxy-generated static and filesystem errors from PHP/FastCGI output and `.htaccess ErrorDocument` responses. Generated errors now use the configured Vhost error page, falling back to the global error page and then the Web Server built-in HTML. Application-provided error bodies remain unchanged unless explicitly selected in Vhost `intercept_statuses`. - **Basic Auth:** 401, 403, 429 and 503 denials can use Vhost/global error HTML without bypassing security checks. Preserve `WWW-Authenticate`, `Retry-After` and private no-store caching. External authentication provider responses and redirects still bypass custom error pages. -- **Compatibility:** no JSON configuration migration or change to the default application-origin interception policy. +- **FastCGI profile editor:** show visible ID and name labels with descriptions in the dynamic form, and generate a unique profile ID from the display name through the shared Auto ID control. Existing IDs and Web Service profile references remain unchanged. +- **Upgrade safety:** apply only SQLite migrations newer than `PRAGMA user_version` and commit them with the version update atomically. Determine the schema version from the migration registry; update the SQLite pragma with audited, compile-time-generated SQL compatible with SQLx 0.9.1 (without hard-coded pragma versions). Version 12 continues to increase the administrator preference document limit to 64 KiB; existing preferences, configuration and credentials are retained. Repeat startups do not execute legacy migrations. +- **Backends table:** keep filter buttons and unchanged table rows in the DOM during live updates to preserve keyboard focus and avoid scroll jumps. Expansion state, sorting, search, columns and saved preferences behave as before. +- **Admin panel focus/scroll fixes:** apply preference changes only to relevant views instead of rebuilding Vhosts, Docker Vhosts, redirects, 404 hosts, streams, or dashboard controls after every save. Keep chart-palette swatches, live/stored log column checkboxes, and stored log sorting headers mounted while updating their state. Preserve keyboard focus and scroll when expanding stored log entries. Add an optional Chromium/Playwright regression check (`python3 scripts/verify_admin_focus.py`) using mocked administration API responses; no database changes. ## 0.42.3 — Offline Cloudflare-style status pages diff --git a/SHA256SUMS b/SHA256SUMS index dfe8517..c665fa2 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ 4140a2956264b44f259e6a37fc00ba02097bbe68b09296e04d3d243c1287129b .env.example 0a5e87541831edca0e7164c6469dba01a8a7053ab14dbfb8019c83e4db10edc2 .gitignore 1c275142e27441c2f70c5361b1065f0cdf5fccf731eaf114a7b2bdf4ae23bd21 AGENTS.md -a7c78fde22738d685c4af12ab845cef5b86a8794189f489c5a228a97f05cfc72 CHANGELOG.md +ecfb8b157f19c966da2523ab0e209966f5cfb7ca7c8525ba74ae72b3437fb7c6 CHANGELOG.md 193d722f4403a57494929392d1256fd73a33246a02edeab9143640b4b61b02ac Cargo.lock d0a17bcb665bcd7814d41e24d7a462427c1b65ec837700aeedbe8d10b14703c1 Cargo.toml 788745d4f70a0382c6280020afbd48844bb2af65e835a826852143f8132cdeca Dockerfile @@ -46,19 +46,19 @@ bfe96dd91dfc6e07918a662d98b036f12ceb011a5aa8381b3778bd0c964b19ab docs/CACHE.md 31285f000cf725d018a926023fe608fec983b959053f7a55e0954b962a8bc20c docs/CERTIFICATES.md 81df6715e2f07617fe0bbb0960c4d5bdac28cf665ce7297fa3768118e6ab28ba docs/CONFIGURATION.md 2cede323fe2767100258b5e1d3e3a8b362e2a91acf2b0ee61090c4a2db97d952 docs/CUSTOM_LOCATIONS.md -16d4510e38d43c3bbde9b7dab7af3aeb0cb837dc2f1956cfaad7a9a11bea3bfc docs/DASHBOARD.md +7b286e85330fad398fc6f9df1b894e004a42fb33ab7168eb93f87220a3bf5503 docs/DASHBOARD.md 53cb0ce7db5ce25e4c2381de3a6e875d212deeed08861da63050de6c51a442bd docs/DOCKER_DISCOVERY.md 279afcf0b5b8d2f8ef7b723ba0b5050ca4536f14445f3ee1b71e9f32b800bb9b docs/ERROR_PAGES.md -3e729724030fd38d2d77272fddbb6509b7cd971c6bf0e9e3ef234ad69e342156 docs/FASTCGI.md +d297397fad57b3fbaf876025e8b3aceb15307d745272d75b1428d498e7153570 docs/FASTCGI.md 01b6d461d6b17b321d63cfb51435814858b29b437ed3e0bb13aba4351eaaf735 docs/FEATURES.md f7bb59821e0d6c45ae2a1789086fd9dab33d91c0ceae784ae68f64bd13b5f496 docs/HEADLESS.md bce732d845c23ad677ae811e7529b9322ab41d04ca808e04087d0f76bccd9309 docs/INSTALL.md 3268808766ad66263e465f251dce18cff2e7ede355638dc2b0975870b1a5eead docs/LOAD_BALANCING.md e5e50be31b3160588599336b1871b07a1e829b202454a67d2dc4e2e754d23eab docs/LOGS.md -3b889851ba3405247861391aefbcfcaa5a96cf9b09b3e0e0e412ec2f54e11b1a docs/MIGRATION.md +127cd47030dc48f5d9d9b1a3853291626440d95bfbd80c604b8eb9d15966f48f docs/MIGRATION.md 48105c4303401aa99ffff00d3ebaf3024535a492a4a7b883c6803e4732b37434 docs/MONITORING.md 6d3937088eeb67a9f690d44ebe0b6e660b68116dbf69091ac7816bdc52cec2b6 docs/PERFORMANCE.md -a8fdd52601f45a19fd194e27d6ce40aaf57603e88633f8d7040775599494e124 docs/PHP_FPM.md +96a69bf9b68e72e6f352f23173bcd0b013af8d6d9cef56141e49efbe35f68f2d docs/PHP_FPM.md 45ce24998bda40e60f34756bef29616114aec9fd5cdd5e1aed692ff2371a3af1 docs/POLICY.md 54e9e771707777144105a59c4d6dd6589cc74d735aea660af5366283cf820ee6 docs/README.md e90842a75459ddb5892334f66a4139d9301280b4d0c17077d211749bd7c90d80 docs/RESPONSE_DELIVERY.md @@ -138,8 +138,8 @@ e9cbb0224c4a3d23a6019ba557e0cd568c1ad5e1582ff1e335fb7d99b7a1055d integrations/r 3f092a9ab80221eddd67be4d1a776acbc6e04c1eb6011b588280c28e83b2582f integrations/routeros-oci-build/build-routeros-oci.sh 3f267cafa16006e5456ade78ee2d5fae02cc7ce747839523068ffd8d7c98798a integrations/routeros-oci-build/docker-entrypoint.sh ae2ee2887fcba096d0de25edcc18faa1ffec35759274518db1bf6d6982f7176c langs/README.md -ebc5205910072c105d5b95b69f5c4994ce11373eabbd762e94f4633aa88e5f31 langs/en_US.json -805e05923939b558f3282e92226d7e501f31612eb8f6ea98308f22cad89ac296 langs/pl_pl.json +8d4af9a24fd055c670ce3d4578ae6dcd21e95f5fe5a8edd86ebc8c11c4ca4e24 langs/en_US.json +4e090839dd038a41d09a445347fe3381f88dce1446e4c46607dbfa44d854fd40 langs/pl_pl.json 38773ed251a8c24af353f4744e498ae2bc7d4151df7927e942c4ac223f6008e1 make_zip.py e830d37dd1f81a4b0aa7d535f5bba69e34e433b0fd99cc8ee0b296786c32379a migrations/0002_admin.sql 20112cc82192098b8d602f1c4f7ca08712e9e1366c845fabb92753187c370d35 migrations/0003_certificate_renewals.sql @@ -175,14 +175,13 @@ a59587ce8ad41b1bbb431356b58398f9c8ff7cb96a613a91752e907a70e10c2e scripts/deploy a459d95bbb0076f33ade8b273b813308167f9d8d45242b309a2d18320ca0093c scripts/migration/migrate_npm_api.py 4c905a387f210c30fbf12a7738676fd39819bc96bc4a272da1db5f18a2d3013e scripts/migration/migrate_npm_core.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 -f097cce1f831e01b68688eb60c1b6393413131e6543c4627f3cedd9ef706193b src/acl/dynamic/mod.rs -0b10c7f6086086754d2bca22fb04116d534bf461d36b0b6bcaf20c0b42996b2a src/acl/dynamic/tests.rs +bbc2c592a91ae4392b996e80066430568cc042d54bb9eeda3825100af2e5a136 src/acl/dynamic/mod.rs +f9479b3a3ba56261e45bc1d066508c73e1ff1f295588168680d0d34f136b4acf src/acl/dynamic/tests.rs 50d9a0009cdcee6dd34a6215755d98f38ea18fa39b9faf070d1a7649eeac6aae src/acl/tests.rs f15b5bb11e2b949d7ed203711275b24b3f76de2ab617ef8b7345585c15ca34bd src/acme.rs 767d2f26fa8dea4ff6717d1e20ac0611b83bd20ab64bda8163cc6a5cc4dcb614 src/acme/headless.rs @@ -214,7 +213,7 @@ f9b2c8fe62cc92d7693e46145b2543b12dd6d4943fe2d52c67ed6958d4af83de src/admin/docu e2253599b5e39510946729920d240711403a3889cc495eb49824296228f1d080 src/admin/file_logs_query.rs 1594c8666991c1d07487a6a718211ef404cf49114721960f7e119bb7f605e3d2 src/admin/logging_api.rs 781fd5f176dd8f2372f75bd90edcf160708e2d0a8d6a115ba4b283c0cd49eb2d src/admin/mod.rs -e3a2142fa7244c08c88bcf5829c4cbab9e42388c22aaef5970ed075fe7022f1e src/admin/openapi.json +e04ae9e0a71d41849315dbebfb51755e7e73489741ffa0fd6b815a6e74be576a src/admin/openapi.json 9f8842cdec27d703d1795dd6eb37d9420e9f5a2e56a0df93278c92bace5d1f4c src/admin/operations.rs 257d93a29d0bda96462bcf695aba8d0ec0f9412c379e066ec46ae8ee034e3a53 src/admin/panel_assets.rs f5127855c2994d052678865df36d703b74f4a0afc633daf7718b10da18d26e37 src/admin/panel_content.rs @@ -256,7 +255,7 @@ e165db3dd12be8dbff2dfffe3bb9608ce9125924cb97558c26826e9f3d070699 src/admin/web/ 6f10f3239aea505aa01796620981eed873930c129ed5a2fd7eb439e0e0d24558 src/admin/web/app/overview-samples.js 3b5c68e6258946b79b7f5042384ad2d39407807a40984ef2f58c4b0edb9d65fa src/admin/web/app/overview-wide-metrics.js e799e0406c7ff54cbf71faf704a20265bdf5180a8ed2f26388d0775231365410 src/admin/web/app/path-permissions.js -b0930110e4eb7de6826e27b5b46c47e46556449fed6dc505d42da4f5e9c20366 src/admin/web/app/preferences.js +e3b9202fa113f39453c699c3595ab006b120dd759c342c078660d85c77e4c2df src/admin/web/app/preferences.js 30ec0a7027215eae63946689af2c042de0cf468a6b1054535694da4dd4214cdb src/admin/web/app/rate-sampling.js 3b8e566d81a5b94ef21c73e7805ae128454f085554de9358040de266bcbdb0e0 src/admin/web/app/refresh.js 66de066418464669f9d47c6f61b0333b13b95e188a90bb964c7851acb3bc3cbf src/admin/web/app/runtime.js @@ -285,7 +284,7 @@ e9cfe14e8e5093e8f8be504d9590643d71935846241f4e73ea4afcafb7f0f806 src/admin/web/ 9efc37b434336db30333f28c09e14355c45332e1d28c64bb6b88f875ba9fd297 src/admin/web/cf_page/placeholder.html 38bb67d9ec6b6e08298d63267afa3a92cbc0818fb0a21fc39520afdca4a995e4 src/admin/web/cf_page/welcome.html c2912a5e218896177776d4c5920e240092a3de66f9a4b95c1631796771e0ce3c src/admin/web/css/00-tokens.css -03fcd3917f84eb995bfea8ffebd261c90cae3733e26c2dcac2be3a7d5edd60ec src/admin/web/css/10-base.css +a7bfda3be5d72876679d532f03db00705f5e11426d665d8d1e6dc5b35e389c22 src/admin/web/css/10-base.css 9cd9b62ff8cfba47cb180e29ea5f69b8e97c7817dfcfddcb55fc4e08d11a7184 src/admin/web/css/20-shell.css 5af483ff7937ff245d8718179dc6001716d2b279f6ce935f5aa0c9fcfa370ab8 src/admin/web/css/30-overview.css 2763ff8969567cbd001ba4b5d5b669aea7aec347088ffe7c2b164b82396755d5 src/admin/web/css/40-editors.css @@ -318,14 +317,14 @@ ff72fc4c6a11907a16234c4b3c7d7f7bcf82eb72868dc3fbf654b04aff806fc8 src/admin/web/ e6c4d91d1542d0a5b47bb8736f9539d43a6713df5a473b635519d5b7eac2eb9c src/admin/web/error_504.html 003d382cc8dd69ad7237679632c04a9389366bb71dd7dca8ee64ee06614aa9a5 src/admin/web/error_auth_provider.html 0a5fff35555153f59d4346933030a67b6e1a8768cee7a47cfa2fcf1a2c564f63 src/admin/web/favicon.svg -e0f0b302092ced1c84ef7e99864984444f0e9d4e3b7d85e74d3507d566952a7f src/admin/web/file-logs.js +3fbd758d96701dab907e98331b41e8e8953bc969a00aa9e44df5c401b8ac19c9 src/admin/web/file-logs.js 9a243e651984cf0b84649c89ed0452d4961f5384c00909403fc640768ed3feef src/admin/web/host404.js a066fc38de115ac5b9c76cee73a14f47b9df43370a45c9cf8fec8f2bda8cbb60 src/admin/web/index.html be9999a001c59630963d60539e860b59999dcf74c5ff0087b12a6fb69b4e7bd2 src/admin/web/integrations.js 7a12f020fc587205694978ab41b660e9a80487d413fbf6e34fc525eabc58308f src/admin/web/login-keys.json ac9f667273918e18406df06cb2613c923f50a88897693a03a18f500e22dc6ec2 src/admin/web/login.html c2e5f554810b8e34fb47361fb90a01073a2e332ee26d82e030956fad3ec1f83e src/admin/web/login.js -0704aad8f68d5e56a5ec33b3b80f072e086b455c8dcbe1dac9a0320cb518c9ca src/admin/web/management.js +719c7cc6f718a376cf390c58d7d493c6fa0b4126b8f727e9eab823f8609cdb6a src/admin/web/management.js 1f3d10e389c9c20e6eb019509fa6e82b50c6b43bbf988c1210a4d42bb73985d0 src/admin/web/partials/overview-charts.html bd94e61e051a6bebe0afbda0a21aa36349c2067516b974986765555ed47455cc src/admin/web/partials/overview-metrics.html 8bb503677f51362dc3cc9522596affa65c5960ab5e44b1c935cb4abf85505429 src/admin/web/policy-presets.js @@ -346,10 +345,10 @@ f082588c35d981fc689542d4c12a7614638279335220d587fdee5d3fff822e80 src/admin/web/ 3776f72d7051af86ac5fbdd4581040dd88a424c0c6cde789301b032b159094d8 src/admin/web/vhosts/health.js b3239e67901f1796d7a974ade0796f2e3590ff8064628a5629b78c7f6ce2f32e src/admin/web/vhosts/protocol.js 8c3da49973c62333559b0e3588c02beb0b425c025eac5cfa82a1bb968f70d9dd src/admin/web/vhosts/rates.js -76f603802ad3e19005de583fcaac24b61b5bc79317894fca2fd9fd974b5f33fd src/admin/web/vhosts/render.js +3159bfe7edafe11ed6dfa5411cac80f99520fc1cd25e88c3132bce5c172befd9 src/admin/web/vhosts/render.js 90684f1bfb0e079438654e1f8c5b9ee1b4f74e49126a82c88768f3ae209a1875 src/admin/web/vhosts/routing.js 7be5a5fed5480b431d2eece59271c2567dd48592b9d7e65fdb30b4a28f58ce3a src/admin/web/vhosts/source.js -b6f06f16e4035d856f13a633e51fd6bd1de23b872fc1b47726557554ef2a8a42 src/admin/web/web-server-profiles.js +a6b50bd62b0396df7b0701b39dd362a9f5402bce8b7acca8fecb5b17fbce009e src/admin/web/web-server-profiles.js 31cc5bc08cb1d34cfbed206277eeed0f4dd09333de0ff0537bd67b404f1184de src/admin/web/web-server.js 36f11beed56711640bb56bb6f452bf76dec2ce4be6a57e8abc19560af477c870 src/alerts.rs 2d40c2cb32d7365df0c9cd6c8cb6f0483c7a799786c648f4836a0d9740c6c5ef src/auth/files/mod.rs @@ -380,8 +379,8 @@ ded4f445eec1caacd92fb1546f9eaeba1bc35fd164deb4d3142a64d0e9e261d9 src/balance/mo 5f9419176d5b927f8376d39b7dc4a6adf37b975835fedb35d82e7d6a2bb052fd src/balance/pool_selection.rs d789bf40cf9433e2fd16409d112210fe93154588b1ac9bddc9c7f78e1db14426 src/balance/pool_view.rs a361c341932ffd186c0b21356c91ab1fe8043f5020d40798266d15ae896a114e src/balance/tests.rs -f85b967a926e0acb9dec733d028bcc36f3292a488ac460772b9043901185fcf0 src/basic_auth/mod.rs -2e0ad80a3fce45e02e1fc3920c3f49a7af41953fa4b64ceb602a47e9f5508882 src/basic_auth/tests.rs +8a7a6ad2f8e0cbebf9c4c3dcd22bbecb6c2071c2d007b8b8a4de32854d5a4a41 src/basic_auth/mod.rs +8f8a53d32623f95533ba6392a369976093761d41d8176c55f70bb10eee6ac1f6 src/basic_auth/tests.rs d9c44f9be9e3855c2339d4867c164b35938474b0a970de887d3990f33779b03b src/cache/cache_regression_tests.rs 7def03ace07dc38a4806277d75b6ce673d33ddaaf1c4855fa0a3372be1cf9489 src/cache/cold.rs b75ff512a1c6344483e00d2c67578ceea6b5472c279da0246f3622daa68d7e16 src/cache/cold/cleanup.rs @@ -442,12 +441,12 @@ caf688a85edc57e92d9ab0cd480282d4a3ecffe210473cf7e3abaccf8c8cd7ce src/config/rou fa835ba4bf063c373defd95e7b37e95d8a281cfa8b8595f4c1fc0cf3988af3a5 src/config/snapshot.rs c56f696db4e37f5bbf7179e9a952aca8a89c81b4e479f9c79bb18a6f89cf5364 src/config/tests.rs f35de0ee1516ece6bbfd2b2a7db7d1e0f5048b0ec47cf2a3765dffb799abfd93 src/config/transport_tests.rs -a09f361d70510d6226f4dd6785e649c3dc01ccafc70a4c8b0dcd098e224129b7 src/db.rs +b8c1a8a8bad91734b6849e88c035a3d9683051d4a6dbbe17adad11c4f4109724 src/db.rs c290d0cb02dfa5d2c60ecabac1cfb20c8884e3d14cca1944906c6d8e677f1784 src/db/api_tokens.rs 892ec0e5985700cca399c861197f6c9d2f1c823d8d95b88abac9d27ae15a069a src/db/certificate_api.rs 5491dd7bb9b3fceac97c4dea63aba6d5c7abcb0fbd06e36ae986e00c79bc07d0 src/db/dashboard_presets.rs 2ff744223934685439374572b83fd639bb3eabdbac168bea4a6501a6e9ce0ee0 src/db/history.rs -c05a02618d476e4670b4f9930555f199cac776cdf09edb8fcc1a675695b8f99f src/db/tests.rs +fefe4896f91f41b7a9ad1f77560c10eb2b3ed989848d3d402cf00bf4948b9217 src/db/tests.rs dada314e1709e960eb2e225b4d10c3cd12606c62c4bc2c0220aec1ba133e4ade src/demo.rs d2ef07d1565569f520a6a8eb01f4ea9bb673499d038018d52e65fe95e800bb27 src/diagnostics.rs 045593a42a6e4f632e5052c655788f0843faa313fc929265b89509f6dfff91ed src/docker.rs @@ -501,7 +500,7 @@ c456b31ddd7a5c209073812b288f2cc150b5cdb0ed9372d4d1a9a84a74d706cd src/not_found/ c19998732c2d65b464f43d17a58644db5bcf7b4a6dd4c31a65a091c57692a5bb src/oidc/mod.rs c4dbe0f8ded237d45b6a3977bdc7544296e4408996815cae9e28af028419d0b7 src/oidc/tests.rs 992f49379e44361d98088d8f8ca1013d62846a54a5a35c089a5e0e1a9488e08d src/oidc/token.rs -9f853faba02c9a143d441946e839d5b604439ef0d5adab95fc9d074b7dc35489 src/pages/mod.rs +88aec79784c4307707d3c1489d6a4e878f83a7eec2ba7d0f2db98b88589fbc1f src/pages/mod.rs 3ebf39c7e7de2ad794625e67937991b65adcf4e8c9978061f21ad891b2238aaa src/pages/tests.rs 9840ec5b3786661084fefdced6694f3c099fef1e872e28fab9ef9a5cef29d141 src/policy/compile.rs 420d3e1133621a6bab8c15523cbd81712ea4b5d36c1390d52d5ef703164850c9 src/policy/engine.rs @@ -542,7 +541,7 @@ a91d0bdc5740beec921df50ad14a4e85de0a73d46c9626c9cfd37a7f8baca317 src/proxy/forw a1cea78b32c0c05e583f42c98d6387284fe096325a255e3df7f9b7051dad73dd src/proxy/forward/web_source.rs 3df1cd933c77e5390066e0bf3a4671a053b97ec1948c4a4204004312a3572c9d src/proxy/forward_entry.rs 9b25f5e3ea4443a63ee6f45d12e1957dd316fe8e85325fc00ea416faaab1025a src/proxy/h2_graceful.rs -3734ce8c3087d5906c412af872e83f1ed41816f121174db5b898aae49c2c5c53 src/proxy/headers/authority_tests.rs +9f4ac3cd82d8929be015c2a42a1934076e554d714cd0dd34636a9458ec552130 src/proxy/headers/authority_tests.rs e87437ccf80e50e0159d204dfdd1f8dc0739b6e375be192fce0af749810258cf src/proxy/headers/mod.rs af9b044761a56e8a6dc57f9d760b289ff4a6bf37db11dbfcd3ec4da5b8f426b6 src/proxy/headers/tests.rs 2bc63579975387c92a9459a9677b4a49e76df382b1ee19de12c8341a3ead57e8 src/proxy/identity.rs @@ -554,7 +553,7 @@ a57ea795430bf52d550083fef759c739f3821217aac465c0024aa1565b0727d1 src/proxy/requ 16f9ed2ff51879095e6f1a818b03a76a03072b4c8c30d55201cb3d8bf229bf1d src/proxy/types.rs 15df425be6c7ad379920399e9f4674e126668157d64c67f5055a2b7931d8dc48 src/proxy/upstream_helpers.rs 02b56b5a7133e08ab47c9da0fdf1a807d054b2ff95efa0936a0c1d690474ce87 src/proxy/web_cache_revalidation/mod.rs -22c715aeb5b41eded4dc285a352ebf9ff8875f1342d72c1bfaf54131d3317f1a src/proxy/web_cache_revalidation/tests.rs +7258d8cdc6ee0742ddf8a464994cdbca93b028e531be5605518276b2e06301a3 src/proxy/web_cache_revalidation/tests.rs 3d591201595a3b1e928ded20a8736477a47e5acc3bcbde158f7c17547ce155ba src/proxy/websocket.rs aa58bacc35458ac615680e774a235191f80abf0db978b68095571fce94c2b502 src/proxy/websocket/handshake.rs 02eae55007334a289c974c0a050ebe9360822574e5982950245a18e1af05a9fc src/proxy/websocket/http2_tests.rs @@ -656,11 +655,11 @@ d15716d8fa0d722e3189367fd395cac71c2f2a178335120a74a01696abc7cc04 src/web_server 92d2ab4d7ecb766bbc705f8eba94c1ca33347ffb84b36e0ad0eccfed5915473f src/web_server/filesystem.rs d4fec3682532b0f2d11a0aefcd024f69fb623a39922ddb6c528a2d2de265347d src/web_server/htaccess.rs a4d955e9225022a4402885cbbe9b03929a651acb8eac57d304dac297f075eb14 src/web_server/htaccess/model.rs -991a47ea75164c74277e159fdd34c4db11f9b35bbcddb8902e7a58523f856570 src/web_server/htaccess/parse.rs +66e5fafcb04dea31a799bdf330b668e88e35198dfaafeff1134c451a4c6e3fdc src/web_server/htaccess/parse.rs 5f25f62190e5743c3661895e00ffda59e1f7fa5074924a0c5db02789fa20ef69 src/web_server/htaccess/rewrite.rs 8ca74d9cc4470045301f70eb4a9fbabd0dbfe74434429148d2230df9f996c06c src/web_server/htaccess/tests.rs 7fe32af33b4d8e079ad724665aa1cfb62f6e98b9406b77168feaac55dac36137 src/web_server/metrics.rs -ee29a033d138001b9c304f28dbdf079031e58a0fd29d59c1834107be52a5fdbf src/web_server/mod.rs +2356ec4180ad2880766e77c1117ebc2aef0a90c6a47f8fac4a7ec757314318c0 src/web_server/mod.rs 709a672a0d210aae94f791de50ddbe0f902a1955c150ff35a3a575e352d9c198 src/web_server/request.rs d98c80663847d6d83073df074ebff65952755415574708abcc153bd8d3adfaa9 src/web_server/response.rs b38a1c9e648e3606a534ebdf74f6315863a326c6de1ca8edc433abe9c1fed7b4 src/web_server/response/file.rs @@ -669,8 +668,8 @@ e5f5fbe702f66bfcbcbc1d1f3cd3d89bdbb929bb86aed94868a2a06a4b9e59e3 src/web_server 7da903c1a69be0ae6b85772b3208c518679efa8ed9d3e98adb694483518156b6 src/web_server/response/headers.rs 2665d4eac9a6430d68224874784cb65d9b9d424353af77735caf044401d08cb4 src/web_server/routing.rs 9e584eb4455a18641c2c89f9e9725745c93f32877abf0f0f2fbea9e3d5ef38c3 src/web_server/security.rs -0877d32e3315356147f417faf1841698513763435de958d9bb9824b200685a14 src/web_server/serve.rs -6f382b8a7afeb2c5b5bb0b9f26d5251a9463466eb16516b2d12b277492ee634b src/web_server/tests.rs +ca7fbabd87fa117f6cfd9cccb2375396432a999f15d4e9af0f6f3420eb2ae57f src/web_server/serve.rs +8b20e20a967c75b9510c48fad1a9465b55012b2fbc46587e473337b36cb5f397 src/web_server/tests.rs f00743af2cf4a5952caef7a1dcf68e7817b5599a252a9973e1c22045517c0b0e tests/fixtures/argon2id.json 9540e9a904455a2190c2d0a32b47b1345976e4c4618767ed2b55898d13da9987 tests/fixtures/balance_rendezvous_vectors.txt affb5c728d2d2bd58807c080f22ac17575e06486c7cca38dc13cf58ad01873ae tests/fixtures/routing_conditions_cases.json diff --git a/docs/DASHBOARD.md b/docs/DASHBOARD.md index cdf623e..2ea40e2 100644 --- a/docs/DASHBOARD.md +++ b/docs/DASHBOARD.md @@ -31,6 +31,8 @@ In the **Backends** table with **Table density: Ultra compact**, the backend nam In **Overview → Backends → Columns**, enable **Responsive charts** to let the Requests, Latency and Traffic sparklines expand into the available table width. The charts also shrink when the card, browser window or interface scale changes; numeric values and a minimum chart width remain visible. On narrow screens the table still scrolls horizontally if needed. Chart height follows the selected table density. Turning the option off (the default, including existing accounts) restores the fixed chart widths. The setting is saved per administrator immediately (`backend_table_responsive_charts` in `/api/preferences`). +Live status refreshes update the **Backends** table in place. The filter buttons, expansion controls and unchanged rows remain mounted, so refreshing counters does not clear keyboard focus or reset the table's scroll position. Sorting, searching and changing columns still take effect immediately; saved preferences and the update interval are unchanged. + The Overview history sample count is saved in the browser immediately when the selection changes; no separate confirmation button is required. The sidebar application-status indicator runs a lightweight self-check from the live status already used by the dashboard. Green means healthy, amber means attention is needed, and red means a problem was detected; click it to see API, listener, backend and logging details. diff --git a/docs/FASTCGI.md b/docs/FASTCGI.md index 2efff58..8fdb671 100644 --- a/docs/FASTCGI.md +++ b/docs/FASTCGI.md @@ -14,7 +14,7 @@ Select **Web Server → Web Service → PHP-FPM / FastCGI → Handler** (or edit All handlers support Unix sockets (`unix:/absolute/path.sock`) and local TCP (`tcp:127.0.0.1:port` or `tcp:[::1]:port`). TCP is deliberately restricted to loopback. FastCGI must **not** be exposed on a public interface. The backend process must already be running, and the RustProxy service account must be able to connect to its socket. The configured `php.extensions` determine which *existing files* are executable; everything else follows static-file policy, except that a `fcgiwrap` Web Service deliberately refuses to serve ordinary files and directory listings to avoid leaking CGI source or adjacent configuration. PHP extensions can only be assigned to `php_fpm`; `PHP_VALUE` and `PHP_ADMIN_VALUE` are PHP-FPM-only. -The existing **PHP-FPM profiles** section also stores the new handler choices without changing existing profile IDs. Create a separate Web Service/profile for different document roots, handler types, sockets, or trust boundaries. Each Web Service has one FastCGI handler; combine several services under one domain with **Vhost → Custom locations** rather than attempting to paste Nginx `location` or `fastcgi_pass` directives. +The existing **PHP-FPM profiles** section also stores the new handler choices without changing existing profile IDs. The editor generates a unique ID from the profile name; use **Change** to provide a manual ID when creating a profile. Saved IDs are read-only because Web Services refer to them. Create a separate Web Service/profile for different document roots, handler types, sockets, or trust boundaries. Each Web Service has one FastCGI handler; combine several services under one domain with **Vhost → Custom locations** rather than attempting to paste Nginx `location` or `fastcgi_pass` directives. ## How paths are mapped diff --git a/docs/MIGRATION.md b/docs/MIGRATION.md index fc00b8b..b50913d 100644 --- a/docs/MIGRATION.md +++ b/docs/MIGRATION.md @@ -10,7 +10,9 @@ This guide covers upgrades that need operator action and the included Nginx Prox 4. Read release notes for cache compatibility, configuration changes, API token permissions and listeners requiring restart. 5. Update with a maintenance window. Test production DNS, TLS, Vhost routes, access, cache behavior, PHP, Docker, Streams, logging and backup recovery before considering the upgrade complete. -A managed install uses `update.sh`; an unmanaged source-tree install must follow the supplied stopped upgrade path. Never overwrite an active database by extracting a ZIP over live private data. RustProxy normally applies forward SQLite schema migrations as needed; do not manually edit internal migration tables. +A managed install uses `update.sh`; an unmanaged source-tree install must follow the supplied stopped upgrade path. Never overwrite an active database by extracting a ZIP over live private data. RustProxy applies only the SQLite schema migrations newer than the database's `PRAGMA user_version`, inside one transaction. If a migration fails, the schema version and data changes roll back together and startup fails without resetting the database. Do not change `user_version` manually. + +The existing `admin_preferences` table is upgraded from a 4 KiB to a 64 KiB document limit by a one-time copy-and-rename migration (version 12). SQLite cannot alter a column's `CHECK` constraint in place; the original preference row and its administrator foreign key are preserved. Databases already on schema version 12 are not rebuilt on restart. Keep a verified backup before updating a production installation. ## Notable compatibility points diff --git a/docs/PHP_FPM.md b/docs/PHP_FPM.md index 04872d8..5812f4e 100644 --- a/docs/PHP_FPM.md +++ b/docs/PHP_FPM.md @@ -8,6 +8,8 @@ Install and start PHP-FPM independently, configure the application files and cre In **Web Server → PHP-FPM profiles** create a reusable profile, or set PHP options in one Web Service. Select a socket such as `unix:/run/php/app.sock` or a reachable TCP endpoint (use the syntax accepted by the editor); enable PHP, choose extensions (default `.php`) and set request/connect timeouts and concurrency. Attach the profile to a Web Service and publish that service using a Vhost. +The shared profile editor generates a unique profile ID from the display name (for example, `My PHP App` → `my-php-app`). Use **Change** to enter an explicit ID while creating the profile. Existing profile IDs cannot be edited because Web Services refer to them; you can rename a profile without changing those links. + ## Important settings | Setting | Effect | diff --git a/langs/en_US.json b/langs/en_US.json index f6a7d5d..17bb9bb 100644 --- a/langs/en_US.json +++ b/langs/en_US.json @@ -2639,6 +2639,8 @@ "phpProfileNew": "New PHP-FPM profile", "phpProfileId": "Profile ID", "phpProfileName": "Profile name", + "phpProfileIdHelp": "Generated automatically from the profile name. Select Change to edit it when creating a profile; saved IDs stay fixed because Web Services reference them.", + "phpProfileNameHelp": "Name shown in the profile list and Web Service selector. Changing it does not change the profile ID.", "phpProfileAdminValues": "PHP administrator INI overrides (PHP_ADMIN_VALUE)", "phpProfileInUse": "Profile is used by", "phpProfileDelete": "Delete this PHP-FPM profile?", diff --git a/langs/pl_pl.json b/langs/pl_pl.json index 5bbb26b..d676c4c 100644 --- a/langs/pl_pl.json +++ b/langs/pl_pl.json @@ -2639,6 +2639,8 @@ "phpProfileNew": "Nowy profil PHP-FPM", "phpProfileId": "ID profilu", "phpProfileName": "Nazwa profilu", + "phpProfileIdHelp": "ID tworzy się automatycznie z nazwy profilu. Kliknij Zmień, aby ustawić je ręcznie podczas tworzenia. Zapisane ID pozostaje stałe, ponieważ odwołują się do niego usługi.", + "phpProfileNameHelp": "Nazwa widoczna na liście profili i przy wyborze w Web Service. Jej zmiana nie zmienia ID profilu.", "phpProfileAdminValues": "Administracyjne ustawienia PHP (PHP_ADMIN_VALUE)", "phpProfileInUse": "Profil jest używany przez", "phpProfileDelete": "Usunąć profil PHP-FPM?", diff --git a/scripts/resolve_dependencies_0312.sh b/scripts/resolve_dependencies_0312.sh deleted file mode 100755 index 7d11d18..0000000 --- a/scripts/resolve_dependencies_0312.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env bash -# Run on a clean Rust 1.99+ build machine with registry and Swagger asset access. -set -euo pipefail -ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" -cd "$ROOT" -if ! command -v cargo >/dev/null 2>&1 || ! command -v rustc >/dev/null 2>&1; then - printf 'Rust 1.99+ and Cargo are required; no lockfile was regenerated.\n' >&2 - exit 127 -fi -python3 scripts/preflight.py -if [[ "$(python3 scripts/version.py)" != '0.31.8' ]]; then - printf 'Expected RustProxy 0.31.8 sources.\n' >&2 - exit 1 -fi -printf 'Toolchain: '; rustc --version -cargo update -cargo metadata --locked --format-version 1 --no-deps >/dev/null -cargo fmt --all -- --check -cargo clippy --locked --all-targets -- -D warnings -./dev.sh check -./dev.sh test -./dev.sh release -if cargo audit --version >/dev/null 2>&1; then - cargo audit -else - printf 'NOTICE: cargo-audit is unavailable; install it and run cargo audit before release.\n' >&2 -fi -printf 'Source and locked Rust build complete. Still required: live H1/H2/H3, auth/TLS, SQLite, cache, UI and performance acceptance.\n' diff --git a/src/acl/dynamic/mod.rs b/src/acl/dynamic/mod.rs index c06fd52..fbc364d 100644 --- a/src/acl/dynamic/mod.rs +++ b/src/acl/dynamic/mod.rs @@ -53,7 +53,10 @@ pub(crate) fn statuses(config: &Config) -> Result> { let diagnostics = DIAGNOSTICS.load(); let cache = CACHE.load(); let now = Instant::now(); - Ok(names.into_iter().map(|name| status_for_name(name, &cache, &diagnostics, now)).collect()) + Ok(names + .into_iter() + .map(|name| status_for_name(name, &cache, &diagnostics, now)) + .collect()) } fn status_for_name( @@ -184,7 +187,9 @@ fn validate_addresses(mut ips: Vec) -> std::result::Result MAX_ADDRESSES { - return Err(format!("DNS response exceeds the limit of {MAX_ADDRESSES} unique addresses")); + return Err(format!( + "DNS response exceeds the limit of {MAX_ADDRESSES} unique addresses" + )); } if ips .iter() @@ -206,7 +211,9 @@ async fn resolve(name: String) -> (String, std::result::Result Err(format!("DNS lookup timed out after {LOOKUP_SECONDS} seconds")), + Err(_) => Err(format!( + "DNS lookup timed out after {LOOKUP_SECONDS} seconds" + )), Ok(Err(error)) => Err(format!("system DNS resolver returned: {error}")), Ok(Ok(sockets)) => validate_addresses(sockets.map(|socket| socket.ip()).collect()), }; @@ -265,19 +272,35 @@ pub(crate) async fn poll_loop(app: Weak, shutdown: Cancella let checked_unix_ms = checked_unix_ms(); match result { Ok(value) => { - if previous.get(&hostname).is_none_or(|old| old.ips != value.ips) - || previous_diagnostics.get(&hostname).is_some_and(|old| old.error.is_some()) + if previous + .get(&hostname) + .is_none_or(|old| old.ips != value.ips) + || previous_diagnostics + .get(&hostname) + .is_some_and(|old| old.error.is_some()) { tracing::info!(hostname = %hostname, addresses = ?value.ips, "ACL DDNS resolved; allow rule matches only these client addresses"); } addresses.insert(hostname.clone(), value); - diagnostics.insert(hostname, DnsDiagnostic { checked_unix_ms, error: None }); + diagnostics.insert( + hostname, + DnsDiagnostic { + checked_unix_ms, + error: None, + }, + ); } Err(error) => { tracing::warn!(hostname = %hostname, reason = %error, "ACL DDNS resolution failed; hostname allows no client addresses"); - diagnostics.insert(hostname, DnsDiagnostic { checked_unix_ms, error: Some(error) }); + diagnostics.insert( + hostname, + DnsDiagnostic { + checked_unix_ms, + error: Some(error), + }, + ); } } } diff --git a/src/acl/dynamic/tests.rs b/src/acl/dynamic/tests.rs index 161751d..af81b7a 100644 --- a/src/acl/dynamic/tests.rs +++ b/src/acl/dynamic/tests.rs @@ -94,8 +94,14 @@ mod tests { }); let names = configured_hostnames(&config).unwrap(); assert_eq!(names, vec!["my-home.example"]); - let empty = HashMap::new(); - let pending = status_for_name(names[0].clone(), &empty, &empty, Instant::now()); + let empty_cache: HashMap = HashMap::new(); + let empty_diagnostics: HashMap = HashMap::new(); + let pending = status_for_name( + names[0].clone(), + &empty_cache, + &empty_diagnostics, + Instant::now(), + ); assert_eq!(pending.state, "pending"); let ip: IpAddr = "192.0.2.10".parse().unwrap(); let entries = HashMap::from([( @@ -130,7 +136,7 @@ mod tests { error: Some("NXDOMAIN".into()), }, )]); - let failed = status_for_name(names[0].clone(), &empty, &failure, Instant::now()); + let failed = status_for_name(names[0].clone(), &empty_cache, &failure, Instant::now()); assert_eq!(failed.state, "failed"); assert_eq!(failed.error.as_deref(), Some("NXDOMAIN")); } diff --git a/src/admin/openapi.json b/src/admin/openapi.json index bbcd61a..0c78060 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.42.3", + "version": "0.42.4", "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": [ diff --git a/src/admin/web/app/preferences.js b/src/admin/web/app/preferences.js index d5efbbe..57abfdb 100644 --- a/src/admin/web/app/preferences.js +++ b/src/admin/web/app/preferences.js @@ -316,14 +316,29 @@ for (const [id, direction] of [["dashboard-widget-scroll-prev", -1], ["dashboard } function refreshChartStylePalette(active = adminPreferences?.chart_style || "default") { const target = $("chart-style-palette"); if (!target || !languagePacks.size) return; - const buttons = [...ADMIN_CHART_STYLES].map(style => { - const button = el("button", undefined, "chart-style-choice"); button.type = "button"; button.dataset.chartPreset = style; button.classList.toggle("active", style === active); button.setAttribute("aria-pressed", String(style === active)); - const swatches = el("span", undefined, "chart-style-swatches"); for (let i = 1; i <= 4; i++) swatches.append(el("i")); - button.append(swatches, el("span", t(CHART_STYLE_KEYS[style]))); button.addEventListener("click", () => { const select = $("ui-chart-style"); if (!select) return; select.value = style; select.dispatchEvent(new Event("change", { bubbles: true })); }); return button; - }); - target.replaceChildren(...buttons); + // Keep the selected swatch button mounted; replacing it on click loses focus. + for (const style of ADMIN_CHART_STYLES) { + let button = [...target.children].find(node => node.dataset.chartPreset === style); + if (!button) { + button = el("button", undefined, "chart-style-choice"); button.type = "button"; button.dataset.chartPreset = style; + const swatches = el("span", undefined, "chart-style-swatches"); for (let i = 1; i <= 4; i++) swatches.append(el("i")); + button.append(swatches, el("span")); + button.addEventListener("click", () => { const select = $("ui-chart-style"); if (!select) return; select.value = style; select.dispatchEvent(new Event("change", { bubbles: true })); }); + target.append(button); + } + button.classList.toggle("active", style === active); + button.setAttribute("aria-pressed", String(style === active)); + const caption = button.lastElementChild, label = t(CHART_STYLE_KEYS[style]); + if (caption.textContent !== label) caption.textContent = label; + } +} +function refreshAppearanceUi({ palette = true, widgets = true, refresh = true, presets = true, search = true } = {}) { + if (palette) refreshChartStylePalette(); + if (widgets) renderDashboardWidgetSettings(); + if (refresh) renderRefreshPreferences(adminPreferences?.refresh); + if (presets) window.rustProxyDashboardLayout?.refresh?.(); + if (search) window.rustProxySettings?.refreshSearch?.(); } -function refreshAppearanceUi() { refreshChartStylePalette(); renderDashboardWidgetSettings(); renderRefreshPreferences(adminPreferences?.refresh); window.rustProxyDashboardLayout?.refresh?.(); window.rustProxySettings?.refreshSearch?.(); } function formatDateTime(value) { const date = value instanceof Date ? value : new Date(value); if (Number.isNaN(date.getTime())) return String(date); return formatDateParts(date, true, (adminPreferences?.time_format || "24h") === "12h"); } function formatTime(value) { const date = value instanceof Date ? value : new Date(value); if (Number.isNaN(date.getTime())) return String(date); return formatDateParts(date, false, (adminPreferences?.time_format || "24h") === "12h"); } function applyAdminPreferences(value, cache = true) { @@ -336,10 +351,23 @@ function applyAdminPreferences(value, cache = true) { const savedHeights = normalizeDashboardWidgetHeights(value.dashboard_widget_heights); const savedAutoFit = value.dashboard_auto_fit !== false; const savedPositions = normalizeDashboardWidgetPositions(value.dashboard_widget_positions); - window.rustProxyOverviewRows?.setPositions?.(editing ? editing.positions : savedPositions); - window.rustProxyOverviewRows?.setAutoFit?.(editing ? editing.autoFit !== false : savedAutoFit); - if (editing) applyDashboardLayout(editing.order, editing.hidden, editing.sizes, editing.heights); - else applyDashboardLayout(savedOrder, savedHidden, savedSizes, savedHeights); + // A saved table column (or any unrelated preference) must not re-apply the + // dashboard layout. Moving its cards detaches focused controls and shifts + // the page, even if the selected dashboard layout has not changed. + const layoutChanged = !adminPreferences || JSON.stringify([ + adminPreferences.dashboard_widgets, adminPreferences.dashboard_hidden_widgets, + adminPreferences.dashboard_widget_sizes, adminPreferences.dashboard_widget_heights, + adminPreferences.dashboard_auto_fit, adminPreferences.dashboard_widget_positions, + ]) !== JSON.stringify([ + savedOrder, savedHidden, savedSizes, savedHeights, savedAutoFit, savedPositions, + ]); + if (layoutChanged) { + window.rustProxyOverviewRows?.setPositions?.(editing ? editing.positions : savedPositions); + window.rustProxyOverviewRows?.setAutoFit?.(editing ? editing.autoFit !== false : savedAutoFit); + if (editing) applyDashboardLayout(editing.order, editing.hidden, editing.sizes, editing.heights); + else applyDashboardLayout(savedOrder, savedHidden, savedSizes, savedHeights); + } + const languageChanged = !adminPreferences || adminPreferences.language !== normalizeAdminLanguage(value.language); const normalized = { ...value, refresh: normalizeRefreshPreferences(value.refresh), @@ -347,18 +375,30 @@ function applyAdminPreferences(value, cache = true) { time_format: applyAdminTimeFormat(value.time_format), chart_style: applyAdminChartStyle(value.chart_style), chart_axes: applyAdminChartAxes(value.chart_axes), chart_tooltips: applyAdminChartTooltips(value.chart_tooltips), interface_icons: applyAdminInterfaceIcons(value.interface_icons), logo_animation: applyAdminLogoAnimation(value.logo_animation), stable_dialog_position: applyAdminStableDialogPosition(value.stable_dialog_position), switch_controls: applyAdminSwitchControls(value.switch_controls), button_style: applyAdminButtonStyle(value.button_style), corner_style: applyAdminCornerStyle(value.corner_style, cache), table_density: applyAdminTableDensity(value.table_density), dashboard_density: applyAdminDashboardDensity(value.dashboard_density), dashboard_widgets: savedOrder, dashboard_hidden_widgets: savedHidden, dashboard_widget_sizes: savedSizes, dashboard_widget_heights: savedHeights, dashboard_widget_positions: savedPositions, dashboard_auto_fit: savedAutoFit, }; + const changed = (...keys) => !adminPreferences || keys.some(key => + JSON.stringify(adminPreferences[key]) !== JSON.stringify(normalized[key])); + const refreshChanged = changed("refresh"); + const paletteChanged = changed("chart_style") || languageChanged; + const widgetSettingsChanged = layoutChanged || languageChanged; + const sidebarChanged = changed("sidebar_collapsed"); + const poolOrVhostChanged = changed("backend_table_columns", "backend_table_sort", "backend_table_descending", "backend_table_responsive_charts", "vhost_list_sort", "vhost_list_descending"); + const dockerChanged = changed("docker_vhost_sort", "docker_vhost_descending"); + const redirectChanged = changed("redirect_list_sort", "redirect_list_descending"); + const notfoundChanged = changed("notfound_list_sort", "notfound_list_descending"); + const streamChanged = changed("stream_list_sort", "stream_list_descending"); adminPreferences = normalized; - window.rustProxyRefresh?.update(normalized.refresh); - renderRefreshPreferences(normalized.refresh); - window.rustProxyVhosts?.applyPreferences(normalized); - window.rustProxyDocker?.applyPreferences(normalized); - window.rustProxyRedirects?.applyPreferences(normalized); - window.rustProxyNotFound?.applyPreferences(normalized); - window.rustProxyStreams?.applyPreferences(normalized); - if (languagePacks.size) translate(); - refreshAppearanceUi(); - window.rustProxySidebar?.applyPreference?.(normalized.sidebar_collapsed === true); - window.rustProxyOverviewRows?.reveal?.(); + if (refreshChanged) window.rustProxyRefresh?.update(normalized.refresh); + if (poolOrVhostChanged) window.rustProxyVhosts?.applyPreferences(normalized); + if (dockerChanged) window.rustProxyDocker?.applyPreferences(normalized); + if (redirectChanged) window.rustProxyRedirects?.applyPreferences(normalized); + if (notfoundChanged) window.rustProxyNotFound?.applyPreferences(normalized); + if (streamChanged) window.rustProxyStreams?.applyPreferences(normalized); + // Only a real language change requires translating/re-rendering the whole panel. + if (languagePacks.size && languageChanged) translate(); + else refreshAppearanceUi({ palette: paletteChanged, widgets: widgetSettingsChanged, + refresh: refreshChanged, presets: layoutChanged, search: false }); + if (sidebarChanged) window.rustProxySidebar?.applyPreference?.(normalized.sidebar_collapsed === true); + if (layoutChanged) window.rustProxyOverviewRows?.reveal?.(); return normalized; } try { applyAdminTheme(localStorage.getItem("rp-theme") || "dark", false); } catch { applyAdminTheme("dark", false); } diff --git a/src/admin/web/css/10-base.css b/src/admin/web/css/10-base.css index 33926d0..7f162eb 100644 --- a/src/admin/web/css/10-base.css +++ b/src/admin/web/css/10-base.css @@ -1769,6 +1769,27 @@ html[data-interface-icons="true"] :is(button, a, summary)>svg.ui-icon { min-width: 0; } +#php-fpm-profiles-list .fastcgi-profile-editor>label.fastcgi-profile-identity { + display: flex; + flex-direction: column; + align-items: stretch; + grid-row: auto; + gap: 5px; +} + +#php-fpm-profiles-list .fastcgi-profile-identity>span:first-child { + display: block; + min-height: 1em; + color: var(--text); +} + +#php-fpm-profiles-list .fastcgi-profile-identity-help { + display: block; + color: var(--muted); + line-height: 1.45; +} + + #php-fpm-profiles-list .fastcgi-profile-editor .fastcgi-profile-php-heading { padding-top: 6px; border-top: 1px solid var(--line); diff --git a/src/admin/web/file-logs.js b/src/admin/web/file-logs.js index 48dbe29..b5e870d 100644 --- a/src/admin/web/file-logs.js +++ b/src/admin/web/file-logs.js @@ -12,9 +12,6 @@ let availableColumns = new Set(defaultColumnIds); let visibleColumns = new Set(defaultColumnIds); let sortBy = "time", sortDescending = true, pendingRefresh = false; - - // Sources are shown per log (a site with all its rotations); the File picker - // narrows to one rotation. Rotation 0 is the file being written. let groups = new Map(), statusFilter = "", eventFilter = ""; const SCOPE_ORDER = ["vhost", "redirect", "host404", "unmatched", "access", "error"]; const sourceSelect = () => $("file-log-source"); @@ -75,7 +72,6 @@ options.push(optgroup); } select.replaceChildren(...options); - // A file id (older bookmark) selects its group. const owner = [...groups.values()].find(group => group.id === previous || group.files.some(file => file.id === previous)); select.value = owner ? owner.id : "all"; renderFiles(owner && owner.files.some(file => file.id === previousFile) ? previousFile : owner?.files.some(file => file.id === previous) ? previous : "all"); @@ -175,40 +171,68 @@ function syncHeaders() { const row = $("file-logs-table-head").querySelector("tr"); const headers = orderedColumns().filter(id => visibleColumns.has(id)).map(id => { - const header = el("th"); header.dataset.fileLogColumn = id; + let header = [...row.children].find(node => node.dataset.fileLogColumn === id); + if (!header) { + header = el("th"); header.dataset.fileLogColumn = id; + const button = el("button", undefined, "file-log-sort-button"); button.type = "button"; + const caption = el("span"); + const key = specialLabels.get(id); if (key) caption.dataset.i18n = key; + const arrow = el("span", undefined, "file-log-sort-indicator"); arrow.setAttribute("aria-hidden", "true"); + button.addEventListener("click", () => { + sortDescending = sortBy === id ? !sortDescending : false; + sortBy = id; selectedIndex = null; offset = 0; + syncHeaders(); void savePreferences(); void refresh(true); + }); + button.append(caption, arrow); header.append(button); + } header.setAttribute("aria-sort", sortBy === id ? (sortDescending ? "descending" : "ascending") : "none"); - const button = el("button", undefined, "file-log-sort-button"); button.type = "button"; - const caption = el("span", columnLabel(id)); - const key = specialLabels.get(id); if (key) caption.dataset.i18n = key; - const arrow = el("span", sortBy === id ? (sortDescending ? "↓" : "↑") : "↕", "file-log-sort-indicator"); - arrow.setAttribute("aria-hidden", "true"); + const button = header.firstElementChild; + const caption = button.firstElementChild, title = columnLabel(id); + if (caption.textContent !== title) caption.textContent = title; + const arrow = button.lastElementChild, symbol = sortBy === id ? (sortDescending ? "↓" : "↑") : "↕"; + if (arrow.textContent !== symbol) arrow.textContent = symbol; const willDescend = sortBy === id ? !sortDescending : false; - button.title = `${t(willDescend ? "fileLogsSortDescending" : "fileLogsSortAscending")}: ${columnLabel(id)}`; + button.title = `${t(willDescend ? "fileLogsSortDescending" : "fileLogsSortAscending")}: ${title}`; button.setAttribute("aria-label", button.title); - button.addEventListener("click", () => { - sortDescending = sortBy === id ? !sortDescending : false; - sortBy = id; selectedIndex = null; offset = 0; - syncHeaders(); void savePreferences(); void refresh(true); - }); - button.append(caption, arrow); header.append(button); return header; }); - row.replaceChildren(...headers); + let cursor = row.firstElementChild; + for (const header of headers) { + if (header === cursor) cursor = cursor.nextElementSibling; + else row.insertBefore(header, cursor); + } + while (cursor) { const next = cursor.nextElementSibling; cursor.remove(); cursor = next; } } function syncColumnPicker() { const picker = $("file-log-column-options"); - picker.replaceChildren(...orderedColumns().map(id => { - const label = el("label", undefined, "check log-column-option"); - const input = document.createElement("input"); input.type = "checkbox"; input.checked = visibleColumns.has(id); input.dataset.column = id; - const text = el("span", columnLabel(id)); - const key = specialLabels.get(id); if (key) text.dataset.i18n = key; - input.addEventListener("change", () => { - if (!input.checked && visibleColumns.size === 1) { input.checked = true; toast(t("fileLogsColumnsRequired"), true); return; } - if (input.checked) visibleColumns.add(id); else visibleColumns.delete(id); - syncHeaders(); renderRows(); void savePreferences(); - }); - label.append(input, text); return label; - })); + const ordered = orderedColumns(); + for (const id of ordered) { + let input = [...picker.querySelectorAll("input[data-column]")].find(node => node.dataset.column === id); + if (!input) { + const label = el("label", undefined, "check log-column-option"); + input = document.createElement("input"); input.type = "checkbox"; input.dataset.column = id; + const text = el("span"); + const key = specialLabels.get(id); if (key) text.dataset.i18n = key; + input.addEventListener("change", () => { + if (!input.checked && visibleColumns.size === 1) { input.checked = true; toast(t("fileLogsColumnsRequired"), true); return; } + if (input.checked) visibleColumns.add(id); else visibleColumns.delete(id); + syncHeaders(); renderRows(); void savePreferences(); + }); + label.append(input, text); picker.append(label); + } + input.checked = visibleColumns.has(id); + const caption = input.nextElementSibling, text = columnLabel(id); + if (caption.textContent !== text) caption.textContent = text; + } + + + let cursor = picker.firstElementChild; + for (const id of ordered) { + const label = [...picker.children].find(node => node.querySelector("input")?.dataset.column === id); + if (label === cursor) cursor = cursor.nextElementSibling; + else picker.insertBefore(label, cursor); + } + while (cursor) { const next = cursor.nextElementSibling; cursor.remove(); cursor = next; } } function applyPreferences(preferences) { const selected = Array.isArray(preferences?.file_log_columns) @@ -277,11 +301,14 @@ } function renderRows(entries = currentEntries) { + const body = $("file-log-rows"), focusedRow = document.activeElement?.closest?.("tr[data-file-log-entry-index]"); + const focusedIndex = focusedRow && body.contains(focusedRow) ? Number(focusedRow.dataset.fileLogEntryIndex) : -1; + const focusedEntry = focusedIndex >= 0 ? currentEntries[focusedIndex] : null; currentEntries = entries; const ids = orderedColumns().filter(id => visibleColumns.has(id)); const nodes = []; entries.forEach((entry, index) => { - const row = el("tr"); row.tabIndex = 0; row.classList.toggle("selected", selectedIndex === index); + const row = el("tr"); row.tabIndex = 0; row.dataset.fileLogEntryIndex = String(index); row.classList.toggle("selected", selectedIndex === index); const status = Number(entry.status) || 0; if (status >= 100) row.dataset.statusClass = `${Math.floor(status / 100)}xx`; if (entry.event && entry.event !== "request") row.dataset.event = entry.event; row.setAttribute("aria-expanded", selectedIndex === index ? "true" : "false"); @@ -298,7 +325,11 @@ row.addEventListener("keydown", event => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); select(); } }); nodes.push(row); if (selectedIndex === index) nodes.push(detailRow(entry)); }); - $("file-log-rows").replaceChildren(...nodes); + preserveScrollAnchor(() => body.replaceChildren(...nodes)); + + if (focusedIndex >= 0 && entries[focusedIndex] === focusedEntry) { + body.querySelector(`tr[data-file-log-entry-index="${focusedIndex}"]`)?.focus({ preventScroll: true }); + } $("file-logs-empty").hidden = entries.length !== 0; } function queryString() { @@ -344,7 +375,7 @@ } catch (error) { toast(error.message, true); } finally { busy = false; $("file-logs-refresh").disabled = false; if (pendingRefresh) { pendingRefresh = false; void refresh(); } } } - // Status line: what is shown, the time range and which files were read. + function renderSummary(value) { const summary = $("file-log-summary"); summary.replaceChildren(); const from = lastTotal ? offset + 1 : 0, to = Math.min(offset + currentLimit(), lastTotal); @@ -409,7 +440,6 @@ for (const chip of document.querySelectorAll("#file-log-chips .file-log-chip")) { chip.addEventListener("click", () => { statusFilter = chip.dataset.status || ""; eventFilter = chip.dataset.event || ""; syncChips(); void refresh(true); }); } - // Search syntax help opens inline under the search field (works on phones too). const syntaxToggle = $("file-log-syntax-toggle"), syntax = $("file-log-syntax"); syntaxToggle.addEventListener("click", () => { syntax.hidden = !syntax.hidden; syntaxToggle.setAttribute("aria-expanded", String(!syntax.hidden)); syntaxToggle.classList.toggle("active", !syntax.hidden); }); for (const example of syntax.querySelectorAll(".file-log-syntax-examples button")) { diff --git a/src/admin/web/management.js b/src/admin/web/management.js index 6b133f4..e693f98 100644 --- a/src/admin/web/management.js +++ b/src/admin/web/management.js @@ -201,17 +201,23 @@ } function syncColumnPicker() { const picker = $("log-column-options"); - picker.replaceChildren(...columns.map(column => { - const label = el("label", undefined, "check log-column-option"); - const input = document.createElement("input"); input.type = "checkbox"; input.checked = visibleColumns.has(column.id); input.dataset.column = column.id; - const text = el("span", t(column.label)); text.dataset.i18n = column.label; - input.addEventListener("change", () => { - if (!input.checked && visibleColumns.size === 1) { input.checked = true; toast(t("logColumnsRequired"), true); return; } - if (input.checked) visibleColumns.add(column.id); else visibleColumns.delete(column.id); - syncHeaders(); render(); void savePreferences(); - }); - label.append(input, text); return label; - })); + for (const column of columns) { + let input = [...picker.querySelectorAll("input[data-column]")].find(node => node.dataset.column === column.id); + if (!input) { + const label = el("label", undefined, "check log-column-option"); + input = document.createElement("input"); input.type = "checkbox"; input.dataset.column = column.id; + const caption = el("span"); caption.dataset.i18n = column.label; + input.addEventListener("change", () => { + if (!input.checked && visibleColumns.size === 1) { input.checked = true; toast(t("logColumnsRequired"), true); return; } + if (input.checked) visibleColumns.add(column.id); else visibleColumns.delete(column.id); + syncHeaders(); render(); void savePreferences(); + }); + label.append(input, caption); picker.append(label); + } + input.checked = visibleColumns.has(column.id); + const caption = input.nextElementSibling, label = t(column.label); + if (caption.textContent !== label) caption.textContent = label; + } } function applyPreferences(preferences) { if (!preferences) return; diff --git a/src/admin/web/vhosts/render.js b/src/admin/web/vhosts/render.js index 9324908..ab40120 100644 --- a/src/admin/web/vhosts/render.js +++ b/src/admin/web/vhosts/render.js @@ -115,8 +115,10 @@ function refreshVhostBackendPopup(status = latestStatus) { } if (!list.children.length) list.append(el("li", t("vhBackendPopupEmpty"), "fine")); const foot = el("p", t("vhBackendPopupHint"), "fine vhost-backend-popup-hint"); + const closeFocused = current.node.querySelector(".vhost-backend-popup-close") === document.activeElement; current.node.replaceChildren(headingRow, list, foot); current.node.setAttribute("aria-labelledby", heading.id); + if (closeFocused) headingRow.querySelector(".vhost-backend-popup-close")?.focus({ preventScroll: true }); positionVhostBackendPopup(); } function toggleVhostBackendPopup(id, trigger, backendId = null) { @@ -176,12 +178,17 @@ function syncVhostSortDirection() { control.setAttribute("aria-label", t(vhostListPrefs.descending ? "backendSortDescending" : "backendSortAscending")); } function applyPreferences(preferences) { - // A queued local change must survive the response to an earlier save. - if (!poolPreferenceSaveQueued) poolTablePrefs = normalizePoolTablePrefs(preferences); - vhostListPrefs = normalizeVhostListPrefs(preferences); + // Updating backend columns should never reconstruct the unrelated Vhost list. + // Keep any newer local column change while an earlier write is in flight. + const nextPool = poolPreferenceSaveQueued ? poolTablePrefs : normalizePoolTablePrefs(preferences); + const nextVhost = normalizeVhostListPrefs(preferences); + const poolChanged = JSON.stringify(nextPool) !== JSON.stringify(poolTablePrefs); + const vhostChanged = JSON.stringify(nextVhost) !== JSON.stringify(vhostListPrefs); + poolTablePrefs = nextPool; vhostListPrefs = nextVhost; const poolSort = $("pool-sort"); if (poolSort) poolSort.value = poolTablePrefs.sort; const vhostSort = $("vhost-sort"); if (vhostSort) vhostSort.value = vhostListPrefs.sort; - syncPoolColumns(); syncPoolSortDirection(); syncVhostSortDirection(); applyPoolTableView(); render(); + if (poolChanged) { syncPoolColumns(); syncPoolSortDirection(); preserveScrollAnchor(applyPoolTableView); } + if (vhostChanged) { syncVhostSortDirection(); preserveScrollAnchor(render); } } async function saveVhostListPrefs() { if (!authenticated) return; @@ -242,7 +249,13 @@ function applyPoolTableView() { const result = typeof a === "number" && typeof b === "number" ? a - b : compareText(a, b); return poolTablePrefs.descending ? -result : result; }); - body.replaceChildren(...rows); + // Retain rows that are already ordered correctly. A needless detach of a + // focused/anchored table row can jump the page even when sorting is unchanged. + let cursor = body.firstElementChild; + for (const row of rows) { + if (row === cursor) cursor = cursor.nextElementSibling; + else body.insertBefore(row, cursor); + } let visible = 0; for (const row of rows) { const match = !query || (row.poolSearchValue || "").includes(query); row.hidden = !match; if (match) visible++; } syncPoolColumns(); syncPoolSortDirection(); @@ -268,7 +281,9 @@ function initPoolTableTools() { const visible = new Set(poolTablePrefs.columns); if (input.checked) visible.add(input.dataset.poolColumnToggle); else visible.delete(input.dataset.poolColumnToggle); if (!visible.size) { input.checked = true; toast(t("backendColumnsRequired"), true); return; } - poolTablePrefs.columns = poolColumns.filter(key => visible.has(key)); void savePoolTablePrefs(); syncPoolColumns(); applyBackendOverviewView(); + poolTablePrefs.columns = poolColumns.filter(key => visible.has(key)); + preserveScrollAnchor(() => { syncPoolColumns(); applyBackendOverviewView(); }); + void savePoolTablePrefs(); })); syncPoolColumns(); syncPoolSortDirection(); } @@ -469,6 +484,63 @@ const BO_EXTRA_CELLS = { if (extra.h1 + extra.h2) cell.append(el("small", `H2 ${boPercent(extra.h2, extra.h1 + extra.h2)}`)); }, }; +// Keep filter buttons and keyed table rows mounted between live samples. +// Replacing them every few seconds discards keyboard focus and browser scroll anchors. +const BO_FILTERS = [["all", "backendFilterAll"], ["up", "vhUp"], ["down", "vhDown"], ["other", "backendFilterOther"]]; +function syncBackendOverviewFilters(filters, counts) { + if (filters.getAttribute("aria-label") !== t("backendFilterLabel")) filters.setAttribute("aria-label", t("backendFilterLabel")); + for (const [key, label] of BO_FILTERS) { + let chip = [...filters.children].find(button => button.dataset.boFilter === key); + if (!chip) { + chip = el("button", undefined, `bo-chip is-${key}`); + chip.type = "button"; chip.dataset.uiIconName = "none"; chip.dataset.boFilter = key; + chip.append(el("span"), el("b")); + chip.addEventListener("click", () => { boFilter = key; applyBackendOverviewView(); }); + filters.append(chip); + } + const pressed = String(boFilter === key); + if (chip.getAttribute("aria-pressed") !== pressed) chip.setAttribute("aria-pressed", pressed); + const title = chip.querySelector("span"), count = chip.querySelector("b"); + if (title.textContent !== t(label)) title.textContent = t(label); + if (count.textContent !== String(counts[key])) count.textContent = String(counts[key]); + count.classList.toggle("is-zero", !counts[key]); + } +} +function syncBackendOverviewRows(body, rendered) { + const rowKey = row => row.dataset.boRowKey !== undefined ? `row:${row.dataset.boRowKey}` : `detail:${row.dataset.boDetailKey}`; + const existing = new Map([...body.children].map(row => [rowKey(row), row])); + const rows = rendered.map(next => { + const key = rowKey(next); + const current = existing.get(key); + if (!current || current.children.length !== next.children.length || current.dataset.boColumns !== next.dataset.boColumns) return next; + if (current.className !== next.className) current.className = next.className; + for (let index = 0; index < current.cells.length; index++) { + const cell = current.cells[index], updated = next.cells[index]; + if (cell.className !== updated.className) cell.className = updated.className; + if (cell.title !== updated.title) cell.title = updated.title; + if (cell.colSpan !== updated.colSpan) cell.colSpan = updated.colSpan; + if (updated.dataset.boColumn && cell.dataset.boColumn !== updated.dataset.boColumn) cell.dataset.boColumn = updated.dataset.boColumn; + if (updated.dataset.boColumn === "toggle") { + // The expansion control itself must survive refreshes, not just regain focus. + const button = cell.querySelector("button"), nextButton = updated.querySelector("button"); + if (button && nextButton) { + if (button.getAttribute("aria-expanded") !== nextButton.getAttribute("aria-expanded")) button.setAttribute("aria-expanded", nextButton.getAttribute("aria-expanded")); + } else cell.replaceChildren(...updated.childNodes); + } else if (cell.innerHTML !== updated.innerHTML) { + cell.replaceChildren(...updated.childNodes); + } + } + return current; + }); + // Do not detach rows already in the correct position: moving a focused row + // needlessly also breaks the scroll anchor on some browsers. + let cursor = body.firstElementChild; + for (const row of rows) { + if (row === cursor) cursor = cursor.nextElementSibling; + else body.insertBefore(row, cursor); + } + while (cursor) { const next = cursor.nextElementSibling; cursor.remove(); cursor = next; } +} function applyBackendOverviewView() { if (overviewViewsHidden()) { overviewViewsPending = true; return; } const body = $("bo-rows"); if (!body) return; @@ -479,14 +551,7 @@ function applyBackendOverviewView() { for (const item of boItems) counts[item.group]++; const summary = $("bo-summary"); if (summary) summary.textContent = boItems.length ? t("backendSummary").replace("{up}", counts.up).replace("{total}", boItems.length) : ""; const filters = $("bo-filters"); - if (filters) { - filters.setAttribute("aria-label", t("backendFilterLabel")); - filters.replaceChildren(...[["all", "backendFilterAll"], ["up", "vhUp"], ["down", "vhDown"], ["other", "backendFilterOther"]].map(([key, label]) => { - const chip = el("button", undefined, `bo-chip is-${key}`), count = el("b", String(counts[key]), counts[key] ? "" : "is-zero"); - chip.type = "button"; chip.dataset.uiIconName = "none"; chip.setAttribute("aria-pressed", String(boFilter === key)); - chip.append(el("span", t(label)), count); chip.addEventListener("click", () => { boFilter = key; applyBackendOverviewView(); }); return chip; - })); - } + if (filters) syncBackendOverviewFilters(filters, counts); const key = poolTablePrefs.sort; const list = boItems.filter(item => (boFilter === "all" || item.group === boFilter) && (!query || item.search.includes(query))); list.sort((left, right) => { @@ -503,10 +568,15 @@ function applyBackendOverviewView() { visibleColumns.has("p95") && ["p95", t("backendColP95"), true], visibleColumns.has("probe") && ["probe", t("backendColProbe"), true], visibleColumns.has("cache") && ["cache", t("backendColCache")], visibleColumns.has("traffic") && ["traffic", t("vhTraffic"), true], visibleColumns.has("causes") && ["causes", t("backendColCauses")], visibleColumns.has("protocol") && ["protocol", t("backendColProtocol")], showEvent && ["event", t("backendLastEvent")], ].filter(Boolean); - const head = $("bo-head"); if (head) head.replaceChildren(...columns.map(([id, label, numeric]) => { const th = el("th", label, numeric ? "is-num" : ""); th.dataset.boColumn = id; if (id === "toggle") th.setAttribute("aria-label", t("backendDetailsToggle")); return th; })); + const head = $("bo-head"); + if (head && (head.children.length !== columns.length || columns.some(([id, label], index) => head.children[index].dataset.boColumn !== id || head.children[index].textContent !== label))) { + head.replaceChildren(...columns.map(([id, label, numeric]) => { const th = el("th", label, numeric ? "is-num" : ""); th.dataset.boColumn = id; if (id === "toggle") th.setAttribute("aria-label", t("backendDetailsToggle")); return th; })); + } + const columnSignature = columns.map(([id]) => id).join("|"); const rows = []; for (const item of list) { const row = el("tr", undefined, `bo-row is-${item.tone}${item.disabled ? " is-disabled" : ""}`), open = expandable && boOpen.has(item.key); + row.dataset.boRowKey = item.key; row.dataset.boColumns = columnSignature; for (const [id] of columns) { const cell = el("td"); cell.dataset.boColumn = id; if (id === "toggle") { @@ -550,17 +620,18 @@ function applyBackendOverviewView() { rows.push(row); if (open) { const detail = el("tr", undefined, "bo-detail-row"), cell = el("td"), grid = el("div", undefined, "bo-detail-grid"); cell.colSpan = Math.max(1, columns.length); + detail.dataset.boDetailKey = item.key; detail.dataset.boColumns = columnSignature; const values = { generation: item.generation, generationRequests: item.generationRequests, generationAge: item.generationAgeText, rotations: item.rotations, lastFailure: item.lastFailureText, lastRecovery: item.lastRecoveryText }; for (const column of detailColumns) { const entry = el("div", undefined, "bo-detail-item"), value = el("b", String(values[column] ?? "-")); if (column === "lastFailure" && item.lastFailureMs) { value.className = "is-failed"; value.title = item.lastFailureDetail || ""; } else if (column === "lastRecovery" && item.lastRecoveryMs) value.className = "is-recovered"; entry.append(el("span", t(BO_SORT_LABELS[column])), value); grid.append(entry); } cell.append(grid); detail.append(cell); rows.push(detail); } } const scroller = body.closest(".table-scroll"), scrollTop = scroller?.scrollTop ?? 0, scrollLeft = scroller?.scrollLeft ?? 0; - body.replaceChildren(...rows); - // Writing scroll offsets forces a synchronous layout; only restore a - // position the user actually scrolled to. - if (scroller && (scrollTop || scrollLeft)) { scroller.scrollTop = scrollTop; scroller.scrollLeft = scrollLeft; } - if (hadFocus) [...body.querySelectorAll(".bo-expand")].find(button => button.dataset.boKey === focusKey)?.focus({ preventScroll: true }); + syncBackendOverviewRows(body, rows); + // Sorting or filtering can change the table height; preserve the user's + // scroll position, but avoid forced layout for an untouched scroll offset. + if (scroller && (scrollTop || scrollLeft)) { if (scroller.scrollTop !== scrollTop) scroller.scrollTop = scrollTop; if (scroller.scrollLeft !== scrollLeft) scroller.scrollLeft = scrollLeft; } + if (hadFocus && document.activeElement?.dataset?.boKey !== focusKey) [...body.querySelectorAll(".bo-expand")].find(button => button.dataset.boKey === focusKey)?.focus({ preventScroll: true }); const empty = $("bo-empty"); if (empty) { empty.textContent = boItems.length ? t("backendSearchEmpty") : t("vhHealthEmpty"); empty.hidden = list.length > 0 || !boHasProxy; } const toggleAll = document.querySelectorAll("#bo-column-options [data-pool-column-toggle]"); toggleAll.forEach(input => { input.checked = visibleColumns.has(input.dataset.poolColumnToggle); }); @@ -807,6 +878,7 @@ function renderStatus(status) { const row = el("tr"); if (vhostDisabled) row.classList.add("pool-vhost-disabled"); const poolDomain = status.backend_pool_domains?.[pool.id]; const poolLabel = poolDomain ? `${pool.id} (${poolDomain})` : pool.id; const cells = [poolLabel, `${member.id}${member.backup ? " / " + t("vhBackup") : ""}`, label, activeLimit, member.requests, member.errors, member.ewma_latency_ms > 0 ? `${member.ewma_latency_ms.toFixed(1)} ms` : "-", `${rateBytes(memberTraffic)}/s`, extra.text.rate, extra.text.statuses, extra.text.p95, extra.text.cache, extra.text.probe, extra.text.causes, extra.text.protocol, member.upstream_client_generation ?? "-", member.upstream_client_generation_requests ?? "-", generationAgeText, member.upstream_client_rotations_total ?? "-", lastFailure, lastRecovery]; const sortValues = { vhost: poolLabel.toLowerCase(), backend: String(member.id || "").toLowerCase(), status: label.toLowerCase(), active: Number(member.active) || 0, requests: Number(member.requests) || 0, errors: Number(member.errors) || 0, latency: Number(member.ewma_latency_ms) || 0, traffic: memberTraffic, ...extra.sort, generation: Number(member.upstream_client_generation) || 0, generationRequests: Number(member.upstream_client_generation_requests) || 0, generationAge: Number.isFinite(generationAge) ? generationAge : -1, rotations: Number(member.upstream_client_rotations_total) || 0, lastFailure: Number(member.last_failure_at_ms) || 0, lastRecovery: Number(member.last_recovered_ms) || 0 }; + row.dataset.poolKey = JSON.stringify([pool.id, member.id]); row.poolSort = sortValues; row.poolSearchValue = [poolLabel, member.id, label, member.status, member.last_failure_class, member.last_failure_detail].filter(Boolean).join(" ").toLowerCase(); if (buildPoolRows) cells.forEach((value, index) => { const cell = el("td", String(value ?? "-")); const column = poolColumns[index]; cell.dataset.poolColumn = column; cell.title = column === "status" ? (vhostDisabled ? t("vhDisabled") : `${label} · ${healthDetail}`) : column === "lastFailure" ? (member.last_failure_detail || lastFailure) : String(value ?? "-"); if (column === "status" && !vhostDisabled) cell.className = member.status === "down" ? "status-error" : member.status === "up" ? "status-good" : ""; if (column === "lastFailure" && member.last_failure_at_ms) cell.classList.add("backend-last-failure"); row.append(cell); }); if (buildPoolRows) rows.push(row); const tone = vhostDisabled ? "muted" : member.health_mode === "off" && member.status === "up" ? "muted" : member.status === "up" ? "up" : member.status === "down" ? "down" : member.status === "checking" || member.status === "draining" ? "warn" : "muted"; @@ -860,7 +932,28 @@ function renderStatus(status) { const hasConfiguredProxySource = [...configuredVhosts.values()].some(vhost => vhostRequiresProxy(vhost) ); - if (buildPoolRows) $("pool-rows").replaceChildren(...rows); else overviewViewsPending = true; + if (buildPoolRows) { + const body = $("pool-rows"), existing = new Map([...body.rows].map(row => [row.dataset.poolKey, row])); + const refreshed = rows.map(next => { + const current = existing.get(next.dataset.poolKey); + if (!current || current.cells.length !== next.cells.length) return next; + current.className = next.className; + current.poolSort = next.poolSort; current.poolSearchValue = next.poolSearchValue; + for (let index = 0; index < current.cells.length; index++) { + const cell = current.cells[index], changed = next.cells[index]; + if (cell.textContent !== changed.textContent) cell.textContent = changed.textContent; + if (cell.title !== changed.title) cell.title = changed.title; + if (cell.className !== changed.className) cell.className = changed.className; + } + return current; + }); + let cursor = body.firstElementChild; + for (const row of refreshed) { + if (row === cursor) cursor = cursor.nextElementSibling; + else body.insertBefore(row, cursor); + } + while (cursor) { const next = cursor.nextElementSibling; cursor.remove(); cursor = next; } + } else overviewViewsPending = true; renderBackendOverview(overviewItems, hasConfiguredProxySource, status, false); const backendDiagnosticsCard = $("backend-diagnostics-card"); backendDiagnosticsCard?.classList.toggle("is-no-proxy", !hasConfiguredProxySource); diff --git a/src/admin/web/web-server-profiles.js b/src/admin/web/web-server-profiles.js index 4e5fdb7..4ab5a71 100644 --- a/src/admin/web/web-server-profiles.js +++ b/src/admin/web/web-server-profiles.js @@ -49,13 +49,19 @@ window.rustProxyPhpProfiles = ({ defaults, mapLines, lines, parseFastCgiParams, summary.append(title, kindBadge); const editor = document.createElement("form"); editor.className = "vh-grid fastcgi-profile-editor"; editor.noValidate = true; const namedInput = (key, value, readonly = false) => { - const wrapper = el("label"); + const wrapper = el("label", undefined, "fastcgi-profile-identity"); wrapper.append(el("span", t(key))); const input = document.createElement("input"); input.value = value || ""; input.maxLength = key === "phpProfileId" ? 64 : 96; input.required = true; input.readOnly = readonly; wrapper.append(input); editor.append(wrapper); return input; }; - const idInput = namedInput("phpProfileId", profile.id, !creating); const nameInput = namedInput("phpProfileName", profile.name); + const idInput = namedInput("phpProfileId", profile.id, !creating); + window.rustProxyAutoId.attach(idInput, { + elements: [nameInput], + taken: () => (envelope?.config.php_fpm_profiles || []).map(item => item.id) + }); + idInput.closest("label").append(el("small", t("phpProfileIdHelp"), "fine fastcgi-profile-identity-help")); + nameInput.closest("label").append(el("small", t("phpProfileNameHelp"), "fine fastcgi-profile-identity-help")); const controls = {}; const phpOnlyWrappers = []; let phpOnlySection; diff --git a/src/basic_auth/mod.rs b/src/basic_auth/mod.rs index 6f9df6f..968bff4 100644 --- a/src/basic_auth/mod.rs +++ b/src/basic_auth/mod.rs @@ -17,7 +17,7 @@ use tokio::sync::Semaphore; use zeroize::Zeroizing; const MAX_WAITING_VERIFICATIONS: usize = 64; -const WORKER_WAIT_TIMEOUT: Duration = Duration::from_secs(3); +const WORKER_WAIT_TIMEOUT: Duration = Duration::from_secs(15); fn realm() -> String { "Restricted".into() diff --git a/src/basic_auth/tests.rs b/src/basic_auth/tests.rs index 768b09b..d3f631d 100644 --- a/src/basic_auth/tests.rs +++ b/src/basic_auth/tests.rs @@ -117,7 +117,7 @@ mod tests { let response = auth.authorize( &mut headers, true, "127.0.0.1".parse().unwrap(), Arc::new(Semaphore::new(2)), &Limits::default() - ).await.err().expect("queue exhaustion must deny access"); + ).await.expect_err("queue exhaustion must deny access"); assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); assert_eq!(response.headers().get("retry-after").unwrap(), "1"); assert!(!headers.contains_key("authorization")); diff --git a/src/db.rs b/src/db.rs index 1a83dc6..8162b55 100644 --- a/src/db.rs +++ b/src/db.rs @@ -13,11 +13,37 @@ use sqlx::{ }; use std::{path::Path, time::Duration}; -pub const SCHEMA_VERSION: i64 = 12; +pub const SCHEMA_VERSION: i64 = MIGRATIONS[MIGRATIONS.len() - 1].0; pub const ADMIN_PREFERENCES_MAX_BYTES: usize = 64 * 1024; pub const CERTIFICATE_API_CREDENTIAL_CAPACITY: i64 = 32; pub const AUDIT_CAPACITY: i64 = 10_000; +const MIGRATIONS: &[(i64, &str)] = &[ + (2, include_str!("../migrations/0002_admin.sql")), + ( + 3, + include_str!("../migrations/0003_certificate_renewals.sql"), + ), + (4, include_str!("../migrations/0004_admin_preferences.sql")), + (5, include_str!("../migrations/0005_certificate_api.sql")), + ( + 6, + include_str!("../migrations/0006_certificate_api_credentials.sql"), + ), + (7, include_str!("../migrations/0007_secret_store.sql")), + (8, include_str!("../migrations/0008_config_history.sql")), + ( + 9, + include_str!("../migrations/0009_certificate_api_grants.sql"), + ), + (10, include_str!("../migrations/0010_dashboard_presets.sql")), + (11, include_str!("../migrations/0011_tokens.sql")), + ( + 12, + include_str!("../migrations/0012_admin_preferences_size.sql"), + ), +]; + #[derive(Clone)] pub struct Store { pub(crate) pool: SqlitePool, @@ -88,54 +114,23 @@ impl Store { .max_connections(4) .connect_with(options) .await?; + let mut tx = pool.begin().await?; let version: i64 = sqlx::query_scalar("PRAGMA user_version") - .fetch_one(&pool) + .fetch_one(&mut *tx) .await?; ensure!( version <= SCHEMA_VERSION, "database schema is newer than this binary; refusing downgrade" ); - let mut tx = pool.begin().await?; - sqlx::raw_sql(include_str!("../migrations/0002_admin.sql")) - .execute(&mut *tx) - .await?; - sqlx::raw_sql(include_str!("../migrations/0003_certificate_renewals.sql")) - .execute(&mut *tx) - .await?; - sqlx::raw_sql(include_str!("../migrations/0004_admin_preferences.sql")) - .execute(&mut *tx) - .await?; - sqlx::raw_sql(include_str!("../migrations/0005_certificate_api.sql")) - .execute(&mut *tx) - .await?; - sqlx::raw_sql(include_str!( - "../migrations/0006_certificate_api_credentials.sql" - )) - .execute(&mut *tx) - .await?; - sqlx::raw_sql(include_str!("../migrations/0007_secret_store.sql")) - .execute(&mut *tx) - .await?; - sqlx::raw_sql(include_str!("../migrations/0008_config_history.sql")) - .execute(&mut *tx) - .await?; - sqlx::raw_sql(include_str!( - "../migrations/0009_certificate_api_grants.sql" - )) - .execute(&mut *tx) - .await?; - sqlx::raw_sql(include_str!("../migrations/0010_dashboard_presets.sql")) - .execute(&mut *tx) - .await?; - sqlx::raw_sql(include_str!("../migrations/0011_tokens.sql")) - .execute(&mut *tx) - .await?; - if version < 12 { - sqlx::raw_sql(include_str!( - "../migrations/0012_admin_preferences_size.sql" - )) - .execute(&mut *tx) - .await?; + for &(target, sql) in MIGRATIONS { + if version < target { + sqlx::raw_sql(sql) + .execute(&mut *tx) + .await + .with_context(|| { + format!("SQLite schema migration to version {target} failed") + })?; + } } sqlx::query("INSERT OR IGNORE INTO configuration(id, revision, document) VALUES(1, 0, ?)") .bind(serde_json::to_string(initial)?) @@ -147,9 +142,13 @@ impl Store { .bind(crate::auth::now()) .execute(&mut *tx) .await?; - sqlx::query("PRAGMA user_version = 12") + if version < SCHEMA_VERSION { + sqlx::query(sqlx::AssertSqlSafe(format!( + "PRAGMA user_version = {SCHEMA_VERSION}" + ))) .execute(&mut *tx) .await?; + } tx.commit().await?; Ok(Self { pool }) } diff --git a/src/db/tests.rs b/src/db/tests.rs index 8142654..6bff589 100644 --- a/src/db/tests.rs +++ b/src/db/tests.rs @@ -1,5 +1,15 @@ mod tests { use super::*; + + #[test] + fn migration_registry_is_complete_and_ordered() { + assert_eq!(MIGRATIONS.first().map(|(version, _)| *version), Some(2)); + assert_eq!( + MIGRATIONS.last().map(|(version, _)| *version), + Some(SCHEMA_VERSION) + ); + assert!(MIGRATIONS.windows(2).all(|pair| pair[1].0 == pair[0].0 + 1)); + } #[tokio::test] async fn persists_and_rejects_stale_writes() { let dir = tempfile::tempdir().unwrap(); @@ -208,6 +218,135 @@ mod tests { assert!(store.load().await.unwrap().config.vhosts.is_empty()); store.close().await; } + async fn seed_v11_with_preferences(path: &Path) { + let options = SqliteConnectOptions::new() + .filename(path) + .create_if_missing(true) + .foreign_keys(true); + let pool = SqlitePoolOptions::new() + .max_connections(1) + .connect_with(options) + .await + .unwrap(); + for &(target, migration) in MIGRATIONS { + if target >= 12 { + break; + } + sqlx::raw_sql(migration).execute(&pool).await.unwrap(); + } + sqlx::query( + "INSERT INTO administrator(id, username, password_hash, created_at) VALUES(1, 'owner', 'hash', 1)", + ) + .execute(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO admin_preferences(administrator_id, document) VALUES(1, ?)") + .bind(r#"{"language":"pl","theme":"dark"}"#) + .execute(&pool) + .await + .unwrap(); + sqlx::query("PRAGMA user_version = 11") + .execute(&pool) + .await + .unwrap(); + pool.close().await; + } + + #[tokio::test] + async fn v11_upgrade_keeps_admin_preferences_and_is_not_repeated() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("v11.sqlite3"); + seed_v11_with_preferences(&path).await; + + let store = Store::open(&path, &Config::default()).await.unwrap(); + assert_eq!( + store.admin_preferences("owner").await.unwrap().as_deref(), + Some(r#"{"language":"pl","theme":"dark"}"#) + ); + let version: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&store.pool) + .await + .unwrap(); + assert_eq!(version, SCHEMA_VERSION); + let large_document = "x".repeat(8192); + assert!(store + .save_admin_preferences("owner", &large_document) + .await + .unwrap()); + assert!(store + .save_admin_preferences("owner", &"x".repeat(65537)) + .await + .is_err()); + store.close().await; + + let reopened = Store::open(&path, &Config::default()).await.unwrap(); + assert_eq!( + reopened + .admin_preferences("owner") + .await + .unwrap() + .as_deref(), + Some(large_document.as_str()) + ); + let fk_check: Vec<(String, i64, String, i64)> = sqlx::query_as("PRAGMA foreign_key_check") + .fetch_all(&reopened.pool) + .await + .unwrap(); + assert!(fk_check.is_empty()); + sqlx::query("DELETE FROM administrator WHERE id = 1") + .execute(&reopened.pool) + .await + .unwrap(); + assert!(reopened.admin_preferences("owner").await.unwrap().is_none()); + let rows: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM admin_preferences") + .fetch_one(&reopened.pool) + .await + .unwrap(); + assert_eq!( + rows, 0, + "administrator preferences must still cascade on delete" + ); + reopened.close().await; + } + + #[tokio::test] + async fn failed_v11_migration_rolls_back_entire_upgrade() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("v11-failed.sqlite3"); + seed_v11_with_preferences(&path).await; + let options = SqliteConnectOptions::new().filename(&path); + let pool = SqlitePoolOptions::new() + .max_connections(1) + .connect_with(options) + .await + .unwrap(); + sqlx::query("CREATE TABLE admin_preferences_v2 (administrator_id INTEGER PRIMARY KEY)") + .execute(&pool) + .await + .unwrap(); + pool.close().await; + + assert!(Store::open(&path, &Config::default()).await.is_err()); + let options = SqliteConnectOptions::new().filename(&path); + let pool = SqlitePoolOptions::new() + .max_connections(1) + .connect_with(options) + .await + .unwrap(); + let version: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(version, 11); + let original: String = + sqlx::query_scalar("SELECT document FROM admin_preferences WHERE administrator_id = 1") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(original, r#"{"language":"pl","theme":"dark"}"#); + pool.close().await; + } + #[tokio::test] async fn migration_keeps_v1_config_and_revision() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/pages/mod.rs b/src/pages/mod.rs index f8fccda..90cc974 100644 --- a/src/pages/mod.rs +++ b/src/pages/mod.rs @@ -186,7 +186,9 @@ impl Page { Kind::Welcome => include_str!("../admin/web/demo.html").to_owned(), Kind::Builtin => builtin_application_page(status), Kind::CloudflareWelcome => include_str!("../admin/web/cf_page/welcome.html").to_owned(), - Kind::CloudflarePlaceholder => include_str!("../admin/web/cf_page/placeholder.html").to_owned(), + Kind::CloudflarePlaceholder => { + include_str!("../admin/web/cf_page/placeholder.html").to_owned() + } Kind::Cloudflare => cloudflare_style_page(status) .map(str::to_owned) .unwrap_or_else(|| builtin_application_page(status)), @@ -316,11 +318,15 @@ pub fn replace_error(response: &mut Response, page: &Page) { if response .headers() .get(::http::header::CACHE_CONTROL) - .is_some_and(|value| value.as_bytes().split(|&byte| byte == b',').any(|part| - part.iter().copied().filter(|byte| !byte.is_ascii_whitespace()) - .map(|byte| byte.to_ascii_lowercase()) - .eq(b"private".iter().copied()) - )) + .is_some_and(|value| { + value.as_bytes().split(|&byte| byte == b',').any(|part| { + part.iter() + .copied() + .filter(|byte| !byte.is_ascii_whitespace()) + .map(|byte| byte.to_ascii_lowercase()) + .eq(b"private".iter().copied()) + }) + }) { replacement.headers_mut().insert( ::http::header::CACHE_CONTROL, diff --git a/src/proxy/headers/authority_tests.rs b/src/proxy/headers/authority_tests.rs index b4e6388..5134138 100644 --- a/src/proxy/headers/authority_tests.rs +++ b/src/proxy/headers/authority_tests.rs @@ -493,20 +493,27 @@ mod authority_tests { .extensions_mut() .insert(OriginTiming(Duration::from_millis(7))); - // The header is opt-in, including for Docker-generated vhosts. apply_backend_diagnostic_values(&mut response, false, false); assert!(response.headers().get("x-rust-proxy-backend").is_none()); apply_backend_diagnostic_values(&mut response, true, true); - assert_eq!(response.headers()["x-rust-proxy-backend"], "edge-node/012345abcdef"); + assert_eq!( + response.headers()["x-rust-proxy-backend"], + "edge-node/012345abcdef" + ); assert_eq!(response.headers()["x-rustproxy-backend-time"], "7.00ms"); - assert_eq!(response.extensions().get::().unwrap().0, raw_id); + assert_eq!( + response.extensions().get::().unwrap().0, + raw_id + ); - // For cached responses the same OriginBackend extension is used. let mut cached = Response::new(Body::empty()); cached.extensions_mut().insert(OriginBackend(raw_id.into())); apply_backend_diagnostic_values(&mut cached, true, false); - assert_eq!(cached.headers()["x-rust-proxy-backend"], "edge-node/012345abcdef"); + assert_eq!( + cached.headers()["x-rust-proxy-backend"], + "edge-node/012345abcdef" + ); assert!(cached.headers().get("x-rustproxy-backend-time").is_none()); } @@ -812,109 +819,191 @@ mod graceful_h2_tests { } } -#[tokio::test] -async fn proxy_generated_error_responses_use_generic_statuses() { - use http_body_util::BodyExt; - let unsupported = error( - StatusCode::NOT_IMPLEMENTED, - "RustProxy: internal CONNECT implementation detail\n", - ); - assert_eq!(unsupported.status(), StatusCode::NOT_IMPLEMENTED); - assert_eq!(unsupported.headers()["cache-control"], "no-store"); - assert_eq!( - unsupported.into_body().collect().await.unwrap().to_bytes(), - "501 Not Implemented\n" - ); - let not_found = error( - StatusCode::NOT_FOUND, - "RustProxy: internal routing detail\n", - ); - assert_eq!(not_found.status(), StatusCode::NOT_FOUND); - assert_eq!( - not_found.headers()["content-type"], - "text/html; charset=utf-8" - ); - let bytes = not_found.into_body().collect().await.unwrap().to_bytes(); - let page = std::str::from_utf8(&bytes).unwrap(); - assert!(page.contains("404")); - assert!(!page.contains("RustProxy: internal")); +mod error_page_tests { + use super::*; + + fn validation_policy() -> crate::config::ValidationPolicy { + crate::config::ValidationPolicy { + tls_addr: None, + cert_dir: None, + data_dir: None, + proxy_addr: "127.0.0.1:8080".parse().unwrap(), + admin_addr: "127.0.0.1:9090".parse().unwrap(), + } + } + + #[tokio::test] + async fn proxy_generated_error_responses_use_generic_statuses() { + use http_body_util::BodyExt; + let unsupported = error( + StatusCode::NOT_IMPLEMENTED, + "RustProxy: internal CONNECT implementation detail\n", + ); + assert_eq!(unsupported.status(), StatusCode::NOT_IMPLEMENTED); + assert_eq!(unsupported.headers()["cache-control"], "no-store"); + assert_eq!( + unsupported.into_body().collect().await.unwrap().to_bytes(), + "501 Not Implemented\n" + ); + let not_found = error( + StatusCode::NOT_FOUND, + "RustProxy: internal routing detail\n", + ); + assert_eq!(not_found.status(), StatusCode::NOT_FOUND); + assert_eq!( + not_found.headers()["content-type"], + "text/html; charset=utf-8" + ); + let bytes = not_found.into_body().collect().await.unwrap().to_bytes(); + let page = std::str::from_utf8(&bytes).unwrap(); + assert!(page.contains("404")); + assert!(!page.contains("RustProxy: internal")); + } + #[tokio::test] async fn generated_web_errors_use_vhost_then_global_but_origin_errors_keep_their_body() { use http_body_util::BodyExt; let mut config = crate::config::demo_config("127.0.0.1:9000".parse().unwrap()); - config.pages.errors.insert(404, crate::pages::Page { - kind: crate::pages::Kind::Html, - status: None, - html: "global 404".into(), - }); + config.pages.errors.insert( + 404, + crate::pages::Page { + kind: crate::pages::Kind::Html, + status: None, + html: "global 404".into(), + }, + ); let snapshot = crate::config::compile(config.clone(), 1, &validation_policy()).unwrap(); let route = snapshot.select("localhost", "/").unwrap(); - let generated = Response::builder().status(404) - .body(Body::from("generated Web Server 404")).unwrap(); + let generated = Response::builder() + .status(404) + .body(Body::from("generated Web Server 404")) + .unwrap(); let mut generated = intercept_route_web_error(generated, route, &snapshot); assert!(should_replace_error_page(&generated, false)); crate::pages::replace_error(&mut generated, &snapshot.envelope.config.pages.errors[&404]); - assert_eq!(generated.into_body().collect().await.unwrap().to_bytes(), "global 404"); + assert_eq!( + generated.into_body().collect().await.unwrap().to_bytes(), + "global 404" + ); - config.vhosts[0].pages.errors.insert(404, crate::pages::Page { - kind: crate::pages::Kind::Html, - status: None, - html: "vhost 404".into(), - }); + config.vhosts[0].pages.errors.insert( + 404, + crate::pages::Page { + kind: crate::pages::Kind::Html, + status: None, + html: "vhost 404".into(), + }, + ); let snapshot = crate::config::compile(config.clone(), 2, &validation_policy()).unwrap(); let route = snapshot.select("localhost", "/").unwrap(); - let generated = Response::builder().status(404) - .body(Body::from("generated Web Server 404")).unwrap(); + let generated = Response::builder() + .status(404) + .body(Body::from("generated Web Server 404")) + .unwrap(); let mut generated = intercept_route_web_error(generated, route, &snapshot); assert!(should_replace_error_page(&generated, false)); - crate::pages::replace_error(&mut generated, &route.frontend.as_ref().unwrap().pages.errors[&404]); - assert_eq!(generated.into_body().collect().await.unwrap().to_bytes(), "vhost 404"); + crate::pages::replace_error( + &mut generated, + &route.frontend.as_ref().unwrap().pages.errors[&404], + ); + assert_eq!( + generated.into_body().collect().await.unwrap().to_bytes(), + "vhost 404" + ); for source in ["PHP/FastCGI", "htaccess ErrorDocument"] { - let mut response = Response::builder().status(404) - .body(Body::from(source)).unwrap(); - response.extensions_mut().insert(crate::pages::OriginProvidedResponse); + let mut response = Response::builder() + .status(404) + .body(Body::from(source)) + .unwrap(); + response + .extensions_mut() + .insert(crate::pages::OriginProvidedResponse); let response = intercept_route_web_error(response, route, &snapshot); assert!(!should_replace_error_page(&response, false)); - assert_eq!(response.into_body().collect().await.unwrap().to_bytes(), source); + assert_eq!( + response.into_body().collect().await.unwrap().to_bytes(), + source + ); } config.vhosts[0].pages.intercept_statuses = vec![404]; let snapshot = crate::config::compile(config, 3, &validation_policy()).unwrap(); let route = snapshot.select("localhost", "/").unwrap(); - let mut response = Response::builder().status(404) - .body(Body::from("application 404")).unwrap(); - response.extensions_mut().insert(crate::pages::OriginProvidedResponse); + let mut response = Response::builder() + .status(404) + .body(Body::from("application 404")) + .unwrap(); + response + .extensions_mut() + .insert(crate::pages::OriginProvidedResponse); let response = intercept_route_web_error(response, route, &snapshot); assert!(!should_replace_error_page(&response, false)); - assert_eq!(response.into_body().collect().await.unwrap().to_bytes(), "vhost 404"); + assert_eq!( + response.into_body().collect().await.unwrap().to_bytes(), + "vhost 404" + ); } #[tokio::test] async fn basic_auth_denials_keep_challenge_retry_and_private_cache_with_custom_page() { use http_body_util::BodyExt; for (status, challenge, retry) in [ - (StatusCode::UNAUTHORIZED, Some("Basic realm=\"Restricted\""), None), + ( + StatusCode::UNAUTHORIZED, + Some("Basic realm=\"Restricted\""), + None, + ), (StatusCode::TOO_MANY_REQUESTS, None, Some("60")), (StatusCode::SERVICE_UNAVAILABLE, None, Some("1")), ] { - let mut response = Response::builder().status(status) + let mut response = Response::builder() + .status(status) .header("cache-control", "private, no-store") - .body(Body::from("basic auth failure")).unwrap(); - if let Some(value) = challenge { response.headers_mut().insert("www-authenticate", value.parse().unwrap()); } - if let Some(value) = retry { response.headers_mut().insert("retry-after", value.parse().unwrap()); } + .body(Body::from("basic auth failure")) + .unwrap(); + if let Some(value) = challenge { + response + .headers_mut() + .insert("www-authenticate", value.parse().unwrap()); + } + if let Some(value) = retry { + response + .headers_mut() + .insert("retry-after", value.parse().unwrap()); + } assert!(should_replace_error_page(&response, false)); - crate::pages::replace_error(&mut response, &crate::pages::Page { - kind: crate::pages::Kind::Html, - status: None, - html: "custom auth page".into(), - }); + crate::pages::replace_error( + &mut response, + &crate::pages::Page { + kind: crate::pages::Kind::Html, + status: None, + html: "custom auth page".into(), + }, + ); assert_eq!(response.status(), status); - assert_eq!(response.headers().get("cache-control").unwrap(), "private, no-store"); - assert_eq!(response.headers().get("www-authenticate").map(|v| v.to_str().unwrap()), challenge); - assert_eq!(response.headers().get("retry-after").map(|v| v.to_str().unwrap()), retry); - assert_eq!(response.into_body().collect().await.unwrap().to_bytes(), "custom auth page"); + assert_eq!( + response.headers().get("cache-control").unwrap(), + "private, no-store" + ); + assert_eq!( + response + .headers() + .get("www-authenticate") + .map(|v| v.to_str().unwrap()), + challenge + ); + assert_eq!( + response + .headers() + .get("retry-after") + .map(|v| v.to_str().unwrap()), + retry + ); + assert_eq!( + response.into_body().collect().await.unwrap().to_bytes(), + "custom auth page" + ); } } - } diff --git a/src/proxy/web_cache_revalidation/tests.rs b/src/proxy/web_cache_revalidation/tests.rs index c89adcf..2b44474 100644 --- a/src/proxy/web_cache_revalidation/tests.rs +++ b/src/proxy/web_cache_revalidation/tests.rs @@ -81,7 +81,7 @@ async fn serve_file( server_port: 443, tls: true, version: http::Version::HTTP_2, - authenticated_user: None, + authenticated_user: None, }, ) .await diff --git a/src/web_server/htaccess/parse.rs b/src/web_server/htaccess/parse.rs index c8d2a01..abcc84f 100644 --- a/src/web_server/htaccess/parse.rs +++ b/src/web_server/htaccess/parse.rs @@ -423,7 +423,7 @@ pub fn index_files<'a>(compiled: Option<&'a Compiled>, directory_components: &[S pub fn accept_path_info(compiled: Option<&Compiled>, script_path: &str, fallback: bool) -> bool { match compiled.and_then(|compiled| matching_scopes(compiled, script_path).into_iter() - .filter_map(|scope| scope.accept_path_info).last()) { + .filter_map(|scope| scope.accept_path_info).next_back()) { Some(AcceptPathInfoMode::On) => true, Some(AcceptPathInfoMode::Off) => false, Some(AcceptPathInfoMode::Default) | None => fallback, @@ -437,7 +437,7 @@ pub fn has_error_documents(compiled: Option<&Compiled>) -> bool { pub fn error_document<'a>(compiled: Option<&'a Compiled>, path: &str, status: StatusCode) -> Option<&'a str> { compiled?.scopes.iter().filter(|scope| { path_components(path).ok().is_some_and(|parts| scope_matches(scope, &parts)) - }).filter_map(|scope| scope.error_documents.get(&status.as_u16()).map(String::as_str)).last() + }).filter_map(|scope| scope.error_documents.get(&status.as_u16()).map(String::as_str)).next_back() } pub fn directory_listing(compiled: Option<&Compiled>, directory_components: &[String], fallback: bool) -> bool { diff --git a/src/web_server/mod.rs b/src/web_server/mod.rs index 1fd4a80..a959960 100644 --- a/src/web_server/mod.rs +++ b/src/web_server/mod.rs @@ -10,8 +10,8 @@ mod security; mod serve; pub use config::{ - CacheRule, CompiledService, FastCgiHandler, Hardening, Php, PhpFpmProfile, Precompressed, RewriteRule, - SendfileMode, Service, SymlinkPolicy, + CacheRule, CompiledService, FastCgiHandler, Hardening, Php, PhpFpmProfile, Precompressed, + RewriteRule, SendfileMode, Service, SymlinkPolicy, }; pub use htaccess::Config as HtaccessConfig; pub use request::RequestContext; diff --git a/src/web_server/serve.rs b/src/web_server/serve.rs index 83cf620..e57bf56 100644 --- a/src/web_server/serve.rs +++ b/src/web_server/serve.rs @@ -1,10 +1,10 @@ use super::{ + config::FastCgiHandler, fastcgi::{ method_not_allowed_response, php_for_path, php_response, protected_script_without_handler, }, filesystem::{list_directory_sync, path_components, FilesystemRoot}, htaccess, - config::FastCgiHandler, response::{ add_service_headers, builtin_error_response, directory_listing, directory_redirect, file_response, io_response, status_response, @@ -33,8 +33,12 @@ async fn resolve_script_path_info( let script_path = format!("/{}", components[..=script_end].join("/")); // Preserve the exact suffix, including its final slash. Apache // front controllers depend on PATH_INFO retaining that slash. - let Some(path_info) = requested_path.strip_prefix(&script_path) - .filter(|suffix| suffix.starts_with('/')) else { continue; }; + let Some(path_info) = requested_path + .strip_prefix(&script_path) + .filter(|suffix| suffix.starts_with('/')) + else { + continue; + }; if !htaccess::accept_path_info(service.htaccess.as_ref(), &script_path, php.path_info) { continue; } @@ -123,7 +127,7 @@ async fn serve_inner( return status_response( StatusCode::BAD_REQUEST, "RustProxy: invalid .htaccess rewrite target\n", - ) + ); } }; if crate::acl::validate_decoded_routing_path(&rewritten_path).is_err() @@ -135,12 +139,18 @@ async fn serve_inner( htaccess::protected_component(service.htaccess.as_ref(), component) }) }) - || htaccess::denied(service.htaccess.as_ref(), &rewritten_path, context.client_ip) + || htaccess::denied( + service.htaccess.as_ref(), + &rewritten_path, + context.client_ip, + ) { return builtin_error_response(StatusCode::FORBIDDEN, &method); } if let Ok(components) = path_components(&rewritten_path) { - if let Some((script_path, path_info)) = resolve_script_path_info(service, &components, &rewritten_path).await { + if let Some((script_path, path_info)) = + resolve_script_path_info(service, &components, &rewritten_path).await + { let script_components = path_components(&script_path).unwrap_or_default(); if hardening_denied_path(service, &script_path) || script_components.iter().any(|component| { @@ -188,7 +198,11 @@ async fn serve_inner( || components .iter() .any(|component| htaccess::protected_component(service.htaccess.as_ref(), component)) - || htaccess::denied(service.htaccess.as_ref(), &effective_path, context.client_ip) + || htaccess::denied( + service.htaccess.as_ref(), + &effective_path, + context.client_ip, + ) { return builtin_error_response(StatusCode::FORBIDDEN, &method); } @@ -253,7 +267,10 @@ async fn serve_inner( .await; } if protected_script_without_handler(service, &public_path) - || service.php.as_ref().is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap) + || service + .php + .as_ref() + .is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap) { // A CGI-only root must never expose any non-executed file. return builtin_error_response(StatusCode::FORBIDDEN, &method); @@ -311,7 +328,10 @@ async fn serve_inner( .await; } if protected_script_without_handler(service, &public_path) - || service.php.as_ref().is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap) + || service + .php + .as_ref() + .is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap) { return builtin_error_response(StatusCode::FORBIDDEN, &method); } @@ -350,12 +370,16 @@ async fn serve_inner( if method != Method::GET && method != Method::HEAD { return method_not_allowed_response(); } - if service.php.as_ref().is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap) + if service + .php + .as_ref() + .is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap) || !htaccess::directory_listing( - service.htaccess.as_ref(), - &components, - service.directory_listing, - ) { + service.htaccess.as_ref(), + &components, + service.directory_listing, + ) + { return builtin_error_response(StatusCode::FORBIDDEN, &method); } let root = FilesystemRoot::for_service(service); @@ -426,7 +450,7 @@ pub async fn serve( // documents. Normal requests without that feature avoid header cloning. let error_request = ((request_method == Method::GET || request_method == Method::HEAD) && htaccess::has_error_documents(service.htaccess.as_ref())) - .then(|| (headers.clone(), context.clone())); + .then(|| (headers.clone(), context.clone())); let mut response = serve_inner(service, method, headers, uri, path, body, context).await; let original_status = response.status(); let mut used_local_error_document = false; @@ -434,25 +458,42 @@ pub async fn serve( // provide their own error body; do not open a second FastCGI request while // the first one's streamed response could still hold a backend permit. if (original_status.is_client_error() || original_status.is_server_error()) - && !matches!(response.extensions().get::(), - Some(crate::web_server::metrics::ResponseKind::Php)) + && !matches!( + response + .extensions() + .get::(), + Some(crate::web_server::metrics::ResponseKind::Php) + ) { if let Some((mut error_headers, replacement_context)) = error_request { - if let Some(target) = htaccess::error_document(service.htaccess.as_ref(), path, original_status) { + if let Some(target) = + htaccess::error_document(service.htaccess.as_ref(), path, original_status) + { let target_path = target.split('?').next().unwrap_or_default(); if target_path != path { if let Ok(target_uri) = target.parse::() { // Serve the full error document, never a Range or 304 // response produced from the original request headers. for name in [ - http::header::RANGE, http::header::IF_RANGE, - http::header::IF_MODIFIED_SINCE, http::header::IF_NONE_MATCH, - http::header::IF_MATCH, http::header::IF_UNMODIFIED_SINCE, - ] { error_headers.remove(name); } + http::header::RANGE, + http::header::IF_RANGE, + http::header::IF_MODIFIED_SINCE, + http::header::IF_NONE_MATCH, + http::header::IF_MATCH, + http::header::IF_UNMODIFIED_SINCE, + ] { + error_headers.remove(name); + } let replacement = serve_inner( - service, request_method.clone(), error_headers, target_uri, - target_path, Body::empty(), replacement_context, - ).await; + service, + request_method.clone(), + error_headers, + target_uri, + target_path, + Body::empty(), + replacement_context, + ) + .await; if replacement.status() == StatusCode::OK { response = replacement; used_local_error_document = true; @@ -468,7 +509,9 @@ pub async fn serve( // by Vhost/global pages in the outer HTTP response pipeline. if used_local_error_document || matches!( - response.extensions().get::(), + response + .extensions() + .get::(), Some(crate::web_server::metrics::ResponseKind::Php) ) { @@ -484,7 +527,9 @@ pub async fn serve( if used_local_error_document { // A local ErrorDocument is still an error response, even if the page's // normal Cache-Control or Expires rules say that successful pages are public. - response.headers_mut().insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); + response + .headers_mut() + .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); response.headers_mut().remove(http::header::EXPIRES); } strip_unnecessary_headers(&mut response, service); diff --git a/src/web_server/tests.rs b/src/web_server/tests.rs index 493e532..e144ebf 100644 --- a/src/web_server/tests.rs +++ b/src/web_server/tests.rs @@ -119,7 +119,10 @@ async fn missing_files_and_disabled_directory_listing_return_normal_errors() { ) .await; assert_eq!(missing.status(), StatusCode::NOT_FOUND); - assert!(missing.extensions().get::().is_none()); + assert!(missing + .extensions() + .get::() + .is_none()); assert_eq!(missing.headers()[CACHE_CONTROL], "no-store"); assert_eq!(missing.headers()[CONTENT_TYPE], "text/html; charset=utf-8"); assert_eq!(missing.headers()["x-content-type-options"], "nosniff"); @@ -1142,46 +1145,125 @@ async fn htaccess_legacy_deny_from_all_is_enforced_even_in_non_strict_mode() { id: "htaccess-deny-all".into(), name: "htaccess deny all".into(), document_root: tmp.path().to_path_buf(), - htaccess: htaccess::Config { enabled: true, strict: false, ..Default::default() }, + htaccess: htaccess::Config { + enabled: true, + strict: false, + ..Default::default() + }, ..Default::default() }; configured.validate().unwrap(); let service = configured.compile().unwrap(); assert_eq!(service.htaccess.as_ref().unwrap().warnings.len(), 1); - assert_eq!(serve_request(&service, &request(Method::GET, "/index.html"), "/index.html").await.status(), StatusCode::OK); - assert_eq!(serve_request(&service, &request(Method::GET, "/private/secret.txt"), "/private/secret.txt").await.status(), StatusCode::FORBIDDEN); + assert_eq!( + serve_request( + &service, + &request(Method::GET, "/index.html"), + "/index.html" + ) + .await + .status(), + StatusCode::OK + ); + assert_eq!( + serve_request( + &service, + &request(Method::GET, "/private/secret.txt"), + "/private/secret.txt" + ) + .await + .status(), + StatusCode::FORBIDDEN + ); } #[test] fn htaccess_legacy_order_and_ip_rules_follow_apache_22_precedence() { let tmp = TempDir::new().unwrap(); let ht = tmp.path().join(".htaccess"); - let config = htaccess::Config { enabled: true, strict: true, ..Default::default() }; + let config = htaccess::Config { + enabled: true, + strict: true, + ..Default::default() + }; - std::fs::write(&ht, b"Order deny,allow\nDeny from all\nAllow from 192.0.2.0/24\n").unwrap(); + std::fs::write( + &ht, + b"Order deny,allow\nDeny from all\nAllow from 192.0.2.0/24\n", + ) + .unwrap(); let compiled = htaccess::compile(tmp.path(), &config).unwrap().unwrap(); - assert!(htaccess::denied(Some(&compiled), "/index.html", "198.51.100.1".parse().unwrap())); - assert!(!htaccess::denied(Some(&compiled), "/index.html", "192.0.2.42".parse().unwrap())); + assert!(htaccess::denied( + Some(&compiled), + "/index.html", + "198.51.100.1".parse().unwrap() + )); + assert!(!htaccess::denied( + Some(&compiled), + "/index.html", + "192.0.2.42".parse().unwrap() + )); - std::fs::write(&ht, b"Order allow,deny\nAllow from 192.0.2.0/24\nDeny from 192.0.2.42\n").unwrap(); + std::fs::write( + &ht, + b"Order allow,deny\nAllow from 192.0.2.0/24\nDeny from 192.0.2.42\n", + ) + .unwrap(); let compiled = htaccess::compile(tmp.path(), &config).unwrap().unwrap(); - assert!(!htaccess::denied(Some(&compiled), "/index.html", "192.0.2.41".parse().unwrap())); - assert!(htaccess::denied(Some(&compiled), "/index.html", "192.0.2.42".parse().unwrap())); - assert!(htaccess::denied(Some(&compiled), "/index.html", "198.51.100.1".parse().unwrap())); + assert!(!htaccess::denied( + Some(&compiled), + "/index.html", + "192.0.2.41".parse().unwrap() + )); + assert!(htaccess::denied( + Some(&compiled), + "/index.html", + "192.0.2.42".parse().unwrap() + )); + assert!(htaccess::denied( + Some(&compiled), + "/index.html", + "198.51.100.1".parse().unwrap() + )); - std::fs::write(&ht, b"Order allow,deny\nAllow from 2001:db8::/32\nDeny from 2001:db8::bad\n").unwrap(); + std::fs::write( + &ht, + b"Order allow,deny\nAllow from 2001:db8::/32\nDeny from 2001:db8::bad\n", + ) + .unwrap(); let compiled = htaccess::compile(tmp.path(), &config).unwrap().unwrap(); - assert!(!htaccess::denied(Some(&compiled), "/index.html", "2001:db8::1".parse().unwrap())); - assert!(htaccess::denied(Some(&compiled), "/index.html", "2001:db8::bad".parse().unwrap())); + assert!(!htaccess::denied( + Some(&compiled), + "/index.html", + "2001:db8::1".parse().unwrap() + )); + assert!(htaccess::denied( + Some(&compiled), + "/index.html", + "2001:db8::bad".parse().unwrap() + )); } #[test] fn htaccess_legacy_unsupported_hostnames_fail_closed_with_strict_disabled() { let tmp = TempDir::new().unwrap(); - std::fs::write(tmp.path().join(".htaccess"), b"Deny from protected.example\n").unwrap(); - let config = htaccess::Config { enabled: true, strict: false, ..Default::default() }; - let error = htaccess::compile(tmp.path(), &config).unwrap_err().to_string(); - assert!(error.contains("only all, IP and CIDR are supported"), "{error}"); + std::fs::write( + tmp.path().join(".htaccess"), + b"Deny from protected.example\n", + ) + .unwrap(); + let config = htaccess::Config { + enabled: true, + strict: false, + ..Default::default() + }; + let error = htaccess::compile(tmp.path(), &config) + .unwrap_err() + .to_string(); + assert!( + error.contains("only all, IP and CIDR are supported"), + "{error}" + ); } #[test] @@ -2563,7 +2645,11 @@ fn fastcgi_handler_is_backward_compatible_and_prevents_php_as_cgi() { async fn generic_fcgiwrap_mount_passes_public_script_name_without_exposing_other_files() { let tmp = TempDir::new().unwrap(); std::fs::write(tmp.path().join("health.cgi"), b"#!/bin/sh\necho ok\n").unwrap(); - std::fs::write(tmp.path().join("configuration.txt"), b"private CGI settings").unwrap(); + std::fs::write( + tmp.path().join("configuration.txt"), + b"private CGI settings", + ) + .unwrap(); let (address, received) = fastcgi_fixture_record_params().await; let mut config = Service { id: "cgi-app".into(), @@ -2587,7 +2673,10 @@ async fn generic_fcgiwrap_mount_passes_public_script_name_without_exposing_other let response = serve_request(&service, &request(Method::GET, uri), "/health.cgi/more").await; assert_eq!(response.status(), StatusCode::OK); let params = received.await.unwrap(); - assert_eq!(params["SCRIPT_FILENAME"].as_str(), tmp.path().join("health.cgi").to_string_lossy().as_ref()); + assert_eq!( + params["SCRIPT_FILENAME"].as_str(), + tmp.path().join("health.cgi").to_string_lossy().as_ref() + ); assert_eq!(params["SCRIPT_NAME"], "/app/cgi-bin/health.cgi"); assert_eq!(params["PATH_INFO"], "/more"); assert_eq!(params["REQUEST_URI"], uri); @@ -2596,7 +2685,8 @@ async fn generic_fcgiwrap_mount_passes_public_script_name_without_exposing_other &service, &request(Method::GET, "/app/cgi-bin/configuration.txt"), "/configuration.txt", - ).await; + ) + .await; assert_eq!(forbidden.status(), StatusCode::FORBIDDEN); } @@ -2621,12 +2711,25 @@ async fn generic_fastcgi_responder_executes_only_configured_script_extensions() }; config.validate().unwrap(); let service = config.compile().unwrap(); - let executed = serve_request(&service, &request(Method::GET, "/handler.fcgi"), "/handler.fcgi").await; + let executed = serve_request( + &service, + &request(Method::GET, "/handler.fcgi"), + "/handler.fcgi", + ) + .await; assert_eq!(executed.status(), StatusCode::OK); assert_eq!(received.await.unwrap()["SCRIPT_NAME"], "/handler.fcgi"); - let static_file = serve_request(&service, &request(Method::GET, "/public.txt"), "/public.txt").await; + let static_file = serve_request( + &service, + &request(Method::GET, "/public.txt"), + "/public.txt", + ) + .await; assert_eq!(static_file.status(), StatusCode::OK); - assert_eq!(static_file.into_body().collect().await.unwrap().to_bytes(), "public"); + assert_eq!( + static_file.into_body().collect().await.unwrap().to_bytes(), + "public" + ); } #[tokio::test] @@ -2635,19 +2738,26 @@ async fn htaccess_filesmatch_enforces_denial_including_directory_index() { std::fs::write(tmp.path().join("index.html"), b"index").unwrap(); std::fs::write(tmp.path().join("secret.env"), b"secret").unwrap(); std::fs::write(tmp.path().join("public.txt"), b"public").unwrap(); - std::fs::write(tmp.path().join(".htaccess"), r#" + std::fs::write( + tmp.path().join(".htaccess"), + r#" Require all denied Deny from all -"#).unwrap(); +"#, + ) + .unwrap(); let mut config = Service { id: "files-rule".into(), name: "Files rule".into(), document_root: tmp.path().to_path_buf(), - htaccess: htaccess::Config { enabled: true, ..Default::default() }, + htaccess: htaccess::Config { + enabled: true, + ..Default::default() + }, ..Default::default() }; config.validate().unwrap(); @@ -2656,33 +2766,59 @@ Deny from all let response = serve_request(&service, &request(Method::GET, path), path).await; assert_eq!(response.status(), StatusCode::FORBIDDEN, "{path}"); } - let good = serve_request(&service, &request(Method::GET, "/public.txt"), "/public.txt").await; + let good = serve_request( + &service, + &request(Method::GET, "/public.txt"), + "/public.txt", + ) + .await; assert_eq!(good.status(), StatusCode::OK); } #[tokio::test] async fn htaccess_redirect_and_redirectmatch_are_applied_without_rewriteengine() { let tmp = TempDir::new().unwrap(); - std::fs::write(tmp.path().join(".htaccess"), r#" + std::fs::write( + tmp.path().join(".htaccess"), + r#" Redirect permanent /old /new RedirectMatch 302 ^/old-files/(.*)$ /archive/$1 ErrorDocument 404 /error.html -"#).unwrap(); +"#, + ) + .unwrap(); let mut config = Service { id: "redirects".into(), name: "Redirects".into(), document_root: tmp.path().to_path_buf(), - htaccess: htaccess::Config { enabled: true, strict: false, ..Default::default() }, + htaccess: htaccess::Config { + enabled: true, + strict: false, + ..Default::default() + }, ..Default::default() }; config.validate().unwrap(); let service = config.compile().unwrap(); let (_, warnings) = service.htaccess_diagnostics().unwrap(); - assert!(warnings.is_empty(), "local ErrorDocument is supported: {warnings:?}"); - let redirect = serve_request(&service, &request(Method::GET, "/old/docs?a=1"), "/old/docs").await; + assert!( + warnings.is_empty(), + "local ErrorDocument is supported: {warnings:?}" + ); + let redirect = serve_request( + &service, + &request(Method::GET, "/old/docs?a=1"), + "/old/docs", + ) + .await; assert_eq!(redirect.status(), StatusCode::MOVED_PERMANENTLY); assert_eq!(redirect.headers()[LOCATION], "/new/docs?a=1"); - let regex = serve_request(&service, &request(Method::GET, "/old-files/file.txt"), "/old-files/file.txt").await; + let regex = serve_request( + &service, + &request(Method::GET, "/old-files/file.txt"), + "/old-files/file.txt", + ) + .await; assert_eq!(regex.status(), StatusCode::FOUND); assert_eq!(regex.headers()[LOCATION], "/archive/file.txt"); } @@ -2690,23 +2826,40 @@ ErrorDocument 404 /error.html #[tokio::test] async fn htaccess_status_only_redirects_do_not_require_location_headers() { let tmp = TempDir::new().unwrap(); - std::fs::write(tmp.path().join(".htaccess"), r#" + std::fs::write( + tmp.path().join(".htaccess"), + r#" RedirectMatch 404 ^/missing/ Redirect gone /removed Redirect 302 /old /new -"#).unwrap(); +"#, + ) + .unwrap(); let config = Service { id: "status-only".into(), name: "Status only".into(), document_root: tmp.path().to_path_buf(), - htaccess: htaccess::Config { enabled: true, ..Default::default() }, + htaccess: htaccess::Config { + enabled: true, + ..Default::default() + }, ..Default::default() }; let service = config.compile().unwrap(); - let not_found = serve_request(&service, &request(Method::GET, "/missing/secret"), "/missing/secret").await; + let not_found = serve_request( + &service, + &request(Method::GET, "/missing/secret"), + "/missing/secret", + ) + .await; assert_eq!(not_found.status(), StatusCode::NOT_FOUND); assert!(!not_found.headers().contains_key(LOCATION)); - let gone = serve_request(&service, &request(Method::GET, "/removed/file"), "/removed/file").await; + let gone = serve_request( + &service, + &request(Method::GET, "/removed/file"), + "/removed/file", + ) + .await; assert_eq!(gone.status(), StatusCode::GONE); assert!(!gone.headers().contains_key(LOCATION)); let redirect = serve_request(&service, &request(Method::GET, "/old"), "/old").await; @@ -2717,7 +2870,9 @@ Redirect 302 /old /new #[test] fn htaccess_popular_php_front_controller_file_compiles_without_strict_compatibility() { let tmp = TempDir::new().unwrap(); - std::fs::write(tmp.path().join(".htaccess"), r#" + std::fs::write( + tmp.path().join(".htaccess"), + r#" # Typical monitoring/PHP installation, without application-specific rules in RustProxy. Options FollowSymlinks Multiviews ErrorDocument 404 /error.php?404 @@ -2734,20 +2889,40 @@ RewriteCond %{REQUEST_URI} !^rrd/ RewriteCond %{REQUEST_URI} !=/server-status RewriteRule ^(.*)$ index.php/$1/ AcceptPathInfo On -"#).unwrap(); +"#, + ) + .unwrap(); let config = Service { id: "monitoring-app".into(), name: "Monitoring app".into(), document_root: tmp.path().to_path_buf(), - htaccess: htaccess::Config { enabled: true, strict: false, ..Default::default() }, + htaccess: htaccess::Config { + enabled: true, + strict: false, + ..Default::default() + }, ..Default::default() }; let service = config.compile().unwrap(); let (_, warnings) = service.htaccess_diagnostics().unwrap(); - assert_eq!(warnings.len(), 3, "expected unsupported Options and missing PHP handler: {warnings:?}"); - assert_eq!(warnings.iter().filter(|warning| warning.contains("Options")).count(), 2); - assert!(warnings.iter().any(|warning| warning.contains("FastCGI handling for .php is disabled"))); - assert!(!warnings.iter().any(|warning| warning.contains("RedirectMatch"))); + assert_eq!( + warnings.len(), + 3, + "expected unsupported Options and missing PHP handler: {warnings:?}" + ); + assert_eq!( + warnings + .iter() + .filter(|warning| warning.contains("Options")) + .count(), + 2 + ); + assert!(warnings + .iter() + .any(|warning| warning.contains("FastCGI handling for .php is disabled"))); + assert!(!warnings + .iter() + .any(|warning| warning.contains("RedirectMatch"))); } #[tokio::test] @@ -2756,7 +2931,9 @@ async fn htaccess_observium_style_front_controller_executes_php_path_info_withou std::fs::write(tmp.path().join("index.php"), b"