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/AdminAbusePolicyBehaviorTes...

187 lines
7.2 KiB
JavaScript

import assert from 'node:assert/strict';
import fs from 'node:fs';
const source = fs.readFileSync(new URL(
'../public/cloud/admin-abuse-policy.js', import.meta.url,
), 'utf8');
const module = await import(
`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`
);
const definition = {
engine_version: 1,
windows: {warmup: 60, suspicious: 3, high: 2, clear: 5},
rules: {
outbound_tcp_syn_sweep: rule(true, 'outbound', 'tcp',
{tcp_syn_flows: 800, unique_remote_ips: 128},
{tcp_syn_flows: 4000, unique_remote_ips: 512}),
outbound_tcp_port_scan: rule(true, 'outbound', 'tcp',
{tcp_syn_flows: 400, max_remote_ports_per_remote_ip: 48},
{tcp_syn_flows: 2000, max_remote_ports_per_remote_ip: 256}),
outbound_udp_fanout: rule(true, 'outbound', 'udp',
{udp_new_flows: 1200, unique_remote_ips: 256},
{udp_new_flows: 6000, unique_remote_ips: 1024}),
inbound_tcp_syn_attack: rule(true, 'inbound', 'tcp',
{tcp_syn_flows: 4000, tcp_unreplied_flows: 3000},
{tcp_syn_flows: 20000, tcp_unreplied_flows: 15000}),
inbound_tcp_port_scan: rule(true, 'inbound', 'tcp',
{tcp_syn_flows: 400, max_local_ports_per_remote_ip: 48},
{tcp_syn_flows: 2000, max_local_ports_per_remote_ip: 256}),
inbound_udp_flood: rule(true, 'inbound', 'udp',
{udp_active_flows: 5000, udp_new_flows: 1000},
{udp_active_flows: 25000, udp_new_flows: 5000}),
},
};
function rule(enabled, direction, protocol, signals, high) {
return {enabled, direction, protocol, signals, high};
}
const hash = 'a'.repeat(64);
const snapshot = revision => ({
revision, policy_hash: hash, definition,
published_by: null, published_at: 0,
});
const clone = value => JSON.parse(JSON.stringify(value));
assert.equal(module.normalizePolicyDefinition(clone(definition)).windows.warmup, 60);
assert.throws(() => module.normalizePolicyDefinition({
...clone(definition), extra: true,
}), /不兼容/);
const missingRule = clone(definition);
delete missingRule.rules.inbound_udp_flood;
assert.throws(() => module.normalizePolicyDefinition(missingRule), /不兼容/);
const decimal = clone(definition);
decimal.rules.inbound_udp_flood.signals.udp_new_flows = 1.5;
assert.throws(() => module.normalizePolicyDefinition(decimal), /整数/);
const readonlyCalls = [];
const readonlyWorkflow = module.createPolicyWorkflow({
runtime: {
read: async path => {
readonlyCalls.push(['read', path]);
return {active: snapshot(1), can_manage: false};
},
mutate: async (...args) => { readonlyCalls.push(['mutate', ...args]); },
},
});
assert.equal(await readonlyWorkflow.load(), true);
assert.equal(readonlyWorkflow.state().canManage, false);
assert.equal(await readonlyWorkflow.preview(clone(definition)), false);
assert.equal(readonlyCalls.filter(call => call[0] === 'mutate').length, 0,
'A read-only administrator dispatched a policy mutation.');
const draft = clone(definition);
draft.windows.clear = 6;
const calls = [];
const runtime = {
read: async path => {
calls.push(['read', path]);
return {active: snapshot(4), can_manage: true};
},
mutate: async (path, options) => {
calls.push(['mutate', path, options]);
if (path.endsWith('/preview')) return {
current: snapshot(4),
candidate: {policy_hash: 'b'.repeat(64), definition: draft},
changed: true, result_revision: 5,
};
return {active: {...snapshot(5), policy_hash: 'b'.repeat(64), definition: draft},
published: true, can_manage: true};
},
};
let confirmations = 0;
const workflow = module.createPolicyWorkflow({
runtime,
confirmPublish: async revision => { confirmations += 1; return revision === 5; },
});
assert.equal(await workflow.load(), true);
assert.equal(await workflow.preview(draft), true);
const previewCall = calls.find(call => call[1]?.endsWith?.('/preview'));
assert.equal(previewCall[2].body.expected_revision, 4);
assert.deepEqual(Object.keys(previewCall[2].body.definition.rules).sort(),
Object.keys(definition.rules).sort(), 'Preview did not send the whole catalog.');
workflow.changed();
assert.equal(await workflow.publish(draft), false,
'A stale preview remained publishable after editing.');
assert.equal(await workflow.preview(draft), true);
assert.equal(await workflow.publish(draft), true);
const publishCalls = calls.filter(call => call[1]?.endsWith?.('/active'));
assert.equal(confirmations, 1);
assert.equal(publishCalls.length, 1);
assert.equal(publishCalls[0][2].method, 'PUT');
assert.equal(publishCalls[0][2].body.expected_revision, 4);
assert.equal(workflow.state().active.revision, 5);
let uncertainCalls = 0;
const uncertainWorkflow = module.createPolicyWorkflow({
runtime: {
read: async () => ({active: snapshot(7), can_manage: true}),
mutate: async () => {
uncertainCalls += 1;
throw Object.assign(new Error('timeout'), {mutationMayHaveApplied: true});
},
},
});
await uncertainWorkflow.load();
assert.equal(await uncertainWorkflow.preview(draft), false);
assert.equal(uncertainWorkflow.state().mutationLocked, true);
assert.match(uncertainWorkflow.state().error, /不会再次提交/);
assert.equal(await uncertainWorkflow.preview(draft), false);
assert.equal(uncertainCalls, 1, 'Unknown-effect preview was replayed.');
assert.equal(await uncertainWorkflow.load(), true);
assert.equal(uncertainWorkflow.state().mutationLocked, false,
'A successful authoritative reload did not release the editor lock.');
let safeCalls = 0;
const safeWorkflow = module.createPolicyWorkflow({
runtime: {
read: async () => ({active: snapshot(8), can_manage: true}),
mutate: async () => {
safeCalls += 1;
throw Object.assign(new Error('stale'), {
status: 409, mutationMayHaveApplied: false,
});
},
},
});
await safeWorkflow.load();
assert.equal(await safeWorkflow.preview(draft), false);
assert.equal(safeWorkflow.state().mutationLocked, false);
assert.equal(safeCalls, 1);
let stalePublishCalls = 0;
const stalePublish = module.createPolicyWorkflow({
runtime: {
read: async () => ({active: snapshot(8), can_manage: true}),
mutate: async path => {
if (path.endsWith('/preview')) return {
candidate: {policy_hash: 'b'.repeat(64), definition: draft},
changed: true, result_revision: 9,
};
stalePublishCalls += 1;
throw Object.assign(new Error('stale'), {
status: 409, mutationMayHaveApplied: false,
});
},
},
confirmPublish: async () => true,
});
await stalePublish.load();
await stalePublish.preview(draft);
assert.equal(await stalePublish.publish(draft), false);
assert.equal(stalePublish.state().preview, null);
assert.equal(await stalePublish.publish(draft), false);
assert.equal(stalePublishCalls, 1,
'A confirmed failed publish retained a reusable stale preview.');
const monitorSentinel = {items: ['still-visible']};
const failedStates = [];
const failed = module.createPolicyWorkflow({
runtime: {read: async () => { throw new Error('offline'); }, mutate: async () => {}},
onState: state => failedStates.push(state),
});
assert.equal(await failed.load(), false);
assert.deepEqual(monitorSentinel.items, ['still-visible']);
assert.match(failedStates.at(-1).error, /offline/);
console.log('Administrator abuse-policy JavaScript behavior passed.');