From bb29c6f2f7da7d61dde263b193ecfb3a34661a17 Mon Sep 17 00:00:00 2001 From: codex Date: Mon, 9 Nov 2026 03:34:07 +0800 Subject: [PATCH] feat(admin): add abuse policy editor --- web/public/cloud/admin-abuse-monitoring.css | 124 +++++ web/public/cloud/admin-abuse-policy.js | 422 ++++++++++++++++++ .../venix/admin/cloud/abuse_monitoring.tpl | 42 ++ web/resources/views/venix/layout_assets.tpl | 2 +- web/tests/AdminAbusePolicyBehaviorTest.mjs | 186 ++++++++ .../CloudAdminAbusePolicyUiContractTest.php | 67 +++ web/tests/CloudAssetVersionContractTest.php | 2 +- 7 files changed, 843 insertions(+), 2 deletions(-) create mode 100644 web/public/cloud/admin-abuse-policy.js create mode 100644 web/tests/AdminAbusePolicyBehaviorTest.mjs create mode 100644 web/tests/CloudAdminAbusePolicyUiContractTest.php diff --git a/web/public/cloud/admin-abuse-monitoring.css b/web/public/cloud/admin-abuse-monitoring.css index 92623aec..024dd582 100644 --- a/web/public/cloud/admin-abuse-monitoring.css +++ b/web/public/cloud/admin-abuse-monitoring.css @@ -113,6 +113,123 @@ margin-top: 18px; } +.admin-abuse-policy-status { margin-bottom: 18px; } +.admin-abuse-policy-meta { + display: grid; + grid-template-columns: minmax(110px, .5fr) minmax(280px, 2fr) minmax(150px, .7fr); + gap: 12px; + margin-bottom: 20px; +} +.admin-abuse-policy-meta > span { + min-width: 0; + padding: 13px 15px; + border: 1px solid #e4e9f0; + border-radius: 12px; + background: #f8fafc; +} +.admin-abuse-policy-meta small, +.admin-abuse-policy-meta strong, +.admin-abuse-policy-meta code { display: block; } +.admin-abuse-policy-meta small { color: #7b8ca5; margin-bottom: 5px; } +.admin-abuse-policy-meta code { + overflow: hidden; + color: #344054; + font-size: 12px; + text-overflow: ellipsis; + white-space: nowrap; +} +.admin-abuse-policy-fieldset { min-width: 0; padding: 0; border: 0; } +.admin-abuse-policy-fieldset > legend { + float: none; + width: auto; + margin: 0 0 12px; + color: #344054; + font-size: 15px; + font-weight: 700; +} +.admin-abuse-policy-windows { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 12px; +} +.admin-abuse-policy-windows label, +.admin-abuse-policy-thresholds label { display: block; min-width: 0; } +.admin-abuse-policy-windows label > span, +.admin-abuse-policy-thresholds label > span { + display: block; + margin-bottom: 6px; + color: #475467; + font-size: 13px; + font-weight: 600; +} +.admin-abuse-policy-windows small { + display: block; + margin-top: 5px; + color: #98a2b3; + line-height: 1.45; +} +.admin-abuse-policy-rules { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 14px; +} +.admin-abuse-policy-rule { + min-width: 0; + padding: 16px; + border: 1px solid #e4e9f0; + border-radius: 14px; + background: #fff; +} +.admin-abuse-policy-rule-head { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 12px; + padding-bottom: 13px; + border-bottom: 1px solid #edf0f4; +} +.admin-abuse-policy-rule-head strong, +.admin-abuse-policy-rule-head small { display: block; } +.admin-abuse-policy-rule-head small { + margin-top: 4px; + color: #98a2b3; + overflow-wrap: anywhere; +} +.admin-abuse-policy-thresholds { display: grid; gap: 13px; padding-top: 13px; } +.admin-abuse-policy-signal { + display: grid; + grid-template-columns: minmax(150px, 1.35fr) repeat(2, minmax(100px, 1fr)); + gap: 10px; + align-items: end; +} +.admin-abuse-policy-signal-name { + align-self: center; + color: #344054; + font-size: 13px; + font-weight: 600; + line-height: 1.45; +} +.admin-abuse-policy-preview { + padding: 14px 16px; + border: 1px solid #b9e4dc; + border-radius: 12px; + background: #f1fbf8; + color: #2f5f57; +} +.admin-abuse-policy-preview > * { display: block; } +.admin-abuse-policy-preview p { margin-top: 4px; } +.admin-abuse-policy-preview code { + margin-top: 7px; + color: #267569; + overflow-wrap: anywhere; +} +.admin-abuse-policy-actions { + display: flex; + justify-content: flex-end; + gap: 10px; + flex-wrap: wrap; +} + #abuse-monitoring-detail .admin-abuse-direction-banner { border-radius: 10px; font-size: 13px; @@ -200,6 +317,13 @@ #abuse-monitoring-detail .admin-abuse-empty-detail { color: #667085; font-size: 13px; padding: 18px; text-align: center; } @media (max-width: 767.98px) { + .admin-abuse-policy-meta, + .admin-abuse-policy-windows, + .admin-abuse-policy-rules { grid-template-columns: 1fr; } + .admin-abuse-policy-signal { grid-template-columns: 1fr 1fr; } + .admin-abuse-policy-signal-name { grid-column: 1 / -1; } + .admin-abuse-policy-actions { display: grid; grid-template-columns: 1fr; } + .admin-abuse-policy-actions .btn { width: 100%; } [data-admin-abuse-monitoring] .admin-abuse-heading-actions, [data-admin-abuse-monitoring] .admin-abuse-heading-actions .btn { width: 100%; } [data-admin-abuse-monitoring] .admin-abuse-heading-actions { align-items: stretch; } diff --git a/web/public/cloud/admin-abuse-policy.js b/web/public/cloud/admin-abuse-policy.js new file mode 100644 index 00000000..00a70603 --- /dev/null +++ b/web/public/cloud/admin-abuse-policy.js @@ -0,0 +1,422 @@ +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); diff --git a/web/resources/views/venix/admin/cloud/abuse_monitoring.tpl b/web/resources/views/venix/admin/cloud/abuse_monitoring.tpl index a197e400..1f6e7315 100644 --- a/web/resources/views/venix/admin/cloud/abuse_monitoring.tpl +++ b/web/resources/views/venix/admin/cloud/abuse_monitoring.tpl @@ -37,6 +37,47 @@ {/if} +
+
+

检测与告警阈值

策略按完整版本发布;新采样会冻结当时版本,排队中的历史采样不会被新阈值改写。

+ 正在读取策略 +
+
+
正在读取当前检测策略;监控列表仍可独立使用。
+ +
+ + + +
+ + + +
+
+
+
+

筛选实例

入站攻击和对外可疑行为使用不同分类,避免把受攻击实例误判为滥用来源。

@@ -93,4 +134,5 @@ + {include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 9013eefd..5a25b60f 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026110803' scope='global'} +{assign var=venix_asset_version value='2026110901' scope='global'} diff --git a/web/tests/AdminAbusePolicyBehaviorTest.mjs b/web/tests/AdminAbusePolicyBehaviorTest.mjs new file mode 100644 index 00000000..b7f0204c --- /dev/null +++ b/web/tests/AdminAbusePolicyBehaviorTest.mjs @@ -0,0 +1,186 @@ +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.'); diff --git a/web/tests/CloudAdminAbusePolicyUiContractTest.php b/web/tests/CloudAdminAbusePolicyUiContractTest.php new file mode 100644 index 00000000..8475c10c --- /dev/null +++ b/web/tests/CloudAdminAbusePolicyUiContractTest.php @@ -0,0 +1,67 @@ +