// 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('
', { 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; });