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/public/cloud/admin-abuse-policy.js

423 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.

const POLICY_RULES = Object.freeze({
outbound_tcp_syn_sweep: Object.freeze({
label: '对外 TCP SYN 扫描', direction: 'outbound', protocol: 'tcp',
signals: Object.freeze(['tcp_syn_flows', 'unique_remote_ips']),
}),
outbound_tcp_port_scan: Object.freeze({
label: '对外 TCP 端口扫描', direction: 'outbound', protocol: 'tcp',
signals: Object.freeze(['tcp_syn_flows', 'max_remote_ports_per_remote_ip']),
}),
outbound_udp_fanout: Object.freeze({
label: '对外 UDP 扇出', direction: 'outbound', protocol: 'udp',
signals: Object.freeze(['udp_new_flows', 'unique_remote_ips']),
}),
inbound_tcp_syn_attack: Object.freeze({
label: '入站 TCP SYN 攻击', direction: 'inbound', protocol: 'tcp',
signals: Object.freeze(['tcp_syn_flows', 'tcp_unreplied_flows']),
}),
inbound_tcp_port_scan: Object.freeze({
label: '入站 TCP 端口扫描', direction: 'inbound', protocol: 'tcp',
signals: Object.freeze(['tcp_syn_flows', 'max_local_ports_per_remote_ip']),
}),
inbound_udp_flood: Object.freeze({
label: '入站 UDP Flood', direction: 'inbound', protocol: 'udp',
signals: Object.freeze(['udp_active_flows', 'udp_new_flows']),
}),
});
const SIGNAL_LABELS = Object.freeze({
tcp_syn_flows: 'TCP SYN 新建 Flow',
tcp_unreplied_flows: 'TCP 未应答 Flow',
udp_active_flows: 'UDP 活跃 Flow',
udp_new_flows: 'UDP 新建 Flow',
unique_remote_ips: '唯一远端 IP',
max_remote_ports_per_remote_ip: '单远端 IP 最大目标端口数',
max_local_ports_per_remote_ip: '单远端 IP 最大本地端口数',
});
const WINDOW_LIMITS = Object.freeze({
warmup: 1440, suspicious: 60, high: 60, clear: 60,
});
function exactKeys(value, expected) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
const actual = Object.keys(value).sort();
return actual.length === expected.length
&& actual.every((key, index) => key === [...expected].sort()[index]);
}
function positiveInteger(value, maximum, label) {
if (!Number.isInteger(value) || value < 1 || value > maximum) {
throw new Error(`${label}必须是 1 至 ${maximum} 的整数。`);
}
return value;
}
export function normalizePolicyDefinition(input) {
if (!exactKeys(input, ['engine_version', 'windows', 'rules'])
|| input.engine_version !== 1
|| !exactKeys(input.windows, Object.keys(WINDOW_LIMITS))
|| !exactKeys(input.rules, Object.keys(POLICY_RULES))) {
throw new Error('策略定义与当前检测引擎不兼容。');
}
const windows = {};
for (const [name, maximum] of Object.entries(WINDOW_LIMITS)) {
windows[name] = positiveInteger(input.windows[name], maximum, '连续窗口');
}
const rules = {};
for (const [code, catalog] of Object.entries(POLICY_RULES)) {
const rule = input.rules[code];
if (!exactKeys(rule, ['enabled', 'direction', 'protocol', 'signals', 'high'])
|| typeof rule.enabled !== 'boolean'
|| rule.direction !== catalog.direction
|| rule.protocol !== catalog.protocol
|| !exactKeys(rule.signals, catalog.signals)
|| !exactKeys(rule.high, catalog.signals)) {
throw new Error(`规则 ${code} 的身份或指标不完整。`);
}
const signals = {}; const high = {};
for (const signal of catalog.signals) {
signals[signal] = positiveInteger(rule.signals[signal], 1000000000, '可疑阈值');
high[signal] = positiveInteger(rule.high[signal], 1000000000, '高风险阈值');
if (high[signal] < signals[signal]) {
throw new Error(`${SIGNAL_LABELS[signal] || signal}的高风险阈值不能低于可疑阈值。`);
}
}
rules[code] = {
enabled: rule.enabled,
direction: catalog.direction,
protocol: catalog.protocol,
signals,
high,
};
}
return {engine_version: 1, windows, rules};
}
export function normalizePolicySnapshot(input) {
if (!input || typeof input !== 'object'
|| !Number.isInteger(input.revision) || input.revision < 1
|| !/^[a-f0-9]{64}$/.test(String(input.policy_hash || ''))) {
throw new Error('策略服务返回了无效身份。');
}
return Object.freeze({
revision: input.revision,
policy_hash: String(input.policy_hash),
definition: normalizePolicyDefinition(input.definition),
published_by: input.published_by ?? null,
published_at: Number(input.published_at || 0),
});
}
function definitionSignature(definition) {
return JSON.stringify(normalizePolicyDefinition(definition));
}
export function isUncertainPolicyMutation(error) {
return error?.mutationMayHaveApplied === true;
}
export function createPolicyWorkflow({runtime, onState, confirmPublish} = {}) {
const emit = typeof onState === 'function' ? onState : () => {};
const confirm = typeof confirmPublish === 'function'
? confirmPublish : async () => true;
const state = {
active: null, canManage: false, preview: null,
busy: false, mutationLocked: false, error: '', notice: '', renderVersion: 0,
};
const publishState = () => emit({...state});
const fail = (error, fallback) => {
state.error = error?.message || fallback;
if (isUncertainPolicyMutation(error)) {
state.mutationLocked = true;
state.error = '操作结果待核对,请重新读取当前策略确认;当前页面不会再次提交。';
}
state.notice = '';
};
const ready = () => runtime
&& typeof runtime.read === 'function' && typeof runtime.mutate === 'function';
async function load() {
if (state.busy) return false;
if (!ready()) {
state.error = '管理员请求组件不可用;监控列表不受影响。';
publishState(); return false;
}
state.busy = true; state.error = ''; state.notice = '正在读取当前策略…';
publishState();
try {
const payload = await runtime.read('/api/v1/admin/abuse-policies', {timeoutMs: 10000});
state.active = normalizePolicySnapshot(payload?.active);
state.renderVersion += 1;
state.canManage = payload?.can_manage === true;
state.preview = null;
state.mutationLocked = false;
state.notice = state.canManage
? '当前策略已读取;修改后请先预览,再确认发布。'
: '当前账户为只读管理员,可以查看策略但不能修改。';
state.error = '';
return true;
} catch (error) {
fail(error, '当前策略读取失败;监控列表仍可独立使用。');
return false;
} finally {
state.busy = false; publishState();
}
}
function changed() {
state.preview = null;
state.error = '';
state.notice = state.canManage ? '配置已修改,请重新预览。' : state.notice;
publishState();
}
async function preview(definition) {
if (state.busy || state.mutationLocked || !state.canManage || !state.active || !ready()) return false;
let canonical;
try { canonical = normalizePolicyDefinition(definition); }
catch (error) { fail(error, '策略输入无效。'); publishState(); return false; }
state.busy = true; state.error = ''; state.notice = '正在验证完整策略…';
publishState();
try {
const payload = await runtime.mutate('/api/v1/admin/abuse-policies/preview', {
method: 'POST', response: 'json',
body: {expected_revision: state.active.revision, definition: canonical},
});
const candidate = normalizePolicyDefinition(payload?.candidate?.definition);
if (!/^[a-f0-9]{64}$/.test(String(payload?.candidate?.policy_hash || ''))
|| definitionSignature(candidate) !== definitionSignature(canonical)
|| !Number.isInteger(payload?.result_revision)) {
throw Object.assign(new Error('策略预览回执无效,请刷新页面核对。'), {
mutationMayHaveApplied: true,
});
}
state.preview = Object.freeze({
changed: payload.changed === true,
policyHash: String(payload.candidate.policy_hash),
resultRevision: payload.result_revision,
signature: definitionSignature(canonical),
});
state.notice = state.preview.changed
? `预览通过,将发布为修订 ${state.preview.resultRevision}。`
: '策略内容没有变化,无需发布。';
return true;
} catch (error) {
state.preview = null; fail(error, '策略预览失败。'); return false;
} finally {
state.busy = false; publishState();
}
}
async function publish(definition) {
if (state.busy || state.mutationLocked || !state.canManage
|| !state.active || !state.preview?.changed || !ready()) return false;
let canonical;
try { canonical = normalizePolicyDefinition(definition); }
catch (error) { fail(error, '策略输入无效。'); publishState(); return false; }
if (definitionSignature(canonical) !== state.preview.signature) {
changed(); return false;
}
state.busy = true; state.error = ''; state.notice = '等待发布确认…';
publishState();
let confirmed = false;
try { confirmed = await confirm(state.preview.resultRevision); }
catch (error) { fail(error, '无法打开发布确认。'); }
if (!confirmed) {
state.busy = false; publishState(); return false;
}
state.notice = '正在发布完整策略…'; publishState();
try {
const payload = await runtime.mutate('/api/v1/admin/abuse-policies/active', {
method: 'PUT', response: 'json',
body: {expected_revision: state.active.revision, definition: canonical},
});
state.active = normalizePolicySnapshot(payload?.active);
state.renderVersion += 1;
state.canManage = payload?.can_manage === true;
state.preview = null;
state.notice = payload?.published === true
? `策略修订 ${state.active.revision} 已发布。`
: '策略内容没有变化。';
return true;
} catch (error) {
state.preview = null;
fail(error, '策略发布失败。'); return false;
} finally {
state.busy = false; publishState();
}
}
publishState();
return Object.freeze({load, changed, preview, publish, state: () => ({...state})});
}
function element(documentImpl, tag, className = '', value = '') {
const node = documentImpl.createElement(tag);
if (className) node.className = className;
if (value !== '') node.textContent = value;
return node;
}
function integerInputValue(node, label) {
const value = Number(node?.value);
if (!Number.isInteger(value)) throw new Error(`${label}必须填写整数。`);
return value;
}
function collectDefinition(root, active) {
const definition = normalizePolicyDefinition(active.definition);
for (const [name, maximum] of Object.entries(WINDOW_LIMITS)) {
const input = root.querySelector(`[data-policy-window="${name}"]`);
definition.windows[name] = positiveInteger(
integerInputValue(input, '连续窗口'), maximum, '连续窗口',
);
}
for (const [code, catalog] of Object.entries(POLICY_RULES)) {
definition.rules[code].enabled = root.querySelector(
`[data-policy-rule-enabled="${code}"]`,
)?.checked === true;
for (const signal of catalog.signals) {
definition.rules[code].signals[signal] = positiveInteger(
integerInputValue(root.querySelector(
`[data-policy-threshold="${code}:signals:${signal}"]`,
), '可疑阈值'), 1000000000, '可疑阈值',
);
definition.rules[code].high[signal] = positiveInteger(
integerInputValue(root.querySelector(
`[data-policy-threshold="${code}:high:${signal}"]`,
), '高风险阈值'), 1000000000, '高风险阈值',
);
}
}
return normalizePolicyDefinition(definition);
}
export function mountPolicyEditor(root, {windowImpl = window, documentImpl = document} = {}) {
if (!root) return null;
const byId = id => documentImpl.getElementById(id);
let runtime = null; let renderedIdentity = '';
try { runtime = windowImpl.VenixAdminRequestRuntime?.create?.() || null; }
catch (error) { runtime = null; }
function renderRules(active) {
const body = byId('abuse-policy-rules'); body.replaceChildren();
for (const [code, catalog] of Object.entries(POLICY_RULES)) {
const rule = active.definition.rules[code];
const card = element(documentImpl, 'article', 'admin-abuse-policy-rule');
const head = element(documentImpl, 'header', 'admin-abuse-policy-rule-head');
const title = element(documentImpl, 'div');
title.append(
element(documentImpl, 'strong', '', catalog.label),
element(documentImpl, 'small', '', `${catalog.direction === 'outbound' ? '出站' : '入站'} · ${catalog.protocol.toUpperCase()} · ${code}`),
);
const enabledLabel = element(documentImpl, 'label', 'form-check form-switch mb-0');
const enabled = element(documentImpl, 'input', 'form-check-input');
enabled.type = 'checkbox'; enabled.checked = rule.enabled;
enabled.dataset.policyRuleEnabled = code;
enabledLabel.append(enabled, element(documentImpl, 'span', 'form-check-label', '启用'));
head.append(title, enabledLabel); card.append(head);
const grid = element(documentImpl, 'div', 'admin-abuse-policy-thresholds');
for (const signal of catalog.signals) {
const group = element(documentImpl, 'div', 'admin-abuse-policy-signal');
group.append(element(documentImpl, 'span', 'admin-abuse-policy-signal-name', SIGNAL_LABELS[signal] || signal));
for (const [kind, label] of [['signals', '可疑'], ['high', '高风险']]) {
const field = element(documentImpl, 'label');
field.append(element(documentImpl, 'span', '', label));
const input = element(documentImpl, 'input', 'form-control');
input.type = 'number'; input.min = '1'; input.max = '1000000000'; input.step = '1';
input.value = String(rule[kind][signal]);
input.dataset.policyThreshold = `${code}:${kind}:${signal}`;
field.append(input); group.append(field);
}
grid.append(group);
}
card.append(grid); body.append(card);
}
}
function render(state) {
const status = byId('abuse-policy-status');
status.textContent = state.error || state.notice || '策略模块已就绪。';
status.className = `alert admin-abuse-policy-status ${state.error
? (state.mutationLocked ? 'alert-warning' : 'alert-danger') : 'alert-info'}`;
byId('abuse-policy-reload').disabled = state.busy;
if (!state.active) {
byId('abuse-policy-fieldset').hidden = true;
byId('abuse-policy-rules-fieldset').hidden = true;
byId('abuse-policy-preview-button').disabled = true;
byId('abuse-policy-publish').disabled = true;
return;
}
const identity = `${state.active.revision}:${state.active.policy_hash}:${state.renderVersion}`;
if (identity !== renderedIdentity) {
renderedIdentity = identity;
for (const [name, value] of Object.entries(state.active.definition.windows)) {
root.querySelector(`[data-policy-window="${name}"]`).value = String(value);
}
renderRules(state.active);
byId('abuse-policy-fieldset').hidden = false;
byId('abuse-policy-rules-fieldset').hidden = false;
}
byId('abuse-policy-meta').hidden = false;
byId('abuse-policy-current-revision').textContent = String(state.active.revision);
byId('abuse-policy-revision').textContent = `修订 ${state.active.revision}`;
byId('abuse-policy-hash').textContent = state.active.policy_hash;
byId('abuse-policy-permission').textContent = state.canManage ? '超级管理员可编辑' : '只读';
const disabled = state.busy || state.mutationLocked || !state.canManage;
for (const field of root.querySelectorAll('fieldset input')) field.disabled = disabled;
byId('abuse-policy-preview-button').disabled = disabled;
byId('abuse-policy-publish').disabled = disabled || state.preview?.changed !== true;
const preview = byId('abuse-policy-preview');
preview.hidden = !state.preview;
if (state.preview) {
byId('abuse-policy-preview-title').textContent = state.preview.changed
? `将发布修订 ${state.preview.resultRevision}` : '没有检测到变化';
byId('abuse-policy-preview-message').textContent = state.preview.changed
? '完整策略已经通过服务端校验,请确认后发布。' : '当前表单与生效策略一致。';
byId('abuse-policy-preview-hash').textContent = state.preview.policyHash;
}
}
const confirmPublish = async revision => {
if (windowImpl.VenixAdminDangerDialog?.confirm) {
return windowImpl.VenixAdminDangerDialog.confirm({
tone: 'warning', title: `发布检测策略修订 ${revision}`,
message: '新采样将使用这组阈值;已入队的历史采样继续使用其冻结版本。请确认已经核对全部规则。',
confirmText: '确认发布',
});
}
return windowImpl.confirm?.(`确认发布检测策略修订 ${revision}?`) === true;
};
const workflow = createPolicyWorkflow({runtime, onState: render, confirmPublish});
root.addEventListener('input', event => {
if (event.target?.matches?.('[data-policy-window], [data-policy-rule-enabled], [data-policy-threshold]')) workflow.changed();
});
byId('abuse-policy-reload').addEventListener('click', () => { void workflow.load(); });
byId('abuse-policy-preview-button').addEventListener('click', () => {
const active = workflow.state().active;
if (!active) return;
try { void workflow.preview(collectDefinition(root, active)); }
catch (error) {
byId('abuse-policy-status').textContent = error.message || '策略输入无效。';
byId('abuse-policy-status').className = 'alert alert-danger admin-abuse-policy-status';
}
});
byId('abuse-policy-form').addEventListener('submit', event => {
event.preventDefault();
const active = workflow.state().active;
if (!active) return;
try { void workflow.publish(collectDefinition(root, active)); }
catch (error) {
byId('abuse-policy-status').textContent = error.message || '策略输入无效。';
byId('abuse-policy-status').className = 'alert alert-danger admin-abuse-policy-status';
}
});
void workflow.load();
return workflow;
}
const policyRoot = typeof document === 'undefined'
? null : document.querySelector('[data-admin-abuse-policy]');
if (policyRoot) mountPolicyEditor(policyRoot);