This commit is contained in:
Mateusz Gruszczyński committed 2026-11-25 15:47:34 +01:00
1 parent 6df256cdbb
commit 0d6249e383
159 files changed
+16737 -1971

No files matched your search

+10
View File
@@ -1,4 +1,5 @@
let cacheRulesEditor = null, cacheRulesRendered = "";
let globalPolicyEditor = null, globalPolicyRendered = "";
function renderSettings() {
if (!envelope) return; const config = envelope.config; window.rustProxySettings?.render();
if (!settingsDirty.has("listeners-form")) window.rustProxyIntegrations?.renderListeners();
@@ -83,6 +84,14 @@ function renderSettings() {
$("error-log-status").textContent = errorSink ? `${t("loggingQueue")}: ${fmt(errorSink.queue_dropped)} ${t("loggingDropped")} / ${fmt(errorSink.written)} ${t("loggingSent")} / ${fmt(errorSink.errors)} ${t("errors")} · ${t("loggingCapacity")}: ${fmt(errorSink.queue_capacity)}` : "";
if (!settingsDirty.has("forwarding-form")) { $("trusted-proxies").value = (config.forwarding?.trusted_proxies || []).join("\n"); $("trusted-proto").checked = !!config.forwarding?.trust_forwarded_proto; }
if (!settingsDirty.has("headers-form")) { for (const direction of ["request", "response"]) renderHeaderRules(direction, config.headers?.[direction] || []); }
if (!settingsDirty.has("policy-form") && window.rustProxyPolicy) {
const policyJson = JSON.stringify(config.policy || {});
if (!globalPolicyEditor || policyJson !== globalPolicyRendered) {
globalPolicyEditor = window.rustProxyPolicy.create({ value: config.policy || {}, scope: "global", onChange: () => setSettingsDirty("policy-form") });
globalPolicyRendered = policyJson;
$("global-policy-rules-root")?.replaceChildren(globalPolicyEditor.node);
}
}
const global = config.global_security || {};
if (!settingsDirty.has("global-security-form")) {
const country = global.country_access || {}, methods = global.method_policy || {}, content = global.content_type_policy || {}, rate = global.rate_limit || {};
@@ -471,6 +480,7 @@ bindSettingsForm("error-log-form", next => {
}, "logging", selectLoggingSection);
bindSettingsForm("forwarding-form", next => { next.forwarding = { trusted_proxies: $("trusted-proxies").value.split(/[\n,]/).map(s => s.trim()).filter(Boolean), trust_forwarded_proto: $("trusted-proto").checked }; }, "forwarding");
bindSettingsForm("headers-form", next => { next.headers = { request: collectHeaderRules("request"), response: collectHeaderRules("response") }; }, "headers");
bindSettingsForm("policy-form", next => { next.policy = globalPolicyEditor ? globalPolicyEditor.read() : (next.policy || {}); }, "policy");
$("log-format-preset").addEventListener("change", event => applyLoggingPreset(event.target.value));
$("error-log-enabled").addEventListener("change", syncErrorLogMode);
$("log-format-open").addEventListener("click", openLoggingBuilder);
+158 -33
View File
@@ -40,14 +40,71 @@ window.rustProxyCacheRules = (() => {
return { id, name: t("cacheRuleNewName"), enabled: true, stage, match: "all", conditions: [], actions: [{ type: ACTIONS[stage][0] }], stop: false, vhosts: [] };
}
function normalize(rule) {
return { id: rule.id, name: rule.name || "", enabled: rule.enabled !== false, stage: rule.stage || "request", match: rule.match || "all", conditions: (rule.conditions || []).map(c => ({ ...c, values: [...(c.values || [])] })), actions: (rule.actions || []).map(a => ({ ...a })), stop: !!rule.stop, hash_stage: !!rule.hash_stage, vhosts: [...(rule.vhosts || [])] };
return { ...structuredClone(rule), id: rule.id, name: rule.name || "", enabled: rule.enabled !== false, stage: rule.stage || "request", match: rule.match || "all", conditions: (rule.conditions || []).map(c => ({ ...structuredClone(c), values: [...(c.values || [])] })), actions: structuredClone(rule.actions || []), stop: !!rule.stop, hash_stage: !!rule.hash_stage, vhosts: [...(rule.vhosts || [])] };
}
function clean(rule, global) {
const out = { id: rule.id, name: rule.name, enabled: rule.enabled, stage: rule.stage, match: rule.match, conditions: rule.conditions.map(c => { const item = { field: c.field, operator: c.operator, values: c.operator === "exists" ? [] : c.values }; if (FIELDS[c.field]?.name) item.name = c.name || ""; if (c.negate) item.negate = true; return item; }), actions: rule.actions.map(a => ({ ...a })), stop: rule.stop };
const out = { ...structuredClone(rule), id: rule.id, name: rule.name, enabled: rule.enabled, stage: rule.stage, match: rule.match, conditions: rule.conditions.map(c => { const item = { ...structuredClone(c), field: c.field, operator: c.operator, values: c.operator === "exists" ? [] : [...c.values] }; if (FIELDS[c.field]?.name) item.name = c.name || ""; if (c.negate) item.negate = true; return item; }), actions: structuredClone(rule.actions), stop: rule.stop };
delete out.hash_stage;
delete out.vhosts;
if (rule.hash_stage) out.hash_stage = true;
if (global && rule.vhosts.length) out.vhosts = rule.vhosts;
if (global && rule.vhosts.length) out.vhosts = [...rule.vhosts];
return out;
}
const flowMarker = rule => Array.isArray(rule.vcl_flow?.branches) && rule.vcl_flow.branches.length > 0;
function flowFailure(rule) { return new Error(t("cacheRulesFlowInvalid").replace("{rule}", rule?.name || rule?.id || "VCL")); }
// Structural checks only. Conditions/actions are evaluated and validated by
// Rust; this prevents UI operations from splitting or silently flattening a
// saved imported program before it reaches that compiler.
function validateFlow(rules) {
const groups = new Map();
rules.forEach((rule, position) => {
const flow = rule.vcl_flow;
if (!flow) return;
if (flow.version !== 1 || typeof flow.group !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(flow.group) ||
!Number.isInteger(flow.index) || flow.index < 0 || flow.index >= MAX_RULES || !Number.isInteger(flow.count) || flow.count < 1 || flow.count > MAX_RULES ||
!Array.isArray(flow.guards || []) || (flow.guards || []).length > 16 ||
!Array.isArray(flow.branches || []) || (flow.branches || []).length > 16) throw flowFailure(rule);
if (!groups.has(flow.group)) groups.set(flow.group, []);
groups.get(flow.group).push({ rule, position });
});
for (const members of groups.values()) {
const first = members[0], count = first.rule.vcl_flow.count;
if (members.length !== count) throw flowFailure(first.rule);
let conditionCount = 0;
const activeEntries = new Set(), lastBranches = new Map();
members.forEach(({ rule, position }, index) => {
const flow = rule.vcl_flow, guards = flow.guards || [];
if (position !== first.position + index || flow.index !== index || flow.count !== count ||
rule.enabled !== first.rule.enabled || JSON.stringify(rule.vhosts) !== JSON.stringify(first.rule.vhosts) ||
rule.conditions.length || rule.match !== "all") throw flowFailure(rule);
if (flowMarker(rule) && (rule.actions.length || rule.stop)) throw flowFailure(rule);
guards.forEach((guard, depth) => {
if (!guard || !Number.isInteger(guard.entry) || !Number.isInteger(guard.branch)) throw flowFailure(rule);
const entry = members[guard.entry]?.rule;
const ancestors = entry?.vcl_flow?.guards || [];
if (guard.entry < 0 || guard.entry >= index || !activeEntries.has(guard.entry) || guard.branch < 0 || !entry || !flowMarker(entry) ||
guard.branch >= entry.vcl_flow.branches.length || rule.stage !== entry.stage || rule.hash_stage !== entry.hash_stage ||
ancestors.length !== depth || ancestors.some((ancestor, i) => ancestor.entry !== guards[i].entry || ancestor.branch !== guards[i].branch) ||
guard.branch < (lastBranches.get(guard.entry) ?? 0)) throw flowFailure(rule);
lastBranches.set(guard.entry, guard.branch);
});
for (const entry of activeEntries) if (!guards.some(guard => guard.entry === entry)) activeEntries.delete(entry);
if (flowMarker(rule)) activeEntries.add(index);
(flow.branches || []).forEach((branch, branchIndex, branches) => {
if (!branch || !Array.isArray(branch.any) || !branch.any.length || branch.any.length > 128 ||
branch.any.some(clause => !Array.isArray(clause) || clause.length > 16)) throw flowFailure(rule);
if (branch.any.some(clause => !clause.length) && (branch.any.length !== 1 || branchIndex !== branches.length - 1)) throw flowFailure(rule);
conditionCount += branch.any.reduce((sum, clause) => sum + clause.length, 0);
if (conditionCount > 2048) throw flowFailure(rule);
});
});
}
}
function newFlowGroup(taken) {
let group;
do { group = `vcl-${Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, "0")).join("")}`; } while (taken.has(group));
taken.add(group); return group;
}
const esc = value => String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
const reEsc = value => String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const globRe = value => String(value).split("*").map(reEsc).join(".*");
@@ -132,6 +189,7 @@ window.rustProxyCacheRules = (() => {
return conditions.length ? `${description}\nif (${joined}) {\n${body}\n}` : `${description}\n${body.replace(/^ {4}/gm, "")}`;
}
function exportVcl(rules) {
if (rules.some(rule => rule.vcl_flow)) throw new Error(t("cacheRulesFlowExportJson"));
const subs = { request: "vcl_recv", response: "vcl_backend_response", deliver: "vcl_deliver" };
const blocks = [
"vcl 4.1;",
@@ -502,12 +560,29 @@ window.rustProxyCacheRules = (() => {
for (const isolated of [tester.node, importBox, catalog]) for (const type of ["input", "change"]) isolated.addEventListener(type, event => event.stopPropagation());
root.addEventListener("keydown", event => { if (event.key === "Enter" && event.target.matches?.("input:not([type=checkbox])")) event.preventDefault(); });
function taken() { return new Set(rules.map(rule => rule.id)); }
function unit(index) {
const group = rules[index]?.vcl_flow?.group;
if (!group) return { start: index, length: 1, members: [rules[index]] };
const start = rules.findIndex(rule => rule.vcl_flow?.group === group);
const members = rules.filter(rule => rule.vcl_flow?.group === group);
return { start, length: members.length, members };
}
function safelyEditFlow(action) {
try { validateFlow(rules); action(); } catch (error) { render(); toast(error.message, true); }
}
function updateExport() {
const hasFlow = rules.some(rule => rule.vcl_flow);
exportButton.textContent = t(hasFlow ? "cacheRulesExportJson" : "cacheRulesExportVcl");
exportSummary.textContent = t(hasFlow ? "cacheRulesJsonPreview" : "cacheRulesVclPreview");
exportPre.textContent = hasFlow ? JSON.stringify(rules.map(rule => clean(rule, scope === "global")), null, 2) : exportVcl(rules);
}
if (scope === "global") {
void loadTargets();
document.addEventListener("rustproxy-cache-targets", () => { if (root.isConnected && open.size) render(); });
}
function renderNotices() {
notices.replaceChildren();
if (rules.some(rule => rule.vcl_flow)) notices.append(el("p", t("cacheRulesFlowHelp"), "fine cache-rules-notice"));
if (scope !== "vhost") return;
const globals = applicableGlobals(vhostId);
if (ignoreGlobal) { if (globals.length) notices.append(el("p", t("cacheRulesGlobalSkipped").replace("{count}", globals.length), "fine cache-rules-notice")); return; }
@@ -524,11 +599,21 @@ window.rustProxyCacheRules = (() => {
list.replaceChildren(...rules.map((rule, index) => ruleCard(rule, index)));
empty.hidden = rules.length > 0;
addButton.disabled = rules.length >= MAX_RULES;
exportPre.textContent = exportVcl(rules);
updateExport();
renderNotices();
}
function move(from, to) { if (to < 0 || to >= rules.length) return; const [item] = rules.splice(from, 1); rules.splice(to, 0, item); render(); changed(); }
function move(from, to) {
if (from < 0 || from >= rules.length || to < 0 || to >= rules.length) return;
safelyEditFlow(() => {
const source = unit(from), target = unit(to);
if (source.start === target.start) return;
const destination = source.start < target.start ? target.start + target.length - source.length : target.start;
const moved = rules.splice(source.start, source.length);
rules.splice(destination, 0, ...moved); render(); changed();
});
}
function ruleCard(rule, index) {
const grouped = !!rule.vcl_flow, block = unit(index);
const card = el("div", undefined, `cache-rule${rule.enabled ? "" : " is-disabled"}${open.has(rule.id) ? " is-open" : ""}`); card.draggable = true; card.dataset.index = index;
card.addEventListener("dragstart", event => { event.dataTransfer.setData("text/plain", String(index)); card.classList.add("is-dragging"); });
card.addEventListener("dragend", () => card.classList.remove("is-dragging"));
@@ -536,23 +621,36 @@ window.rustProxyCacheRules = (() => {
card.addEventListener("dragleave", () => card.classList.remove("is-drop"));
card.addEventListener("drop", event => { event.preventDefault(); card.classList.remove("is-drop"); const from = Number(event.dataTransfer.getData("text/plain")); if (Number.isInteger(from) && from !== index) move(from, index); });
const head = el("div", undefined, "cache-rule-head");
const grip = el("span", "⠿", "cache-rule-grip"); grip.title = t("cacheRulesDrag");
const grip = el("span", "⠿", "cache-rule-grip"); grip.title = t(grouped ? "cacheRulesFlowMove" : "cacheRulesDrag");
const toggle = el("input", undefined, "switch"); toggle.type = "checkbox"; toggle.checked = rule.enabled; toggle.setAttribute("aria-label", t("enabled"));
toggle.addEventListener("change", () => { rule.enabled = toggle.checked; card.classList.toggle("is-disabled", !rule.enabled); exportPre.textContent = exportVcl(rules); changed(); });
toggle.addEventListener("change", () => safelyEditFlow(() => { for (const item of block.members) item.enabled = toggle.checked; render(); changed(); }));
const title = el("button", undefined, "cache-rule-title"); title.type = "button"; title.dataset.uiIconName = "none";
title.append(el("b", rule.name || rule.id), el("span", t(STAGE_KEYS[rule.stage]), "pill cache-rule-stage"), el("span", summary(rule), "fine cache-rule-summary"));
title.append(el("b", rule.name || rule.id), el("span", t(STAGE_KEYS[rule.stage]), "pill cache-rule-stage"), el("span", flowMarker(rule) ? t("cacheRuleFlowBranch") : summary(rule), "fine cache-rule-summary"));
title.addEventListener("click", () => { if (open.has(rule.id)) open.delete(rule.id); else open.add(rule.id); render(); });
const hitKey = scope === "vhost" ? `vhost:${vhostId}:${rule.id}` : `global:${rule.id}`;
const hitCount = el("span", hits[hitKey] != null ? t("cacheRulesHits").replace("{count}", fmt(hits[hitKey])) : "", "fine cache-rule-hits");
hitCount.dataset.hitKey = hitKey;
const actions = el("span", undefined, "cache-rule-actions");
const up = el("button", "↑", "quiet"); up.type = "button"; up.disabled = index === 0; up.setAttribute("aria-label", t("cacheRulesMoveUp")); up.addEventListener("click", () => move(index, index - 1));
const down = el("button", "↓", "quiet"); down.type = "button"; down.disabled = index === rules.length - 1; down.setAttribute("aria-label", t("cacheRulesMoveDown")); down.addEventListener("click", () => move(index, index + 1));
const copy = el("button", t("cacheRulesDuplicate"), "quiet"); copy.type = "button"; copy.addEventListener("click", () => { if (rules.length >= MAX_RULES) return; const clone = normalize(structuredClone(rule)); clone.id = slug(`${rule.id}-copy`, taken()); clone.name = `${rule.name || rule.id} (${t("cacheRulesCopySuffix")})`; rules.splice(index + 1, 0, clone); open.add(clone.id); render(); changed(); });
const remove = el("button", t("remove"), "quiet danger"); remove.type = "button"; remove.addEventListener("click", () => { rules.splice(index, 1); open.delete(rule.id); render(); changed(); });
const up = el("button", "↑", "quiet"); up.type = "button"; up.disabled = block.start === 0; up.setAttribute("aria-label", t("cacheRulesMoveUp")); up.addEventListener("click", () => move(index, block.start - 1));
const down = el("button", "↓", "quiet"); down.type = "button"; down.disabled = block.start + block.length === rules.length; down.setAttribute("aria-label", t("cacheRulesMoveDown")); down.addEventListener("click", () => move(index, block.start + block.length));
const copy = el("button", t(grouped ? "cacheRulesFlowDuplicate" : "cacheRulesDuplicate"), "quiet"); copy.type = "button"; copy.disabled = rules.length + block.length > MAX_RULES;
copy.addEventListener("click", () => safelyEditFlow(() => {
if (rules.length + block.length > MAX_RULES) { toast(t("cacheRulesLimit"), true); return; }
const ids = taken(), group = grouped ? newFlowGroup(new Set(rules.map(item => item.vcl_flow?.group).filter(Boolean))) : null;
const copies = block.members.map(item => {
const clone = normalize(item); clone.id = slug(`${item.id}-copy`, ids); ids.add(clone.id);
clone.name = `${item.name || item.id} (${t("cacheRulesCopySuffix")})`;
if (group) clone.vcl_flow.group = group;
return clone;
});
rules.splice(block.start + block.length, 0, ...copies); open.add(copies[0].id); render(); changed();
}));
const remove = el("button", t(grouped ? "cacheRulesFlowRemove" : "remove"), "quiet danger"); remove.type = "button";
remove.addEventListener("click", () => safelyEditFlow(() => { rules.splice(block.start, block.length); for (const item of block.members) open.delete(item.id); render(); changed(); }));
actions.append(up, down, copy, remove);
head.append(grip, toggle, title, hitCount, actions);
card.append(head);
if (grouped) card.append(el("p", t("cacheRuleFlowPart").replace("{index}", rule.vcl_flow.index + 1).replace("{count}", rule.vcl_flow.count), "fine cache-rules-notice cache-rule-note"));
if (scope === "global") for (const note of globalOverrideNotes(rule)) card.append(el("p", note, "fine cache-rules-notice cache-rule-note"));
if (cookieOnlyPass(rule)) {
// Controlled migration: an explicit pass is never relaxed automatically.
@@ -568,16 +666,19 @@ window.rustProxyCacheRules = (() => {
}
function ruleEditor(rule) {
const body = el("div", undefined, "cache-rule-body");
const grouped = !!rule.vcl_flow, marker = flowMarker(rule);
const grid = el("div", undefined, "cache-rule-grid");
const name = textInput(rule.name, t("cacheRuleNamePlaceholder")); name.maxLength = 96;
name.addEventListener("input", () => { rule.name = name.value; changed(); syncPreview(); });
const id = textInput(rule.id, "", "mono"); id.maxLength = 64; id.pattern = "[A-Za-z0-9_\\-]{1,64}";
id.addEventListener("change", () => { const value = id.value.trim(); if (!/^[A-Za-z0-9_-]{1,64}$/.test(value) || (value !== rule.id && taken().has(value))) { id.value = rule.id; toast(t("cacheRuleIdInvalid"), true); return; } open.delete(rule.id); rule.id = value; open.add(value); changed(); });
const stage = select(STAGES.map(value => [value, t(STAGE_KEYS[value])]), rule.stage, t("cacheRuleStage"));
stage.addEventListener("change", () => { rule.stage = stage.value; if (rule.stage !== "request") rule.hash_stage = false; rule.actions = rule.actions.filter(a => ACTIONS[rule.stage].includes(a.type)); if (!rule.actions.length && !rule.stop) rule.actions = [{ type: ACTIONS[rule.stage][0] }]; rule.conditions = rule.conditions.filter(c => FIELDS[c.field].stages.includes(rule.stage)); render(); changed(); });
stage.disabled = grouped;
stage.addEventListener("change", () => { if (grouped) { stage.value = rule.stage; toast(t("cacheRulesFlowStructureLocked"), true); return; } rule.stage = stage.value; if (rule.stage !== "request") rule.hash_stage = false; rule.actions = rule.actions.filter(a => ACTIONS[rule.stage].includes(a.type)); if (!rule.actions.length && !rule.stop) rule.actions = [{ type: ACTIONS[rule.stage][0] }]; rule.conditions = rule.conditions.filter(c => FIELDS[c.field].stages.includes(rule.stage)); render(); changed(); });
const match = select([["all", t("cacheRuleMatchAll")], ["any", t("cacheRuleMatchAny")]], rule.match, t("cacheRuleMatch"));
match.addEventListener("change", () => { rule.match = match.value; changed(); syncPreview(); });
const stop = el("input", undefined, "switch"); stop.type = "checkbox"; stop.checked = rule.stop; stop.addEventListener("change", () => { rule.stop = stop.checked; changed(); });
match.disabled = grouped;
match.addEventListener("change", () => { if (grouped) { match.value = rule.match; toast(t("cacheRulesFlowStructureLocked"), true); return; } rule.match = match.value; changed(); syncPreview(); });
const stop = el("input", undefined, "switch"); stop.type = "checkbox"; stop.checked = rule.stop; stop.disabled = grouped; stop.addEventListener("change", () => { if (grouped) { stop.checked = rule.stop; toast(t("cacheRulesFlowStructureLocked"), true); return; } rule.stop = stop.checked; changed(); });
const labeled = (key, control, help) => { const label = el("label", undefined, "cache-rule-field"); label.append(el("span", t(key)), control); if (help) label.append(el("small", t(help), "fine")); return label; };
const stopLabel = el("label", undefined, "check cache-rule-stop"); stopLabel.append(stop, el("span", t("cacheRuleStop")));
grid.append(labeled("cacheRuleName", name), labeled("cacheRuleId", id), labeled("cacheRuleStage", stage, `cacheRuleStageHelp${rule.stage[0].toUpperCase()}${rule.stage.slice(1)}`), labeled("cacheRuleMatch", match), stopLabel);
@@ -585,32 +686,40 @@ window.rustProxyCacheRules = (() => {
if (scope === "global") {
const vhostItems = targetList().map(target => ({ id: target.id, title: targetTitle(target), detail: target.docker ? target.id : (target.hosts || []).slice(0, 3).join(", "), search: (target.hosts || []).join(" "), badge: target.docker ? "Docker" : "", badgeClass: "is-allow" }));
const picker = window.rustProxyChoicePicker.create({ className: "cache-rule-vhosts", selected: rule.vhosts, items: vhostItems, limit: 64, labels: { choose: "cacheRuleVhostsAll", selected: "cacheRuleVhostsSelected", none: "cacheRuleVhostsNone", empty: "cacheRuleVhostsEmpty" } });
picker.addEventListener("choicechange", event => { rule.vhosts = event.detail || []; exportPre.textContent = exportVcl(rules); });
picker.addEventListener("change", changed);
picker.addEventListener("choicechange", event => {
if (grouped) safelyEditFlow(() => { for (const item of unit(rules.indexOf(rule)).members) item.vhosts = [...(event.detail || [])]; render(); changed(); });
else { rule.vhosts = event.detail || []; updateExport(); }
});
picker.addEventListener("change", () => { if (!grouped) changed(); });
const field = el("div", undefined, "cache-rule-field cache-rule-vhosts-field"); field.append(el("span", t("cacheRuleVhosts")), picker, el("small", t("cacheRuleVhostsHelp"), "fine"));
body.append(field);
}
const conditions = el("div", undefined, "cache-rule-section");
conditions.append(el("h4", t("cacheRuleConditions")));
const conditionRows = el("div", undefined, "cache-rule-rows");
rule.conditions.forEach((condition, index) => conditionRows.append(conditionRow(rule, condition, index)));
if (!rule.conditions.length) conditionRows.append(el("p", t("cacheRuleNoConditions"), "fine"));
if (grouped) {
conditionRows.append(el("p", t("cacheRulesFlowStructureLocked"), "fine"), el("pre", JSON.stringify(rule.vcl_flow, null, 2), "metrics-example mono cache-rule-flow"));
} else {
rule.conditions.forEach((condition, index) => conditionRows.append(conditionRow(rule, condition, index)));
if (!rule.conditions.length) conditionRows.append(el("p", t("cacheRuleNoConditions"), "fine"));
}
const addCondition = el("button", t("cacheRuleAddCondition"), "outline"); addCondition.type = "button";
addCondition.disabled = rule.conditions.length >= 16;
addCondition.addEventListener("click", () => { rule.conditions.push({ field: "path", operator: "prefix", values: [] }); render(); changed(); });
addCondition.disabled = grouped || rule.conditions.length >= 16;
addCondition.addEventListener("click", () => { if (grouped) return; rule.conditions.push({ field: "path", operator: "prefix", values: [] }); render(); changed(); });
conditions.append(conditionRows, addCondition);
const actionsSection = el("div", undefined, "cache-rule-section");
actionsSection.append(el("h4", t("cacheRuleActions")));
const actionRows = el("div", undefined, "cache-rule-rows");
rule.actions.forEach((action, index) => actionRows.append(actionRow(rule, action, index)));
const addAction = el("button", t("cacheRuleAddAction"), "outline"); addAction.type = "button";
addAction.disabled = rule.actions.length >= 16;
addAction.addEventListener("click", () => { const used = new Set(rule.actions.map(a => a.type)); rule.actions.push({ type: ACTIONS[rule.stage].find(type => !used.has(type)) || ACTIONS[rule.stage][0] }); render(); changed(); });
addAction.disabled = marker || rule.actions.length >= 16;
addAction.addEventListener("click", () => { if (marker) return; const used = new Set(rule.actions.map(a => a.type)); rule.actions.push({ type: ACTIONS[rule.stage].find(type => !used.has(type)) || ACTIONS[rule.stage][0] }); render(); changed(); });
if (marker) actionRows.append(el("p", t("cacheRuleFlowBranch"), "fine"));
actionsSection.append(actionRows, addAction);
const preview = el("pre", "", "metrics-example mono cache-rule-vcl");
const syncPreview = () => { preview.textContent = ruleVcl(rule); exportPre.textContent = exportVcl(rules); };
const syncPreview = () => { preview.textContent = grouped ? JSON.stringify(clean(rule, scope === "global"), null, 2) : ruleVcl(rule); updateExport(); };
body.addEventListener("input", syncPreview); body.addEventListener("change", syncPreview);
const previewWrap = el("div", undefined, "cache-rule-section"); previewWrap.append(el("h4", t("cacheRuleVcl")), preview);
const previewWrap = el("div", undefined, "cache-rule-section"); previewWrap.append(el("h4", t(grouped ? "cacheRulesJsonPreview" : "cacheRuleVcl")), preview);
body.append(conditions, actionsSection, previewWrap);
syncPreview();
return body;
@@ -745,10 +854,18 @@ window.rustProxyCacheRules = (() => {
}
function addRules(items, templateKey = "") {
if (rules.length + items.length > MAX_RULES) { toast(t("cacheRulesLimit"), true); return 0; }
const ids = taken();
const ids = taken(), groups = new Set(rules.map(rule => rule.vcl_flow?.group).filter(Boolean)), remappedGroups = new Map();
const addedRules = items.map(item => {
const rule = normalize({ ...item, id: slug(item.id || item.name, ids), vhosts: scope === "global" ? item.vhosts || [] : [] });
ids.add(rule.id);
if (rule.vcl_flow) {
const original = rule.vcl_flow.group;
if (!remappedGroups.has(original)) {
const group = groups.has(original) ? newFlowGroup(groups) : original;
remappedGroups.set(original, group); groups.add(group);
}
rule.vcl_flow.group = remappedGroups.get(original);
}
return rule;
});
// The parent-name rule must execute before the independent CDN cookie
@@ -756,8 +873,10 @@ window.rustProxyCacheRules = (() => {
const cdnIndex = templateKey === "publiccookies" ? rules.findIndex(rule =>
/^CDN:/.test(rule.name || "") && rule.conditions.some(c => c.field === "header" && String(c.name || "").toLowerCase() === "cookie") &&
rule.actions.some(a => a.type === "strip_cookies" || a.type === "pass" || a.type === "cookie_pass")) : -1;
if (cdnIndex >= 0) rules.splice(cdnIndex, 0, ...addedRules);
else rules.push(...addedRules);
const candidate = [...rules];
candidate.splice(cdnIndex >= 0 ? unit(cdnIndex).start : candidate.length, 0, ...addedRules);
validateFlow(candidate);
rules = candidate;
if (addedRules.length) open.add(addedRules[0].id);
render();
if (addedRules.length) changed();
@@ -766,7 +885,9 @@ window.rustProxyCacheRules = (() => {
function addTemplate(key) {
const make = TEMPLATES[key];
if (!make || !templateAvailable(key, scope)) return;
const items = make(), added = addRules(items, key);
const items = make();
let added;
try { added = addRules(items, key); } catch (error) { toast(error.message, true); return; }
if (!added) return;
const needsReview = items.some(item => item.enabled === false);
toast(t(needsReview ? "cacheRuleCatalogAddedDisabled" : "cacheRulesTemplateAdded").replace("{count}", added));
@@ -843,15 +964,19 @@ window.rustProxyCacheRules = (() => {
});
importApply.addEventListener("click", () => {
if (!pendingImport) return;
const added = addRules(pendingImport);
resetImportPreview();
importResult.append(el("p", t("cacheRulesImportDone").replace("{count}", added), "fine is-ok"));
try {
const added = addRules(pendingImport);
if (!added) return;
resetImportPreview();
importResult.append(el("p", t("cacheRulesImportDone").replace("{count}", added), "fine is-ok"));
} catch (error) { importResult.append(el("p", error.message, "fine is-error")); }
});
exportButton.addEventListener("click", async () => { exportBox.open = true; exportBox.scrollIntoView?.({ block: "nearest", behavior: "smooth" }); try { await navigator.clipboard.writeText(exportPre.textContent); toast(t("copied")); } catch { } });
ignoreBox.addEventListener("change", () => { ignoreGlobal = ignoreBox.checked; renderNotices(); changed(); });
function read() {
validateFlow(rules);
for (const rule of rules) {
if (!rule.actions.length && !rule.stop) throw new Error(t("cacheRuleNeedsAction").replace("{rule}", rule.name || rule.id));
if (!rule.actions.length && !rule.stop && !flowMarker(rule)) throw new Error(t("cacheRuleNeedsAction").replace("{rule}", rule.name || rule.id));
for (const c of rule.conditions) {
if (FIELDS[c.field].name && !c.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id));
if (c.operator !== "exists" && !(c.values || []).length) throw new Error(t("cacheRuleNeedsValue").replace("{rule}", rule.name || rule.id));
+96
View File
@@ -0,0 +1,96 @@
/* Shared global, vhost, Docker and location HTTP policy editor. */
.http-policy-editor,
.policy-visual,
.policy-rules,
.policy-detail-body,
.policy-actions,
.policy-test-output {
display: grid;
gap: 12px;
min-width: 0;
}
.http-policy-editor { width: 100%; margin-top: 10px; }
.http-policy-editor p,
.http-policy-editor h4 { margin: 0; }
.http-policy-editor [hidden] { display: none !important; }
.policy-toolbar,
.policy-row-controls,
.policy-rule-heading {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
}
.policy-toolbar > button,
.policy-row-controls > button { width: auto; }
.policy-toolbar > [aria-pressed="true"] { border-color: var(--accent); color: var(--accent); }
.policy-guide { margin-left: auto; }
.policy-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; min-width: 0; }
.policy-wide { grid-column: 1 / -1; }
.policy-field { display: grid; gap: 5px; min-width: 0; color: var(--muted); font-size: 12px; }
.policy-field > :is(input, select, textarea) { min-width: 0; width: 100%; margin: 0; }
.policy-field > textarea { resize: vertical; font-family: ui-monospace, monospace; font-size: 12px; line-height: 1.5; }
.policy-check { display: flex; gap: 8px; align-items: center; }
.policy-check > input { width: auto; flex: 0 0 auto; }
.policy-rule {
display: grid;
gap: 14px;
min-width: 0;
padding: 16px;
border: 1px solid var(--line);
border-left: 3px solid var(--accent);
background: var(--panel2);
border-radius: var(--rp-radius-surface, 0px);
}
.policy-rule.is-disabled { border-left-color: var(--muted); }
.policy-rule.is-disabled .policy-order { color: var(--muted); }
.policy-rule-heading > .policy-field:not(.policy-check) { flex: 1 1 180px; }
.policy-order { color: var(--accent); }
.policy-action {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(155px, 1fr));
gap: 10px;
align-items: end;
padding: 12px;
background: var(--panel);
border: 1px solid var(--line);
min-width: 0;
}
.policy-action > .policy-row-controls { grid-column: 1 / -1; justify-content: flex-end; }
.http-policy-editor details { min-width: 0; border: 1px solid var(--line); border-radius: var(--rp-radius-surface, 0px); }
.http-policy-editor details > summary { padding: 10px 12px; cursor: pointer; color: var(--text); font-weight: 600; }
.policy-detail-body { padding: 12px; border-top: 1px solid var(--line); }
.policy-rule > button,
.policy-detail-body > button { justify-self: start; }
.policy-result {
margin: 0;
padding: 12px;
max-height: 420px;
overflow: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
background: var(--code-bg);
border: 1px solid var(--line);
color: var(--text);
font-size: 12px;
line-height: 1.5;
}
.policy-message { padding: 10px; border: 1px solid var(--line); white-space: pre-wrap; }
.policy-message.is-error { color: var(--red); border-color: var(--danger-line-strong); }
.policy-trace { width: 100%; border-collapse: collapse; font-size: 12px; table-layout: fixed; }
.policy-trace th,
.policy-trace td { padding: 8px; text-align: left; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; white-space: pre-wrap; }
.policy-trace .is-matched td:first-child { color: var(--green); }
.policy-trace .is-skipped { color: var(--muted); }
.policy-counter-scroll { overflow: auto; display: grid; gap: 10px; }
.policy-counter-scroll > table { min-width: 520px; }
.docker-policy-editor { margin: 12px 0; border: 1px solid var(--line); padding: 12px; }
.docker-policy-editor > summary { cursor: pointer; font-weight: 600; }
@media (max-width: 760px) {
.policy-grid { grid-template-columns: 1fr; }
.policy-rule { padding: 12px; }
.policy-rule-heading > .policy-row-controls { width: 100%; justify-content: flex-end; }
.policy-action { grid-template-columns: minmax(0, 1fr); }
.policy-toolbar > button { flex: 1 1 auto; }
.policy-guide { margin: 0; }
}
+1 -3
View File
@@ -62,14 +62,12 @@ From the repository root:
```bash
python3 scripts/build/panel_css.py --check
python3 tools/dev/test_panel_css.py
python3 scripts/preflight.py
python3 scripts/audit_css_usage.py --strict
bash dev.sh check
bash dev.sh test
```
The first three commands require only Python 3.10+. The optional CSS audit
The stylesheet check requires only Python 3.10+. The optional CSS audit
requires `tinycss2` and `cssselect2`; install them in a development environment,
not on the deployed server. `--structure-json PATH` records repeated selectors,
conditional blocks, properties and identical declaration blocks. `--json PATH`
+1
View File
@@ -6,6 +6,7 @@
"30-overview.css",
"40-editors.css",
"50-settings.css",
"55-policy.css",
"60-monitoring.css",
"70-responsive.css"
]
+7 -2
View File
@@ -882,6 +882,11 @@
grid.append(checkboxField("vhTimingHeaders", box("docker-timing-headers", assignment?.timing_headers)), checkboxField("vhBackendHeader", box("docker-backend-header", assignment?.backend_header)), checkboxField("vhBackendTimingHeader", box("docker-backend-timing-header", assignment?.backend_timing_header)));
details.append(grid); return details;
}
function policyEditor(assignment, row) {
const details = el("details", undefined, "docker-policy-editor"); details.append(el("summary", t("policyTitle")));
const policy = window.rustProxyPolicy.create({ value: assignment?.policy || {}, scope: "vhost", onChange: () => row.classList.add("is-dirty") });
details.append(policy.node); row._readPolicy = () => policy.read(); return details;
}
function collectDiagnostics(row) {
const on = cls => row.querySelector(cls)?.checked === true;
return { timing_headers: on(".docker-timing-headers"), backend_header: on(".docker-backend-header"), backend_timing_header: on(".docker-backend-timing-header") };
@@ -903,7 +908,7 @@
allow_certificate_mismatch: row.querySelector(".docker-cert-mismatch")?.checked === true,
acl: inline && row.querySelector(".docker-acl-public")?.checked !== true ? { default: row.querySelector(".docker-acl-default").value, rules: parseRules(row.querySelector(".docker-acl-rules").value) } : null,
proxy_timeouts: { connect_timeout_seconds: Number(row.querySelector(".docker-proxy-connect").value), response_header_timeout_seconds: Number(row.querySelector(".docker-proxy-header").value), read_timeout_seconds: Number(row.querySelector(".docker-proxy-read").value), send_timeout_seconds: Number(row.querySelector(".docker-proxy-send").value) },
health_check: collectHealth(row), passive_health: collectPassiveHealth(row)
health_check: collectHealth(row), passive_health: collectPassiveHealth(row), policy: row._readPolicy?.() || {}
};
}
async function saveAssignment(agentId, row, publish) {
@@ -1063,7 +1068,7 @@
protocolOptions.append(h1, checkboxField("dockerHttp2Enabled", h2Enabled), checkboxField("dockerHttp3Enabled", h3Enabled));
protocolBox.append(protocolSummary, protocolOptions);
route.append(hostField, aliases.node, backendIpSettings, labeled("dockerBackendScheme", scheme), switches); syncHostHelp();
editor.append(route, protocolBox, aclEditor(assignment, agent), securityEditor(assignment), cacheEditor(assignment, agent, key, cacheEnabled, () => expandedHost(host.value.trim() || technical, domainSelect.value)), diagnosticsEditor(assignment), timeoutEditor(assignment), healthEditor(assignment), passiveHealthEditor(assignment));
editor.append(route, protocolBox, aclEditor(assignment, agent), securityEditor(assignment), cacheEditor(assignment, agent, key, cacheEnabled, () => expandedHost(host.value.trim() || technical, domainSelect.value)), diagnosticsEditor(assignment), policyEditor(assignment, row), timeoutEditor(assignment), healthEditor(assignment), passiveHealthEditor(assignment));
const actions = el("div", undefined, "docker-service-actions"); apply = el("button", t("dockerApplyService"), "outline docker-apply"); apply.type = "button"; apply.disabled = !publish.checked; apply.addEventListener("click", async () => { apply.disabled = true; try { await saveAssignment(agent.id, row, true); } catch (error) { toast(error.message, true); } finally { if (row.isConnected) apply.disabled = !publish.checked; } }); actions.append(apply); editor.append(actions);
function updateHint() { syncCertificateHint(); editorHint.textContent = hintFor({ hostname: host.value.trim(), domain: domainSelect.value, targetLabel: target.selectedOptions?.[0]?.textContent || t("dockerBackendIpAuto"), scheme: scheme.value, h2: h2Enabled.checked, h3: h3Enabled.checked, aliasCount: aliases.count() }); } updateHint();
for (const control of [host, aliases.input, target, scheme]) { control.addEventListener("input", updateHint); control.addEventListener("change", updateHint); }
+12
View File
@@ -2513,6 +2513,8 @@
data-i18n="globalSecurityHeaders" type="button">Security headers</button>
<button aria-selected="false" data-policy-settings-tab="headers"
data-i18n="customHeaders" type="button">Global custom headers</button>
<button aria-selected="false" data-policy-settings-tab="policy"
data-i18n="policyTitle" role="tab" tabindex="-1" type="button">HTTP policies</button>
<button aria-selected="false" data-policy-settings-tab="response"
data-i18n="responseSettings" type="button">Client response</button>
</nav>
@@ -2726,6 +2728,16 @@
type="submit">Apply header rules</button></div>
</form>
</div>
<div data-policy-settings-page="policy" hidden="">
<form class="card edit-form" id="policy-form">
<div class="card-heading">
<h2 data-i18n="policyTitle">HTTP policies</h2>
<span class="pill live" data-i18n="hotApply">LIVE APPLY</span>
</div>
<div id="global-policy-rules-root"></div>
<div class="form-actions"><button class="primary" data-i18n="policySave" type="submit">Apply HTTP policies</button></div>
</form>
</div>
<div data-policy-settings-page="response" hidden="">
<form class="card edit-form" id="response-form">
<div class="card-heading">
+286
View File
@@ -0,0 +1,286 @@
"use strict";
// The editor only builds configuration. Import, validation and test evaluation use
// the same Rust compiler/evaluator as live traffic; there is no JS policy engine.
window.rustProxyPolicy = (() => {
const STAGES = ["pre_route", "request", "backend_request", "backend_response", "deliver", "after_response"];
const OPERATORS = ["equals", "contains", "prefix", "suffix", "regex", "exists", "cidr", "eq", "ne", "gt", "ge", "lt", "le"];
const ACTION_FIELDS = {
set_header: ["name", "value"], append_header: ["name", "value"], remove_header: ["name"], set_if_missing: ["name", "value"],
normalize_header: ["name"], merge_header: ["name", "value"], remove_value: ["name", "value"], replace_header: ["name", "pattern", "replacement"], replace_value: ["name", "pattern", "replacement"],
set_var: ["name", "value"], unset_var: ["name"], set_path: ["value"], set_query: ["value"], use_backend: ["id"],
deny: ["status"], return: ["status", "body"], redirect: ["status", "location"], pass: [], lookup: [], no_store: [],
set_ttl: ["seconds"], set_grace: ["seconds"], hash_header: ["name"], disable_compression: [], stop: []
};
const clone = value => structuredClone(value);
const label = (prefix, value) => t(`${prefix}${String(value).split("_").map(part => part[0].toUpperCase() + part.slice(1)).join("")}`);
const text = (tag, key, cls) => { const node = el(tag, t(key), cls); node.dataset.i18n = key; return node; };
const button = (key, fn, cls = "quiet") => { const node = text("button", key, cls); node.type = "button"; node.addEventListener("click", fn); return node; };
const object = value => value !== null && typeof value === "object" && !Array.isArray(value);
function settings(value) {
if (!object(value) || (value.rules !== undefined && !Array.isArray(value.rules)) || (value.acls !== undefined && !object(value.acls)) || (value.maps !== undefined && !object(value.maps))) throw Error(t("policyInvalid"));
const copy = clone(value);
copy.rules ??= []; copy.acls ??= {}; copy.maps ??= {};
if (copy.rules.length > 128 || copy.rules.some(rule => !object(rule) || !Array.isArray(rule.actions))) throw Error(t("policyInvalid"));
return copy;
}
function headers(source) {
return String(source).split(/\r?\n/).filter(line => line.trim()).map((line, index) => {
const at = line.indexOf(":");
if (at < 1 || /^[ \t]/.test(line)) throw Error(t("policyHeaderInvalid").replace("{line}", index + 1));
return { name: line.slice(0, at).trim(), value: line.slice(at + 1).replace(/^[ \t]+|[ \t]+$/g, "") };
});
}
function input(parent, key, value, options = {}) {
const holder = el("label", undefined, `policy-field${options.wide ? " policy-wide" : ""}${options.type === "checkbox" ? " policy-check" : ""}`);
const node = document.createElement(options.type === "textarea" ? "textarea" : options.values ? "select" : "input");
if (options.values) for (const [v, name] of options.values) { const item = el("option", name); item.value = v; node.append(item); }
else if (options.type !== "textarea") node.type = options.type || "text";
if (options.type === "checkbox") node.checked = Boolean(value); else node.value = value ?? "";
if (!options.values && options.type !== "checkbox") { node.spellcheck = false; node.autocomplete = "off"; }
if (options.rows) node.rows = options.rows;
if (options.maxLength) node.maxLength = options.maxLength;
if (options.min !== undefined) node.min = options.min;
if (options.max !== undefined) node.max = options.max;
if (options.placeholder) node.placeholder = options.placeholder;
node.setAttribute("aria-label", t(key));
if (options.type === "checkbox") holder.append(node, text("span", key)); else holder.append(text("span", key), node);
parent.append(holder); return node;
}
function defaultAction(type) {
const action = { type };
for (const field of ACTION_FIELDS[type] || []) action[field] = field === "status" ? (type === "deny" ? 403 : type === "redirect" ? 302 : 200) : field === "seconds" ? 60 : "";
if (type === "normalize_header") action.name = "Vary";
return action;
}
function limitTerminalActions(select, stage) {
for (const option of select.options) option.disabled = ["return", "redirect"].includes(option.value) && stage !== "request";
}
function uniqueId(rules, prefix = "policy") { let n = 1; while (rules.some(rule => rule.id === `${prefix}-${n}`)) n++; return `${prefix}-${n}`; }
function mergeImports(current, addition) {
const next = settings(current), incoming = settings(addition);
for (const kind of ["acls", "maps"]) for (const [name, value] of Object.entries(incoming[kind])) {
if (Object.hasOwn(next[kind], name) && JSON.stringify(next[kind][name]) !== JSON.stringify(value)) throw Error(t("policyImportCollision").replace("{name}", name));
Object.defineProperty(next[kind], name, { value: clone(value), enumerable: true, configurable: true, writable: true });
}
for (const rule of incoming.rules) {
const copy = clone(rule);
if (next.rules.some(item => item.id === copy.id)) copy.id = uniqueId(next.rules, "imported");
next.rules.push(copy);
}
return settings(next);
}
function preset(kind, id) {
const base = { id, name: t(kind === "vary" ? "policyPresetVary" : "policyPresetNormalize"), enabled: true, stage: kind === "vary" ? "backend_response" : "after_response", when: { all: [] }, actions: [], stop: false };
if (kind === "vary") {
base.when.all = [
{ fetch: "res.fhdr_cnt(Vary)", operator: "eq", values: ["2"] },
{ fetch: "res.fhdr(Vary)", operator: "equals", values: ["Accept-Encoding"], ignore_case: true },
{ fetch: "res.fhdr(Vary)", operator: "equals", values: ["Accept,Accept-Encoding", "Accept, Accept-Encoding"], ignore_case: true }
];
base.actions = [{ type: "set_header", name: "Vary", value: "Accept, Accept-Encoding" }];
} else base.actions = [{ type: "normalize_header", name: "Vary" }];
return base;
}
function create({ value = {}, scope = "vhost", onChange = () => {} } = {}) {
let model = settings(value), mode = "visual", epoch = 0, importResult = null;
const stagesForScope = STAGES.filter(stage => scope !== "location" || stage !== "pre_route");
const node = el("section", undefined, "http-policy-editor vh-wide"), message = el("p", undefined, "policy-message fine");
message.setAttribute("role", "status"); message.setAttribute("aria-live", "polite"); message.hidden = true;
const toolbar = el("div", undefined, "policy-toolbar"), visual = el("div", undefined, "policy-visual"), rawPane = el("div", undefined, "policy-raw"); rawPane.hidden = true;
node.append(text("p", "policyIntro", "fine"), text("p", "policyCompatibility", "fine"), toolbar, message, visual, rawPane);
const raw = input(rawPane, "policyJson", JSON.stringify(model, null, 2), { type: "textarea", rows: 18, maxLength: 262144, wide: true });
const fail = error => { message.textContent = error.message || String(error); message.classList.add("is-error"); message.hidden = false; };
const clear = () => { message.hidden = true; message.classList.remove("is-error"); };
const change = () => { epoch++; clear(); onChange(); };
const safely = fn => (...args) => { try { return fn(...args); } catch (error) { fail(error); } };
const parse = (control, check = value => value) => {
try { const value = check(JSON.parse(control.value)); control.setCustomValidity(""); return value; }
catch (error) { control.setCustomValidity(error.message || t("policyInvalid")); throw error; }
};
function read() {
if (mode !== "json") for (const control of visual.querySelectorAll(".policy-config-json")) control._readJson();
const value = mode === "json" ? settings(parse(raw, settings)) : settings(model);
if (scope === "location" && value.rules.some(rule => rule.stage === "pre_route")) throw Error(t("policyLocationStage"));
return value;
}
function setValue(value) { model = settings(value); raw.value = JSON.stringify(model, null, 2); raw.setCustomValidity(""); render(); }
const setMode = safely(next => {
model = read(); mode = next; visual.hidden = mode !== "visual"; rawPane.hidden = mode !== "json";
if (mode === "json") raw.value = JSON.stringify(model, null, 2); else render();
visualButton.setAttribute("aria-pressed", String(mode === "visual")); jsonButton.setAttribute("aria-pressed", String(mode === "json")); clear();
});
const visualButton = button("policyVisual", () => setMode("visual")), jsonButton = button("policyJson", () => setMode("json"));
visualButton.setAttribute("aria-pressed", "true"); jsonButton.setAttribute("aria-pressed", "false"); toolbar.append(visualButton, jsonButton);
raw.addEventListener("input", () => { raw.setCustomValidity(""); change(); });
const guide = el("a", t("documentation"), "policy-guide"); guide.href = "/docs#doc=docs%2FPOLICY.md"; guide.target = "_blank"; guide.rel = "noopener"; toolbar.append(guide);
const editJson = (parent, key, current, apply, check = value => value, rows = 4) => {
const area = input(parent, key, JSON.stringify(current, null, 2), { type: "textarea", rows, maxLength: 65536, wide: true }); area.classList.add("policy-config-json");
area._readJson = () => { const data = parse(area, check); apply(data); return data; };
area.addEventListener("input", () => { try { area._readJson(); } catch { } change(); }); return area;
};
const requireObject = value => { if (!object(value)) throw Error(t("policyInvalid")); return value; };
function renderAction(parent, rule, action, index, refresh) {
const row = el("div", undefined, "policy-action"); parent.append(row);
const known = Object.hasOwn(ACTION_FIELDS, action.type), choices = Object.keys(ACTION_FIELDS).map(type => [type, label("policyAction", type)]);
if (!known) choices.unshift([action.type || "", action.type || t("policyAdvancedAction")]);
const op = input(row, "policyAction", action.type, { values: choices });
op.dataset.policyAction = ""; limitTerminalActions(op, rule.stage || "request");
op.addEventListener("change", safely(() => { read(); rule.actions[index] = defaultAction(op.value); refresh(); change(); }));
if (!known) editJson(row, "policyAdvancedAction", action, value => { rule.actions[index] = value; }, requireObject);
else for (const key of ACTION_FIELDS[action.type]) {
const number = ["status", "seconds"].includes(key), field = input(row, `policyField${key[0].toUpperCase()}${key.slice(1)}`, action[key], { type: number ? "number" : key === "body" ? "textarea" : "text", rows: key === "body" ? 2 : undefined, maxLength: key === "body" ? 65536 : 8192, min: number ? 0 : undefined });
field.addEventListener("input", () => { action[key] = number ? Number(field.value) : field.value; change(); });
}
const controls = el("div", undefined, "policy-row-controls"); row.append(controls);
const up = button("policyMoveUp", safely(() => { read(); [rule.actions[index - 1], rule.actions[index]] = [rule.actions[index], rule.actions[index - 1]]; refresh(); change(); })); up.disabled = index === 0;
const down = button("policyMoveDown", safely(() => { read(); [rule.actions[index + 1], rule.actions[index]] = [rule.actions[index], rule.actions[index + 1]]; refresh(); change(); })); down.disabled = index === rule.actions.length - 1;
controls.append(up, down, button("remove", safely(() => { read(); rule.actions.splice(index, 1); refresh(); change(); })));
}
function renderRule(parent, rule, index) {
const card = el("article", undefined, `policy-rule${rule.enabled === false ? " is-disabled" : ""}`); card.dataset.ruleId = rule.id || ""; parent.append(card);
const heading = el("div", undefined, "policy-rule-heading"), enabled = input(heading, "enabled", rule.enabled !== false, { type: "checkbox" });
heading.append(el("b", `${index + 1}.`, "policy-order"));
const title = input(heading, "policyRuleName", rule.name || "", { maxLength: 128 });
card.append(heading);
enabled.addEventListener("change", () => { rule.enabled = enabled.checked; card.classList.toggle("is-disabled", !enabled.checked); change(); });
title.addEventListener("input", () => { rule.name = title.value; change(); });
const commands = el("div", undefined, "policy-row-controls"); heading.append(commands);
const up = button("policyMoveUp", safely(() => { read(); [model.rules[index - 1], model.rules[index]] = [model.rules[index], model.rules[index - 1]]; render(); change(); })); up.disabled = index === 0;
const down = button("policyMoveDown", safely(() => { read(); [model.rules[index + 1], model.rules[index]] = [model.rules[index], model.rules[index + 1]]; render(); change(); })); down.disabled = index === model.rules.length - 1;
commands.append(up, down, button("remove", safely(() => { read(); model.rules.splice(index, 1); render(); change(); })));
const meta = el("div", undefined, "policy-grid"), id = input(meta, "policyRuleId", rule.id, { maxLength: 128 });
const stages = [...stagesForScope]; if (rule.stage && !stages.includes(rule.stage)) stages.push(rule.stage);
const stage = input(meta, "policyStage", rule.stage || "request", { values: stages.map(stage => [stage, label("policyStage", stage)]) });
const stop = input(meta, "policyStop", !!rule.stop, { type: "checkbox" });
id.addEventListener("input", () => { rule.id = id.value; change(); }); stop.addEventListener("change", () => { rule.stop = stop.checked; change(); });
const stageHint = el("p", label("policyStageHelp", stage.value), "policy-wide fine");
stage.addEventListener("change", () => { rule.stage = stage.value; stageHint.textContent = label("policyStageHelp", stage.value); for (const op of card.querySelectorAll("select[data-policy-action]")) limitTerminalActions(op, stage.value); change(); });
meta.append(stageHint); card.append(meta);
const conditions = el("details", undefined, "policy-conditions"), conditionSummary = text("summary", "policyConditions"); conditions.append(conditionSummary); card.append(conditions);
const conditionBody = el("div", undefined, "policy-detail-body"); conditions.append(conditionBody);
const when = editJson(conditionBody, "policyConditionJson", rule.when || { all: [] }, value => { rule.when = value; }, requireObject, 5);
const simple = el("div", undefined, "policy-grid"), fetch = input(simple, "policyFetch", "res.fhdr(Vary)", { maxLength: 4096 });
const operator = input(simple, "policyOperator", "equals", { values: OPERATORS.map(op => [op, op]) });
const values = input(simple, "policyValues", "Accept-Encoding", { type: "textarea", rows: 2, maxLength: 8192 });
const ignore = input(simple, "policyIgnoreCase", true, { type: "checkbox" });
const modeSelect = input(simple, "policyCombine", "all", { values: [["all", "AND"], ["any", "OR"]] });
operator.addEventListener("change", () => { values.disabled = operator.value === "exists"; });
simple.append(button("policyAddCondition", safely(() => {
const before = parse(when, requireObject), condition = { fetch: fetch.value, operator: operator.value, values: operator.value === "exists" ? [] : values.value.split(/\r?\n/).filter(value => value.length), ignore_case: ignore.checked };
const group = modeSelect.value;
const empty = Object.keys(before).length === 1 && ((Array.isArray(before.all) && !before.all.length) || (Array.isArray(before.any) && !before.any.length));
rule.when = empty ? { [group]: [condition] } : Object.keys(before).length === 1 && Array.isArray(before[group]) ? { [group]: [...before[group], condition] } : { [group]: [before, condition] };
when.value = JSON.stringify(rule.when, null, 2); when.setCustomValidity(""); change();
})));
conditionBody.append(simple, text("p", "policyConditionsHelp", "fine"));
card.append(text("h4", "policyActions")); const actions = el("div", undefined, "policy-actions"); card.append(actions);
const refresh = () => { actions.replaceChildren(); rule.actions.forEach((action, index) => renderAction(actions, rule, action, index, refresh)); };
refresh(); const addAction = button("policyAddAction", safely(() => { read(); if (rule.actions.length >= 16) throw Error(t("policyActionLimit")); rule.actions.push(defaultAction("set_header")); refresh(); change(); })); card.append(addAction);
}
function render() {
visual.replaceChildren();
const bar = el("div", undefined, "policy-toolbar"); visual.append(bar);
const add = safely(kind => {
model = read(); if (model.rules.length >= 128) throw Error(t("policyRuleLimit"));
const id = uniqueId(model.rules);
model.rules.push(kind ? preset(kind, id) : { id, name: t("policyNewRule"), enabled: true, stage: "after_response", when: { all: [] }, actions: [defaultAction("set_header")], stop: false });
render(); change();
});
bar.append(button("policyAddRule", () => add(), "primary"), button("policyPresetVary", () => add("vary")), button("policyPresetNormalize", () => add("normalize")));
if (!model.rules.length) visual.append(text("p", "policyEmpty", "fine"));
const rules = el("div", undefined, "policy-rules"); visual.append(rules); model.rules.forEach((rule, index) => renderRule(rules, rule, index));
const definitions = el("details", undefined, "policy-definitions"); definitions.append(text("summary", "policyDefinitions"));
const body = el("div", undefined, "policy-detail-body"); definitions.append(body);
editJson(body, "policyAcls", model.acls, value => { model.acls = value; }, requireObject, 5);
editJson(body, "policyMaps", model.maps, value => { model.maps = value; }, requireObject, 5);
body.append(text("p", "policyDefinitionsHelp", "fine")); visual.append(definitions);
}
render();
// Import is staged: server validation, visible preview, then an explicit add
// to the unsaved draft. Source changes invalidate a pending preview.
const importer = el("details", undefined, "policy-import"); importer.append(text("summary", "policyImport"));
const importBody = el("div", undefined, "policy-detail-body"); importer.append(importBody);
const source = input(importBody, "policyHaproxySource", "", { type: "textarea", rows: 7, maxLength: 262144, wide: true, placeholder: "acl vary_duplicate res.fhdr_cnt(Vary) eq 2\nacl vary_encoding res.fhdr(Vary) -i Accept-Encoding\nacl vary_combined res.fhdr(Vary) -i \"Accept,Accept-Encoding\" \"Accept, Accept-Encoding\"\nhttp-response set-header Vary \"Accept, Accept-Encoding\" if vary_duplicate vary_encoding vary_combined" });
source.setAttribute("form", "rustproxy-policy-tools");
const imported = el("pre", undefined, "policy-result"), importNotes = el("p", undefined, "fine"); imported.hidden = true; importNotes.hidden = true;
const applyImport = button("policyImportAdd", safely(() => {
if (!importResult) return;
const next = mergeImports(read(), importResult.policy); setValue(next); change(); importResult = null; applyImport.disabled = true;
importNotes.textContent = t("policyImportAdded"); importNotes.hidden = false;
})); applyImport.disabled = true;
const importButton = button("policyImportPreview", async () => {
clear(); importResult = null; applyImport.disabled = true; importButton.disabled = true; imported.hidden = true; importNotes.hidden = true;
const submitted = source.value;
try {
const result = await api("/api/policy/import-haproxy", { method: "POST", body: JSON.stringify({ source: submitted }) });
if (source.value !== submitted) return;
settings(result.policy); importResult = result; imported.textContent = JSON.stringify(result.policy, null, 2); imported.hidden = false;
importNotes.textContent = (result.warnings || []).join("\n") || t("policyImportReady"); importNotes.hidden = false; applyImport.disabled = false;
} catch (error) { fail(error); } finally { importButton.disabled = false; }
});
source.addEventListener("input", event => { event.stopPropagation(); importResult = null; applyImport.disabled = true; imported.hidden = true; importNotes.hidden = true; });
source.addEventListener("change", event => event.stopPropagation());
const importActions = el("div", undefined, "policy-toolbar"); importActions.append(importButton, applyImport);
importBody.append(importActions, importNotes, imported, text("p", "policyImportHelp", "fine")); node.append(importer);
const tester = el("details", undefined, "policy-tester"); tester.append(text("summary", "policyTest"));
const testBody = el("div", undefined, "policy-detail-body"), testGrid = el("div", undefined, "policy-grid"); tester.append(testBody); testBody.append(text("p", "policyTestHelp", "fine"), testGrid);
const testStage = input(testGrid, "policyStage", "after_response", { values: stagesForScope.map(stage => [stage, label("policyStage", stage)]) });
const method = input(testGrid, "policyMethod", "GET", { values: ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"].map(value => [value, value]) });
const host = input(testGrid, "policyHost", "example.com", { maxLength: 255 }), path = input(testGrid, "policyPath", "/", { maxLength: 8192 }), query = input(testGrid, "policyQuery", "", { maxLength: 8192 });
const ip = input(testGrid, "policyClientIp", "203.0.113.10", { maxLength: 64 }), country = input(testGrid, "policyCountry", "PL", { maxLength: 2 }), tls = input(testGrid, "policyTls", true, { type: "checkbox" });
const status = input(testGrid, "policyStatus", 200, { type: "number", min: 100, max: 599 });
const cache = input(testGrid, "policyCacheStatus", "MISS", { values: [["", "—"], ...["HIT", "MISS", "BYPASS"].map(value => [value, value])] }), backend = input(testGrid, "policyBackend", "", { maxLength: 128 });
const requestHeaders = input(testGrid, "policyRequestHeaders", "Accept-Encoding: gzip\nAccept: text/html", { type: "textarea", rows: 4, maxLength: 65536, wide: true });
const responseHeaders = input(testGrid, "policyResponseHeaders", "Vary: Accept-Encoding\nVary: Accept,Accept-Encoding", { type: "textarea", rows: 4, maxLength: 65536, wide: true });
const variables = input(testGrid, "policyVariables", "{}", { type: "textarea", rows: 2, maxLength: 8192, wide: true });
const resultBox = el("div", undefined, "policy-test-output"); resultBox.setAttribute("aria-live", "polite");
const testButton = button("policyRunTest", async () => {
clear(); testButton.disabled = true; resultBox.replaceChildren(); const submittedEpoch = epoch;
try {
const vars = parse(variables, requireObject);
if (Object.values(vars).some(value => typeof value !== "string")) throw Error(t("policyVariablesInvalid"));
const payload = { policy: read(), stage: testStage.value, request: { method: method.value, host: host.value, path: path.value, query: query.value || null, headers: headers(requestHeaders.value), client_ip: ip.value || null, country: country.value || null, tls: tls.checked }, response: { status: Number(status.value), headers: headers(responseHeaders.value) }, variables: vars, cache_status: cache.value || null, srv_id: backend.value || null };
const result = await api("/api/policy/test", { method: "POST", body: JSON.stringify(payload) });
if (epoch !== submittedEpoch) { resultBox.append(text("p", "policyTestStale", "fine")); return; }
if (result.requires_private_response) resultBox.append(text("p", "policyPrivateResponse", "fine"));
const table = el("table", undefined, "policy-trace"), head = el("tr");
for (const key of ["policyRuleId", "policyStage", "policyMatched", "policyActions"]) head.append(text("th", key));
const thead = el("thead"), body = el("tbody"); thead.append(head); table.append(thead, body);
for (const entry of result.trace || []) {
const row = el("tr"); row.className = entry.matched ? "is-matched" : "is-skipped";
row.append(el("td", entry.rule), el("td", label("policyStage", entry.stage)), el("td", t(entry.matched ? "policyYes" : "policyNo")), el("td", [...(entry.actions || []), ...(entry.warnings || [])].join("\n"))); body.append(row);
}
if (body.children.length) resultBox.append(table); else resultBox.append(text("p", "policyNoStageRules", "fine"));
const printHeaders = (key, values) => { resultBox.append(text("h4", key), el("pre", (values || []).map(item => `${item.name}: ${item.value}`).join("\n") || "—", "policy-result")); };
printHeaders("policyRequestResult", result.request?.headers); printHeaders("policyResponseResult", result.response?.headers);
const details = el("details"); details.append(text("summary", "policyFullResult"), el("pre", JSON.stringify(result, null, 2), "policy-result")); resultBox.append(details);
} catch (error) { fail(error); } finally { testButton.disabled = false; }
}, "primary");
// Tester input changes invalidate an in-flight result without dirtying config.
for (const control of testGrid.querySelectorAll("input, select, textarea")) control.setAttribute("form", "rustproxy-policy-tools");
testGrid.addEventListener("input", event => { event.stopPropagation(); epoch++; }); testGrid.addEventListener("change", event => { event.stopPropagation(); epoch++; });
testBody.append(testButton, resultBox); node.append(tester);
const counters = el("details", undefined, "policy-counters"); counters.append(text("summary", "policyCounters"));
const counterBody = el("div", undefined, "policy-detail-body"), counterResult = el("div", undefined, "policy-counter-scroll");
counterResult.setAttribute("aria-live", "polite"); counterBody.append(text("p", "policyCountersHelp", "fine"));
const refreshCounters = button("policyRefreshCounters", async () => {
refreshCounters.disabled = true; counterResult.replaceChildren(); clear();
try {
const result = await api("/api/policy/stats");
counterResult.append(el("p", `${t("policySavedRevision")}: ${result.revision}`, "fine"));
const table = el("table", undefined, "policy-trace"), thead = el("thead"), heading = el("tr"), body = el("tbody");
for (const key of ["policyScope", "policyRuleId", "policyStage", "policyMatches", "policyErrors"]) heading.append(text("th", key));
thead.append(heading); table.append(thead, body);
for (const item of result.scopes || []) for (const rule of item.rules || []) {
const row = el("tr"), identity = [item.scope, item.vhost, item.location].filter(Boolean).join(" / ");
row.append(el("td", identity), el("td", rule.id), el("td", label("policyStage", rule.stage)), el("td", String(rule.matches ?? 0)), el("td", String(rule.errors ?? 0))); body.append(row);
}
if (body.children.length) counterResult.append(table); else counterResult.append(text("p", "policyCountersEmpty", "fine"));
} catch (error) { fail(error); } finally { refreshCounters.disabled = false; }
});
counterBody.append(refreshCounters, counterResult); counters.append(counterBody); node.append(counters);
node.dataset.policyScope = scope;
return { node, read, set: setValue };
}
return { create, settings, headers, mergeImports, preset };
})();
+2 -2
View File
@@ -9,7 +9,7 @@
const requestedTab = typeof location !== "undefined" && location.pathname === "/logging"
? "logging"
: (typeof location !== "undefined" && location.pathname === "/settings" ? new URLSearchParams(location.search).get("tab") : null);
const tabAliases = { http2: "connections", headers: "policies", response: "policies" };
const tabAliases = { http2: "connections", headers: "policies", response: "policies", policy: "policies" };
function pinnedAdminHostname(value) {
try {
const url = new URL(value);
@@ -91,7 +91,7 @@
event.preventDefault(); selectPolicyTab(policyTabs[next].dataset.policySettingsTab, true);
});
}
selectPolicyTab(["headers", "response", "security-headers", "block-allow"].includes(requestedTab) ? requestedTab : "block-allow");
selectPolicyTab(["headers", "policy", "response", "security-headers", "block-allow"].includes(requestedTab) ? requestedTab : "block-allow");
const cacheTabs = [...document.querySelectorAll("[data-cache-settings-tab]")];
function selectCacheTab(name, focus = false) {
if (!cacheTabs.some(button => button.dataset.cacheSettingsTab === name)) return;
@@ -0,0 +1,190 @@
// Cache/VCL editor round-trip regressions. Requires Node.js and jsdom.
// Run: node src/admin/web/tests/cache-rules.dom.test.cjs
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { JSDOM } = require('jsdom');
const root = path.resolve(__dirname, '../../../..');
const translations = JSON.parse(fs.readFileSync(path.join(root, 'langs/en_US.json'), 'utf8')).translations;
const dom = new JSDOM('<html><body><form id="fixture"><main id="root"></main></form></body></html>', { runScripts: 'outside-only', url: 'https://panel.example.test' });
const w = dom.window, d = w.document;
w.structuredClone = structuredClone;
w.t = key => translations[key] || key;
w.el = (tag, text, cls) => { const node = d.createElement(tag); if (text !== undefined) node.textContent = text; if (cls) node.className = cls; return node; };
w.envelope = { config: { cache: { rules: [] }, vhosts: [] } };
w.authenticated = false;
w.fmt = value => String(value);
w.rustProxyChoicePicker = { create: options => { const node = d.createElement('div'); node.className = options.className || ''; return node; } };
let notices = [], calls = [], reply = {}, dirty = 0, editor, checks = 0;
w.toast = (message, error) => notices.push({ message, error });
w.api = async (url, options) => { calls.push({ url, body: options?.body ? JSON.parse(options.body) : null }); return structuredClone(reply); };
w.eval(fs.readFileSync(path.join(root, 'src/admin/web/cache-rules.js'), 'utf8'));
const api = w.rustProxyCacheRules;
const plain = value => JSON.parse(JSON.stringify(value));
const flush = () => new Promise(resolve => setImmediate(resolve));
function mount(rules = [], scope = 'vhost') {
notices = []; calls = []; dirty = 0;
editor = api.create({ rules, scope, vhostId: 'site', autoLoadHits: false, onChange: () => dirty++ });
d.getElementById('root').replaceChildren(editor.node);
}
function button(key, within = editor.node) {
const found = [...within.querySelectorAll('button')].find(node => node.textContent === w.t(key) || node.getAttribute('aria-label') === w.t(key));
assert.ok(found, `button ${key}`); return found;
}
function card(index = 0) { return editor.node.querySelectorAll('.cache-rule')[index]; }
function open(index = 0) { card(index).querySelector('.cache-rule-title').click(); return card(index); }
function field(key, within) {
const found = [...within.querySelectorAll('.cache-rule-field')].find(node => node.firstElementChild?.textContent === w.t(key));
assert.ok(found, `field ${key}`); return found.querySelector('input, select, textarea');
}
function fill(node, value, event = 'input') { node.value = value; node.dispatchEvent(new w.Event(event, { bubbles: true })); }
function drop(from, to) { const event = new w.Event('drop', { bubbles: true, cancelable: true }); Object.defineProperty(event, 'dataTransfer', { value: { getData: () => String(from) } }); card(to).dispatchEvent(event); }
async function importRules(rules, warnings = []) {
reply = { rules, warnings }; button('cacheRulesImportVcl').click();
fill(editor.node.querySelector('.cache-rules-import textarea'), 'sub vcl_recv { if (req.http.X-Mode == "old") { set req.http.X-Mode = "new"; } else { return (pass); } }');
button('cacheRulesImportRun').click(); await flush();
}
async function check(name, fn) { await fn(); checks++; console.log(`ok ${checks} - ${name}`); }
(async () => {
const ordinary = { id: 'ordinary', name: 'Ordinary', enabled: true, stage: 'request', match: 'all', conditions: [{ field: 'path', operator: 'prefix', values: ['/assets'] }], actions: [{ type: 'set_request_header', name: 'X-Device', value: 'desktop' }], stop: false };
const hashing = { id: 'hash', name: 'Imported hash', enabled: true, stage: 'request', match: 'all', conditions: [], actions: [{ type: 'hash_header', name: 'X-Device' }], stop: false, hash_stage: true };
const flow = [
{ ...ordinary, id: 'vcl-if', name: 'If decision', conditions: [], actions: [], vcl_flow: { version: 1, group: 'vcl-fixture', index: 0, count: 3, branches: [{ any: [[{ field: 'header', name: 'X-Mode', operator: 'equals', values: ['old'] }]] }, { any: [[]] }] } },
{ ...ordinary, id: 'vcl-then', name: 'Selected branch', conditions: [], actions: [{ type: 'set_request_header', name: 'X-Mode', value: 'new' }], vcl_flow: { version: 1, group: 'vcl-fixture', index: 1, count: 3, guards: [{ entry: 0, branch: 0 }] } },
{ ...ordinary, id: 'vcl-else', name: 'Else branch', conditions: [], actions: [{ type: 'pass' }], stop: true, vcl_flow: { version: 1, group: 'vcl-fixture', index: 2, count: 3, guards: [{ entry: 0, branch: 1 }] } },
];
await check('existing request and imported hash rules survive opening and save', () => {
mount([ordinary, hashing]); open(); assert.deepEqual(plain(editor.read()), [ordinary, hashing]);
assert.equal(dirty, 0);
});
await check('ordinary reorder keeps hash phase and edited action values', () => {
const first = card(); const input = [...first.querySelectorAll('input')].find(node => node.placeholder === w.t('cacheRuleHeaderValue'));
fill(input, 'mobile'); button('cacheRulesMoveDown', first).click();
assert.deepEqual(plain(editor.read()), [hashing, { ...ordinary, actions: [{ ...ordinary.actions[0], value: 'mobile' }] }]);
assert.equal(ordinary.actions[0].value, 'desktop');
});
await check('tester sends the same saved-rule structure without configuration writes', async () => {
mount([ordinary, hashing]); reply = { request: { cacheable: true }, response: { stored: true, ttl: 60, grace: 0 } };
button('cacheRulesTesterRun').click(); await flush();
assert.equal(calls.length, 1); assert.equal(calls[0].url, '/api/cache/rules/test');
assert.deepEqual(calls[0].body.vhost_rules, [ordinary, hashing]); assert.equal(dirty, 0);
});
await check('opening a branch marker allows zero actions and preserves every condition and guard', () => {
mount(flow); open(); assert.deepEqual(plain(editor.read()), flow); assert.equal(dirty, 0);
const copy = editor.read(); copy[0].vcl_flow.branches[0].any[0][0].values[0] = 'tampered';
copy[1].vcl_flow.guards[0].branch = 1;
assert.deepEqual(plain(editor.read()), flow); assert.equal(flow[0].vcl_flow.branches[0].any[0][0].values[0], 'old');
});
await check('structural controls are disabled and reject synthetic changes without flattening', () => {
const marker = card();
assert.ok(field('cacheRuleStage', marker).disabled); assert.ok(field('cacheRuleMatch', marker).disabled);
assert.ok(marker.querySelector('.cache-rule-stop input').disabled);
assert.ok(button('cacheRuleAddCondition', marker).disabled); assert.ok(button('cacheRuleAddAction', marker).disabled);
fill(field('cacheRuleStage', marker), 'deliver', 'change');
fill(field('cacheRuleMatch', marker), 'any', 'change');
assert.deepEqual(plain(editor.read()), flow); assert.equal(dirty, 0); assert.equal(notices.length, 2);
});
await check('editing an action and renaming a rule preserve branch references', () => {
mount(flow); const row = open(1);
fill(row.querySelector('input[placeholder="' + w.t('cacheRuleHeaderValue') + '"]'), 'reviewed');
fill(field('cacheRuleId', row), 'renamed-action', 'change');
const saved = plain(editor.read());
assert.equal(saved[1].actions[0].value, 'reviewed'); assert.equal(saved[1].id, 'renamed-action');
assert.deepEqual(saved.map(rule => rule.vcl_flow), flow.map(rule => rule.vcl_flow));
assert.equal(flow[1].actions[0].value, 'new');
});
await check('moving any member or dropping a flat rule cannot split a VCL block', () => {
mount([ordinary, ...flow, hashing]);
button('cacheRulesMoveDown', card(2)).click();
assert.deepEqual(plain(editor.read()), [ordinary, hashing, ...flow]);
drop(0, 3); assert.deepEqual(plain(editor.read()), [hashing, ...flow, ordinary]);
button('cacheRulesMoveUp', card(3)).click();
assert.deepEqual(plain(editor.read()), [...flow, hashing, ordinary]);
const before = dirty; drop(0, 2); assert.equal(dirty, before); assert.deepEqual(plain(editor.read()), [...flow, hashing, ordinary]);
});
await check('enable controls change the complete block and leave unrelated rules alone', () => {
mount([ordinary, ...flow]);
const toggle = card(2).querySelector('.cache-rule-head input'); toggle.checked = false; toggle.dispatchEvent(new w.Event('change', { bubbles: true }));
assert.deepEqual(plain(editor.read()), [ordinary, ...flow.map(rule => ({ ...rule, enabled: false }))]);
assert.equal(dirty, 1);
});
await check('duplicate creates independent group and rule IDs; remove deletes the complete copy', () => {
mount([ordinary, ...flow]); button('cacheRulesFlowDuplicate', card(2)).click();
const saved = plain(editor.read()), copies = saved.slice(4);
assert.equal(saved.length, 7); assert.equal(new Set(saved.map(rule => rule.id)).size, 7);
assert.match(copies[0].vcl_flow.group, /^vcl-[a-f0-9]{32}$/); assert.notEqual(copies[0].vcl_flow.group, flow[0].vcl_flow.group);
assert.equal(new Set(copies.map(rule => rule.vcl_flow.group)).size, 1);
assert.deepEqual(copies.map(rule => ({ ...rule.vcl_flow, group: 'vcl-fixture' })), flow.map(rule => rule.vcl_flow));
button('cacheRulesFlowRemove', card(5)).click(); assert.deepEqual(plain(editor.read()), [ordinary, ...flow]);
});
await check('vhost targeting is updated atomically for the whole global VCL block', () => {
mount([ordinary, ...flow], 'global'); const row = open(2);
row.querySelector('.cache-rule-vhosts').dispatchEvent(new w.CustomEvent('choicechange', { detail: ['site-a', 'site-b'], bubbles: true }));
const saved = plain(editor.read()); assert.deepEqual(saved[0], ordinary);
assert.ok(saved.slice(1).every(rule => JSON.stringify(rule.vhosts) === '["site-a","site-b"]'));
const detached = editor.read(); detached[1].vhosts.push('tampered'); assert.equal(editor.read()[1].vhosts.length, 2);
});
await check('importing the same block again remaps IDs without changing its guards', async () => {
mount(flow); await importRules(flow);
const saved = plain(editor.read()), added = saved.slice(3);
assert.equal(saved.length, 6); assert.deepEqual(saved.slice(0, 3), flow);
assert.equal(new Set(saved.map(rule => rule.id)).size, 6); assert.notEqual(added[0].vcl_flow.group, flow[0].vcl_flow.group);
assert.deepEqual(added.map(rule => ({ ...rule.vcl_flow, group: 'vcl-fixture' })), flow.map(rule => rule.vcl_flow));
assert.equal(dirty, 1); assert.deepEqual(flow[1].vcl_flow.guards, [{ entry: 0, branch: 0 }]);
});
await check('partial import keeps the complete structure only after explicit acceptance', async () => {
mount([ordinary]); await importRules(flow, ['Unsupported log statement was omitted.']);
assert.deepEqual(plain(editor.read()), [ordinary]); assert.equal(dirty, 0);
button('cacheRulesImportApplyPartial').click();
assert.deepEqual(plain(editor.read()), [ordinary, ...flow]); assert.equal(dirty, 1);
});
await check('incomplete import is rejected atomically and preserves existing rules', async () => {
mount([ordinary]); await importRules(flow.slice(0, 2));
assert.deepEqual(plain(editor.read()), [ordinary]); assert.equal(dirty, 0);
assert.match(editor.node.querySelector('.cache-rules-import-result .is-error').textContent, /incomplete or structurally changed/);
});
await check('reordered or incomplete saved metadata cannot be saved or accidentally moved', () => {
mount([flow[0], flow[2], flow[1], ordinary]);
assert.throws(() => editor.read(), /incomplete or structurally changed/);
button('cacheRulesMoveUp', card(3)).click(); assert.equal(dirty, 0); assert.equal(notices.length, 1);
assert.equal(card(3).querySelector('.cache-rule-title b').textContent, ordinary.name);
editor.set(flow.slice(0, 2)); assert.throws(() => editor.read(), /incomplete or structurally changed/);
});
await check('tester and JSON export preserve the full imported program without executing in JavaScript', async () => {
mount(flow); reply = { request: { cacheable: false, reason: 'pass' } };
button('cacheRulesTesterRun').click(); await flush();
assert.equal(calls.length, 1); assert.equal(calls[0].url, '/api/cache/rules/test'); assert.deepEqual(calls[0].body.vhost_rules, flow);
assert.ok(button('cacheRulesExportJson')); assert.deepEqual(JSON.parse(editor.node.querySelector('.cache-rules-vcl').textContent), flow);
assert.throws(() => api.exportVcl(flow), /complete JSON export/); assert.equal(dirty, 0);
});
await check('a hash-stage imported action retains its phase when its action is edited', () => {
const hashFlow = { ...hashing, vcl_flow: { version: 1, group: 'vcl-hash', index: 0, count: 1 } };
mount([hashFlow]); const row = open();
const name = row.querySelector('input[placeholder="Accept-Language"]'); fill(name, 'X-Experiment');
assert.deepEqual(plain(editor.read()), [{ ...hashFlow, actions: [{ type: 'hash_header', name: 'X-Experiment' }] }]);
});
await check('nested guards and OR clauses survive editing and moving the complete program', () => {
const parent = { entry: 0, branch: 0 };
const nested = [
{ ...flow[0], vcl_flow: { ...flow[0].vcl_flow, group: 'vcl-nested', count: 5, branches: flow[0].vcl_flow.branches.slice(0, 1) } },
{ ...flow[0], id: 'nested-if', vcl_flow: { ...flow[0].vcl_flow, group: 'vcl-nested', index: 1, count: 5, guards: [parent], branches: [{ any: [[{ field: 'header', name: 'X-Inner', operator: 'exists' }], [{ field: 'path', operator: 'prefix', values: ['/public'] }]] }, { any: [[]] }] } },
{ ...flow[1], actions: [{ type: 'remove_request_header', name: 'X-Mode' }], vcl_flow: { ...flow[1].vcl_flow, group: 'vcl-nested', index: 2, count: 5, guards: [parent, { branch: 0, entry: 1 }] } },
{ ...flow[1], id: 'nested-else', vcl_flow: { ...flow[1].vcl_flow, group: 'vcl-nested', index: 3, count: 5, guards: [{ branch: 0, entry: 0 }, { entry: 1, branch: 1 }] } },
{ ...flow[2], vcl_flow: { ...flow[2].vcl_flow, group: 'vcl-nested', index: 4, count: 5, guards: [parent] } },
];
mount([...nested, ordinary]); open(2);
assert.deepEqual(plain(editor.read()), [...nested, ordinary]);
button('cacheRulesMoveDown', card(2)).click(); assert.deepEqual(plain(editor.read()), [ordinary, ...nested]);
const invalid = structuredClone(nested); invalid[4].vcl_flow.guards.push({ entry: 1, branch: 0 });
editor.set(invalid); assert.throws(() => editor.read(), /incomplete or structurally changed/);
});
await check('cross-phase guards and altered branch markers are rejected before save', () => {
const wrongPhase = structuredClone(flow); wrongPhase[1].hash_stage = true;
mount(wrongPhase); assert.throws(() => editor.read(), /incomplete or structurally changed/);
const wrongMarker = structuredClone(flow); wrongMarker[0].actions = [{ type: 'pass' }];
editor.set(wrongMarker); assert.throws(() => editor.read(), /incomplete or structurally changed/);
});
console.log(`PASS: ${checks} cache/VCL editor DOM regression checks`);
dom.window.close();
})().catch(error => { console.error(error); dom.window.close(); process.exitCode = 1; });
+130
View File
@@ -0,0 +1,130 @@
// Fast policy editor regressions using a DOM. Requires Node.js and jsdom.
// Run: node src/admin/web/tests/policy.dom.test.cjs
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { JSDOM } = require('jsdom');
const root = path.resolve(__dirname, '../../../..');
const translations = JSON.parse(fs.readFileSync(path.join(root, 'langs/en_US.json'), 'utf8')).translations;
const dom = new JSDOM('<html><body><form id="fixture"><main id="root"></main><button type="submit">Save</button></form></body></html>', { runScripts: 'outside-only', url: 'https://panel.example.test' });
const w = dom.window, d = w.document;
w.structuredClone = structuredClone;
w.t = key => translations[key] || key;
w.el = (tag, text, cls) => { const n = d.createElement(tag); if (text !== undefined) n.textContent = text; if (cls) n.className = cls; return n; };
let dirty = 0, bubbled = 0, calls = [], response = {}, pending = false, resolver;
w.api = async (url, options) => { calls.push({ url, body: options?.body ? JSON.parse(options.body) : null }); if (pending) return new Promise(resolve => { resolver = resolve; }); return structuredClone(response); };
d.getElementById('fixture').addEventListener('input', () => bubbled++);
w.eval(fs.readFileSync(path.join(root, 'src/admin/web/policy.js'), 'utf8'));
const plain = value => JSON.parse(JSON.stringify(value));
const api = w.rustProxyPolicy;
let editor, checks = 0;
const flush = () => new Promise(resolve => setImmediate(resolve));
function mount(value = {}, scope = 'vhost') { dirty = 0; bubbled = 0; calls = []; pending = false; editor = api.create({ value, scope, onChange: () => dirty++ }); d.getElementById('root').replaceChildren(editor.node); }
function button(key, within = editor.node) { const found = [...within.querySelectorAll('button')].find(n => n.textContent === w.t(key)); assert.ok(found, `button ${key}`); return found; }
function control(key, within = editor.node) { const found = [...within.querySelectorAll('input, textarea, select')].find(n => n.getAttribute('aria-label') === w.t(key)); assert.ok(found, `control ${key}`); return found; }
function fill(node, value, event = 'input') { node.value = value; node.dispatchEvent(new w.Event(event, { bubbles: true })); }
async function check(name, fn) { await fn(); checks++; console.log(`ok ${checks} - ${name}`); }
(async () => {
const original = { acls: { mobile: { fetch: 'req.fhdr(User-Agent)', operator: 'contains', values: ['mobile'], ignore_case: true } }, maps: { devices: { kind: 'exact', entries: [{ key: 'a', value: 'b' }], default: 'fallback', ignore_case: false } }, rules: [
{ id: 'one', name: '<img src=x onerror=alert(1)>', enabled: false, stage: 'request', when: { any: [{ acl: 'mobile' }, { not: { fetch: 'req.fhdr(X-Test)', operator: 'exists', values: [] } }] }, actions: [{ type: 'set_var', name: 'txn.device', value: '%[req.fhdr(User-Agent),lower,map(devices)]' }], stop: true },
{ id: 'two', name: 'Response', enabled: true, stage: 'after_response', when: { all: [] }, actions: [{ type: 'normalize_header', name: 'Vary' }], stop: false }
] };
await check('duplicate and empty header fields are preserved', () => {
assert.deepEqual(plain(api.headers('Vary: Accept-Encoding\nVary: Accept,Accept-Encoding\nX-Empty:\nX-URL: https://example.test:8443/')), [{ name: 'Vary', value: 'Accept-Encoding' }, { name: 'Vary', value: 'Accept,Accept-Encoding' }, { name: 'X-Empty', value: '' }, { name: 'X-URL', value: 'https://example.test:8443/' }]);
assert.throws(() => api.headers('not a header'), /Invalid header/);
assert.throws(() => api.headers(' folded: header'), /Invalid header/);
});
await check('opening complex existing settings preserves all values', () => { mount(original); assert.deepEqual(plain(editor.read()), original); assert.equal(editor.node.querySelector('img'), null); });
await check('reordering rules preserves ACLs, maps, conditions and actions', () => {
button('policyMoveDown', editor.node.querySelector('.policy-rule-heading')).click();
assert.deepEqual(plain(editor.read()), { ...original, rules: [original.rules[1], original.rules[0]] });
});
await check('raw JSON round trip is lossless and malformed JSON prevents switching/save', () => {
mount(original); button('policyJson').click(); const raw = editor.node.querySelector('.policy-raw textarea');
assert.deepEqual(plain(editor.read()), original); fill(raw, '{broken'); assert.throws(() => editor.read());
button('policyVisual').click(); assert.equal(editor.node.querySelector('.policy-raw').hidden, false);
fill(raw, JSON.stringify(original)); button('policyVisual').click(); assert.deepEqual(plain(editor.read()), original);
});
await check('editing nested condition JSON is never discarded by reorder', () => {
mount(original); const condition = editor.node.querySelector('.policy-conditions textarea'); fill(condition, '{broken');
button('policyMoveDown', editor.node.querySelector('.policy-rule-heading')).click(); assert.throws(() => editor.read());
assert.equal(editor.node.querySelector('.policy-rule').dataset.ruleId, 'one');
fill(condition, JSON.stringify({ acl: 'mobile' })); button('policyMoveDown', editor.node.querySelector('.policy-rule-heading')).click();
assert.deepEqual(plain(editor.read().rules[1].when), { acl: 'mobile' });
});
await check('first OR condition replaces the empty default group', () => {
mount(); button('policyAddRule').click(); const conditions = editor.node.querySelector('.policy-conditions');
fill(control('policyCombine', conditions), 'any', 'change'); button('policyAddCondition', conditions).click();
const expression = plain(editor.read().rules[0].when); assert.equal(expression.any.length, 1); assert.equal(expression.any[0].fetch, 'res.fhdr(Vary)');
});
await check('presets encode full-field count and final Vary normalization', () => {
mount(); button('policyPresetVary').click(); button('policyPresetNormalize').click();
const rules = editor.read().rules; assert.equal(rules[0].stage, 'backend_response'); assert.equal(rules[0].when.all.length, 3);
assert.deepEqual(plain(rules[0].when.all[0]), { fetch: 'res.fhdr_cnt(Vary)', operator: 'eq', values: ['2'] });
assert.deepEqual(plain(rules[1].actions), [{ type: 'normalize_header', name: 'Vary' }]); assert.equal(rules[1].stage, 'after_response');
});
await check('import requires review and explicit add; existing rules are retained', async () => {
mount(original); response = { policy: { rules: [{ ...original.rules[1], id: 'one' }] }, warnings: [] };
fill(control('policyHaproxySource'), 'http-after-response normalize-header Vary'); button('policyImportPreview').click(); await flush();
assert.deepEqual(plain(editor.read()), original); assert.equal(dirty, 0);
button('policyImportAdd').click(); const result = editor.read(); assert.equal(result.rules.length, 3); assert.equal(result.rules[2].id, 'imported-1');
assert.deepEqual(plain(result.acls), original.acls); assert.deepEqual(calls.map(c => c.url), ['/api/policy/import-haproxy']);
});
await check('name collisions reject imports atomically and special keys remain data', () => {
assert.throws(() => api.mergeImports(original, { acls: { mobile: { all: [] } }, rules: [{ id: 'bad', actions: [] }] }), /mobile/);
const special = api.mergeImports({}, JSON.parse('{"acls":{"__proto__":{"all":[]}},"rules":[]}'));
assert.equal(Object.hasOwn(special.acls, '__proto__'), true); assert.equal(Object.getPrototypeOf(special.acls), Object.prototype);
assert.equal(editor.read().rules.length, 3);
});
await check('source edits invalidate a pending import preview', async () => {
mount(); response = { policy: { rules: [original.rules[1]] }, warnings: [] };
fill(control('policyHaproxySource'), 'source'); button('policyImportPreview').click(); await flush();
assert.equal(button('policyImportAdd').disabled, false); fill(control('policyHaproxySource'), 'modified'); assert.equal(button('policyImportAdd').disabled, true);
assert.equal(editor.read().rules.length, 0);
});
await check('server tester receives duplicate headers and renders trace as text', async () => {
mount({ rules: [original.rules[1]] });
response = { request: { headers: [{ name: 'X-Unsafe', value: '<script>throw Error(1)</script>' }] }, response: { status: 200, headers: [{ name: 'Vary', value: 'Accept-Encoding, Accept' }] }, trace: [{ rule: 'two', stage: 'after_response', matched: true, actions: ['normalize_header'], warnings: [] }], variables: {} };
button('policyRunTest').click(); await flush();
assert.equal(calls[0].url, '/api/policy/test'); assert.equal(calls[0].body.stage, 'after_response');
assert.deepEqual(calls[0].body.response.headers, [{ name: 'Vary', value: 'Accept-Encoding' }, { name: 'Vary', value: 'Accept,Accept-Encoding' }]);
assert.equal(editor.node.querySelectorAll('.policy-trace tbody tr').length, 1); assert.equal(editor.node.querySelector('.policy-test-output script'), null);
assert.match(editor.node.querySelector('.policy-test-output').textContent, /<script>/);
});
await check('tester inputs neither dirty nor invalidate the enclosing config form', async () => {
mount(); fill(control('policyVariables'), 'malformed'); button('policyRunTest').click(); await flush();
assert.equal(dirty, 0); assert.equal(bubbled, 0); assert.equal(control('policyVariables').form, null); assert.equal(d.getElementById('fixture').checkValidity(), true);
});
await check('pre_route is unavailable and rejected in a location draft', () => {
mount({}, 'location'); assert.equal(editor.node.querySelector('.policy-tester option[value="pre_route"]'), null);
button('policyJson').click(); fill(editor.node.querySelector('.policy-raw textarea'), JSON.stringify({ rules: [{ id: 'bad', stage: 'pre_route', actions: [] }] }));
assert.throws(() => editor.read(), /pre_route/);
});
await check('return and redirect are selectable only after request access checks', () => {
mount({ rules: [{ id: 'terminal', stage: 'pre_route', actions: [{ type: 'return', status: 200, body: 'existing draft' }] }] });
const action = control('policyAction', editor.node.querySelector('.policy-action'));
for (const type of ['return', 'redirect']) assert.equal(action.querySelector(`option[value="${type}"]`).disabled, true);
assert.equal(action.querySelector('option[value="deny"]').disabled, false);
assert.equal(editor.read().rules[0].actions[0].body, 'existing draft');
fill(control('policyStage', editor.node.querySelector('.policy-rule')), 'request', 'change');
for (const type of ['return', 'redirect']) assert.equal(action.querySelector(`option[value="${type}"]`).disabled, false);
assert.equal(editor.read().rules[0].actions[0].body, 'existing draft');
});
await check('in-flight test result is discarded when inputs change', async () => {
mount({ rules: [original.rules[1]] }); pending = true; button('policyRunTest').click(); await flush();
fill(control('policyHost'), 'changed.example'); resolver({ trace: [] }); await flush();
assert.match(editor.node.querySelector('.policy-test-output').textContent, /changed during evaluation/); pending = false;
});
await check('live counters use a read-only saved-config request and do not dirty drafts', async () => {
mount(); response = { revision: 7, scopes: [{ scope: 'vhost', vhost: 'site-a', rules: [{ id: 'vary', stage: 'after_response', matches: 32, errors: 1 }] }] };
button('policyRefreshCounters').click(); await flush();
assert.deepEqual(calls, [{ url: '/api/policy/stats', body: null }]); assert.equal(dirty, 0);
const output = editor.node.querySelector('.policy-counter-scroll').textContent; assert.match(output, /7/); assert.match(output, /site-a/); assert.match(output, /32/);
assert.equal(editor.read().rules.length, 0);
});
await check('separate editor instances keep separate drafts', () => {
const first = api.create({ value: original }), second = api.create({ value: { rules: [original.rules[1]] } });
button('policyAddRule', first.node).click(); assert.equal(first.read().rules.length, 3); assert.equal(second.read().rules.length, 1); assert.equal(original.rules.length, 2);
});
console.log(`PASS: ${checks} DOM policy editor regression checks`); dom.window.close();
})().catch(error => { console.error(error); dom.window.close(); process.exitCode = 1; });
+132
View File
@@ -0,0 +1,132 @@
// Component regression tests. Requires Node.js and Playwright Chromium.
// Run: node src/admin/web/tests/policy.test.cjs
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { chromium } = require('playwright');
const root = path.resolve(__dirname, '../../../..');
const policyFile = path.join(root, 'src/admin/web/policy.js');
const translations = JSON.parse(fs.readFileSync(path.join(root, 'langs/en_US.json'), 'utf8')).translations;
let checks = 0;
async function check(name, fn) { await fn(); checks++; console.log(`ok ${checks} - ${name}`); }
(async () => {
const browser = await chromium.launch({ headless: true, ...(process.env.POLICY_TEST_CHROMIUM ? { executablePath: process.env.POLICY_TEST_CHROMIUM } : {}) });
try {
const page = await browser.newPage({ viewport: { width: 1180, height: 900 } });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.setContent('<html><body style="margin:20px"><form id="fixture"><div id="root"></div><button type="submit">Save</button></form></body></html>');
await page.evaluate(translations => {
window.translations = translations;
window.t = key => translations[key] || key;
window.el = (tag, text, cls) => { const node = document.createElement(tag); if (text !== undefined) node.textContent = text; if (cls) node.className = cls; return node; };
window.changed = 0; window.parentChanged = 0; window.calls = [];
document.getElementById('fixture').addEventListener('input', () => window.parentChanged++);
window.api = async (url, options) => { const body = options?.body ? JSON.parse(options.body) : null; window.calls.push({ url, body }); if (window.pendingApi) return new Promise(resolve => { window.resolveApi = resolve; }); return structuredClone(window.apiResult || {}); };
}, translations);
for (const file of ['00-tokens.css', '10-base.css', '55-policy.css']) await page.addStyleTag({ path: path.join(root, 'src/admin/web/css', file) });
await page.addScriptTag({ path: policyFile });
const mount = async (value = {}, scope = 'vhost') => page.evaluate(({ value, scope }) => {
window.changed = 0; window.parentChanged = 0; window.calls = [];
window.editor = window.rustProxyPolicy.create({ value, scope, onChange: () => window.changed++ });
document.getElementById('root').replaceChildren(window.editor.node);
}, { value, scope });
await check('header parser preserves repeated fields and empty values', async () => {
const values = await page.evaluate(() => window.rustProxyPolicy.headers('Vary: Accept-Encoding\nVary: Accept,Accept-Encoding\nX-Empty:\nX-URL: https://example.test:8443/'));
assert.deepEqual(values, [{ name: 'Vary', value: 'Accept-Encoding' }, { name: 'Vary', value: 'Accept,Accept-Encoding' }, { name: 'X-Empty', value: '' }, { name: 'X-URL', value: 'https://example.test:8443/' }]);
assert.equal(await page.evaluate(() => { try { window.rustProxyPolicy.headers('not a header'); return false; } catch { return true; } }), true);
});
const original = { acls: { mobile: { fetch: 'req.fhdr(User-Agent)', operator: 'contains', values: ['mobile'], ignore_case: true } }, maps: { devices: { kind: 'exact', entries: [{ key: 'a', value: 'b' }], default: 'fallback', ignore_case: false } }, rules: [
{ id: 'one', name: '<img src=x onerror=alert(1)>', enabled: false, stage: 'request', when: { any: [{ acl: 'mobile' }, { not: { fetch: 'req.fhdr(X-Test)', operator: 'exists', values: [] } }] }, actions: [{ type: 'set_var', name: 'txn.device', value: '%[req.fhdr(User-Agent),lower,map(devices)]' }], stop: true },
{ id: 'two', name: 'Response', enabled: true, stage: 'after_response', when: { all: [] }, actions: [{ type: 'normalize_header', name: 'Vary' }], stop: false }
] };
await check('complex rules, ACLs and maps survive opening and reading', async () => {
await mount(original); assert.deepEqual(await page.evaluate(() => window.editor.read()), original);
assert.equal(await page.locator('img').count(), 0);
});
await check('rule reorder preserves every condition, action and definition', async () => {
await page.locator('.policy-rule').first().locator('.policy-rule-heading').getByRole('button', { name: 'Move down', exact: true }).click();
const value = await page.evaluate(() => window.editor.read());
assert.deepEqual(value, { ...original, rules: [original.rules[1], original.rules[0]] });
});
await check('raw/visual round trip is lossless and invalid raw JSON blocks reading', async () => {
await mount(original); await page.getByRole('button', { name: 'Policy JSON', exact: true }).click();
assert.deepEqual(await page.evaluate(() => window.editor.read()), original);
await page.locator('.policy-raw textarea').fill('{broken');
assert.equal(await page.evaluate(() => { try { window.editor.read(); return false; } catch { return true; } }), true);
await page.getByRole('button', { name: 'Rule builder', exact: true }).click();
assert.equal(await page.locator('.policy-raw').isVisible(), true);
await page.locator('.policy-raw textarea').fill(JSON.stringify(original));
await page.getByRole('button', { name: 'Rule builder', exact: true }).click();
assert.deepEqual(await page.evaluate(() => window.editor.read()), original);
});
await check('Vary preset keeps field-count and separate full-field conditions', async () => {
await mount(); await page.getByRole('button', { name: 'Fix duplicate Vary (exact match)', exact: true }).click();
const rule = await page.evaluate(() => window.editor.read().rules[0]);
assert.equal(rule.stage, 'backend_response'); assert.equal(rule.when.all.length, 3);
assert.deepEqual(rule.when.all[0], { fetch: 'res.fhdr_cnt(Vary)', operator: 'eq', values: ['2'] });
assert.deepEqual(rule.actions, [{ type: 'set_header', name: 'Vary', value: 'Accept, Accept-Encoding' }]);
await page.getByRole('button', { name: 'Normalize Vary (preserve dimensions)', exact: true }).click();
assert.deepEqual(await page.evaluate(() => window.editor.read().rules[1].actions), [{ type: 'normalize_header', name: 'Vary' }]);
});
await check('import preview never silently activates or replaces existing rules', async () => {
await mount(original); await page.locator('.policy-import > summary').click();
const incoming = { acls: {}, maps: {}, rules: [{ ...original.rules[1], id: 'one' }] };
await page.evaluate(policy => { window.apiResult = { policy, warnings: [] }; }, incoming);
await page.getByLabel('HAProxy source', { exact: true }).fill('http-after-response normalize-header Vary');
await page.getByRole('button', { name: 'Validate and preview import', exact: true }).click();
assert.deepEqual(await page.evaluate(() => window.editor.read()), original);
await page.getByRole('button', { name: 'Add imported rules to draft', exact: true }).click();
const value = await page.evaluate(() => window.editor.read());
assert.equal(value.rules.length, 3); assert.equal(value.rules[2].id, 'imported-1'); assert.deepEqual(value.acls, original.acls);
assert.deepEqual(await page.evaluate(() => window.calls.map(call => call.url)), ['/api/policy/import-haproxy']);
});
await check('conflicting ACL imports are rejected atomically', async () => {
const value = await page.evaluate(original => {
try { window.rustProxyPolicy.mergeImports(original, { acls: { mobile: { all: [] } }, rules: [{ id: 'unsafe', actions: [] }] }); return null; }
catch (error) { return error.message; }
}, original);
assert.match(value, /mobile/);
assert.equal(await page.evaluate(() => window.editor.read().rules.length), 3);
});
await check('tester uses server API and preserves duplicate request/response fields', async () => {
await mount({ rules: [original.rules[1]] }); await page.locator('.policy-tester > summary').click();
const response = { request: { headers: [{ name: 'X-Unsafe', value: '<script>throw Error(1)</script>' }] }, response: { status: 200, headers: [{ name: 'Vary', value: 'Accept-Encoding, Accept' }] }, trace: [{ rule: 'two', stage: 'after_response', matched: true, actions: ['normalize_header'], warnings: [] }], variables: {}, cache: {} };
await page.evaluate(response => { window.apiResult = response; }, response);
await page.getByRole('button', { name: 'Run test', exact: true }).click();
const calls = await page.evaluate(() => window.calls); assert.equal(calls[0].url, '/api/policy/test');
assert.deepEqual(calls[0].body.response.headers, [{ name: 'Vary', value: 'Accept-Encoding' }, { name: 'Vary', value: 'Accept,Accept-Encoding' }]);
assert.equal(calls[0].body.stage, 'after_response'); assert.equal(await page.locator('.policy-trace tbody tr').count(), 1);
assert.match(await page.locator('.policy-test-output').innerText(), /<script>/); assert.equal(await page.locator('.policy-test-output script').count(), 0);
});
await check('tester inputs do not dirty or invalidate the configuration form', async () => {
await mount(); await page.locator('.policy-tester > summary').click();
await page.getByLabel('Transaction variables (JSON string values)', { exact: true }).fill('malformed');
await page.getByRole('button', { name: 'Run test', exact: true }).click();
assert.equal(await page.evaluate(() => window.changed), 0); assert.equal(await page.evaluate(() => window.parentChanged), 0);
assert.equal(await page.evaluate(() => document.getElementById('fixture').checkValidity()), true);
});
await check('location editor excludes pre_route and refuses raw configuration using it', async () => {
await mount({}, 'location');
assert.equal(await page.locator('.policy-tester option[value="pre_route"]').count(), 0);
await page.getByRole('button', { name: 'Policy JSON', exact: true }).click();
await page.locator('.policy-raw textarea').fill(JSON.stringify({ rules: [{ id: 'bad', stage: 'pre_route', actions: [] }] }));
assert.match(await page.evaluate(() => { try { window.editor.read(); return ''; } catch (error) { return error.message; } }), /pre_route/);
});
await check('asynchronous tester rejects stale results after input changes', async () => {
await mount({ rules: [original.rules[1]] }); await page.locator('.policy-tester > summary').click();
await page.evaluate(() => { window.pendingApi = true; });
await page.getByRole('button', { name: 'Run test', exact: true }).click();
await page.getByLabel('Host', { exact: true }).fill('different.example');
await page.evaluate(() => { window.pendingApi = false; window.resolveApi({ trace: [] }); });
await page.getByText('The draft or test input changed during evaluation. Run the test again.', { exact: true }).waitFor();
});
await check('responsive policy editor remains within the viewport', async () => {
await mount({ rules: [original.rules[1]] });
await page.setViewportSize({ width: 390, height: 850 });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= 390), true);
if (process.env.POLICY_TEST_SCREENSHOT) await page.screenshot({ path: process.env.POLICY_TEST_SCREENSHOT, fullPage: true });
});
assert.deepEqual(errors, []); console.log(`PASS: ${checks} policy editor regression checks`);
} finally { await browser.close(); }
})().catch(error => { console.error(error); process.exitCode = 1; });
+11 -3
View File
@@ -1,5 +1,5 @@
"use strict";
let vhostCacheRulesEditor = null;
let vhostCacheRulesEditor = null, vhostPolicyEditor = null;
let basicEditor = null, locationsReader = () => [], aclControl = null, editing = null, revision = null, dirty = false, initialized = false, readBindings = () => [], readHosts = () => [], countryRatesReader = () => [], uaRatesReader = () => [], pagesEditor = null, stagedCertificates = [], uploading = false, draftEpoch = 0, backendHealthEditorControl = null, vhostBalancingControl = null, vhostHeadersControl = null, headersPreviewControl = null, presetsRefresh = () => { };
const chartHistory = new Map();
const backendTrafficHistory = new Map();
@@ -23,7 +23,7 @@ const field = (parent, name, key, value, type = "text", options = {}) => {
};
const group = (key, advanced = false) => {
const box = el(advanced ? "details" : "fieldset", undefined, "vh-group");
box.dataset.tab = ({ vhEditor: "details", vhFrontends: "details", vhBackendPool: "backends", vhBackendDiagnostics: "headers", vhProxyTimeouts: "backends", vhBalancing: "backends", vhSticky: "backends", vhHealth: "health", vhPassiveHealth: "health", vhSecurity: "security", vhTrafficPolicy: "security", vhTinyauth: "auth", vhResponsePolicy: "headers", vhHeaders: "headers", vhHeadersPreview: "headers", vhAdvanced: "advanced", vhLocations: "locations", vhSsl: "ssl", vhSslSettings: "ssl", vhCache: "cache", vhCompression: "compression", vhTransform: "transform", vhPages: "pages" })[key] || "advanced"; box.append(text(advanced ? "summary" : "legend", key));
box.dataset.tab = ({ vhEditor: "details", vhFrontends: "details", vhBackendPool: "backends", vhBackendDiagnostics: "headers", vhProxyTimeouts: "backends", vhBalancing: "backends", vhSticky: "backends", vhHealth: "health", vhPassiveHealth: "health", vhSecurity: "security", vhTrafficPolicy: "security", vhTinyauth: "auth", vhResponsePolicy: "headers", vhHeaders: "headers", policyTitle: "headers", vhHeadersPreview: "headers", vhAdvanced: "advanced", vhLocations: "locations", vhSsl: "ssl", vhSslSettings: "ssl", vhCache: "cache", vhCompression: "compression", vhTransform: "transform", vhPages: "pages" })[key] || "advanced"; box.append(text(advanced ? "summary" : "legend", key));
const body = el("div", undefined, "vh-grid"); box.append(body); container.append(box); return body;
};
const note = (parent, key) => { const node = text("p", key, "fine vh-wide"); parent.append(node); return node; };
@@ -174,7 +174,7 @@ function suspendDraft() {
editing, revision, label: $("vhost-editing").textContent,
fields: window.rustProxyDrafts.takeChildren(container), tabs: window.rustProxyDrafts.takeChildren($("vhost-tabs")),
basicEditor, locationsReader, aclControl, readBindings, readHosts, countryRatesReader, uaRatesReader, pagesEditor, backendHealthEditorControl,
stagedCertificates, uploading
stagedCertificates, uploading, vhostPolicyEditor, vhostCacheRulesEditor, vhostHeadersControl, headersPreviewControl, presetsRefresh
};
const title = read("id")?.value.trim() || editing || t("draftUntitled");
draftEpoch++; editing = null; revision = null; dirty = false; stagedCertificates = []; uploading = false; dialog.close();
@@ -184,6 +184,8 @@ function restoreDraft(state) {
draftEpoch++; window.rustProxyDrafts.restoreChildren(container, state.fields); window.rustProxyDrafts.restoreChildren($("vhost-tabs"), state.tabs);
editing = state.editing; revision = state.revision; basicEditor = state.basicEditor; locationsReader = state.locationsReader; aclControl = state.aclControl;
readBindings = state.readBindings; readHosts = state.readHosts; countryRatesReader = state.countryRatesReader; uaRatesReader = state.uaRatesReader || (() => []); pagesEditor = state.pagesEditor; backendHealthEditorControl = state.backendHealthEditorControl || null;
vhostPolicyEditor = state.vhostPolicyEditor || null; vhostCacheRulesEditor = state.vhostCacheRulesEditor || null;
vhostHeadersControl = state.vhostHeadersControl || null; headersPreviewControl = state.headersPreviewControl || null; presetsRefresh = state.presetsRefresh || (() => {});
stagedCertificates = state.stagedCertificates || []; uploading = state.uploading === true; initialized = true; dirty = true; $("vhost-editing").textContent = state.label;
if (!dialog.open) dialog.showModal(); if (latestStatus) renderStatus(latestStatus);
}
@@ -402,6 +404,7 @@ function locationsEditor(parent, values) {
country_access: { mode: str("location-country-mode", r), countries: lines(str("location-country-list", r)).map(value => value.toUpperCase()) },
method_policy: { mode: str("location-method-mode", r), methods: lines(str("location-method-list", r)).map(value => value.toUpperCase()) },
headers: r.readHeaders(),
policy: r.readPolicy(),
rewrite: { mode: handled ? rewriteMode : "preserve", value: handled && rewriteMode !== "preserve" ? read("location-rewrite-value", r).value.trim() : "" },
response: action === "return" ? { status: Number(str("location-response-status", r)), content_type: str("location-response-type", r), body: read("location-response-body", r).value } : null,
redirect: action === "redirect" ? { status: Number(str("location-redirect-status", r)), target: str("location-redirect-target", r), rewrite_pattern: nullable("location-redirect-pattern", r), preserve_query: yes("location-redirect-query", r) } : null,
@@ -501,6 +504,11 @@ function locationsEditor(parent, values) {
const raw = field(jsonPane, "location-headers", "headersAdvancedJson", JSON.stringify(value.headers || {}, null, 2), "textarea", { rows: 8, maxLength: 65536 });
const editor = headerEditors(visualPane, value.headers || {}, raw, sync, () => ({ location: str("location-id", row) || "main" })); row.readHeaders = () => editor.read();
const policyBox = el("details", undefined, "vh-wide location-section"), policyBody = el("div", undefined, "policy-detail-body");
policyBox.append(text("summary", "policyTitle"), policyBody); body.append(policyBox);
const policyEditor = window.rustProxyPolicy.create({ value: value.policy || {}, scope: "location", onChange: sync });
policyBody.append(policyEditor.node); row.readPolicy = () => policyEditor.read();
const preview = el("section", undefined, "vh-wide location-preview");
preview.append(text("h4", "locationPreviewTitle"));
const previewStatus = text("p", "locationPreviewDisabled", "fine location-preview-disabled"); preview.append(previewStatus);
+2 -1
View File
@@ -579,6 +579,7 @@ function load(value = defaults(), migrationIds = [], show = true) {
transformEnabled.addEventListener("change", syncTransform); customTransformExtensions.addEventListener("change", syncTransform); syncTransform();
note(transformOptions, "vhTransformHelp");
g = group("vhHeaders"); g.parentElement.classList.add("hdr-rules-anchor"); vhostHeadersControl = headerEditors(g, value.headers || {});
g = group("policyTitle"); vhostPolicyEditor = window.rustProxyPolicy.create({ value: value.policy || {}, scope: "vhost", onChange: changed }); g.append(vhostPolicyEditor.node);
g = group("vhPages"); g.classList.add("vh-pages-grid"); pagesEditor = window.rustProxyPages.vhostEditor(g, value.pages || {});
initTabs(); dirty = false; if (latestStatus) renderStatus(latestStatus); if (show && !dialog.open) dialog.showModal();
headersPreviewControl?.refresh(); presetsRefresh();
@@ -662,7 +663,7 @@ function collect() {
allow_private: yes("oidc-private"), address_allowlist: lines(str("oidc-allowlist")),
tls_ca_pem: nullable("oidc-ca"), connect_timeout_seconds: num("oidc-connect"),
timeout_seconds: num("oidc-timeout"), session_ttl_seconds: num("oidc-ttl") },
backends: members, routes: paths, acl, headers,
backends: members, routes: paths, acl, headers, policy: vhostPolicyEditor ? vhostPolicyEditor.read() : {},
load_balancing: {
algorithm: str("algorithm"), ...(vhostBalancingControl?.hash() ? { hash: vhostBalancingControl.hash() } : {}), slow_start_seconds: num("slow-start"), keepalive: { enabled: yes("keepalive"), idle_timeout_seconds: num("idle-timeout"), max_idle_per_host: num("max-idle"), tcp_keepalive_seconds: num("tcp-keepalive"), pool_recycle_requests: num("pool-recycle-requests"), pool_recycle_seconds: num("pool-recycle-seconds"), http1_max_buffer_bytes: num("http1-max-buffer") },
retry: { max_retries: num("retry-max"), retry_connect_errors: yes("retry-connect"), retry_timeouts: yes("retry-timeouts"), retry_statuses: str("retry-statuses").split(/[\s,]+/).filter(Boolean).map(value => Number(value)) },
+1
View File
@@ -61,6 +61,7 @@ function headersPreview(parent) {
const column = (key, hint) => { const col = el("section", undefined, "hdr-preview-col"); col.append(text("h4", key), text("p", hint, "fine")); const listNode = el("ul", undefined, "hdr-preview-list"); col.append(listNode); columns.append(col); return listNode; };
const requestList = column("hdrPreviewRequest", "hdrPreviewRequestHint"), responseList = column("hdrPreviewResponse", "hdrPreviewResponseHint");
box.append(text("p", "hdrPreviewHelp", "fine"));
box.append(text("p", "policyHeaderPreviewHelp", "fine"));
const fillSelect = (node, options, current) => { node.replaceChildren(...options.map(([value, label]) => { const o = el("option", label); o.value = value; return o; })); node.value = options.some(([v]) => v === current) ? current : options[0]?.[0] ?? ""; return node.value; };
const readRoutes = () => { try { return JSON.parse(read("paths")?.value || "[]"); } catch { return []; } };
const safe = fn => { try { return fn(); } catch { return undefined; } };