diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a7d655..432d5df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Release history focused on **features, settings, default behavior, compatibility ## 0.42.2 — Generic FastCGI/CGI hosting and Apache compatibility +- **Maintenance: status-only Apache redirects:** accept `RedirectMatch 404 /\.` and other bounded 404/410 status-only Redirect/RedirectMatch forms without a target URL. Return the requested status with no `Location` header; keep path hardening and redirect validation. Add a regression fixture with a typical PHP front-controller `.htaccess` file, including unsupported non-security directives in non-strict mode. +- **Maintenance: observable DNS/DDNS ACLs:** keep the exact system DNS error or timeout rather than a generic failed-lookup warning. Failed refreshes emit structured warnings with hostname and reason; successful initial/change resolutions emit informational events. Add an authenticated read-only `/api/acl/dns-status` view and ACL profile panel diagnostics (active IPs, lookup time, remaining validity, error). DNS errors and expired addresses still fail closed. No change to ACL configuration or permission semantics. Source changes require a full Rust compile/test and deployment smoke test. - **Legacy Apache access rules:** compile and enforce `Order`, `Allow from` and `Deny from` for `all`, IP addresses and CIDR networks (IPv4/IPv6), including `Deny from all`, rather than rejecting them independent of Strict mode. This preserves access restrictions. Unsupported security and handler constructs still fail closed; non-security unsupported directives remain warnings when Strict is off. - **Panel:** clarify that turning Strict mode off does not disable security rules. Show per-Web-Service skipped .htaccess directives with file and line from the compiled configuration; diagnostics are also logged as warnings. - **Universal FastCGI handlers:** Web Services support `php.handler=php_fpm` (default for existing configurations), `fcgiwrap` (external CGI runner), or `fastcgi` (generic responder). Socket/loopback TCP endpoint, executable extensions, `SCRIPT_NAME` public mount prefix, PATH_INFO, streaming bodies and bounded headers/timeouts are configurable independently per Web Service or shared profile. Verified Vhost Basic Auth identity can populate `REMOTE_USER` and `AUTH_USER`; reserved CGI identity and script parameters are never accepted as untrusted custom overrides. A CGI-only Web Service refuses raw static file delivery. No application-specific filesystem or URL paths are hard-coded. diff --git a/SHA256SUMS b/SHA256SUMS index 40b7dca..af110d4 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ 4140a2956264b44f259e6a37fc00ba02097bbe68b09296e04d3d243c1287129b .env.example 0a5e87541831edca0e7164c6469dba01a8a7053ab14dbfb8019c83e4db10edc2 .gitignore 3c4638dc086333b8383c5bc77fe967b790075439f5e7a8257e5dd0dd4cf4233b AGENTS.md -b446765161f494e1e07196bcec6f6edcc8e42216bed8b8ad6dfc58a0136eb89e CHANGELOG.md +d1f91464ba2452a27ee2ea540297bdecbbf7dd251ba22b9eca8819dd36cd336f CHANGELOG.md c28d825120a878684b511b1a6a4f372aced5098ed7b9bec8b318c4ec3fb1cbf4 Cargo.lock 3ac98730af5caa39f81d28f4a4f7f14710fbb53d625794dd5704e65afebe4d8e Cargo.toml 788745d4f70a0382c6280020afbd48844bb2af65e835a826852143f8132cdeca Dockerfile @@ -38,8 +38,8 @@ d3ceee01252c1b7280a7f0d38828def899c3e3baeb62c27c7946fac23918c7f7 docker-agent/m f30c895df3d7f289f3b7c9a73969009ecf91110f59cb247daa242f68e78aa014 docker-agent/server.go 20313df0c14a1696d099ed881b159fe854e92538a60548a1729f92babaead881 docker-agent/system.go 188b74ec4f58da1b46d86925a67b6a590c92fb4fd7516e8d03d43871bc3b4542 docker-agent/system_test.go -c0940a4b323d71931cf2ad4ad24d58b6d6bfd49af90c6e3fc91fcbe2b4cf312f docs/ACCESS.md -74046c96c7c28e5d0f5d81ee9cf223a6519dad8abc0945959b78eab750815480 docs/API.md +0b86005a5b83671b8c1ded181e3bf95194d250b87bb7cfb3b4567567bac9e8ec docs/ACCESS.md +6f1d77e529f8f4d837e76a2feaa8eb4e47a4646c2903d598651217f679266a98 docs/API.md 728b15b9825f547f34c4121219784798dd046fbbdd72ece8906d0cd77e8efc64 docs/BACKUP.md bfe96dd91dfc6e07918a662d98b036f12ceb011a5aa8381b3778bd0c964b19ab docs/CACHE.md 51d34823d139ff3b0b8e1cf1a31850746be5ed7da847a2cca51be36fd5f7733a docs/CACHE_TEMPLATE_LIBRARY.md @@ -49,11 +49,11 @@ bfe96dd91dfc6e07918a662d98b036f12ceb011a5aa8381b3778bd0c964b19ab docs/CACHE.md 16d4510e38d43c3bbde9b7dab7af3aeb0cb837dc2f1956cfaad7a9a11bea3bfc docs/DASHBOARD.md 53cb0ce7db5ce25e4c2381de3a6e875d212deeed08861da63050de6c51a442bd docs/DOCKER_DISCOVERY.md 6b575c6c1c7e01b252bbbf441ab100745dace3799f70fd65b840cba4681d1c08 docs/FASTCGI.md -e7c5ec82c5a0ec336fa7e88835f82925bb75f213975309853a3d748b28f1b6b2 docs/FEATURES.md +a024fa9e6113ca1ae99bb62e25a607ff1e092728c1c5519cf99793ef9ae215ba docs/FEATURES.md f7bb59821e0d6c45ae2a1789086fd9dab33d91c0ceae784ae68f64bd13b5f496 docs/HEADLESS.md bce732d845c23ad677ae811e7529b9322ab41d04ca808e04087d0f76bccd9309 docs/INSTALL.md 3268808766ad66263e465f251dce18cff2e7ede355638dc2b0975870b1a5eead docs/LOAD_BALANCING.md -425f1ca32172d987b6fabbd08076bbd091101193e103e9fe5452e0709159a2bd docs/LOGS.md +e5e50be31b3160588599336b1871b07a1e829b202454a67d2dc4e2e754d23eab docs/LOGS.md 3b889851ba3405247861391aefbcfcaa5a96cf9b09b3e0e0e412ec2f54e11b1a docs/MIGRATION.md 48105c4303401aa99ffff00d3ebaf3024535a492a4a7b883c6803e4732b37434 docs/MONITORING.md 6d3937088eeb67a9f690d44ebe0b6e660b68116dbf69091ac7816bdc52cec2b6 docs/PERFORMANCE.md @@ -66,12 +66,12 @@ e90842a75459ddb5892334f66a4139d9301280b4d0c17077d211749bd7c90d80 docs/RESPONSE_ a1f69782b08d395a9672250eaac4595ffb1465b66a7a62901781a01a9030c6a0 docs/STREAMS.md c9c9a0b401f0565f15b834d855bfdb34edb3eab46bff03d9e0825af204d20bf8 docs/TODO.md c4407cbd70d181e87f64e8d1736624d7b8b59a04b915ad3464f0e1f16d474e99 docs/TRANSPORT.md -1335bc863391858ff4d584eb7f8ad771e270d36708061f2a1bff09de7906a8ab docs/TROUBLESHOOTING.md +df83d07d7186a5eea60d206dee3cb62b7f6505a066d84141fc53130e2f29760b docs/TROUBLESHOOTING.md 53005e1eeb460c960794e2b2f1ab7cfc472c510b14bea3193d25f5f81ba7a1e4 docs/VCL.md 4a5534b628c18f4e83c67c6136b60969c884391fbe55cc6bd4f2354711d8ffb7 docs/VCL_SUPPORT_MATRIX.md 382e084a1f9e35627ccb43eaf451c18fb6d0cc752397c2178108d71de592a931 docs/VCL_TRAFFIC_COOKBOOK.md 181444ea2c28171ed89ead25dcfc60ee6bd05f7b01c1a49d8248a307dc9be7a4 docs/VHOSTS.md -720d4bf8ba2bfd502de98fa2fc9df97d7155e36f10e7106238646fed8a5f19ff docs/WEB_SERVER.md +ee23424a3446e25a17a84c1b50de224e27d99ee04a6655f2e142bad6c63c25f8 docs/WEB_SERVER.md 42822b1c9801bcadb0e2d785cb91883ca2df1da141222631f153030c95f5e197 docs/images/about.png deff2393a987ac7102179dc85b48baf2c4a3882291bb8c7c584d760cc497c631 docs/images/api.png 74df8228ea6283004b3e87b4d297e43637371eb4a700b69c7248114c8670777a docs/images/cache.png @@ -137,8 +137,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 -15cd8725e17d0f9ce60423574ed7405f68f25697247987cae048ddda71eb2075 langs/en_US.json -4947f1cbff86adb68ad840cae65a27f5ad553fc0273af2b3fbea974509a32191 langs/pl_pl.json +94dd341ba75ddc719adb58f6c4448d788d7650d83b993772b34a91939089d567 langs/en_US.json +14dec3e0ce949606adb24755aec204fad741fb3c51d9878771f704ed8a4c792a langs/pl_pl.json 38773ed251a8c24af353f4744e498ae2bc7d4151df7927e942c4ac223f6008e1 make_zip.py e830d37dd1f81a4b0aa7d535f5bba69e34e433b0fd99cc8ee0b296786c32379a migrations/0002_admin.sql 20112cc82192098b8d602f1c4f7ca08712e9e1366c845fabb92753187c370d35 migrations/0003_certificate_renewals.sql @@ -179,8 +179,8 @@ e69813fb1d3a4cdcfb7243964cc323fc21a603087bf2e84188fa42b9d3cee4b5 scripts/runtim 91c883cfdce94c8c22c98749f611317f538a112d29be4f3fb1fa460b8f29ceaa scripts/start_stream_backends.sh 22e880e98c7b9d700c7a4c02b9b1d543e5dbd1f4ecdca42813a1083165b32a19 scripts/version.py 78efae6c43732c0f5527d467bf07d1f890da361925416c89b58bc449d852fc2b src/acl.rs -1d55ecb2e104be1d3b19623a1380584724c106ed234d2e79fd2a2fef1d891ee3 src/acl/dynamic/mod.rs -1eee2ea2c8dd6068dd0bbb058a06d26436f14767d8efbc2010bbdb4e3e523672 src/acl/dynamic/tests.rs +f097cce1f831e01b68688eb60c1b6393413131e6543c4627f3cedd9ef706193b src/acl/dynamic/mod.rs +978fdb2f61b7f04245609a275cd80a7f473c89ce7205d3aff1fd1f11ffacd7aa src/acl/dynamic/tests.rs 50d9a0009cdcee6dd34a6215755d98f38ea18fa39b9faf070d1a7649eeac6aae src/acl/tests.rs f15b5bb11e2b949d7ed203711275b24b3f76de2ab617ef8b7345585c15ca34bd src/acme.rs 767d2f26fa8dea4ff6717d1e20ac0611b83bd20ab64bda8163cc6a5cc4dcb614 src/acme/headless.rs @@ -194,7 +194,7 @@ c51fd51177a476be6462ca980e9bc13f0d0b41538f520118b80a685130f0dbf0 src/acme/runti b10a8fddb3dac455e5779e70c8045fea7c0cc19e1974737f749321a5f7579275 src/acme/tests.rs b28a08ea996befe10949676f40fab5f1036a274c7d0ab1175cf5c43c59849dc3 src/admin/access.rs f73678bfa4c4f92779cf4e8ae2feb37419de320fb1b53111c982539d5761dbcf src/admin/alerts.rs -7e23e70451c6498a43f65751c5bd7a110c63e24da05f6126b38dbacb33c962ca src/admin/api_token_access.rs +898351284480b0d55c6f1ed56c2185ca137fc44926864ab61238ff7f6e98cb6d src/admin/api_token_access.rs 5f5b150bb8f51f57462e519650093354ae7b40fcb80c4380fd3391a33f4b30f2 src/admin/api_tokens.rs 498f3640101b0505b5d8f6aee05b2c0e8a248a6ed53ef52b287496839919692b src/admin/cache_rules.rs 34e851f725e8605e3c5d9946e56ac035996f3bd9d608169cba3408060d229c9b src/admin/certificate_api.rs @@ -212,7 +212,7 @@ f9b2c8fe62cc92d7693e46145b2543b12dd6d4943fe2d52c67ed6958d4af83de src/admin/docu e2253599b5e39510946729920d240711403a3889cc495eb49824296228f1d080 src/admin/file_logs_query.rs 1594c8666991c1d07487a6a718211ef404cf49114721960f7e119bb7f605e3d2 src/admin/logging_api.rs 781fd5f176dd8f2372f75bd90edcf160708e2d0a8d6a115ba4b283c0cd49eb2d src/admin/mod.rs -7db46bdbef37c8295d7aee2c0d9150ccd51c30ca6fd2af9f859785766b8e926d src/admin/openapi.json +321e1b3a1a501db774485724f2b7443081054e65f789ccee0ae35c71a9422f16 src/admin/openapi.json 9f8842cdec27d703d1795dd6eb37d9420e9f5a2e56a0df93278c92bace5d1f4c src/admin/operations.rs 257d93a29d0bda96462bcf695aba8d0ec0f9412c379e066ec46ae8ee034e3a53 src/admin/panel_assets.rs f5127855c2994d052678865df36d703b74f4a0afc633daf7718b10da18d26e37 src/admin/panel_content.rs @@ -224,13 +224,13 @@ ea202c67d9acb7614046f153beecdff10d5822b3d5627eaf2ebda33954b36474 src/admin/pref 62ecbae5dee00aeeca3eb806e2605372471dfab971cde8f66f11e711df8fcea1 src/admin/public/mod.rs 7a00e4ab943f74d2b1bdcbfab7f9cd3f584e9f59536b4aca6c4c31f5f5508d12 src/admin/public/tests.rs 6930b4f4b45257772b321b20a9becdf9bc4610274852948ba38c2d0cdf02dfaf src/admin/refresh_preferences.rs -8df90dffdbdb14e068d26f2a81801a76c69ec0bb65a9d13a4cae7bdf367be6cd src/admin/router.rs +3d210447933638b507e70692bcbacf7bb1bb1a62f9bf3b3300ee0dc5c7c3e20e src/admin/router.rs fba52102e77ca8871a42f97c91be8f10a9aa4f997868652d550fff3fbd41b66e src/admin/session.rs -1c4d04b14a508fca7537f54e660124f4dae1964b48d7bd3b878ec4faa7156805 src/admin/status.rs +38f53c52c2e3bc49b5ad4254c657d282cf4ca7c8c11c6a79cc1d7a2086f017de src/admin/status.rs bac2116e9a7d5f19a112565e1483787ff6102f489bed0cb3b0b3e2102ddd3edb src/admin/status_live.rs c20f214e2ec2a14d8a88d07a63a27d9396a7a6bf9446f6ee31dbd77b12e4b585 src/admin/status_system.rs ea1d0b8ff69157215f9358f0de35b91462ab2bf1fb97f9ce9b37846d0432c56b src/admin/tail.rs -b4bcfb9fc989d5586ca3d82e8b5777c306e9a6720f9ec011d09bd786db9faf49 src/admin/tests.rs +6c72807e230f3df2d7c72f25f840e2f0accdf95371d9c4d63f9a49c1a7a35876 src/admin/tests.rs d6c7ef48325c8f4f7ae7504827c0255c263b41c838f61960381907ca78eb9b95 src/admin/web/acl-picker.js 1e46ac359a11a85374d93936fb849864bea43021c20770fff5076acd846e8859 src/admin/web/acme.js 30a71c399e9a2cd9a4c1830568e4767f219ce09bca35f6d5fd22424f1a6617ac src/admin/web/admin_origin_rejected.html @@ -302,12 +302,12 @@ e6c4d91d1542d0a5b47bb8736f9539d43a6713df5a473b635519d5b7eac2eb9c src/admin/web/ 0a5fff35555153f59d4346933030a67b6e1a8768cee7a47cfa2fcf1a2c564f63 src/admin/web/favicon.svg e0f0b302092ced1c84ef7e99864984444f0e9d4e3b7d85e74d3507d566952a7f src/admin/web/file-logs.js 85f54ce519140a38e31fb1b3d5974585748d7162f0499aa63703c1db56334b2c src/admin/web/host404.js -31a45d496f39bec083a13b7ce68989cc3af25926aa313f4defb5ae09d87007da src/admin/web/index.html +64f680beeea88eea811d4d85b7d484f656d961c3369432be11adde37d010a95d 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 -6185182b81273372dbd506fa57281ee81d3cd1233ac328640a7f33794f754e1b src/admin/web/management.js +0c6ca054a7eaabaa34c50fde251c114f03c73055f6e44272dee740abbe780984 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 @@ -636,9 +636,9 @@ d15716d8fa0d722e3189367fd395cac71c2f2a178335120a74a01696abc7cc04 src/web_server 6b24c3ed2249e7c0d29ab27a5bc8ea05527a2a0314ae067acd6035327db3e814 src/web_server/fastcgi/response.rs 92d2ab4d7ecb766bbc705f8eba94c1ca33347ffb84b36e0ad0eccfed5915473f src/web_server/filesystem.rs d4fec3682532b0f2d11a0aefcd024f69fb623a39922ddb6c528a2d2de265347d src/web_server/htaccess.rs -0b5060ea681bc35085511658d0d92d276aa39aa5c44cbab8b2adbdad84a05b8e src/web_server/htaccess/model.rs -2f8b33e736a49f5518360bf2be433dfdb0641eb00474da83cf7f2d255d6184d5 src/web_server/htaccess/parse.rs -8dce3855a191fea50962cd7e1132335e422047c9c41e7f5e1b3b023e25675131 src/web_server/htaccess/rewrite.rs +370f5ee3bb0d1627e3a14c2f2a9920035fb80fcc6736bb5f75c02aa43899b2c0 src/web_server/htaccess/model.rs +a149ae8497f776fd580034f78e179d36a936ad9fa6c002fd8509ab8773a3a09b 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 @@ -650,8 +650,8 @@ e5f5fbe702f66bfcbcbc1d1f3cd3d89bdbb929bb86aed94868a2a06a4b9e59e3 src/web_server 7da903c1a69be0ae6b85772b3208c518679efa8ed9d3e98adb694483518156b6 src/web_server/response/headers.rs 2665d4eac9a6430d68224874784cb65d9b9d424353af77735caf044401d08cb4 src/web_server/routing.rs 9e584eb4455a18641c2c89f9e9725745c93f32877abf0f0f2fbea9e3d5ef38c3 src/web_server/security.rs -42937064cd38468b0c2e2f57b810bee9df9e6568e74d1ab3d805ea9a39259375 src/web_server/serve.rs -951291172a80ab57205aa10dd95e2805d0afc82f86e3c46479c96962a3853c92 src/web_server/tests.rs +487515bf6c1f8630a4aa7aacdf13bb9ae13c8610422f0426b620b7ee49014788 src/web_server/serve.rs +3862c31e3f031c5ae8d7cf76dcfeeab48b806d7cfe9ab5f2c3815cc87c6fd8e8 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/ACCESS.md b/docs/ACCESS.md index 3697ac6..e603c1c 100644 --- a/docs/ACCESS.md +++ b/docs/ACCESS.md @@ -13,6 +13,21 @@ Global restrictions add to per-vhost and path rules. Rate-limit requests are cou - **IP/CIDR ACL:** allow or deny IPv4/IPv6 networks. Use reusable ACL profiles for settings shared by several domains. Both ordinary and Docker Vhosts use a searchable multi-select with selected badges and a preview of IP/CIDR rules, country restrictions and the default policy; the selection changes presentation only, not ACL evaluation. A Vhost can select up to eight profiles (`acl_profile_ids`, or one legacy `acl_profile_id`); Docker assignments can override or inherit the agent's profile selection. - **DNS/DDNS:** an ACL `allow` rule may use a hostname, such as `allow office.example.ddns.net`; `deny` with DNS is not supported. Records are refreshed periodically; unknown, failed or expired resolutions authorize nobody under the allow rule. This is appropriate for a trusted, controlled DDNS record, not a replacement for login. + +### Diagnose dynamic DNS access + +Open **ACL profiles -> DNS/DDNS ACL resolver status -> Refresh DNS status** or request authenticated `GET /api/acl/dns-status`. The view includes every DNS rule (global, profile, Vhost and location), not just the currently selected profile. It returns the normalized hostname, `pending` / `resolved` / `failed` / `expired`, the **currently permitted A/AAAA addresses**, time of last lookup, remaining validity and the most recent failure reason. The API is restricted to the admin session or a read-scoped administrative API token. + +Resolution starts when the server starts, updates after configuration changes and refreshes every 60 seconds. A successful answer is valid for up to 180 seconds, provided it remains in the active cache. Every failed refresh **immediately removes the permission** for that hostname. `resolved` does not mean that a particular visitor is allowed: the source IP seen by RustProxy must be one of the returned addresses, and all other attached ACL/country/access policies still apply. Verify whether traffic arrives through a reverse proxy, NAT or IPv6 before blaming DNS. + +Resolution uses the operating system's resolver (the server running RustProxy, or the container's resolver). Check on that host: + +```bash +getent ahosts office.example.ddns.net +journalctl -u rustproxy --since '10 minutes ago' | grep 'ACL DDNS' +``` + +Look for `ACL DDNS resolver inventory updated` and `ACL DDNS resolved` at info level in the journal. Failed lookups emit a **warning** with the hostname and actual system resolver error or timeout; if error-file logging is enabled, these warnings are written to the configured error file. The access log contains HTTP requests, not DNS refresh results. No warning after the first refresh is **not proof of a failure**; a successful lookup that resolves to the wrong address also denies access without generating a DNS error. If the status remains `pending` for more than one refresh interval while the rule exists in the active configuration, investigate whether the DNS worker started or crashed. Avoid changing the ACL default to `allow` as a workaround. - **Country access:** allow-only or blocking based on the configured GeoIP database. Allow-only mode fails closed when a country cannot be determined. Keep the GeoIP database updated in **Settings → GeoIP updates**. - **Cloudflare client IP:** enable the integration only when traffic really arrives through a controlled Cloudflare/trusted-proxy boundary. Never trust arbitrary client-supplied forwarding headers as an identity proof. diff --git a/docs/API.md b/docs/API.md index f288c07..294f976 100644 --- a/docs/API.md +++ b/docs/API.md @@ -20,6 +20,7 @@ The current bundled `src/admin/openapi.json` declares these operations (among ot | `POST /api/config/geoip/update` | Run a GeoIP download/check/reload immediately using already-saved GeoIP settings; does not change revision. | | `GET /api/config/history` · `POST /api/config/history/restore` | Review/restore retained configuration snapshots. | | `GET /api/status` · `GET /api/backends` | Operational status and backend observations. | +| `GET /api/acl/dns-status` | Read-only status for configured DNS/DDNS ACL names: currently allowed A/AAAA addresses, lookup time, TTL and last error. Protected by admin session or RO/RW API token. | | `GET /api/cache` · `POST /api/cache/purge` · `POST /api/cache/invalidate` | Cache observations and authenticated invalidation. `GET` supports the lightweight `view=live` polling view. | | `GET /api/cache/rules/stats` · `GET /api/cache/rules/targets` · `POST /api/cache/rules/test` · `POST /api/cache/rules/import-vcl` | Cache rule match counters, the vhosts a rule can target (ordinary and generated Docker vhosts), simulation of saved or draft rules for a test request/response (also for Docker vhosts), and conversion of a VCL subset into rules (nothing is saved). See [Cache rules](CACHE.md#cache-rules-vcl-style) and the [supported VCL import matrix](VCL.md). | | `POST /api/policy/import-haproxy` · `POST /api/policy/test` | Convert a strictly supported HAProxy snippet into a policy draft, or evaluate policy rules against a supplied fixture with a trace. Neither endpoint saves configuration. See [HTTP policy rules](POLICY.md). | diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 73dcdc7..bf7d72c 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -32,7 +32,7 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se - Static sites and downloads served from reusable **Web Services** shared by several Vhosts. - Index files, optional directory listing, MIME mapping and attachment extensions. -- `try_files`, regex rewrites and a safe subset of Apache `.htaccess` rules. +- `try_files`, regex rewrites and a safe subset of Apache `.htaccess` rules, including status-only `RedirectMatch 404` / `410` rules without `Location`. - Conditional requests (`ETag`, `Last-Modified`), byte ranges, precompressed `.br`/`.gz` sidecars and optional Linux `sendfile`. - Symlink policy, attack-probe blocking and header hardening presets. - External FastCGI: PHP-FPM pools, CGI scripts via fcgiwrap, and generic FastCGI responders; Unix or loopback TCP endpoints, script allowlists, SCRIPT_NAME mount prefixes, PATH_INFO, bounded request/resource limits, Vhost location routing and shared profiles. @@ -52,7 +52,7 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se ## Access and security -- IP/CIDR and DNS/DDNS allow/deny rules, reusable ACL profiles (up to eight per Vhost). +- IP/CIDR and DNS/DDNS allow-only names with periodic A/AAAA refresh, a fail-closed resolver, diagnostics in ACL profiles and a read-only status API; reusable ACL profiles (up to eight per Vhost). - Country allow/deny lists with automatic GeoIP database updates and a searchable country picker in global and Vhost security settings. - Request rate limiting per Vhost and globally, with burst and `Retry-After`. - HTTP method policy, request Content-Type denylist and User-Agent blocking. diff --git a/docs/LOGS.md b/docs/LOGS.md index 0ccd870..24a34e6 100644 --- a/docs/LOGS.md +++ b/docs/LOGS.md @@ -74,6 +74,8 @@ Plain words search stored values; quotes allow spaces, `!` negates a clause, `*` RustProxy can persist warnings/errors and selected protocol failures separately from access traffic. Set output level, sink and optional retention/rotation under **Settings → Logging** and related error-log controls. Access logs may use the global structured file or per-Vhost locations. Log paths must be writable by the service identity, including when running inside a container/systemd sandbox. +**DNS/DDNS ACL diagnostics:** a failed DNS refresh logs `ACL DDNS resolution failed` with `hostname` and `reason` (timeout, OS resolver failure, empty or invalid A/AAAA answer). The error-file sink records this warning when enabled. Successful DNS refreshes and changes to the resolver inventory are informational events normally found via `journalctl -u rustproxy`, not warning/error records. For both successful and failed lookups, use **ACL profiles → DNS/DDNS ACL resolver status** or authenticated `GET /api/acl/dns-status` to see the last query result, permitted addresses and refresh time. A resolved name with the wrong client IP is an ACL mismatch, not a DNS error; see [Access](ACCESS.md#diagnose-dynamic-dns-access). + The installed Linux deployment may configure `logrotate` for durable logs; check the installed policy rather than assuming all platforms rotate automatically. Logging is bounded/asynchronous where practical, and some records can be dropped under saturation; inspect sink drop/error counters in monitoring. ## Privacy and investigation diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 219bc14..bbd92a3 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -2,6 +2,10 @@ Start with a reproducible request, its hostname/path and the exact listener. Compare **Vhost**, **Backend**, **Cache**, **Logs** and the service journal before changing multiple settings at once. +## DNS/DDNS ACL name resolves but a client is blocked + +Open **ACL profiles -> DNS/DDNS ACL resolver status** (or authenticated `GET /api/acl/dns-status`). Check that the hostname appears and that its state is `resolved`; compare its A/AAAA address list to the actual incoming client IP as seen by the proxy. `pending` means no completed attempt, `failed` includes the OS resolver error, and `expired` means the previous addresses are no longer usable. A `resolved` entry that does not contain the actual IP grants no access. A missing hostname means the active configuration does not contain that DNS rule. The error log records failed refreshes, not successful lookups or IP mismatches. Test `getent ahosts ` on the RustProxy host/container, verify DNS reachability, and inspect the ACL profile, Vhost, global rules and trusted proxy IP handling. Do not set default access to `allow` to bypass a failed DNS rule. + ## Quick symptoms | Symptom | First checks | diff --git a/docs/WEB_SERVER.md b/docs/WEB_SERVER.md index 1d46e9b..5f253ec 100644 --- a/docs/WEB_SERVER.md +++ b/docs/WEB_SERVER.md @@ -59,6 +59,8 @@ An optional bounded Apache-style `.htaccess` compatibility layer supports a **su With **Strict unsupported-directive mode disabled**, harmless unimplemented directives (such as `ErrorDocument` and unsupported `Options` tokens) are skipped and logged as warnings during Web Service validation/apply; inspect the server logs or expand **Skipped .htaccess directives** on the Web Service card for file/line locations. They do **not** become active Apache functionality. Unsupported security/handler syntax is still rejected to avoid unintentionally exposing protected content. +`RedirectMatch 404 /\.` is accepted as a **status-only rule**: a matching request returns HTTP 404 without a `Location` header. `Redirect gone /old` and `RedirectMatch 410 ` similarly return HTTP 410, while ordinary `Redirect 301 /old /new` and `RedirectMatch 302 /replacement` retain redirect behavior. This works without `RewriteEngine`. Safety filters for protected paths still run before rewrites and can return 403 for a hidden or otherwise forbidden file. `ErrorDocument`, unsupported `Options` values and `AcceptPathInfo` are still skipped with warnings when Strict is off; they do **not** enable their Apache semantics. If your application needs PHP `PATH_INFO`, enable it in the FastCGI Web Service settings instead; see [FastCGI](FASTCGI.md). + For common Apache 2.2 migrations, `Order deny,allow`, `Order allow,deny`, `Order mutual-failure`, `Allow from all` / `Deny from all`, and `Allow from` / `Deny from` explicit IP addresses or CIDR networks (IPv4/IPv6) are supported and **enforced** using the actual client IP. For instance, `Deny from all` blocks the affected directory, returning HTTP 403; it is not silently ignored. `Order allow,deny` denies unmatched clients by default, while `Order deny,allow` allows them by default. Hostname-based ACLs and other unsupported access/authentication constructs fail validation even with Strict disabled. Test allow/deny cases after migrating; legacy access rules are not a general Apache authorization emulator. ## Admin editor layout diff --git a/langs/en_US.json b/langs/en_US.json index 193c81f..09b06c6 100644 --- a/langs/en_US.json +++ b/langs/en_US.json @@ -2948,6 +2948,17 @@ "aclRuleIp": "IP / CIDR", "aclRuleDns": "DNS / DDNS", "aclDnsAllowOnly": "DNS/DDNS addresses only support allow rules. Use IP/CIDR for deny.", + "aclDnsStatusTitle": "DNS/DDNS ACL resolver status", + "aclDnsStatusHelp": "Shows the current A/AAAA addresses and last DNS error. Compare them to the actual client IP. Unresolved names do not grant access.", + "aclDnsStatusRefresh": "Refresh DNS status", + "aclDnsPending": "Awaiting first lookup", + "aclDnsResolved": "Resolved", + "aclDnsFailed": "DNS failed (access denied)", + "aclDnsExpired": "Expired (access denied)", + "aclDnsAddresses": "Resolved addresses", + "aclDnsChecked": "Last lookup", + "aclDnsError": "DNS error", + "aclDnsNoNames": "No DNS/DDNS names configured in access rules.", "aclDnsHelp": "DNS/DDNS allow rules resolve A/AAAA every 60 seconds. DNS errors remove access (fail closed). Enter a hostname such as office.example.ddns.net; no URL or wildcard. Select Allow exceptions with default Deny. Up to 128 unique hostnames, 32 addresses per hostname.", "overviewExtraColdQueueMemory": "COLD queue RAM utilization", "overviewExtraColdQueueMemoryDescription": "RAM used by the COLD write queue relative to its configured RAM budget, not the disk cache.", diff --git a/langs/pl_pl.json b/langs/pl_pl.json index 0a89b61..beb67b2 100644 --- a/langs/pl_pl.json +++ b/langs/pl_pl.json @@ -2948,6 +2948,17 @@ "aclRuleIp": "IP / CIDR", "aclRuleDns": "DNS / DDNS", "aclDnsAllowOnly": "Reguły DNS/DDNS obsługują tylko allow. Do deny użyj IP/CIDR.", + "aclDnsStatusTitle": "Stan DNS/DDNS w ACL", + "aclDnsStatusHelp": "Ostatnie adresy A/AAAA i błąd DNS. Porównaj je z rzeczywistym IP klienta. Nierozwiązana nazwa nie daje dostępu.", + "aclDnsStatusRefresh": "Odśwież stan DNS", + "aclDnsPending": "Oczekiwanie na pierwsze zapytanie", + "aclDnsResolved": "Rozwiązano", + "aclDnsFailed": "Błąd DNS (brak dostępu)", + "aclDnsExpired": "Wygasło (brak dostępu)", + "aclDnsAddresses": "Rozwiązane adresy", + "aclDnsChecked": "Ostatnie zapytanie", + "aclDnsError": "Błąd DNS", + "aclDnsNoNames": "Brak nazw DNS/DDNS w skonfigurowanych ACL.", "aclDnsHelp": "Reguły DNS/DDNS typu allow odświeżają rekordy A/AAAA co 60 sekund. Błąd DNS usuwa zezwolenie (fail closed). Podaj nazwę, np. biuro.example.ddns.net, bez URL i gwiazdek. Wybierz wyjątki zezwalające z domyślną blokadą. Maksymalnie 128 nazw i 32 adresy na nazwę.", "overviewExtraColdQueueMemory": "Wykorzystanie RAM kolejki COLD", "overviewExtraColdQueueMemoryDescription": "RAM używany przez kolejkę zapisu COLD w stosunku do jej limitu; nie jest to pamięć dyskowa.", diff --git a/src/acl/dynamic/mod.rs b/src/acl/dynamic/mod.rs index ec5423f..c06fd52 100644 --- a/src/acl/dynamic/mod.rs +++ b/src/acl/dynamic/mod.rs @@ -2,11 +2,12 @@ use crate::config::Config; use anyhow::{ensure, Result}; use arc_swap::ArcSwap; use futures_util::{stream, StreamExt}; +use serde::Serialize; use std::{ collections::{BTreeSet, HashMap}, net::IpAddr, sync::{Arc, LazyLock, Weak}, - time::{Duration, Instant}, + time::{Duration, Instant, SystemTime, UNIX_EPOCH}, }; use tokio::{sync::Notify, time::MissedTickBehavior}; use tokio_util::sync::CancellationToken; @@ -18,7 +19,7 @@ const MAX_ADDRESSES: usize = 32; const PARALLEL_LOOKUPS: usize = 8; const LOOKUP_SECONDS: u64 = 4; -#[derive(Clone)] +#[derive(Clone, Debug)] struct Addresses { ips: Vec, valid_until: Instant, @@ -26,8 +27,63 @@ struct Addresses { static CACHE: LazyLock>> = LazyLock::new(|| ArcSwap::from_pointee(HashMap::new())); +static DIAGNOSTICS: LazyLock>> = + LazyLock::new(|| ArcSwap::from_pointee(HashMap::new())); static CHANGED: LazyLock = LazyLock::new(Notify::new); +#[derive(Clone)] +struct DnsDiagnostic { + checked_unix_ms: u64, + error: Option, +} + +/// A read-only view of the live resolver, not a second source of ACL permissions. +#[derive(Debug, Serialize)] +pub(crate) struct DnsAclStatus { + pub hostname: String, + pub state: &'static str, + pub addresses: Vec, + pub last_checked_unix_ms: Option, + pub valid_for_seconds: Option, + pub error: Option, +} + +pub(crate) fn statuses(config: &Config) -> Result> { + let names = configured_hostnames(config)?; + 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()) +} + +fn status_for_name( + hostname: String, + cache: &HashMap, + diagnostics: &HashMap, + now: Instant, +) -> DnsAclStatus { + let latest = diagnostics.get(&hostname); + let cached = cache.get(&hostname); + let current = cached.filter(|entry| entry.valid_until > now); + let state = if current.is_some() { + "resolved" + } else if latest.is_none() { + "pending" + } else if latest.is_some_and(|entry| entry.error.is_some()) { + "failed" + } else { + "expired" + }; + DnsAclStatus { + hostname, + state, + addresses: current.map_or_else(Vec::new, |entry| entry.ips.clone()), + last_checked_unix_ms: latest.map(|entry| entry.checked_unix_ms), + valid_for_seconds: current.map(|entry| entry.valid_until.duration_since(now).as_secs()), + error: latest.and_then(|entry| entry.error.clone()), + } +} + pub(crate) fn matches(name: &str, ip: IpAddr) -> bool { let cache = CACHE.load(); cache.get(name).is_some_and(|entry| { @@ -114,38 +170,47 @@ pub(crate) fn configured_hostnames(config: &Config) -> Result> { Ok(names.into_iter().collect()) } -async fn resolve(name: String) -> (String, Option) { +fn checked_unix_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as u64 +} + +fn validate_addresses(mut ips: Vec) -> std::result::Result { + ips.sort_unstable(); + ips.dedup(); + if ips.is_empty() { + return Err("DNS response contains no A/AAAA addresses".into()); + } + if ips.len() > MAX_ADDRESSES { + return Err(format!("DNS response exceeds the limit of {MAX_ADDRESSES} unique addresses")); + } + if ips + .iter() + .any(|ip| matches!(ip, IpAddr::V6(v6) if v6.to_ipv4_mapped().is_some())) + { + return Err("DNS response contains an IPv4-mapped IPv6 address".into()); + } + Ok(Addresses { + ips, + valid_until: Instant::now() + Duration::from_secs(MAX_AGE_SECONDS), + }) +} + +async fn resolve(name: String) -> (String, std::result::Result) { let lookup_name = name.clone(); let answer = tokio::time::timeout( Duration::from_secs(LOOKUP_SECONDS), tokio::net::lookup_host((lookup_name.as_str(), 0u16)), ) .await; - let mut ips = match answer { - Ok(Ok(sockets)) => sockets.map(|socket| socket.ip()).collect::>(), - _ => { - tracing::warn!(hostname = %name, "dynamic ACL DNS lookup failed; no addresses permitted"); - return (name, None); - } + let result = match answer { + 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()), }; - ips.sort_unstable(); - ips.dedup(); - if ips.is_empty() - || ips.len() > MAX_ADDRESSES - || ips - .iter() - .any(|ip| matches!(ip, IpAddr::V6(v6) if v6.to_ipv4_mapped().is_some())) - { - tracing::warn!(hostname = %name, "dynamic ACL DNS returned an invalid or excessive address set"); - return (name, None); - } - ( - name, - Some(Addresses { - ips, - valid_until: Instant::now() + Duration::from_secs(MAX_AGE_SECONDS), - }), - ) + (name, result) } pub(crate) fn config_changed() { @@ -155,6 +220,7 @@ pub(crate) fn config_changed() { pub(crate) async fn poll_loop(app: Weak, shutdown: CancellationToken) { let mut interval = tokio::time::interval(Duration::from_secs(REFRESH_SECONDS)); interval.set_missed_tick_behavior(MissedTickBehavior::Skip); + let mut previous_names = Vec::new(); loop { tokio::select! { _ = shutdown.cancelled() => break, @@ -165,16 +231,25 @@ pub(crate) async fn poll_loop(app: Weak, shutdown: Cancella break; }; let snapshot = state.config.load(); - let Ok(names) = configured_hostnames(&snapshot.envelope.config) else { - continue; + let names = match configured_hostnames(&snapshot.envelope.config) { + Ok(names) => names, + Err(error) => { + tracing::error!(error = %error, "ACL DDNS inventory invalid; dynamic DNS rules fail closed"); + CACHE.store(Arc::new(HashMap::new())); + DIAGNOSTICS.store(Arc::new(HashMap::new())); + continue; + } }; drop(snapshot); + if names != previous_names { + tracing::info!(hostnames = ?names, "ACL DDNS resolver inventory updated"); + previous_names = names.clone(); + } let results: HashMap<_, _> = tokio::select! { _ = shutdown.cancelled() => break, result = stream::iter(names.iter().cloned()) .map(resolve) .buffer_unordered(PARALLEL_LOOKUPS) - .filter_map(|(name, answer)| async move { answer.map(|value| (name, value)) }) .collect() => result, }; let current = state.config.load(); @@ -182,9 +257,35 @@ pub(crate) async fn poll_loop(app: Weak, shutdown: Cancella CHANGED.notify_one(); continue; } - CACHE.store(Arc::new(results)); + let previous = CACHE.load(); + let previous_diagnostics = DIAGNOSTICS.load(); + let mut addresses = HashMap::new(); + let mut diagnostics = HashMap::new(); + for (hostname, result) in results { + 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()) + { + 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 }); + } + 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) }); + } + } + } + CACHE.store(Arc::new(addresses)); + DIAGNOSTICS.store(Arc::new(diagnostics)); } CACHE.store(Arc::new(HashMap::new())); + DIAGNOSTICS.store(Arc::new(HashMap::new())); } #[cfg(test)] diff --git a/src/acl/dynamic/tests.rs b/src/acl/dynamic/tests.rs index 14f03d4..3d901d6 100644 --- a/src/acl/dynamic/tests.rs +++ b/src/acl/dynamic/tests.rs @@ -34,5 +34,54 @@ mod tests { CACHE.store(Arc::new(HashMap::new())); assert!(!matches(name, new_ip)); } + + #[test] + fn invalid_dns_answers_do_not_grant_access() { + assert!(validate_addresses(Vec::new()).unwrap_err().contains("no A/AAAA")); + let too_many = (1..=33) + .map(|octet| IpAddr::V4(std::net::Ipv4Addr::new(198, 51, 100, octet))) + .collect(); + assert!(validate_addresses(too_many).unwrap_err().contains("limit")); + assert!(validate_addresses(vec!["::ffff:198.51.100.42".parse().unwrap()]) + .unwrap_err().contains("IPv4-mapped")); + let valid = validate_addresses(vec!["198.51.100.2".parse().unwrap(), "198.51.100.2".parse().unwrap()]).unwrap(); + assert_eq!(valid.ips.len(), 1); + } + + #[test] + fn status_reports_pending_success_expiry_and_failure_independently_of_acl_decision() { + let mut config = Config::default(); + config.global_security.acl = Some(crate::acl::Acl { + default: crate::acl::Action::Deny, + rules: vec![crate::acl::Rule { + network: "My-Home.Example".into(), + action: crate::acl::Action::Allow, + }], + }); + 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()); + assert_eq!(pending.state, "pending"); + let ip: IpAddr = "192.0.2.10".parse().unwrap(); + let entries = HashMap::from([(names[0].clone(), Addresses { + ips: vec![ip], valid_until: Instant::now() + Duration::from_secs(120), + })]); + let diagnostics = HashMap::from([(names[0].clone(), DnsDiagnostic { + checked_unix_ms: 123, error: None, + })]); + let resolved = status_for_name(names[0].clone(), &entries, &diagnostics, Instant::now()); + assert_eq!(resolved.state, "resolved"); + assert_eq!(resolved.addresses, vec![ip]); + let expired = status_for_name(names[0].clone(), &entries, &diagnostics, Instant::now() + Duration::from_secs(121)); + assert_eq!(expired.state, "expired"); + assert!(expired.addresses.is_empty()); + let failure = HashMap::from([(names[0].clone(), DnsDiagnostic { + checked_unix_ms: 456, error: Some("NXDOMAIN".into()), + })]); + let failed = status_for_name(names[0].clone(), &empty, &failure, Instant::now()); + assert_eq!(failed.state, "failed"); + assert_eq!(failed.error.as_deref(), Some("NXDOMAIN")); + } } diff --git a/src/admin/api_token_access.rs b/src/admin/api_token_access.rs index 942a06e..b22baa6 100644 --- a/src/admin/api_token_access.rs +++ b/src/admin/api_token_access.rs @@ -3,6 +3,7 @@ fn general_api_token_allowed(method: &Method, path: &str, permission: &str) -> b && matches!( path, "/api/status" + | "/api/acl/dns-status" | "/api/system-info" | "/api/alerts" | "/api/backends" diff --git a/src/admin/openapi.json b/src/admin/openapi.json index 4877061..585556f 100644 --- a/src/admin/openapi.json +++ b/src/admin/openapi.json @@ -11200,6 +11200,36 @@ } } }, + "/api/acl/dns-status": { + "get": { + "summary": "Live DNS/DDNS ACL resolver diagnostics", + "description": "Authenticated read-only snapshot of every DNS ACL name configured globally, in profiles, Vhosts and locations. Status is pending, resolved, failed or expired. Addresses are currently valid A/AAAA records; an error or expired entry grants no access. Check the actual client IP separately. DNS lookups are refreshed every 60 seconds and valid for at most 180 seconds.", + "tags": ["Monitoring"], + "operationId": "get_api_acl_dns_status", + "responses": { + "200": { + "description": "Resolver state", + "content": {"application/json": {"schema": { + "type": "object", + "required": ["refresh_seconds", "hostnames"], + "properties": { + "refresh_seconds": {"type": "integer", "example": 60}, + "hostnames": {"type": "array", "items": {"type": "object", "required": ["hostname", "state", "addresses"], "properties": { + "hostname": {"type": "string"}, + "state": {"type": "string", "enum": ["pending", "resolved", "failed", "expired"]}, + "addresses": {"type": "array", "items": {"type": "string"}}, + "last_checked_unix_ms": {"type": "integer", "nullable": true}, + "valid_for_seconds": {"type": "integer", "nullable": true}, + "error": {"type": "string", "nullable": true} + }}} + } + }}} + }, + "401": {"description": "Authentication required"}, + "403": {"description": "Administrative access forbidden"} + } + } + }, "/api/status": { "get": { "summary": "Application, listener, system and traffic status", diff --git a/src/admin/router.rs b/src/admin/router.rs index cf9739d..5f4604f 100644 --- a/src/admin/router.rs +++ b/src/admin/router.rs @@ -183,6 +183,7 @@ pub fn router(state: Arc) -> Router { .route("/favicon.svg", get(panel_assets::serve)) .route("/healthz", get(|| async { Json(json!({"status":"ok"})) })) .route("/api/status", get(status)) + .route("/api/acl/dns-status", get(dns_acl_status)) .route("/api/web-services/htaccess-warnings", get(web_service_htaccess_warnings)) .route("/api/system-info", get(system_info)) .route("/api/backends", get(backend_status)) diff --git a/src/admin/status.rs b/src/admin/status.rs index bd74eef..a748f71 100644 --- a/src/admin/status.rs +++ b/src/admin/status.rs @@ -1,5 +1,21 @@ include!("status_system.rs"); +/// Live, read-only diagnostics for every configured DNS/DDNS ACL hostname. +/// In particular, a successful lookup need not match the address of a caller. +async fn dns_acl_status(State(state): State>) -> Result, ApiError> { + let snapshot = state.config.load(); + let hostnames = crate::acl::dynamic::statuses(&snapshot.envelope.config).map_err(|error| { + ApiError( + StatusCode::INTERNAL_SERVER_ERROR, + format!("cannot enumerate ACL DDNS hostnames: {error}"), + ) + })?; + Ok(Json(json!({ + "refresh_seconds": crate::acl::dynamic::REFRESH_SECONDS, + "hostnames": hostnames, + }))) +} + fn status_payload(state: &App) -> Value { let snapshot = state.config.load_full(); let listeners = json!({ diff --git a/src/admin/tests.rs b/src/admin/tests.rs index 2fff8ae..7e44944 100644 --- a/src/admin/tests.rs +++ b/src/admin/tests.rs @@ -2597,11 +2597,42 @@ mod tests { assert!(!dir.path().join("certs").join(&first_key_file).exists()); store.close().await; } + #[tokio::test] + async fn dns_acl_status_is_authenticated_and_reports_configured_names() { + let mut config = Config::default(); + config.global_security.acl = Some(crate::acl::Acl { + default: crate::acl::Action::Deny, + rules: vec![crate::acl::Rule { + network: "Home.Example.DDNS.Net".into(), + action: crate::acl::Action::Allow, + }], + }); + let (router, store, _dir, secret, _) = fixture_with_config(config).await; + let response = router + .clone() + .oneshot( + request("/api/acl/dns-status") + .header("cookie", format!("{}={secret}", auth::COOKIE_NAME)) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let status = json_body(response).await; + assert_eq!(status["refresh_seconds"], 60); + assert_eq!(status["hostnames"][0]["hostname"], "home.example.ddns.net"); + assert_eq!(status["hostnames"][0]["state"], "pending"); + assert!(status["hostnames"][0]["addresses"].as_array().unwrap().is_empty()); + store.close().await; + } + #[tokio::test] async fn anonymous_operational_paths_fail_closed_before_extractors() { let (router, store, _dir, _, _) = fixture().await; for path in [ "/api/status", + "/api/acl/dns-status", "/api/system-info", "/api/config", "/api/config/history", diff --git a/src/admin/web/index.html b/src/admin/web/index.html index 014ecb2..280963d 100644 --- a/src/admin/web/index.html +++ b/src/admin/web/index.html @@ -1101,6 +1101,12 @@ type="button">New profile
+
+ DNS/DDNS ACL resolver status +

Shows the addresses currently permitted by DNS ACL rules, not the current visitor IP.

+ +
+
diff --git a/src/admin/web/management.js b/src/admin/web/management.js index 5304654..620d68a 100644 --- a/src/admin/web/management.js +++ b/src/admin/web/management.js @@ -228,6 +228,33 @@ const countryHelp = $("acl-profile-country-help"), countryLabel = $("acl-profile-country-label"), ipHelp = $("acl-profile-ip-help"); const i18n = (tag, key, cls) => { const node = el(tag, t(key), cls); node.dataset.i18n = key; return node; }; const dnsHint = i18n("p", "aclDnsHelp", "fine"); ipHelp?.after(dnsHint); + const dnsStatus = $("acl-dns-status"), dnsStatusList = $("acl-dns-status-list"); + async function refreshDnsStatus() { + const button = $("acl-dns-status-refresh"); + button.disabled = true; + try { + const snapshot = await api("/api/acl/dns-status"); + const names = snapshot.hostnames || []; + const labels = { pending: "aclDnsPending", resolved: "aclDnsResolved", failed: "aclDnsFailed", expired: "aclDnsExpired" }; + const rows = names.map(item => { + const card = el("div", undefined, "entity"); + const title = el("div", undefined, "entity-top"); + title.append(el("strong", item.hostname), el("span", t(labels[item.state] || "aclDnsPending"))); + card.append(title); + const addresses = (item.addresses || []).join(", "); + card.append(el("p", `${t("aclDnsAddresses")}: ${addresses || "-"}`, "entity-details")); + const checked = item.last_checked_unix_ms ? new Date(item.last_checked_unix_ms).toLocaleString() : "-"; + card.append(el("p", `${t("aclDnsChecked")}: ${checked} · TTL: ${item.valid_for_seconds ?? "-"} s`, "fine")); + if (item.error) card.append(el("p", `${t("aclDnsError")}: ${item.error}`, "fine")); + return card; + }); + dnsStatusList.replaceChildren(...(rows.length ? rows : [el("p", t("aclDnsNoNames"), "fine")])); + } catch (error) { + dnsStatusList.replaceChildren(el("p", error.message, "fine")); + } finally { button.disabled = false; } + } + dnsStatus.addEventListener("toggle", () => { if (dnsStatus.open) void refreshDnsStatus(); }); + $("acl-dns-status-refresh").addEventListener("click", () => void refreshDnsStatus()); const modeInputs = [...form.querySelectorAll('input[name="acl-profile-mode"]')]; const selectedMode = () => modeInputs.find(node => node.checked)?.value || "allow_exceptions"; const setMode = value => { for (const node of modeInputs) node.checked = node.value === value; }; diff --git a/src/web_server/htaccess/model.rs b/src/web_server/htaccess/model.rs index 45c856b..0f6d6e9 100644 --- a/src/web_server/htaccess/model.rs +++ b/src/web_server/htaccess/model.rs @@ -168,7 +168,7 @@ impl LegacyAccess { #[derive(Debug, Clone)] struct SimpleRedirect { matcher: RedirectMatcher, - replacement: String, + replacement: Option, status: StatusCode, } @@ -233,6 +233,7 @@ pub enum RewriteOutcome { Internal { path: String, query: Option }, Redirect(Response), Forbidden, + Status(StatusCode), } #[derive(Default)] diff --git a/src/web_server/htaccess/parse.rs b/src/web_server/htaccess/parse.rs index 79b2092..579dc44 100644 --- a/src/web_server/htaccess/parse.rs +++ b/src/web_server/htaccess/parse.rs @@ -5,27 +5,33 @@ fn redirect_status(value: &str) -> Option { "seeother" | "303" => Some(StatusCode::SEE_OTHER), "307" => Some(StatusCode::TEMPORARY_REDIRECT), "308" => Some(StatusCode::PERMANENT_REDIRECT), + "404" => Some(StatusCode::NOT_FOUND), + "gone" | "410" => Some(StatusCode::GONE), _ => None, } } fn redirect_rule(parts: &[String], regex: bool) -> Result { - let (status, source_index) = if parts.len() == 4 { - (redirect_status(&parts[1]).context("unsupported Redirect status")?, 2) - } else { - ensure!(parts.len() == 3, "Redirect / RedirectMatch expects [status] source target"); - (StatusCode::FOUND, 1) - }; + let explicit = parts.get(1).and_then(|value| redirect_status(value)); + let (status, source_index) = explicit.map_or((StatusCode::FOUND, 1), |status| (status, 2)); + let status_only = matches!(status, StatusCode::NOT_FOUND | StatusCode::GONE); + ensure!(parts.len() == source_index + if status_only { 1 } else { 2 }, + "Redirect / RedirectMatch expects [status] source target, or 404/gone source without target"); let source = &parts[source_index]; - let replacement = &parts[source_index + 1]; - ensure!(!source.is_empty() && source.len() <= 512 && replacement.len() <= 1024, - "Redirect source/target is invalid"); - ensure!((replacement.starts_with('/') && !replacement.starts_with("//")) - || replacement.starts_with("http://") || replacement.starts_with("https://"), - "Redirect target must be a local absolute path or an explicit http(s) URL"); - ensure!(!replacement.contains('\\') && !replacement.contains('\r') && !replacement.contains('\n'), - "Redirect target contains unsafe characters"); - HeaderValue::from_str(replacement).context("invalid Redirect target")?; + ensure!(!source.is_empty() && source.len() <= 512, "Redirect source is invalid"); + let replacement = if status_only { + None + } else { + let replacement = &parts[source_index + 1]; + ensure!(replacement.len() <= 1024, "Redirect target is too long"); + ensure!((replacement.starts_with('/') && !replacement.starts_with("//")) + || replacement.starts_with("http://") || replacement.starts_with("https://"), + "Redirect target must be a local absolute path or an explicit http(s) URL"); + ensure!(!replacement.contains('\\') && !replacement.contains('\r') && !replacement.contains('\n'), + "Redirect target contains unsafe characters"); + HeaderValue::from_str(replacement).context("invalid Redirect target")?; + Some(replacement.to_owned()) + }; let matcher = if regex { RedirectMatcher::Regex(Regex::new(source).context("invalid RedirectMatch regex")?) } else { @@ -34,7 +40,7 @@ fn redirect_rule(parts: &[String], regex: bool) -> Result { && !source.contains('#') && !source.contains('\\'), "invalid Redirect path prefix"); RedirectMatcher::Prefix(source.to_owned()) }; - Ok(SimpleRedirect { matcher, replacement: replacement.to_owned(), status }) + Ok(SimpleRedirect { matcher, replacement, status }) } // Only a safe, deterministic subset of Apache access rules is allowed in diff --git a/src/web_server/htaccess/rewrite.rs b/src/web_server/htaccess/rewrite.rs index 5c4180d..12a5fbe 100644 --- a/src/web_server/htaccess/rewrite.rs +++ b/src/web_server/htaccess/rewrite.rs @@ -33,15 +33,20 @@ pub async fn apply_rewrites( } RedirectMatcher::Regex(_) => None, }; - let target = match &rule.matcher { - RedirectMatcher::Prefix(_) => tail.map(|tail| format!("{}{}", rule.replacement, tail)), - RedirectMatcher::Regex(regex) => regex.captures(&path).map(|captures| { + let target = match (&rule.matcher, rule.replacement.as_deref()) { + (RedirectMatcher::Prefix(_), None) => tail.map(|_| String::new()), + (RedirectMatcher::Regex(regex), None) => regex.is_match(&path).then(String::new), + (RedirectMatcher::Prefix(_), Some(base)) => tail.map(|tail| format!("{base}{tail}")), + (RedirectMatcher::Regex(regex), Some(base)) => regex.captures(&path).map(|captures| { let mut target = String::new(); - captures.expand(&rule.replacement, &mut target); + captures.expand(base, &mut target); target }), }; if let Some(mut target) = target { + if rule.replacement.is_none() { + return Ok(RewriteOutcome::Status(rule.status)); + } ensure!((target.starts_with('/') && !target.starts_with("//")) || target.starts_with("http://") || target.starts_with("https://"), "unsafe .htaccess Redirect expansion"); diff --git a/src/web_server/serve.rs b/src/web_server/serve.rs index 9f3bf66..f728ce6 100644 --- a/src/web_server/serve.rs +++ b/src/web_server/serve.rs @@ -109,6 +109,9 @@ async fn serve_inner( Ok(htaccess::RewriteOutcome::Forbidden) => { return builtin_error_response(StatusCode::FORBIDDEN, &method) } + Ok(htaccess::RewriteOutcome::Status(status)) => { + return builtin_error_response(status, &method) + } Ok(htaccess::RewriteOutcome::Internal { path, query }) => (path, query), Err(_) => { return status_response( diff --git a/src/web_server/tests.rs b/src/web_server/tests.rs index d9cdffa..d37efa3 100644 --- a/src/web_server/tests.rs +++ b/src/web_server/tests.rs @@ -2685,3 +2685,65 @@ ErrorDocument 404 /error.html assert_eq!(regex.status(), StatusCode::FOUND); assert_eq!(regex.headers()[LOCATION], "/archive/file.txt"); } + +#[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#" +RedirectMatch 404 ^/missing/ +Redirect gone /removed +Redirect 302 /old /new +"#).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() }, + ..Default::default() + }; + let service = config.compile().unwrap(); + 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; + assert_eq!(gone.status(), StatusCode::GONE); + assert!(!gone.headers().contains_key(LOCATION)); + let redirect = serve_request(&service, &request(Method::GET, "/old"), "/old").await; + assert_eq!(redirect.status(), StatusCode::FOUND); + assert_eq!(redirect.headers()[LOCATION], "/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#" +# Typical monitoring/PHP installation, without application-specific rules in RustProxy. +Options FollowSymlinks Multiviews +ErrorDocument 404 /error.php?404 +RedirectMatch 404 /\. +RewriteEngine On +RewriteBase / +RewriteRule ^\..*$ - [F,L] +RewriteCond %{REQUEST_FILENAME} !^favicon\.ico +RewriteCond %{REQUEST_FILENAME} !-f +RewriteCond %{REQUEST_FILENAME} !-d +RewriteCond %{REQUEST_URI} !\.(js|ico|txt|gif|jpg|png|css|php) +RewriteCond %{REQUEST_URI} !^api/ +RewriteCond %{REQUEST_URI} !^rrd/ +RewriteCond %{REQUEST_URI} !=/server-status +RewriteRule ^(.*)$ index.php/$1/ +AcceptPathInfo On +"#).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() }, + ..Default::default() + }; + let service = config.compile().unwrap(); + let (_, warnings) = service.htaccess_diagnostics().unwrap(); + assert!(warnings.iter().any(|warning| warning.contains("ErrorDocument"))); + assert!(warnings.iter().any(|warning| warning.contains("AcceptPathInfo"))); + assert!(!warnings.iter().any(|warning| warning.contains("RedirectMatch"))); +}