v0.38.2
This commit is contained in:
1 parent
758cfd6274
commit
8bdec5c757
32 files changed
+418
-44
No files matched your search
@@ -27,7 +27,7 @@ async fn logs(
|
||||
|| filter
|
||||
.cache
|
||||
.as_ref()
|
||||
.is_some_and(|v| !matches!(v.as_str(), "HIT" | "MISS" | "BYPASS" | "-"))
|
||||
.is_some_and(|v| !matches!(v.as_str(), "HIT" | "STALE" | "REVALIDATED" | "MISS" | "BYPASS" | "-"))
|
||||
{
|
||||
return Err(ApiError(
|
||||
StatusCode::BAD_REQUEST,
|
||||
|
||||
+27
-2
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.0.3",
|
||||
"info": {
|
||||
"title": "RustProxy Administration API",
|
||||
"version": "0.38.1",
|
||||
"version": "0.38.2",
|
||||
"description": "Administration API for the active panel origin. Sign in through the panel; the same-origin HttpOnly cookie authenticates all private operations. Mutations also require the exact Origin, X-RustProxy-Request: 1 and a session-bound X-CSRF-Token. Loopback HTTP is the default; Settings can enable HTTPS before using a non-loopback administration bind. This document contains no live configuration or credentials. Object schemas marked extensible are summaries: full configuration validation is authoritative in Rust. The API also permits explicitly scoped GeneralApiBearer tokens on a narrow route allowlist, with RO/RW and source CIDR checks; API-token management and Prometheus-token management are browser-session-only."
|
||||
},
|
||||
"servers": [
|
||||
@@ -756,6 +756,12 @@
|
||||
"default": null,
|
||||
"description": "If true, only emit cache diagnostic headers for actual HIT responses, never MISS/BYPASS. null inherits global expose_only_hits. Via is controlled independently."
|
||||
},
|
||||
"expose_detailed_status": {
|
||||
"type": "boolean",
|
||||
"nullable": true,
|
||||
"default": null,
|
||||
"description": "If true, X-Cache reports STALE or REVALIDATED instead of HIT for such responses. null inherits global expose_detailed_status."
|
||||
},
|
||||
"rules": {
|
||||
"type": "array",
|
||||
"maxItems": 128,
|
||||
@@ -852,7 +858,19 @@
|
||||
"timing_headers": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Expose Server-Timing diagnostics for this vhost."
|
||||
"description": "Append Server-Timing diagnostics for this vhost to the origin's own Server-Timing metrics. Responses served from the cache drop the stored origin metrics."
|
||||
},
|
||||
"timing_header_names": {
|
||||
"type": "string",
|
||||
"enum": ["standard", "cdn", "legacy"],
|
||||
"default": "standard",
|
||||
"description": "Metric names in Server-Timing. standard (reverse proxy): proxy;dur, upstream;dur, proxy-cache;desc. cdn (RustProxy is the outermost CDN-like edge): edge;dur, origin;dur, cdn-cache;desc. legacy (before 0.38.2): proxy;dur, origin;dur, cache;desc. The cache value is HIT, MISS, BYPASS, STALE or REVALIDATED."
|
||||
},
|
||||
"timing_allow_origin": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" },
|
||||
"maxItems": 16,
|
||||
"description": "Timing-Allow-Origin sent with Server-Timing: origins such as https://app.example.com that may read the timings from scripts, or a single \"*\". Empty sends no header (same-origin scripts can always read them)."
|
||||
},
|
||||
"backend_header": {
|
||||
"type": "boolean",
|
||||
@@ -2461,6 +2479,11 @@
|
||||
"default": false,
|
||||
"description": "Suppress RustProxy cache diagnostic headers on MISS/BYPASS. Cache HIT diagnostics remain governed by expose_* flags. The independently configured Via header is unaffected."
|
||||
},
|
||||
"expose_detailed_status": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "X-Cache reports STALE (served past freshness: grace, stale-while-revalidate, stale-if-error, collapse timeout) or REVALIDATED (confirmed by the origin with 304) instead of HIT. These still count as HIT for expose_only_hits and the hit ratio."
|
||||
},
|
||||
"http_invalidation_allowed_cidrs": {
|
||||
"type": "array",
|
||||
"description": "Optional IP/CIDR allowlist for HTTP BAN and PURGE on matched public vhosts. Empty disables all HTTP invalidation. Max 32 entries; /0 networks forbidden. Trusted reverse proxies must provide an authenticated forwarding chain.",
|
||||
@@ -11361,6 +11384,8 @@
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"HIT",
|
||||
"STALE",
|
||||
"REVALIDATED",
|
||||
"MISS",
|
||||
"BYPASS",
|
||||
"-"
|
||||
|
||||
@@ -37,7 +37,7 @@ function renderSettings() {
|
||||
$("cache-query").checked = !!c.bypass_query; $("cache-prefixes").value = (c.bypass_prefixes || []).join("\n");
|
||||
$("cache-http-invalidation-cidrs").value = (c.http_invalidation_allowed_cidrs || []).join("\n");
|
||||
$("cache-static-cookie").checked = c.static_ignore_cookies !== false; $("cache-static-extensions").value = (c.static_extensions || []).join("\n");
|
||||
$("cache-status-header").checked = !!c.expose_status; $("cache-hits-header").checked = !!c.expose_hits; $("cache-rfc-header").checked = !!c.expose_cache_status; $("cache-resident-age-header").checked = !!c.expose_resident_age; $("cache-only-hits").checked = !!c.expose_only_hits;
|
||||
$("cache-status-header").checked = !!c.expose_status; $("cache-hits-header").checked = !!c.expose_hits; $("cache-rfc-header").checked = !!c.expose_cache_status; $("cache-resident-age-header").checked = !!c.expose_resident_age; $("cache-only-hits").checked = !!c.expose_only_hits; $("cache-detailed-status").checked = !!c.expose_detailed_status;
|
||||
const viaHeader = c.via_header === undefined ? "RustProxy" : c.via_header;
|
||||
$("cache-via-enabled").checked = viaHeader !== null; $("cache-via-value").value = viaHeader || "RustProxy"; syncCacheVia();
|
||||
setCacheMemoryPresetSelection(["conservative", "recommended", "performance"].includes(c.memory_preset) ? c.memory_preset : null);
|
||||
@@ -376,7 +376,7 @@ bindSettingsForm("response-form", next => {
|
||||
next.compression = { min_bytes: Number($("compress-min").value) }; for (const name of ["gzip", "br", "zstd", "deflate"]) next.compression[name] = $(`compress-${name}`).checked;
|
||||
}, "response", next => ({ server_header: next.server_header, diagnostic_headers: next.diagnostic_headers, compression: next.compression }));
|
||||
bindSettingsForm("cache-form", next => {
|
||||
next.cache = { ...(next.cache || {}), enabled: $("cache-enabled").checked, varnish_compatible: $("cache-varnish-compatible").checked, varnish_grace_seconds: Number($("cache-varnish-grace").value), memory_preset: selectedCacheMemoryPreset, max_bytes: Math.round(Number($("cache-memory").value) * 1048576), transient_max_bytes: Math.round(Number($("cache-transient-memory").value) * 1048576), max_object_bytes: Number($("cache-object").value) * 1024, max_entries: Number($("cache-entries").value), hot_eviction_max_objects: Number($("cache-eviction-limit").value), hot_auto_trim_enabled: $("cache-auto-trim-enabled").checked, hot_auto_trim_after_seconds: Number($("cache-auto-trim-after").value), hot_auto_trim_target_percent: Number($("cache-auto-trim-target").value), cold_enabled: $("cache-cold-enabled").checked, cold_preset: selectedCacheColdPreset, cold_path: $("cache-cold-path").value.trim(), cold_max_bytes: Math.round(Number($("cache-cold-bytes").value) * 1048576), cold_max_entries: Number($("cache-cold-entries").value), cold_queue_max_bytes: Math.round(Number($("cache-cold-queue-bytes").value) * 1048576), cold_gc_interval_seconds: Number($("cache-cold-gc-interval").value), cold_gc_max_delete: Number($("cache-cold-gc-max-delete").value), cold_after_seconds: Number($("cache-cold-after").value), cold_max_hot_seconds: Number($("cache-cold-max-hot").value), cold_on_idle: $("cache-cold-on-idle").checked, cold_on_age: $("cache-cold-on-age").checked, cold_on_lru: $("cache-cold-on-lru").checked, cold_on_shutdown: $("cache-cold-on-shutdown").checked, max_ttl_seconds: Number($("cache-ttl").value), default_ttl_seconds: Number($("cache-default-ttl").value), collapse_enabled: $("cache-collapse-enabled").checked, collapse_wait_timeout_ms: Number($("cache-collapse-timeout").value), collapse_timeout_fallback: $("cache-collapse-fallback").value, stale_if_error_timeout: $("cache-sie-timeout").checked, stale_if_error_connection: $("cache-sie-connection").checked, stale_if_error_dns: $("cache-sie-dns").checked, stale_if_error_tls: $("cache-sie-tls").checked, stale_if_error_statuses: $("cache-sie-statuses").value.split(/[\s,]+/).filter(Boolean).map(Number), proactive_refresh_enabled: $("cache-proactive-enabled").checked, proactive_refresh_before_expiry_seconds: Number($("cache-proactive-before").value), proactive_refresh_percent: Number($("cache-proactive-percent").value), proactive_refresh_max_inflight: Number($("cache-proactive-inflight").value), bypass_query: $("cache-query").checked, bypass_prefixes: $("cache-prefixes").value.split(/\r?\n/).map(v => v.trim()).filter(Boolean), http_invalidation_allowed_cidrs: $("cache-http-invalidation-cidrs").value.split(/[\n,]+/).map(v => v.trim()).filter(Boolean), static_ignore_cookies: $("cache-static-cookie").checked, static_extensions: $("cache-static-extensions").value.split(/[\n,]+/).map(v => v.trim().replace(/^\./, "").toLowerCase()).filter(Boolean), expose_status: $("cache-status-header").checked, expose_hits: $("cache-hits-header").checked, expose_cache_status: $("cache-rfc-header").checked, expose_resident_age: $("cache-resident-age-header").checked, expose_only_hits: $("cache-only-hits").checked, via_header: $("cache-via-enabled").checked ? $("cache-via-value").value.trim() : null, rules: cacheRulesEditor ? cacheRulesEditor.read() : (next.cache?.rules || []) };
|
||||
next.cache = { ...(next.cache || {}), enabled: $("cache-enabled").checked, varnish_compatible: $("cache-varnish-compatible").checked, varnish_grace_seconds: Number($("cache-varnish-grace").value), memory_preset: selectedCacheMemoryPreset, max_bytes: Math.round(Number($("cache-memory").value) * 1048576), transient_max_bytes: Math.round(Number($("cache-transient-memory").value) * 1048576), max_object_bytes: Number($("cache-object").value) * 1024, max_entries: Number($("cache-entries").value), hot_eviction_max_objects: Number($("cache-eviction-limit").value), hot_auto_trim_enabled: $("cache-auto-trim-enabled").checked, hot_auto_trim_after_seconds: Number($("cache-auto-trim-after").value), hot_auto_trim_target_percent: Number($("cache-auto-trim-target").value), cold_enabled: $("cache-cold-enabled").checked, cold_preset: selectedCacheColdPreset, cold_path: $("cache-cold-path").value.trim(), cold_max_bytes: Math.round(Number($("cache-cold-bytes").value) * 1048576), cold_max_entries: Number($("cache-cold-entries").value), cold_queue_max_bytes: Math.round(Number($("cache-cold-queue-bytes").value) * 1048576), cold_gc_interval_seconds: Number($("cache-cold-gc-interval").value), cold_gc_max_delete: Number($("cache-cold-gc-max-delete").value), cold_after_seconds: Number($("cache-cold-after").value), cold_max_hot_seconds: Number($("cache-cold-max-hot").value), cold_on_idle: $("cache-cold-on-idle").checked, cold_on_age: $("cache-cold-on-age").checked, cold_on_lru: $("cache-cold-on-lru").checked, cold_on_shutdown: $("cache-cold-on-shutdown").checked, max_ttl_seconds: Number($("cache-ttl").value), default_ttl_seconds: Number($("cache-default-ttl").value), collapse_enabled: $("cache-collapse-enabled").checked, collapse_wait_timeout_ms: Number($("cache-collapse-timeout").value), collapse_timeout_fallback: $("cache-collapse-fallback").value, stale_if_error_timeout: $("cache-sie-timeout").checked, stale_if_error_connection: $("cache-sie-connection").checked, stale_if_error_dns: $("cache-sie-dns").checked, stale_if_error_tls: $("cache-sie-tls").checked, stale_if_error_statuses: $("cache-sie-statuses").value.split(/[\s,]+/).filter(Boolean).map(Number), proactive_refresh_enabled: $("cache-proactive-enabled").checked, proactive_refresh_before_expiry_seconds: Number($("cache-proactive-before").value), proactive_refresh_percent: Number($("cache-proactive-percent").value), proactive_refresh_max_inflight: Number($("cache-proactive-inflight").value), bypass_query: $("cache-query").checked, bypass_prefixes: $("cache-prefixes").value.split(/\r?\n/).map(v => v.trim()).filter(Boolean), http_invalidation_allowed_cidrs: $("cache-http-invalidation-cidrs").value.split(/[\n,]+/).map(v => v.trim()).filter(Boolean), static_ignore_cookies: $("cache-static-cookie").checked, static_extensions: $("cache-static-extensions").value.split(/[\n,]+/).map(v => v.trim().replace(/^\./, "").toLowerCase()).filter(Boolean), expose_status: $("cache-status-header").checked, expose_hits: $("cache-hits-header").checked, expose_cache_status: $("cache-rfc-header").checked, expose_resident_age: $("cache-resident-age-header").checked, expose_only_hits: $("cache-only-hits").checked, expose_detailed_status: $("cache-detailed-status").checked, via_header: $("cache-via-enabled").checked ? $("cache-via-value").value.trim() : null, rules: cacheRulesEditor ? cacheRulesEditor.read() : (next.cache?.rules || []) };
|
||||
}, "cache");
|
||||
bindSettingsForm("transform-form", next => {
|
||||
next.transform = {
|
||||
|
||||
@@ -165,7 +165,8 @@
|
||||
$("cp-cold-bytes").textContent = fmtBytes(coldBytes);
|
||||
$("cp-cold-disk-detail").textContent = `${t("cacheLimitShort")}: ${fmtBytes(coldLimit)} · ${coldPercent.toFixed(1)}%`;
|
||||
$("cp-ratio").textContent = `${fmt((all ? (m.hit_ratio || 0) : (hits + misses ? hits / (hits + misses) : 0)) * 100, 1)}%`;
|
||||
$("cp-requests").textContent = `${number(all ? m.hits : hits)} HIT / ${number(all ? m.misses : misses)} MISS`;
|
||||
const staleHits = total("stale"), revalidatedHits = total("revalidated");
|
||||
$("cp-requests").textContent = `${number(all ? m.hits : hits)} HIT / ${number(all ? m.misses : misses)} MISS${staleHits ? ` · ${number(staleHits)} STALE` : ""}${revalidatedHits ? ` · ${number(revalidatedHits)} REVALIDATED` : ""}`;
|
||||
const bypasses = all ? (Number(m.bypasses) || 0) : total("bypasses");
|
||||
$("cp-bypass").textContent = number(bypasses);
|
||||
renderLiveChart({ hits: all ? (Number(m.hits) || 0) : hits, misses: all ? (Number(m.misses) || 0) : misses, bypasses });
|
||||
|
||||
@@ -49,6 +49,10 @@ html[data-theme=cream] :is(.card, .stat, dialog) {
|
||||
margin: 4px 0;
|
||||
}
|
||||
|
||||
.status-stale {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.status-good,
|
||||
.stat:first-child small,
|
||||
.acl-policy-preview-head .is-allow,
|
||||
|
||||
@@ -3008,6 +3008,9 @@
|
||||
<label class="check"><input id="cache-only-hits" type="checkbox" /><span
|
||||
data-i18n="cacheOnlyHits">Show RustProxy cache diagnostics only on HIT
|
||||
(retain origin headers)</span></label>
|
||||
<label class="check"><input id="cache-detailed-status" type="checkbox" /><span
|
||||
data-i18n="cacheDetailedStatus">X-Cache shows STALE and REVALIDATED
|
||||
instead of HIT</span></label>
|
||||
<div class="cache-via-setting">
|
||||
<label class="check"><input id="cache-via-enabled" type="checkbox" /><span
|
||||
data-i18n="cacheViaEnable">Add Via response header</span></label>
|
||||
@@ -4394,6 +4397,8 @@
|
||||
id="log-outcome">
|
||||
<option data-i18n="allResults" value="all">All results</option>
|
||||
<option value="HIT">HIT</option>
|
||||
<option value="STALE">STALE</option>
|
||||
<option value="REVALIDATED">REVALIDATED</option>
|
||||
<option value="MISS">MISS</option>
|
||||
<option value="BYPASS">BYPASS</option>
|
||||
<option data-i18n="errors" value="errors">Errors</option>
|
||||
|
||||
@@ -181,7 +181,8 @@
|
||||
if (!visibleColumns.has(column.id)) continue;
|
||||
const value = column.value(e), cell = el("td", String(value)); cell.title = String(value);
|
||||
if (column.id === "status") cell.className = e.status < 400 ? "status-good" : "status-error";
|
||||
if (column.id === "cache" && e.cache === "HIT") cell.className = "status-good";
|
||||
if (column.id === "cache" && ["HIT", "REVALIDATED"].includes(e.cache)) cell.className = "status-good";
|
||||
if (column.id === "cache" && e.cache === "STALE") cell.className = "status-stale";
|
||||
row.append(cell);
|
||||
}
|
||||
return row;
|
||||
|
||||
@@ -51,7 +51,7 @@ const fillWebServices = (select, chosen = "") => {
|
||||
};
|
||||
const allowDiscard = async () => { if (!dirty) return true; if (!(await appConfirm(t("vhUnsaved"), { danger: true, confirmLabel: t("discardAction") }))) return false; dirty = false; return true; };
|
||||
const defaults = () => ({
|
||||
id: "", enabled: true, force_ssl: false, www_redirect: false, www_redirect_target: null, forward_client_ip: true, websockets: false, websocket_legacy_support: false, websocket_rfc8441: false, websocket_rfc9220: false, http2_enabled: true, http3_enabled: true, cloudflare_client_ip: false, timing_headers: false, backend_header: false, backend_timing_header: false,
|
||||
id: "", enabled: true, force_ssl: false, www_redirect: false, www_redirect_target: null, forward_client_ip: true, websockets: false, websocket_legacy_support: false, websocket_rfc8441: false, websocket_rfc9220: false, http2_enabled: true, http3_enabled: true, cloudflare_client_ip: false, timing_headers: false, timing_header_names: "standard", timing_allow_origin: [], backend_header: false, backend_timing_header: false,
|
||||
frontend: { hosts: [], listener_ids: [] },
|
||||
source: { type: "reverse_proxy" },
|
||||
backends: [{ id: "origin-1", url: "", weight: 1, enabled: true, pool_eligible: true, allow_private: true, accept_local_listener_risk: false, preserve_host: true, protocol: "http1", tls_verify: false }],
|
||||
@@ -60,7 +60,7 @@ const defaults = () => ({
|
||||
|
||||
function activateTab(name) { document.querySelectorAll("#vhost-tabs button").forEach(b => { const active = b.dataset.tab === name; b.classList.toggle("active", active); b.setAttribute("aria-pressed", String(active)); b.setAttribute("aria-selected", String(active)); b.tabIndex = active ? 0 : -1; }); container.querySelectorAll(".vh-group").forEach(g => g.hidden = g.dataset.tab !== name); }
|
||||
function initTabs() { const tabs = $("vhost-tabs"); tabs.replaceChildren(); tabs.setAttribute("role", "tablist"); for (const [name, key] of [["details", "vhDetailsTab"], ["backends", "vhBackendPool"], ["health", "vhHealth"], ["locations", "vhLocations"], ["auth", "vhTabAuth"], ["ssl", "vhSsl"], ["cache", "vhCache"], ["compression", "vhCompression"], ["transform", "vhTransform"], ["security", "vhSecurity"], ["pages", "vhPages"], ["advanced", "advanced"]]) { const b = button(key, () => activateTab(name)); b.dataset.tab = name; b.setAttribute("role", "tab"); b.addEventListener("keydown", event => { const buttons = [...tabs.querySelectorAll("button")], index = buttons.indexOf(b); let next; if (event.key === "ArrowRight" || event.key === "ArrowDown") next = (index + 1) % buttons.length; else if (event.key === "ArrowLeft" || event.key === "ArrowUp") next = (index + buttons.length - 1) % buttons.length; else if (event.key === "Home") next = 0; else if (event.key === "End") next = buttons.length - 1; else return; event.preventDefault(); activateTab(buttons[next].dataset.tab); buttons[next].focus(); }); tabs.append(b); } activateTab("details"); }
|
||||
function collectCache() { const tri = name => str(name) === "" ? null : str(name) === "on", number = (name, mul = 1) => { if (str(name) === "") return null; const value = Number(str(name)) * mul; if (!Number.isSafeInteger(value)) throw new Error(t("vhJsonInvalid")); return value; }; return { enabled: tri("vh-cache-enabled"), max_ttl_seconds: number("vh-cache-ttl"), default_ttl_seconds: number("vh-cache-default"), max_object_bytes: number("vh-cache-object", 1024), bypass_query: tri("vh-cache-query"), static_ignore_cookies: tri("vh-cache-static-cookie"), static_extensions: yes("vh-cache-static-custom") ? lines(str("vh-cache-static-extensions")).map(v => v.replace(/^\./, "").toLowerCase()) : null, expose_status: tri("vh-cache-status"), expose_hits: tri("vh-cache-hits"), expose_cache_status: tri("vh-cache-rfc"), expose_resident_age: tri("vh-cache-resident-age"), expose_only_hits: tri("vh-cache-only-hits"), bypass_prefixes: yes("vh-cache-prefix-custom") ? lines(str("vh-cache-prefixes")) : null, unsafe_force: { enabled: yes("vh-cache-force-enabled"), targets: lines(str("vh-cache-force-targets")) }, rules: vhostCacheRulesEditor ? vhostCacheRulesEditor.read() : [], ignore_global_rules: vhostCacheRulesEditor ? vhostCacheRulesEditor.ignoreGlobal() : false }; }
|
||||
function collectCache() { const tri = name => str(name) === "" ? null : str(name) === "on", number = (name, mul = 1) => { if (str(name) === "") return null; const value = Number(str(name)) * mul; if (!Number.isSafeInteger(value)) throw new Error(t("vhJsonInvalid")); return value; }; return { enabled: tri("vh-cache-enabled"), max_ttl_seconds: number("vh-cache-ttl"), default_ttl_seconds: number("vh-cache-default"), max_object_bytes: number("vh-cache-object", 1024), bypass_query: tri("vh-cache-query"), static_ignore_cookies: tri("vh-cache-static-cookie"), static_extensions: yes("vh-cache-static-custom") ? lines(str("vh-cache-static-extensions")).map(v => v.replace(/^\./, "").toLowerCase()) : null, expose_status: tri("vh-cache-status"), expose_hits: tri("vh-cache-hits"), expose_cache_status: tri("vh-cache-rfc"), expose_resident_age: tri("vh-cache-resident-age"), expose_only_hits: tri("vh-cache-only-hits"), expose_detailed_status: tri("vh-cache-detailed-status"), bypass_prefixes: yes("vh-cache-prefix-custom") ? lines(str("vh-cache-prefixes")) : null, unsafe_force: { enabled: yes("vh-cache-force-enabled"), targets: lines(str("vh-cache-force-targets")) }, rules: vhostCacheRulesEditor ? vhostCacheRulesEditor.read() : [], ignore_global_rules: vhostCacheRulesEditor ? vhostCacheRulesEditor.ignoreGlobal() : false }; }
|
||||
function collectCompression() { const tri = name => str(name) === "" ? null : str(name) === "on"; return { enabled: tri("vh-compression-enabled"), zstd: tri("vh-compression-zstd"), br: tri("vh-compression-br"), gzip: tri("vh-compression-gzip"), deflate: tri("vh-compression-deflate") }; }
|
||||
function collectTransform() {
|
||||
const tri = name => str(name) === "" ? null : str(name) === "on";
|
||||
|
||||
@@ -206,6 +206,8 @@ function load(value = defaults(), migrationIds = [], show = true) {
|
||||
(value.backends || []).forEach(m => memberRow(members, m)); g.append(button("vhAddBackend", () => { memberRow(members); changed(); }));
|
||||
g = group("vhBackendDiagnostics");
|
||||
field(g, "timing-headers", "vhTimingHeaders", value.timing_headers === true, "checkbox");
|
||||
field(g, "timing-header-names", "vhTimingHeaderNames", value.timing_header_names || "standard", "select", { values: [["standard", "vhTimingHeaderNamesStandard"], ["cdn", "vhTimingHeaderNamesCdn"], ["legacy", "vhTimingHeaderNamesLegacy"]] });
|
||||
field(g, "timing-allow-origin", "vhTimingAllowOrigin", (value.timing_allow_origin || []).join(", "), "text", { maxLength: 2048 }).placeholder = "https://app.example.com";
|
||||
field(g, "backend-header", "vhBackendHeader", value.backend_header === true, "checkbox");
|
||||
field(g, "backend-timing-header", "vhBackendTimingHeader", value.backend_timing_header === true, "checkbox");
|
||||
note(g, "vhBackendDiagnosticsHelp");
|
||||
@@ -517,7 +519,7 @@ function load(value = defaults(), migrationIds = [], show = true) {
|
||||
const customStatic = field(staticExtensionFields, "vh-cache-static-custom", "vhCacheStaticCustom", cache.static_extensions != null, "checkbox");
|
||||
const staticExtensions = field(staticExtensionFields, "vh-cache-static-extensions", "vhCacheStaticExtensions", (cache.static_extensions || envelope?.config.cache?.static_extensions || []).join("\n"), "textarea", { rows: 5, maxLength: 2048 });
|
||||
const syncStatic = () => { staticExtensions.disabled = !customStatic.checked; }; customStatic.addEventListener("change", syncStatic); syncStatic(); note(staticExtensionFields, "vhCacheStaticHelp");
|
||||
tri(cacheOptions, "vh-cache-status", "cacheStatusHeader", cache.expose_status); tri(cacheOptions, "vh-cache-hits", "cacheHitsHeader", cache.expose_hits); tri(cacheOptions, "vh-cache-rfc", "cacheRfcHeader", cache.expose_cache_status); tri(cacheOptions, "vh-cache-resident-age", "cacheResidentAge", cache.expose_resident_age); tri(cacheOptions, "vh-cache-only-hits", "cacheOnlyHits", cache.expose_only_hits);
|
||||
tri(cacheOptions, "vh-cache-status", "cacheStatusHeader", cache.expose_status); tri(cacheOptions, "vh-cache-hits", "cacheHitsHeader", cache.expose_hits); tri(cacheOptions, "vh-cache-rfc", "cacheRfcHeader", cache.expose_cache_status); tri(cacheOptions, "vh-cache-resident-age", "cacheResidentAge", cache.expose_resident_age); tri(cacheOptions, "vh-cache-only-hits", "cacheOnlyHits", cache.expose_only_hits); tri(cacheOptions, "vh-cache-detailed-status", "cacheDetailedStatus", cache.expose_detailed_status);
|
||||
const bypassFields = el("div", undefined, "vh-wide vh-override-fields"); cacheOptions.append(bypassFields);
|
||||
const customCachePrefixes = field(bypassFields, "vh-cache-prefix-custom", "vhCacheCustomPrefixes", cache.bypass_prefixes != null, "checkbox");
|
||||
const bypassPrefixes = field(bypassFields, "vh-cache-prefixes", "cacheBypassPrefixes", (cache.bypass_prefixes || []).join("\n"), "textarea", { rows: 2, maxLength: 32768 });
|
||||
@@ -617,7 +619,7 @@ function collect() {
|
||||
}
|
||||
if (yes("content-type-block-enabled") && !lines(str("content-type-block-list")).length) throw new Error(t("vhContentTypeRequired"));
|
||||
return {
|
||||
id: str("id"), enabled: yes("enabled"), source: mainSourceType === "web_server" ? { type: "web_server", web_service_id: str("source-web-service") } : { type: "reverse_proxy" }, error_fallback: mainFallbackTarget ? { target: mainFallbackTarget, statuses: mainFallbackStatuses.length ? mainFallbackStatuses : [404] } : null, force_ssl: yes("force-ssl"), www_redirect: yes("www-redirect"), www_redirect_target: str("www-redirect-target") || null, forward_client_ip: yes("forward-client-ip"), websockets: yes("websockets"), websocket_legacy_support: yes("websockets") && yes("websocket-legacy-support"), websocket_rfc8441: yes("websockets") && ["h2", "h2h3"].includes(str("websocket-mode")), websocket_rfc9220: yes("websockets") && ["h3", "h2h3"].includes(str("websocket-mode")), http2_enabled: yes("http2-enabled"), http3_enabled: yes("http3-enabled"), cloudflare_client_ip: yes("cloudflare-client-ip"), timing_headers: yes("timing-headers"), backend_header: yes("backend-header"), backend_timing_header: yes("backend-timing-header"), basic_auth: basicEditor.read(), certificate_id: nullable("certificate-id"), allow_certificate_mismatch: yes("allow-certificate-mismatch"), tls_policy: yes("tls-policy-custom") ? { tls12: yes("tls-policy-12"), tls13: yes("tls-policy-13"), cipher_suites: lines(str("tls-policy-ciphers")), post_quantum: yes("tls-policy-pqc") } : null, cache: collectCache(), compression: collectCompression(), transform: collectTransform(), pages: pagesEditor.read(), frontend: { hosts: readHosts(), listener_ids: bindingSelection }, acl_profile_id: null,
|
||||
id: str("id"), enabled: yes("enabled"), source: mainSourceType === "web_server" ? { type: "web_server", web_service_id: str("source-web-service") } : { type: "reverse_proxy" }, error_fallback: mainFallbackTarget ? { target: mainFallbackTarget, statuses: mainFallbackStatuses.length ? mainFallbackStatuses : [404] } : null, force_ssl: yes("force-ssl"), www_redirect: yes("www-redirect"), www_redirect_target: str("www-redirect-target") || null, forward_client_ip: yes("forward-client-ip"), websockets: yes("websockets"), websocket_legacy_support: yes("websockets") && yes("websocket-legacy-support"), websocket_rfc8441: yes("websockets") && ["h2", "h2h3"].includes(str("websocket-mode")), websocket_rfc9220: yes("websockets") && ["h3", "h2h3"].includes(str("websocket-mode")), http2_enabled: yes("http2-enabled"), http3_enabled: yes("http3-enabled"), cloudflare_client_ip: yes("cloudflare-client-ip"), timing_headers: yes("timing-headers"), timing_header_names: str("timing-header-names") || "standard", timing_allow_origin: str("timing-allow-origin").split(/[\s,]+/).filter(Boolean), backend_header: yes("backend-header"), backend_timing_header: yes("backend-timing-header"), basic_auth: basicEditor.read(), certificate_id: nullable("certificate-id"), allow_certificate_mismatch: yes("allow-certificate-mismatch"), tls_policy: yes("tls-policy-custom") ? { tls12: yes("tls-policy-12"), tls13: yes("tls-policy-13"), cipher_suites: lines(str("tls-policy-ciphers")), post_quantum: yes("tls-policy-pqc") } : null, cache: collectCache(), compression: collectCompression(), transform: collectTransform(), pages: pagesEditor.read(), frontend: { hosts: readHosts(), listener_ids: bindingSelection }, acl_profile_id: null,
|
||||
acl_profile_ids: window.rustProxyAclPicker.read(form.querySelector(".vh-acl-profile-choices")),
|
||||
proxy_timeouts: { connect_timeout_seconds: num("proxy-connect-timeout"), response_header_timeout_seconds: num("proxy-header-timeout"), read_timeout_seconds: num("proxy-read-timeout"), send_timeout_seconds: num("proxy-send-timeout") },
|
||||
rate_limit: { enabled: yes("rate-enabled"), requests: num("rate-requests"), window_seconds: num("rate-window"), burst: num("rate-burst"), country_access: { mode: str("country-mode"), countries: lines(str("country-list")).map(value => value.toUpperCase()) }, country_limits: countryRatesReader(), user_agent_limits: uaRatesReader() },
|
||||
|
||||
Vendored
+29
-1
@@ -1,3 +1,21 @@
|
||||
pub const STALE_REASONS: [&str; 4] = [
|
||||
"cache_stale_if_error",
|
||||
"cache_stale_while_revalidate",
|
||||
"cache_max_stale",
|
||||
"cache_collapse_timeout_stale",
|
||||
];
|
||||
pub const REVALIDATED_REASONS: [&str; 2] = ["cache_revalidated", "cache_revalidated_uncached"];
|
||||
pub fn detailed_outcome(outcome: &'static str, reason: &str) -> &'static str {
|
||||
if outcome != "HIT" {
|
||||
outcome
|
||||
} else if STALE_REASONS.contains(&reason) {
|
||||
"STALE"
|
||||
} else if REVALIDATED_REASONS.contains(&reason) {
|
||||
"REVALIDATED"
|
||||
} else {
|
||||
"HIT"
|
||||
}
|
||||
}
|
||||
impl Settings {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
validate_rules(&self.rules, true)?;
|
||||
@@ -280,11 +298,15 @@ impl Settings {
|
||||
return;
|
||||
}
|
||||
if self.expose_status {
|
||||
let shown = match reason {
|
||||
Some(reason) if self.expose_detailed_status => detailed_outcome(outcome, reason),
|
||||
_ => outcome,
|
||||
};
|
||||
insert_cache_diagnostic(
|
||||
headers,
|
||||
"x-cache",
|
||||
"x-upstream-cache",
|
||||
HeaderValue::from_static(outcome),
|
||||
HeaderValue::from_static(shown),
|
||||
);
|
||||
if let Some(reason) = reason {
|
||||
insert_cache_diagnostic(
|
||||
@@ -441,6 +463,7 @@ pub struct Overrides {
|
||||
pub expose_cache_status: Option<bool>,
|
||||
pub expose_resident_age: Option<bool>,
|
||||
pub expose_only_hits: Option<bool>,
|
||||
pub expose_detailed_status: Option<bool>,
|
||||
pub unsafe_force: UnsafeForce,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub rules: Vec<Rule>,
|
||||
@@ -496,6 +519,9 @@ impl Overrides {
|
||||
if let Some(value) = self.expose_only_hits {
|
||||
result.expose_only_hits = value;
|
||||
}
|
||||
if let Some(value) = self.expose_detailed_status {
|
||||
result.expose_detailed_status = value;
|
||||
}
|
||||
result.validate()?;
|
||||
let compiled = CompiledRules::compile(
|
||||
vhost_id,
|
||||
@@ -600,6 +626,8 @@ pub struct DomainCounters {
|
||||
pub bypasses: u64,
|
||||
pub stored: u64,
|
||||
pub saved_body_bytes: u64,
|
||||
pub stale: u64,
|
||||
pub revalidated: u64,
|
||||
pub reasons: BTreeMap<String, u64>,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Default, Serialize, PartialEq, Eq)]
|
||||
|
||||
Vendored
+2
@@ -188,6 +188,7 @@ pub struct Settings {
|
||||
pub expose_cache_status: bool,
|
||||
pub expose_resident_age: bool,
|
||||
pub expose_only_hits: bool,
|
||||
pub expose_detailed_status: bool,
|
||||
pub via_header: Option<String>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub rules: Vec<Rule>,
|
||||
@@ -256,6 +257,7 @@ impl Default for Settings {
|
||||
expose_cache_status: false,
|
||||
expose_resident_age: false,
|
||||
expose_only_hits: false,
|
||||
expose_detailed_status: false,
|
||||
via_header: Some("RustProxy".into()),
|
||||
rules: Vec::new(),
|
||||
compiled_rules: None,
|
||||
|
||||
Vendored
+7
@@ -95,7 +95,14 @@ impl DomainStats {
|
||||
for (label, counter) in self.reasons.load().iter() {
|
||||
reasons.insert((*label).to_owned(), load(counter));
|
||||
}
|
||||
let sum = |labels: &[&str]| -> u64 {
|
||||
labels.iter().filter_map(|label| reasons.get(*label)).sum()
|
||||
};
|
||||
let stale = sum(&STALE_REASONS);
|
||||
let revalidated = sum(&REVALIDATED_REASONS);
|
||||
DomainCounters {
|
||||
stale,
|
||||
revalidated,
|
||||
hits: load(&self.hits),
|
||||
misses: load(&self.misses),
|
||||
bypasses: load(&self.bypasses),
|
||||
|
||||
@@ -287,6 +287,8 @@ pub struct CompiledFrontend {
|
||||
pub tls_http1: Option<Arc<rustls::ServerConfig>>,
|
||||
pub cloudflare_client_ip: bool,
|
||||
pub timing_headers: bool,
|
||||
pub timing_header_names: crate::vhost::TimingHeaderNames,
|
||||
pub timing_allow_origin: Option<http::HeaderValue>,
|
||||
pub backend_header: bool,
|
||||
pub backend_timing_header: bool,
|
||||
pub rate_limit: crate::rate_limit::Settings,
|
||||
|
||||
@@ -251,6 +251,8 @@ fn compile_routing(
|
||||
tls_http1: frontend_tls_http1,
|
||||
cloudflare_client_ip: host.cloudflare_client_ip,
|
||||
timing_headers: host.timing_headers,
|
||||
timing_header_names: host.timing_header_names,
|
||||
timing_allow_origin: crate::vhost::timing_allow_origin_value(&host.timing_allow_origin)?,
|
||||
backend_header: host.backend_header,
|
||||
backend_timing_header: host.backend_timing_header,
|
||||
rate_limit: host.rate_limit.clone(),
|
||||
|
||||
@@ -206,6 +206,10 @@ impl Drop for Exchange {
|
||||
let request_bytes = self.request_bytes.load(Ordering::Relaxed);
|
||||
let response_bytes = self.response_bytes.load(Ordering::Relaxed);
|
||||
let duration_ms = duration.as_millis() as u64;
|
||||
let cache_reason = *self
|
||||
.cache_reason
|
||||
.get_mut()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
let cache = match self.cache_status.load(Ordering::Relaxed) {
|
||||
1 => "HIT",
|
||||
2 => "MISS",
|
||||
@@ -251,10 +255,7 @@ impl Drop for Exchange {
|
||||
sni: None,
|
||||
authority: None,
|
||||
matched_by: None,
|
||||
cache_reason: self
|
||||
.cache_reason
|
||||
.get_mut()
|
||||
.unwrap_or_else(|e| e.into_inner()),
|
||||
cache_reason,
|
||||
vhost: self.vhost.take(),
|
||||
route,
|
||||
cache_effective_enabled,
|
||||
@@ -292,7 +293,7 @@ impl Drop for Exchange {
|
||||
country,
|
||||
status,
|
||||
duration_ms,
|
||||
cache,
|
||||
cache: crate::cache::detailed_outcome(cache, cache_reason),
|
||||
request_bytes,
|
||||
response_bytes,
|
||||
outcome,
|
||||
|
||||
+44
-17
@@ -293,31 +293,58 @@ fn finish_headers(
|
||||
!frontend.is_some_and(|frontend| !frontend.http3_enabled),
|
||||
);
|
||||
}
|
||||
fn server_timing_cache_desc(status: u16, reason: &str) -> Option<&'static str> {
|
||||
match status {
|
||||
1 => Some(crate::cache::detailed_outcome("HIT", reason)),
|
||||
2 => Some("MISS"),
|
||||
3 => Some("BYPASS"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn server_timing_value(
|
||||
names: crate::vhost::TimingHeaderNames,
|
||||
total: Duration,
|
||||
origin: Option<Duration>,
|
||||
cache: Option<&str>,
|
||||
) -> String {
|
||||
let (total_name, origin_name, cache_name) = match names {
|
||||
crate::vhost::TimingHeaderNames::Standard => ("proxy", "upstream", "proxy-cache"),
|
||||
crate::vhost::TimingHeaderNames::Cdn => ("edge", "origin", "cdn-cache"),
|
||||
crate::vhost::TimingHeaderNames::Legacy => ("proxy", "origin", "cache"),
|
||||
};
|
||||
let mut values = vec![format!("{total_name};dur={:.2}", total.as_secs_f64() * 1000.0)];
|
||||
if let Some(origin) = origin {
|
||||
values.push(format!("{origin_name};dur={:.2}", origin.as_secs_f64() * 1000.0));
|
||||
}
|
||||
if let Some(cache) = cache {
|
||||
values.push(format!("{cache_name};desc=\"{cache}\""));
|
||||
}
|
||||
values.join(", ")
|
||||
}
|
||||
fn apply_timing_headers(
|
||||
response: &mut Response,
|
||||
frontend: Option<&crate::config::CompiledFrontend>,
|
||||
exchange: &Exchange,
|
||||
) {
|
||||
if !frontend.is_some_and(|frontend| frontend.timing_headers) {
|
||||
let status = exchange.cache_status.load(Ordering::Relaxed);
|
||||
if status == 1 {
|
||||
response.headers_mut().remove("server-timing");
|
||||
}
|
||||
let Some(frontend) = frontend.filter(|frontend| frontend.timing_headers) else {
|
||||
return;
|
||||
}
|
||||
let total_ms = exchange.started.elapsed().as_secs_f64() * 1000.0;
|
||||
let mut values = vec![format!("proxy;dur={total_ms:.2}")];
|
||||
if let Some(origin) = response.extensions().get::<OriginTiming>() {
|
||||
values.push(format!("origin;dur={:.2}", origin.0.as_secs_f64() * 1000.0));
|
||||
}
|
||||
let cache = match exchange.cache_status.load(Ordering::Relaxed) {
|
||||
1 => Some("HIT"),
|
||||
2 => Some("MISS"),
|
||||
3 => Some("BYPASS"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(cache) = cache {
|
||||
values.push(format!("cache;desc=\"{cache}\""));
|
||||
let reason = *exchange.cache_reason.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let value = server_timing_value(
|
||||
frontend.timing_header_names,
|
||||
exchange.started.elapsed(),
|
||||
response.extensions().get::<OriginTiming>().map(|origin| origin.0),
|
||||
server_timing_cache_desc(status, reason),
|
||||
);
|
||||
if let Ok(value) = HeaderValue::from_str(&value) {
|
||||
response.headers_mut().append("server-timing", value);
|
||||
}
|
||||
response.headers_mut().remove("server-timing");
|
||||
if let Ok(value) = HeaderValue::from_str(&values.join(", ")) {
|
||||
response.headers_mut().insert("server-timing", value);
|
||||
if let Some(value) = &frontend.timing_allow_origin {
|
||||
response.headers_mut().insert("timing-allow-origin", value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -526,6 +526,11 @@ mod cache_fast_path_tests {
|
||||
if parts.uri.path() == "/stale-no-validator" {
|
||||
response.headers_mut().remove("etag");
|
||||
}
|
||||
if matches!(parts.uri.path(), "/server-timing" | "/stale-then-503") {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("server-timing", HeaderValue::from_static("app;dur=7"));
|
||||
}
|
||||
if parts.uri.path() == "/stale-then-503" && request_number > 1 {
|
||||
*response.status_mut() = StatusCode::SERVICE_UNAVAILABLE;
|
||||
*response.body_mut() = Body::from("origin failed");
|
||||
@@ -776,6 +781,125 @@ mod cache_fast_path_tests {
|
||||
fixture.stop().await;
|
||||
}
|
||||
|
||||
fn server_timing(headers: &HeaderMap) -> Vec<String> {
|
||||
headers
|
||||
.get_all("server-timing")
|
||||
.iter()
|
||||
.map(|value| value.to_str().unwrap().to_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn server_timing_appends_to_origin_metrics_and_replaces_them_on_hits() {
|
||||
let origin = origin().await;
|
||||
let mut config = config_for(origin.addr, true);
|
||||
config.vhosts[0].timing_headers = true;
|
||||
let fixture = Fixture::new(config).await;
|
||||
let miss = server_timing(&fixture.get("/server-timing", &[]).await.headers);
|
||||
assert_eq!(miss.len(), 2, "{miss:?}");
|
||||
assert_eq!(miss[0], "app;dur=7");
|
||||
assert!(miss[1].starts_with("proxy;dur="), "{miss:?}");
|
||||
assert!(miss[1].contains(", upstream;dur="), "{miss:?}");
|
||||
assert!(miss[1].ends_with(", proxy-cache;desc=\"MISS\""), "{miss:?}");
|
||||
let hit = server_timing(&fixture.get("/server-timing", &[]).await.headers);
|
||||
assert_eq!(hit.len(), 1, "{hit:?}");
|
||||
assert!(hit[0].starts_with("proxy;dur="), "{hit:?}");
|
||||
assert!(!hit[0].contains("upstream;dur="), "{hit:?}");
|
||||
assert!(hit[0].ends_with(", proxy-cache;desc=\"HIT\""), "{hit:?}");
|
||||
fixture
|
||||
.change(|config| {
|
||||
config.vhosts[0].timing_header_names = crate::vhost::TimingHeaderNames::Cdn;
|
||||
config.vhosts[0].timing_allow_origin = vec!["https://rum.example.com".into()];
|
||||
})
|
||||
.await;
|
||||
let cdn = fixture.get("/server-timing", &[]).await.headers;
|
||||
let cdn_timing = server_timing(&cdn);
|
||||
assert!(cdn_timing[0].starts_with("edge;dur="), "{cdn_timing:?}");
|
||||
assert!(cdn_timing[0].ends_with(", cdn-cache;desc=\"HIT\""), "{cdn_timing:?}");
|
||||
assert_eq!(cdn["timing-allow-origin"], "https://rum.example.com");
|
||||
fixture
|
||||
.change(|config| {
|
||||
config.vhosts[0].timing_header_names = crate::vhost::TimingHeaderNames::Legacy
|
||||
})
|
||||
.await;
|
||||
let legacy = server_timing(&fixture.get("/server-timing", &[]).await.headers);
|
||||
assert_eq!(legacy.len(), 1, "{legacy:?}");
|
||||
assert!(legacy[0].starts_with("proxy;dur="), "{legacy:?}");
|
||||
assert!(legacy[0].ends_with(", cache;desc=\"HIT\""), "{legacy:?}");
|
||||
fixture.stop().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn server_timing_reports_stale_and_drops_cached_metrics_without_timing_headers() {
|
||||
let origin = origin().await;
|
||||
let mut config = config_for(origin.addr, true);
|
||||
config.vhosts[0].timing_headers = true;
|
||||
let fixture = Fixture::new(config).await;
|
||||
fixture.get("/stale-then-503", &[]).await;
|
||||
let stale = server_timing(&fixture.get("/stale-then-503", &[]).await.headers);
|
||||
assert_eq!(stale.len(), 1, "{stale:?}");
|
||||
assert!(stale[0].ends_with(", proxy-cache;desc=\"STALE\""), "{stale:?}");
|
||||
fixture.get("/cache-headers-revalidate", &[]).await;
|
||||
let revalidated =
|
||||
server_timing(&fixture.get("/cache-headers-revalidate", &[]).await.headers);
|
||||
assert_eq!(revalidated.len(), 1, "{revalidated:?}");
|
||||
assert!(revalidated[0].contains(", upstream;dur="), "{revalidated:?}");
|
||||
assert!(
|
||||
revalidated[0].ends_with(", proxy-cache;desc=\"REVALIDATED\""),
|
||||
"{revalidated:?}"
|
||||
);
|
||||
fixture.change(|config| config.vhosts[0].timing_headers = false).await;
|
||||
let quiet = fixture.get("/server-timing", &[]).await;
|
||||
assert_eq!(server_timing(&quiet.headers), vec!["app;dur=7".to_owned()]);
|
||||
let cached = fixture.get("/server-timing", &[]).await;
|
||||
assert_eq!(cached.headers["x-cache"], "HIT");
|
||||
assert!(server_timing(&cached.headers).is_empty());
|
||||
fixture.stop().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn detailed_cache_status_reaches_x_cache_logs_and_domain_counters() {
|
||||
let origin = origin().await;
|
||||
let mut config = config_for(origin.addr, true);
|
||||
config.cache.expose_detailed_status = true;
|
||||
let fixture = Fixture::new(config).await;
|
||||
assert_eq!(fixture.get("/stale-then-503", &[]).await.headers["x-cache"], "MISS");
|
||||
assert_eq!(fixture.get("/stale-then-503", &[]).await.headers["x-cache"], "STALE");
|
||||
fixture.get("/cache-headers-revalidate", &[]).await;
|
||||
let revalidated = fixture.get("/cache-headers-revalidate", &[]).await;
|
||||
assert_eq!(revalidated.headers["x-cache"], "REVALIDATED");
|
||||
assert_eq!(fixture.get("/server-timing", &[]).await.headers["x-cache"], "MISS");
|
||||
assert_eq!(fixture.get("/server-timing", &[]).await.headers["x-cache"], "HIT");
|
||||
let mut logged = Vec::new();
|
||||
for _ in 0..50 {
|
||||
logged = fixture
|
||||
.app
|
||||
.logs
|
||||
.recent()
|
||||
.into_iter()
|
||||
.filter(|entry| entry.event == "request")
|
||||
.map(|entry| entry.cache)
|
||||
.collect();
|
||||
if logged.len() >= 6 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert_eq!(logged, ["HIT", "MISS", "REVALIDATED", "MISS", "STALE", "MISS"]);
|
||||
let dashboard = fixture.app.cache.dashboard(None, 0, 10);
|
||||
let stale: u64 = dashboard.domains.iter().map(|row| row.counters.stale).sum();
|
||||
let revalidated: u64 = dashboard
|
||||
.domains
|
||||
.iter()
|
||||
.map(|row| row.counters.revalidated)
|
||||
.sum();
|
||||
let hits: u64 = dashboard.domains.iter().map(|row| row.counters.hits).sum();
|
||||
assert_eq!((stale, revalidated, hits), (1, 1, 3));
|
||||
fixture.change(|config| config.cache.expose_detailed_status = false).await;
|
||||
assert_eq!(fixture.get("/stale-then-503", &[]).await.headers["x-cache"], "HIT");
|
||||
fixture.stop().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rfc9211_stale_origin_200_is_fwd_stale_not_fwd_miss() {
|
||||
let origin = origin().await;
|
||||
|
||||
@@ -98,6 +98,7 @@ fn cache_revision(config: &config::Config) -> u64 {
|
||||
cache.expose_cache_status = false;
|
||||
cache.expose_resident_age = false;
|
||||
cache.expose_only_hits = false;
|
||||
cache.expose_detailed_status = false;
|
||||
cache.via_header = None;
|
||||
let mut transform = config.transform.clone();
|
||||
transform.preset = None;
|
||||
@@ -136,6 +137,8 @@ fn vhost_cache_revision(vhost: &crate::vhost::Vhost) -> u64 {
|
||||
view.www_redirect = false;
|
||||
view.www_redirect_target = None;
|
||||
view.timing_headers = false;
|
||||
view.timing_header_names = Default::default();
|
||||
view.timing_allow_origin.clear();
|
||||
view.backend_header = false;
|
||||
view.backend_timing_header = false;
|
||||
view.certificate_id = None;
|
||||
@@ -155,6 +158,7 @@ fn vhost_cache_revision(vhost: &crate::vhost::Vhost) -> u64 {
|
||||
view.proxy_timeouts = Default::default();
|
||||
view.frontend.listener_ids.clear();
|
||||
view.cache.expose_only_hits = None;
|
||||
view.cache.expose_detailed_status = None;
|
||||
view.load_balancing = Default::default();
|
||||
for member in &mut view.backends {
|
||||
member.weight = 1;
|
||||
|
||||
@@ -40,6 +40,14 @@ impl Default for ProxyTimeouts {
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TimingHeaderNames {
|
||||
#[default]
|
||||
Standard,
|
||||
Cdn,
|
||||
Legacy,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MethodPolicyMode {
|
||||
#[default]
|
||||
Off,
|
||||
@@ -316,6 +324,10 @@ pub struct Vhost {
|
||||
#[serde(default)]
|
||||
pub timing_headers: bool,
|
||||
#[serde(default)]
|
||||
pub timing_header_names: TimingHeaderNames,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub timing_allow_origin: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub backend_header: bool,
|
||||
#[serde(default)]
|
||||
pub backend_timing_header: bool,
|
||||
|
||||
@@ -299,3 +299,31 @@ mod websocket_protocol_flags_tests {
|
||||
assert!(r#"{"websocket_rfc9220":true}"#.contains("\"websocket_rfc9220\":true"));
|
||||
}
|
||||
}
|
||||
mod timing_allow_origin_tests {
|
||||
use super::*;
|
||||
fn value(origins: &[&str]) -> Result<Option<http::HeaderValue>> {
|
||||
timing_allow_origin_value(&origins.iter().map(|v| v.to_string()).collect::<Vec<_>>())
|
||||
}
|
||||
#[test]
|
||||
fn origins_and_wildcard_are_accepted() {
|
||||
assert!(value(&[]).unwrap().is_none());
|
||||
assert_eq!(value(&["*"]).unwrap().unwrap(), "*");
|
||||
assert_eq!(
|
||||
value(&["https://app.example.com", "http://localhost:3000"]).unwrap().unwrap(),
|
||||
"https://app.example.com, http://localhost:3000"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn paths_wildcard_mixes_and_other_schemes_are_rejected() {
|
||||
for bad in [
|
||||
&["https://app.example.com/"][..],
|
||||
&["https://app.example.com/path"],
|
||||
&["https://user@app.example.com"],
|
||||
&["ftp://app.example.com"],
|
||||
&["app.example.com"],
|
||||
&["*", "https://app.example.com"],
|
||||
] {
|
||||
assert!(value(bad).is_err(), "{bad:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -251,6 +251,7 @@ impl Vhost {
|
||||
if let Some(server) = &self.server_header {
|
||||
server.validate()?;
|
||||
}
|
||||
timing_allow_origin_value(&self.timing_allow_origin)?;
|
||||
self.basic_auth.compile()?;
|
||||
crate::auth_provider::Selection {
|
||||
choice: self.authentication,
|
||||
@@ -511,3 +512,36 @@ pub fn listener_plan(config: &Config, policy: &ValidationPolicy) -> Result<Vec<L
|
||||
result.sort_by_key(|l| (l.address, l.tls, l.http2, l.h2c));
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn timing_allow_origin_value(origins: &[String]) -> Result<Option<http::HeaderValue>> {
|
||||
if origins.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
ensure!(
|
||||
origins.len() <= 16,
|
||||
"Timing-Allow-Origin accepts at most 16 origins"
|
||||
);
|
||||
if origins.iter().any(|origin| origin == "*") {
|
||||
ensure!(
|
||||
origins.len() == 1,
|
||||
"Timing-Allow-Origin \"*\" cannot be combined with other origins"
|
||||
);
|
||||
return Ok(Some(http::HeaderValue::from_static("*")));
|
||||
}
|
||||
for origin in origins {
|
||||
let parsed = url::Url::parse(origin)
|
||||
.with_context(|| format!("invalid Timing-Allow-Origin origin {origin:?}"))?;
|
||||
ensure!(
|
||||
matches!(parsed.scheme(), "http" | "https")
|
||||
&& parsed.host_str().is_some()
|
||||
&& parsed.username().is_empty()
|
||||
&& parsed.password().is_none()
|
||||
&& parsed.path() == "/"
|
||||
&& parsed.query().is_none()
|
||||
&& parsed.fragment().is_none()
|
||||
&& !origin.ends_with('/'),
|
||||
"Timing-Allow-Origin {origin:?} must be an origin such as https://app.example.com"
|
||||
);
|
||||
}
|
||||
Ok(Some(http::HeaderValue::from_str(&origins.join(", "))?))
|
||||
}
|
||||
Reference in new issue
Block a user