v0.42.4_fixes

This commit is contained in:
Mateusz Gruszczyński committed 2026-11-27 13:56:59 +01:00
1 parent efc6eda4cd
commit 51631810e1
29 files changed
+1192 -394

No files matched your search

+30 -7
View File
@@ -53,7 +53,10 @@ pub(crate) fn statuses(config: &Config) -> Result<Vec<DnsAclStatus>> {
let diagnostics = DIAGNOSTICS.load();
let cache = CACHE.load();
let now = Instant::now();
Ok(names.into_iter().map(|name| status_for_name(name, &cache, &diagnostics, now)).collect())
Ok(names
.into_iter()
.map(|name| status_for_name(name, &cache, &diagnostics, now))
.collect())
}
fn status_for_name(
@@ -184,7 +187,9 @@ fn validate_addresses(mut ips: Vec<IpAddr>) -> std::result::Result<Addresses, St
return Err("DNS response contains no A/AAAA addresses".into());
}
if ips.len() > MAX_ADDRESSES {
return Err(format!("DNS response exceeds the limit of {MAX_ADDRESSES} unique addresses"));
return Err(format!(
"DNS response exceeds the limit of {MAX_ADDRESSES} unique addresses"
));
}
if ips
.iter()
@@ -206,7 +211,9 @@ async fn resolve(name: String) -> (String, std::result::Result<Addresses, String
)
.await;
let result = match answer {
Err(_) => Err(format!("DNS lookup timed out after {LOOKUP_SECONDS} seconds")),
Err(_) => Err(format!(
"DNS lookup timed out after {LOOKUP_SECONDS} seconds"
)),
Ok(Err(error)) => Err(format!("system DNS resolver returned: {error}")),
Ok(Ok(sockets)) => validate_addresses(sockets.map(|socket| socket.ip()).collect()),
};
@@ -265,19 +272,35 @@ pub(crate) async fn poll_loop(app: Weak<crate::runtime::App>, shutdown: Cancella
let checked_unix_ms = checked_unix_ms();
match result {
Ok(value) => {
if previous.get(&hostname).is_none_or(|old| old.ips != value.ips)
|| previous_diagnostics.get(&hostname).is_some_and(|old| old.error.is_some())
if previous
.get(&hostname)
.is_none_or(|old| old.ips != value.ips)
|| previous_diagnostics
.get(&hostname)
.is_some_and(|old| old.error.is_some())
{
tracing::info!(hostname = %hostname, addresses = ?value.ips,
"ACL DDNS resolved; allow rule matches only these client addresses");
}
addresses.insert(hostname.clone(), value);
diagnostics.insert(hostname, DnsDiagnostic { checked_unix_ms, error: None });
diagnostics.insert(
hostname,
DnsDiagnostic {
checked_unix_ms,
error: None,
},
);
}
Err(error) => {
tracing::warn!(hostname = %hostname, reason = %error,
"ACL DDNS resolution failed; hostname allows no client addresses");
diagnostics.insert(hostname, DnsDiagnostic { checked_unix_ms, error: Some(error) });
diagnostics.insert(
hostname,
DnsDiagnostic {
checked_unix_ms,
error: Some(error),
},
);
}
}
}
+9 -3
View File
@@ -94,8 +94,14 @@ mod tests {
});
let names = configured_hostnames(&config).unwrap();
assert_eq!(names, vec!["my-home.example"]);
let empty = HashMap::new();
let pending = status_for_name(names[0].clone(), &empty, &empty, Instant::now());
let empty_cache: HashMap<String, Addresses> = HashMap::new();
let empty_diagnostics: HashMap<String, DnsDiagnostic> = HashMap::new();
let pending = status_for_name(
names[0].clone(),
&empty_cache,
&empty_diagnostics,
Instant::now(),
);
assert_eq!(pending.state, "pending");
let ip: IpAddr = "192.0.2.10".parse().unwrap();
let entries = HashMap::from([(
@@ -130,7 +136,7 @@ mod tests {
error: Some("NXDOMAIN".into()),
},
)]);
let failed = status_for_name(names[0].clone(), &empty, &failure, Instant::now());
let failed = status_for_name(names[0].clone(), &empty_cache, &failure, Instant::now());
assert_eq!(failed.state, "failed");
assert_eq!(failed.error.as_deref(), Some("NXDOMAIN"));
}
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.0.3",
"info": {
"title": "RustProxy Administration API",
"version": "0.42.3",
"version": "0.42.4",
"description": "Administration API for the active panel origin. Sign in through the panel; the same-origin HttpOnly cookie authenticates all private operations. Mutations also require the exact Origin, X-RustProxy-Request: 1 and a session-bound X-CSRF-Token. Loopback HTTP is the default; Settings can enable HTTPS before using a non-loopback administration bind. This document contains no live configuration or credentials. Object schemas marked extensible are summaries: full configuration validation is authoritative in Rust. The API also permits explicitly scoped GeneralApiBearer tokens on a narrow route allowlist, with RO/RW and source CIDR checks; API-token management and Prometheus-token management are browser-session-only."
},
"servers": [
+62 -22
View File
@@ -316,14 +316,29 @@ for (const [id, direction] of [["dashboard-widget-scroll-prev", -1], ["dashboard
}
function refreshChartStylePalette(active = adminPreferences?.chart_style || "default") {
const target = $("chart-style-palette"); if (!target || !languagePacks.size) return;
const buttons = [...ADMIN_CHART_STYLES].map(style => {
const button = el("button", undefined, "chart-style-choice"); button.type = "button"; button.dataset.chartPreset = style; button.classList.toggle("active", style === active); button.setAttribute("aria-pressed", String(style === active));
const swatches = el("span", undefined, "chart-style-swatches"); for (let i = 1; i <= 4; i++) swatches.append(el("i"));
button.append(swatches, el("span", t(CHART_STYLE_KEYS[style]))); button.addEventListener("click", () => { const select = $("ui-chart-style"); if (!select) return; select.value = style; select.dispatchEvent(new Event("change", { bubbles: true })); }); return button;
});
target.replaceChildren(...buttons);
// Keep the selected swatch button mounted; replacing it on click loses focus.
for (const style of ADMIN_CHART_STYLES) {
let button = [...target.children].find(node => node.dataset.chartPreset === style);
if (!button) {
button = el("button", undefined, "chart-style-choice"); button.type = "button"; button.dataset.chartPreset = style;
const swatches = el("span", undefined, "chart-style-swatches"); for (let i = 1; i <= 4; i++) swatches.append(el("i"));
button.append(swatches, el("span"));
button.addEventListener("click", () => { const select = $("ui-chart-style"); if (!select) return; select.value = style; select.dispatchEvent(new Event("change", { bubbles: true })); });
target.append(button);
}
button.classList.toggle("active", style === active);
button.setAttribute("aria-pressed", String(style === active));
const caption = button.lastElementChild, label = t(CHART_STYLE_KEYS[style]);
if (caption.textContent !== label) caption.textContent = label;
}
}
function refreshAppearanceUi({ palette = true, widgets = true, refresh = true, presets = true, search = true } = {}) {
if (palette) refreshChartStylePalette();
if (widgets) renderDashboardWidgetSettings();
if (refresh) renderRefreshPreferences(adminPreferences?.refresh);
if (presets) window.rustProxyDashboardLayout?.refresh?.();
if (search) window.rustProxySettings?.refreshSearch?.();
}
function refreshAppearanceUi() { refreshChartStylePalette(); renderDashboardWidgetSettings(); renderRefreshPreferences(adminPreferences?.refresh); window.rustProxyDashboardLayout?.refresh?.(); window.rustProxySettings?.refreshSearch?.(); }
function formatDateTime(value) { const date = value instanceof Date ? value : new Date(value); if (Number.isNaN(date.getTime())) return String(date); return formatDateParts(date, true, (adminPreferences?.time_format || "24h") === "12h"); }
function formatTime(value) { const date = value instanceof Date ? value : new Date(value); if (Number.isNaN(date.getTime())) return String(date); return formatDateParts(date, false, (adminPreferences?.time_format || "24h") === "12h"); }
function applyAdminPreferences(value, cache = true) {
@@ -336,10 +351,23 @@ function applyAdminPreferences(value, cache = true) {
const savedHeights = normalizeDashboardWidgetHeights(value.dashboard_widget_heights);
const savedAutoFit = value.dashboard_auto_fit !== false;
const savedPositions = normalizeDashboardWidgetPositions(value.dashboard_widget_positions);
window.rustProxyOverviewRows?.setPositions?.(editing ? editing.positions : savedPositions);
window.rustProxyOverviewRows?.setAutoFit?.(editing ? editing.autoFit !== false : savedAutoFit);
if (editing) applyDashboardLayout(editing.order, editing.hidden, editing.sizes, editing.heights);
else applyDashboardLayout(savedOrder, savedHidden, savedSizes, savedHeights);
// A saved table column (or any unrelated preference) must not re-apply the
// dashboard layout. Moving its cards detaches focused controls and shifts
// the page, even if the selected dashboard layout has not changed.
const layoutChanged = !adminPreferences || JSON.stringify([
adminPreferences.dashboard_widgets, adminPreferences.dashboard_hidden_widgets,
adminPreferences.dashboard_widget_sizes, adminPreferences.dashboard_widget_heights,
adminPreferences.dashboard_auto_fit, adminPreferences.dashboard_widget_positions,
]) !== JSON.stringify([
savedOrder, savedHidden, savedSizes, savedHeights, savedAutoFit, savedPositions,
]);
if (layoutChanged) {
window.rustProxyOverviewRows?.setPositions?.(editing ? editing.positions : savedPositions);
window.rustProxyOverviewRows?.setAutoFit?.(editing ? editing.autoFit !== false : savedAutoFit);
if (editing) applyDashboardLayout(editing.order, editing.hidden, editing.sizes, editing.heights);
else applyDashboardLayout(savedOrder, savedHidden, savedSizes, savedHeights);
}
const languageChanged = !adminPreferences || adminPreferences.language !== normalizeAdminLanguage(value.language);
const normalized = {
...value,
refresh: normalizeRefreshPreferences(value.refresh),
@@ -347,18 +375,30 @@ function applyAdminPreferences(value, cache = true) {
time_format: applyAdminTimeFormat(value.time_format), chart_style: applyAdminChartStyle(value.chart_style), chart_axes: applyAdminChartAxes(value.chart_axes), chart_tooltips: applyAdminChartTooltips(value.chart_tooltips), interface_icons: applyAdminInterfaceIcons(value.interface_icons), logo_animation: applyAdminLogoAnimation(value.logo_animation), stable_dialog_position: applyAdminStableDialogPosition(value.stable_dialog_position), switch_controls: applyAdminSwitchControls(value.switch_controls), button_style: applyAdminButtonStyle(value.button_style), corner_style: applyAdminCornerStyle(value.corner_style, cache), table_density: applyAdminTableDensity(value.table_density),
dashboard_density: applyAdminDashboardDensity(value.dashboard_density), dashboard_widgets: savedOrder, dashboard_hidden_widgets: savedHidden, dashboard_widget_sizes: savedSizes, dashboard_widget_heights: savedHeights, dashboard_widget_positions: savedPositions, dashboard_auto_fit: savedAutoFit,
};
const changed = (...keys) => !adminPreferences || keys.some(key =>
JSON.stringify(adminPreferences[key]) !== JSON.stringify(normalized[key]));
const refreshChanged = changed("refresh");
const paletteChanged = changed("chart_style") || languageChanged;
const widgetSettingsChanged = layoutChanged || languageChanged;
const sidebarChanged = changed("sidebar_collapsed");
const poolOrVhostChanged = changed("backend_table_columns", "backend_table_sort", "backend_table_descending", "backend_table_responsive_charts", "vhost_list_sort", "vhost_list_descending");
const dockerChanged = changed("docker_vhost_sort", "docker_vhost_descending");
const redirectChanged = changed("redirect_list_sort", "redirect_list_descending");
const notfoundChanged = changed("notfound_list_sort", "notfound_list_descending");
const streamChanged = changed("stream_list_sort", "stream_list_descending");
adminPreferences = normalized;
window.rustProxyRefresh?.update(normalized.refresh);
renderRefreshPreferences(normalized.refresh);
window.rustProxyVhosts?.applyPreferences(normalized);
window.rustProxyDocker?.applyPreferences(normalized);
window.rustProxyRedirects?.applyPreferences(normalized);
window.rustProxyNotFound?.applyPreferences(normalized);
window.rustProxyStreams?.applyPreferences(normalized);
if (languagePacks.size) translate();
refreshAppearanceUi();
window.rustProxySidebar?.applyPreference?.(normalized.sidebar_collapsed === true);
window.rustProxyOverviewRows?.reveal?.();
if (refreshChanged) window.rustProxyRefresh?.update(normalized.refresh);
if (poolOrVhostChanged) window.rustProxyVhosts?.applyPreferences(normalized);
if (dockerChanged) window.rustProxyDocker?.applyPreferences(normalized);
if (redirectChanged) window.rustProxyRedirects?.applyPreferences(normalized);
if (notfoundChanged) window.rustProxyNotFound?.applyPreferences(normalized);
if (streamChanged) window.rustProxyStreams?.applyPreferences(normalized);
// Only a real language change requires translating/re-rendering the whole panel.
if (languagePacks.size && languageChanged) translate();
else refreshAppearanceUi({ palette: paletteChanged, widgets: widgetSettingsChanged,
refresh: refreshChanged, presets: layoutChanged, search: false });
if (sidebarChanged) window.rustProxySidebar?.applyPreference?.(normalized.sidebar_collapsed === true);
if (layoutChanged) window.rustProxyOverviewRows?.reveal?.();
return normalized;
}
try { applyAdminTheme(localStorage.getItem("rp-theme") || "dark", false); } catch { applyAdminTheme("dark", false); }
+21
View File
@@ -1769,6 +1769,27 @@ html[data-interface-icons="true"] :is(button, a, summary)>svg.ui-icon {
min-width: 0;
}
#php-fpm-profiles-list .fastcgi-profile-editor>label.fastcgi-profile-identity {
display: flex;
flex-direction: column;
align-items: stretch;
grid-row: auto;
gap: 5px;
}
#php-fpm-profiles-list .fastcgi-profile-identity>span:first-child {
display: block;
min-height: 1em;
color: var(--text);
}
#php-fpm-profiles-list .fastcgi-profile-identity-help {
display: block;
color: var(--muted);
line-height: 1.45;
}
#php-fpm-profiles-list .fastcgi-profile-editor .fastcgi-profile-php-heading {
padding-top: 6px;
border-top: 1px solid var(--line);
+64 -34
View File
@@ -12,9 +12,6 @@
let availableColumns = new Set(defaultColumnIds);
let visibleColumns = new Set(defaultColumnIds);
let sortBy = "time", sortDescending = true, pendingRefresh = false;
// Sources are shown per log (a site with all its rotations); the File picker
// narrows to one rotation. Rotation 0 is the file being written.
let groups = new Map(), statusFilter = "", eventFilter = "";
const SCOPE_ORDER = ["vhost", "redirect", "host404", "unmatched", "access", "error"];
const sourceSelect = () => $("file-log-source");
@@ -75,7 +72,6 @@
options.push(optgroup);
}
select.replaceChildren(...options);
// A file id (older bookmark) selects its group.
const owner = [...groups.values()].find(group => group.id === previous || group.files.some(file => file.id === previous));
select.value = owner ? owner.id : "all";
renderFiles(owner && owner.files.some(file => file.id === previousFile) ? previousFile : owner?.files.some(file => file.id === previous) ? previous : "all");
@@ -175,40 +171,68 @@
function syncHeaders() {
const row = $("file-logs-table-head").querySelector("tr");
const headers = orderedColumns().filter(id => visibleColumns.has(id)).map(id => {
const header = el("th"); header.dataset.fileLogColumn = id;
let header = [...row.children].find(node => node.dataset.fileLogColumn === id);
if (!header) {
header = el("th"); header.dataset.fileLogColumn = id;
const button = el("button", undefined, "file-log-sort-button"); button.type = "button";
const caption = el("span");
const key = specialLabels.get(id); if (key) caption.dataset.i18n = key;
const arrow = el("span", undefined, "file-log-sort-indicator"); arrow.setAttribute("aria-hidden", "true");
button.addEventListener("click", () => {
sortDescending = sortBy === id ? !sortDescending : false;
sortBy = id; selectedIndex = null; offset = 0;
syncHeaders(); void savePreferences(); void refresh(true);
});
button.append(caption, arrow); header.append(button);
}
header.setAttribute("aria-sort", sortBy === id ? (sortDescending ? "descending" : "ascending") : "none");
const button = el("button", undefined, "file-log-sort-button"); button.type = "button";
const caption = el("span", columnLabel(id));
const key = specialLabels.get(id); if (key) caption.dataset.i18n = key;
const arrow = el("span", sortBy === id ? (sortDescending ? "↓" : "↑") : "↕", "file-log-sort-indicator");
arrow.setAttribute("aria-hidden", "true");
const button = header.firstElementChild;
const caption = button.firstElementChild, title = columnLabel(id);
if (caption.textContent !== title) caption.textContent = title;
const arrow = button.lastElementChild, symbol = sortBy === id ? (sortDescending ? "↓" : "↑") : "↕";
if (arrow.textContent !== symbol) arrow.textContent = symbol;
const willDescend = sortBy === id ? !sortDescending : false;
button.title = `${t(willDescend ? "fileLogsSortDescending" : "fileLogsSortAscending")}: ${columnLabel(id)}`;
button.title = `${t(willDescend ? "fileLogsSortDescending" : "fileLogsSortAscending")}: ${title}`;
button.setAttribute("aria-label", button.title);
button.addEventListener("click", () => {
sortDescending = sortBy === id ? !sortDescending : false;
sortBy = id; selectedIndex = null; offset = 0;
syncHeaders(); void savePreferences(); void refresh(true);
});
button.append(caption, arrow); header.append(button);
return header;
});
row.replaceChildren(...headers);
let cursor = row.firstElementChild;
for (const header of headers) {
if (header === cursor) cursor = cursor.nextElementSibling;
else row.insertBefore(header, cursor);
}
while (cursor) { const next = cursor.nextElementSibling; cursor.remove(); cursor = next; }
}
function syncColumnPicker() {
const picker = $("file-log-column-options");
picker.replaceChildren(...orderedColumns().map(id => {
const label = el("label", undefined, "check log-column-option");
const input = document.createElement("input"); input.type = "checkbox"; input.checked = visibleColumns.has(id); input.dataset.column = id;
const text = el("span", columnLabel(id));
const key = specialLabels.get(id); if (key) text.dataset.i18n = key;
input.addEventListener("change", () => {
if (!input.checked && visibleColumns.size === 1) { input.checked = true; toast(t("fileLogsColumnsRequired"), true); return; }
if (input.checked) visibleColumns.add(id); else visibleColumns.delete(id);
syncHeaders(); renderRows(); void savePreferences();
});
label.append(input, text); return label;
}));
const ordered = orderedColumns();
for (const id of ordered) {
let input = [...picker.querySelectorAll("input[data-column]")].find(node => node.dataset.column === id);
if (!input) {
const label = el("label", undefined, "check log-column-option");
input = document.createElement("input"); input.type = "checkbox"; input.dataset.column = id;
const text = el("span");
const key = specialLabels.get(id); if (key) text.dataset.i18n = key;
input.addEventListener("change", () => {
if (!input.checked && visibleColumns.size === 1) { input.checked = true; toast(t("fileLogsColumnsRequired"), true); return; }
if (input.checked) visibleColumns.add(id); else visibleColumns.delete(id);
syncHeaders(); renderRows(); void savePreferences();
});
label.append(input, text); picker.append(label);
}
input.checked = visibleColumns.has(id);
const caption = input.nextElementSibling, text = columnLabel(id);
if (caption.textContent !== text) caption.textContent = text;
}
let cursor = picker.firstElementChild;
for (const id of ordered) {
const label = [...picker.children].find(node => node.querySelector("input")?.dataset.column === id);
if (label === cursor) cursor = cursor.nextElementSibling;
else picker.insertBefore(label, cursor);
}
while (cursor) { const next = cursor.nextElementSibling; cursor.remove(); cursor = next; }
}
function applyPreferences(preferences) {
const selected = Array.isArray(preferences?.file_log_columns)
@@ -277,11 +301,14 @@
}
function renderRows(entries = currentEntries) {
const body = $("file-log-rows"), focusedRow = document.activeElement?.closest?.("tr[data-file-log-entry-index]");
const focusedIndex = focusedRow && body.contains(focusedRow) ? Number(focusedRow.dataset.fileLogEntryIndex) : -1;
const focusedEntry = focusedIndex >= 0 ? currentEntries[focusedIndex] : null;
currentEntries = entries;
const ids = orderedColumns().filter(id => visibleColumns.has(id));
const nodes = [];
entries.forEach((entry, index) => {
const row = el("tr"); row.tabIndex = 0; row.classList.toggle("selected", selectedIndex === index);
const row = el("tr"); row.tabIndex = 0; row.dataset.fileLogEntryIndex = String(index); row.classList.toggle("selected", selectedIndex === index);
const status = Number(entry.status) || 0; if (status >= 100) row.dataset.statusClass = `${Math.floor(status / 100)}xx`;
if (entry.event && entry.event !== "request") row.dataset.event = entry.event;
row.setAttribute("aria-expanded", selectedIndex === index ? "true" : "false");
@@ -298,7 +325,11 @@
row.addEventListener("keydown", event => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); select(); } });
nodes.push(row); if (selectedIndex === index) nodes.push(detailRow(entry));
});
$("file-log-rows").replaceChildren(...nodes);
preserveScrollAnchor(() => body.replaceChildren(...nodes));
if (focusedIndex >= 0 && entries[focusedIndex] === focusedEntry) {
body.querySelector(`tr[data-file-log-entry-index="${focusedIndex}"]`)?.focus({ preventScroll: true });
}
$("file-logs-empty").hidden = entries.length !== 0;
}
function queryString() {
@@ -344,7 +375,7 @@
} catch (error) { toast(error.message, true); }
finally { busy = false; $("file-logs-refresh").disabled = false; if (pendingRefresh) { pendingRefresh = false; void refresh(); } }
}
// Status line: what is shown, the time range and which files were read.
function renderSummary(value) {
const summary = $("file-log-summary"); summary.replaceChildren();
const from = lastTotal ? offset + 1 : 0, to = Math.min(offset + currentLimit(), lastTotal);
@@ -409,7 +440,6 @@
for (const chip of document.querySelectorAll("#file-log-chips .file-log-chip")) {
chip.addEventListener("click", () => { statusFilter = chip.dataset.status || ""; eventFilter = chip.dataset.event || ""; syncChips(); void refresh(true); });
}
// Search syntax help opens inline under the search field (works on phones too).
const syntaxToggle = $("file-log-syntax-toggle"), syntax = $("file-log-syntax");
syntaxToggle.addEventListener("click", () => { syntax.hidden = !syntax.hidden; syntaxToggle.setAttribute("aria-expanded", String(!syntax.hidden)); syntaxToggle.classList.toggle("active", !syntax.hidden); });
for (const example of syntax.querySelectorAll(".file-log-syntax-examples button")) {
+17 -11
View File
@@ -201,17 +201,23 @@
}
function syncColumnPicker() {
const picker = $("log-column-options");
picker.replaceChildren(...columns.map(column => {
const label = el("label", undefined, "check log-column-option");
const input = document.createElement("input"); input.type = "checkbox"; input.checked = visibleColumns.has(column.id); input.dataset.column = column.id;
const text = el("span", t(column.label)); text.dataset.i18n = column.label;
input.addEventListener("change", () => {
if (!input.checked && visibleColumns.size === 1) { input.checked = true; toast(t("logColumnsRequired"), true); return; }
if (input.checked) visibleColumns.add(column.id); else visibleColumns.delete(column.id);
syncHeaders(); render(); void savePreferences();
});
label.append(input, text); return label;
}));
for (const column of columns) {
let input = [...picker.querySelectorAll("input[data-column]")].find(node => node.dataset.column === column.id);
if (!input) {
const label = el("label", undefined, "check log-column-option");
input = document.createElement("input"); input.type = "checkbox"; input.dataset.column = column.id;
const caption = el("span"); caption.dataset.i18n = column.label;
input.addEventListener("change", () => {
if (!input.checked && visibleColumns.size === 1) { input.checked = true; toast(t("logColumnsRequired"), true); return; }
if (input.checked) visibleColumns.add(column.id); else visibleColumns.delete(column.id);
syncHeaders(); render(); void savePreferences();
});
label.append(input, caption); picker.append(label);
}
input.checked = visibleColumns.has(column.id);
const caption = input.nextElementSibling, label = t(column.label);
if (caption.textContent !== label) caption.textContent = label;
}
}
function applyPreferences(preferences) {
if (!preferences) return;
+114 -21
View File
@@ -115,8 +115,10 @@ function refreshVhostBackendPopup(status = latestStatus) {
}
if (!list.children.length) list.append(el("li", t("vhBackendPopupEmpty"), "fine"));
const foot = el("p", t("vhBackendPopupHint"), "fine vhost-backend-popup-hint");
const closeFocused = current.node.querySelector(".vhost-backend-popup-close") === document.activeElement;
current.node.replaceChildren(headingRow, list, foot);
current.node.setAttribute("aria-labelledby", heading.id);
if (closeFocused) headingRow.querySelector(".vhost-backend-popup-close")?.focus({ preventScroll: true });
positionVhostBackendPopup();
}
function toggleVhostBackendPopup(id, trigger, backendId = null) {
@@ -176,12 +178,17 @@ function syncVhostSortDirection() {
control.setAttribute("aria-label", t(vhostListPrefs.descending ? "backendSortDescending" : "backendSortAscending"));
}
function applyPreferences(preferences) {
// A queued local change must survive the response to an earlier save.
if (!poolPreferenceSaveQueued) poolTablePrefs = normalizePoolTablePrefs(preferences);
vhostListPrefs = normalizeVhostListPrefs(preferences);
// Updating backend columns should never reconstruct the unrelated Vhost list.
// Keep any newer local column change while an earlier write is in flight.
const nextPool = poolPreferenceSaveQueued ? poolTablePrefs : normalizePoolTablePrefs(preferences);
const nextVhost = normalizeVhostListPrefs(preferences);
const poolChanged = JSON.stringify(nextPool) !== JSON.stringify(poolTablePrefs);
const vhostChanged = JSON.stringify(nextVhost) !== JSON.stringify(vhostListPrefs);
poolTablePrefs = nextPool; vhostListPrefs = nextVhost;
const poolSort = $("pool-sort"); if (poolSort) poolSort.value = poolTablePrefs.sort;
const vhostSort = $("vhost-sort"); if (vhostSort) vhostSort.value = vhostListPrefs.sort;
syncPoolColumns(); syncPoolSortDirection(); syncVhostSortDirection(); applyPoolTableView(); render();
if (poolChanged) { syncPoolColumns(); syncPoolSortDirection(); preserveScrollAnchor(applyPoolTableView); }
if (vhostChanged) { syncVhostSortDirection(); preserveScrollAnchor(render); }
}
async function saveVhostListPrefs() {
if (!authenticated) return;
@@ -242,7 +249,13 @@ function applyPoolTableView() {
const result = typeof a === "number" && typeof b === "number" ? a - b : compareText(a, b);
return poolTablePrefs.descending ? -result : result;
});
body.replaceChildren(...rows);
// Retain rows that are already ordered correctly. A needless detach of a
// focused/anchored table row can jump the page even when sorting is unchanged.
let cursor = body.firstElementChild;
for (const row of rows) {
if (row === cursor) cursor = cursor.nextElementSibling;
else body.insertBefore(row, cursor);
}
let visible = 0;
for (const row of rows) { const match = !query || (row.poolSearchValue || "").includes(query); row.hidden = !match; if (match) visible++; }
syncPoolColumns(); syncPoolSortDirection();
@@ -268,7 +281,9 @@ function initPoolTableTools() {
const visible = new Set(poolTablePrefs.columns);
if (input.checked) visible.add(input.dataset.poolColumnToggle); else visible.delete(input.dataset.poolColumnToggle);
if (!visible.size) { input.checked = true; toast(t("backendColumnsRequired"), true); return; }
poolTablePrefs.columns = poolColumns.filter(key => visible.has(key)); void savePoolTablePrefs(); syncPoolColumns(); applyBackendOverviewView();
poolTablePrefs.columns = poolColumns.filter(key => visible.has(key));
preserveScrollAnchor(() => { syncPoolColumns(); applyBackendOverviewView(); });
void savePoolTablePrefs();
}));
syncPoolColumns(); syncPoolSortDirection();
}
@@ -469,6 +484,63 @@ const BO_EXTRA_CELLS = {
if (extra.h1 + extra.h2) cell.append(el("small", `H2 ${boPercent(extra.h2, extra.h1 + extra.h2)}`));
},
};
// Keep filter buttons and keyed table rows mounted between live samples.
// Replacing them every few seconds discards keyboard focus and browser scroll anchors.
const BO_FILTERS = [["all", "backendFilterAll"], ["up", "vhUp"], ["down", "vhDown"], ["other", "backendFilterOther"]];
function syncBackendOverviewFilters(filters, counts) {
if (filters.getAttribute("aria-label") !== t("backendFilterLabel")) filters.setAttribute("aria-label", t("backendFilterLabel"));
for (const [key, label] of BO_FILTERS) {
let chip = [...filters.children].find(button => button.dataset.boFilter === key);
if (!chip) {
chip = el("button", undefined, `bo-chip is-${key}`);
chip.type = "button"; chip.dataset.uiIconName = "none"; chip.dataset.boFilter = key;
chip.append(el("span"), el("b"));
chip.addEventListener("click", () => { boFilter = key; applyBackendOverviewView(); });
filters.append(chip);
}
const pressed = String(boFilter === key);
if (chip.getAttribute("aria-pressed") !== pressed) chip.setAttribute("aria-pressed", pressed);
const title = chip.querySelector("span"), count = chip.querySelector("b");
if (title.textContent !== t(label)) title.textContent = t(label);
if (count.textContent !== String(counts[key])) count.textContent = String(counts[key]);
count.classList.toggle("is-zero", !counts[key]);
}
}
function syncBackendOverviewRows(body, rendered) {
const rowKey = row => row.dataset.boRowKey !== undefined ? `row:${row.dataset.boRowKey}` : `detail:${row.dataset.boDetailKey}`;
const existing = new Map([...body.children].map(row => [rowKey(row), row]));
const rows = rendered.map(next => {
const key = rowKey(next);
const current = existing.get(key);
if (!current || current.children.length !== next.children.length || current.dataset.boColumns !== next.dataset.boColumns) return next;
if (current.className !== next.className) current.className = next.className;
for (let index = 0; index < current.cells.length; index++) {
const cell = current.cells[index], updated = next.cells[index];
if (cell.className !== updated.className) cell.className = updated.className;
if (cell.title !== updated.title) cell.title = updated.title;
if (cell.colSpan !== updated.colSpan) cell.colSpan = updated.colSpan;
if (updated.dataset.boColumn && cell.dataset.boColumn !== updated.dataset.boColumn) cell.dataset.boColumn = updated.dataset.boColumn;
if (updated.dataset.boColumn === "toggle") {
// The expansion control itself must survive refreshes, not just regain focus.
const button = cell.querySelector("button"), nextButton = updated.querySelector("button");
if (button && nextButton) {
if (button.getAttribute("aria-expanded") !== nextButton.getAttribute("aria-expanded")) button.setAttribute("aria-expanded", nextButton.getAttribute("aria-expanded"));
} else cell.replaceChildren(...updated.childNodes);
} else if (cell.innerHTML !== updated.innerHTML) {
cell.replaceChildren(...updated.childNodes);
}
}
return current;
});
// Do not detach rows already in the correct position: moving a focused row
// needlessly also breaks the scroll anchor on some browsers.
let cursor = body.firstElementChild;
for (const row of rows) {
if (row === cursor) cursor = cursor.nextElementSibling;
else body.insertBefore(row, cursor);
}
while (cursor) { const next = cursor.nextElementSibling; cursor.remove(); cursor = next; }
}
function applyBackendOverviewView() {
if (overviewViewsHidden()) { overviewViewsPending = true; return; }
const body = $("bo-rows"); if (!body) return;
@@ -479,14 +551,7 @@ function applyBackendOverviewView() {
for (const item of boItems) counts[item.group]++;
const summary = $("bo-summary"); if (summary) summary.textContent = boItems.length ? t("backendSummary").replace("{up}", counts.up).replace("{total}", boItems.length) : "";
const filters = $("bo-filters");
if (filters) {
filters.setAttribute("aria-label", t("backendFilterLabel"));
filters.replaceChildren(...[["all", "backendFilterAll"], ["up", "vhUp"], ["down", "vhDown"], ["other", "backendFilterOther"]].map(([key, label]) => {
const chip = el("button", undefined, `bo-chip is-${key}`), count = el("b", String(counts[key]), counts[key] ? "" : "is-zero");
chip.type = "button"; chip.dataset.uiIconName = "none"; chip.setAttribute("aria-pressed", String(boFilter === key));
chip.append(el("span", t(label)), count); chip.addEventListener("click", () => { boFilter = key; applyBackendOverviewView(); }); return chip;
}));
}
if (filters) syncBackendOverviewFilters(filters, counts);
const key = poolTablePrefs.sort;
const list = boItems.filter(item => (boFilter === "all" || item.group === boFilter) && (!query || item.search.includes(query)));
list.sort((left, right) => {
@@ -503,10 +568,15 @@ function applyBackendOverviewView() {
visibleColumns.has("p95") && ["p95", t("backendColP95"), true], visibleColumns.has("probe") && ["probe", t("backendColProbe"), true], visibleColumns.has("cache") && ["cache", t("backendColCache")], visibleColumns.has("traffic") && ["traffic", t("vhTraffic"), true],
visibleColumns.has("causes") && ["causes", t("backendColCauses")], visibleColumns.has("protocol") && ["protocol", t("backendColProtocol")], showEvent && ["event", t("backendLastEvent")],
].filter(Boolean);
const head = $("bo-head"); if (head) head.replaceChildren(...columns.map(([id, label, numeric]) => { const th = el("th", label, numeric ? "is-num" : ""); th.dataset.boColumn = id; if (id === "toggle") th.setAttribute("aria-label", t("backendDetailsToggle")); return th; }));
const head = $("bo-head");
if (head && (head.children.length !== columns.length || columns.some(([id, label], index) => head.children[index].dataset.boColumn !== id || head.children[index].textContent !== label))) {
head.replaceChildren(...columns.map(([id, label, numeric]) => { const th = el("th", label, numeric ? "is-num" : ""); th.dataset.boColumn = id; if (id === "toggle") th.setAttribute("aria-label", t("backendDetailsToggle")); return th; }));
}
const columnSignature = columns.map(([id]) => id).join("|");
const rows = [];
for (const item of list) {
const row = el("tr", undefined, `bo-row is-${item.tone}${item.disabled ? " is-disabled" : ""}`), open = expandable && boOpen.has(item.key);
row.dataset.boRowKey = item.key; row.dataset.boColumns = columnSignature;
for (const [id] of columns) {
const cell = el("td"); cell.dataset.boColumn = id;
if (id === "toggle") {
@@ -550,17 +620,18 @@ function applyBackendOverviewView() {
rows.push(row);
if (open) {
const detail = el("tr", undefined, "bo-detail-row"), cell = el("td"), grid = el("div", undefined, "bo-detail-grid"); cell.colSpan = Math.max(1, columns.length);
detail.dataset.boDetailKey = item.key; detail.dataset.boColumns = columnSignature;
const values = { generation: item.generation, generationRequests: item.generationRequests, generationAge: item.generationAgeText, rotations: item.rotations, lastFailure: item.lastFailureText, lastRecovery: item.lastRecoveryText };
for (const column of detailColumns) { const entry = el("div", undefined, "bo-detail-item"), value = el("b", String(values[column] ?? "-")); if (column === "lastFailure" && item.lastFailureMs) { value.className = "is-failed"; value.title = item.lastFailureDetail || ""; } else if (column === "lastRecovery" && item.lastRecoveryMs) value.className = "is-recovered"; entry.append(el("span", t(BO_SORT_LABELS[column])), value); grid.append(entry); }
cell.append(grid); detail.append(cell); rows.push(detail);
}
}
const scroller = body.closest(".table-scroll"), scrollTop = scroller?.scrollTop ?? 0, scrollLeft = scroller?.scrollLeft ?? 0;
body.replaceChildren(...rows);
// Writing scroll offsets forces a synchronous layout; only restore a
// position the user actually scrolled to.
if (scroller && (scrollTop || scrollLeft)) { scroller.scrollTop = scrollTop; scroller.scrollLeft = scrollLeft; }
if (hadFocus) [...body.querySelectorAll(".bo-expand")].find(button => button.dataset.boKey === focusKey)?.focus({ preventScroll: true });
syncBackendOverviewRows(body, rows);
// Sorting or filtering can change the table height; preserve the user's
// scroll position, but avoid forced layout for an untouched scroll offset.
if (scroller && (scrollTop || scrollLeft)) { if (scroller.scrollTop !== scrollTop) scroller.scrollTop = scrollTop; if (scroller.scrollLeft !== scrollLeft) scroller.scrollLeft = scrollLeft; }
if (hadFocus && document.activeElement?.dataset?.boKey !== focusKey) [...body.querySelectorAll(".bo-expand")].find(button => button.dataset.boKey === focusKey)?.focus({ preventScroll: true });
const empty = $("bo-empty");
if (empty) { empty.textContent = boItems.length ? t("backendSearchEmpty") : t("vhHealthEmpty"); empty.hidden = list.length > 0 || !boHasProxy; }
const toggleAll = document.querySelectorAll("#bo-column-options [data-pool-column-toggle]"); toggleAll.forEach(input => { input.checked = visibleColumns.has(input.dataset.poolColumnToggle); });
@@ -807,6 +878,7 @@ function renderStatus(status) {
const row = el("tr"); if (vhostDisabled) row.classList.add("pool-vhost-disabled"); const poolDomain = status.backend_pool_domains?.[pool.id]; const poolLabel = poolDomain ? `${pool.id} (${poolDomain})` : pool.id; const cells = [poolLabel, `${member.id}${member.backup ? " / " + t("vhBackup") : ""}`, label, activeLimit, member.requests, member.errors,
member.ewma_latency_ms > 0 ? `${member.ewma_latency_ms.toFixed(1)} ms` : "-", `${rateBytes(memberTraffic)}/s`, extra.text.rate, extra.text.statuses, extra.text.p95, extra.text.cache, extra.text.probe, extra.text.causes, extra.text.protocol, member.upstream_client_generation ?? "-", member.upstream_client_generation_requests ?? "-", generationAgeText, member.upstream_client_rotations_total ?? "-", lastFailure, lastRecovery];
const sortValues = { vhost: poolLabel.toLowerCase(), backend: String(member.id || "").toLowerCase(), status: label.toLowerCase(), active: Number(member.active) || 0, requests: Number(member.requests) || 0, errors: Number(member.errors) || 0, latency: Number(member.ewma_latency_ms) || 0, traffic: memberTraffic, ...extra.sort, generation: Number(member.upstream_client_generation) || 0, generationRequests: Number(member.upstream_client_generation_requests) || 0, generationAge: Number.isFinite(generationAge) ? generationAge : -1, rotations: Number(member.upstream_client_rotations_total) || 0, lastFailure: Number(member.last_failure_at_ms) || 0, lastRecovery: Number(member.last_recovered_ms) || 0 };
row.dataset.poolKey = JSON.stringify([pool.id, member.id]);
row.poolSort = sortValues; row.poolSearchValue = [poolLabel, member.id, label, member.status, member.last_failure_class, member.last_failure_detail].filter(Boolean).join(" ").toLowerCase();
if (buildPoolRows) cells.forEach((value, index) => { const cell = el("td", String(value ?? "-")); const column = poolColumns[index]; cell.dataset.poolColumn = column; cell.title = column === "status" ? (vhostDisabled ? t("vhDisabled") : `${label} · ${healthDetail}`) : column === "lastFailure" ? (member.last_failure_detail || lastFailure) : String(value ?? "-"); if (column === "status" && !vhostDisabled) cell.className = member.status === "down" ? "status-error" : member.status === "up" ? "status-good" : ""; if (column === "lastFailure" && member.last_failure_at_ms) cell.classList.add("backend-last-failure"); row.append(cell); }); if (buildPoolRows) rows.push(row);
const tone = vhostDisabled ? "muted" : member.health_mode === "off" && member.status === "up" ? "muted" : member.status === "up" ? "up" : member.status === "down" ? "down" : member.status === "checking" || member.status === "draining" ? "warn" : "muted";
@@ -860,7 +932,28 @@ function renderStatus(status) {
const hasConfiguredProxySource = [...configuredVhosts.values()].some(vhost =>
vhostRequiresProxy(vhost)
);
if (buildPoolRows) $("pool-rows").replaceChildren(...rows); else overviewViewsPending = true;
if (buildPoolRows) {
const body = $("pool-rows"), existing = new Map([...body.rows].map(row => [row.dataset.poolKey, row]));
const refreshed = rows.map(next => {
const current = existing.get(next.dataset.poolKey);
if (!current || current.cells.length !== next.cells.length) return next;
current.className = next.className;
current.poolSort = next.poolSort; current.poolSearchValue = next.poolSearchValue;
for (let index = 0; index < current.cells.length; index++) {
const cell = current.cells[index], changed = next.cells[index];
if (cell.textContent !== changed.textContent) cell.textContent = changed.textContent;
if (cell.title !== changed.title) cell.title = changed.title;
if (cell.className !== changed.className) cell.className = changed.className;
}
return current;
});
let cursor = body.firstElementChild;
for (const row of refreshed) {
if (row === cursor) cursor = cursor.nextElementSibling;
else body.insertBefore(row, cursor);
}
while (cursor) { const next = cursor.nextElementSibling; cursor.remove(); cursor = next; }
} else overviewViewsPending = true;
renderBackendOverview(overviewItems, hasConfiguredProxySource, status, false);
const backendDiagnosticsCard = $("backend-diagnostics-card");
backendDiagnosticsCard?.classList.toggle("is-no-proxy", !hasConfiguredProxySource);
+8 -2
View File
@@ -49,13 +49,19 @@ window.rustProxyPhpProfiles = ({ defaults, mapLines, lines, parseFastCgiParams,
summary.append(title, kindBadge);
const editor = document.createElement("form"); editor.className = "vh-grid fastcgi-profile-editor"; editor.noValidate = true;
const namedInput = (key, value, readonly = false) => {
const wrapper = el("label");
const wrapper = el("label", undefined, "fastcgi-profile-identity");
wrapper.append(el("span", t(key)));
const input = document.createElement("input"); input.value = value || ""; input.maxLength = key === "phpProfileId" ? 64 : 96;
input.required = true; input.readOnly = readonly; wrapper.append(input); editor.append(wrapper); return input;
};
const idInput = namedInput("phpProfileId", profile.id, !creating);
const nameInput = namedInput("phpProfileName", profile.name);
const idInput = namedInput("phpProfileId", profile.id, !creating);
window.rustProxyAutoId.attach(idInput, {
elements: [nameInput],
taken: () => (envelope?.config.php_fpm_profiles || []).map(item => item.id)
});
idInput.closest("label").append(el("small", t("phpProfileIdHelp"), "fine fastcgi-profile-identity-help"));
nameInput.closest("label").append(el("small", t("phpProfileNameHelp"), "fine fastcgi-profile-identity-help"));
const controls = {};
const phpOnlyWrappers = [];
let phpOnlySection;
+1 -1
View File
@@ -17,7 +17,7 @@ use tokio::sync::Semaphore;
use zeroize::Zeroizing;
const MAX_WAITING_VERIFICATIONS: usize = 64;
const WORKER_WAIT_TIMEOUT: Duration = Duration::from_secs(3);
const WORKER_WAIT_TIMEOUT: Duration = Duration::from_secs(15);
fn realm() -> String {
"Restricted".into()
+1 -1
View File
@@ -117,7 +117,7 @@ mod tests {
let response = auth.authorize(
&mut headers, true, "127.0.0.1".parse().unwrap(),
Arc::new(Semaphore::new(2)), &Limits::default()
).await.err().expect("queue exhaustion must deny access");
).await.expect_err("queue exhaustion must deny access");
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(response.headers().get("retry-after").unwrap(), "1");
assert!(!headers.contains_key("authorization"));
+43 -44
View File
@@ -13,11 +13,37 @@ use sqlx::{
};
use std::{path::Path, time::Duration};
pub const SCHEMA_VERSION: i64 = 12;
pub const SCHEMA_VERSION: i64 = MIGRATIONS[MIGRATIONS.len() - 1].0;
pub const ADMIN_PREFERENCES_MAX_BYTES: usize = 64 * 1024;
pub const CERTIFICATE_API_CREDENTIAL_CAPACITY: i64 = 32;
pub const AUDIT_CAPACITY: i64 = 10_000;
const MIGRATIONS: &[(i64, &str)] = &[
(2, include_str!("../migrations/0002_admin.sql")),
(
3,
include_str!("../migrations/0003_certificate_renewals.sql"),
),
(4, include_str!("../migrations/0004_admin_preferences.sql")),
(5, include_str!("../migrations/0005_certificate_api.sql")),
(
6,
include_str!("../migrations/0006_certificate_api_credentials.sql"),
),
(7, include_str!("../migrations/0007_secret_store.sql")),
(8, include_str!("../migrations/0008_config_history.sql")),
(
9,
include_str!("../migrations/0009_certificate_api_grants.sql"),
),
(10, include_str!("../migrations/0010_dashboard_presets.sql")),
(11, include_str!("../migrations/0011_tokens.sql")),
(
12,
include_str!("../migrations/0012_admin_preferences_size.sql"),
),
];
#[derive(Clone)]
pub struct Store {
pub(crate) pool: SqlitePool,
@@ -88,54 +114,23 @@ impl Store {
.max_connections(4)
.connect_with(options)
.await?;
let mut tx = pool.begin().await?;
let version: i64 = sqlx::query_scalar("PRAGMA user_version")
.fetch_one(&pool)
.fetch_one(&mut *tx)
.await?;
ensure!(
version <= SCHEMA_VERSION,
"database schema is newer than this binary; refusing downgrade"
);
let mut tx = pool.begin().await?;
sqlx::raw_sql(include_str!("../migrations/0002_admin.sql"))
.execute(&mut *tx)
.await?;
sqlx::raw_sql(include_str!("../migrations/0003_certificate_renewals.sql"))
.execute(&mut *tx)
.await?;
sqlx::raw_sql(include_str!("../migrations/0004_admin_preferences.sql"))
.execute(&mut *tx)
.await?;
sqlx::raw_sql(include_str!("../migrations/0005_certificate_api.sql"))
.execute(&mut *tx)
.await?;
sqlx::raw_sql(include_str!(
"../migrations/0006_certificate_api_credentials.sql"
))
.execute(&mut *tx)
.await?;
sqlx::raw_sql(include_str!("../migrations/0007_secret_store.sql"))
.execute(&mut *tx)
.await?;
sqlx::raw_sql(include_str!("../migrations/0008_config_history.sql"))
.execute(&mut *tx)
.await?;
sqlx::raw_sql(include_str!(
"../migrations/0009_certificate_api_grants.sql"
))
.execute(&mut *tx)
.await?;
sqlx::raw_sql(include_str!("../migrations/0010_dashboard_presets.sql"))
.execute(&mut *tx)
.await?;
sqlx::raw_sql(include_str!("../migrations/0011_tokens.sql"))
.execute(&mut *tx)
.await?;
if version < 12 {
sqlx::raw_sql(include_str!(
"../migrations/0012_admin_preferences_size.sql"
))
.execute(&mut *tx)
.await?;
for &(target, sql) in MIGRATIONS {
if version < target {
sqlx::raw_sql(sql)
.execute(&mut *tx)
.await
.with_context(|| {
format!("SQLite schema migration to version {target} failed")
})?;
}
}
sqlx::query("INSERT OR IGNORE INTO configuration(id, revision, document) VALUES(1, 0, ?)")
.bind(serde_json::to_string(initial)?)
@@ -147,9 +142,13 @@ impl Store {
.bind(crate::auth::now())
.execute(&mut *tx)
.await?;
sqlx::query("PRAGMA user_version = 12")
if version < SCHEMA_VERSION {
sqlx::query(sqlx::AssertSqlSafe(format!(
"PRAGMA user_version = {SCHEMA_VERSION}"
)))
.execute(&mut *tx)
.await?;
}
tx.commit().await?;
Ok(Self { pool })
}
+139
View File
@@ -1,5 +1,15 @@
mod tests {
use super::*;
#[test]
fn migration_registry_is_complete_and_ordered() {
assert_eq!(MIGRATIONS.first().map(|(version, _)| *version), Some(2));
assert_eq!(
MIGRATIONS.last().map(|(version, _)| *version),
Some(SCHEMA_VERSION)
);
assert!(MIGRATIONS.windows(2).all(|pair| pair[1].0 == pair[0].0 + 1));
}
#[tokio::test]
async fn persists_and_rejects_stale_writes() {
let dir = tempfile::tempdir().unwrap();
@@ -208,6 +218,135 @@ mod tests {
assert!(store.load().await.unwrap().config.vhosts.is_empty());
store.close().await;
}
async fn seed_v11_with_preferences(path: &Path) {
let options = SqliteConnectOptions::new()
.filename(path)
.create_if_missing(true)
.foreign_keys(true);
let pool = SqlitePoolOptions::new()
.max_connections(1)
.connect_with(options)
.await
.unwrap();
for &(target, migration) in MIGRATIONS {
if target >= 12 {
break;
}
sqlx::raw_sql(migration).execute(&pool).await.unwrap();
}
sqlx::query(
"INSERT INTO administrator(id, username, password_hash, created_at) VALUES(1, 'owner', 'hash', 1)",
)
.execute(&pool)
.await
.unwrap();
sqlx::query("INSERT INTO admin_preferences(administrator_id, document) VALUES(1, ?)")
.bind(r#"{"language":"pl","theme":"dark"}"#)
.execute(&pool)
.await
.unwrap();
sqlx::query("PRAGMA user_version = 11")
.execute(&pool)
.await
.unwrap();
pool.close().await;
}
#[tokio::test]
async fn v11_upgrade_keeps_admin_preferences_and_is_not_repeated() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("v11.sqlite3");
seed_v11_with_preferences(&path).await;
let store = Store::open(&path, &Config::default()).await.unwrap();
assert_eq!(
store.admin_preferences("owner").await.unwrap().as_deref(),
Some(r#"{"language":"pl","theme":"dark"}"#)
);
let version: i64 = sqlx::query_scalar("PRAGMA user_version")
.fetch_one(&store.pool)
.await
.unwrap();
assert_eq!(version, SCHEMA_VERSION);
let large_document = "x".repeat(8192);
assert!(store
.save_admin_preferences("owner", &large_document)
.await
.unwrap());
assert!(store
.save_admin_preferences("owner", &"x".repeat(65537))
.await
.is_err());
store.close().await;
let reopened = Store::open(&path, &Config::default()).await.unwrap();
assert_eq!(
reopened
.admin_preferences("owner")
.await
.unwrap()
.as_deref(),
Some(large_document.as_str())
);
let fk_check: Vec<(String, i64, String, i64)> = sqlx::query_as("PRAGMA foreign_key_check")
.fetch_all(&reopened.pool)
.await
.unwrap();
assert!(fk_check.is_empty());
sqlx::query("DELETE FROM administrator WHERE id = 1")
.execute(&reopened.pool)
.await
.unwrap();
assert!(reopened.admin_preferences("owner").await.unwrap().is_none());
let rows: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM admin_preferences")
.fetch_one(&reopened.pool)
.await
.unwrap();
assert_eq!(
rows, 0,
"administrator preferences must still cascade on delete"
);
reopened.close().await;
}
#[tokio::test]
async fn failed_v11_migration_rolls_back_entire_upgrade() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("v11-failed.sqlite3");
seed_v11_with_preferences(&path).await;
let options = SqliteConnectOptions::new().filename(&path);
let pool = SqlitePoolOptions::new()
.max_connections(1)
.connect_with(options)
.await
.unwrap();
sqlx::query("CREATE TABLE admin_preferences_v2 (administrator_id INTEGER PRIMARY KEY)")
.execute(&pool)
.await
.unwrap();
pool.close().await;
assert!(Store::open(&path, &Config::default()).await.is_err());
let options = SqliteConnectOptions::new().filename(&path);
let pool = SqlitePoolOptions::new()
.max_connections(1)
.connect_with(options)
.await
.unwrap();
let version: i64 = sqlx::query_scalar("PRAGMA user_version")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(version, 11);
let original: String =
sqlx::query_scalar("SELECT document FROM admin_preferences WHERE administrator_id = 1")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(original, r#"{"language":"pl","theme":"dark"}"#);
pool.close().await;
}
#[tokio::test]
async fn migration_keeps_v1_config_and_revision() {
let dir = tempfile::tempdir().unwrap();
+12 -6
View File
@@ -186,7 +186,9 @@ impl Page {
Kind::Welcome => include_str!("../admin/web/demo.html").to_owned(),
Kind::Builtin => builtin_application_page(status),
Kind::CloudflareWelcome => include_str!("../admin/web/cf_page/welcome.html").to_owned(),
Kind::CloudflarePlaceholder => include_str!("../admin/web/cf_page/placeholder.html").to_owned(),
Kind::CloudflarePlaceholder => {
include_str!("../admin/web/cf_page/placeholder.html").to_owned()
}
Kind::Cloudflare => cloudflare_style_page(status)
.map(str::to_owned)
.unwrap_or_else(|| builtin_application_page(status)),
@@ -316,11 +318,15 @@ pub fn replace_error(response: &mut Response, page: &Page) {
if response
.headers()
.get(::http::header::CACHE_CONTROL)
.is_some_and(|value| value.as_bytes().split(|&byte| byte == b',').any(|part|
part.iter().copied().filter(|byte| !byte.is_ascii_whitespace())
.map(|byte| byte.to_ascii_lowercase())
.eq(b"private".iter().copied())
))
.is_some_and(|value| {
value.as_bytes().split(|&byte| byte == b',').any(|part| {
part.iter()
.copied()
.filter(|byte| !byte.is_ascii_whitespace())
.map(|byte| byte.to_ascii_lowercase())
.eq(b"private".iter().copied())
})
})
{
replacement.headers_mut().insert(
::http::header::CACHE_CONTROL,
+160 -71
View File
@@ -493,20 +493,27 @@ mod authority_tests {
.extensions_mut()
.insert(OriginTiming(Duration::from_millis(7)));
// The header is opt-in, including for Docker-generated vhosts.
apply_backend_diagnostic_values(&mut response, false, false);
assert!(response.headers().get("x-rust-proxy-backend").is_none());
apply_backend_diagnostic_values(&mut response, true, true);
assert_eq!(response.headers()["x-rust-proxy-backend"], "edge-node/012345abcdef");
assert_eq!(
response.headers()["x-rust-proxy-backend"],
"edge-node/012345abcdef"
);
assert_eq!(response.headers()["x-rustproxy-backend-time"], "7.00ms");
assert_eq!(response.extensions().get::<OriginBackend>().unwrap().0, raw_id);
assert_eq!(
response.extensions().get::<OriginBackend>().unwrap().0,
raw_id
);
// For cached responses the same OriginBackend extension is used.
let mut cached = Response::new(Body::empty());
cached.extensions_mut().insert(OriginBackend(raw_id.into()));
apply_backend_diagnostic_values(&mut cached, true, false);
assert_eq!(cached.headers()["x-rust-proxy-backend"], "edge-node/012345abcdef");
assert_eq!(
cached.headers()["x-rust-proxy-backend"],
"edge-node/012345abcdef"
);
assert!(cached.headers().get("x-rustproxy-backend-time").is_none());
}
@@ -812,109 +819,191 @@ mod graceful_h2_tests {
}
}
#[tokio::test]
async fn proxy_generated_error_responses_use_generic_statuses() {
use http_body_util::BodyExt;
let unsupported = error(
StatusCode::NOT_IMPLEMENTED,
"RustProxy: internal CONNECT implementation detail\n",
);
assert_eq!(unsupported.status(), StatusCode::NOT_IMPLEMENTED);
assert_eq!(unsupported.headers()["cache-control"], "no-store");
assert_eq!(
unsupported.into_body().collect().await.unwrap().to_bytes(),
"501 Not Implemented\n"
);
let not_found = error(
StatusCode::NOT_FOUND,
"RustProxy: internal routing detail\n",
);
assert_eq!(not_found.status(), StatusCode::NOT_FOUND);
assert_eq!(
not_found.headers()["content-type"],
"text/html; charset=utf-8"
);
let bytes = not_found.into_body().collect().await.unwrap().to_bytes();
let page = std::str::from_utf8(&bytes).unwrap();
assert!(page.contains("404"));
assert!(!page.contains("RustProxy: internal"));
mod error_page_tests {
use super::*;
fn validation_policy() -> crate::config::ValidationPolicy {
crate::config::ValidationPolicy {
tls_addr: None,
cert_dir: None,
data_dir: None,
proxy_addr: "127.0.0.1:8080".parse().unwrap(),
admin_addr: "127.0.0.1:9090".parse().unwrap(),
}
}
#[tokio::test]
async fn proxy_generated_error_responses_use_generic_statuses() {
use http_body_util::BodyExt;
let unsupported = error(
StatusCode::NOT_IMPLEMENTED,
"RustProxy: internal CONNECT implementation detail\n",
);
assert_eq!(unsupported.status(), StatusCode::NOT_IMPLEMENTED);
assert_eq!(unsupported.headers()["cache-control"], "no-store");
assert_eq!(
unsupported.into_body().collect().await.unwrap().to_bytes(),
"501 Not Implemented\n"
);
let not_found = error(
StatusCode::NOT_FOUND,
"RustProxy: internal routing detail\n",
);
assert_eq!(not_found.status(), StatusCode::NOT_FOUND);
assert_eq!(
not_found.headers()["content-type"],
"text/html; charset=utf-8"
);
let bytes = not_found.into_body().collect().await.unwrap().to_bytes();
let page = std::str::from_utf8(&bytes).unwrap();
assert!(page.contains("404"));
assert!(!page.contains("RustProxy: internal"));
}
#[tokio::test]
async fn generated_web_errors_use_vhost_then_global_but_origin_errors_keep_their_body() {
use http_body_util::BodyExt;
let mut config = crate::config::demo_config("127.0.0.1:9000".parse().unwrap());
config.pages.errors.insert(404, crate::pages::Page {
kind: crate::pages::Kind::Html,
status: None,
html: "global 404".into(),
});
config.pages.errors.insert(
404,
crate::pages::Page {
kind: crate::pages::Kind::Html,
status: None,
html: "global 404".into(),
},
);
let snapshot = crate::config::compile(config.clone(), 1, &validation_policy()).unwrap();
let route = snapshot.select("localhost", "/").unwrap();
let generated = Response::builder().status(404)
.body(Body::from("generated Web Server 404")).unwrap();
let generated = Response::builder()
.status(404)
.body(Body::from("generated Web Server 404"))
.unwrap();
let mut generated = intercept_route_web_error(generated, route, &snapshot);
assert!(should_replace_error_page(&generated, false));
crate::pages::replace_error(&mut generated, &snapshot.envelope.config.pages.errors[&404]);
assert_eq!(generated.into_body().collect().await.unwrap().to_bytes(), "global 404");
assert_eq!(
generated.into_body().collect().await.unwrap().to_bytes(),
"global 404"
);
config.vhosts[0].pages.errors.insert(404, crate::pages::Page {
kind: crate::pages::Kind::Html,
status: None,
html: "vhost 404".into(),
});
config.vhosts[0].pages.errors.insert(
404,
crate::pages::Page {
kind: crate::pages::Kind::Html,
status: None,
html: "vhost 404".into(),
},
);
let snapshot = crate::config::compile(config.clone(), 2, &validation_policy()).unwrap();
let route = snapshot.select("localhost", "/").unwrap();
let generated = Response::builder().status(404)
.body(Body::from("generated Web Server 404")).unwrap();
let generated = Response::builder()
.status(404)
.body(Body::from("generated Web Server 404"))
.unwrap();
let mut generated = intercept_route_web_error(generated, route, &snapshot);
assert!(should_replace_error_page(&generated, false));
crate::pages::replace_error(&mut generated, &route.frontend.as_ref().unwrap().pages.errors[&404]);
assert_eq!(generated.into_body().collect().await.unwrap().to_bytes(), "vhost 404");
crate::pages::replace_error(
&mut generated,
&route.frontend.as_ref().unwrap().pages.errors[&404],
);
assert_eq!(
generated.into_body().collect().await.unwrap().to_bytes(),
"vhost 404"
);
for source in ["PHP/FastCGI", "htaccess ErrorDocument"] {
let mut response = Response::builder().status(404)
.body(Body::from(source)).unwrap();
response.extensions_mut().insert(crate::pages::OriginProvidedResponse);
let mut response = Response::builder()
.status(404)
.body(Body::from(source))
.unwrap();
response
.extensions_mut()
.insert(crate::pages::OriginProvidedResponse);
let response = intercept_route_web_error(response, route, &snapshot);
assert!(!should_replace_error_page(&response, false));
assert_eq!(response.into_body().collect().await.unwrap().to_bytes(), source);
assert_eq!(
response.into_body().collect().await.unwrap().to_bytes(),
source
);
}
config.vhosts[0].pages.intercept_statuses = vec![404];
let snapshot = crate::config::compile(config, 3, &validation_policy()).unwrap();
let route = snapshot.select("localhost", "/").unwrap();
let mut response = Response::builder().status(404)
.body(Body::from("application 404")).unwrap();
response.extensions_mut().insert(crate::pages::OriginProvidedResponse);
let mut response = Response::builder()
.status(404)
.body(Body::from("application 404"))
.unwrap();
response
.extensions_mut()
.insert(crate::pages::OriginProvidedResponse);
let response = intercept_route_web_error(response, route, &snapshot);
assert!(!should_replace_error_page(&response, false));
assert_eq!(response.into_body().collect().await.unwrap().to_bytes(), "vhost 404");
assert_eq!(
response.into_body().collect().await.unwrap().to_bytes(),
"vhost 404"
);
}
#[tokio::test]
async fn basic_auth_denials_keep_challenge_retry_and_private_cache_with_custom_page() {
use http_body_util::BodyExt;
for (status, challenge, retry) in [
(StatusCode::UNAUTHORIZED, Some("Basic realm=\"Restricted\""), None),
(
StatusCode::UNAUTHORIZED,
Some("Basic realm=\"Restricted\""),
None,
),
(StatusCode::TOO_MANY_REQUESTS, None, Some("60")),
(StatusCode::SERVICE_UNAVAILABLE, None, Some("1")),
] {
let mut response = Response::builder().status(status)
let mut response = Response::builder()
.status(status)
.header("cache-control", "private, no-store")
.body(Body::from("basic auth failure")).unwrap();
if let Some(value) = challenge { response.headers_mut().insert("www-authenticate", value.parse().unwrap()); }
if let Some(value) = retry { response.headers_mut().insert("retry-after", value.parse().unwrap()); }
.body(Body::from("basic auth failure"))
.unwrap();
if let Some(value) = challenge {
response
.headers_mut()
.insert("www-authenticate", value.parse().unwrap());
}
if let Some(value) = retry {
response
.headers_mut()
.insert("retry-after", value.parse().unwrap());
}
assert!(should_replace_error_page(&response, false));
crate::pages::replace_error(&mut response, &crate::pages::Page {
kind: crate::pages::Kind::Html,
status: None,
html: "custom auth page".into(),
});
crate::pages::replace_error(
&mut response,
&crate::pages::Page {
kind: crate::pages::Kind::Html,
status: None,
html: "custom auth page".into(),
},
);
assert_eq!(response.status(), status);
assert_eq!(response.headers().get("cache-control").unwrap(), "private, no-store");
assert_eq!(response.headers().get("www-authenticate").map(|v| v.to_str().unwrap()), challenge);
assert_eq!(response.headers().get("retry-after").map(|v| v.to_str().unwrap()), retry);
assert_eq!(response.into_body().collect().await.unwrap().to_bytes(), "custom auth page");
assert_eq!(
response.headers().get("cache-control").unwrap(),
"private, no-store"
);
assert_eq!(
response
.headers()
.get("www-authenticate")
.map(|v| v.to_str().unwrap()),
challenge
);
assert_eq!(
response
.headers()
.get("retry-after")
.map(|v| v.to_str().unwrap()),
retry
);
assert_eq!(
response.into_body().collect().await.unwrap().to_bytes(),
"custom auth page"
);
}
}
}
+1 -1
View File
@@ -81,7 +81,7 @@ async fn serve_file(
server_port: 443,
tls: true,
version: http::Version::HTTP_2,
authenticated_user: None,
authenticated_user: None,
},
)
.await
+2 -2
View File
@@ -423,7 +423,7 @@ pub fn index_files<'a>(compiled: Option<&'a Compiled>, directory_components: &[S
pub fn accept_path_info(compiled: Option<&Compiled>, script_path: &str, fallback: bool) -> bool {
match compiled.and_then(|compiled| matching_scopes(compiled, script_path).into_iter()
.filter_map(|scope| scope.accept_path_info).last()) {
.filter_map(|scope| scope.accept_path_info).next_back()) {
Some(AcceptPathInfoMode::On) => true,
Some(AcceptPathInfoMode::Off) => false,
Some(AcceptPathInfoMode::Default) | None => fallback,
@@ -437,7 +437,7 @@ pub fn has_error_documents(compiled: Option<&Compiled>) -> bool {
pub fn error_document<'a>(compiled: Option<&'a Compiled>, path: &str, status: StatusCode) -> Option<&'a str> {
compiled?.scopes.iter().filter(|scope| {
path_components(path).ok().is_some_and(|parts| scope_matches(scope, &parts))
}).filter_map(|scope| scope.error_documents.get(&status.as_u16()).map(String::as_str)).last()
}).filter_map(|scope| scope.error_documents.get(&status.as_u16()).map(String::as_str)).next_back()
}
pub fn directory_listing(compiled: Option<&Compiled>, directory_components: &[String], fallback: bool) -> bool {
+2 -2
View File
@@ -10,8 +10,8 @@ mod security;
mod serve;
pub use config::{
CacheRule, CompiledService, FastCgiHandler, Hardening, Php, PhpFpmProfile, Precompressed, RewriteRule,
SendfileMode, Service, SymlinkPolicy,
CacheRule, CompiledService, FastCgiHandler, Hardening, Php, PhpFpmProfile, Precompressed,
RewriteRule, SendfileMode, Service, SymlinkPolicy,
};
pub use htaccess::Config as HtaccessConfig;
pub use request::RequestContext;
+72 -27
View File
@@ -1,10 +1,10 @@
use super::{
config::FastCgiHandler,
fastcgi::{
method_not_allowed_response, php_for_path, php_response, protected_script_without_handler,
},
filesystem::{list_directory_sync, path_components, FilesystemRoot},
htaccess,
config::FastCgiHandler,
response::{
add_service_headers, builtin_error_response, directory_listing, directory_redirect,
file_response, io_response, status_response,
@@ -33,8 +33,12 @@ async fn resolve_script_path_info(
let script_path = format!("/{}", components[..=script_end].join("/"));
// Preserve the exact suffix, including its final slash. Apache
// front controllers depend on PATH_INFO retaining that slash.
let Some(path_info) = requested_path.strip_prefix(&script_path)
.filter(|suffix| suffix.starts_with('/')) else { continue; };
let Some(path_info) = requested_path
.strip_prefix(&script_path)
.filter(|suffix| suffix.starts_with('/'))
else {
continue;
};
if !htaccess::accept_path_info(service.htaccess.as_ref(), &script_path, php.path_info) {
continue;
}
@@ -123,7 +127,7 @@ async fn serve_inner(
return status_response(
StatusCode::BAD_REQUEST,
"RustProxy: invalid .htaccess rewrite target\n",
)
);
}
};
if crate::acl::validate_decoded_routing_path(&rewritten_path).is_err()
@@ -135,12 +139,18 @@ async fn serve_inner(
htaccess::protected_component(service.htaccess.as_ref(), component)
})
})
|| htaccess::denied(service.htaccess.as_ref(), &rewritten_path, context.client_ip)
|| htaccess::denied(
service.htaccess.as_ref(),
&rewritten_path,
context.client_ip,
)
{
return builtin_error_response(StatusCode::FORBIDDEN, &method);
}
if let Ok(components) = path_components(&rewritten_path) {
if let Some((script_path, path_info)) = resolve_script_path_info(service, &components, &rewritten_path).await {
if let Some((script_path, path_info)) =
resolve_script_path_info(service, &components, &rewritten_path).await
{
let script_components = path_components(&script_path).unwrap_or_default();
if hardening_denied_path(service, &script_path)
|| script_components.iter().any(|component| {
@@ -188,7 +198,11 @@ async fn serve_inner(
|| components
.iter()
.any(|component| htaccess::protected_component(service.htaccess.as_ref(), component))
|| htaccess::denied(service.htaccess.as_ref(), &effective_path, context.client_ip)
|| htaccess::denied(
service.htaccess.as_ref(),
&effective_path,
context.client_ip,
)
{
return builtin_error_response(StatusCode::FORBIDDEN, &method);
}
@@ -253,7 +267,10 @@ async fn serve_inner(
.await;
}
if protected_script_without_handler(service, &public_path)
|| service.php.as_ref().is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
|| service
.php
.as_ref()
.is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
{
// A CGI-only root must never expose any non-executed file.
return builtin_error_response(StatusCode::FORBIDDEN, &method);
@@ -311,7 +328,10 @@ async fn serve_inner(
.await;
}
if protected_script_without_handler(service, &public_path)
|| service.php.as_ref().is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
|| service
.php
.as_ref()
.is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
{
return builtin_error_response(StatusCode::FORBIDDEN, &method);
}
@@ -350,12 +370,16 @@ async fn serve_inner(
if method != Method::GET && method != Method::HEAD {
return method_not_allowed_response();
}
if service.php.as_ref().is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
if service
.php
.as_ref()
.is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
|| !htaccess::directory_listing(
service.htaccess.as_ref(),
&components,
service.directory_listing,
) {
service.htaccess.as_ref(),
&components,
service.directory_listing,
)
{
return builtin_error_response(StatusCode::FORBIDDEN, &method);
}
let root = FilesystemRoot::for_service(service);
@@ -426,7 +450,7 @@ pub async fn serve(
// documents. Normal requests without that feature avoid header cloning.
let error_request = ((request_method == Method::GET || request_method == Method::HEAD)
&& htaccess::has_error_documents(service.htaccess.as_ref()))
.then(|| (headers.clone(), context.clone()));
.then(|| (headers.clone(), context.clone()));
let mut response = serve_inner(service, method, headers, uri, path, body, context).await;
let original_status = response.status();
let mut used_local_error_document = false;
@@ -434,25 +458,42 @@ pub async fn serve(
// provide their own error body; do not open a second FastCGI request while
// the first one's streamed response could still hold a backend permit.
if (original_status.is_client_error() || original_status.is_server_error())
&& !matches!(response.extensions().get::<crate::web_server::metrics::ResponseKind>(),
Some(crate::web_server::metrics::ResponseKind::Php))
&& !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) {
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); }
http::header::RANGE,
http::header::IF_RANGE,
http::header::IF_MODIFIED_SINCE,
http::header::IF_NONE_MATCH,
http::header::IF_MATCH,
http::header::IF_UNMODIFIED_SINCE,
] {
error_headers.remove(name);
}
let replacement = serve_inner(
service, request_method.clone(), error_headers, target_uri,
target_path, Body::empty(), replacement_context,
).await;
service,
request_method.clone(),
error_headers,
target_uri,
target_path,
Body::empty(),
replacement_context,
)
.await;
if replacement.status() == StatusCode::OK {
response = replacement;
used_local_error_document = true;
@@ -468,7 +509,9 @@ pub async fn serve(
// by Vhost/global pages in the outer HTTP response pipeline.
if used_local_error_document
|| matches!(
response.extensions().get::<crate::web_server::metrics::ResponseKind>(),
response
.extensions()
.get::<crate::web_server::metrics::ResponseKind>(),
Some(crate::web_server::metrics::ResponseKind::Php)
)
{
@@ -484,7 +527,9 @@ pub async fn serve(
if used_local_error_document {
// A local ErrorDocument is still an error response, even if the page's
// normal Cache-Control or Expires rules say that successful pages are public.
response.headers_mut().insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
response
.headers_mut()
.insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
response.headers_mut().remove(http::header::EXPIRES);
}
strip_unnecessary_headers(&mut response, service);
+390 -79
View File
@@ -119,7 +119,10 @@ async fn missing_files_and_disabled_directory_listing_return_normal_errors() {
)
.await;
assert_eq!(missing.status(), StatusCode::NOT_FOUND);
assert!(missing.extensions().get::<crate::pages::OriginProvidedResponse>().is_none());
assert!(missing
.extensions()
.get::<crate::pages::OriginProvidedResponse>()
.is_none());
assert_eq!(missing.headers()[CACHE_CONTROL], "no-store");
assert_eq!(missing.headers()[CONTENT_TYPE], "text/html; charset=utf-8");
assert_eq!(missing.headers()["x-content-type-options"], "nosniff");
@@ -1142,46 +1145,125 @@ async fn htaccess_legacy_deny_from_all_is_enforced_even_in_non_strict_mode() {
id: "htaccess-deny-all".into(),
name: "htaccess deny all".into(),
document_root: tmp.path().to_path_buf(),
htaccess: htaccess::Config { enabled: true, strict: false, ..Default::default() },
htaccess: htaccess::Config {
enabled: true,
strict: false,
..Default::default()
},
..Default::default()
};
configured.validate().unwrap();
let service = configured.compile().unwrap();
assert_eq!(service.htaccess.as_ref().unwrap().warnings.len(), 1);
assert_eq!(serve_request(&service, &request(Method::GET, "/index.html"), "/index.html").await.status(), StatusCode::OK);
assert_eq!(serve_request(&service, &request(Method::GET, "/private/secret.txt"), "/private/secret.txt").await.status(), StatusCode::FORBIDDEN);
assert_eq!(
serve_request(
&service,
&request(Method::GET, "/index.html"),
"/index.html"
)
.await
.status(),
StatusCode::OK
);
assert_eq!(
serve_request(
&service,
&request(Method::GET, "/private/secret.txt"),
"/private/secret.txt"
)
.await
.status(),
StatusCode::FORBIDDEN
);
}
#[test]
fn htaccess_legacy_order_and_ip_rules_follow_apache_22_precedence() {
let tmp = TempDir::new().unwrap();
let ht = tmp.path().join(".htaccess");
let config = htaccess::Config { enabled: true, strict: true, ..Default::default() };
let config = htaccess::Config {
enabled: true,
strict: true,
..Default::default()
};
std::fs::write(&ht, b"Order deny,allow\nDeny from all\nAllow from 192.0.2.0/24\n").unwrap();
std::fs::write(
&ht,
b"Order deny,allow\nDeny from all\nAllow from 192.0.2.0/24\n",
)
.unwrap();
let compiled = htaccess::compile(tmp.path(), &config).unwrap().unwrap();
assert!(htaccess::denied(Some(&compiled), "/index.html", "198.51.100.1".parse().unwrap()));
assert!(!htaccess::denied(Some(&compiled), "/index.html", "192.0.2.42".parse().unwrap()));
assert!(htaccess::denied(
Some(&compiled),
"/index.html",
"198.51.100.1".parse().unwrap()
));
assert!(!htaccess::denied(
Some(&compiled),
"/index.html",
"192.0.2.42".parse().unwrap()
));
std::fs::write(&ht, b"Order allow,deny\nAllow from 192.0.2.0/24\nDeny from 192.0.2.42\n").unwrap();
std::fs::write(
&ht,
b"Order allow,deny\nAllow from 192.0.2.0/24\nDeny from 192.0.2.42\n",
)
.unwrap();
let compiled = htaccess::compile(tmp.path(), &config).unwrap().unwrap();
assert!(!htaccess::denied(Some(&compiled), "/index.html", "192.0.2.41".parse().unwrap()));
assert!(htaccess::denied(Some(&compiled), "/index.html", "192.0.2.42".parse().unwrap()));
assert!(htaccess::denied(Some(&compiled), "/index.html", "198.51.100.1".parse().unwrap()));
assert!(!htaccess::denied(
Some(&compiled),
"/index.html",
"192.0.2.41".parse().unwrap()
));
assert!(htaccess::denied(
Some(&compiled),
"/index.html",
"192.0.2.42".parse().unwrap()
));
assert!(htaccess::denied(
Some(&compiled),
"/index.html",
"198.51.100.1".parse().unwrap()
));
std::fs::write(&ht, b"Order allow,deny\nAllow from 2001:db8::/32\nDeny from 2001:db8::bad\n").unwrap();
std::fs::write(
&ht,
b"Order allow,deny\nAllow from 2001:db8::/32\nDeny from 2001:db8::bad\n",
)
.unwrap();
let compiled = htaccess::compile(tmp.path(), &config).unwrap().unwrap();
assert!(!htaccess::denied(Some(&compiled), "/index.html", "2001:db8::1".parse().unwrap()));
assert!(htaccess::denied(Some(&compiled), "/index.html", "2001:db8::bad".parse().unwrap()));
assert!(!htaccess::denied(
Some(&compiled),
"/index.html",
"2001:db8::1".parse().unwrap()
));
assert!(htaccess::denied(
Some(&compiled),
"/index.html",
"2001:db8::bad".parse().unwrap()
));
}
#[test]
fn htaccess_legacy_unsupported_hostnames_fail_closed_with_strict_disabled() {
let tmp = TempDir::new().unwrap();
std::fs::write(tmp.path().join(".htaccess"), b"Deny from protected.example\n").unwrap();
let config = htaccess::Config { enabled: true, strict: false, ..Default::default() };
let error = htaccess::compile(tmp.path(), &config).unwrap_err().to_string();
assert!(error.contains("only all, IP and CIDR are supported"), "{error}");
std::fs::write(
tmp.path().join(".htaccess"),
b"Deny from protected.example\n",
)
.unwrap();
let config = htaccess::Config {
enabled: true,
strict: false,
..Default::default()
};
let error = htaccess::compile(tmp.path(), &config)
.unwrap_err()
.to_string();
assert!(
error.contains("only all, IP and CIDR are supported"),
"{error}"
);
}
#[test]
@@ -2563,7 +2645,11 @@ fn fastcgi_handler_is_backward_compatible_and_prevents_php_as_cgi() {
async fn generic_fcgiwrap_mount_passes_public_script_name_without_exposing_other_files() {
let tmp = TempDir::new().unwrap();
std::fs::write(tmp.path().join("health.cgi"), b"#!/bin/sh\necho ok\n").unwrap();
std::fs::write(tmp.path().join("configuration.txt"), b"private CGI settings").unwrap();
std::fs::write(
tmp.path().join("configuration.txt"),
b"private CGI settings",
)
.unwrap();
let (address, received) = fastcgi_fixture_record_params().await;
let mut config = Service {
id: "cgi-app".into(),
@@ -2587,7 +2673,10 @@ async fn generic_fcgiwrap_mount_passes_public_script_name_without_exposing_other
let response = serve_request(&service, &request(Method::GET, uri), "/health.cgi/more").await;
assert_eq!(response.status(), StatusCode::OK);
let params = received.await.unwrap();
assert_eq!(params["SCRIPT_FILENAME"].as_str(), tmp.path().join("health.cgi").to_string_lossy().as_ref());
assert_eq!(
params["SCRIPT_FILENAME"].as_str(),
tmp.path().join("health.cgi").to_string_lossy().as_ref()
);
assert_eq!(params["SCRIPT_NAME"], "/app/cgi-bin/health.cgi");
assert_eq!(params["PATH_INFO"], "/more");
assert_eq!(params["REQUEST_URI"], uri);
@@ -2596,7 +2685,8 @@ async fn generic_fcgiwrap_mount_passes_public_script_name_without_exposing_other
&service,
&request(Method::GET, "/app/cgi-bin/configuration.txt"),
"/configuration.txt",
).await;
)
.await;
assert_eq!(forbidden.status(), StatusCode::FORBIDDEN);
}
@@ -2621,12 +2711,25 @@ async fn generic_fastcgi_responder_executes_only_configured_script_extensions()
};
config.validate().unwrap();
let service = config.compile().unwrap();
let executed = serve_request(&service, &request(Method::GET, "/handler.fcgi"), "/handler.fcgi").await;
let executed = serve_request(
&service,
&request(Method::GET, "/handler.fcgi"),
"/handler.fcgi",
)
.await;
assert_eq!(executed.status(), StatusCode::OK);
assert_eq!(received.await.unwrap()["SCRIPT_NAME"], "/handler.fcgi");
let static_file = serve_request(&service, &request(Method::GET, "/public.txt"), "/public.txt").await;
let static_file = serve_request(
&service,
&request(Method::GET, "/public.txt"),
"/public.txt",
)
.await;
assert_eq!(static_file.status(), StatusCode::OK);
assert_eq!(static_file.into_body().collect().await.unwrap().to_bytes(), "public");
assert_eq!(
static_file.into_body().collect().await.unwrap().to_bytes(),
"public"
);
}
#[tokio::test]
@@ -2635,19 +2738,26 @@ async fn htaccess_filesmatch_enforces_denial_including_directory_index() {
std::fs::write(tmp.path().join("index.html"), b"index").unwrap();
std::fs::write(tmp.path().join("secret.env"), b"secret").unwrap();
std::fs::write(tmp.path().join("public.txt"), b"public").unwrap();
std::fs::write(tmp.path().join(".htaccess"), r#"
std::fs::write(
tmp.path().join(".htaccess"),
r#"
<FilesMatch "^secret\.env$">
Require all denied
</FilesMatch>
<Files "index.html">
Deny from all
</Files>
"#).unwrap();
"#,
)
.unwrap();
let mut config = Service {
id: "files-rule".into(),
name: "Files rule".into(),
document_root: tmp.path().to_path_buf(),
htaccess: htaccess::Config { enabled: true, ..Default::default() },
htaccess: htaccess::Config {
enabled: true,
..Default::default()
},
..Default::default()
};
config.validate().unwrap();
@@ -2656,33 +2766,59 @@ Deny from all
let response = serve_request(&service, &request(Method::GET, path), path).await;
assert_eq!(response.status(), StatusCode::FORBIDDEN, "{path}");
}
let good = serve_request(&service, &request(Method::GET, "/public.txt"), "/public.txt").await;
let good = serve_request(
&service,
&request(Method::GET, "/public.txt"),
"/public.txt",
)
.await;
assert_eq!(good.status(), StatusCode::OK);
}
#[tokio::test]
async fn htaccess_redirect_and_redirectmatch_are_applied_without_rewriteengine() {
let tmp = TempDir::new().unwrap();
std::fs::write(tmp.path().join(".htaccess"), r#"
std::fs::write(
tmp.path().join(".htaccess"),
r#"
Redirect permanent /old /new
RedirectMatch 302 ^/old-files/(.*)$ /archive/$1
ErrorDocument 404 /error.html
"#).unwrap();
"#,
)
.unwrap();
let mut config = Service {
id: "redirects".into(),
name: "Redirects".into(),
document_root: tmp.path().to_path_buf(),
htaccess: htaccess::Config { enabled: true, strict: false, ..Default::default() },
htaccess: htaccess::Config {
enabled: true,
strict: false,
..Default::default()
},
..Default::default()
};
config.validate().unwrap();
let service = config.compile().unwrap();
let (_, warnings) = service.htaccess_diagnostics().unwrap();
assert!(warnings.is_empty(), "local ErrorDocument is supported: {warnings:?}");
let redirect = serve_request(&service, &request(Method::GET, "/old/docs?a=1"), "/old/docs").await;
assert!(
warnings.is_empty(),
"local ErrorDocument is supported: {warnings:?}"
);
let redirect = serve_request(
&service,
&request(Method::GET, "/old/docs?a=1"),
"/old/docs",
)
.await;
assert_eq!(redirect.status(), StatusCode::MOVED_PERMANENTLY);
assert_eq!(redirect.headers()[LOCATION], "/new/docs?a=1");
let regex = serve_request(&service, &request(Method::GET, "/old-files/file.txt"), "/old-files/file.txt").await;
let regex = serve_request(
&service,
&request(Method::GET, "/old-files/file.txt"),
"/old-files/file.txt",
)
.await;
assert_eq!(regex.status(), StatusCode::FOUND);
assert_eq!(regex.headers()[LOCATION], "/archive/file.txt");
}
@@ -2690,23 +2826,40 @@ ErrorDocument 404 /error.html
#[tokio::test]
async fn htaccess_status_only_redirects_do_not_require_location_headers() {
let tmp = TempDir::new().unwrap();
std::fs::write(tmp.path().join(".htaccess"), r#"
std::fs::write(
tmp.path().join(".htaccess"),
r#"
RedirectMatch 404 ^/missing/
Redirect gone /removed
Redirect 302 /old /new
"#).unwrap();
"#,
)
.unwrap();
let config = Service {
id: "status-only".into(),
name: "Status only".into(),
document_root: tmp.path().to_path_buf(),
htaccess: htaccess::Config { enabled: true, ..Default::default() },
htaccess: htaccess::Config {
enabled: true,
..Default::default()
},
..Default::default()
};
let service = config.compile().unwrap();
let not_found = serve_request(&service, &request(Method::GET, "/missing/secret"), "/missing/secret").await;
let not_found = serve_request(
&service,
&request(Method::GET, "/missing/secret"),
"/missing/secret",
)
.await;
assert_eq!(not_found.status(), StatusCode::NOT_FOUND);
assert!(!not_found.headers().contains_key(LOCATION));
let gone = serve_request(&service, &request(Method::GET, "/removed/file"), "/removed/file").await;
let gone = serve_request(
&service,
&request(Method::GET, "/removed/file"),
"/removed/file",
)
.await;
assert_eq!(gone.status(), StatusCode::GONE);
assert!(!gone.headers().contains_key(LOCATION));
let redirect = serve_request(&service, &request(Method::GET, "/old"), "/old").await;
@@ -2717,7 +2870,9 @@ Redirect 302 /old /new
#[test]
fn htaccess_popular_php_front_controller_file_compiles_without_strict_compatibility() {
let tmp = TempDir::new().unwrap();
std::fs::write(tmp.path().join(".htaccess"), r#"
std::fs::write(
tmp.path().join(".htaccess"),
r#"
# Typical monitoring/PHP installation, without application-specific rules in RustProxy.
Options FollowSymlinks Multiviews
ErrorDocument 404 /error.php?404
@@ -2734,20 +2889,40 @@ RewriteCond %{REQUEST_URI} !^rrd/
RewriteCond %{REQUEST_URI} !=/server-status
RewriteRule ^(.*)$ index.php/$1/
AcceptPathInfo On
"#).unwrap();
"#,
)
.unwrap();
let config = Service {
id: "monitoring-app".into(),
name: "Monitoring app".into(),
document_root: tmp.path().to_path_buf(),
htaccess: htaccess::Config { enabled: true, strict: false, ..Default::default() },
htaccess: htaccess::Config {
enabled: true,
strict: false,
..Default::default()
},
..Default::default()
};
let service = config.compile().unwrap();
let (_, warnings) = service.htaccess_diagnostics().unwrap();
assert_eq!(warnings.len(), 3, "expected unsupported Options and missing PHP handler: {warnings:?}");
assert_eq!(warnings.iter().filter(|warning| warning.contains("Options")).count(), 2);
assert!(warnings.iter().any(|warning| warning.contains("FastCGI handling for .php is disabled")));
assert!(!warnings.iter().any(|warning| warning.contains("RedirectMatch")));
assert_eq!(
warnings.len(),
3,
"expected unsupported Options and missing PHP handler: {warnings:?}"
);
assert_eq!(
warnings
.iter()
.filter(|warning| warning.contains("Options"))
.count(),
2
);
assert!(warnings
.iter()
.any(|warning| warning.contains("FastCGI handling for .php is disabled")));
assert!(!warnings
.iter()
.any(|warning| warning.contains("RedirectMatch")));
}
#[tokio::test]
@@ -2756,7 +2931,9 @@ async fn htaccess_observium_style_front_controller_executes_php_path_info_withou
std::fs::write(tmp.path().join("index.php"), b"<?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
std::fs::write(
tmp.path().join(".htaccess"),
br#"# Original, representative application .htaccess
Options FollowSymlinks Multiviews
ErrorDocument 404 /error.php?404
RedirectMatch 404 /\.
@@ -2772,31 +2949,66 @@ RewriteCond %{REQUEST_URI} !^rrd/
RewriteCond %{REQUEST_URI} !=/server-status
RewriteRule ^(.*)$ index.php/$1/
AcceptPathInfo On
"#).unwrap();
"#,
)
.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() },
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:?}");
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;
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");
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;
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_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");
@@ -2807,14 +3019,26 @@ AcceptPathInfo On
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();
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() },
htaccess: htaccess::Config {
enabled: true,
strict: true,
..Default::default()
},
php: Php {
enabled: true,
endpoint: format!("tcp:{endpoint}"),
..Default::default()
},
..Default::default()
};
configured.validate().unwrap();
@@ -2835,14 +3059,32 @@ async fn htaccess_accept_path_info_off_overrides_enabled_php_path_info() {
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() },
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!(!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);
}
@@ -2850,12 +3092,20 @@ async fn htaccess_accept_path_info_off_overrides_enabled_php_path_info() {
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();
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() },
htaccess: htaccess::Config {
enabled: true,
strict: true,
..Default::default()
},
..Default::default()
};
configured.validate().unwrap();
@@ -2863,7 +3113,10 @@ async fn htaccess_local_error_document_renders_but_preserves_original_error_stat
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");
assert_eq!(
response.into_body().collect().await.unwrap().to_bytes(),
"custom-not-found"
);
}
#[tokio::test]
@@ -2872,19 +3125,30 @@ async fn htaccess_rewrite_base_maps_relative_target_to_configured_url_prefix() {
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();
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() },
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");
assert_eq!(
response.into_body().collect().await.unwrap().to_bytes(),
"mounted-ok"
);
}
#[test]
@@ -2892,11 +3156,32 @@ 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();
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));
assert!(!htaccess::accept_path_info(
Some(&ht),
"/nested/index.php",
false
));
assert!(htaccess::accept_path_info(
Some(&ht),
"/nested/index.php",
true
));
}
#[test]
@@ -2910,7 +3195,18 @@ fn htaccess_error_document_rejects_external_and_escaping_urls_even_non_strict()
"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:?}");
assert!(
htaccess::compile(
tmp.path(),
&htaccess::Config {
enabled: true,
strict: false,
..Default::default()
}
)
.is_err(),
"accepted {bad:?}"
);
}
}
@@ -2918,14 +3214,26 @@ fn htaccess_error_document_rejects_external_and_escaping_urls_even_non_strict()
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();
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() },
htaccess: htaccess::Config {
enabled: true,
strict: true,
..Default::default()
},
php: Php {
enabled: true,
endpoint: format!("tcp:{endpoint}"),
..Default::default()
},
..Default::default()
};
configured.validate().unwrap();
@@ -2935,7 +3243,10 @@ async fn htaccess_php_error_document_preserves_status_and_passes_its_own_query()
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["SCRIPT_FILENAME"],
tmp.path().join("error.php").to_string_lossy()
);
assert_eq!(params["QUERY_STRING"], "404");
assert_eq!(params["REQUEST_URI"], "/error.php?404");
}