This commit is contained in:
Mateusz Gruszczyński committed 2026-11-26 11:02:46 +01:00
1 parent aa0a271a1c
commit f38a2b9e5e
38 files changed
+1098 -160

No files matched your search

+1
View File
@@ -25,6 +25,7 @@ pub(super) static READER_DOCUMENTS: &[(&str, &str, &str)] = &[
reader_doc!("docs/ACCESS.md", "guides"),
reader_doc!("docs/WEB_SERVER.md", "guides"),
reader_doc!("docs/PHP_FPM.md", "guides"),
reader_doc!("docs/FASTCGI.md", "guides"),
reader_doc!("docs/CACHE.md", "guides"),
reader_doc!("docs/CACHE_TEMPLATE_LIBRARY.md", "guides"),
reader_doc!("docs/VCL.md", "guides"),
+66 -3
View File
@@ -2,7 +2,7 @@
"openapi": "3.0.3",
"info": {
"title": "RustProxy Administration API",
"version": "0.42.1",
"version": "0.42.2",
"description": "Administration API for the active panel origin. Sign in through the panel; the same-origin HttpOnly cookie authenticates all private operations. Mutations also require the exact Origin, X-RustProxy-Request: 1 and a session-bound X-CSRF-Token. Loopback HTTP is the default; Settings can enable HTTPS before using a non-loopback administration bind. This document contains no live configuration or credentials. Object schemas marked extensible are summaries: full configuration validation is authoritative in Rust. The API also permits explicitly scoped GeneralApiBearer tokens on a narrow route allowlist, with RO/RW and source CIDR checks; API-token management and Prometheus-token management are browser-session-only."
},
"servers": [
@@ -6806,9 +6806,25 @@
"maxLength": 8192
},
"description": "Trusted operator PHP-FPM administrative php.ini directives packed into PHP_ADMIN_VALUE. Restrict access to FastCGI endpoints."
},
"handler": {
"type": "string",
"enum": [
"php_fpm",
"fcgiwrap",
"fastcgi"
],
"default": "php_fpm",
"description": "PHP-FPM, a CGI runner such as fcgiwrap, or a general FastCGI responder. Existing PHP configurations default to php_fpm."
},
"script_name_prefix": {
"type": "string",
"maxLength": 256,
"default": "",
"description": "Fixed public URL mount prefix prepended to SCRIPT_NAME when the Vhost route strips or rewrites a URL prefix. SCRIPT_FILENAME remains inside the Web Service document root."
}
},
"description": "Optional bounded direct FastCGI connection to a PHP-FPM pool."
"description": "Optional bounded direct FastCGI connection to PHP-FPM, a CGI runner, or another FastCGI responder."
},
"htaccess": {
"type": "object",
@@ -6839,7 +6855,7 @@
"strict": {
"type": "boolean",
"default": false,
"description": "Reject Apply when an unsupported directive is found instead of logging and ignoring it."
"description": "Reject unsupported non-security directives during Apply instead of logging and skipping them. Unsupported access-control and handler constructs are rejected regardless of this setting; supported Order/Allow/Deny IP/CIDR/all rules are enforced."
}
},
"description": "Migration-oriented Apache .htaccess subset compiled at Web Service apply time; never parsed per request."
@@ -13268,6 +13284,53 @@
}
}
},
"/api/web-services/htaccess-warnings": {
"get": {
"summary": "Compiled .htaccess warnings for Web Services",
"tags": [
"Configuration"
],
"operationId": "get_api_web_services_htaccess_warnings",
"description": "Authenticated read-only snapshot. Returns {revision, services:{id:{files_loaded,warnings:[file:line:reason]}}} for configured .htaccess services. Warnings describe non-security directives skipped because Strict is disabled. Unsupported security directives fail validation instead of appearing as warnings. No disk scan is performed per request.",
"security": [
{
"AdminSession": []
}
],
"responses": {
"200": {
"description": "Compiled diagnostics from the active configuration",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
},
"401": {
"description": "Authentication required",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"403": {
"description": "Host or session access denied",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
},
"/api/config/{section}": {
"put": {
"summary": "Replace one configuration section atomically",
+1
View File
@@ -183,6 +183,7 @@ pub fn router(state: Arc<App>) -> Router {
.route("/favicon.svg", get(panel_assets::serve))
.route("/healthz", get(|| async { Json(json!({"status":"ok"})) }))
.route("/api/status", get(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))
.route("/api/alerts", get(alerts_status))
+9
View File
@@ -11,6 +11,15 @@ fn live_chart_system_payload(state: &App) -> Value {
})
}
async fn web_service_htaccess_warnings(State(state): State<Arc<App>>) -> Json<Value> {
let snapshot = state.config.load();
let services = snapshot.web_php_services.iter().filter_map(|(id, service)| {
let (files_loaded, warnings) = service.htaccess_diagnostics()?;
Some((id.clone(), json!({ "files_loaded": files_loaded, "warnings": warnings })))
}).collect::<serde_json::Map<String, Value>>();
Json(json!({ "revision": snapshot.envelope.revision, "services": services }))
}
fn web_server_metrics_payload(snapshot: &crate::config::Snapshot) -> Value {
let mut services = serde_json::Map::new();
for service in &snapshot.envelope.config.web_services {
+24 -15
View File
@@ -921,7 +921,7 @@
data-i18n-placeholder="webServiceSearchPlaceholder" id="web-service-search"
type="search" />
<button class="outline" data-i18n="phpProfileToolbar"
id="web-service-php-profiles-open" type="button">PHP-FPM profiles</button>
id="web-service-php-profiles-open" type="button">FastCGI profiles</button>
<button class="outline" data-i18n="webServiceNew" id="web-service-new"
type="button">New Web Service</button>
</div>
@@ -4864,6 +4864,7 @@ curl -sS -D - -o /dev/null \
checked /><span data-i18n="webServiceHtaccessRecursive">Scan subdirectories</span></label>
<label class="check"><input class="switch" id="web-service-htaccess-strict" type="checkbox" /><span
data-i18n="webServiceHtaccessStrict">Strict unsupported-directive mode</span></label>
<p class="fine vh-wide" data-i18n="webServiceHtaccessStrictHelp">When Strict is off, unsupported non-security directives are skipped and logged as warnings. Legacy Order/Allow/Deny with all, IP and CIDR are enforced; unsupported access-control rules still block Apply.</p>
<div class="vh-wide"><button class="outline" id="web-service-htaccess-help"
data-i18n="webServiceHtaccessDocs" type="button">Compatibility documentation</button></div>
<p class="fine vh-wide" data-i18n="webServiceHtaccessHelp">RustProxy compiles a bounded
@@ -4982,7 +4983,7 @@ curl -sS -D - -o /dev/null \
</div>
<div class="vh-grid web-service-page" data-web-service-page="php" hidden>
<section class="vh-wide vh-setting-section web-service-setting-section">
<h3 data-i18n="webServicePhpSourceSection">PHP-FPM source and endpoint</h3>
<h3 data-i18n="webServicePhpSourceSection">FastCGI / PHP-FPM source and endpoint</h3>
<div class="vh-grid">
<label class="vh-wide"><span data-i18n="phpProfileSelect">PHP-FPM configuration
source</span>
@@ -4994,7 +4995,7 @@ curl -sS -D - -o /dev/null \
Profile changes apply to all attached Web Services.</small>
</label>
<div class="vh-wide"><button type="button" class="outline" id="web-service-php-profiles"
data-i18n="phpProfileManage">Manage PHP-FPM profiles</button></div>
data-i18n="phpProfileManage">Manage FastCGI profiles</button></div>
<div class="vh-wide php-switch-row"><label class="check php-switch-label"><input
class="switch" id="web-service-php-enabled" type="checkbox" /><span
data-i18n="webServicePhpEnabled">Enable PHP-FPM / FastCGI</span></label>
@@ -5009,13 +5010,24 @@ curl -sS -D - -o /dev/null \
</div>
</details>
</div>
<label class="vh-wide"><span data-i18n="webServicePhpEndpoint">PHP-FPM endpoint</span><input
<label class="vh-wide"><span data-i18n="webServiceFastCgiHandler">FastCGI handler</span>
<select id="web-service-php-handler">
<option value="php_fpm">PHP-FPM</option>
<option value="fcgiwrap">fcgiwrap (CGI)</option>
<option value="fastcgi">FastCGI responder</option>
</select><small class="fine" data-i18n="webServiceFastCgiHandlerHelp">Select PHP-FPM for PHP, fcgiwrap for CGI programs or FastCGI for compatible responders.</small>
</label>
<label class="vh-wide"><span data-i18n="webServiceFastCgiScriptPrefix">Public SCRIPT_NAME prefix</span>
<input id="web-service-php-script-prefix" maxlength="256" placeholder="/app/cgi-bin" />
<small class="fine" data-i18n="webServiceFastCgiScriptPrefixHelp">Set the public URL prefix removed by the Vhost path rewrite, for example /app/cgi-bin. Leave empty without a rewrite.</small>
</label>
<label class="vh-wide"><span data-i18n="webServicePhpEndpoint">FastCGI endpoint</span><input
id="web-service-php-endpoint" maxlength="512"
placeholder="unix:/run/php/php-fpm.sock" /><small class="fine"
data-i18n="webServicePhpEndpointHelp">Unix: unix:/run/php/php-fpm.sock. TCP:
tcp:127.0.0.1:9000 or tcp:[::1]:9000. TCP is intentionally limited to loopback
addresses.</small></label>
<label><span data-i18n="webServicePhpExtensions">PHP extensions</span><input
<label><span data-i18n="webServicePhpExtensions">Executable extensions (PHP or CGI)</span><input
id="web-service-php-extensions" maxlength="512" placeholder="php, phtml" /><small
class="fine" data-i18n="phpHintExtensions">Comma-separated extensions without dots
(e.g.
@@ -5125,10 +5137,7 @@ curl -sS -D - -o /dev/null \
<div class="vh-wide form-actions"><button class="outline"
data-i18n="webServicePhpDocsButton" id="web-service-php-help" type="button">FastCGI
syntax and safety</button></div>
<p class="fine vh-wide" data-i18n="webServicePhpHelp">RustProxy speaks FastCGI directly to a
long-running PHP-FPM pool. PHP is not spawned per request and PHP source is never served
when
PHP handling is selected.</p>
<p class="fine vh-wide" data-i18n="webServicePhpHelp">RustProxy connects to PHP-FPM, fcgiwrap or other compatible FastCGI responders. Select executable extensions, configure a Unix or loopback TCP endpoint, and optionally set the public SCRIPT_NAME prefix when Vhost locations strip a URL prefix. Script source is never served statically for protected executable extensions.</p>
</div>
</section>
</div>
@@ -5160,7 +5169,7 @@ curl -sS -D - -o /dev/null \
</dialog>
<dialog aria-labelledby="php-profiles-title" class="vhost-dialog location-help-dialog" id="php-fpm-profiles-dialog">
<div class="window-heading">
<h2 id="php-profiles-title" data-i18n="phpProfileTitle">Shared PHP-FPM profiles</h2>
<h2 id="php-profiles-title" data-i18n="phpProfileTitle">Shared FastCGI profiles</h2>
<button type="button" class="outline" id="php-fpm-profiles-close" data-i18n="close">Close</button>
</div>
<div class="card location-help-content">
@@ -5207,11 +5216,11 @@ RewriteRule . /index.php [L]</code></pre>
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 in this compatibility layer. General Files/FilesMatch, unsupported
authentication/authorization directives, non-PHP handlers and SetHandler are rejected even when Strict
mode is off because silently ignoring them could weaken access control or expose source.
.htaccess/.htpasswd files are always blocked from HTTP delivery. Other unsupported non-security
directives are logged and ignored unless Strict mode is enabled.</p>
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 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>
+33 -3
View File
@@ -13,6 +13,8 @@ window.rustProxyPhpProfiles = ({ defaults, mapLines, lines, parseFastCgiParams,
const profileFields = [
["enabled", "webServicePhpEnabled", "checkbox"],
["endpoint", "webServicePhpEndpoint", "text"],
["handler", "webServiceFastCgiHandler", "select"],
["script_name_prefix", "webServiceFastCgiScriptPrefix", "text"],
["extensions", "webServicePhpExtensions", "text"],
["path_info", "webServicePhpPathInfo", "checkbox"],
["pass_authorization", "webServicePhpPassAuthorization", "checkbox"],
@@ -29,6 +31,7 @@ window.rustProxyPhpProfiles = ({ defaults, mapLines, lines, parseFastCgiParams,
const helpKeys = {
enabled: "phpHintEnabled", path_info: "phpHintPathInfo", endpoint: "webServicePhpDocsEndpoint",
handler: "webServiceFastCgiHandlerHelp", script_name_prefix: "webServiceFastCgiScriptPrefixHelp",
extensions: "phpHintExtensions", pass_authorization: "phpHintPassAuthorization",
connect_timeout_ms: "phpHintConnectTimeout", request_timeout_ms: "phpHintRequestTimeout",
max_concurrent_requests: "phpHintConcurrency", max_request_body_bytes: "phpHintBodyLimit",
@@ -56,18 +59,25 @@ window.rustProxyPhpProfiles = ({ defaults, mapLines, lines, parseFastCgiParams,
const wrapper = toggle ? el("div", undefined, "php-switch-row vh-wide") : el("label");
if (!toggle && kind === "textarea") wrapper.className = "vh-wide";
const labelEl = toggle ? el("label", undefined, "check php-switch-label") : wrapper;
const input = document.createElement(kind === "textarea" ? "textarea" : "input");
if (kind !== "textarea") input.type = kind;
const input = document.createElement(kind === "textarea" ? "textarea" : kind === "select" ? "select" : "input");
if (kind !== "textarea" && kind !== "select") input.type = kind;
if (kind === "select") {
for (const [value, label] of [["php_fpm", "PHP-FPM"], ["fcgiwrap", "fcgiwrap (CGI)"], ["fastcgi", "FastCGI responder"]]) {
const option = el("option", label); option.value = value; input.append(option);
}
}
if (toggle) input.classList.add("switch");
const caption = el("span", t(label));
if (toggle) labelEl.append(input, caption); else labelEl.append(caption, input);
if (toggle) input.checked = profile.php?.[key] === true;
else if (kind === "textarea") { input.rows = 4; input.maxLength = 65536; input.value = mapLines(profile.php?.[key]); }
else if (key === "extensions") input.value = (profile.php?.extensions || ["php"]).join(", ");
else if (key === "handler") input.value = profile.php?.handler || "php_fpm";
else input.value = profile.php?.[key] ?? "";
if (kind === "number") { input.min = min; input.max = max; input.step = 1; input.required = true; }
if (key === "endpoint") { input.required = true; input.maxLength = 512; input.placeholder = "unix:/run/php/php-fpm.sock"; }
if (key === "extensions") input.placeholder = "php, phtml";
if (key === "script_name_prefix") { input.maxLength = 256; input.placeholder = "/app/cgi-bin"; }
if (key === "extensions") input.placeholder = "php, cgi, fcgi";
if (key === "custom_params") input.placeholder = "APP_ENV = production\nAPP_DEBUG = 0";
if (key === "php_values") input.placeholder = "memory_limit = 256M\npost_max_size = 64M";
if (key === "php_admin_values") input.placeholder = "open_basedir = /var/www/webmail/:/tmp/";
@@ -83,6 +93,26 @@ window.rustProxyPhpProfiles = ({ defaults, mapLines, lines, parseFastCgiParams,
}
editor.append(wrapper); controls[key] = input;
}
const handlerSelector = controls.handler;
handlerSelector.addEventListener("change", () => {
const kind = handlerSelector.value;
if (kind !== "php_fpm" && controls.extensions.value.trim().toLowerCase() === "php") {
controls.extensions.value = kind === "fcgiwrap" ? "cgi" : "fcgi";
} else if (kind === "php_fpm" && ["cgi", "fcgi"].includes(controls.extensions.value.trim().toLowerCase())) {
controls.extensions.value = "php";
}
if (kind === "fcgiwrap" && controls.endpoint.value === "unix:/run/php/php-fpm.sock") {
controls.endpoint.value = "unix:/run/fcgiwrap.socket";
}
if (kind !== "php_fpm") {
controls.php_values.value = "";
controls.php_admin_values.value = "";
}
controls.php_values.disabled = kind !== "php_fpm";
controls.php_admin_values.disabled = kind !== "php_fpm";
});
controls.php_values.disabled = handlerSelector.value !== "php_fpm";
controls.php_admin_values.disabled = handlerSelector.value !== "php_fpm";
const actions = el("div", undefined, "form-actions vh-wide");
const save = el("button", t("apply"), "primary"); save.type = "submit";
actions.append(save);
+57 -4
View File
@@ -1,6 +1,7 @@
"use strict";
(() => {
let editing = null, dirty = false;
let htaccessWarnings = {}, htaccessWarningsRevision = null, htaccessWarningsLoading = false;
const form = $("web-service-form"), dialog = $("web-service-dialog");
function syncRootPermissions() {
window.rustProxyPermissions?.render($("web-service-permissions"), { kind: "web", paths: [$("web-service-root").value] });
@@ -54,7 +55,7 @@
const reservedFastCgiParams = new Set([
"REQUEST_METHOD", "SCRIPT_FILENAME", "SCRIPT_NAME", "QUERY_STRING", "REQUEST_URI", "DOCUMENT_ROOT",
"SERVER_PROTOCOL", "SERVER_NAME", "SERVER_PORT", "REMOTE_ADDR", "REMOTE_PORT", "HTTPS",
"SERVER_PROTOCOL", "SERVER_NAME", "SERVER_PORT", "REMOTE_ADDR", "REMOTE_PORT", "REMOTE_USER", "AUTH_USER", "HTTPS",
"GATEWAY_INTERFACE", "SERVER_SOFTWARE", "REDIRECT_STATUS", "CONTENT_TYPE", "CONTENT_LENGTH",
"PATH_INFO", "PATH_TRANSLATED", "PHP_VALUE", "PHP_ADMIN_VALUE"
]);
@@ -170,13 +171,17 @@
const attached = !!$("web-service-php-profile").value;
const enabled = $("web-service-php-enabled").checked;
$("web-service-php-enabled").disabled = attached;
const phpFpm = $("web-service-php-handler").value === "php_fpm";
$("web-service-php-values").disabled = !enabled || attached || !phpFpm;
$("web-service-php-admin-values").disabled = !enabled || attached || !phpFpm;
for (const id of [
"web-service-php-endpoint", "web-service-php-extensions", "web-service-php-connect-timeout",
"web-service-php-endpoint", "web-service-php-handler", "web-service-php-script-prefix",
"web-service-php-extensions", "web-service-php-connect-timeout",
"web-service-php-request-timeout", "web-service-php-concurrency", "web-service-php-pass-authorization",
"web-service-php-path-info",
"web-service-php-body-limit", "web-service-php-header-limit", "web-service-php-stderr-limit",
"web-service-php-custom-params", "web-service-php-values", "web-service-php-admin-values"
"web-service-php-custom-params"
]) $(id).disabled = !enabled || attached;
}
@@ -213,7 +218,8 @@
mime_types: {}, default_mime_type: "application/octet-stream", cache_control: null, cache_rules: [], response_headers: {},
try_files: [], rewrites: [], compression: { enabled: null, gzip: null, br: null, zstd: null, deflate: null }, precompressed: { enabled: false, brotli: true, gzip: true }, download_extensions: [],
symlink_policy: "deny", php_profile_id: null, php: {
enabled: false, path_info: false, extensions: ["php"], endpoint: "unix:/run/php/php-fpm.sock", connect_timeout_ms: 1000,
enabled: false, path_info: false, extensions: ["php"], endpoint: "unix:/run/php/php-fpm.sock",
handler: "php_fpm", script_name_prefix: "", connect_timeout_ms: 1000,
request_timeout_ms: 30000, max_concurrent_requests: 64, pass_authorization: true, max_request_body_bytes: 0,
max_response_header_bytes: 65536, stderr_log_bytes: 4096, custom_params: {}, php_values: {}, php_admin_values: {}
},
@@ -264,6 +270,8 @@
$("web-service-php-enabled").checked = item.php?.enabled === true;
$("web-service-php-path-info").checked = item.php?.path_info === true;
$("web-service-php-endpoint").value = item.php?.endpoint || "unix:/run/php/php-fpm.sock";
$("web-service-php-handler").value = ["php_fpm", "fcgiwrap", "fastcgi"].includes(item.php?.handler) ? item.php.handler : "php_fpm";
$("web-service-php-script-prefix").value = item.php?.script_name_prefix || "";
$("web-service-php-extensions").value = (item.php?.extensions || ["php"]).join(", ");
$("web-service-php-connect-timeout").value = item.php?.connect_timeout_ms ?? 1000;
$("web-service-php-request-timeout").value = item.php?.request_timeout_ms ?? 30000;
@@ -362,9 +370,23 @@
}
function closeEditor() { if (dirty) return window.rustProxyDrafts.dock("web-server"); clearEditor(); return true; }
async function loadHtaccessWarnings() {
if (htaccessWarningsLoading || !envelope || !authenticated) return;
htaccessWarningsLoading = true;
try {
const result = await api("/api/web-services/htaccess-warnings");
if (!envelope || result.revision !== envelope.revision) return;
htaccessWarnings = result.services || {};
htaccessWarningsRevision = result.revision;
if (currentPanel === "web-server") render();
} catch { /* The configuration remains available if diagnostics cannot be loaded. */ }
finally { htaccessWarningsLoading = false; }
}
function render() {
syncRootPermissions();
if (!envelope) return;
if (htaccessWarningsRevision !== envelope.revision && !htaccessWarningsLoading) void loadHtaccessWarnings();
const query = ($("web-service-search")?.value || "").trim().toLowerCase();
const services = (envelope.config.web_services || []).filter(service => !query || [service.id, service.name, service.document_root].join(" ").toLowerCase().includes(query));
const cards = services.map(service => {
@@ -402,6 +424,17 @@
item.append(el("span", t(key), "small-label"), el("b", value));
details.append(item);
}
// Show the real skipped directives from the active configuration, with
// file/line context. Security-related errors never appear here: they fail Apply.
const ignored = htaccessWarningsRevision === envelope.revision ? (htaccessWarnings[service.id]?.warnings || []) : [];
if (service.htaccess?.enabled && ignored.length) {
const details = el("details", undefined, "web-service-htaccess-warnings");
details.append(el("summary", `${t("webServiceHtaccessWarningsCount")}: ${ignored.length}`));
const lines = el("ul");
for (const warning of ignored.slice(0, 50)) lines.append(el("li", warning));
if (ignored.length > 50) lines.append(el("li", `+${ignored.length - 50}`));
details.append(lines); box.append(details);
}
const live = el("section", undefined, "www-service-panel");
const panel = el("div", undefined, "www-service-live"); panel.dataset.webLiveId = service.id;
@@ -517,6 +550,8 @@
path_info: $("web-service-php-path-info").checked,
extensions: lines($("web-service-php-extensions").value).map(value => value.replace(/^\./, "").toLowerCase()),
endpoint: $("web-service-php-endpoint").value.trim() || "unix:/run/php/php-fpm.sock",
handler: $("web-service-php-handler").value,
script_name_prefix: $("web-service-php-script-prefix").value.trim(),
connect_timeout_ms: Number($("web-service-php-connect-timeout").value || 1000),
request_timeout_ms: Number($("web-service-php-request-timeout").value || 30000),
max_concurrent_requests: Number($("web-service-php-concurrency").value || 64),
@@ -548,6 +583,24 @@
$("web-service-root").addEventListener("input", syncRootPermissions);
$("web-service-root").addEventListener("change", syncRootPermissions);
$("web-service-php-enabled").addEventListener("change", syncPhp);
$("web-service-php-handler").addEventListener("change", () => {
const kind = $("web-service-php-handler").value;
const extensions = $("web-service-php-extensions");
if (kind !== "php_fpm" && extensions.value.trim().toLowerCase() === "php") {
extensions.value = kind === "fcgiwrap" ? "cgi" : "fcgi";
} else if (kind === "php_fpm" && ["cgi", "fcgi"].includes(extensions.value.trim().toLowerCase())) {
extensions.value = "php";
}
const endpoint = $("web-service-php-endpoint");
if (kind === "fcgiwrap" && endpoint.value === "unix:/run/php/php-fpm.sock") {
endpoint.value = "unix:/run/fcgiwrap.socket";
}
if (kind !== "php_fpm") {
$("web-service-php-values").value = "";
$("web-service-php-admin-values").value = "";
}
syncPhp();
});
$("web-service-php-profile").addEventListener("change", syncPhp);
$("web-service-php-profiles").addEventListener("click", openProfiles);
$("web-service-php-profiles-open").addEventListener("click", openProfiles);
+7
View File
@@ -157,6 +157,13 @@ fn denied(status: StatusCode, challenge: Option<&HeaderValue>) -> Response {
.insert(crate::auth_provider::AuthenticationResponse);
response
}
/// Use only with the Authorization value returned from a successful authorize().
/// This is not itself authentication; do not call on untrusted request headers.
pub(crate) fn verified_username(value: &HeaderValue) -> Option<String> {
let mut headers = HeaderMap::new();
headers.insert("authorization", value.clone());
credentials(&headers).map(|(username, _, _)| username)
}
fn credentials(headers: &HeaderMap) -> Option<(String, Zeroizing<String>, HeaderValue)> {
if headers.get_all("authorization").iter().count() != 1 {
return None;
+7 -3
View File
@@ -428,8 +428,10 @@ impl CompiledRoute {
let tail = path.strip_prefix(&self.path_prefix).unwrap_or("");
if tail.is_empty() {
"/".to_owned()
} else {
} else if tail.starts_with('/') {
tail.to_owned()
} else {
format!("/{tail}")
}
}
RewriteMode::ReplacePrefix => {
@@ -442,9 +444,11 @@ impl CompiledRoute {
base.to_owned()
}
} else if base.is_empty() || base == "/" {
tail.to_owned()
} else {
if tail.starts_with('/') { tail.to_owned() } else { format!("/{tail}") }
} else if tail.starts_with('/') {
format!("{base}{tail}")
} else {
format!("{base}/{tail}")
}
}
RewriteMode::Regex => self
+26
View File
@@ -837,6 +837,32 @@ mod tests {
Some("/service/42/Ubuntu 14.04 LTS")
);
}
#[test]
fn web_service_prefix_mount_rewrite_keeps_absolute_script_paths() {
for prefix in ["/console", "/console/"] {
let mut config = demo_config("127.0.0.1:9000".parse().unwrap());
let route = &mut config.vhosts[0].routes[0];
route.id = "mount".into();
route.match_type = crate::vhost::PathMatch::Prefix;
route.path_prefix = prefix.into();
route.rewrite = crate::vhost::PathRewrite {
mode: crate::vhost::RewriteMode::StripPrefix,
value: String::new(),
};
let snapshot = compile(config.clone(), 1, &policy()).unwrap();
let selected = snapshot.select("localhost", "/console/status.php").unwrap();
assert_eq!(selected.rewritten_path("/console/status.php").unwrap().as_deref(), Some("/status.php"));
assert_eq!(selected.rewritten_path("/console/").unwrap().as_deref(), Some("/"));
config.vhosts[0].routes[0].rewrite = crate::vhost::PathRewrite {
mode: crate::vhost::RewriteMode::ReplacePrefix,
value: "/internal".into(),
};
let snapshot = compile(config, 1, &policy()).unwrap();
assert_eq!(snapshot.select("localhost", "/console/status.php").unwrap()
.rewritten_path("/console/status.php").unwrap().as_deref(), Some("/internal/status.php"));
}
}
#[test]
fn custom_location_response_is_validated() {
let mut c = demo_config("127.0.0.1:9000".parse().unwrap());
+9
View File
@@ -139,6 +139,14 @@
} else {
(std::mem::take(&mut request_headers), false)
};
// Vhost Basic authentication already removed untrusted credentials. Forward
// only the verified value, when the operator selected forward_credentials.
let mut origin_request_headers = origin_request_headers;
if let Some(auth) = frontend.and_then(|f| f.basic_auth.as_ref()) {
auth.apply_upstream(&mut origin_request_headers, basic_identity.clone());
}
let authenticated_user = basic_identity.as_ref()
.and_then(crate::basic_auth::verified_username);
let started = Instant::now();
let response = crate::web_server::serve(service, request_method.clone(),
origin_request_headers, request_uri, &service_path, static_body,
@@ -149,6 +157,7 @@
server_port: local.0.port(),
tls,
version: request_version,
authenticated_user,
}).await;
if let Some(fallback) = execute_error_fallback(
state.clone(), peer, local, &snapshot, &host, tls, route,
@@ -81,6 +81,7 @@ async fn serve_file(
server_port: 443,
tls: true,
version: http::Version::HTTP_2,
authenticated_user: None,
},
)
.await
+30 -4
View File
@@ -9,6 +9,28 @@ impl Php {
"Web Service PHP extension",
)?;
self.endpoint = self.endpoint.trim().to_owned();
self.script_name_prefix = self.script_name_prefix.trim().to_owned();
if !self.script_name_prefix.is_empty() {
ensure!(
self.script_name_prefix.starts_with('/')
&& !self.script_name_prefix.ends_with('/')
&& self.script_name_prefix.len() <= 256
&& self.script_name_prefix.bytes().all(|byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'_' | b'-' | b'.')
})
&& self.script_name_prefix.split('/').skip(1).all(|part| {
!part.is_empty() && part != "." && part != ".."
}),
"Web Service FastCGI SCRIPT_NAME prefix must be /path (no trailing slash, dot segments or special characters)"
);
}
if self.handler != FastCgiHandler::PhpFpm {
ensure!(self.php_values.is_empty() && self.php_admin_values.is_empty(),
"PHP_VALUE and PHP_ADMIN_VALUE require handler=php_fpm");
ensure!(self.extensions.iter().all(|ext| !matches!(ext.as_str(),
"php" | "phtml" | "phar" | "php3" | "php4" | "php5" | "php7" | "php8")),
"non-PHP FastCGI handlers cannot execute PHP extensions; use php_fpm");
}
ensure!(
self.connect_timeout_ms >= 50 && self.connect_timeout_ms <= 60_000,
"Web Service PHP connect timeout must be 50..60000 ms"
@@ -57,7 +79,7 @@ impl Php {
if self.enabled {
ensure!(
!self.extensions.is_empty(),
"PHP-FPM needs executable extensions"
"FastCGI needs at least one executable extension"
);
FastCgiEndpoint::parse(&self.endpoint)?;
}
@@ -304,12 +326,12 @@ impl Service {
if self.php.enabled {
ensure!(
!self.php.extensions.is_empty(),
"Web Service PHP needs at least one executable extension"
"Web Service FastCGI needs at least one executable extension"
);
FastCgiEndpoint::parse(&self.php.endpoint)?;
ensure!(
self.symlink_policy == SymlinkPolicy::Deny,
"PHP-FPM currently requires symlink_policy=deny to avoid script-path races"
"FastCGI script execution requires symlink_policy=deny to avoid script-path races"
);
}
@@ -348,7 +370,8 @@ impl Service {
let htaccess = htaccess::compile(&root, &self.htaccess)?;
if let Some(compiled) = &htaccess {
ensure!(
self.php.enabled || !htaccess::adds_php_extensions(Some(compiled)),
(self.php.enabled && self.php.handler == FastCgiHandler::PhpFpm)
|| !htaccess::adds_php_extensions(Some(compiled)),
".htaccess AddHandler for PHP requires PHP-FPM to be enabled on the Web Service"
);
tracing::debug!(service = %self.id, files = compiled.files_loaded, ".htaccess compatibility compiled");
@@ -397,6 +420,7 @@ impl Service {
script_extensions.extend(
[
"php", "phtml", "phar", "php3", "php4", "php5", "php7", "php8",
"cgi", "fcgi", "pl", "py", "sh",
]
.into_iter()
.map(str::to_owned),
@@ -406,6 +430,8 @@ impl Service {
extensions: self.php.extensions.iter().cloned().collect(),
path_info: self.php.path_info,
endpoint: FastCgiEndpoint::parse(&self.php.endpoint)?,
handler: self.php.handler,
script_name_prefix: self.php.script_name_prefix.clone(),
connect_timeout: Duration::from_millis(self.php.connect_timeout_ms),
request_timeout: Duration::from_millis(self.php.request_timeout_ms),
permits: Arc::new(Semaphore::new(self.php.max_concurrent_requests)),
+18
View File
@@ -112,6 +112,8 @@ fn reserved_fastcgi_param(name: &str) -> bool {
| "SERVER_PORT"
| "REMOTE_ADDR"
| "REMOTE_PORT"
| "REMOTE_USER"
| "AUTH_USER"
| "HTTPS"
| "GATEWAY_INTERFACE"
| "SERVER_SOFTWARE"
@@ -259,6 +261,15 @@ impl Default for Precompressed {
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum FastCgiHandler {
#[default]
PhpFpm,
Fcgiwrap,
Fastcgi,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Php {
@@ -267,6 +278,11 @@ pub struct Php {
#[serde(default = "default_php_extensions")]
pub extensions: Vec<String>,
pub endpoint: String,
/// Existing configurations default to PHP-FPM; fcgiwrap runs installed CGI scripts.
pub handler: FastCgiHandler,
/// Public URL prefix when a Vhost location rewrites a mount path.
/// SCRIPT_FILENAME stays confined to document_root; SCRIPT_NAME gains this prefix.
pub script_name_prefix: String,
#[serde(default = "default_php_connect_timeout_ms")]
pub connect_timeout_ms: u64,
#[serde(default = "default_php_request_timeout_ms")]
@@ -292,6 +308,8 @@ impl Default for Php {
path_info: false,
extensions: default_php_extensions(),
endpoint: "unix:/run/php/php-fpm.sock".into(),
handler: FastCgiHandler::PhpFpm,
script_name_prefix: String::new(),
connect_timeout_ms: default_php_connect_timeout_ms(),
request_timeout_ms: default_php_request_timeout_ms(),
max_concurrent_requests: default_php_max_concurrent_requests(),
+15 -5
View File
@@ -1,25 +1,25 @@
impl FastCgiEndpoint {
pub(super) fn parse(value: &str) -> Result<Self> {
if let Some(path) = value.strip_prefix("unix:") {
ensure!(!path.trim().is_empty(), "PHP-FPM unix socket path is empty");
ensure!(!path.trim().is_empty(), "FastCGI Unix socket path is empty");
#[cfg(unix)]
{
return Ok(Self::Unix(PathBuf::from(path)));
}
#[cfg(not(unix))]
anyhow::bail!("PHP-FPM unix sockets require a Unix platform");
anyhow::bail!("FastCGI Unix sockets require a Unix platform");
}
if let Some(address) = value.strip_prefix("tcp:") {
let address = address
.parse::<std::net::SocketAddr>()
.context("PHP-FPM TCP endpoint must be an IP socket address")?;
.context("FastCGI TCP endpoint must be an IP socket address")?;
ensure!(
address.ip().is_loopback(),
"PHP-FPM TCP endpoint must use a loopback address"
"FastCGI TCP endpoint must use a loopback address"
);
return Ok(Self::Tcp(address));
}
anyhow::bail!("PHP-FPM endpoint must start with unix: or tcp:")
anyhow::bail!("FastCGI endpoint must start with unix: or tcp:")
}
}
@@ -28,6 +28,8 @@ pub(crate) struct CompiledPhp {
pub(super) extensions: HashSet<String>,
pub(super) path_info: bool,
pub(super) endpoint: FastCgiEndpoint,
pub(super) handler: FastCgiHandler,
pub(super) script_name_prefix: String,
pub(super) connect_timeout: Duration,
pub(super) request_timeout: Duration,
pub(crate) permits: Arc<Semaphore>,
@@ -69,3 +71,11 @@ pub struct CompiledService {
#[cfg(unix)]
pub(super) root_handle: Arc<File>,
}
impl CompiledService {
// Read-only diagnostics for the authenticated administration UI. Warnings
// come from the active compiled snapshot, not from another filesystem scan.
pub fn htaccess_diagnostics(&self) -> Option<(usize, &[String])> {
self.htaccess.as_ref().map(|compiled| (compiled.files_loaded, compiled.warnings.as_slice()))
}
}
+8 -4
View File
@@ -141,7 +141,11 @@ pub(super) fn fastcgi_params(
let mut params = BTreeMap::<String, String>::new();
params.insert("REQUEST_METHOD".into(), method.as_str().into());
params.insert("SCRIPT_FILENAME".into(), script_filename);
params.insert("SCRIPT_NAME".into(), script_path.into());
params.insert("SCRIPT_NAME".into(), format!("{}{}", php.script_name_prefix, script_path));
if let Some(username) = context.authenticated_user.as_deref() {
params.insert("REMOTE_USER".into(), username.to_owned());
params.insert("AUTH_USER".into(), username.to_owned());
}
if let Some(path_info) = path_info.filter(|value| !value.is_empty()) {
params.insert("PATH_INFO".into(), path_info.into());
}
@@ -208,7 +212,7 @@ pub(super) fn fastcgi_params(
for (name, value) in &php.custom_params {
params.insert(name.clone(), value.clone());
}
if !php.php_values.is_empty() {
if php.handler == super::config::FastCgiHandler::PhpFpm && !php.php_values.is_empty() {
let mut value = String::new();
for (name, item) in &php.php_values {
if !value.is_empty() {
@@ -220,7 +224,7 @@ pub(super) fn fastcgi_params(
}
params.insert("PHP_VALUE".into(), value);
}
if !php.php_admin_values.is_empty() {
if php.handler == super::config::FastCgiHandler::PhpFpm && !php.php_admin_values.is_empty() {
let value = php
.php_admin_values
.iter()
@@ -375,7 +379,7 @@ async fn drain_fastcgi_body(
if !stderr.is_empty() {
tracing::warn!(
stderr = %String::from_utf8_lossy(&stderr),
"PHP-FPM FastCGI stderr"
"FastCGI stderr"
);
}
}
+7 -10
View File
@@ -73,7 +73,7 @@ async fn php_response_inner(
Ok(Ok(io)) => io,
Ok(Err(error)) => {
php.metrics.failure(2);
tracing::warn!(%error, service = %service.id, "PHP-FPM connection failed");
tracing::warn!(%error, service = %service.id, "FastCGI connection failed");
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
}
Err(_) => {
@@ -94,7 +94,7 @@ async fn php_response_inner(
) {
Ok(params) => params,
Err(error) => {
tracing::warn!(%error, service = %service.id, "PHP-FPM parameter preparation failed");
tracing::warn!(%error, service = %service.id, "FastCGI parameter preparation failed");
php.metrics.failure(4);
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
}
@@ -136,7 +136,7 @@ async fn php_response_inner(
}
Ok(Err(FastCgiRequestWriteError::Io(error))) => {
php.metrics.failure(4);
tracing::warn!(%error, service = %service.id, "PHP-FPM request write failed");
tracing::warn!(%error, service = %service.id, "FastCGI request write failed");
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
}
Err(_) => {
@@ -156,7 +156,7 @@ async fn php_response_inner(
return builtin_error_response(StatusCode::GATEWAY_TIMEOUT, &method);
}
Err(error) => {
tracing::warn!(%error, service = %service.id, "PHP-FPM response read failed");
tracing::warn!(%error, service = %service.id, "FastCGI response read failed");
php.metrics.failure(6);
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
}
@@ -174,7 +174,7 @@ async fn php_response_inner(
match parsed {
Ok((status, headers)) => break (status, headers, body),
Err(error) => {
tracing::warn!(%error, service = %service.id, "PHP-FPM CGI headers rejected");
tracing::warn!(%error, service = %service.id, "FastCGI CGI headers rejected");
php.metrics.failure(7);
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
}
@@ -188,7 +188,7 @@ async fn php_response_inner(
FCGI_END_REQUEST => {
php.metrics.failure(7);
if !stderr.is_empty() {
tracing::warn!(stderr = %String::from_utf8_lossy(&stderr), service = %service.id, "PHP-FPM FastCGI stderr");
tracing::warn!(stderr = %String::from_utf8_lossy(&stderr), service = %service.id, "FastCGI stderr");
}
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
}
@@ -196,7 +196,7 @@ async fn php_response_inner(
}
};
if !stderr.is_empty() {
tracing::warn!(stderr = %String::from_utf8_lossy(&stderr), service = %service.id, "PHP-FPM FastCGI stderr");
tracing::warn!(stderr = %String::from_utf8_lossy(&stderr), service = %service.id, "FastCGI stderr");
}
let send_body = method != Method::HEAD
&& status != StatusCode::NO_CONTENT
@@ -258,9 +258,6 @@ pub(super) fn php_for_path<'a>(
}
pub(super) fn protected_script_without_handler(service: &CompiledService, path: &Path) -> bool {
if service.php.is_some() {
return false;
}
path.extension()
.and_then(|value| value.to_str())
.map(|value| value.to_ascii_lowercase())
+114 -1
View File
@@ -3,6 +3,7 @@ use super::{
routing::open_components,
};
use anyhow::{bail, ensure, Context, Result};
use ipnet::IpNet;
use axum::{body::Body, response::Response};
use http::{
header::{CACHE_CONTROL, EXPIRES, LOCATION},
@@ -14,6 +15,7 @@ use std::{
collections::{BTreeMap, HashSet},
fs,
io::Read,
net::IpAddr,
path::{Path, PathBuf},
str::FromStr,
time::{Duration, SystemTime},
@@ -27,6 +29,8 @@ const MAX_HTACCESS_RULES: usize = 256;
const MAX_HTACCESS_CONDITIONS: usize = 512;
const MAX_HTACCESS_HEADERS: usize = 64;
const MAX_HTACCESS_MIME_TYPES: usize = 128;
const MAX_HTACCESS_ACCESS_SELECTORS: usize = 128;
const MAX_HTACCESS_FILE_RULES: usize = 64;
fn default_filename() -> String {
".htaccess".into()
@@ -85,6 +89,7 @@ pub struct Compiled {
struct Scope {
components: Vec<String>,
rewrites: Vec<RewriteRule>,
redirects: Vec<SimpleRedirect>,
directory_index: Option<Vec<String>>,
directory_listing: Option<bool>,
mime_types: BTreeMap<String, HeaderValue>,
@@ -94,6 +99,83 @@ struct Scope {
expires_default: Option<Duration>,
expires_by_type: Vec<(String, Duration)>,
deny_all: Option<bool>,
legacy_access: Option<LegacyAccess>,
file_rules: Vec<FileAccessRule>,
}
// Apache Files / FilesMatch rules apply to filenames below their directory.
// Only bounded access-control directives are accepted inside these blocks.
#[derive(Debug, Clone)]
struct FileAccessRule {
matcher: Regex,
deny_all: Option<bool>,
legacy_access: Option<LegacyAccess>,
}
impl FileAccessRule {
fn denied(&self, client_ip: IpAddr) -> Option<bool> {
if let Some(legacy) = &self.legacy_access {
Some(self.deny_all.unwrap_or(false) || legacy.denied(client_ip))
} else {
self.deny_all
}
}
}
// Apache 2.2 mod_access_compat's Order/Allow/Deny are access rules, not
// harmless unsupported directives. Evaluate them instead of silently skipping
// them and accidentally publishing protected files.
#[derive(Debug, Clone, Copy, Default)]
enum LegacyOrder {
#[default]
DenyAllow,
AllowDeny,
MutualFailure,
}
#[derive(Debug, Clone)]
enum AccessSelector {
All,
Network(IpNet),
}
impl AccessSelector {
fn matches(&self, client_ip: IpAddr) -> bool {
match self {
Self::All => true,
Self::Network(network) => network.contains(&client_ip),
}
}
}
#[derive(Debug, Clone, Default)]
struct LegacyAccess {
order: LegacyOrder,
allow: Vec<AccessSelector>,
deny: Vec<AccessSelector>,
}
impl LegacyAccess {
fn denied(&self, client_ip: IpAddr) -> bool {
let allowed = self.allow.iter().any(|selector| selector.matches(client_ip));
let denied = self.deny.iter().any(|selector| selector.matches(client_ip));
match self.order {
LegacyOrder::DenyAllow => denied && !allowed,
LegacyOrder::AllowDeny | LegacyOrder::MutualFailure => !allowed || denied,
}
}
}
#[derive(Debug, Clone)]
struct SimpleRedirect {
matcher: RedirectMatcher,
replacement: String,
status: StatusCode,
}
#[derive(Debug, Clone)]
enum RedirectMatcher {
Prefix(String),
Regex(Regex),
}
#[derive(Debug, Clone)]
@@ -158,7 +240,7 @@ struct ParseState {
rewrite_engine: bool,
pending_conditions: Vec<RewriteCondition>,
skip_next_rule: bool,
in_files_block: usize,
file_block: Option<FileAccessRule>,
unsupported: Vec<String>,
}
@@ -395,6 +477,37 @@ fn normalize_extension(value: &str) -> Result<String> {
Ok(value)
}
fn legacy_access_selectors(parts: &[String], path: &Path, line_no: usize) -> Result<Vec<AccessSelector>> {
ensure!(
parts.len() >= 3 && parts[1].eq_ignore_ascii_case("from"),
"{}:{line_no}: {} expects 'from all' or 'from IP/CIDR'",
path.display(),
parts[0]
);
ensure!(
parts.len() - 2 <= MAX_HTACCESS_ACCESS_SELECTORS,
"{}:{line_no}: too many access-control selectors",
path.display()
);
let mut selectors = Vec::with_capacity(parts.len() - 2);
for value in &parts[2..] {
if value.eq_ignore_ascii_case("all") {
selectors.push(AccessSelector::All);
} else {
let network = if let Ok(ip) = value.parse::<IpAddr>() {
IpNet::from(ip)
} else {
value.parse::<IpNet>().with_context(|| format!(
"{}:{line_no}: unsupported {} source {value:?}; only all, IP and CIDR are supported to avoid weakening access control",
path.display(), parts[0]
))?
};
selectors.push(AccessSelector::Network(network));
}
}
Ok(selectors)
}
fn unsupported(
state: &mut ParseState,
config: &Config,
+166 -18
View File
@@ -1,3 +1,115 @@
fn redirect_status(value: &str) -> Option<StatusCode> {
match value.to_ascii_lowercase().as_str() {
"permanent" | "301" => Some(StatusCode::MOVED_PERMANENTLY),
"temp" | "temporary" | "302" => Some(StatusCode::FOUND),
"seeother" | "303" => Some(StatusCode::SEE_OTHER),
"307" => Some(StatusCode::TEMPORARY_REDIRECT),
"308" => Some(StatusCode::PERMANENT_REDIRECT),
_ => None,
}
}
fn redirect_rule(parts: &[String], regex: bool) -> Result<SimpleRedirect> {
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 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")?;
let matcher = if regex {
RedirectMatcher::Regex(Regex::new(source).context("invalid RedirectMatch regex")?)
} else {
ensure!(source.starts_with('/') && !source.starts_with("//")
&& !source.contains('\r') && !source.contains('\n') && !source.contains('?')
&& !source.contains('#') && !source.contains('\\'), "invalid Redirect path prefix");
RedirectMatcher::Prefix(source.to_owned())
};
Ok(SimpleRedirect { matcher, replacement: replacement.to_owned(), status })
}
// Only a safe, deterministic subset of Apache access rules is allowed in
// <Files> and <FilesMatch>. Unknown directives inside a security scope must
// fail closed, including when the general "ignore unsupported" option is off.
fn file_rule_start(line: &str) -> Result<FileAccessRule> {
let inner = line.trim().strip_prefix('<').and_then(|s| s.strip_suffix('>'))
.context("unterminated Files or FilesMatch tag")?;
let (tag, value) = inner.split_once(char::is_whitespace)
.context("Files or FilesMatch requires a filename/pattern")?;
let values = tokens(value)?;
let regex_pattern = if tag.eq_ignore_ascii_case("filesmatch") {
ensure!(values.len() == 1, "FilesMatch needs one quoted regex");
values[0].clone()
} else {
// Apache also accepts <Files ~ "regex"> as an alias of FilesMatch.
if values.len() == 2 && values[0] == "~" {
values[1].clone()
} else {
ensure!(values.len() == 1, "Files needs a single filename/glob");
let mut pattern = String::from("^");
for ch in values[0].chars() {
match ch {
'*' => pattern.push_str(".*"),
'?' => pattern.push('.'),
_ => pattern.push_str(&regex::escape(&ch.to_string())),
}
}
pattern.push('$');
pattern
}
};
ensure!(regex_pattern.len() <= 512, "Files/FilesMatch pattern exceeds 512 bytes");
Ok(FileAccessRule { matcher: Regex::new(&regex_pattern)
.context("invalid Files/FilesMatch regular expression")?,
deny_all: None, legacy_access: None })
}
fn apply_access_directive(
directive: &str, parts: &[String], path: &Path, line_no: usize,
deny_all: &mut Option<bool>, legacy_access: &mut Option<LegacyAccess>,
) -> Result<()> {
match directive {
"require" => {
if parts.len() == 3 && parts[1].eq_ignore_ascii_case("all") && parts[2].eq_ignore_ascii_case("denied") {
*deny_all = Some(true);
} else if parts.len() == 3 && parts[1].eq_ignore_ascii_case("all") && parts[2].eq_ignore_ascii_case("granted") {
*deny_all = Some(false);
} else {
bail!("{}:{line_no}: unsupported Require; refusing to ignore access control", path.display());
}
}
"order" => {
ensure!(parts.len() == 2, "{}:{line_no}: Order expects allow,deny or deny,allow", path.display());
let order = match parts[1].to_ascii_lowercase().as_str() {
"deny,allow" => LegacyOrder::DenyAllow,
"allow,deny" => LegacyOrder::AllowDeny,
"mutual-failure" => LegacyOrder::MutualFailure,
_ => bail!("{}:{line_no}: unsupported Order value {:?}", path.display(), parts[1]),
};
legacy_access.get_or_insert_with(LegacyAccess::default).order = order;
}
"allow" | "deny" => {
let selectors = legacy_access_selectors(parts, path, line_no)?;
let access = legacy_access.get_or_insert_with(LegacyAccess::default);
let dest = if directive == "allow" { &mut access.allow } else { &mut access.deny };
ensure!(dest.len() + selectors.len() <= MAX_HTACCESS_ACCESS_SELECTORS,
"{}:{line_no}: too many access-control selectors", path.display());
dest.extend(selectors);
}
_ => bail!("{}:{line_no}: unsupported access directive", path.display()),
}
Ok(())
}
fn parse_file(path: &Path, components: Vec<String>, config: &Config) -> Result<(Scope, Vec<String>)> {
let content = read_htaccess_nofollow(path)?;
let mut scope = Scope { components, ..Scope::default() };
@@ -11,21 +123,33 @@ fn parse_file(path: &Path, components: Vec<String>, config: &Config) -> Result<(
if line.is_empty() || line.starts_with('#') { continue; }
let lower_line = line.to_ascii_lowercase();
if lower_line.starts_with("<ifmodule") || lower_line == "</ifmodule>" { continue; }
if lower_line.starts_with("<files") || lower_line.starts_with("<filesmatch") {
if lower_line.contains(".htaccess") || lower_line.contains(".htpasswd") || lower_line.contains("^\\.ht") {
state.in_files_block = state.in_files_block.saturating_add(1);
continue;
}
bail!("{}:{line_no}: general Files/FilesMatch semantics are not supported; refusing to ignore an access/handler scope", path.display());
}
if line.eq_ignore_ascii_case("</Files>") || line.eq_ignore_ascii_case("</FilesMatch>") {
state.in_files_block = state.in_files_block.saturating_sub(1);
if lower_line == "</files>" || lower_line == "</filesmatch>" {
let rule = state.file_block.take()
.with_context(|| format!("{}:{line_no}: unmatched Files/FilesMatch closing tag", path.display()))?;
ensure!(rule.deny_all.is_some() || rule.legacy_access.is_some(),
"{}:{line_no}: Files/FilesMatch block has no supported access rule", path.display());
scope.file_rules.push(rule);
continue;
}
if state.in_files_block != 0 {
if lower_line.starts_with("<files ") || lower_line.starts_with("<filesmatch ") {
ensure!(state.file_block.is_none(), "{}:{line_no}: nested Files/FilesMatch blocks are unsupported", path.display());
ensure!(scope.file_rules.len() < MAX_HTACCESS_FILE_RULES,
"{}:{line_no}: too many Files/FilesMatch rules", path.display());
state.file_block = Some(file_rule_start(line)
.with_context(|| format!("{}:{line_no}", path.display()))?);
continue;
}
let parts = tokens(line).with_context(|| format!("{}:{line_no}", path.display()))?;
if let Some(rule) = state.file_block.as_mut() {
let directive = parts.first().map(|s| s.to_ascii_lowercase()).unwrap_or_default();
if !matches!(directive.as_str(), "require" | "order" | "allow" | "deny") {
bail!("{}:{line_no}: unsupported {} inside Files/FilesMatch; refusing unsafe ignore",
path.display(), parts.first().map(String::as_str).unwrap_or("directive"));
}
apply_access_directive(&directive, &parts, path, line_no,
&mut rule.deny_all, &mut rule.legacy_access)?;
continue;
}
if parts.is_empty() { continue; }
let directive = parts[0].to_ascii_lowercase();
match directive.as_str() {
@@ -127,20 +251,25 @@ fn parse_file(path: &Path, components: Vec<String>, config: &Config) -> Result<(
ensure!(parts.len() >= 3, "{}:{line_no}: ExpiresByType needs media type and duration", path.display());
scope.expires_by_type.push((parts[1].to_ascii_lowercase(), parse_duration(&parts[2..].join(" "))?));
}
"require" => {
if parts.len() == 3 && parts[1].eq_ignore_ascii_case("all") && parts[2].eq_ignore_ascii_case("denied") { scope.deny_all = Some(true); }
else if parts.len() == 3 && parts[1].eq_ignore_ascii_case("all") && parts[2].eq_ignore_ascii_case("granted") { scope.deny_all = Some(false); }
else { bail!("{}:{line_no}: only 'Require all granted/denied' is supported; refusing to ignore an access-control directive", path.display()); }
"require" | "order" | "allow" | "deny" => {
apply_access_directive(&directive, &parts, path, line_no,
&mut scope.deny_all, &mut scope.legacy_access)?;
}
"sethandler" | "removehandler" | "authtype" | "authname" | "authuserfile" | "authgroupfile" | "order" | "allow" | "deny" => {
"sethandler" | "removehandler" | "authtype" | "authname" | "authuserfile" | "authgroupfile" => {
bail!("{}:{line_no}: security/handler directive {} is not supported and cannot be ignored safely", path.display(), parts[0]);
}
"errordocument" | "setenvif" | "redirect" | "redirectmatch" | "fallbackresource" => {
"redirect" | "redirectmatch" => {
ensure!(scope.redirects.len() < 64, "{}:{line_no}: at most 64 Redirect/RedirectMatch rules per file", path.display());
scope.redirects.push(redirect_rule(&parts, directive == "redirectmatch")
.with_context(|| format!("{}:{line_no}", path.display()))?);
}
"errordocument" | "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]))?,
}
}
ensure!(state.file_block.is_none(), "{}: unclosed Files/FilesMatch block", path.display());
ensure!(state.pending_conditions.is_empty(), "{}: RewriteCond without following RewriteRule", path.display());
Ok((scope, state.unsupported))
}
@@ -215,9 +344,28 @@ fn matching_scopes<'a>(compiled: &'a Compiled, path: &str) -> Vec<&'a Scope> {
compiled.scopes.iter().filter(|scope| scope_matches(scope, &components)).collect()
}
pub fn denied(compiled: Option<&Compiled>, path: &str) -> bool {
pub fn denied(compiled: Option<&Compiled>, path: &str, client_ip: IpAddr) -> bool {
let Some(compiled) = compiled else { return false; };
matching_scopes(compiled, path).into_iter().filter_map(|scope| scope.deny_all).next_back().unwrap_or(false)
let scopes = matching_scopes(compiled, path);
// A matching <Files>/<FilesMatch> denial is additive. A narrower file
// grant must not cancel a directory denial or another matched file rule.
let basename = path_components(path).ok().and_then(|parts| parts.last().cloned());
if let Some(name) = basename {
for scope in &scopes {
for rule in &scope.file_rules {
if rule.matcher.is_match(&name) && rule.denied(client_ip) == Some(true) {
return true;
}
}
}
}
scopes.into_iter().filter_map(|scope| {
if let Some(legacy) = &scope.legacy_access {
Some(scope.deny_all.unwrap_or(false) || legacy.denied(client_ip))
} else {
scope.deny_all
}
}).next_back().unwrap_or(false)
}
pub fn index_files<'a>(compiled: Option<&'a Compiled>, directory_components: &[String], fallback: &'a [String]) -> &'a [String] {
+31
View File
@@ -22,6 +22,37 @@ pub async fn apply_rewrites(
let mut changed = false;
let mut end = false;
'scope: for scope in scopes {
// Apache mod_alias Redirect / RedirectMatch, independently of RewriteEngine.
for rule in &scope.redirects {
let tail = match &rule.matcher {
RedirectMatcher::Prefix(prefix) => {
if path == *prefix { Some("") }
else if prefix.ends_with('/') && path.starts_with(prefix) {
Some(&path[prefix.len()..])
} else { path.strip_prefix(prefix).filter(|tail| tail.starts_with('/')) }
}
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 mut target = String::new();
captures.expand(&rule.replacement, &mut target);
target
}),
};
if let Some(mut target) = target {
ensure!((target.starts_with('/') && !target.starts_with("//"))
|| target.starts_with("http://") || target.starts_with("https://"),
"unsafe .htaccess Redirect expansion");
ensure!(!target.contains('\\') && !target.contains('\r') && !target.contains('\n'),
"unsafe .htaccess Redirect expansion");
if let Some(query) = query.as_deref().filter(|q| !q.is_empty()) {
if !target.contains('?') { target.push('?'); target.push_str(query); }
}
return Ok(RewriteOutcome::Redirect(redirect_response(rule.status, &target)?));
}
}
for rule in &scope.rewrites {
let relative = scope_relative_path(scope, &path);
if !rule.pattern.is_match(&relative) {
+1 -1
View File
@@ -10,7 +10,7 @@ mod security;
mod serve;
pub use config::{
CacheRule, CompiledService, Hardening, Php, PhpFpmProfile, Precompressed, RewriteRule,
CacheRule, CompiledService, FastCgiHandler, Hardening, Php, PhpFpmProfile, Precompressed, RewriteRule,
SendfileMode, Service, SymlinkPolicy,
};
pub use htaccess::Config as HtaccessConfig;
+2
View File
@@ -8,6 +8,8 @@ pub struct RequestContext {
pub server_port: u16,
pub tls: bool,
pub version: Version,
/// Set only after Vhost Basic authentication has succeeded.
pub authenticated_user: Option<String>,
}
pub(super) fn server_protocol(version: http::Version) -> &'static str {
+21 -12
View File
@@ -4,6 +4,7 @@ use super::{
},
filesystem::{list_directory_sync, path_components, FilesystemRoot},
htaccess,
config::FastCgiHandler,
response::{
add_service_headers, builtin_error_response, directory_listing, directory_redirect,
file_response, io_response, status_response,
@@ -22,7 +23,7 @@ use http::{
};
use std::{io, path::PathBuf};
async fn resolve_php_path_info(
async fn resolve_script_path_info(
service: &CompiledService,
components: &[String],
) -> Option<(String, String)> {
@@ -77,7 +78,7 @@ async fn serve_inner(
components
.iter()
.any(|component| htaccess::protected_component(service.htaccess.as_ref(), component))
}) || htaccess::denied(service.htaccess.as_ref(), path)
}) || htaccess::denied(service.htaccess.as_ref(), path, context.client_ip)
{
return builtin_error_response(StatusCode::FORBIDDEN, &method);
}
@@ -125,18 +126,18 @@ async fn serve_inner(
htaccess::protected_component(service.htaccess.as_ref(), component)
})
})
|| htaccess::denied(service.htaccess.as_ref(), &rewritten_path)
|| htaccess::denied(service.htaccess.as_ref(), &rewritten_path, context.client_ip)
{
return builtin_error_response(StatusCode::FORBIDDEN, &method);
}
if let Ok(components) = path_components(&rewritten_path) {
if let Some((script_path, path_info)) = resolve_php_path_info(service, &components).await {
if let Some((script_path, path_info)) = resolve_script_path_info(service, &components).await {
let script_components = path_components(&script_path).unwrap_or_default();
if hardening_denied_path(service, &script_path)
|| script_components.iter().any(|component| {
htaccess::protected_component(service.htaccess.as_ref(), component)
})
|| htaccess::denied(service.htaccess.as_ref(), &script_path)
|| htaccess::denied(service.htaccess.as_ref(), &script_path, context.client_ip)
{
return builtin_error_response(StatusCode::FORBIDDEN, &method);
}
@@ -178,7 +179,7 @@ async fn serve_inner(
|| components
.iter()
.any(|component| htaccess::protected_component(service.htaccess.as_ref(), component))
|| htaccess::denied(service.htaccess.as_ref(), &effective_path)
|| htaccess::denied(service.htaccess.as_ref(), &effective_path, context.client_ip)
{
return builtin_error_response(StatusCode::FORBIDDEN, &method);
}
@@ -192,14 +193,14 @@ async fn serve_inner(
) =>
{
if let Some((script_path, path_info)) =
resolve_php_path_info(service, &components).await
resolve_script_path_info(service, &components).await
{
let script_components = path_components(&script_path).unwrap_or_default();
if hardening_denied_path(service, &script_path)
|| script_components.iter().any(|component| {
htaccess::protected_component(service.htaccess.as_ref(), component)
})
|| htaccess::denied(service.htaccess.as_ref(), &script_path)
|| htaccess::denied(service.htaccess.as_ref(), &script_path, context.client_ip)
{
return builtin_error_response(StatusCode::FORBIDDEN, &method);
}
@@ -242,7 +243,10 @@ async fn serve_inner(
)
.await;
}
if protected_script_without_handler(service, &public_path) {
if protected_script_without_handler(service, &public_path)
|| service.php.as_ref().is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
{
// A CGI-only root must never expose any non-executed file.
return builtin_error_response(StatusCode::FORBIDDEN, &method);
}
if method != Method::GET && method != Method::HEAD {
@@ -276,7 +280,9 @@ async fn serve_inner(
let mut script_path = effective_path.trim_end_matches('/').to_owned();
script_path.push('/');
script_path.push_str(index);
if hardening_denied_path(service, &script_path) {
if hardening_denied_path(service, &script_path)
|| htaccess::denied(service.htaccess.as_ref(), &script_path, context.client_ip)
{
return builtin_error_response(StatusCode::FORBIDDEN, &method);
}
let public_path = PathBuf::from(&script_path);
@@ -295,7 +301,9 @@ async fn serve_inner(
)
.await;
}
if protected_script_without_handler(service, &public_path) {
if protected_script_without_handler(service, &public_path)
|| service.php.as_ref().is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
{
return builtin_error_response(StatusCode::FORBIDDEN, &method);
}
if method != Method::GET && method != Method::HEAD {
@@ -333,7 +341,8 @@ async fn serve_inner(
if method != Method::GET && method != Method::HEAD {
return method_not_allowed_response();
}
if !htaccess::directory_listing(
if service.php.as_ref().is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
|| !htaccess::directory_listing(
service.htaccess.as_ref(),
&components,
service.directory_listing,
+231
View File
@@ -68,6 +68,7 @@ async fn serve_body_request(
server_port: 80,
tls: false,
version: Version::HTTP_11,
authenticated_user: None,
},
)
.await
@@ -1126,6 +1127,62 @@ SetHandler application/x-httpd-php
assert!(error.contains("Files/FilesMatch"));
}
#[tokio::test]
async fn htaccess_legacy_deny_from_all_is_enforced_even_in_non_strict_mode() {
let tmp = TempDir::new().unwrap();
std::fs::create_dir(tmp.path().join("private")).unwrap();
std::fs::write(tmp.path().join("index.html"), b"public").unwrap();
std::fs::write(tmp.path().join("private/secret.txt"), b"secret").unwrap();
std::fs::write(
tmp.path().join("private/.htaccess"),
b"Order allow,deny\nDeny from all\nErrorDocument 403 /denied.html\nOptions +FollowSymLinks\n",
).unwrap();
let mut configured = Service {
id: "htaccess-deny-all".into(),
name: "htaccess deny all".into(),
document_root: tmp.path().to_path_buf(),
htaccess: htaccess::Config { enabled: true, strict: false, ..Default::default() },
..Default::default()
};
configured.validate().unwrap();
let service = configured.compile().unwrap();
assert_eq!(service.htaccess.as_ref().unwrap().warnings.len(), 2);
assert_eq!(serve_request(&service, &request(Method::GET, "/index.html"), "/index.html").await.status(), StatusCode::OK);
assert_eq!(serve_request(&service, &request(Method::GET, "/private/secret.txt"), "/private/secret.txt").await.status(), StatusCode::FORBIDDEN);
}
#[test]
fn htaccess_legacy_order_and_ip_rules_follow_apache_22_precedence() {
let tmp = TempDir::new().unwrap();
let ht = tmp.path().join(".htaccess");
let config = htaccess::Config { enabled: true, strict: true, ..Default::default() };
std::fs::write(&ht, b"Order deny,allow\nDeny from all\nAllow from 192.0.2.0/24\n").unwrap();
let compiled = htaccess::compile(tmp.path(), &config).unwrap().unwrap();
assert!(htaccess::denied(Some(&compiled), "/index.html", "198.51.100.1".parse().unwrap()));
assert!(!htaccess::denied(Some(&compiled), "/index.html", "192.0.2.42".parse().unwrap()));
std::fs::write(&ht, b"Order allow,deny\nAllow from 192.0.2.0/24\nDeny from 192.0.2.42\n").unwrap();
let compiled = htaccess::compile(tmp.path(), &config).unwrap().unwrap();
assert!(!htaccess::denied(Some(&compiled), "/index.html", "192.0.2.41".parse().unwrap()));
assert!(htaccess::denied(Some(&compiled), "/index.html", "192.0.2.42".parse().unwrap()));
assert!(htaccess::denied(Some(&compiled), "/index.html", "198.51.100.1".parse().unwrap()));
std::fs::write(&ht, b"Order allow,deny\nAllow from 2001:db8::/32\nDeny from 2001:db8::bad\n").unwrap();
let compiled = htaccess::compile(tmp.path(), &config).unwrap().unwrap();
assert!(!htaccess::denied(Some(&compiled), "/index.html", "2001:db8::1".parse().unwrap()));
assert!(htaccess::denied(Some(&compiled), "/index.html", "2001:db8::bad".parse().unwrap()));
}
#[test]
fn htaccess_legacy_unsupported_hostnames_fail_closed_with_strict_disabled() {
let tmp = TempDir::new().unwrap();
std::fs::write(tmp.path().join(".htaccess"), b"Deny from protected.example\n").unwrap();
let config = htaccess::Config { enabled: true, strict: false, ..Default::default() };
let error = htaccess::compile(tmp.path(), &config).unwrap_err().to_string();
assert!(error.contains("only all, IP and CIDR are supported"), "{error}");
}
#[test]
fn htaccess_strict_mode_rejects_unsupported_directives() {
let tmp = TempDir::new().unwrap();
@@ -1221,6 +1278,7 @@ fn fastcgi_never_forwards_proxy_header_as_http_proxy() {
server_port: 80,
tls: false,
version: Version::HTTP_11,
authenticated_user: None,
},
)
.unwrap();
@@ -1272,6 +1330,7 @@ fn php_custom_fastcgi_params_and_php_values_are_validated() {
server_port: 443,
tls: true,
version: Version::HTTP_2,
authenticated_user: None,
},
)
.unwrap();
@@ -1327,6 +1386,7 @@ fn fastcgi_path_info_keeps_script_filename_separate() {
server_port: 80,
tls: false,
version: Version::HTTP_11,
authenticated_user: None,
},
)
.unwrap();
@@ -1539,6 +1599,7 @@ fn php_admin_values_are_operator_only_and_serialized() {
server_port: 8589,
tls: false,
version: Version::HTTP_11,
authenticated_user: None,
},
)
.unwrap();
@@ -1596,6 +1657,7 @@ fn fastcgi_always_sets_http_host_for_http2_http3_wordpress_requests() {
server_port: 443,
tls: true,
version,
authenticated_user: None,
},
)
.unwrap();
@@ -1645,6 +1707,7 @@ fn fastcgi_http_host_keeps_explicit_host_and_port() {
server_port: 443,
tls: true,
version: Version::HTTP_11,
authenticated_user: None,
},
)
.unwrap();
@@ -2454,3 +2517,171 @@ fn sendfile_mode_is_backward_compatible_and_rejects_unknown_values() {
SendfileMode::Off
);
}
#[test]
fn fastcgi_handler_is_backward_compatible_and_prevents_php_as_cgi() {
let legacy: Php = serde_json::from_str(r#"{"enabled":false}"#).unwrap();
assert_eq!(legacy.handler, FastCgiHandler::PhpFpm);
assert_eq!(legacy.script_name_prefix, "");
assert_eq!(
serde_json::from_str::<FastCgiHandler>(r#""fcgiwrap""#).unwrap(),
FastCgiHandler::Fcgiwrap
);
assert_eq!(
serde_json::from_str::<FastCgiHandler>(r#""fastcgi""#).unwrap(),
FastCgiHandler::Fastcgi
);
for handler in [FastCgiHandler::Fcgiwrap, FastCgiHandler::Fastcgi] {
let mut unsafe_php = Php {
enabled: true,
handler,
extensions: vec!["php".into()],
..Default::default()
};
assert!(unsafe_php.validate().is_err());
let mut unsafe_ini = Php {
enabled: true,
handler,
extensions: vec!["cgi".into()],
php_values: BTreeMap::from([("memory_limit".into(), "128M".into())]),
..Default::default()
};
assert!(unsafe_ini.validate().is_err());
}
let mut bad_prefix = Php {
enabled: true,
handler: FastCgiHandler::Fcgiwrap,
extensions: vec!["cgi".into()],
script_name_prefix: "/app/../admin".into(),
..Default::default()
};
assert!(bad_prefix.validate().is_err());
}
#[tokio::test]
async fn generic_fcgiwrap_mount_passes_public_script_name_without_exposing_other_files() {
let tmp = TempDir::new().unwrap();
std::fs::write(tmp.path().join("health.cgi"), b"#!/bin/sh\necho ok\n").unwrap();
std::fs::write(tmp.path().join("configuration.txt"), b"private CGI settings").unwrap();
let (address, received) = fastcgi_fixture_record_params().await;
let mut config = Service {
id: "cgi-app".into(),
name: "CGI app".into(),
document_root: tmp.path().to_path_buf(),
php: Php {
enabled: true,
handler: FastCgiHandler::Fcgiwrap,
extensions: vec!["cgi".into()],
endpoint: format!("tcp:{address}"),
path_info: true,
script_name_prefix: "/app/cgi-bin".into(),
..Default::default()
},
..Default::default()
};
config.validate().unwrap();
let service = config.compile().unwrap();
// The Vhost strips /app/cgi-bin before invoking the mounted Web Service.
let uri = "/app/cgi-bin/health.cgi/more?query=1";
let response = serve_request(&service, &request(Method::GET, uri), "/health.cgi/more").await;
assert_eq!(response.status(), StatusCode::OK);
let params = received.await.unwrap();
assert_eq!(params["SCRIPT_FILENAME"].as_str(), tmp.path().join("health.cgi").to_string_lossy().as_ref());
assert_eq!(params["SCRIPT_NAME"], "/app/cgi-bin/health.cgi");
assert_eq!(params["PATH_INFO"], "/more");
assert_eq!(params["REQUEST_URI"], uri);
assert_eq!(params["QUERY_STRING"], "query=1");
let forbidden = serve_request(
&service,
&request(Method::GET, "/app/cgi-bin/configuration.txt"),
"/configuration.txt",
).await;
assert_eq!(forbidden.status(), StatusCode::FORBIDDEN);
}
#[tokio::test]
async fn generic_fastcgi_responder_executes_only_configured_script_extensions() {
let tmp = TempDir::new().unwrap();
std::fs::write(tmp.path().join("handler.fcgi"), b"script").unwrap();
std::fs::write(tmp.path().join("public.txt"), b"public").unwrap();
let (address, received) = fastcgi_fixture_record_params().await;
let mut config = Service {
id: "responder".into(),
name: "FastCGI responder".into(),
document_root: tmp.path().to_path_buf(),
php: Php {
enabled: true,
handler: FastCgiHandler::Fastcgi,
extensions: vec!["fcgi".into()],
endpoint: format!("tcp:{address}"),
..Default::default()
},
..Default::default()
};
config.validate().unwrap();
let service = config.compile().unwrap();
let executed = serve_request(&service, &request(Method::GET, "/handler.fcgi"), "/handler.fcgi").await;
assert_eq!(executed.status(), StatusCode::OK);
assert_eq!(received.await.unwrap()["SCRIPT_NAME"], "/handler.fcgi");
let static_file = serve_request(&service, &request(Method::GET, "/public.txt"), "/public.txt").await;
assert_eq!(static_file.status(), StatusCode::OK);
assert_eq!(static_file.into_body().collect().await.unwrap().to_bytes(), "public");
}
#[tokio::test]
async fn htaccess_filesmatch_enforces_denial_including_directory_index() {
let tmp = TempDir::new().unwrap();
std::fs::write(tmp.path().join("index.html"), b"index").unwrap();
std::fs::write(tmp.path().join("secret.env"), b"secret").unwrap();
std::fs::write(tmp.path().join("public.txt"), b"public").unwrap();
std::fs::write(tmp.path().join(".htaccess"), r#"
<FilesMatch "^secret\.env$">
Require all denied
</FilesMatch>
<Files "index.html">
Deny from all
</Files>
"#).unwrap();
let mut config = Service {
id: "files-rule".into(),
name: "Files rule".into(),
document_root: tmp.path().to_path_buf(),
htaccess: htaccess::Config { enabled: true, ..Default::default() },
..Default::default()
};
config.validate().unwrap();
let service = config.compile().unwrap();
for path in ["/secret.env", "/", "/index.html"] {
let response = serve_request(&service, &request(Method::GET, path), path).await;
assert_eq!(response.status(), StatusCode::FORBIDDEN, "{path}");
}
let good = serve_request(&service, &request(Method::GET, "/public.txt"), "/public.txt").await;
assert_eq!(good.status(), StatusCode::OK);
}
#[tokio::test]
async fn htaccess_redirect_and_redirectmatch_are_applied_without_rewriteengine() {
let tmp = TempDir::new().unwrap();
std::fs::write(tmp.path().join(".htaccess"), r#"
Redirect permanent /old /new
RedirectMatch 302 ^/old-files/(.*)$ /archive/$1
ErrorDocument 404 /error.html
"#).unwrap();
let mut config = Service {
id: "redirects".into(),
name: "Redirects".into(),
document_root: tmp.path().to_path_buf(),
htaccess: htaccess::Config { enabled: true, strict: false, ..Default::default() },
..Default::default()
};
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.
let redirect = serve_request(&service, &request(Method::GET, "/old/docs?a=1"), "/old/docs").await;
assert_eq!(redirect.status(), StatusCode::MOVED_PERMANENTLY);
assert_eq!(redirect.headers()[LOCATION], "/new/docs?a=1");
let regex = serve_request(&service, &request(Method::GET, "/old-files/file.txt"), "/old-files/file.txt").await;
assert_eq!(regex.status(), StatusCode::FOUND);
assert_eq!(regex.headers()[LOCATION], "/archive/file.txt");
}