v0.42.2_fix2
This commit is contained in:
1 parent
15c7f9ff9e
commit
25148f26eb
14 files changed
+407
-54
No files matched your search
@@ -4,6 +4,8 @@ Release history focused on **features, settings, default behavior, compatibility
|
||||
|
||||
## 0.42.2 — Generic FastCGI/CGI hosting and Apache compatibility
|
||||
|
||||
- **Web Server `.htaccess` routing fix:** `AcceptPathInfo On/Off/Default` now controls safe FastCGI script suffix dispatch instead of being silently skipped; the original suffix (including final slash) becomes `PATH_INFO`, with `SCRIPT_FILENAME` still constrained to the real script. `RewriteBase` is parsed and applied to relative targets. Default PHP-capable Web Services try `index.php` after the static index names unless an explicit index list was set. Local `ErrorDocument` URL targets (HTTP 400–599) are rendered once for GET/HEAD with the original status preserved; other handlers and unsafe targets remain unsupported. Misconfigured `.php` front-controller rewrites produce a Web Service warning when there is no enabled `.php` FastCGI handler. Regression tests cover a realistic PHP front-controller `.htaccess`, static assets, root indexes, disabled PATH_INFO, local errors and nested base paths. `Options MultiViews`/`FollowSymlinks` continue as explicitly warned unsupported options rather than being falsely reported as supported.
|
||||
|
||||
- **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.
|
||||
|
||||
+13
-13
@@ -2,7 +2,7 @@
|
||||
4140a2956264b44f259e6a37fc00ba02097bbe68b09296e04d3d243c1287129b .env.example
|
||||
0a5e87541831edca0e7164c6469dba01a8a7053ab14dbfb8019c83e4db10edc2 .gitignore
|
||||
3c4638dc086333b8383c5bc77fe967b790075439f5e7a8257e5dd0dd4cf4233b AGENTS.md
|
||||
d1f91464ba2452a27ee2ea540297bdecbbf7dd251ba22b9eca8819dd36cd336f CHANGELOG.md
|
||||
47dff846d956b68ef225d0c6332ea9ed4b4248db2f26aef9a615c510c3d24cb9 CHANGELOG.md
|
||||
c28d825120a878684b511b1a6a4f372aced5098ed7b9bec8b318c4ec3fb1cbf4 Cargo.lock
|
||||
3ac98730af5caa39f81d28f4a4f7f14710fbb53d625794dd5704e65afebe4d8e Cargo.toml
|
||||
788745d4f70a0382c6280020afbd48844bb2af65e835a826852143f8132cdeca Dockerfile
|
||||
@@ -48,8 +48,8 @@ bfe96dd91dfc6e07918a662d98b036f12ceb011a5aa8381b3778bd0c964b19ab docs/CACHE.md
|
||||
966a1c49274c45568cf2b34158900524471f50d796d227a02db49c57941cc808 docs/CUSTOM_LOCATIONS.md
|
||||
16d4510e38d43c3bbde9b7dab7af3aeb0cb837dc2f1956cfaad7a9a11bea3bfc docs/DASHBOARD.md
|
||||
53cb0ce7db5ce25e4c2381de3a6e875d212deeed08861da63050de6c51a442bd docs/DOCKER_DISCOVERY.md
|
||||
6b575c6c1c7e01b252bbbf441ab100745dace3799f70fd65b840cba4681d1c08 docs/FASTCGI.md
|
||||
a024fa9e6113ca1ae99bb62e25a607ff1e092728c1c5519cf99793ef9ae215ba docs/FEATURES.md
|
||||
6a8ccaa0220acce78e596360998752e859fc53984410e8cc5f4c33cc92317d36 docs/FASTCGI.md
|
||||
d86b3d705d0cc46182c355deeb3d6e88bcf81d031560aad0eb4cc3dee3b38ec8 docs/FEATURES.md
|
||||
f7bb59821e0d6c45ae2a1789086fd9dab33d91c0ceae784ae68f64bd13b5f496 docs/HEADLESS.md
|
||||
bce732d845c23ad677ae811e7529b9322ab41d04ca808e04087d0f76bccd9309 docs/INSTALL.md
|
||||
3268808766ad66263e465f251dce18cff2e7ede355638dc2b0975870b1a5eead docs/LOAD_BALANCING.md
|
||||
@@ -71,7 +71,7 @@ df83d07d7186a5eea60d206dee3cb62b7f6505a066d84141fc53130e2f29760b docs/TROUBLESH
|
||||
4a5534b628c18f4e83c67c6136b60969c884391fbe55cc6bd4f2354711d8ffb7 docs/VCL_SUPPORT_MATRIX.md
|
||||
382e084a1f9e35627ccb43eaf451c18fb6d0cc752397c2178108d71de592a931 docs/VCL_TRAFFIC_COOKBOOK.md
|
||||
181444ea2c28171ed89ead25dcfc60ee6bd05f7b01c1a49d8248a307dc9be7a4 docs/VHOSTS.md
|
||||
ee23424a3446e25a17a84c1b50de224e27d99ee04a6655f2e142bad6c63c25f8 docs/WEB_SERVER.md
|
||||
bccc92cf4d751c05a4a315076739582fe0f307b54fd4f26273fa4a3caaa1a23d 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
|
||||
94dd341ba75ddc719adb58f6c4448d788d7650d83b993772b34a91939089d567 langs/en_US.json
|
||||
14dec3e0ce949606adb24755aec204fad741fb3c51d9878771f704ed8a4c792a langs/pl_pl.json
|
||||
a899c29ec4d21c6feb436567626b82a0c97c8b494b4976a4e93caed74b37b144 langs/en_US.json
|
||||
eb1aa36fdb83b224e64a47ac13816a63811069beec22751efea6a8632444d1c1 langs/pl_pl.json
|
||||
38773ed251a8c24af353f4744e498ae2bc7d4151df7927e942c4ac223f6008e1 make_zip.py
|
||||
e830d37dd1f81a4b0aa7d535f5bba69e34e433b0fd99cc8ee0b296786c32379a migrations/0002_admin.sql
|
||||
20112cc82192098b8d602f1c4f7ca08712e9e1366c845fabb92753187c370d35 migrations/0003_certificate_renewals.sql
|
||||
@@ -302,7 +302,7 @@ e6c4d91d1542d0a5b47bb8736f9539d43a6713df5a473b635519d5b7eac2eb9c src/admin/web/
|
||||
0a5fff35555153f59d4346933030a67b6e1a8768cee7a47cfa2fcf1a2c564f63 src/admin/web/favicon.svg
|
||||
e0f0b302092ced1c84ef7e99864984444f0e9d4e3b7d85e74d3507d566952a7f src/admin/web/file-logs.js
|
||||
85f54ce519140a38e31fb1b3d5974585748d7162f0499aa63703c1db56334b2c src/admin/web/host404.js
|
||||
64f680beeea88eea811d4d85b7d484f656d961c3369432be11adde37d010a95d src/admin/web/index.html
|
||||
e41461c7acd92b83bc6074ac97b6764847a3f7985c03a3120531e98f9db8cfe7 src/admin/web/index.html
|
||||
be9999a001c59630963d60539e860b59999dcf74c5ff0087b12a6fb69b4e7bd2 src/admin/web/integrations.js
|
||||
7a12f020fc587205694978ab41b660e9a80487d413fbf6e34fc525eabc58308f src/admin/web/login-keys.json
|
||||
ac9f667273918e18406df06cb2613c923f50a88897693a03a18f500e22dc6ec2 src/admin/web/login.html
|
||||
@@ -628,7 +628,7 @@ fc8af7342a3b147921e9040116af5dfe680b3df910db2416ada18198bbeea7df src/vhost/redi
|
||||
5a5768740e9a486436f6bb4e285ed99fd445cabbc21f317a47dc32c1f7091385 src/vhost/tests.rs
|
||||
34ffb202075c9fa720d2a23c6d901471655befe583a6335d778391d467cc8186 src/vhost/validation.rs
|
||||
8d1eff4b24f01d137414ef5419f75dd281879228adb70409645b11b3c78c20e9 src/web_server/config.rs
|
||||
21b7872f9672d3a95647496977ca7c5dcde4c4c90d2f5f17260abf17ad24945b src/web_server/config/compile.rs
|
||||
77e030e44dfb3019765927a42626f6154df423b74f816e6432dec1df14572e65 src/web_server/config/compile.rs
|
||||
a4d394582f34ab16bb046780d4f755c6bbcc6afb497b03e277980750ab2e5f25 src/web_server/config/model.rs
|
||||
9a3056d371219b7327d612b40b89587a0c30c7f8487386ba95e69050d0bdf11f src/web_server/config/validation.rs
|
||||
86c744216d7132d8294a6e90ba9be5fd871646006313d1c62506d40c81db9b12 src/web_server/fastcgi.rs
|
||||
@@ -636,13 +636,13 @@ d15716d8fa0d722e3189367fd395cac71c2f2a178335120a74a01696abc7cc04 src/web_server
|
||||
6b24c3ed2249e7c0d29ab27a5bc8ea05527a2a0314ae067acd6035327db3e814 src/web_server/fastcgi/response.rs
|
||||
92d2ab4d7ecb766bbc705f8eba94c1ca33347ffb84b36e0ad0eccfed5915473f src/web_server/filesystem.rs
|
||||
d4fec3682532b0f2d11a0aefcd024f69fb623a39922ddb6c528a2d2de265347d src/web_server/htaccess.rs
|
||||
370f5ee3bb0d1627e3a14c2f2a9920035fb80fcc6736bb5f75c02aa43899b2c0 src/web_server/htaccess/model.rs
|
||||
a149ae8497f776fd580034f78e179d36a936ad9fa6c002fd8509ab8773a3a09b src/web_server/htaccess/parse.rs
|
||||
a4d955e9225022a4402885cbbe9b03929a651acb8eac57d304dac297f075eb14 src/web_server/htaccess/model.rs
|
||||
991a47ea75164c74277e159fdd34c4db11f9b35bbcddb8902e7a58523f856570 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
|
||||
f27e483737d17c73200b227b2720bfd79333bfd6abbe34ed9f73906f373a8a4e src/web_server/request.rs
|
||||
709a672a0d210aae94f791de50ddbe0f902a1955c150ff35a3a575e352d9c198 src/web_server/request.rs
|
||||
d98c80663847d6d83073df074ebff65952755415574708abcc153bd8d3adfaa9 src/web_server/response.rs
|
||||
b38a1c9e648e3606a534ebdf74f6315863a326c6de1ca8edc433abe9c1fed7b4 src/web_server/response/file.rs
|
||||
df87b67c75bbe58d7e077ed4c4cfa105ec680e89dd0c25af7dbd793d418a01ad src/web_server/response/file_body/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
|
||||
487515bf6c1f8630a4aa7aacdf13bb9ae13c8610422f0426b620b7ee49014788 src/web_server/serve.rs
|
||||
3862c31e3f031c5ae8d7cf76dcfeeab48b806d7cfe9ab5f2c3815cc87c6fd8e8 src/web_server/tests.rs
|
||||
add6e69fe51af4ce28004b056be1366a82a7426640feea64150c286d637993ad src/web_server/serve.rs
|
||||
8c41430117399bcf835b4c7c95a40ef17a3e2e53ff63db9c68ca332d2e3bee06 src/web_server/tests.rs
|
||||
f00743af2cf4a5952caef7a1dcf68e7817b5599a252a9973e1c22045517c0b0e tests/fixtures/argon2id.json
|
||||
9540e9a904455a2190c2d0a32b47b1345976e4c4618767ed2b55898d13da9987 tests/fixtures/balance_rendezvous_vectors.txt
|
||||
affb5c728d2d2bd58807c080f22ac17575e06486c7cca38dc13cf58ad01873ae tests/fixtures/routing_conditions_cases.json
|
||||
|
||||
@@ -108,3 +108,7 @@ curl -Ik https://portal.example.test/console/cgi-bin/config.txt
|
||||
- **Browser downloads a script:** verify the active Web Service and extension. RustProxy refuses to send known executable script extensions as static files when no matching handler is configured.
|
||||
|
||||
The new protocol paths are covered by source-level tests using a mock FastCGI responder. Before production use, run `./dev.sh check` and `./dev.sh test` with the project toolchain and exercise real PHP-FPM and fcgiwrap instances; mock responders cannot prove OS-level script execution.
|
||||
|
||||
### `.htaccess` front-controller suffixes
|
||||
|
||||
When `.htaccess` compatibility is enabled, `AcceptPathInfo On` allows an eligible FastCGI script to receive a rewritten `script.php/extra/` URL even if **PATH_INFO** is disabled at Web Service level. `AcceptPathInfo Off` overrides the Web Service toggle and denies suffix routing; `AcceptPathInfo Default` restores the Web Service setting. `SCRIPT_FILENAME` is always the existing script file under the Web Service document root. `PATH_INFO` is the path after that script, including the trailing slash, and `REQUEST_URI` remains the original requested URL. The FastCGI endpoint is still configured in the Web Service; `.htaccess` cannot select a socket. Explicit index lists remain unchanged; the default static index list also tries `index.php` last on PHP-FPM services handling `.php`. Re-apply the Web Service when the `.htaccess` file changes.
|
||||
+1
-1
@@ -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, including status-only `RedirectMatch 404` / `410` rules without `Location`.
|
||||
- `try_files`, regex rewrites and a safe subset of Apache `.htaccess` rules, including status-only `RedirectMatch 404` / `410`, active `RewriteBase`, PHP script `AcceptPathInfo` overrides and local `ErrorDocument` responses (GET/HEAD).
|
||||
- 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.
|
||||
|
||||
+21
-3
@@ -5,7 +5,7 @@ The built-in Web Server serves local files and can forward executable scripts to
|
||||
## Create a Web Service
|
||||
|
||||
1. Open **Web Server → New Web Service**. Choose an ID/name and an absolute document root readable by the RustProxy service account.
|
||||
2. Set index files (default `index.html`, `index.htm`), whether directory listing is allowed (off by default), MIME handling and download extensions.
|
||||
2. Set index files (static default `index.html`, `index.htm`; when PHP-FPM for `.php` is enabled with that unchanged default, `index.php` is also tried last), whether directory listing is allowed (off by default), MIME handling and download extensions.
|
||||
3. Add `try_files`, rewrites and response headers only if your application requires them. VCL-style cache rules (including `pass` / `cookie_pass`) are **not** evaluated for Web Server sources; the static-extension Cookie option and the regular cache policy still apply to local files.
|
||||
4. Enable FastCGI only if you have a reachable, protected external PHP-FPM pool, CGI runner or compatible FastCGI responder; otherwise static files do not need an executable runtime.
|
||||
5. Save, create or edit a **Vhost**, select **Web Server** as source and choose the service ID.
|
||||
@@ -57,9 +57,27 @@ The editor supports common website presets to fill suggested fields; review thei
|
||||
|
||||
An optional bounded Apache-style `.htaccess` compatibility layer supports a **subset** of rules useful for migrations, not arbitrary Apache modules or dynamic directive execution. It can scan configured paths and enforce stricter handling of unsupported expressions. Prefer explicit `try_files`/rewrite/header controls when possible and test migrated sites. A real Apache configuration cannot be pasted unchanged into RustProxy.
|
||||
|
||||
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.
|
||||
With **Strict unsupported-directive mode disabled**, unimplemented directives (such as unsupported `Options` tokens) are skipped and logged as warnings during Web Service validation/apply; inspect the server logs or expand **.htaccess compatibility warnings** 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 <regex>` similarly return HTTP 410, while ordinary `Redirect 301 /old /new` and `RedirectMatch 302 <regex> /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).
|
||||
`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 <regex>` similarly return HTTP 410, while ordinary `Redirect 301 /old /new` and `RedirectMatch 302 <regex> /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.
|
||||
|
||||
**PHP routing using `.htaccess`:** `RewriteEngine`, `RewriteBase` (absolute safe URL prefix), `RewriteCond` and `RewriteRule` are active. `AcceptPathInfo On` enables script suffix routing such as `index.php/devices/42/` even if the Web Service FastCGI **PATH_INFO** toggle is off. `AcceptPathInfo Off` disables it, even if that toggle is on; `Default` restores the Web Service toggle. These settings apply to eligible FastCGI script files, not arbitrary static files. RustProxy preserves the rewritten suffix, including the trailing `/`, in the FastCGI `PATH_INFO`; `SCRIPT_FILENAME` still refers only to the existing executable file under the document root. PHP-FPM must be enabled with the correct socket and `.php` extension. If an `.htaccess` rule rewrites to `.php` but that handler is missing, Web Service validation now produces an explicit warning rather than silently accepting a non-functional front controller. The stock Web Service index list additionally tries `index.php` *last* when PHP-FPM for `.php` is enabled, while explicit index lists are unchanged. An `.htaccess` edit requires re-applying the service.
|
||||
|
||||
`ErrorDocument 404 /error.php?404` and other **local** `ErrorDocument` targets (HTTP 400–599) are supported for GET/HEAD. RustProxy performs one internal Web Service request for the error document and preserves the original error status when the document succeeds. The same filesystem and security controls apply to that document; recursive error handling is prohibited. External URL targets and custom literal error messages are not supported. Errors from other methods keep their built-in error response. `Options FollowSymlinks` and `Options MultiViews` are **not** equivalent to RustProxy's symlink policy and Apache content negotiation: they are still warned/skipped with Strict off. `Options -MultiViews` is accepted because MultiViews is not enabled. Do not assume these options are active.
|
||||
|
||||
**Example of a front controller with `PATH_INFO`:**
|
||||
|
||||
```apache
|
||||
RewriteEngine On
|
||||
RewriteBase /
|
||||
RewriteCond %{REQUEST_FILENAME} !-f
|
||||
RewriteCond %{REQUEST_FILENAME} !-d
|
||||
RewriteRule ^(.*)$ index.php/$1/ [L]
|
||||
AcceptPathInfo On
|
||||
ErrorDocument 404 /error.php?404
|
||||
```
|
||||
|
||||
For application-specific route exclusions, remember that `%{REQUEST_URI}` begins with `/`; use `!^/api/` rather than `!^api/` when excluding `/api/` URLs. A rule containing `RewriteCond %{REQUEST_URI} !\.php` prevents repeatedly rewriting `/index.php/...` on subsequent passes. 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.
|
||||
|
||||
|
||||
+3
-3
@@ -2227,7 +2227,7 @@
|
||||
"webServiceHtaccessRecursive": "Scan subdirectories",
|
||||
"webServiceHtaccessStrict": "Strict unsupported-directive mode",
|
||||
"webServiceHtaccessDocs": "Compatibility documentation",
|
||||
"webServiceHtaccessWarningsCount": "Skipped .htaccess directives (ignored)",
|
||||
"webServiceHtaccessWarningsCount": ".htaccess compatibility warnings",
|
||||
"webServiceHtaccessStrictHelp": "With Strict off, unsupported non-security directives are skipped and logged as warnings. Order/Allow/Deny with all, IP or CIDR are enforced; unsupported access rules still block Apply.",
|
||||
"webServiceHtaccessHelp": "RustProxy compiles a bounded Apache-compatible subset when the Web Service is applied. Files are not parsed on every request; apply the Web Service again after editing .htaccess on disk.",
|
||||
"webServiceHtaccessDocsTitle": ".htaccess compatibility",
|
||||
@@ -2236,11 +2236,11 @@
|
||||
"webServiceHtaccessDocsRewriteTitle": "Rewrite compatibility",
|
||||
"webServiceHtaccessDocsRewrite": "Rewrite conditions support REQUEST_FILENAME file tests (-f, -d, -s), REQUEST_URI, REQUEST_METHOD, QUERY_STRING, HTTP_HOST, HTTPS, DOCUMENT_ROOT, THE_REQUEST and HTTP headers. Flags: L, END, R, R=301/302/307/308, QSA, NC, F, OR. PT/NE are accepted as no-ops. E= is accepted as a compatibility no-op because request HTTP headers already reach PHP-FPM.",
|
||||
"webServiceHtaccessDocsPhpTitle": "PHP-FPM",
|
||||
"webServiceHtaccessDocsPhp": ".htaccess may add PHP extensions with AddHandler, but the PHP-FPM endpoint, timeouts and concurrency remain controlled by the Web Service PHP-FPM tab. Apache SetHandler proxy socket syntax is intentionally not accepted.",
|
||||
"webServiceHtaccessDocsPhp": "AddHandler can add PHP extensions. AcceptPathInfo On/Off overrides the Web Service PATH_INFO toggle for script suffixes. The FastCGI endpoint and limits still come from the Web Service. With the stock index list, PHP-FPM services also try index.php last. Apache SetHandler socket syntax is not accepted.",
|
||||
"webServiceHtaccessDocsReloadTitle": "Loading and limits",
|
||||
"webServiceHtaccessDocsReload": "Files are read and compiled on Validate, save and apply. RustProxy does not parse .htaccess per request. Re-apply after changing a file. The scan is bounded to 128 files, depth 16, 128 KiB per file and 1 MiB total.",
|
||||
"webServiceHtaccessDocsUnsupportedTitle": "Not Apache-complete",
|
||||
"webServiceHtaccessDocsUnsupported": "ErrorDocument, SetEnvIf, Redirect/RedirectMatch and FallbackResource are not implemented. Order/Allow/Deny with all, IP or CIDR (IPv4/IPv6) are supported and enforced. General Files/FilesMatch, unsupported authentication/authorization and hostname access directives, non-PHP handlers and SetHandler are rejected even with Strict off: ignoring them could expose protected content. .htaccess/.htpasswd are never served over HTTP. Other unsupported non-security directives are logged and skipped with Strict off.",
|
||||
"webServiceHtaccessDocsUnsupported": "Local ErrorDocument URLs (GET/HEAD), Redirect and RedirectMatch work. External and literal ErrorDocument values, SetEnvIf, FallbackResource, Options FollowSymlinks and Options MultiViews remain unsupported. Order/Allow/Deny and Files/FilesMatch access rules are enforced. Unsafe unsupported authentication, hostname access or handlers still fail closed, even with Strict off. Other unsupported directives are logged and skipped; re-apply after editing .htaccess.",
|
||||
"webServiceHtaccessDocsSecurity": "Vhost/location ACL, authentication, error pages and response rules still remain authoritative. .htaccess cannot escape the document root, select an arbitrary FastCGI socket or override protected framing headers.",
|
||||
"webServicePresetTitle": "Configuration preset",
|
||||
"webServicePreset": "Preset",
|
||||
|
||||
+3
-3
@@ -2227,7 +2227,7 @@
|
||||
"webServiceHtaccessRecursive": "Skanuj podkatalogi",
|
||||
"webServiceHtaccessStrict": "Tryb ścisły dla niewspieranych dyrektyw",
|
||||
"webServiceHtaccessDocs": "Dokumentacja zgodności",
|
||||
"webServiceHtaccessWarningsCount": "Pominięte dyrektywy .htaccess (ostrzeżenia)",
|
||||
"webServiceHtaccessWarningsCount": "Ostrzeżenia zgodności .htaccess",
|
||||
"webServiceHtaccessStrictHelp": "Po wyłączeniu trybu ścisłego nieobsługiwane dyrektywy niezwiązane z bezpieczeństwem są pomijane, a ostrzeżenia trafiają do logów. Order/Allow/Deny z all, IP lub CIDR są egzekwowane; nieobsługiwane reguły dostępu nadal blokują zapis.",
|
||||
"webServiceHtaccessHelp": "RustProxy kompiluje ograniczony podzbiór zgodny z Apache podczas zastosowania Web Service. Pliki nie są parsowane przy każdym żądaniu; po zmianie .htaccess na dysku zastosuj Web Service ponownie.",
|
||||
"webServiceHtaccessDocsTitle": "Zgodność .htaccess",
|
||||
@@ -2236,11 +2236,11 @@
|
||||
"webServiceHtaccessDocsRewriteTitle": "Zgodność rewrite",
|
||||
"webServiceHtaccessDocsRewrite": "Warunki rewrite obsługują testy REQUEST_FILENAME (-f, -d, -s), REQUEST_URI, REQUEST_METHOD, QUERY_STRING, HTTP_HOST, HTTPS, DOCUMENT_ROOT, THE_REQUEST i nagłówki HTTP. Flagi: L, END, R, R=301/302/307/308, QSA, NC, F, OR. PT/NE są akceptowane jako no-op. E= jest akceptowane jako no-op zgodności, ponieważ nagłówki HTTP żądania i tak trafiają do PHP-FPM.",
|
||||
"webServiceHtaccessDocsPhpTitle": "PHP-FPM",
|
||||
"webServiceHtaccessDocsPhp": ".htaccess może dodawać rozszerzenia PHP przez AddHandler, ale endpoint PHP-FPM, timeouty i limit współbieżności nadal są kontrolowane w zakładce PHP-FPM Web Service. Składnia Apache SetHandler wskazująca socket proxy celowo nie jest akceptowana.",
|
||||
"webServiceHtaccessDocsPhp": "AddHandler może dodawać rozszerzenia PHP. AcceptPathInfo On/Off nadpisuje przełącznik PATH_INFO Web Service dla adresów ze ścieżką po skrypcie. Endpoint FastCGI i limity pozostają w konfiguracji Web Service. Przy domyślnej liście indeksów, usługa PHP-FPM próbuje też index.php na końcu. Składnia Apache SetHandler z socketem nie jest obsługiwana.",
|
||||
"webServiceHtaccessDocsReloadTitle": "Ładowanie i limity",
|
||||
"webServiceHtaccessDocsReload": "Pliki są odczytywane i kompilowane podczas „Validate, save and apply”. RustProxy nie parsuje .htaccess przy każdym żądaniu. Po zmianie pliku zastosuj konfigurację ponownie. Skan ma limity: 128 plików, głębokość 16, 128 KiB na plik i 1 MiB łącznie.",
|
||||
"webServiceHtaccessDocsUnsupportedTitle": "To nie jest pełny Apache",
|
||||
"webServiceHtaccessDocsUnsupported": "ErrorDocument, SetEnvIf, Redirect/RedirectMatch i FallbackResource nie są zaimplementowane. Order/Allow/Deny z all, IP lub CIDR (IPv4/IPv6) są obsługiwane i egzekwowane. Ogólne Files/FilesMatch, nieobsługiwane dyrektywy uwierzytelniania/autoryzacji i reguły dostępu po nazwie hosta, handlery inne niż PHP oraz SetHandler są odrzucane nawet przy wyłączonym trybie ścisłym, ponieważ ich zignorowanie mogłoby ujawnić chronione zasoby. Pliki .htaccess/.htpasswd nigdy nie są udostępniane przez HTTP. Pozostałe nieobsługiwane dyrektywy niezwiązane z bezpieczeństwem są logowane i pomijane przy wyłączonym trybie ścisłym.",
|
||||
"webServiceHtaccessDocsUnsupported": "Lokalne ErrorDocument (GET/HEAD), Redirect i RedirectMatch działają. Zewnętrzne lub tekstowe ErrorDocument, SetEnvIf, FallbackResource, Options FollowSymlinks i Options MultiViews nadal nie są obsługiwane. Reguły dostępu Order/Allow/Deny oraz Files/FilesMatch są egzekwowane. Nieobsługiwane reguły uwierzytelniania, dostępu po nazwach hostów i handlerów blokują zapis nawet bez trybu ścisłego. Pozostałe są logowane i pomijane; po zmianie .htaccess zastosuj usługę ponownie.",
|
||||
"webServiceHtaccessDocsSecurity": "ACL vhost/location, uwierzytelnianie, strony błędów i reguły odpowiedzi nadal mają nadrzędną rolę. .htaccess nie może wyjść poza document root, wybrać dowolnego socketu FastCGI ani nadpisać chronionych nagłówków transportowych.",
|
||||
"webServicePresetTitle": "Preset konfiguracji",
|
||||
"webServicePreset": "Preset",
|
||||
|
||||
@@ -5199,9 +5199,9 @@ curl -sS -D - -o /dev/null \
|
||||
Apache runtime. Supported directives are compiled into RustProxy Web Server rules.</p>
|
||||
<h3 data-i18n="webServiceHtaccessDocsSupportedTitle">Supported subset</h3>
|
||||
<p><code>RewriteEngine</code>, <code>RewriteBase</code>, <code>RewriteCond</code>, <code>RewriteRule</code>,
|
||||
<code>DirectoryIndex</code>, <code>Options +/-Indexes</code>, <code>AddType</code>,
|
||||
<code>DirectoryIndex</code>, <code>AcceptPathInfo On/Off/Default</code>, <code>Options +/-Indexes</code>, <code>AddType</code>,
|
||||
<code>AddHandler</code> (PHP extensions), <code>Header set/add/unset</code>, <code>ExpiresActive</code>,
|
||||
<code>ExpiresDefault</code>, <code>ExpiresByType</code>, <code>Require all granted/denied</code>.
|
||||
<code>ExpiresDefault</code>, <code>ExpiresByType</code>, <code>Redirect/RedirectMatch</code>, <code>ErrorDocument (local URL)</code>, <code>Require all granted/denied</code>.
|
||||
</p>
|
||||
<h3 data-i18n="webServiceHtaccessDocsRewriteTitle">Rewrite compatibility</h3>
|
||||
<p data-i18n="webServiceHtaccessDocsRewrite">Rewrite conditions support REQUEST_FILENAME file tests (-f, -d,
|
||||
@@ -5213,20 +5213,13 @@ RewriteCond %{REQUEST_FILENAME} !-f
|
||||
RewriteCond %{REQUEST_FILENAME} !-d
|
||||
RewriteRule . /index.php [L]</code></pre>
|
||||
<h3 data-i18n="webServiceHtaccessDocsPhpTitle">PHP-FPM</h3>
|
||||
<p data-i18n="webServiceHtaccessDocsPhp">.htaccess may add PHP extensions with AddHandler, but the PHP-FPM
|
||||
endpoint, timeouts and concurrency remain controlled by the Web Service PHP-FPM tab. Apache SetHandler
|
||||
proxy socket syntax is intentionally not accepted.</p>
|
||||
<p data-i18n="webServiceHtaccessDocsPhp">.htaccess may add PHP extensions with AddHandler. AcceptPathInfo On enables PHP script/path suffix routing and Off disables it, overriding the Web Service PATH_INFO switch. The PHP-FPM endpoint, timeouts and concurrency remain controlled by the Web Service PHP-FPM tab. The unchanged default index list also tries index.php last when PHP-FPM for .php is enabled. Apache SetHandler proxy socket syntax is intentionally not accepted.</p>
|
||||
<h3 data-i18n="webServiceHtaccessDocsReloadTitle">Loading and limits</h3>
|
||||
<p data-i18n="webServiceHtaccessDocsReload">Files are read and compiled on Validate, save and apply.
|
||||
RustProxy does not parse .htaccess per request. Re-apply after changing a file. The scan is bounded to
|
||||
128 files, depth 16, 128 KiB per file and 1 MiB total.</p>
|
||||
<h3 data-i18n="webServiceHtaccessDocsUnsupportedTitle">Not Apache-complete</h3>
|
||||
<p data-i18n="webServiceHtaccessDocsUnsupported">ErrorDocument, SetEnvIf, Redirect/RedirectMatch and
|
||||
FallbackResource are not implemented. Order/Allow/Deny with all, IP or CIDR (IPv4/IPv6) are supported
|
||||
and enforced. General Files/FilesMatch, unsupported authentication/authorization and hostname access
|
||||
directives, non-PHP handlers and SetHandler are rejected even with Strict off: ignoring them may expose
|
||||
protected content. .htaccess/.htpasswd are never served over HTTP. Other unsupported non-security
|
||||
directives are logged and skipped with Strict off.</p>
|
||||
<p data-i18n="webServiceHtaccessDocsUnsupported">Only local ErrorDocument URLs are supported (GET/HEAD); custom literal/external error documents, SetEnvIf, FallbackResource, Options FollowSymlinks and Options MultiViews are not implemented. Order/Allow/Deny with all, IP or CIDR (IPv4/IPv6) and Files/FilesMatch access rules are enforced. Unsupported authentication/authorization, host-based access and handler rules still fail closed, even with Strict off. Other unsupported non-security directives are logged and skipped with Strict off. Re-apply the Web Service after .htaccess changes.</p>
|
||||
<p class="fine" data-i18n="webServiceHtaccessDocsSecurity">Vhost/location ACL, authentication, error pages
|
||||
and response rules still remain authoritative. .htaccess cannot escape the document root, select an
|
||||
arbitrary FastCGI socket or override protected framing headers.</p>
|
||||
|
||||
@@ -367,8 +367,16 @@ impl Service {
|
||||
self.id
|
||||
)
|
||||
})?);
|
||||
let htaccess = htaccess::compile(&root, &self.htaccess)?;
|
||||
if let Some(compiled) = &htaccess {
|
||||
let mut htaccess = htaccess::compile(&root, &self.htaccess)?;
|
||||
if let Some(compiled) = &mut htaccess {
|
||||
if htaccess::rewrites_to_php(Some(compiled))
|
||||
&& (!self.php.enabled || !self.php.extensions.iter().any(|extension| extension == "php"))
|
||||
{
|
||||
compiled.warnings.push(format!(
|
||||
"Web Service {}: .htaccess rewrites to a .php script, but FastCGI handling for .php is disabled; configure a PHP-FPM/FastCGI endpoint and the php extension before expecting the route to work",
|
||||
self.id
|
||||
));
|
||||
}
|
||||
ensure!(
|
||||
(self.php.enabled && self.php.handler == FastCgiHandler::PhpFpm)
|
||||
|| !htaccess::adds_php_extensions(Some(compiled)),
|
||||
@@ -454,7 +462,18 @@ impl Service {
|
||||
name: self.name.clone(),
|
||||
sendfile: self.sendfile,
|
||||
root,
|
||||
index: self.index.clone(),
|
||||
// Keep explicit index priorities unchanged. For the stock static
|
||||
// default, PHP-capable services also try index.php when the HTML
|
||||
// indexes are absent, matching common PHP application installs.
|
||||
index: {
|
||||
let mut index = self.index.clone();
|
||||
if self.php.enabled && self.php.handler == FastCgiHandler::PhpFpm
|
||||
&& self.php.extensions.iter().any(|extension| extension == "php")
|
||||
&& index == default_index() {
|
||||
index.push("index.php".to_owned());
|
||||
}
|
||||
index
|
||||
},
|
||||
directory_listing: self.directory_listing,
|
||||
mime_types: self
|
||||
.mime_types
|
||||
|
||||
@@ -90,6 +90,9 @@ struct Scope {
|
||||
components: Vec<String>,
|
||||
rewrites: Vec<RewriteRule>,
|
||||
redirects: Vec<SimpleRedirect>,
|
||||
rewrite_base: Option<String>,
|
||||
accept_path_info: Option<AcceptPathInfoMode>,
|
||||
error_documents: BTreeMap<u16, String>,
|
||||
directory_index: Option<Vec<String>>,
|
||||
directory_listing: Option<bool>,
|
||||
mime_types: BTreeMap<String, HeaderValue>,
|
||||
@@ -103,6 +106,14 @@ struct Scope {
|
||||
file_rules: Vec<FileAccessRule>,
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum AcceptPathInfoMode {
|
||||
On,
|
||||
Off,
|
||||
Default,
|
||||
}
|
||||
|
||||
// Apache Files / FilesMatch rules apply to filenames below their directory.
|
||||
// Only bounded access-control directives are accepted inside these blocks.
|
||||
#[derive(Debug, Clone)]
|
||||
|
||||
@@ -165,6 +165,42 @@ fn parse_file(path: &Path, components: Vec<String>, config: &Config) -> Result<(
|
||||
if !state.rewrite_engine { state.pending_conditions.clear(); state.skip_next_rule = false; }
|
||||
}
|
||||
"rewritebase" => {
|
||||
ensure!(parts.len() == 2, "{}:{line_no}: RewriteBase expects one absolute URL prefix", path.display());
|
||||
let base = &parts[1];
|
||||
ensure!(base.starts_with('/') && !base.starts_with("//")
|
||||
&& !base.contains('\\') && !base.contains('?') && !base.contains('#')
|
||||
&& !base.chars().any(char::is_control),
|
||||
"{}:{line_no}: RewriteBase must be a safe absolute URL path", path.display());
|
||||
crate::acl::validate_decoded_routing_path(base)
|
||||
.map_err(|_| anyhow::anyhow!("{}:{line_no}: invalid RewriteBase path", path.display()))?;
|
||||
scope.rewrite_base = Some(if base.ends_with('/') { base.to_owned() } else { format!("{base}/") });
|
||||
}
|
||||
"acceptpathinfo" => {
|
||||
ensure!(parts.len() == 2, "{}:{line_no}: AcceptPathInfo expects On, Off or Default", path.display());
|
||||
scope.accept_path_info = if parts[1].eq_ignore_ascii_case("on") {
|
||||
Some(AcceptPathInfoMode::On)
|
||||
} else if parts[1].eq_ignore_ascii_case("off") {
|
||||
Some(AcceptPathInfoMode::Off)
|
||||
} else if parts[1].eq_ignore_ascii_case("default") {
|
||||
Some(AcceptPathInfoMode::Default)
|
||||
} else {
|
||||
bail!("{}:{line_no}: AcceptPathInfo expects On, Off or Default", path.display());
|
||||
};
|
||||
}
|
||||
"errordocument" => {
|
||||
ensure!(parts.len() == 3, "{}:{line_no}: ErrorDocument expects an HTTP error status and a local URL", path.display());
|
||||
let status: u16 = parts[1].parse().context("ErrorDocument status must be numeric")?;
|
||||
ensure!((400..600).contains(&status), "{}:{line_no}: ErrorDocument status must be 400..599", path.display());
|
||||
let target = &parts[2];
|
||||
ensure!(target.len() <= 1024 && target.starts_with('/') && !target.starts_with("//")
|
||||
&& !target.contains('\\') && !target.contains('#')
|
||||
&& !target.chars().any(char::is_control),
|
||||
"{}:{line_no}: ErrorDocument requires a safe local URL, not an external redirect or literal response", path.display());
|
||||
let path_only = target.split('?').next().unwrap_or_default();
|
||||
crate::acl::validate_decoded_routing_path(path_only)
|
||||
.map_err(|_| anyhow::anyhow!("{}:{line_no}: invalid ErrorDocument URL path", path.display()))?;
|
||||
target.parse::<Uri>().context("invalid ErrorDocument URL")?;
|
||||
scope.error_documents.insert(status, target.to_owned());
|
||||
}
|
||||
"rewritecond" if state.rewrite_engine => {
|
||||
condition_count += 1;
|
||||
@@ -269,7 +305,7 @@ fn parse_file(path: &Path, components: Vec<String>, config: &Config) -> Result<(
|
||||
scope.redirects.push(redirect_rule(&parts, directive == "redirectmatch")
|
||||
.with_context(|| format!("{}:{line_no}", path.display()))?);
|
||||
}
|
||||
"errordocument" | "setenvif" | "fallbackresource" => {
|
||||
"setenvif" | "fallbackresource" => {
|
||||
unsupported(&mut state, config, path, line_no, format!("directive {} is not in the RustProxy compatibility subset", parts[0]))?;
|
||||
}
|
||||
_ => unsupported(&mut state, config, path, line_no, format!("unsupported directive {}", parts[0]))?,
|
||||
@@ -335,6 +371,12 @@ pub fn adds_php_extensions(compiled: Option<&Compiled>) -> bool {
|
||||
compiled.is_some_and(|compiled| compiled.scopes.iter().any(|scope| !scope.php_extensions.is_empty()))
|
||||
}
|
||||
|
||||
pub fn rewrites_to_php(compiled: Option<&Compiled>) -> bool {
|
||||
compiled.is_some_and(|compiled| compiled.scopes.iter().any(|scope| {
|
||||
scope.rewrites.iter().any(|rule| rule.replacement.to_ascii_lowercase().contains(".php"))
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn protected_component(compiled: Option<&Compiled>, value: &str) -> bool {
|
||||
let lower = value.to_ascii_lowercase();
|
||||
if lower == ".htaccess" || lower == ".htpasswd" || lower.starts_with(".ht") { return true; }
|
||||
@@ -379,6 +421,25 @@ pub fn index_files<'a>(compiled: Option<&'a Compiled>, directory_components: &[S
|
||||
compiled.scopes.iter().filter(|scope| scope_matches(scope, directory_components)).filter_map(|scope| scope.directory_index.as_deref()).next_back().unwrap_or(fallback)
|
||||
}
|
||||
|
||||
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()) {
|
||||
Some(AcceptPathInfoMode::On) => true,
|
||||
Some(AcceptPathInfoMode::Off) => false,
|
||||
Some(AcceptPathInfoMode::Default) | None => fallback,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_error_documents(compiled: Option<&Compiled>) -> bool {
|
||||
compiled.is_some_and(|compiled| compiled.scopes.iter().any(|scope| !scope.error_documents.is_empty()))
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
pub fn directory_listing(compiled: Option<&Compiled>, directory_components: &[String], fallback: bool) -> bool {
|
||||
let Some(compiled) = compiled else { return fallback; };
|
||||
compiled.scopes.iter().filter(|scope| scope_matches(scope, directory_components)).filter_map(|scope| scope.directory_listing).next_back().unwrap_or(fallback)
|
||||
@@ -535,6 +596,7 @@ fn replacement_with_captures(rule: &RewriteRule, captures: ®ex::Captures<'_>,
|
||||
|
||||
fn scoped_target(scope: &Scope, replacement: &str) -> String {
|
||||
if replacement.starts_with('/') { return replacement.to_owned(); }
|
||||
if let Some(base) = &scope.rewrite_base { return format!("{base}{replacement}"); }
|
||||
if scope.components.is_empty() { format!("/{replacement}") } else if replacement.is_empty() { format!("/{}/", scope.components.join("/")) } else { format!("/{}/{}", scope.components.join("/"), replacement) }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use http::Version;
|
||||
use std::net::IpAddr;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RequestContext {
|
||||
pub client_ip: IpAddr,
|
||||
pub client_port: Option<u16>,
|
||||
|
||||
+62
-10
@@ -26,13 +26,18 @@ use std::{io, path::PathBuf};
|
||||
async fn resolve_script_path_info(
|
||||
service: &CompiledService,
|
||||
components: &[String],
|
||||
requested_path: &str,
|
||||
) -> Option<(String, String)> {
|
||||
let php = service.php.as_ref().filter(|php| php.path_info)?;
|
||||
if components.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
for script_end in 0..components.len() - 1 {
|
||||
let php = service.php.as_ref()?;
|
||||
for script_end in 0..components.len() {
|
||||
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; };
|
||||
if !htaccess::accept_path_info(service.htaccess.as_ref(), &script_path, php.path_info) {
|
||||
continue;
|
||||
}
|
||||
if !php.extensions.iter().any(|extension| {
|
||||
PathBuf::from(&script_path)
|
||||
.extension()
|
||||
@@ -43,8 +48,7 @@ async fn resolve_script_path_info(
|
||||
}
|
||||
match open_components(service, components[..=script_end].to_vec()).await {
|
||||
Ok(opened) if opened.metadata.is_file() => {
|
||||
let path_info = format!("/{}", components[script_end + 1..].join("/"));
|
||||
return Some((script_path, path_info));
|
||||
return Some((script_path, path_info.to_owned()));
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
@@ -113,7 +117,9 @@ async fn serve_inner(
|
||||
return builtin_error_response(status, &method)
|
||||
}
|
||||
Ok(htaccess::RewriteOutcome::Internal { path, query }) => (path, query),
|
||||
Err(_) => {
|
||||
Err(error) => {
|
||||
tracing::warn!(service = %service.id, path = %path, error = %error,
|
||||
".htaccess rewrite rejected Web Service request");
|
||||
return status_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"RustProxy: invalid .htaccess rewrite target\n",
|
||||
@@ -134,7 +140,7 @@ async fn serve_inner(
|
||||
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).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| {
|
||||
@@ -196,7 +202,7 @@ async fn serve_inner(
|
||||
) =>
|
||||
{
|
||||
if let Some((script_path, path_info)) =
|
||||
resolve_script_path_info(service, &components).await
|
||||
resolve_script_path_info(service, &components, &effective_path).await
|
||||
{
|
||||
let script_components = path_components(&script_path).unwrap_or_default();
|
||||
if hardening_denied_path(service, &script_path)
|
||||
@@ -416,12 +422,58 @@ pub async fn serve(
|
||||
let _in_flight =
|
||||
crate::web_server::metrics::HeadersInFlight::new(&service.web_metrics.in_flight_headers);
|
||||
let request_method = method.clone();
|
||||
// Copy request metadata only for services that actually have local error
|
||||
// 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()));
|
||||
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;
|
||||
// Only replace server-generated errors. FastCGI applications may already
|
||||
// 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::<crate::web_server::metrics::ResponseKind>(),
|
||||
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) {
|
||||
let target_path = target.split('?').next().unwrap_or_default();
|
||||
if target_path != path {
|
||||
if let Ok(target_uri) = target.parse::<Uri>() {
|
||||
// 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); }
|
||||
let replacement = serve_inner(
|
||||
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;
|
||||
*response.status_mut() = original_status;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if request_method == Method::HEAD {
|
||||
*response.body_mut() = Body::empty();
|
||||
}
|
||||
add_service_headers(&mut response, service);
|
||||
htaccess::apply_response(service.htaccess.as_ref(), &mut response, path);
|
||||
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().remove(http::header::EXPIRES);
|
||||
}
|
||||
strip_unnecessary_headers(&mut response, service);
|
||||
let kind = response
|
||||
.extensions()
|
||||
|
||||
+197
-6
@@ -1146,7 +1146,7 @@ async fn htaccess_legacy_deny_from_all_is_enforced_even_in_non_strict_mode() {
|
||||
};
|
||||
configured.validate().unwrap();
|
||||
let service = configured.compile().unwrap();
|
||||
assert_eq!(service.htaccess.as_ref().unwrap().warnings.len(), 2);
|
||||
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);
|
||||
}
|
||||
@@ -1189,7 +1189,7 @@ fn htaccess_strict_mode_rejects_unsupported_directives() {
|
||||
std::fs::write(tmp.path().join("index.html"), b"ok").unwrap();
|
||||
std::fs::write(
|
||||
tmp.path().join(".htaccess"),
|
||||
b"ErrorDocument 404 /404.html\n",
|
||||
b"SetEnvIf Request_URI ^/legacy legacy=1\n",
|
||||
)
|
||||
.unwrap();
|
||||
let mut configured = Service {
|
||||
@@ -1208,7 +1208,7 @@ fn htaccess_strict_mode_rejects_unsupported_directives() {
|
||||
.compile()
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("ErrorDocument"));
|
||||
.contains("SetEnvIf"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -2677,7 +2677,7 @@ ErrorDocument 404 /error.html
|
||||
config.validate().unwrap();
|
||||
let service = config.compile().unwrap();
|
||||
let (_, warnings) = service.htaccess_diagnostics().unwrap();
|
||||
assert_eq!(warnings.len(), 1); // ErrorDocument ignored in non-strict mode.
|
||||
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");
|
||||
@@ -2743,7 +2743,198 @@ AcceptPathInfo On
|
||||
};
|
||||
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_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]
|
||||
async fn htaccess_observium_style_front_controller_executes_php_path_info_without_global_switch() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::write(tmp.path().join("index.php"), b"<?php // index").unwrap();
|
||||
std::fs::write(tmp.path().join("error.php"), b"<?php // errors").unwrap();
|
||||
std::fs::write(tmp.path().join("site.css"), b"static-css").unwrap();
|
||||
std::fs::write(tmp.path().join(".htaccess"), br#"# Original, representative application .htaccess
|
||||
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 (endpoint, received) = fastcgi_fixture_record_params().await;
|
||||
let mut configured = Service {
|
||||
id: "front-controller-php-pathinfo".into(),
|
||||
name: "Generic PHP application".into(),
|
||||
document_root: tmp.path().to_path_buf(),
|
||||
htaccess: htaccess::Config { enabled: true, strict: false, ..Default::default() },
|
||||
php: Php { enabled: true, path_info: false, endpoint: format!("tcp:{endpoint}"), ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
configured.validate().unwrap();
|
||||
let service = configured.compile().unwrap();
|
||||
let warnings = &service.htaccess.as_ref().unwrap().warnings;
|
||||
assert_eq!(warnings.len(), 2, "expected only FollowSymlinks and MultiViews warnings: {warnings:?}");
|
||||
assert!(warnings.iter().all(|warning| warning.contains("Options")), "{warnings:?}");
|
||||
|
||||
let static_response = serve_request(&service, &request(Method::GET, "/site.css"), "/site.css").await;
|
||||
assert_eq!(static_response.status(), StatusCode::OK);
|
||||
assert_eq!(static_response.into_body().collect().await.unwrap().to_bytes(), "static-css");
|
||||
|
||||
let response = serve_request(&service, &request(Method::GET, "/devices/42?debug=1"), "/devices/42").await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let params = received.await.unwrap();
|
||||
assert_eq!(params["SCRIPT_FILENAME"], tmp.path().join("index.php").to_string_lossy());
|
||||
assert_eq!(params["SCRIPT_NAME"], "/index.php");
|
||||
assert_eq!(params["PATH_INFO"], "/devices/42/");
|
||||
assert_eq!(params["REQUEST_URI"], "/devices/42?debug=1");
|
||||
assert_eq!(params["QUERY_STRING"], "debug=1");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn htaccess_php_root_defaults_to_index_php_when_no_html_index_exists() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::write(tmp.path().join("index.php"), b"<?php // app").unwrap();
|
||||
std::fs::write(tmp.path().join(".htaccess"), b"RewriteEngine On\nAcceptPathInfo On\n").unwrap();
|
||||
let (endpoint, received) = fastcgi_fixture_record_params().await;
|
||||
let mut configured = Service {
|
||||
id: "php-root-default-index".into(),
|
||||
name: "PHP root".into(),
|
||||
document_root: tmp.path().to_path_buf(),
|
||||
htaccess: htaccess::Config { enabled: true, strict: true, ..Default::default() },
|
||||
php: Php { enabled: true, endpoint: format!("tcp:{endpoint}"), ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
configured.validate().unwrap();
|
||||
let service = configured.compile().unwrap();
|
||||
let response = serve_request(&service, &request(Method::GET, "/"), "/").await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let params = received.await.unwrap();
|
||||
assert_eq!(params["SCRIPT_NAME"], "/index.php");
|
||||
assert!(!params.contains_key("PATH_INFO"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn htaccess_accept_path_info_off_overrides_enabled_php_path_info() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::write(tmp.path().join("index.php"), b"<?php // app").unwrap();
|
||||
std::fs::write(tmp.path().join(".htaccess"), b"AcceptPathInfo Off\n").unwrap();
|
||||
let mut configured = Service {
|
||||
id: "pathinfo-overridden".into(),
|
||||
name: "Reject path info".into(),
|
||||
document_root: tmp.path().to_path_buf(),
|
||||
htaccess: htaccess::Config { enabled: true, strict: true, ..Default::default() },
|
||||
php: Php { enabled: true, path_info: true, endpoint: "tcp:127.0.0.1:9000".into(), ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
configured.validate().unwrap();
|
||||
let service = configured.compile().unwrap();
|
||||
assert!(!htaccess::accept_path_info(service.htaccess.as_ref(), "/index.php", true));
|
||||
let response = serve_request(&service, &request(Method::GET, "/index.php/abc"), "/index.php/abc").await;
|
||||
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn htaccess_local_error_document_renders_but_preserves_original_error_status() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::write(tmp.path().join("error.html"), b"custom-not-found").unwrap();
|
||||
std::fs::write(tmp.path().join(".htaccess"), b"ErrorDocument 404 /error.html?404\n").unwrap();
|
||||
let mut configured = Service {
|
||||
id: "local-error-document".into(),
|
||||
name: "Local errors".into(),
|
||||
document_root: tmp.path().to_path_buf(),
|
||||
htaccess: htaccess::Config { enabled: true, strict: true, ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
configured.validate().unwrap();
|
||||
let service = configured.compile().unwrap();
|
||||
let response = serve_request(&service, &request(Method::GET, "/missing"), "/missing").await;
|
||||
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||
assert_eq!(response.headers()[CACHE_CONTROL], "no-store");
|
||||
assert_eq!(response.into_body().collect().await.unwrap().to_bytes(), "custom-not-found");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn htaccess_rewrite_base_maps_relative_target_to_configured_url_prefix() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::create_dir(tmp.path().join("app")).unwrap();
|
||||
std::fs::create_dir(tmp.path().join("mounted")).unwrap();
|
||||
std::fs::write(tmp.path().join("mounted/landing.html"), b"mounted-ok").unwrap();
|
||||
std::fs::write(tmp.path().join("app/.htaccess"), b"RewriteEngine On\nRewriteBase /mounted/\nRewriteRule ^old$ landing.html [L]\n").unwrap();
|
||||
let mut configured = Service {
|
||||
id: "nested-rewrite-base".into(),
|
||||
name: "RewriteBase".into(),
|
||||
document_root: tmp.path().to_path_buf(),
|
||||
htaccess: htaccess::Config { enabled: true, strict: true, ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
configured.validate().unwrap();
|
||||
let service = configured.compile().unwrap();
|
||||
let response = serve_request(&service, &request(Method::GET, "/app/old"), "/app/old").await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.into_body().collect().await.unwrap().to_bytes(), "mounted-ok");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn htaccess_nested_accept_path_info_default_resets_parent_override() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::create_dir(tmp.path().join("nested")).unwrap();
|
||||
std::fs::write(tmp.path().join(".htaccess"), b"AcceptPathInfo On\n").unwrap();
|
||||
std::fs::write(tmp.path().join("nested/.htaccess"), b"AcceptPathInfo Default\n").unwrap();
|
||||
let ht = htaccess::compile(tmp.path(), &htaccess::Config { enabled: true, strict: true, ..Default::default() }).unwrap().unwrap();
|
||||
assert!(htaccess::accept_path_info(Some(&ht), "/index.php", false));
|
||||
assert!(!htaccess::accept_path_info(Some(&ht), "/nested/index.php", false));
|
||||
assert!(htaccess::accept_path_info(Some(&ht), "/nested/index.php", true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn htaccess_error_document_rejects_external_and_escaping_urls_even_non_strict() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
for bad in [
|
||||
"ErrorDocument 404 https://example.test/hidden\n",
|
||||
"ErrorDocument 404 //external.test/\n",
|
||||
"ErrorDocument 404 /../private\n",
|
||||
"ErrorDocument 404 /secret%2f..%2fother\n",
|
||||
"ErrorDocument 404 /malformed?x#frag\n",
|
||||
] {
|
||||
std::fs::write(tmp.path().join(".htaccess"), bad).unwrap();
|
||||
assert!(htaccess::compile(tmp.path(), &htaccess::Config { enabled: true, strict: false, ..Default::default() }).is_err(), "accepted {bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn htaccess_php_error_document_preserves_status_and_passes_its_own_query() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::write(tmp.path().join("error.php"), b"<?php // custom error").unwrap();
|
||||
std::fs::write(tmp.path().join(".htaccess"), b"ErrorDocument 404 /error.php?404\n").unwrap();
|
||||
let (endpoint, received) = fastcgi_fixture_record_params().await;
|
||||
let mut configured = Service {
|
||||
id: "php-local-error".into(),
|
||||
name: "PHP local error".into(),
|
||||
document_root: tmp.path().to_path_buf(),
|
||||
htaccess: htaccess::Config { enabled: true, strict: true, ..Default::default() },
|
||||
php: Php { enabled: true, endpoint: format!("tcp:{endpoint}"), ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
configured.validate().unwrap();
|
||||
let service = configured.compile().unwrap();
|
||||
let response = serve_request(&service, &request(Method::GET, "/missing?x=1"), "/missing").await;
|
||||
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||
assert_eq!(response.headers()[CACHE_CONTROL], "no-store");
|
||||
let params = received.await.unwrap();
|
||||
assert_eq!(params["SCRIPT_NAME"], "/error.php");
|
||||
assert_eq!(params["SCRIPT_FILENAME"], tmp.path().join("error.php").to_string_lossy());
|
||||
assert_eq!(params["QUERY_STRING"], "404");
|
||||
assert_eq!(params["REQUEST_URI"], "/error.php?404");
|
||||
}
|
||||
Reference in new issue
Block a user