v0.38.7
This commit is contained in:
1 parent
d4a604970e
commit
38a23e2210
40 files changed
+928
-532
No files matched your search
+56
-11
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.0.3",
|
||||
"info": {
|
||||
"title": "RustProxy Administration API",
|
||||
"version": "0.38.6",
|
||||
"version": "0.38.7",
|
||||
"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": [
|
||||
@@ -862,13 +862,19 @@
|
||||
},
|
||||
"timing_header_names": {
|
||||
"type": "string",
|
||||
"enum": ["standard", "cdn", "legacy"],
|
||||
"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" },
|
||||
"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)."
|
||||
},
|
||||
@@ -2513,6 +2519,11 @@
|
||||
"$ref": "#/components/schemas/CacheRule"
|
||||
},
|
||||
"description": "Global cache rules (Cache → Rules)."
|
||||
},
|
||||
"static_ignore_vary_cookie": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"description": "For cookie-independent configured static extensions only, omit Cookie from Vary on explicitly public, otherwise cacheable responses. Requires static_ignore_cookies. Preserves other Vary dimensions and all private/no-store/Set-Cookie safeguards."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
@@ -3461,14 +3472,48 @@
|
||||
"default": false,
|
||||
"description": "Explicit, persistent administrator opt-in: allow assigning a named public certificate to hostnames not covered by its DNS SAN. This does not suppress TLS client warnings, validate the certificate less during agent polling, or disable backend TLS verification. Requires a named certificate."
|
||||
},
|
||||
"timing_headers": { "type": "boolean", "default": false, "description": "Since 0.38.3. Server-Timing diagnostics for this Docker vhost." },
|
||||
"backend_header": { "type": "boolean", "default": false, "description": "Since 0.38.3. X-Rust-Proxy-Backend with the generated backend id." },
|
||||
"backend_timing_header": { "type": "boolean", "default": false, "description": "Since 0.38.3. X-RustProxy-Backend-Time with the origin response-header latency." },
|
||||
"cloudflare_client_ip": { "type": "boolean", "default": false, "description": "Since 0.38.3. Use verified Cloudflare client-IP and country headers, as on ordinary vhosts." },
|
||||
"method_policy": { "type": "object", "description": "Since 0.38.3. Same format as the vhost method_policy: mode off, allow or block with a list of methods." },
|
||||
"rate_limit": { "type": "object", "nullable": true, "default": null, "description": "Since 0.38.3. Same format as the vhost rate_limit (per-client IP limit and country_access); null = off." },
|
||||
"security_headers": { "type": "object", "nullable": true, "default": null, "description": "Since 0.38.3. Same format as the vhost security_headers (HSTS, nosniff, frame_options, referrer_policy, CSP, permissions policy); null = none." },
|
||||
"basic_auth": { "type": "object", "nullable": true, "default": null, "description": "Since 0.38.3. Same format as the vhost basic_auth: enabled, realm, require_tls, forward_credentials and users with Argon2id password_hash from POST /api/basic-auth/hash; null = no login." }
|
||||
"timing_headers": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Since 0.38.3. Server-Timing diagnostics for this Docker vhost."
|
||||
},
|
||||
"backend_header": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Since 0.38.3. X-Rust-Proxy-Backend with the generated backend id."
|
||||
},
|
||||
"backend_timing_header": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Since 0.38.3. X-RustProxy-Backend-Time with the origin response-header latency."
|
||||
},
|
||||
"cloudflare_client_ip": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Since 0.38.3. Use verified Cloudflare client-IP and country headers, as on ordinary vhosts."
|
||||
},
|
||||
"method_policy": {
|
||||
"type": "object",
|
||||
"description": "Since 0.38.3. Same format as the vhost method_policy: mode off, allow or block with a list of methods."
|
||||
},
|
||||
"rate_limit": {
|
||||
"type": "object",
|
||||
"nullable": true,
|
||||
"default": null,
|
||||
"description": "Since 0.38.3. Same format as the vhost rate_limit (per-client IP limit and country_access); null = off."
|
||||
},
|
||||
"security_headers": {
|
||||
"type": "object",
|
||||
"nullable": true,
|
||||
"default": null,
|
||||
"description": "Since 0.38.3. Same format as the vhost security_headers (HSTS, nosniff, frame_options, referrer_policy, CSP, permissions policy); null = none."
|
||||
},
|
||||
"basic_auth": {
|
||||
"type": "object",
|
||||
"nullable": true,
|
||||
"default": null,
|
||||
"description": "Since 0.38.3. Same format as the vhost basic_auth: enabled, realm, require_tls, forward_credentials and users with Argon2id password_hash from POST /api/basic-auth/hash; null = no login."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"service_key",
|
||||
|
||||
@@ -36,7 +36,7 @@ function renderSettings() {
|
||||
$("cache-proactive-enabled").checked = c.proactive_refresh_enabled === true; $("cache-proactive-before").value = c.proactive_refresh_before_expiry_seconds ?? 15; $("cache-proactive-percent").value = c.proactive_refresh_percent ?? 10; $("cache-proactive-inflight").value = c.proactive_refresh_max_inflight ?? 4;
|
||||
$("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-static-cookie").checked = c.static_ignore_cookies !== false; $("cache-static-vary-cookie").checked = c.static_ignore_vary_cookie !== 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-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();
|
||||
@@ -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, 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 || []) };
|
||||
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_ignore_vary_cookie: $("cache-static-vary-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 = {
|
||||
|
||||
@@ -1357,9 +1357,9 @@
|
||||
<label class="check" data-acme-provider="rfc2136"><input class="switch"
|
||||
id="acme-sign-query" type="checkbox" /><span
|
||||
data-i18n="acmeSignQuery"></span></label>
|
||||
<label class="check vh-wide"><input id="acme-tos" required=""
|
||||
<label class="check vh-wide"><input class="switch" id="acme-tos" required=""
|
||||
type="checkbox" /><span data-i18n="acmeTos"></span></label>
|
||||
<label class="check vh-wide"><input id="acme-confirm-production"
|
||||
<label class="check vh-wide"><input class="switch" id="acme-confirm-production"
|
||||
type="checkbox" /><span
|
||||
data-i18n="acmeConfirmProduction"></span></label>
|
||||
<label class="vh-wide" data-acme-provider="cloudflare"><span
|
||||
@@ -3001,12 +3001,15 @@
|
||||
<label class="check"><input class="switch" id="cache-static-cookie" type="checkbox" /><span
|
||||
data-i18n="cacheStaticCookie">Ignore request cookies for static
|
||||
files</span></label>
|
||||
<label class="check"><input class="switch" id="cache-static-vary-cookie" type="checkbox" checked /><span
|
||||
data-i18n="cacheStaticVaryCookie">Ignore Vary: Cookie for public static assets</span></label>
|
||||
<label data-i18n="cacheStaticExtensions" for="cache-static-extensions">Global static
|
||||
extensions</label><textarea id="cache-static-extensions" rows="5"
|
||||
spellcheck="false"></textarea>
|
||||
<p class="fine cache-static-guidance" data-i18n="cacheStaticHelp">Cookie bypass is
|
||||
limited to these file
|
||||
extensions. Response privacy rules still apply.</p>
|
||||
<p class="fine cache-static-guidance" data-i18n="cacheStaticHelp">Use only for
|
||||
static assets that never depend on user sessions. Cookie is removed from Vary
|
||||
only for explicitly public, cacheable responses; private, no-store and
|
||||
Set-Cookie still prevent caching.</p>
|
||||
<h3 class="subheading cache-header-settings-heading"
|
||||
data-i18n="cacheHeadersSection">Cache response headers</h3>
|
||||
<div class="switch-grid"><label class="check"><input class="switch" id="cache-status-header"
|
||||
|
||||
@@ -61,7 +61,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"), 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 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_ignore_vary_cookie: tri("vh-cache-static-vary-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";
|
||||
|
||||
@@ -313,8 +313,11 @@ function load(value = defaults(), migrationIds = [], show = true) {
|
||||
note(rateFields, "vhRateHelp");
|
||||
|
||||
const countryFields = subsection(g, "vhTrafficCountrySection");
|
||||
field(countryFields, "country-mode", "vhCountryMode", access.mode || "off", "select", { values: [["off", "vhOff"], ["block", "vhCountryBlock"], ["allow", "vhCountryAllow"]] });
|
||||
field(countryFields, "country-list", "vhCountryList", (access.countries || []).join("\n"), "textarea", { rows: 3, maxLength: 1024 });
|
||||
const countryMode = field(countryFields, "country-mode", "vhCountryMode", access.mode || "off", "select", { values: [["off", "vhOff"], ["block", "vhCountryBlock"], ["allow", "vhCountryAllow"]] });
|
||||
const countryList = field(countryFields, "country-list", "vhCountryList", (access.countries || []).join("\n"), "textarea", { rows: 3, maxLength: 1024 });
|
||||
window.rustProxyCountryPicker?.attach(countryList);
|
||||
const syncCountryPicker = () => { countryList.disabled = countryMode.value === "off"; };
|
||||
countryMode.addEventListener("change", syncCountryPicker); syncCountryPicker();
|
||||
note(countryFields, "vhCountryPolicyHelp");
|
||||
|
||||
const countryRateFields = subsection(g, "vhTrafficCountryRatesSection");
|
||||
@@ -515,6 +518,7 @@ function load(value = defaults(), migrationIds = [], show = true) {
|
||||
field(cacheOptions, "vh-cache-object", "vhCacheObject", cache.max_object_bytes == null ? "" : cache.max_object_bytes / 1024, "number", { min: 1, step: "any", max: (envelope?.config.cache?.max_object_bytes ?? 1048576) / 1024 });
|
||||
tri(cacheOptions, "vh-cache-query", "cacheBypassQuery", cache.bypass_query);
|
||||
tri(cacheOptions, "vh-cache-static-cookie", "vhCacheStaticCookie", cache.static_ignore_cookies);
|
||||
tri(cacheOptions, "vh-cache-static-vary-cookie", "vhCacheStaticVaryCookie", cache.static_ignore_vary_cookie);
|
||||
const staticExtensionFields = el("div", undefined, "vh-wide vh-override-fields"); cacheOptions.append(staticExtensionFields);
|
||||
const customStatic = field(staticExtensionFields, "vh-cache-static-custom", "vhCacheStaticCustom", cache.static_extensions != null, "checkbox", { switch: true });
|
||||
const staticExtensions = field(staticExtensionFields, "vh-cache-static-extensions", "vhCacheStaticExtensions", (cache.static_extensions || envelope?.config.cache?.static_extensions || []).join("\n"), "textarea", { rows: 5, maxLength: 2048 });
|
||||
|
||||
Vendored
+248
@@ -958,6 +958,144 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn vary_keys_normalize_only_known_equivalent_header_values() {
|
||||
fn keyed(name: &str, fields: &[&str]) -> Key {
|
||||
let mut request = HeaderMap::new();
|
||||
let header_name = http::HeaderName::from_bytes(name.as_bytes()).unwrap();
|
||||
for field in fields {
|
||||
request.append(
|
||||
header_name.clone(),
|
||||
HeaderValue::from_str(field).unwrap(),
|
||||
);
|
||||
}
|
||||
variant_key(&[0x52; 32], &[name.to_owned()], &request)
|
||||
}
|
||||
|
||||
// RFC 9111 section 4.1: OWS, equivalent repeated list fields,
|
||||
// case-insensitive language tags and equivalent qvalues.
|
||||
assert_eq!(
|
||||
keyed("accept-language", &["en,pl;q=0.5"]),
|
||||
keyed("accept-language", &["EN ; q=1.0", " PL ; Q=0.500"])
|
||||
);
|
||||
assert_eq!(
|
||||
keyed("accept-encoding", &["GZIP ; q=1, BR;q=0.800"]),
|
||||
keyed("accept-encoding", &["gzip", "br;q=0.8"])
|
||||
);
|
||||
assert_eq!(
|
||||
keyed("accept-charset", &["UTF-8, iso-8859-1;q=0.8"]),
|
||||
keyed("accept-charset", &["utf-8;q=1.000", "ISO-8859-1 ;q=0.80"])
|
||||
);
|
||||
assert_eq!(
|
||||
keyed("accept", &["TEXT/HTML ;level=One, application/json"]),
|
||||
keyed("accept", &["text/html;level=One", "application/json"])
|
||||
);
|
||||
assert_eq!(
|
||||
keyed("accept", &["text/plain;profile=\"a,b\", application/json"]),
|
||||
keyed("accept", &["text/plain;profile=\"a,b\"", "application/json"])
|
||||
);
|
||||
assert_eq!(
|
||||
keyed("if-none-match", &["\"tag,a\", W/\"tag-b\""]),
|
||||
keyed("if-none-match", &["\"tag,a\"", "W/\"tag-b\""])
|
||||
);
|
||||
|
||||
// Header order remains significant unless a field's specification
|
||||
// guarantees otherwise; opaque and session-related values stay exact.
|
||||
assert_ne!(
|
||||
keyed("accept-language", &["en,pl"]),
|
||||
keyed("accept-language", &["pl,en"])
|
||||
);
|
||||
assert_ne!(
|
||||
keyed("accept-encoding", &["gzip;q=0.5"]),
|
||||
keyed("accept-encoding", &["gzip;q=0.6"])
|
||||
);
|
||||
assert_ne!(
|
||||
keyed("accept", &["text/plain;profile=Case"]),
|
||||
keyed("accept", &["text/plain;profile=case"])
|
||||
);
|
||||
assert_ne!(
|
||||
keyed("accept", &["text/plain;profile=\"a, b\""]),
|
||||
keyed("accept", &["text/plain;profile=\"a,b\""])
|
||||
);
|
||||
assert_ne!(
|
||||
keyed("x-custom", &["foo, bar"]),
|
||||
keyed("x-custom", &["foo,bar"])
|
||||
);
|
||||
assert_eq!(keyed("x-custom", &[" token "]), keyed("x-custom", &["token"]));
|
||||
assert_ne!(
|
||||
keyed("x-custom", &["foo", "bar"]),
|
||||
keyed("x-custom", &["foo,bar"])
|
||||
);
|
||||
assert_ne!(keyed("user-agent", &["Agent"]), keyed("user-agent", &["agent"]));
|
||||
assert_ne!(
|
||||
keyed("cookie", &["session=one; theme=dark"]),
|
||||
keyed("cookie", &["session=two; theme=dark"])
|
||||
);
|
||||
assert_ne!(keyed("user-agent", &[]), keyed("user-agent", &[""]));
|
||||
assert_ne!(
|
||||
keyed("accept-encoding", &["gzip;q=invalid"]),
|
||||
keyed("accept-encoding", &["gzip"])
|
||||
);
|
||||
// Invalid raw fields cannot collide with a valid canonical value.
|
||||
assert_ne!(
|
||||
keyed("accept-encoding", &["gzip;q=1000"]),
|
||||
keyed("accept-encoding", &["gzip"])
|
||||
);
|
||||
assert_ne!(
|
||||
keyed("accept-language", &["en;q=1000"]),
|
||||
keyed("accept-language", &["en"])
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hot_vary_hit_uses_semantic_header_normalization() {
|
||||
let cache = Cache::new(1);
|
||||
let settings = settings();
|
||||
let mut original = HeaderMap::new();
|
||||
original.insert("accept-language", "en,pl;q=0.5".parse().unwrap());
|
||||
original.insert("user-agent", "AgentOne".parse().unwrap());
|
||||
let original_ticket = ticket(&cache, &original);
|
||||
|
||||
let mut response = Response::new(Body::from("public-variant"));
|
||||
*response.headers_mut() = headers("public, max-age=60");
|
||||
response.headers_mut().insert(
|
||||
"vary",
|
||||
HeaderValue::from_static("Accept-Language, User-Agent"),
|
||||
);
|
||||
let policy = plan(
|
||||
StatusCode::OK,
|
||||
response.headers(),
|
||||
&settings,
|
||||
Duration::ZERO,
|
||||
)
|
||||
.unwrap();
|
||||
cache
|
||||
.wrap(response, original_ticket.clone(), policy, &settings)
|
||||
.into_body()
|
||||
.collect()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut equivalent = HeaderMap::new();
|
||||
equivalent.append("accept-language", HeaderValue::from_static("EN"));
|
||||
equivalent.append("accept-language", HeaderValue::from_static("PL;q=0.500"));
|
||||
equivalent.insert("user-agent", HeaderValue::from_static("AgentOne"));
|
||||
let equivalent_ticket = ticket(&cache, &equivalent);
|
||||
assert_eq!(original_ticket.key, equivalent_ticket.key);
|
||||
let hit = cache.get(&equivalent_ticket).expect("semantically equivalent Vary HIT");
|
||||
assert_eq!(
|
||||
hit.response.into_body().collect().await.unwrap().to_bytes(),
|
||||
Bytes::from_static(b"public-variant")
|
||||
);
|
||||
|
||||
let mut different = equivalent.clone();
|
||||
different.insert("user-agent", HeaderValue::from_static("AgentTwo"));
|
||||
assert!(cache.get(&ticket(&cache, &different)).is_none());
|
||||
different.insert("user-agent", HeaderValue::from_static("AgentOne"));
|
||||
different.insert("accept-language", HeaderValue::from_static("de"));
|
||||
assert!(cache.get(&ticket(&cache, &different)).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn canonical_identity_drops_accept_encoding_as_a_cache_variant() {
|
||||
let cache = Cache::new(1);
|
||||
@@ -1272,6 +1410,7 @@ mod tests {
|
||||
let settings = Settings::default();
|
||||
assert!(settings.enabled);
|
||||
assert!(settings.static_ignore_cookies);
|
||||
assert!(settings.static_ignore_vary_cookie);
|
||||
for path in [
|
||||
"/asset.jpg",
|
||||
"/asset.jpeg",
|
||||
@@ -1302,6 +1441,115 @@ mod tests {
|
||||
Some("request_cookie")
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn static_vary_cookie_is_stripped_only_for_explicitly_public_cacheable_assets() {
|
||||
let settings = Settings::default();
|
||||
let mut h = headers("public, max-age=120");
|
||||
h.append("vary", HeaderValue::from_static("Cookie, Accept-Language"));
|
||||
h.append("vary", HeaderValue::from_static("X-Theme, cookie"));
|
||||
assert!(normalize_static_cookie_vary(
|
||||
StatusCode::OK, &mut h, &settings, Duration::ZERO, true,
|
||||
&ResponseOverrides::NONE,
|
||||
));
|
||||
assert_eq!(h["vary"], "Accept-Language, X-Theme");
|
||||
assert_eq!(
|
||||
plan(StatusCode::OK, &h, &settings, Duration::ZERO).unwrap().vary,
|
||||
vec!["accept-language".to_owned(), "x-theme".to_owned()]
|
||||
);
|
||||
assert!(!normalize_static_cookie_vary(
|
||||
StatusCode::OK, &mut h, &settings, Duration::ZERO, true,
|
||||
&ResponseOverrides::NONE,
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_vary_cookie_never_overrides_privacy_or_malformed_vary() {
|
||||
for (policy, has_cookie, vary) in [
|
||||
("private, max-age=120", false, "Cookie"),
|
||||
("public, no-store, max-age=120", false, "Cookie"),
|
||||
("max-age=120", false, "Cookie"),
|
||||
("public, max-age=120", true, "Cookie"),
|
||||
("public, max-age=120", false, "Cookie, *"),
|
||||
("public, max-age=120", false, "Cookie, Broken Header"),
|
||||
("public", false, "Cookie"),
|
||||
("public, max-age=0", false, "Cookie"),
|
||||
] {
|
||||
let settings = Settings::default();
|
||||
let mut h = headers(policy);
|
||||
h.insert("vary", vary.parse().unwrap());
|
||||
if has_cookie { h.insert("set-cookie", HeaderValue::from_static("session=secret")); }
|
||||
let original = h.clone();
|
||||
assert!(!normalize_static_cookie_vary(
|
||||
StatusCode::OK, &mut h, &settings, Duration::ZERO, true,
|
||||
&ResponseOverrides::NONE,
|
||||
), "{policy}, {vary}");
|
||||
assert_eq!(h, original, "{policy}, {vary}");
|
||||
}
|
||||
let mut settings = Settings::default();
|
||||
let mut h = headers("public, max-age=120");
|
||||
h.insert("vary", HeaderValue::from_static("Cookie"));
|
||||
settings.static_ignore_vary_cookie = false;
|
||||
assert!(!normalize_static_cookie_vary(
|
||||
StatusCode::OK, &mut h, &settings, Duration::ZERO, true,
|
||||
&ResponseOverrides::NONE,
|
||||
));
|
||||
settings.static_ignore_vary_cookie = true;
|
||||
assert!(!normalize_static_cookie_vary(
|
||||
StatusCode::OK, &mut h, &settings, Duration::ZERO, false,
|
||||
&ResponseOverrides::NONE,
|
||||
));
|
||||
assert!(!normalize_static_cookie_vary(
|
||||
StatusCode::NOT_MODIFIED, &mut h, &settings, Duration::ZERO, true,
|
||||
&ResponseOverrides::NONE,
|
||||
));
|
||||
assert_eq!(h["vary"], "Cookie");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_vary_cookie_requires_freshness_without_revalidation() {
|
||||
let settings = Settings::default();
|
||||
for (policy, age, needs_validator) in [
|
||||
("public, max-age=120", Some("120"), false),
|
||||
("public, no-cache, max-age=120", None, true),
|
||||
] {
|
||||
let mut h = headers(policy);
|
||||
h.insert("vary", HeaderValue::from_static("Cookie"));
|
||||
if let Some(age) = age {
|
||||
h.insert("age", age.parse().unwrap());
|
||||
}
|
||||
if needs_validator {
|
||||
h.insert("etag", HeaderValue::from_static("\"asset\""));
|
||||
}
|
||||
let original = h.clone();
|
||||
assert!(!normalize_static_cookie_vary(
|
||||
StatusCode::OK, &mut h, &settings, Duration::ZERO, true,
|
||||
&ResponseOverrides::NONE,
|
||||
), "{policy}");
|
||||
assert_eq!(h, original, "{policy}");
|
||||
}
|
||||
|
||||
// A positive administrator-configured fallback does make `public`
|
||||
// without an explicit max-age a reusable static response.
|
||||
let mut settings = Settings::default();
|
||||
settings.default_ttl_seconds = 60;
|
||||
let mut h = headers("public");
|
||||
h.insert("vary", HeaderValue::from_static("Cookie"));
|
||||
assert!(normalize_static_cookie_vary(
|
||||
StatusCode::OK, &mut h, &settings, Duration::ZERO, true,
|
||||
&ResponseOverrides::NONE,
|
||||
));
|
||||
assert!(!h.contains_key("vary"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_vary_cookie_vhost_override_inherits_and_can_disable() {
|
||||
let global = Settings::default();
|
||||
let mut overrides = Overrides::default();
|
||||
assert!(overrides.resolve(&global).unwrap().static_ignore_vary_cookie);
|
||||
overrides.static_ignore_vary_cookie = Some(false);
|
||||
assert!(!overrides.resolve(&global).unwrap().static_ignore_vary_cookie);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn age_uses_corrected_received_age_plus_response_delay_without_rounding_up() {
|
||||
let settings = settings();
|
||||
|
||||
Vendored
+80
@@ -62,6 +62,86 @@ mod cold_tier_tests {
|
||||
panic!("cold tier did not persist in time");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn normalized_vary_keys_work_after_cold_demotion() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let settings = cold_settings();
|
||||
let shutdown = CancellationToken::new();
|
||||
let cache = Cache::start(
|
||||
11,
|
||||
Some(dir.path().to_path_buf()),
|
||||
settings.clone(),
|
||||
shutdown.clone(),
|
||||
);
|
||||
let mut original = HeaderMap::new();
|
||||
original.insert("accept-language", HeaderValue::from_static("en,pl;q=0.5"));
|
||||
let original_ticket = cache
|
||||
.ticket_scoped(
|
||||
11,
|
||||
"cold-test",
|
||||
"http",
|
||||
"cold.example",
|
||||
"origin@127.0.0.1:8080",
|
||||
"/vary-cold",
|
||||
&original,
|
||||
)
|
||||
.unwrap();
|
||||
let mut response = Response::new(Body::from("cold-language-variant"));
|
||||
response.headers_mut().insert(
|
||||
"cache-control",
|
||||
HeaderValue::from_static("public, max-age=120"),
|
||||
);
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("vary", HeaderValue::from_static("Accept-Language"));
|
||||
let policy = plan(StatusCode::OK, response.headers(), &settings, Duration::ZERO)
|
||||
.expect("cacheable Vary response");
|
||||
cache
|
||||
.wrap(response, original_ticket, policy, &settings)
|
||||
.into_body()
|
||||
.collect()
|
||||
.await
|
||||
.unwrap();
|
||||
fill(&cache, &settings, "/second", "demote-the-first-object").await;
|
||||
wait_for_cold(&cache, 1).await;
|
||||
|
||||
let mut equivalent = HeaderMap::new();
|
||||
equivalent.append("accept-language", HeaderValue::from_static("EN;q=1"));
|
||||
equivalent.append("accept-language", HeaderValue::from_static("pl;q=0.500"));
|
||||
let lookup = cache
|
||||
.ticket_scoped(
|
||||
11,
|
||||
"cold-test",
|
||||
"http",
|
||||
"cold.example",
|
||||
"origin@127.0.0.1:8080",
|
||||
"/vary-cold",
|
||||
&equivalent,
|
||||
)
|
||||
.unwrap();
|
||||
let hit = cache.get_tiered(&lookup, &settings).await.expect("COLD Vary HIT");
|
||||
assert_eq!(
|
||||
hit.response.into_body().collect().await.unwrap().to_bytes(),
|
||||
Bytes::from_static(b"cold-language-variant")
|
||||
);
|
||||
|
||||
let mut different = HeaderMap::new();
|
||||
different.insert("accept-language", HeaderValue::from_static("de"));
|
||||
let mismatch = cache
|
||||
.ticket_scoped(
|
||||
11,
|
||||
"cold-test",
|
||||
"http",
|
||||
"cold.example",
|
||||
"origin@127.0.0.1:8080",
|
||||
"/vary-cold",
|
||||
&different,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(cache.get_tiered(&mismatch, &settings).await.is_none());
|
||||
shutdown.cancel();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn upstream_cache_headers_survive_cold_demotion_and_hit_annotation() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
Vendored
+4
@@ -457,6 +457,7 @@ pub struct Overrides {
|
||||
pub bypass_query: Option<bool>,
|
||||
pub bypass_prefixes: Option<Vec<String>>,
|
||||
pub static_ignore_cookies: Option<bool>,
|
||||
pub static_ignore_vary_cookie: Option<bool>,
|
||||
pub static_extensions: Option<Vec<String>>,
|
||||
pub expose_status: Option<bool>,
|
||||
pub expose_hits: Option<bool>,
|
||||
@@ -501,6 +502,9 @@ impl Overrides {
|
||||
if let Some(value) = self.static_ignore_cookies {
|
||||
result.static_ignore_cookies = value;
|
||||
}
|
||||
if let Some(value) = self.static_ignore_vary_cookie {
|
||||
result.static_ignore_vary_cookie = value;
|
||||
}
|
||||
if let Some(value) = &self.static_extensions {
|
||||
result.static_extensions = value.clone();
|
||||
}
|
||||
|
||||
Vendored
+199
-6
@@ -332,21 +332,214 @@ fn vary_names(headers: &HeaderMap) -> Option<Vec<String>> {
|
||||
(names.len() <= 64).then_some(names)
|
||||
}
|
||||
|
||||
// RFC 9111 section 4.1 permits only semantics-preserving Vary comparisons.
|
||||
// In particular, Cookie and arbitrary extension fields are NOT comma lists.
|
||||
fn trim_vary_ows(mut value: &[u8]) -> &[u8] {
|
||||
while value.first().is_some_and(|byte| matches!(*byte, b' ' | b'\t')) {
|
||||
value = &value[1..];
|
||||
}
|
||||
while value.last().is_some_and(|byte| matches!(*byte, b' ' | b'\t')) {
|
||||
value = &value[..value.len() - 1];
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
fn split_vary_unquoted(value: &[u8], separator: u8) -> Option<Vec<&[u8]>> {
|
||||
let mut parts = Vec::new();
|
||||
let mut start = 0;
|
||||
let mut quoted = false;
|
||||
let mut escaped = false;
|
||||
for (index, &byte) in value.iter().enumerate() {
|
||||
if quoted {
|
||||
if escaped {
|
||||
escaped = false;
|
||||
} else if byte == b'\\' {
|
||||
escaped = true;
|
||||
} else if byte == b'"' {
|
||||
quoted = false;
|
||||
}
|
||||
} else if byte == b'"' {
|
||||
quoted = true;
|
||||
} else if byte == separator {
|
||||
parts.push(trim_vary_ows(&value[start..index]));
|
||||
start = index + 1;
|
||||
}
|
||||
}
|
||||
if quoted || escaped {
|
||||
return None;
|
||||
}
|
||||
parts.push(trim_vary_ows(&value[start..]));
|
||||
Some(parts)
|
||||
}
|
||||
|
||||
fn is_http_token(value: &[u8]) -> bool {
|
||||
!value.is_empty()
|
||||
&& value.iter().all(|byte| {
|
||||
byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(byte)
|
||||
})
|
||||
}
|
||||
|
||||
fn is_language_range(value: &[u8]) -> bool {
|
||||
if value == b"*" {
|
||||
return true;
|
||||
}
|
||||
let mut parts = value.split(|byte| *byte == b'-');
|
||||
let Some(primary) = parts.next() else {
|
||||
return false;
|
||||
};
|
||||
(1..=8).contains(&primary.len())
|
||||
&& primary.iter().all(u8::is_ascii_alphabetic)
|
||||
&& parts.all(|subtag| {
|
||||
(1..=8).contains(&subtag.len()) && subtag.iter().all(u8::is_ascii_alphanumeric)
|
||||
})
|
||||
}
|
||||
|
||||
// qvalue is 0..1, expressed with at most three fractional digits (RFC 9110).
|
||||
fn parse_vary_quality(value: &[u8]) -> Option<u16> {
|
||||
let (&whole, rest) = value.split_first()?;
|
||||
if whole != b'0' && whole != b'1' {
|
||||
return None;
|
||||
}
|
||||
let fraction = if rest.is_empty() {
|
||||
rest
|
||||
} else if rest[0] == b'.' {
|
||||
&rest[1..]
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
if fraction.len() > 3
|
||||
|| !fraction.iter().all(u8::is_ascii_digit)
|
||||
|| (whole == b'1' && fraction.iter().any(|digit| *digit != b'0'))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if whole == b'1' {
|
||||
return Some(1000);
|
||||
}
|
||||
let mut result = 0;
|
||||
for (digit, factor) in fraction.iter().zip([100, 10, 1]) {
|
||||
result += u16::from(*digit - b'0') * factor;
|
||||
}
|
||||
Some(result)
|
||||
}
|
||||
|
||||
fn normalize_vary_weighted(name: &str, member: &[u8]) -> Option<Vec<u8>> {
|
||||
let parts = split_vary_unquoted(member, b';')?;
|
||||
if parts.is_empty() || parts.len() > 2 {
|
||||
return None;
|
||||
}
|
||||
let token = parts[0];
|
||||
if !(if name == "accept-language" {
|
||||
is_language_range(token)
|
||||
} else {
|
||||
is_http_token(token)
|
||||
}) {
|
||||
return None;
|
||||
}
|
||||
let quality = if parts.len() == 2 {
|
||||
let weight = parts[1];
|
||||
if weight.len() < 2 || !weight[..2].eq_ignore_ascii_case(b"q=") {
|
||||
return None;
|
||||
}
|
||||
parse_vary_quality(&weight[2..])?
|
||||
} else {
|
||||
1000
|
||||
};
|
||||
let mut canonical = token.to_ascii_lowercase();
|
||||
canonical.extend_from_slice(b";q=");
|
||||
canonical.extend_from_slice(quality.to_string().as_bytes());
|
||||
Some(canonical)
|
||||
}
|
||||
|
||||
fn normalize_vary_accept(member: &[u8]) -> Option<Vec<u8>> {
|
||||
let parts = split_vary_unquoted(member, b';')?;
|
||||
let media_range = *parts.first()?;
|
||||
let slash = media_range.iter().position(|byte| *byte == b'/')?;
|
||||
if !is_http_token(&media_range[..slash]) || !is_http_token(&media_range[slash + 1..]) {
|
||||
return None;
|
||||
}
|
||||
// Media type/subtype is case-insensitive; parameter values need not be.
|
||||
let mut canonical = media_range.to_ascii_lowercase();
|
||||
for param in parts.iter().skip(1) {
|
||||
if param.is_empty() {
|
||||
return None;
|
||||
}
|
||||
canonical.push(b';');
|
||||
canonical.extend_from_slice(param);
|
||||
}
|
||||
Some(canonical)
|
||||
}
|
||||
|
||||
fn normalize_vary_list(name: &str, values: &[&[u8]]) -> Option<Vec<u8>> {
|
||||
let known_list = matches!(
|
||||
name,
|
||||
"accept" | "accept-charset" | "accept-encoding" | "accept-language"
|
||||
| "cache-control" | "if-match" | "if-none-match" | "pragma" | "te"
|
||||
);
|
||||
if !known_list || values.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut canonical = Vec::new();
|
||||
let mut first = true;
|
||||
for value in values {
|
||||
// Commas inside a quoted-string are data, not list separators.
|
||||
for member in split_vary_unquoted(value, b',')? {
|
||||
let normalized = match name {
|
||||
"accept-language" | "accept-encoding" | "accept-charset" => {
|
||||
// Empty list elements are kept distinct. Never confuse an
|
||||
// explicitly empty field with an absent header field.
|
||||
if member.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
normalize_vary_weighted(name, member)?
|
||||
}
|
||||
}
|
||||
"accept" if !member.is_empty() => normalize_vary_accept(member)?,
|
||||
_ => member.to_vec(),
|
||||
};
|
||||
if !first {
|
||||
canonical.push(b',');
|
||||
}
|
||||
first = false;
|
||||
canonical.extend_from_slice(&normalized);
|
||||
}
|
||||
}
|
||||
Some(canonical)
|
||||
}
|
||||
|
||||
fn variant_key(base_key: &Key, vary: &[String], headers: &HeaderMap) -> Key {
|
||||
if vary.is_empty() {
|
||||
return *base_key;
|
||||
}
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(b"RustProxy-Vary-v1");
|
||||
// The v2 domain deliberately makes old COLD variant hashes miss instead
|
||||
// of reusing entries that were indexed with the previous bytewise keys.
|
||||
digest.update(b"RustProxy-Vary-v2");
|
||||
digest.update(base_key);
|
||||
for name in vary {
|
||||
digest.update((name.len() as u64).to_be_bytes());
|
||||
digest.update(name.as_bytes());
|
||||
let values = headers.get_all(name.as_str());
|
||||
digest.update((values.iter().count() as u64).to_be_bytes());
|
||||
for value in values.iter() {
|
||||
digest.update((value.as_bytes().len() as u64).to_be_bytes());
|
||||
digest.update(value.as_bytes());
|
||||
let header_values = headers.get_all(name.as_str());
|
||||
let values: Vec<&[u8]> = header_values.iter().map(HeaderValue::as_bytes).collect();
|
||||
if let Some(value) = normalize_vary_list(name, &values) {
|
||||
// Separate normalized values from raw fallback values: a malformed
|
||||
// literal such as "gzip;q=1000" must not match canonical gzip.
|
||||
digest.update([1_u8]);
|
||||
// RFC 9110 allows combining multiple lines for known list fields.
|
||||
digest.update(1_u64.to_be_bytes());
|
||||
digest.update((value.len() as u64).to_be_bytes());
|
||||
digest.update(&value);
|
||||
} else {
|
||||
// Unknown fields are opaque: no comma splitting, token case-folding
|
||||
// or quote rewriting. Leading/trailing HTTP OWS is insignificant.
|
||||
// The count also distinguishes an absent field from an empty one.
|
||||
digest.update([0_u8]);
|
||||
digest.update((values.len() as u64).to_be_bytes());
|
||||
for value in values {
|
||||
let value = trim_vary_ows(value);
|
||||
digest.update((value.len() as u64).to_be_bytes());
|
||||
digest.update(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
digest.finalize().into()
|
||||
|
||||
Vendored
+2
@@ -170,6 +170,7 @@ pub struct Settings {
|
||||
pub bypass_prefixes: Vec<String>,
|
||||
pub http_invalidation_allowed_cidrs: Vec<String>,
|
||||
pub static_ignore_cookies: bool,
|
||||
pub static_ignore_vary_cookie: bool,
|
||||
pub static_extensions: Vec<String>,
|
||||
pub collapse_enabled: bool,
|
||||
pub collapse_wait_timeout_ms: u64,
|
||||
@@ -230,6 +231,7 @@ impl Default for Settings {
|
||||
bypass_prefixes: Vec::new(),
|
||||
http_invalidation_allowed_cidrs: Vec::new(),
|
||||
static_ignore_cookies: true,
|
||||
static_ignore_vary_cookie: true,
|
||||
static_extensions: vec![
|
||||
"css", "js", "mjs", "cjs", "wasm", "png", "jpg", "jpeg", "jfif", "jxl", "gif",
|
||||
"webp", "avif", "apng", "svg", "ico", "cur", "bmp", "tif", "tiff", "heic", "heif",
|
||||
|
||||
Vendored
+65
@@ -54,6 +54,71 @@ impl Plan {
|
||||
self
|
||||
}
|
||||
}
|
||||
/// For cookie-independent static files only: remove Cookie from the Vary schema
|
||||
/// presented to both RustProxy and downstream caches. A backend's public cache
|
||||
/// policy must be explicit; private/Set-Cookie/no-store responses are untouched.
|
||||
/// The caller is responsible for applying this only to configured static paths.
|
||||
pub fn normalize_static_cookie_vary(
|
||||
status: StatusCode,
|
||||
headers: &mut HeaderMap,
|
||||
settings: &Settings,
|
||||
response_delay: Duration,
|
||||
ignore_static_cookie: bool,
|
||||
overrides: &ResponseOverrides,
|
||||
) -> bool {
|
||||
if !ignore_static_cookie
|
||||
|| !settings.static_ignore_vary_cookie
|
||||
|| !varies_on(headers, "cookie")
|
||||
|| headers.contains_key(::http::header::SET_COOKIE)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let Some(control) = directives(headers) else {
|
||||
return false;
|
||||
};
|
||||
if !control.contains_key("public")
|
||||
|| control.contains_key("private")
|
||||
|| control.contains_key("no-store")
|
||||
|| control.contains_key("must-understand")
|
||||
|| (settings.varnish_compatible && surrogate_no_store(headers))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut retained = Vec::new();
|
||||
for field in headers.get_all(::http::header::VARY) {
|
||||
let Ok(text) = field.to_str() else { return false; };
|
||||
for part in text.split(',') {
|
||||
let name = part.trim();
|
||||
if name == "*" || name.parse::<http::HeaderName>().is_err() {
|
||||
return false;
|
||||
}
|
||||
if !name.eq_ignore_ascii_case("cookie") {
|
||||
retained.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut candidate = headers.clone();
|
||||
candidate.remove(::http::header::VARY);
|
||||
if !retained.is_empty() {
|
||||
let Ok(value) = HeaderValue::from_str(&retained.join(", ")) else {
|
||||
return false;
|
||||
};
|
||||
candidate.insert(::http::header::VARY, value);
|
||||
}
|
||||
// A response may have a storage plan with zero freshness (e.g. `public`
|
||||
// with no fallback TTL, or `max-age=0`). Such a response must retain the
|
||||
// origin's Vary: Cookie. The same applies when reuse needs revalidation.
|
||||
let Some(plan) = plan_with(status, &candidate, settings, response_delay, overrides) else {
|
||||
return false;
|
||||
};
|
||||
if plan.remaining_ttl() == 0 || plan.requires_revalidation {
|
||||
return false;
|
||||
}
|
||||
*headers = candidate;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn plan(
|
||||
status: StatusCode,
|
||||
headers: &HeaderMap,
|
||||
|
||||
@@ -348,6 +348,24 @@ fn apply_timing_headers(
|
||||
}
|
||||
}
|
||||
|
||||
// Docker publications use "docker-<agent>-<service hash>/docker" internally.
|
||||
// Keep those stable internal IDs for routing, logs, and metrics, but avoid
|
||||
// repeating the Docker marker in the opt-in response diagnostic header.
|
||||
fn backend_diagnostic_label(id: &str) -> std::borrow::Cow<'_, str> {
|
||||
let Some(name) = id.strip_prefix("docker-").and_then(|id| id.strip_suffix("/docker")) else {
|
||||
return std::borrow::Cow::Borrowed(id);
|
||||
};
|
||||
let Some((agent, hash)) = name.rsplit_once('-') else {
|
||||
return std::borrow::Cow::Borrowed(id);
|
||||
};
|
||||
// The generated Docker vhost ID ends in a 12-character SHA-256 prefix.
|
||||
// Do not rewrite ordinary or malformed backend identifiers.
|
||||
if agent.is_empty() || hash.len() != 12 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return std::borrow::Cow::Borrowed(id);
|
||||
}
|
||||
std::borrow::Cow::Owned(format!("{agent}/{hash}"))
|
||||
}
|
||||
|
||||
fn apply_backend_diagnostic_values(
|
||||
response: &mut Response,
|
||||
backend_header: bool,
|
||||
@@ -366,7 +384,7 @@ fn apply_backend_diagnostic_values(
|
||||
}
|
||||
if backend_header {
|
||||
if let Some(origin) = response.extensions().get::<OriginBackend>() {
|
||||
if let Ok(value) = HeaderValue::from_str(&origin.0) {
|
||||
if let Ok(value) = HeaderValue::from_str(&backend_diagnostic_label(&origin.0)) {
|
||||
response.headers_mut().insert(LEGACY_BACKEND, value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -471,7 +471,7 @@ mod cache_fast_path_tests {
|
||||
response.headers_mut().insert(
|
||||
"cache-control",
|
||||
HeaderValue::from_static(match parts.uri.path() {
|
||||
"/private" => "private, max-age=600",
|
||||
"/private" | "/vary-cookie-private.css" => "private, max-age=600",
|
||||
"/backend-no-cache" | "/cache-headers-revalidate" => {
|
||||
"public, no-cache, max-age=600"
|
||||
}
|
||||
@@ -484,7 +484,14 @@ mod cache_fast_path_tests {
|
||||
);
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("vary", HeaderValue::from_static("X-Variant"));
|
||||
.insert("vary", HeaderValue::from_static(if parts.uri.path().starts_with("/vary-cookie") {
|
||||
"Cookie, X-Variant"
|
||||
} else {
|
||||
"X-Variant"
|
||||
}));
|
||||
if parts.uri.path() == "/vary-cookie-set.css" {
|
||||
response.headers_mut().insert("set-cookie", HeaderValue::from_static("session=private"));
|
||||
}
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-type", HeaderValue::from_static("text/plain"));
|
||||
@@ -518,6 +525,11 @@ mod cache_fast_path_tests {
|
||||
"authorization",
|
||||
"x-request-id",
|
||||
] {
|
||||
// Static asset responses in this fixture must not echo a
|
||||
// request cookie into a publicly shared response header.
|
||||
if name == "cookie" && parts.uri.path().starts_with("/vary-cookie") {
|
||||
continue;
|
||||
}
|
||||
if let Some(value) = parts.headers.get(name) {
|
||||
let echoed: http::HeaderName = format!("x-seen-{name}").parse().unwrap();
|
||||
response.headers_mut().insert(echoed, value.clone());
|
||||
@@ -920,6 +932,52 @@ mod cache_fast_path_tests {
|
||||
fixture.stop().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn public_static_vary_cookie_is_shared_but_other_vary_fields_remain() {
|
||||
let origin = origin().await;
|
||||
let mut config = config_for(origin.addr, true);
|
||||
config.cache.static_ignore_cookies = true;
|
||||
config.cache.static_ignore_vary_cookie = true;
|
||||
let fixture = Fixture::new(config).await;
|
||||
let first = fixture.get("/vary-cookie.css", &[("cookie", "session=alpha"), ("x-variant", "a")]).await;
|
||||
assert_eq!(first.headers["x-cache"], "MISS");
|
||||
assert_eq!(first.headers["vary"], "X-Variant");
|
||||
assert_eq!(first.body, "origin-a");
|
||||
let second = fixture.get("/vary-cookie.css", &[("cookie", "session=beta"), ("x-variant", "a")]).await;
|
||||
assert_eq!(second.headers["x-cache"], "HIT");
|
||||
assert_eq!(second.headers["vary"], "X-Variant");
|
||||
assert_eq!(second.body, "origin-a");
|
||||
let other = fixture.get("/vary-cookie.css", &[("cookie", "session=gamma"), ("x-variant", "b")]).await;
|
||||
assert_eq!(other.headers["x-cache"], "MISS");
|
||||
assert_eq!(other.body, "origin-b");
|
||||
assert_eq!(origin.requests.load(Ordering::Relaxed), 2);
|
||||
fixture.stop().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn static_vary_cookie_can_be_disabled_per_vhost_and_private_stays_private() {
|
||||
let origin = origin().await;
|
||||
let mut config = config_for(origin.addr, true);
|
||||
config.cache.static_ignore_cookies = true;
|
||||
config.cache.static_ignore_vary_cookie = true;
|
||||
config.vhosts[0].cache.static_ignore_vary_cookie = Some(false);
|
||||
let fixture = Fixture::new(config).await;
|
||||
let first = fixture.get("/vary-cookie.css", &[("cookie", "session=alpha")]).await;
|
||||
assert_eq!(first.headers["x-cache-reason"], "response_vary_cookie");
|
||||
assert_eq!(first.headers["vary"], "Cookie, X-Variant");
|
||||
let second = fixture.get("/vary-cookie.css", &[("cookie", "session=beta")]).await;
|
||||
assert_eq!(second.headers["x-cache"], "MISS");
|
||||
assert_eq!(origin.requests.load(Ordering::Relaxed), 2);
|
||||
fixture.change(|config| { config.vhosts[0].cache.static_ignore_vary_cookie = None; }).await;
|
||||
let private = fixture.get("/vary-cookie-private.css", &[]).await;
|
||||
assert_eq!(private.headers["vary"], "Cookie, X-Variant");
|
||||
assert_eq!(private.headers["x-cache"], "MISS");
|
||||
let set_cookie = fixture.get("/vary-cookie-set.css", &[]).await;
|
||||
assert_eq!(set_cookie.headers["vary"], "Cookie, X-Variant");
|
||||
assert!(set_cookie.headers.contains_key("set-cookie"));
|
||||
fixture.stop().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn proxy_cache_on_preserves_vary_private_revalidation_and_ranges() {
|
||||
let origin = origin().await;
|
||||
|
||||
@@ -3,7 +3,12 @@ if response.status() == StatusCode::NOT_MODIFIED && revalidation_sent {
|
||||
if let (Some(ticket), Some(cached)) =
|
||||
(cache_ticket.as_ref(), cached_revalidation.as_ref())
|
||||
{
|
||||
let merged = cached.merge_validation_headers(response.headers());
|
||||
let mut merged = cached.merge_validation_headers(response.headers());
|
||||
crate::cache::normalize_static_cookie_vary(
|
||||
StatusCode::OK, &mut merged, cache_settings,
|
||||
upstream_started.elapsed(), ignore_static_cookie,
|
||||
&crate::cache::ResponseOverrides::NONE,
|
||||
);
|
||||
let client_not_modified =
|
||||
crate::cache::conditional_not_modified(&client_conditionals, &merged);
|
||||
let mut revalidated = if let Some(mut hit) = state.cache.publish_revalidated(
|
||||
|
||||
@@ -119,6 +119,11 @@ let cache_rule_overrides = match (&cache_rule_context, cache_ticket.is_some()) {
|
||||
if cache_rule_overrides.strip_set_cookie {
|
||||
response.headers_mut().remove(::http::header::SET_COOKIE);
|
||||
}
|
||||
let origin_status = response.status();
|
||||
crate::cache::normalize_static_cookie_vary(
|
||||
origin_status, response.headers_mut(), cache_settings,
|
||||
upstream_started.elapsed(), ignore_static_cookie, &cache_rule_overrides,
|
||||
);
|
||||
let origin_plan = if cache_ticket.is_some()
|
||||
&& !(ignore_static_cookie && crate::cache::varies_on(response.headers(), "cookie"))
|
||||
{
|
||||
@@ -171,6 +176,10 @@ if let Some(pool) = &route.pool {
|
||||
if let Some(cookie) = active_affinity_cookie {
|
||||
parts.headers.append(::http::header::SET_COOKIE, cookie);
|
||||
}
|
||||
crate::cache::normalize_static_cookie_vary(
|
||||
parts.status, &mut parts.headers, cache_settings,
|
||||
upstream_started.elapsed(), ignore_static_cookie, &cache_rule_overrides,
|
||||
);
|
||||
let h3_tunnel = handshake.as_ref().is_some_and(|handshake| handshake.h3())
|
||||
&& upgraded.is_some();
|
||||
let h2_bridge_tunnel = handshake.as_ref().is_some_and(|handshake| handshake.h2())
|
||||
@@ -400,5 +409,10 @@ if !range_requested && handshake.is_none() {
|
||||
};
|
||||
}
|
||||
}
|
||||
let transformed_status = response.status();
|
||||
crate::cache::normalize_static_cookie_vary(
|
||||
transformed_status, response.headers_mut(), cache_settings,
|
||||
upstream_started.elapsed(), ignore_static_cookie, &cache_rule_overrides,
|
||||
);
|
||||
(origin_validation_headers, origin_plan, origin_reason, response, cache_rule_overrides)
|
||||
}
|
||||
@@ -206,6 +206,11 @@
|
||||
response.extensions_mut().insert(ResponseRulesApplied);
|
||||
response.extensions_mut().insert(StaticSourceResponse);
|
||||
|
||||
let response_status = response.status();
|
||||
crate::cache::normalize_static_cookie_vary(
|
||||
response_status, response.headers_mut(), cache_settings,
|
||||
started.elapsed(), ignore_cookie, &crate::cache::ResponseOverrides::NONE,
|
||||
);
|
||||
let origin_eligible_plan = if origin_safe
|
||||
&& !(ignore_cookie && crate::cache::varies_on(response.headers(), "cookie"))
|
||||
{
|
||||
|
||||
@@ -482,6 +482,52 @@ mod authority_tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn docker_backend_diagnostic_header_is_short_but_retains_agent_and_service_identity() {
|
||||
let mut response = Response::new(Body::empty());
|
||||
let raw_id = "docker-edge-node-012345abcdef/docker";
|
||||
response
|
||||
.extensions_mut()
|
||||
.insert(OriginBackend(raw_id.into()));
|
||||
response
|
||||
.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-rustproxy-backend-time"], "7.00ms");
|
||||
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!(cached.headers().get("x-rustproxy-backend-time").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_and_unrecognized_backend_ids_are_not_rewritten() {
|
||||
for id in [
|
||||
"app-primary/backend-1",
|
||||
"docker-edge-node-012345abcdef/backend-1",
|
||||
"docker-edge-node-not-a-hash/docker",
|
||||
"docker-edge-node-012345abcdeg/docker",
|
||||
"docker--012345abcdef/docker",
|
||||
"docker-edge-node-012345abcdef/docker#health",
|
||||
] {
|
||||
assert_eq!(backend_diagnostic_label(id).as_ref(), id);
|
||||
}
|
||||
assert_eq!(
|
||||
backend_diagnostic_label("docker-docker-agent-012345abcdef/docker").as_ref(),
|
||||
"docker-agent/012345abcdef"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_slash_routes_on_normalized_path_but_preserves_upstream_target() {
|
||||
let config = crate::config::demo_config("127.0.0.1:9000".parse().unwrap());
|
||||
|
||||
@@ -56,11 +56,27 @@ pub(super) fn finish_web_revalidation(
|
||||
force_cache: bool,
|
||||
apply_rules: impl FnOnce(&mut HeaderMap),
|
||||
) -> Option<WebRevalidated> {
|
||||
let origin_merged = web_merged_validation_headers(cached, validation);
|
||||
let mut origin_merged = web_merged_validation_headers(cached, validation);
|
||||
crate::cache::normalize_static_cookie_vary(
|
||||
StatusCode::OK,
|
||||
&mut origin_merged,
|
||||
settings,
|
||||
elapsed,
|
||||
ignore_cookie,
|
||||
&crate::cache::ResponseOverrides::NONE,
|
||||
);
|
||||
let origin_safe =
|
||||
crate::cache::plan(StatusCode::OK, &origin_merged, settings, elapsed).is_some();
|
||||
let mut merged = origin_merged;
|
||||
apply_rules(&mut merged);
|
||||
crate::cache::normalize_static_cookie_vary(
|
||||
StatusCode::OK,
|
||||
&mut merged,
|
||||
settings,
|
||||
elapsed,
|
||||
ignore_cookie,
|
||||
&crate::cache::ResponseOverrides::NONE,
|
||||
);
|
||||
if force_cache {
|
||||
if client.contains_key(::http::header::COOKIE) {
|
||||
merged.append(::http::header::VARY, HeaderValue::from_static("Cookie"));
|
||||
|
||||
Reference in new issue
Block a user