You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/AdminFabricWizardBehaviorTe...

357 lines
18 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import vm from 'node:vm';
const source = await readFile(new URL('../public/cloud/admin-fabric.js', import.meta.url), 'utf8');
class Node {
constructor(tag = 'div') {
this.tagName = tag.toUpperCase(); this.children = []; this.dataset = {};
this.listeners = new Map(); this.attributes = new Map(); this.hidden = false;
this.disabled = false; this.value = ''; this.className = ''; this._text = '';
const classes = new Set();
this.classList = {
add: (...values) => values.forEach(value => classes.add(value)),
remove: (...values) => values.forEach(value => classes.delete(value)),
contains: value => classes.has(value),
};
}
set textContent(value) { this._text = String(value); this.children = []; }
get textContent() { return this._text + this.children.map(child => child.textContent).join(''); }
set innerHTML(_) { throw new Error('Fabric content must never be interpreted as HTML.'); }
get options() { return this.children; }
append(...values) { this.children.push(...values); }
replaceChildren(...values) { this._text = ''; this.children = []; this.append(...values); }
setAttribute(key, value) { this.attributes.set(key, String(value)); }
removeAttribute(key) { this.attributes.delete(key); }
getAttribute(key) { return this.attributes.get(key) ?? null; }
addEventListener(key, handler) {
const handlers = this.listeners.get(key) || []; handlers.push(handler);
this.listeners.set(key, handlers);
}
dispatch(key, fields = {}) {
const event = { target: this, currentTarget: this, preventDefault() {}, ...fields };
for (const handler of this.listeners.get(key) || []) handler(event);
}
}
const flush = async () => { for (let index = 0; index < 30; index += 1) await Promise.resolve(); };
function workflow(stage, changes = {}) {
return {
stage, can_probe: stage === 'needs_probe' || stage === 'blocked',
can_apply: stage === 'ready_to_apply',
can_reconcile: stage === 'needs_reconcile' || stage === 'active',
blocking_reasons: stage === 'blocked' ? ['firewall_owner_not_nftables'] : [],
action_mode: stage === 'ready_to_apply' ? 'apply'
: stage === 'needs_reconcile' || stage === 'active' ? 'reconcile' : 'probe',
...changes,
};
}
function region(id, stage, changes = {}) {
return {
region_id: id, region_code: id === 1 ? 'hk' : 'sg',
region_name: id === 1 ? 'Hong Kong' : 'Singapore', region_status: 'active',
host_count: 2, required_host_count: 2, ready_host_count: 0,
blocked_host_count: 0, hosts: [], ready: stage === 'active',
mapping_state: stage === 'active' ? 'active' : 'unconfigured',
fabric_state: stage === 'active' ? 'active' : null,
workflow: workflow(stage), plan_preview: null,
...changes,
};
}
function preview(code = 'hk') {
return {
mode: 'automatic', fabric_id: `fabric-${code}`, fabric_region: code,
revision: 1, listen_port: 51820, overlay_cidr: '100.64.7.0/24', host_count: 2,
};
}
function fixture(initialRegions, canManage = true) {
const ids = [...source.matchAll(/byId\('([^']+)'\)/g)].map(match => match[1]);
ids.push('fabric-detect-hosts', 'fabric-auto-configure', 'fabric-reconcile');
const nodes = Object.fromEntries([...new Set(ids)].map(id => [id,
new Node(id === 'fabric-region-select' ? 'select' : 'div')]));
const actions = ['probe', 'apply', 'reconcile'].map(action => {
const id = { probe: 'fabric-detect-hosts', apply: 'fabric-auto-configure',
reconcile: 'fabric-reconcile' }[action];
const button = nodes[id]; button.tagName = 'BUTTON';
button.dataset.fabricPrimaryAction = ''; button.dataset.fabricAction = action;
return button;
});
const steps = ['select', 'probe', 'apply', 'reconcile'].map(step => {
const item = new Node('li'); item.dataset.fabricWizardStep = step; return item;
});
const root = new Node('main'); root.dataset.canManage = canManage ? '1' : '0';
const document = {
getElementById: id => nodes[id] || null,
createElement: tag => new Node(tag),
querySelector: selector => selector === '[data-admin-fabric]' ? root : null,
querySelectorAll: selector => selector === '[data-fabric-primary-action]'
? actions : selector === '[data-fabric-wizard-step]' ? steps : [],
};
let now = 0; let timerId = 0; const timers = new Map(); const requests = [];
const setTimeout = (callback, delay) => {
const id = ++timerId; timers.set(id, { callback, due: now + delay }); return id;
};
const clearTimeout = id => timers.delete(id);
const window = { ADMIN_CSRF_TOKEN: 'csrf-test', setTimeout, clearTimeout };
const fetch = (url, options) => new Promise((resolve, reject) => {
const request = { url: String(url), options, resolve, reject, settled: false };
requests.push(request);
options.signal.addEventListener('abort', () => {
if (!request.settled) { request.settled = true; reject(new Error('aborted')); }
});
});
vm.runInNewContext(source, { document, window, fetch, AbortController, Date, console },
{ filename: 'admin-fabric.js' });
async function respond(request, payload, status = 200) {
assert.ok(request, 'Expected an outstanding Fabric request.');
request.settled = true;
request.resolve({ ok: status >= 200 && status < 300, status, json: async () => payload });
await flush();
}
async function reject(request, error = new TypeError('network failed')) {
assert.ok(request, 'Expected an outstanding Fabric request.');
request.settled = true; request.reject(error); await flush();
}
async function advance(milliseconds) {
const end = now + milliseconds;
for (;;) {
const next = [...timers.entries()].filter(([, item]) => item.due <= end)
.sort((left, right) => left[1].due - right[1].due)[0];
if (!next) break;
now = next[1].due; timers.delete(next[0]); next[1].callback(); await flush();
}
now = end; await flush();
}
return { nodes, actions, steps, requests, respond, reject, advance, initialRegions };
}
// The server workflow, not browser-invented conditions, owns every enabled
// action and the read-only plan rendered after a successful fresh probe.
{
const test = fixture([region(1, 'needs_probe')]);
await test.respond(test.requests[0], { regions: test.initialRegions, engine_available: true });
assert.equal(test.nodes['fabric-detect-hosts'].disabled, false);
assert.equal(test.nodes['fabric-auto-configure'].disabled, true);
assert.equal(test.nodes['fabric-reconcile'].disabled, true);
test.nodes['fabric-detect-hosts'].dispatch('click'); await flush();
const mutation = test.requests[1];
assert.equal(mutation.url, '/api/v1/admin/fabric/regions/1/probe');
assert.equal(mutation.options.body, '{}');
assert.equal(mutation.options.headers['X-CSRF-Token'], 'csrf-test');
const ready = region(1, 'ready_to_apply', { ready_host_count: 2,
plan_preview: preview() });
await test.respond(mutation, { region: ready, engine_available: true });
assert.equal(test.nodes['fabric-auto-configure'].disabled, false);
assert.equal(test.nodes['fabric-plan-id'].textContent, 'fabric-hk');
assert.equal(test.nodes['fabric-plan-overlay'].textContent, '100.64.7.0/24');
assert.match(test.nodes['fabric-notice'].textContent, /检测通过/);
}
// rp_filter diagnostics expose the bounded values that affect the policy
// decision. Alma/RHEL strict defaults and the public underlay stay visible as
// preserved OS/operator policy; an absent owned Fabric interface is pending
// automatic configuration, not a failed vnet/tap probe.
{
const host = {
host_id: '1', host_name: 'alma', engine_region: 'hk', host_enabled: true,
scheduler_state: 'active', pool_name: 'hk', pool_status: 'active',
line_name: 'Hong Kong', line_status: 'active', platform_ready: true,
configured: true, reachable: true, endpoint_ip: '203.0.113.11',
endpoint_source: 'ssh_host_ipv4', probe_checked: true, probed_at: 1770000100,
fabric_member: false, fabric_state: 'unchecked', transport_verified: false,
observed_revision: 0, readiness_state: 'ready', reasons: [],
capabilities: {
ip_forward: 1, rp_filter: 0, rp_filter_all: 0,
rp_filter_default: 1, rp_filter_default_effective: 1,
underlay_interface: 'br0', rp_filter_underlay_raw: 1,
rp_filter_underlay_effective: 1, rp_filter_fabric_raw: null,
rp_filter_fabric_effective: null, public_selector: 'bridge:br0',
public_verified: true, interfaces: ['br0', 'vnet3', 'vnet10'],
},
};
const strictFabricHost = {
...host, host_id: '2', host_name: 'existing-strict',
capabilities: {
...host.capabilities, rp_filter_fabric_raw: 1,
rp_filter_fabric_effective: 1,
},
};
const test = fixture([region(1, 'ready_to_apply', {
host_count: 2, required_host_count: 2, ready_host_count: 2,
hosts: [host, strictFabricHost], plan_preview: preview(),
})]);
await test.respond(test.requests[0], { regions: test.initialRegions, engine_available: true });
const copy = test.nodes['fabric-hosts-body'].textContent;
assert.match(copy, /rp_filter all:raw 0 · effective 0(关闭,兼容)/);
assert.match(copy, /rp_filter default:raw 1 · effective 1(strict,发行版默认保留)/);
assert.match(copy, /Endpoint br0:raw 1 · effective 1(strict,公网接口保留)/);
assert.match(copy, /wg-fabric0:未创建(自动配置时由平台设为 2)/);
assert.match(copy, /wg-fabric0:raw 1 · effective 1(strict,自动配置将收敛为 2)/);
assert.match(copy, /仅平台自有 wg-fabric0 与 VPC bridge 设为 2/);
assert.doesNotMatch(copy, /vnet3|vnet10/);
}
// Mixed-version responses keep the legacy all value useful without claiming
// that omitted detailed evidence was checked.
{
const host = {
host_id: '1', host_name: 'legacy', engine_region: 'hk',
capabilities: { ip_forward: 1, rp_filter: 2, underlay_interface: 'br0' },
};
const test = fixture([region(1, 'needs_probe', { host_count: 1, hosts: [host] })]);
await test.respond(test.requests[0], { regions: test.initialRegions, engine_available: true });
const copy = test.nodes['fabric-hosts-body'].textContent;
assert.match(copy, /rp_filter all:raw 2 · effective 2(loose,兼容)/);
assert.match(copy, /rp_filter default:未检测/);
assert.match(copy, /Endpoint br0:未检测/);
assert.match(copy, /wg-fabric0:未检测/);
}
// Double activation emits one apply only. A 200 response that has not reached
// the authoritative active stage is never painted as success and advances to
// the server-selected reconcile step.
{
const ready = region(1, 'ready_to_apply', { plan_preview: preview() });
const test = fixture([ready]);
await test.respond(test.requests[0], { regions: test.initialRegions, engine_available: true });
test.nodes['fabric-auto-configure'].dispatch('click');
test.nodes['fabric-auto-configure'].dispatch('click'); await flush();
assert.equal(test.requests.filter(request => request.options.method === 'POST').length, 1);
const pending = region(1, 'needs_reconcile', { plan_preview: { ...preview(), mode: 'existing' } });
await test.respond(test.requests[1], { regions: [pending], engine_available: true });
assert.match(test.nodes['fabric-notice'].textContent, /尚未 active/);
assert.ok(!test.nodes['fabric-notice'].className.includes('is-success'));
assert.equal(test.nodes['fabric-auto-configure'].disabled, true);
assert.equal(test.nodes['fabric-reconcile'].disabled, false);
}
// A region change while a request is in flight cannot redirect the returned
// projection into the newly selected region or redraw that region as active.
{
const first = region(1, 'ready_to_apply', { plan_preview: preview() });
const second = region(2, 'needs_probe');
const test = fixture([first, second]);
await test.respond(test.requests[0], { regions: test.initialRegions, engine_available: true });
test.nodes['fabric-auto-configure'].dispatch('click'); await flush();
test.nodes['fabric-region-select'].value = '2';
test.nodes['fabric-region-select'].dispatch('change'); await flush();
await test.respond(test.requests[1], { regions: [region(1, 'active'), second], engine_available: true });
assert.equal(test.nodes['fabric-region-select'].value, '2');
assert.match(test.nodes['fabric-wizard-stage'].textContent, /等待检测/);
assert.match(test.nodes['fabric-notice'].textContent, /后来选择的地区/);
}
// A write timeout is an unknown outcome. It releases the in-flight lock but
// prevents replay of automatic apply from the stale preflight projection.
{
const ready = region(1, 'ready_to_apply', { plan_preview: preview() });
const test = fixture([ready]);
await test.respond(test.requests[0], { regions: test.initialRegions, engine_available: true });
test.nodes['fabric-auto-configure'].dispatch('click'); await flush();
await test.advance(240000);
assert.match(test.nodes['fabric-notice'].textContent, /结果尚未确认/);
assert.match(test.nodes['fabric-wizard-stage'].textContent, /尚未确认/);
assert.equal(test.nodes['fabric-auto-configure'].disabled, true);
assert.equal(test.nodes['fabric-reconcile'].disabled, false,
'Unknown outcomes must expose only the server-side reconcile recovery path.');
test.nodes['fabric-auto-configure'].dispatch('click'); await flush();
assert.equal(test.requests.filter(request => request.options.method === 'POST').length, 1,
'An unknown apply outcome must never be replayed from stale browser state.');
test.nodes['fabric-reconcile'].dispatch('click'); await flush();
assert.equal(test.requests.filter(request => request.options.method === 'POST').length, 2);
assert.match(test.requests[2].url, /\/regions\/1\/reconcile$/);
await test.respond(test.requests[2], { regions: [region(1, 'active')], engine_available: true });
assert.match(test.nodes['fabric-notice'].textContent, /通过全部门禁/);
}
// Once a write has been dispatched, a non-HTTP fetch failure and every HTTP
// 5xx response are unknown outcomes. An explicit 4xx rejection remains
// definitive and does not invent an in-flight apply.
{
const ready = region(1, 'ready_to_apply', { plan_preview: preview() });
const test = fixture([ready]);
await test.respond(test.requests[0], { regions: test.initialRegions, engine_available: true });
test.nodes['fabric-auto-configure'].dispatch('click'); await flush();
await test.reject(test.requests[1]);
assert.match(test.nodes['fabric-notice'].textContent, /网络连接中断.*尚未确认/);
assert.equal(test.nodes['fabric-auto-configure'].disabled, true);
assert.equal(test.nodes['fabric-reconcile'].disabled, false);
}
{
const ready = region(1, 'ready_to_apply', { plan_preview: preview() });
const test = fixture([ready]);
await test.respond(test.requests[0], { regions: test.initialRegions, engine_available: true });
test.nodes['fabric-auto-configure'].dispatch('click'); await flush();
await test.respond(test.requests[1], { detail: '网关等待引擎超时' }, 504);
assert.match(test.nodes['fabric-notice'].textContent, /504.*结果尚未确认/);
assert.equal(test.nodes['fabric-auto-configure'].disabled, true,
'A gateway timeout must never leave stale automatic apply available.');
assert.equal(test.nodes['fabric-reconcile'].disabled, false,
'A gateway timeout must expose the reconcile recovery path.');
}
{
const ready = region(1, 'ready_to_apply', { plan_preview: preview() });
const test = fixture([ready]);
await test.respond(test.requests[0], { regions: test.initialRegions, engine_available: true });
test.nodes['fabric-auto-configure'].dispatch('click'); await flush();
await test.respond(test.requests[1], { detail: '地区宿主机集合已经变化' }, 409);
assert.match(test.nodes['fabric-notice'].textContent, /集合已经变化/);
assert.equal(test.nodes['fabric-auto-configure'].disabled, false,
'A definitive HTTP rejection must not be converted into an unknown write outcome.');
assert.equal(test.nodes['fabric-reconcile'].disabled, true);
}
// Unknown outcomes are isolated by region. A later successful action for a
// different region must not clear the first region's stale-write guard.
{
const first = region(1, 'ready_to_apply', { plan_preview: preview() });
const second = region(2, 'ready_to_apply', { plan_preview: preview('sg') });
const test = fixture([first, second]);
await test.respond(test.requests[0], { regions: test.initialRegions, engine_available: true });
test.nodes['fabric-auto-configure'].dispatch('click'); await flush();
await test.reject(test.requests[1]);
assert.equal(test.nodes['fabric-auto-configure'].disabled, true);
assert.equal(test.nodes['fabric-reconcile'].disabled, false);
test.nodes['fabric-region-select'].value = '2';
test.nodes['fabric-region-select'].dispatch('change'); await flush();
assert.equal(test.nodes['fabric-auto-configure'].disabled, false);
test.nodes['fabric-auto-configure'].dispatch('click'); await flush();
await test.respond(test.requests[2], {
regions: [first, region(2, 'active', { plan_preview: { ...preview('sg'), mode: 'existing' } })],
engine_available: true,
});
assert.match(test.nodes['fabric-notice'].textContent, /通过权威回读/);
test.nodes['fabric-region-select'].value = '1';
test.nodes['fabric-region-select'].dispatch('change'); await flush();
assert.match(test.nodes['fabric-wizard-stage'].textContent, /尚未确认/);
assert.equal(test.nodes['fabric-auto-configure'].disabled, true,
'A successful action in region 2 must not unlock region 1 stale apply.');
assert.equal(test.nodes['fabric-reconcile'].disabled, false,
'Region 1 must keep its own reconcile-only recovery path.');
}
// The diagnostic HTTP-200 shell is not a successful load and never enables a
// write, even when a stale region projection is present.
{
const stale = region(1, 'engine_unavailable', {
workflow: workflow('engine_unavailable', { can_probe: false, action_mode: 'none',
blocking_reasons: ['engine_unavailable'] }),
});
const test = fixture([stale]);
await test.respond(test.requests[0], { regions: test.initialRegions,
engine_available: false, engine_error: 'Fabric 引擎状态暂时无法读取。' });
assert.equal(test.actions.every(button => button.disabled), true);
assert.ok(test.nodes['fabric-notice'].className.includes('is-error'));
}
console.log('Administrator Fabric inline wizard gating, per-region unknown outcomes, stale selection and timeout safety passed.');