From bddd36b533a443a006e3040c91514d098694ebf1 Mon Sep 17 00:00:00 2001 From: codex Date: Mon, 9 Nov 2026 04:44:49 +0800 Subject: [PATCH] feat(admin): expose abuse alert delivery history --- docs/DEPLOYMENT.md | 2 + .../CloudAdminAbuseMonitoringController.php | 13 + .../CloudAdminAbuseAlertHistoryService.php | 513 ++++++++++++++++++ web/config/routes_cloud.php | 2 + web/public/cloud/admin-abuse-alert-history.js | 387 +++++++++++++ web/public/cloud/admin-abuse-monitoring.css | 319 +++++++++++ .../venix/admin/cloud/abuse_monitoring.tpl | 29 + web/resources/views/venix/layout_assets.tpl | 2 +- .../AdminAbuseAlertHistoryBehaviorTest.mjs | 90 +++ .../CloudAdminAbuseAlertHistoryApiTest.php | 88 +++ ...CloudAdminAbuseAlertHistoryServiceTest.php | 247 +++++++++ ...udAdminAbuseAlertHistoryUiContractTest.php | 88 +++ .../CloudAdminAbusePolicyUiContractTest.php | 2 +- web/tests/CloudAssetVersionContractTest.php | 2 +- 14 files changed, 1781 insertions(+), 3 deletions(-) create mode 100644 web/app/Services/Cloud/CloudAdminAbuseAlertHistoryService.php create mode 100644 web/public/cloud/admin-abuse-alert-history.js create mode 100644 web/tests/AdminAbuseAlertHistoryBehaviorTest.mjs create mode 100644 web/tests/CloudAdminAbuseAlertHistoryApiTest.php create mode 100644 web/tests/CloudAdminAbuseAlertHistoryServiceTest.php create mode 100644 web/tests/CloudAdminAbuseAlertHistoryUiContractTest.php diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index e1404ede..5d16db55 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -164,6 +164,8 @@ libvirt 的持久 pool 定义就是 Agent 后续使用的映射,不另写存 事件 header 与 projection receipt 在同一个主库事务中写入,且事件先于 receipt;同一实例同一采样桶的多规则、双协议族转移合并为一个 header 和多个 item。`continued` 不产生事件,`policy_replaced` 与 `owner_changed` 只关闭 finding,不能伪造“恢复”事件。item 已冻结当时的聚合 evidence、规则身份和 finding 代次,后续投递不得回读会变化的 finding。v46 为每个事件建立至多一条 Telegram 投递决策;远端调用开始后的中断或回执不确定统一进入 `unknown`,禁止自动重放。删除用户时按事件冻结的 `user_id` 显式删除 header,item 与投递账本按当前外键和账户清理规则收敛,避免实例转交后遗留原租户数据。 +管理员“网络滥用监控 -> 滥用告警历史”通过 `GET /api/v1/admin/abuse-monitoring/alerts` 异步读取只读投影。没有投递行的事件显示为 `queued`,其余只显示 `pending`、`dispatching`、`sent`、`skipped`、`failed` 或 `unknown` 的安全文案;页面不提供重试、重新发送或任何写操作。接口不得返回 Telegram chat、绑定代次、token、冻结消息、内容/策略 hash、内部事件 key 或原始 evidence JSON,只允许展示白名单内的非负聚合计数。部署验收必须用只读管理员验证事件/实例/用户/节点独立筛选和分页,并确认移动端卡片可读;再用 `unknown` 测试记录确认页面明确提示“禁止自动重放”。 + `occurrence_generation` 与 `transition_revision` 只描述当前仍保留的 finding 生命周期,不是跨 retention 的全局幂等键;旧 finding 被清理后,同一规则以后允许从 `1/1` 重新建立。未来投递只能以不可变的 `event_id` / `item_key` 建立幂等边界,不能使用 generation/revision 猜测是否已经外发。账户删除与投影都必须遵循“先锁 user、再锁 instance”的顺序;正式部署还应在真实 MySQL 双连接下验收删除和投影并发,SQLite 行为测试不等价于 InnoDB 行锁门禁。 自动备份订阅通过独立的延期字段保留原逻辑执行时隙;只有已确认未应用且可安全重试的救援或磁盘切换竞态,才会退休空白制品并以递增的 `schedule_attempt` 建立新代次。每个资源预留的当前公网权威只来自 `cloud_resource_reservation_ips.active_claim = 1` 的一组 IPv4+IPv6 精确声明;两族允许具有各自的 generation 和 operation ID,但必须绑定同一资源预留和网络接入,并各自与具体 IP、地址池、宿主机、实例状态双向一致。`cloud_resource_reservations` 中旧的单地址列只保留审计形态,不参与当前地址读取、释放或管理员投影。释放时历史声明保留并把 `active_claim` 置空,具体 IP 同时清空 claim、operation、reservation 和 instance 归属。普通换 IP、独立恢复和维护迁移分别只允许 transition ledger、restore attempt 与 migration source debt 所有的完整双栈流程;旧 `CloudPlacementService` 单地址恢复、旧换 IP writer,以及缺少或损坏冻结身份的任务仍会在派发 CAS 前拒绝,不能绕过新账本。 diff --git a/web/app/Controllers/CloudAdminAbuseMonitoringController.php b/web/app/Controllers/CloudAdminAbuseMonitoringController.php index 0c5a0896..02210237 100644 --- a/web/app/Controllers/CloudAdminAbuseMonitoringController.php +++ b/web/app/Controllers/CloudAdminAbuseMonitoringController.php @@ -3,6 +3,7 @@ namespace App\Controllers; use App\Services\Cloud\CloudAccess; +use App\Services\Cloud\CloudAdminAbuseAlertHistoryService; use App\Services\Cloud\CloudAdminAbuseMonitoringService; /** Administrator-only, observe-only network-abuse monitoring API. */ @@ -31,4 +32,16 @@ final class CloudAdminAbuseMonitoringController return $response->withJson($payload) ->withHeader('Cache-Control', 'private, no-store'); } + + public function alerts($request, $response) + { + $actor = $request->getAttribute('cloud_actor') + ?? CloudAccess::actor(false); + $payload = (new CloudAdminAbuseAlertHistoryService())->page( + $actor, + $request->getQueryParams() + ); + return $response->withJson($payload) + ->withHeader('Cache-Control', 'private, no-store'); + } } diff --git a/web/app/Services/Cloud/CloudAdminAbuseAlertHistoryService.php b/web/app/Services/Cloud/CloudAdminAbuseAlertHistoryService.php new file mode 100644 index 00000000..95d8d698 --- /dev/null +++ b/web/app/Services/Cloud/CloudAdminAbuseAlertHistoryService.php @@ -0,0 +1,513 @@ + '对外 TCP SYN 扫描', + 'outbound_tcp_port_scan' => '对外 TCP 端口扫描', + 'outbound_udp_fanout' => '对外 UDP 扇出', + 'inbound_tcp_syn_attack' => '入站 TCP SYN 攻击', + 'inbound_tcp_port_scan' => '入站 TCP 端口扫描', + 'inbound_udp_flood' => '入站 UDP Flood', + ]; + private const EVIDENCE_LABELS = [ + 'tcp_active_flows' => 'TCP 活跃 Flow', + 'tcp_new_flows' => 'TCP 新建 Flow', + '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 数', + 'unique_remote_ports' => '唯一远端端口数', + 'unique_local_ports' => '唯一本地端口数', + 'max_remote_ports_per_remote_ip' => '单远端 IP 最大端口数', + 'max_remote_ips_per_remote_port' => '单远端端口最大 IP 数', + 'max_local_ports_per_remote_ip' => '单远端 IP 最大本地端口数', + 'max_remote_ips_per_local_port' => '单本地端口最大远端 IP 数', + ]; + + /** @param array $actor @param array $input */ + public function page(array $actor, array $input = []): array + { + self::authorize($actor); + $filters = self::filters($input); + $base = $this->baseQuery(); + $this->applyFactFilters($base, $filters); + $summary = $this->summary(clone $base); + + $query = clone $base; + $this->applyStatusFilter($query, $filters['status']); + $total = max(0, (int) $query->count('event.id')); + $pages = max(1, (int) ceil($total / $filters['per_page'])); + $filters['page'] = min($filters['page'], $pages); + $records = $query->select(self::columns()) + ->orderByDesc('event.id') + ->offset(($filters['page'] - 1) * $filters['per_page']) + ->limit($filters['per_page'])->get(); + + $eventIds = []; + foreach ($records as $record) { + $eventIds[] = (int) $record->event_id; + } + $items = $this->eventItems($eventIds); + $rows = []; + foreach ($records as $record) { + $eventId = (int) $record->event_id; + $rows[] = $this->eventRow($record, $items[$eventId] ?? []); + } + $from = $total === 0 ? 0 + : (($filters['page'] - 1) * $filters['per_page']) + 1; + + return [ + 'summary' => $summary + ['total' => array_sum($summary)], + 'filters' => $filters, + 'items' => $rows, + 'pagination' => [ + 'page' => $filters['page'], + 'per_page' => $filters['per_page'], + 'total' => $total, + 'total_pages' => $pages, + 'from' => $from, + 'to' => $from === 0 ? 0 : $from + count($rows) - 1, + ], + 'generated_at' => self::timestamp(time()), + ]; + } + + /** @param array $actor */ + private static function authorize(array $actor): void + { + if (!($actor['is_admin'] ?? false) + || (int) ($actor['user_id'] ?? 0) < 1) { + throw new CloudError('需要管理员权限', 403); + } + } + + /** @param array $input @return array */ + public static function filters(array $input): array + { + $allowed = [ + 'status', 'transition', 'severity', 'direction', 'ip_family', + 'event_id', 'instance_id', 'user_id', 'host_id', + 'query', 'page', 'per_page', + ]; + foreach ($input as $key => $value) { + if (!in_array($key, $allowed, true) + || (!is_string($value) && !is_int($value))) { + throw new CloudError('筛选参数无效', 400); + } + } + $filters = []; + foreach ([ + 'status' => self::STATUSES, + 'transition' => self::TRANSITIONS, + 'severity' => self::SEVERITIES, + 'direction' => self::DIRECTIONS, + 'ip_family' => self::IP_FAMILIES, + ] as $name => $values) { + $value = trim((string) ($input[$name] ?? '')); + if ($value !== '' && !in_array($value, $values, true)) { + throw new CloudError('筛选参数无效', 400); + } + $filters[$name] = $value; + } + foreach (['event_id', 'instance_id', 'user_id', 'host_id'] as $name) { + $value = trim((string) ($input[$name] ?? '')); + $filters[$name] = $value === '' ? null + : self::boundedInteger($value, 1, PHP_INT_MAX, $name); + } + $query = trim((string) ($input['query'] ?? '')); + $filters['query'] = $query === '' ? '' : (string) self::boundedInteger( + $query, 1, PHP_INT_MAX, '编号筛选' + ); + $filters['page'] = self::boundedInteger( + $input['page'] ?? 1, 1, 100000, '页码' + ); + $filters['per_page'] = self::boundedInteger( + $input['per_page'] ?? 20, 1, 50, '每页数量' + ); + return $filters; + } + + private function baseQuery() + { + return User::getConnectionResolver()->connection('default') + ->table('cloud_abuse_alert_events as event') + ->leftJoin('cloud_abuse_alert_deliveries as delivery', + 'delivery.event_id', '=', 'event.id') + ->leftJoin('cloud_instances as instance', + 'instance.id', '=', 'event.instance_id') + ->leftJoin('user as owner', 'owner.id', '=', 'event.user_id') + ->leftJoin('cloud_hosts as host', + 'host.id', '=', 'event.host_id'); + } + + /** @return list */ + private static function columns(): array + { + return [ + 'event.id as event_id', 'event.instance_id', 'event.user_id', + 'event.host_id', 'event.bucket_start', 'event.transition_count', + 'event.highest_severity', 'event.created_at', + 'instance.name as instance_name', + 'owner.user_name as user_name', 'host.name as host_name', + 'delivery.id as delivery_id', 'delivery.state as delivery_state', + 'delivery.error_code as delivery_error_code', + 'delivery.skip_reason as delivery_skip_reason', + 'delivery.dispatch_started_at', 'delivery.sent_at', + 'delivery.terminal_at', + ]; + } + + /** @param array $filters */ + private function applyFactFilters(object $query, array $filters): void + { + if ($filters['severity'] !== '') { + $query->where('event.highest_severity', $filters['severity']); + } + foreach ([ + 'event_id' => 'event.id', + 'instance_id' => 'event.instance_id', + 'user_id' => 'event.user_id', + 'host_id' => 'event.host_id', + ] as $filter => $column) { + if ($filters[$filter] !== null) { + $query->where($column, $filters[$filter]); + } + } + if ($filters['transition'] !== '' + || $filters['direction'] !== '' + || $filters['ip_family'] !== '') { + $query->whereExists(static function ($item) use ($filters): void { + $item->selectRaw('1') + ->from('cloud_abuse_alert_event_items as filter_item') + ->whereColumn('filter_item.event_id', 'event.id'); + foreach ([ + 'transition' => 'transition_type', + 'direction' => 'direction', + 'ip_family' => 'ip_family', + ] as $filter => $column) { + if ($filters[$filter] !== '') { + $item->where( + 'filter_item.' . $column, + $filters[$filter] + ); + } + } + }); + } + if ($filters['query'] !== '') { + $id = (int) $filters['query']; + $query->where(static function ($ids) use ($id): void { + $ids->where('event.id', $id) + ->orWhere('event.instance_id', $id) + ->orWhere('event.user_id', $id) + ->orWhere('event.host_id', $id); + }); + } + } + + private function applyStatusFilter(object $query, string $status): void + { + if ($status === '') { + return; + } + if ($status === 'queued') { + $query->whereNull('delivery.id'); + return; + } + $query->where('delivery.state', $status); + } + + /** @return array */ + private function summary(object $query): array + { + $counts = array_fill_keys(self::STATUSES, 0); + $connection = $query->getConnection(); + $status = "COALESCE(delivery.state, 'queued')"; + $records = $query->selectRaw( + $status . ' AS effective_status, COUNT(event.id) AS aggregate' + )->groupBy($connection->raw($status))->get(); + foreach ($records as $record) { + $key = (string) $record->effective_status; + if (array_key_exists($key, $counts)) { + $counts[$key] = max(0, (int) $record->aggregate); + } + } + return $counts; + } + + /** + * @param list $eventIds + * @return array>> + */ + private function eventItems(array $eventIds): array + { + if ($eventIds === []) { + return []; + } + $records = User::getConnectionResolver()->connection('default') + ->table('cloud_abuse_alert_event_items') + ->whereIn('event_id', $eventIds) + ->orderBy('event_id')->orderBy('id')->get([ + 'event_id', 'rule_code', 'direction', 'ip_family', + 'transition_type', 'from_severity', 'to_severity', + 'evidence_json', 'occurred_at', + ]); + $grouped = []; + foreach ($records as $record) { + $eventId = (int) $record->event_id; + $grouped[$eventId] ??= []; + $grouped[$eventId][] = self::itemRow($record); + } + return $grouped; + } + + /** @param list> $items @return array */ + private function eventRow(object $record, array $items): array + { + $delivery = self::deliveryRow($record); + return [ + 'event_id' => (string) $record->event_id, + 'instance_id' => (string) $record->instance_id, + 'user_id' => (string) $record->user_id, + 'host_id' => (string) $record->host_id, + 'instance_name' => self::nullableText($record->instance_name), + 'user_name' => self::nullableText($record->user_name), + 'host_name' => self::nullableText($record->host_name), + 'instance_deleted' => $record->instance_name === null, + 'bucket_start' => self::timestamp((int) $record->bucket_start), + 'created_at' => self::timestamp((int) $record->created_at), + 'transition_count' => max(1, + (int) $record->transition_count), + 'highest_severity' => self::severityRow( + (string) $record->highest_severity + ), + 'delivery' => $delivery, + 'items' => $items, + ]; + } + + /** @return array */ + private static function deliveryRow(object $record): array + { + $status = $record->delivery_id === null + ? 'queued' : (string) $record->delivery_state; + if (!in_array($status, self::STATUSES, true)) { + $status = 'unknown'; + } + $labels = [ + 'queued' => ['已入队', 'secondary'], + 'pending' => ['等待发送', 'info'], + 'dispatching' => ['发送中', 'warning'], + 'sent' => ['已发送', 'success'], + 'skipped' => ['已跳过', 'secondary'], + 'failed' => ['发送失败', 'danger'], + 'unknown' => ['效果未知', 'danger'], + ]; + return [ + 'status' => $status, + 'label' => $labels[$status][0], + 'tone' => $labels[$status][1], + 'detail' => self::deliveryDetail( + $status, + (string) ($record->delivery_error_code ?? ''), + (string) ($record->delivery_skip_reason ?? '') + ), + 'needs_attention' => in_array( + $status, ['failed', 'unknown'], true + ), + 'automatic_replay_allowed' => false, + 'dispatch_started_at' => self::timestampOrNull( + $record->dispatch_started_at + ), + 'sent_at' => self::timestampOrNull($record->sent_at), + 'terminal_at' => self::timestampOrNull($record->terminal_at), + ]; + } + + private static function deliveryDetail( + string $status, + string $errorCode, + string $skipReason + ): string { + if ($status === 'queued') { + return '事件已持久化,投递 Worker 尚未建立发送记录。'; + } + if ($status === 'pending') { + return '发送内容已冻结,正在等待 Telegram 投递。'; + } + if ($status === 'dispatching') { + return '远端请求正在执行,当前发送结果尚未确认。'; + } + if ($status === 'sent') { + return 'Telegram 已确认接收该告警。'; + } + if ($status === 'unknown') { + return '远端效果未知;系统禁止自动重放,请人工核对 Telegram。'; + } + if ($status === 'skipped') { + return match ($skipReason) { + 'channel_unavailable' => '没有可用的管理员 Telegram 绑定,已安全跳过。', + 'channel_disabled_or_unavailable' => '管理员 Telegram 告警通道已停用或不可用,已安全跳过。', + 'destination_ineligible' => '冻结的接收管理员已不具备接收资格,已安全跳过。', + 'destination_changed' => '管理员 Telegram 绑定已变化,旧接收目标未被使用。', + default => '该告警按本地安全条件跳过,未发起远端请求。', + }; + } + return match ($errorCode) { + 'message_format_invalid' => '告警内容无法安全格式化,未发起远端请求。', + 'delivery_identity_invalid' => '冻结的接收身份或内容校验失败,未发起远端请求。', + default => '投递在远端请求前失败,不会自动重放。', + }; + } + + /** @return array */ + private static function itemRow(object $record): array + { + $transition = (string) $record->transition_type; + $transitionLabels = [ + 'opened' => '新触发', + 'escalated' => '风险升级', + 'resolved' => '已恢复', + ]; + $direction = (string) $record->direction; + $directionLabels = [ + 'outbound' => '对外可疑行为', + 'inbound' => '正在遭受攻击', + ]; + return [ + 'rule_code' => (string) $record->rule_code, + 'rule_label' => self::RULE_LABELS[(string) $record->rule_code] + ?? '网络行为规则', + 'direction' => in_array( + $direction, self::DIRECTIONS, true + ) ? $direction : 'inbound', + 'direction_label' => $directionLabels[$direction] + ?? '网络行为', + 'ip_family' => in_array( + (string) $record->ip_family, self::IP_FAMILIES, true + ) ? (string) $record->ip_family : 'mixed', + 'transition' => in_array( + $transition, self::TRANSITIONS, true + ) ? $transition : 'opened', + 'transition_label' => $transitionLabels[$transition] + ?? '状态变化', + 'from_severity' => self::severityValue( + (string) $record->from_severity + ), + 'to_severity' => self::severityValue( + (string) $record->to_severity + ), + 'evidence' => self::evidenceRows( + (string) $record->evidence_json + ), + 'occurred_at' => self::timestamp((int) $record->occurred_at), + ]; + } + + /** @return list */ + private static function evidenceRows(string $json): array + { + if ($json === '' || strlen($json) > self::JSON_LIMIT) { + return []; + } + try { + $decoded = json_decode($json, true, 8, JSON_THROW_ON_ERROR); + } catch (\JsonException) { + return []; + } + if (!is_array($decoded) || array_is_list($decoded)) { + return []; + } + $rows = []; + foreach (self::EVIDENCE_LABELS as $key => $label) { + $value = $decoded[$key] ?? null; + if (!is_int($value) || $value < 0) { + continue; + } + $rows[] = ['key' => $key, 'label' => $label, 'value' => $value]; + } + return $rows; + } + + /** @return array{value:string,label:string,tone:string} */ + private static function severityRow(string $severity): array + { + $severity = in_array($severity, self::SEVERITIES, true) + ? $severity : 'suspicious'; + return [ + 'value' => $severity, + 'label' => $severity === 'high' ? '高风险' : '可疑', + 'tone' => $severity === 'high' ? 'danger' : 'warning', + ]; + } + + private static function severityValue(string $severity): string + { + return in_array($severity, ['none', 'suspicious', 'high'], true) + ? $severity : 'none'; + } + + private static function nullableText(mixed $value): ?string + { + if ($value === null) { + return null; + } + $text = trim((string) $value); + return $text === '' ? null : $text; + } + + private static function timestamp(int $value): string + { + return gmdate('Y-m-d\TH:i:s\Z', max(1, $value)); + } + + private static function timestampOrNull(mixed $value): ?string + { + if ((!is_int($value) && !ctype_digit((string) $value)) + || (int) $value < 1) { + return null; + } + return self::timestamp((int) $value); + } + + private static function boundedInteger( + mixed $value, + int $minimum, + int $maximum, + string $name + ): int { + if ((!is_int($value) && !is_string($value)) + || !ctype_digit((string) $value)) { + throw new CloudError($name . '无效', 400); + } + $parsed = filter_var((string) $value, FILTER_VALIDATE_INT, [ + 'options' => ['min_range' => $minimum, 'max_range' => $maximum], + ]); + if ($parsed === false) { + throw new CloudError($name . '无效', 400); + } + return (int) $parsed; + } +} diff --git a/web/config/routes_cloud.php b/web/config/routes_cloud.php index 7526543b..25c4fd47 100644 --- a/web/config/routes_cloud.php +++ b/web/config/routes_cloud.php @@ -175,6 +175,8 @@ $app->group('/api/v1', function () { $this->get('/admin/operations/health', 'App\Controllers\CloudAdminRuntimeController:index'); $this->get('/admin/abuse-monitoring', 'App\Controllers\CloudAdminAbuseMonitoringController:index'); + $this->get('/admin/abuse-monitoring/alerts', + 'App\Controllers\CloudAdminAbuseMonitoringController:alerts'); $this->get('/admin/abuse-monitoring/instances/{id:[1-9][0-9]*}', 'App\Controllers\CloudAdminAbuseMonitoringController:detail'); $this->get('/admin/abuse-policies', diff --git a/web/public/cloud/admin-abuse-alert-history.js b/web/public/cloud/admin-abuse-alert-history.js new file mode 100644 index 00000000..d6bbddf8 --- /dev/null +++ b/web/public/cloud/admin-abuse-alert-history.js @@ -0,0 +1,387 @@ +const historyRoot = document.querySelector('[data-admin-abuse-alert-history]'); +const historyRuntime = window.VenixAdminRequestRuntime?.create?.(); + +const STATUS = new Set([ + 'queued', 'pending', 'dispatching', 'sent', + 'skipped', 'failed', 'unknown', +]); +const TRANSITIONS = new Set(['opened', 'escalated', 'resolved']); +const SEVERITIES = new Set(['none', 'suspicious', 'high']); +const DIRECTIONS = new Set(['inbound', 'outbound']); +const FAMILIES = new Set(['ipv4', 'ipv6', 'mixed']); +const EVIDENCE_LABELS = Object.freeze({ + tcp_active_flows: 'TCP 活跃 Flow', + tcp_new_flows: 'TCP 新建 Flow', + 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 数', + unique_remote_ports: '唯一远端端口数', + unique_local_ports: '唯一本地端口数', + max_remote_ports_per_remote_ip: '单远端 IP 最大端口数', + max_remote_ips_per_remote_port: '单远端端口最大 IP 数', + max_local_ports_per_remote_ip: '单远端 IP 最大本地端口数', + max_remote_ips_per_local_port: '单本地端口最大远端 IP 数', +}); +const RULE_LABELS = Object.freeze({ + outbound_tcp_syn_sweep: '对外 TCP SYN 扫描', + outbound_tcp_port_scan: '对外 TCP 端口扫描', + outbound_udp_fanout: '对外 UDP 扇出', + inbound_tcp_syn_attack: '入站 TCP SYN 攻击', + inbound_tcp_port_scan: '入站 TCP 端口扫描', + inbound_udp_flood: '入站 UDP Flood', +}); +const STATUS_LABELS = Object.freeze({ + queued: '已入队', pending: '等待发送', dispatching: '发送中', + sent: '已发送', skipped: '已跳过', failed: '发送失败', + unknown: '效果未知', +}); + +const historyState = {page: 1, request: null, payload: null}; +const historyById = id => document.getElementById(id); + +function safeText(value, fallback = '未记录', maximum = 180) { + if (value === null || value === undefined) return fallback; + const text = String(value).trim(); + return text === '' ? fallback : text.slice(0, maximum); +} + +function safeId(value) { + const text = String(value ?? ''); + return /^[1-9][0-9]{0,19}$/.test(text) ? text : ''; +} + +function safeCount(value, minimum = 0) { + const parsed = Number(value); + return Number.isInteger(parsed) && parsed >= minimum ? parsed : minimum; +} + +function safeTime(value) { + const text = String(value ?? ''); + return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(text) ? text : null; +} + +function normalizeEvidence(value) { + if (!Array.isArray(value)) return []; + return value.flatMap(row => { + const key = String(row?.key ?? ''); + const count = Number(row?.value); + if (!Object.hasOwn(EVIDENCE_LABELS, key) + || !Number.isInteger(count) || count < 0) return []; + return [{key, label: EVIDENCE_LABELS[key], value: count}]; + }); +} + +function normalizeItem(value) { + const transition = TRANSITIONS.has(value?.transition) + ? value.transition : 'opened'; + const direction = DIRECTIONS.has(value?.direction) + ? value.direction : 'inbound'; + const family = FAMILIES.has(value?.ip_family) + ? value.ip_family : 'mixed'; + const ruleCode = String(value?.rule_code ?? ''); + return Object.freeze({ + rule_code: ruleCode, + rule_label: RULE_LABELS[ruleCode] || '网络行为规则', + direction, + direction_label: direction === 'outbound' + ? '对外可疑行为' : '正在遭受攻击', + ip_family: family, + transition, + transition_label: transition === 'opened' ? '新触发' + : transition === 'escalated' ? '风险升级' : '已恢复', + from_severity: SEVERITIES.has(value?.from_severity) + ? value.from_severity : 'none', + to_severity: SEVERITIES.has(value?.to_severity) + ? value.to_severity : 'none', + evidence: normalizeEvidence(value?.evidence), + occurred_at: safeTime(value?.occurred_at), + }); +} + +function normalizeDelivery(value) { + const status = STATUS.has(value?.status) ? value.status : 'unknown'; + return Object.freeze({ + status, + label: STATUS_LABELS[status], + detail: safeText(value?.detail, + status === 'unknown' + ? '远端效果未知;系统禁止自动重放,请人工核对 Telegram。' + : '投递状态说明不可用。', 240), + needs_attention: value?.needs_attention === true, + automatic_replay_allowed: false, + dispatch_started_at: safeTime(value?.dispatch_started_at), + sent_at: safeTime(value?.sent_at), + terminal_at: safeTime(value?.terminal_at), + }); +} + +function normalizeEvent(value) { + const eventId = safeId(value?.event_id); + if (!eventId) throw new Error('告警历史缺少事件编号。'); + const severityValue = value?.highest_severity?.value === 'high' + ? 'high' : 'suspicious'; + return Object.freeze({ + event_id: eventId, + instance_id: safeId(value?.instance_id), + user_id: safeId(value?.user_id), + host_id: safeId(value?.host_id), + instance_name: value?.instance_name == null + ? null : safeText(value.instance_name), + user_name: value?.user_name == null + ? null : safeText(value.user_name), + host_name: value?.host_name == null + ? null : safeText(value.host_name), + instance_deleted: value?.instance_deleted === true, + bucket_start: safeTime(value?.bucket_start), + created_at: safeTime(value?.created_at), + transition_count: safeCount(value?.transition_count, 1), + highest_severity: Object.freeze({ + value: severityValue, + label: severityValue === 'high' ? '高风险' : '可疑', + }), + delivery: normalizeDelivery(value?.delivery), + items: Array.isArray(value?.items) + ? value.items.map(normalizeItem) : [], + }); +} + +function normalizeAlertHistoryPayload(payload) { + const source = payload?.data && typeof payload.data === 'object' + ? payload.data : payload; + if (!source || typeof source !== 'object') { + throw new Error('告警历史响应格式无效。'); + } + const summary = {}; + for (const status of STATUS) { + summary[status] = safeCount(source.summary?.[status]); + } + summary.total = safeCount(source.summary?.total); + const page = safeCount(source.pagination?.page, 1); + const totalPages = safeCount(source.pagination?.total_pages, 1); + return Object.freeze({ + summary: Object.freeze(summary), + items: Array.isArray(source.items) + ? source.items.map(normalizeEvent) : [], + pagination: Object.freeze({ + page, total_pages: Math.max(page, totalPages), + total: safeCount(source.pagination?.total), + }), + }); +} + +function buildAlertHistoryUrl(base, filters = {}, page = 1) { + const parameters = new URLSearchParams(); + for (const key of [ + 'status', 'transition', 'severity', 'direction', 'ip_family', + 'event_id', 'instance_id', 'user_id', 'host_id', 'query', + ]) { + const value = String(filters[key] ?? '').trim(); + if (value !== '') parameters.set(key, value); + } + if (page > 1) parameters.set('page', String(page)); + const query = parameters.toString(); + return `${base}${query ? `?${query}` : ''}`; +} + +function localDate(value) { + if (!value) return '时间未记录'; + const parsed = new Date(value); + return Number.isFinite(parsed.getTime()) + ? parsed.toLocaleString('zh-CN', {hour12: false}) : '时间未记录'; +} + +function element(tag, className, text) { + const node = document.createElement(tag); + if (className) node.className = className; + if (text !== undefined) node.textContent = text; + return node; +} + +function renderSummary(summary) { + const target = historyById('abuse-alert-history-summary'); + if (!target) return; + target.replaceChildren(); + for (const status of STATUS) { + const card = element('div', `admin-abuse-alert-summary-item is-${status}`); + card.append( + element('span', '', STATUS_LABELS[status]), + element('strong', '', summary[status].toLocaleString('zh-CN')), + ); + target.append(card); + } +} + +function appendIdentity(container, label, value) { + const row = element('span', 'admin-abuse-alert-identity'); + row.append(element('small', '', label), element('strong', '', value)); + container.append(row); +} + +function renderRule(item) { + const card = element('li', `admin-abuse-alert-rule is-${item.direction}`); + const header = element('div', 'admin-abuse-alert-rule-head'); + header.append( + element('strong', '', item.rule_label), + element('span', `admin-abuse-alert-transition is-${item.transition}`, + item.transition_label), + ); + const meta = element('p', 'admin-abuse-alert-rule-meta', + `${item.direction_label} · ${item.ip_family.toUpperCase()} · ${localDate(item.occurred_at)}`); + card.append(header, meta); + if (item.evidence.length) { + const evidence = element('div', 'admin-abuse-alert-evidence'); + for (const row of item.evidence) { + evidence.append(element('span', '', + `${row.label} ${row.value.toLocaleString('zh-CN')}`)); + } + card.append(evidence); + } else { + card.append(element('p', 'admin-abuse-alert-evidence-empty', + '聚合证据不可用;未展示原始观测数据。')); + } + return card; +} + +function renderEvent(item) { + const card = element('article', 'admin-abuse-alert-event'); + const header = element('header', 'admin-abuse-alert-event-head'); + const title = element('div'); + title.append( + element('strong', '', `告警事件 #${item.event_id}`), + element('span', 'admin-abuse-alert-event-time', + localDate(item.created_at || item.bucket_start)), + ); + const badges = element('div', 'admin-abuse-alert-badges'); + badges.append( + element('span', `admin-abuse-alert-severity is-${item.highest_severity.value}`, + item.highest_severity.label), + element('span', `admin-abuse-alert-delivery is-${item.delivery.status}`, + item.delivery.label), + ); + header.append(title, badges); + + const identities = element('div', 'admin-abuse-alert-identities'); + appendIdentity(identities, '实例', item.instance_name + ? `${item.instance_name} (#${item.instance_id})` + : `实例 #${item.instance_id || '未知'}(已删除或不可用)`); + appendIdentity(identities, '用户', item.user_name + ? `${item.user_name} (#${item.user_id})` : `用户 #${item.user_id || '未知'}`); + appendIdentity(identities, '节点', item.host_name + ? `${item.host_name} (#${item.host_id})` : `节点 #${item.host_id || '未知'}`); + + const delivery = element('div', + `admin-abuse-alert-delivery-note is-${item.delivery.status}`); + delivery.append( + element('strong', '', item.delivery.label), + element('p', '', item.delivery.detail), + ); + if (item.delivery.status === 'unknown') { + delivery.append(element('small', '', + '该状态仅供人工核对;页面不提供重试或重新发送入口。')); + } + + const rules = element('ul', 'admin-abuse-alert-rules'); + for (const row of item.items) rules.append(renderRule(row)); + if (!item.items.length) { + rules.append(element('li', 'admin-abuse-alert-evidence-empty', + '事件没有可展示的规则变化。')); + } + card.append(header, identities, delivery, rules); + return card; +} + +function renderHistory(payload) { + const list = historyById('abuse-alert-history-list'); + if (!list) return; + list.replaceChildren(); + renderSummary(payload.summary); + historyById('abuse-alert-history-total').textContent + = `共 ${payload.pagination.total.toLocaleString('zh-CN')} 条`; + if (!payload.items.length) { + const empty = element('div', 'admin-abuse-alert-history-empty'); + empty.append( + element('i', 'mdi mdi-bell-off-outline'), + element('strong', '', '没有符合条件的告警历史'), + element('span', '', '请调整只读筛选条件,或等待新的规则状态变化。'), + ); + list.append(empty); + } else { + for (const item of payload.items) list.append(renderEvent(item)); + } + const pagination = historyById('abuse-alert-history-pagination'); + pagination.hidden = payload.pagination.total_pages <= 1; + historyById('abuse-alert-history-page').textContent + = `第 ${payload.pagination.page} / ${payload.pagination.total_pages} 页`; + historyById('abuse-alert-history-previous').disabled + = payload.pagination.page <= 1; + historyById('abuse-alert-history-next').disabled + = payload.pagination.page >= payload.pagination.total_pages; +} + +function formFilters() { + const form = historyById('abuse-alert-history-filter'); + const data = new FormData(form); + return Object.fromEntries(data.entries()); +} + +async function loadHistory(page = 1) { + if (!historyRoot) return false; + const status = historyById('abuse-alert-history-state'); + historyState.request?.abort('replaced'); + const controller = new AbortController(); + historyState.request = controller; + status.hidden = false; + status.className = 'alert alert-info admin-abuse-alert-history-state'; + status.textContent = '正在读取告警历史;实例监控与策略配置不受影响。'; + try { + if (!historyRuntime) throw new Error('只读请求组件不可用,请刷新页面。'); + const url = buildAlertHistoryUrl( + historyRoot.dataset.alertApi || '/api/v1/admin/abuse-monitoring/alerts', + formFilters(), page, + ); + const response = await historyRuntime.read(url, { + signal: controller.signal, timeoutMs: 10000, + }); + if (historyState.request !== controller) return false; + const payload = normalizeAlertHistoryPayload(response); + historyState.page = payload.pagination.page; + historyState.payload = payload; + renderHistory(payload); + status.hidden = true; + return true; + } catch (error) { + if (controller.signal.aborted) return false; + status.className = 'alert alert-danger admin-abuse-alert-history-state'; + status.textContent = error?.message + || '告警历史暂不可读取;实例监控与策略配置仍可独立使用。'; + return false; + } finally { + if (historyState.request === controller) historyState.request = null; + } +} + +if (historyRoot) { + historyById('abuse-alert-history-filter')?.addEventListener('submit', event => { + event.preventDefault(); loadHistory(1); + }); + historyById('abuse-alert-history-clear')?.addEventListener('click', () => { + historyById('abuse-alert-history-filter')?.reset(); loadHistory(1); + }); + historyById('abuse-alert-history-previous')?.addEventListener('click', () => { + if (historyState.page > 1) loadHistory(historyState.page - 1); + }); + historyById('abuse-alert-history-next')?.addEventListener('click', () => { + const last = historyState.payload?.pagination?.total_pages || 1; + if (historyState.page < last) loadHistory(historyState.page + 1); + }); + loadHistory(1); +} + +export { + buildAlertHistoryUrl, + normalizeAlertHistoryPayload, + normalizeDelivery, + normalizeEvidence, +}; diff --git a/web/public/cloud/admin-abuse-monitoring.css b/web/public/cloud/admin-abuse-monitoring.css index 024dd582..559e9ad8 100644 --- a/web/public/cloud/admin-abuse-monitoring.css +++ b/web/public/cloud/admin-abuse-monitoring.css @@ -230,6 +230,291 @@ flex-wrap: wrap; } +[data-admin-abuse-alert-history] .admin-abuse-alert-history-state { + margin-bottom: 16px; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-history-filters { + align-items: end; + display: grid; + gap: 12px; + grid-template-columns: repeat(5, minmax(0, 1fr)); +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-history-filters label { + min-width: 0; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-history-actions { + display: flex; + gap: 8px; + justify-content: flex-end; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-history-summary { + display: grid; + gap: 8px; + grid-template-columns: repeat(7, minmax(0, 1fr)); + margin: 18px 0; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-summary-item { + background: #f8fafc; + border: 1px solid #e5ebf2; + border-radius: 10px; + min-width: 0; + padding: 10px 12px; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-summary-item span, +[data-admin-abuse-alert-history] .admin-abuse-alert-summary-item strong { + display: block; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-summary-item span { + color: #667085; + font-size: 11px; + white-space: nowrap; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-summary-item strong { + color: #344054; + font-size: 18px; + margin-top: 3px; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-summary-item.is-sent { + background: #f1fbf8; + border-color: #b9e4dc; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-summary-item.is-failed, +[data-admin-abuse-alert-history] .admin-abuse-alert-summary-item.is-unknown { + background: #fff5f6; + border-color: #fecdd6; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-history-list { + display: grid; + gap: 12px; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-event { + border: 1px solid #e4e9f0; + border-radius: 14px; + overflow: hidden; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-event-head { + align-items: flex-start; + background: #f8fafc; + border-bottom: 1px solid #e8edf3; + display: flex; + gap: 14px; + justify-content: space-between; + padding: 14px 16px; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-event-head strong, +[data-admin-abuse-alert-history] .admin-abuse-alert-event-time { + display: block; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-event-time { + color: #667085; + font-size: 12px; + margin-top: 4px; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-badges { + display: flex; + flex-wrap: wrap; + gap: 7px; + justify-content: flex-end; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-severity, +[data-admin-abuse-alert-history] .admin-abuse-alert-delivery, +[data-admin-abuse-alert-history] .admin-abuse-alert-transition { + border-radius: 999px; + display: inline-flex; + font-size: 11px; + font-weight: 800; + padding: 4px 9px; + white-space: nowrap; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-severity.is-suspicious, +[data-admin-abuse-alert-history] .admin-abuse-alert-delivery.is-dispatching, +[data-admin-abuse-alert-history] .admin-abuse-alert-transition.is-escalated { + background: #fff4da; + color: #9b6800; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-severity.is-high, +[data-admin-abuse-alert-history] .admin-abuse-alert-delivery.is-failed, +[data-admin-abuse-alert-history] .admin-abuse-alert-delivery.is-unknown { + background: #feecef; + color: #b4233d; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-delivery.is-sent, +[data-admin-abuse-alert-history] .admin-abuse-alert-transition.is-resolved { + background: #e8f8f1; + color: #12805c; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-delivery.is-pending, +[data-admin-abuse-alert-history] .admin-abuse-alert-transition.is-opened { + background: #eaf2ff; + color: #2f6bb2; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-delivery.is-queued, +[data-admin-abuse-alert-history] .admin-abuse-alert-delivery.is-skipped { + background: #eef1f5; + color: #475467; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-identities { + display: grid; + gap: 10px; + grid-template-columns: repeat(3, minmax(0, 1fr)); + padding: 14px 16px 0; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-identity { + background: #f8fafc; + border-radius: 9px; + min-width: 0; + padding: 10px 12px; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-identity small, +[data-admin-abuse-alert-history] .admin-abuse-alert-identity strong { + display: block; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-identity small { + color: #667085; + font-size: 11px; + margin-bottom: 3px; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-identity strong { + color: #344054; + font-size: 13px; + overflow-wrap: anywhere; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-delivery-note { + border-left: 3px solid #98a2b3; + margin: 14px 16px; + padding: 2px 0 2px 12px; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-delivery-note.is-sent { + border-left-color: #12b76a; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-delivery-note.is-dispatching { + border-left-color: #f79009; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-delivery-note.is-failed, +[data-admin-abuse-alert-history] .admin-abuse-alert-delivery-note.is-unknown { + border-left-color: #d92d20; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-delivery-note p, +[data-admin-abuse-alert-history] .admin-abuse-alert-delivery-note small { + color: #667085; + display: block; + font-size: 12px; + margin: 4px 0 0; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-delivery-note.is-unknown small { + color: #b4233d; + font-weight: 700; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-rules { + border-top: 1px solid #eef2f6; + display: grid; + gap: 0; + list-style: none; + margin: 0; + padding: 0 16px 6px; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-rule { + border-bottom: 1px solid #eef2f6; + padding: 13px 0; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-rule:last-child { + border-bottom: 0; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-rule-head { + align-items: center; + display: flex; + gap: 10px; + justify-content: space-between; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-rule-meta, +[data-admin-abuse-alert-history] .admin-abuse-alert-evidence-empty { + color: #667085; + font-size: 12px; + margin: 5px 0 0; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-evidence { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 8px; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-evidence span { + background: #f2f4f7; + border-radius: 999px; + color: #475467; + font-size: 11px; + padding: 4px 8px; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-history-empty { + align-items: center; + color: #667085; + display: flex; + flex-direction: column; + gap: 5px; + min-height: 180px; + justify-content: center; + text-align: center; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-history-empty i { + color: #98a2b3; + font-size: 32px; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-history-empty strong { + color: #344054; +} + +[data-admin-abuse-alert-history] .admin-abuse-alert-history-pagination { + align-items: center; + color: #667085; + display: flex; + font-size: 13px; + justify-content: space-between; + margin-top: 16px; +} + #abuse-monitoring-detail .admin-abuse-direction-banner { border-radius: 10px; font-size: 13px; @@ -317,6 +602,40 @@ #abuse-monitoring-detail .admin-abuse-empty-detail { color: #667085; font-size: 13px; padding: 18px; text-align: center; } @media (max-width: 767.98px) { + [data-admin-abuse-alert-history] .admin-abuse-alert-history-filters, + [data-admin-abuse-alert-history] .admin-abuse-alert-identities { + grid-template-columns: 1fr; + } + [data-admin-abuse-alert-history] .admin-abuse-alert-history-actions { + display: grid; + grid-template-columns: 1fr 1fr; + } + [data-admin-abuse-alert-history] .admin-abuse-alert-history-actions .btn { + width: 100%; + } + [data-admin-abuse-alert-history] .admin-abuse-alert-history-summary { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + [data-admin-abuse-alert-history] .admin-abuse-alert-event-head, + [data-admin-abuse-alert-history] .admin-abuse-alert-rule-head { + align-items: flex-start; + flex-direction: column; + } + [data-admin-abuse-alert-history] .admin-abuse-alert-badges { + justify-content: flex-start; + } + [data-admin-abuse-alert-history] .admin-abuse-alert-identities { + gap: 7px; + } + [data-admin-abuse-alert-history] .admin-abuse-alert-history-pagination { + align-items: stretch; + flex-direction: column; + gap: 10px; + } + [data-admin-abuse-alert-history] .admin-abuse-alert-history-pagination > div, + [data-admin-abuse-alert-history] .admin-abuse-alert-history-pagination .btn { + flex: 1; + } .admin-abuse-policy-meta, .admin-abuse-policy-windows, .admin-abuse-policy-rules { grid-template-columns: 1fr; } diff --git a/web/resources/views/venix/admin/cloud/abuse_monitoring.tpl b/web/resources/views/venix/admin/cloud/abuse_monitoring.tpl index 1f6e7315..e1727c82 100644 --- a/web/resources/views/venix/admin/cloud/abuse_monitoring.tpl +++ b/web/resources/views/venix/admin/cloud/abuse_monitoring.tpl @@ -78,6 +78,34 @@ +
+
+

滥用告警历史

只读展示规则状态变化和 Telegram 投递结果;效果未知的发送不会自动重放。

+ 正在读取 +
+
+
正在读取告警历史;实例监控与策略配置不受影响。
+
+ + + + + + + + + +
+
+
+
+ +
+
+

筛选实例

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

@@ -135,4 +163,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 5a25b60f..c05eb9e6 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='2026110901' scope='global'} +{assign var=venix_asset_version value='2026110902' scope='global'} diff --git a/web/tests/AdminAbuseAlertHistoryBehaviorTest.mjs b/web/tests/AdminAbuseAlertHistoryBehaviorTest.mjs new file mode 100644 index 00000000..2a7d8069 --- /dev/null +++ b/web/tests/AdminAbuseAlertHistoryBehaviorTest.mjs @@ -0,0 +1,90 @@ +import fs from 'node:fs'; + +globalThis.document = { + querySelector: () => null, + getElementById: () => null, +}; +globalThis.window = {}; + +const source = fs.readFileSync(new URL( + '../public/cloud/admin-abuse-alert-history.js', + import.meta.url, +), 'utf8'); +const module = await import( + `data:text/javascript;base64,${Buffer.from(source).toString('base64')}` +); + +const assert = (condition, message) => { + if (!condition) throw new Error(message); +}; + +const payload = module.normalizeAlertHistoryPayload({ + summary: {unknown: 1, total: 1}, + pagination: {page: 1, total_pages: 1, total: 1}, + items: [{ + event_id: '7', instance_id: '41', user_id: '10', host_id: '3', + instance_name: 'vm-a', user_name: 'owner', host_name: 'host-a', + created_at: '2026-11-09T01:02:03Z', transition_count: 1, + highest_severity: {value: 'high'}, + event_key: 'secret-event-key', policy_hash: 'secret-policy-hash', + sample_key: 'secret-sample-key', + delivery: { + status: 'unknown', + detail: '远端效果未知;系统禁止自动重放,请人工核对 Telegram。', + automatic_replay_allowed: true, + chat_id: '99887766', binding_generation: 'secret-binding', + token: 'secret-token', message_text: 'secret-message', + content_hash: 'secret-content-hash', + }, + items: [{ + rule_code: 'outbound_tcp_syn_sweep', direction: 'outbound', + ip_family: 'ipv4', transition: 'opened', + from_severity: 'none', to_severity: 'high', + occurred_at: '2026-11-09T01:02:00Z', + finding_key: 'secret-finding-key', item_key: 'secret-item-key', + evidence_json: '{"remote_ip":"203.0.113.7"}', + evidence: [ + {key: 'tcp_syn_flows', label: 'untrusted', value: 900}, + {key: 'remote_ip', label: 'raw address', value: 1}, + {key: 'nested', value: {token: 'secret'}}, + ], + }], + }], +}); + +const encoded = JSON.stringify(payload); +assert(payload.items[0].delivery.status === 'unknown' + && payload.items[0].delivery.automatic_replay_allowed === false + && payload.items[0].items[0].evidence.length === 1 + && payload.items[0].items[0].evidence[0].label === 'TCP SYN Flow', +'Unknown/no-replay state or aggregate evidence normalization drifted.'); +for (const secret of [ + '99887766', 'secret-binding', 'secret-token', 'secret-message', + 'secret-content-hash', 'secret-event-key', 'secret-policy-hash', + 'secret-sample-key', 'secret-finding-key', 'secret-item-key', + '203.0.113.7', 'evidence_json', +]) { + assert(!encoded.includes(secret), `Normalized history leaked ${secret}.`); +} + +const url = module.buildAlertHistoryUrl('/alerts', { + status: 'unknown', transition: 'opened', direction: 'outbound', + ip_family: 'ipv4', event_id: '7', instance_id: '41', + user_id: '10', host_id: '3', query: '', +}, 2); +assert(url.includes('status=unknown') + && url.includes('event_id=7') + && url.includes('instance_id=41') + && url.includes('user_id=10') + && url.includes('host_id=3') + && url.includes('page=2'), +'Alert history URL lost independent identity filters or pagination.'); + +const invalid = module.normalizeDelivery({ + status: 'future_state', automatic_replay_allowed: true, +}); +assert(invalid.status === 'unknown' + && invalid.automatic_replay_allowed === false, +'Unknown server enums gained a replay-capable dynamic UI state.'); + +console.log('Administrator abuse-alert history JavaScript behavior passed.'); diff --git a/web/tests/CloudAdminAbuseAlertHistoryApiTest.php b/web/tests/CloudAdminAbuseAlertHistoryApiTest.php new file mode 100644 index 00000000..4e3ed9e8 --- /dev/null +++ b/web/tests/CloudAdminAbuseAlertHistoryApiTest.php @@ -0,0 +1,88 @@ + 'GET', + 'REQUEST_URI' => $uri, + 'QUERY_STRING' => parse_url($uri, PHP_URL_QUERY) ?: '', + ]))->withAttribute('cloud_actor', $actor); +}; + +$controller = new CloudAdminAbuseMonitoringController(); +$response = $controller->alerts($request([ + 'user_id' => 88, 'is_admin' => true, + 'is_super_admin' => false, 'can_manage' => false, +], [ + 'event_id' => '1', 'instance_id' => '41', + 'user_id' => '10', 'host_id' => '3', +]), new Response()); +$body = (string) $response->getBody(); +$decoded = json_decode($body, true, flags: JSON_THROW_ON_ERROR); +$assert($response->getStatusCode() === 200 + && $response->getHeaderLine('Cache-Control') === 'private, no-store' + && ($decoded['pagination']['total'] ?? 0) === 1 + && ($decoded['items'][0]['event_id'] ?? '') === '1' + && !str_contains($body, 'message_text') + && !str_contains($body, 'chat_id') + && !str_contains($body, 'binding_generation') + && !str_contains($body, 'telegram_message_id') + && !str_contains($body, 'content_hash') + && !str_contains($body, 'evidence_json') + && !str_contains($body, 'policy_hash') + && !str_contains($body, 'sample_key') + && !str_contains($body, 'finding_key') + && !str_contains($body, 'item_key'), + 'Read-only alert history API lost its cache, filter, or secrecy boundary.'); + +try { + $controller->alerts($request([ + 'user_id' => 89, 'is_admin' => false, + ]), new Response()); + throw new RuntimeException('Non-administrator alert history API succeeded.'); +} catch (CloudError $error) { + $assert($error->httpStatus === 403, + 'Non-administrator alert history API returned the wrong status.'); +} + +$routes = file_get_contents(dirname(__DIR__) . '/config/routes_cloud.php'); +$controllerSource = file_get_contents(dirname(__DIR__) + . '/app/Controllers/CloudAdminAbuseMonitoringController.php'); +$assert(is_string($routes) + && str_contains($routes, + "\$this->get('/admin/abuse-monitoring/alerts'") + && !str_contains($routes, + "\$this->post('/admin/abuse-monitoring/alerts'") + && !str_contains($routes, + "\$this->put('/admin/abuse-monitoring/alerts'") + && !str_contains($routes, + "\$this->patch('/admin/abuse-monitoring/alerts'") + && !str_contains($routes, + "\$this->delete('/admin/abuse-monitoring/alerts'") + && is_string($controllerSource) + && str_contains($controllerSource, + 'new CloudAdminAbuseAlertHistoryService()'), + 'Alert history must expose exactly one administrator-only GET surface.'); + +echo "Administrator abuse-alert history API tests passed.\n"; diff --git a/web/tests/CloudAdminAbuseAlertHistoryServiceTest.php b/web/tests/CloudAdminAbuseAlertHistoryServiceTest.php new file mode 100644 index 00000000..d7aef797 --- /dev/null +++ b/web/tests/CloudAdminAbuseAlertHistoryServiceTest.php @@ -0,0 +1,247 @@ +addConnection([ + 'driver' => 'sqlite', 'database' => ':memory:', +], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->schema('default'); +$schema->create('user', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('user_name'); +}); +$schema->create('cloud_hosts', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('name'); +}); +$schema->create('cloud_instances', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('name'); +}); +$schema->create('cloud_abuse_alert_events', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('instance_id'); + $table->integer('user_id'); + $table->integer('host_id'); + $table->integer('bucket_start'); + $table->integer('transition_count'); + $table->string('highest_severity'); + $table->integer('created_at'); + }); +$schema->create('cloud_abuse_alert_event_items', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('event_id'); + $table->string('rule_code'); + $table->string('direction'); + $table->string('ip_family'); + $table->string('transition_type'); + $table->string('from_severity'); + $table->string('to_severity'); + $table->text('evidence_json'); + $table->integer('occurred_at'); + }); +$schema->create('cloud_abuse_alert_deliveries', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('event_id')->unique(); + $table->string('binding_generation')->nullable(); + $table->integer('bound_admin_id')->nullable(); + $table->string('chat_id')->nullable(); + $table->integer('telegram_message_id')->nullable(); + $table->string('state'); + $table->text('message_text'); + $table->string('content_hash'); + $table->string('error_code')->default(''); + $table->string('skip_reason')->default(''); + $table->integer('dispatch_started_at')->nullable(); + $table->integer('sent_at')->nullable(); + $table->integer('terminal_at')->nullable(); + }); + +$db = $capsule->connection('default'); +$db->table('user')->insert([ + ['id' => 10, 'user_name' => 'owner-a'], + ['id' => 11, 'user_name' => 'owner-b'], +]); +$db->table('cloud_hosts')->insert([ + ['id' => 3, 'name' => 'host-a'], + ['id' => 4, 'name' => 'host-b'], +]); +$db->table('cloud_instances')->insert([ + ['id' => 41, 'name' => 'vm-a'], + ['id' => 42, 'name' => 'vm-b'], +]); +$db->table('cloud_abuse_alert_events')->insert([ + [ + 'id' => 1, 'instance_id' => 41, 'user_id' => 10, 'host_id' => 3, + 'bucket_start' => 120, 'transition_count' => 2, + 'highest_severity' => 'high', 'created_at' => 130, + ], + [ + 'id' => 2, 'instance_id' => 42, 'user_id' => 11, 'host_id' => 4, + 'bucket_start' => 180, 'transition_count' => 1, + 'highest_severity' => 'suspicious', 'created_at' => 190, + ], + [ + 'id' => 3, 'instance_id' => 99, 'user_id' => 10, 'host_id' => 3, + 'bucket_start' => 240, 'transition_count' => 1, + 'highest_severity' => 'high', 'created_at' => 250, + ], +]); +$db->table('cloud_abuse_alert_event_items')->insert([ + [ + 'event_id' => 1, 'rule_code' => 'outbound_tcp_syn_sweep', + 'direction' => 'outbound', 'ip_family' => 'ipv4', + 'transition_type' => 'opened', 'from_severity' => 'none', + 'to_severity' => 'high', + 'evidence_json' => json_encode([ + 'tcp_syn_flows' => 900, + 'unique_remote_ips' => 140, + 'remote_ip' => '203.0.113.5', + 'nested' => ['token' => 'must-not-leak'], + ], JSON_THROW_ON_ERROR), + 'occurred_at' => 120, + ], + [ + 'event_id' => 1, 'rule_code' => 'inbound_udp_flood', + 'direction' => 'inbound', 'ip_family' => 'ipv6', + 'transition_type' => 'resolved', 'from_severity' => 'high', + 'to_severity' => 'none', + 'evidence_json' => '{"udp_active_flows":0}', + 'occurred_at' => 120, + ], + [ + 'event_id' => 2, 'rule_code' => 'outbound_udp_fanout', + 'direction' => 'outbound', 'ip_family' => 'ipv4', + 'transition_type' => 'opened', 'from_severity' => 'none', + 'to_severity' => 'suspicious', + 'evidence_json' => '{"udp_new_flows":45}', + 'occurred_at' => 180, + ], + [ + 'event_id' => 3, 'rule_code' => 'inbound_tcp_syn_attack', + 'direction' => 'inbound', 'ip_family' => 'mixed', + 'transition_type' => 'escalated', + 'from_severity' => 'suspicious', 'to_severity' => 'high', + 'evidence_json' => '{"tcp_unreplied_flows":77}', + 'occurred_at' => 240, + ], +]); +$secretMessage = 'secret telegram message body'; +$db->table('cloud_abuse_alert_deliveries')->insert([ + [ + 'id' => 1, 'event_id' => 2, + 'binding_generation' => str_repeat('b', 32), + 'bound_admin_id' => 77, 'chat_id' => '9988776655', + 'telegram_message_id' => 123, 'state' => 'sent', + 'message_text' => $secretMessage, + 'content_hash' => str_repeat('c', 64), + 'error_code' => '', 'skip_reason' => '', + 'dispatch_started_at' => 191, 'sent_at' => 192, + 'terminal_at' => 192, + ], + [ + 'id' => 2, 'event_id' => 3, + 'binding_generation' => str_repeat('d', 32), + 'bound_admin_id' => 77, 'chat_id' => '1122334455', + 'telegram_message_id' => null, 'state' => 'unknown', + 'message_text' => 'another private message', + 'content_hash' => str_repeat('e', 64), + 'error_code' => 'remote_effect_unknown', 'skip_reason' => '', + 'dispatch_started_at' => 251, 'sent_at' => null, + 'terminal_at' => 252, + ], +]); + +$service = new CloudAdminAbuseAlertHistoryService(); +$admin = ['user_id' => 8, 'is_admin' => true, 'can_manage' => false]; +$page = $service->page($admin, ['per_page' => '2']); +$encoded = json_encode($page, JSON_THROW_ON_ERROR); +$assert($page['summary']['queued'] === 1 + && $page['summary']['sent'] === 1 + && $page['summary']['unknown'] === 1 + && $page['summary']['total'] === 3 + && $page['pagination']['total'] === 3 + && count($page['items']) === 2, + 'Alert history summary or pagination lost an effective delivery state.'); +$assert(!str_contains($encoded, '9988776655') + && !str_contains($encoded, $secretMessage) + && !str_contains($encoded, str_repeat('c', 64)) + && !str_contains($encoded, '203.0.113.5') + && !str_contains($encoded, 'must-not-leak') + && !str_contains($encoded, 'binding_generation') + && !str_contains($encoded, 'content_hash') + && !str_contains($encoded, 'evidence_json'), + 'History DTO leaked delivery identity, frozen content, hash, or raw evidence.'); +$assert(($page['items'][0]['instance_deleted'] ?? false) === true + && ($page['items'][0]['delivery']['status'] ?? '') === 'unknown' + && ($page['items'][0]['delivery']['automatic_replay_allowed'] ?? true) + === false + && str_contains( + (string) $page['items'][0]['delivery']['detail'], + '禁止自动重放' + ), 'Unknown delivery did not retain its no-replay operator boundary.'); + +$queued = $service->page($admin, [ + 'status' => 'queued', 'instance_id' => '41', 'user_id' => '10', + 'host_id' => '3', 'event_id' => '1', +]); +$assert($queued['pagination']['total'] === 1 + && ($queued['items'][0]['event_id'] ?? '') === '1', + 'Independent event, instance, user, host, or queued filters drifted.'); +$wrongOwner = $service->page($admin, [ + 'instance_id' => '41', 'user_id' => '11', +]); +$assert($wrongOwner['pagination']['total'] === 0, + 'Independent identity filters were collapsed into an OR search.'); +$sameItem = $service->page($admin, [ + 'transition' => 'opened', 'direction' => 'inbound', + 'ip_family' => 'ipv4', +]); +$assert($sameItem['pagination']['total'] === 0, + 'Combined item filters were incorrectly satisfied by different items.'); +$matchedItem = $service->page($admin, [ + 'transition' => 'opened', 'direction' => 'outbound', + 'ip_family' => 'ipv4', +]); +$assert($matchedItem['pagination']['total'] === 2, + 'A valid same-item transition/direction/family filter did not match.'); + +foreach ([ + ['status' => 'future'], ['instance_id' => 'no'], + ['query' => '99999999999999999999'], ['extra' => '1'], +] as $invalid) { + try { + $service->page($admin, $invalid); + throw new RuntimeException('Invalid alert history filter succeeded.'); + } catch (CloudError $error) { + $assert($error->httpStatus === 400, + 'Invalid alert history filter returned the wrong status.'); + } +} +try { + $service->page(['user_id' => 9, 'is_admin' => false]); + throw new RuntimeException('Non-administrator alert history access succeeded.'); +} catch (CloudError $error) { + $assert($error->httpStatus === 403, + 'Alert history authorization returned the wrong status.'); +} + +echo "Administrator abuse-alert history service tests passed.\n"; diff --git a/web/tests/CloudAdminAbuseAlertHistoryUiContractTest.php b/web/tests/CloudAdminAbuseAlertHistoryUiContractTest.php new file mode 100644 index 00000000..0a727f6c --- /dev/null +++ b/web/tests/CloudAdminAbuseAlertHistoryUiContractTest.php @@ -0,0 +1,88 @@ +]*>[^<]*(?:重试|重新发送)/u', + $template) !== 1, + 'Unknown delivery must be explicit and must expose no replay action.'); + +$assert(str_contains($styles, + '[data-admin-abuse-alert-history] .admin-abuse-alert-event') + && str_contains($styles, + '[data-admin-abuse-alert-history] .admin-abuse-alert-identities') + && str_contains($styles, '@media (max-width: 767.98px)') + && str_contains($styles, + 'grid-template-columns: repeat(2, minmax(0, 1fr))'), + 'Alert history lacks its desktop or mobile card presentation.'); + +$assert(str_contains($service, + "COALESCE(delivery.state, 'queued')") + && str_contains($service, "'channel_disabled_or_unavailable'") + && str_contains($service, "'automatic_replay_allowed' => false") + && !str_contains($service, "'chat_id'") + && !str_contains($service, "'message_text'") + && !str_contains($service, "'content_hash'") + && !str_contains($service, "'policy_hash'") + && !str_contains($service, "'evidence_json' =>"), + 'Server projection must derive queued and omit sensitive ledger fields.'); + +echo "Administrator abuse-alert history UI contracts passed.\n"; diff --git a/web/tests/CloudAdminAbusePolicyUiContractTest.php b/web/tests/CloudAdminAbusePolicyUiContractTest.php index 8475c10c..865cdd9a 100644 --- a/web/tests/CloudAdminAbusePolicyUiContractTest.php +++ b/web/tests/CloudAdminAbusePolicyUiContractTest.php @@ -61,7 +61,7 @@ $assert(str_contains($styles, '.admin-abuse-policy-rules') && str_contains($styles, '.admin-abuse-policy-actions { display: grid; grid-template-columns: 1fr; }'), 'Policy rules and actions lack responsive presentation contracts.'); -$assert(str_contains($assets, "venix_asset_version value='2026110901'"), +$assert(str_contains($assets, "venix_asset_version value='2026110902'"), 'Static asset version was not advanced for the policy module.'); echo "Administrator abuse-policy UI contracts passed.\n"; diff --git a/web/tests/CloudAssetVersionContractTest.php b/web/tests/CloudAssetVersionContractTest.php index b79a24f3..d18466e6 100644 --- a/web/tests/CloudAssetVersionContractTest.php +++ b/web/tests/CloudAssetVersionContractTest.php @@ -15,7 +15,7 @@ $assert = static function (bool $condition, string $message): void { }; $assert(is_string($assets) - && str_contains($assets, "venix_asset_version value='2026110901'") + && str_contains($assets, "venix_asset_version value='2026110902'") && is_string($cloudShell) && str_contains($cloudShell, '/cloud/app.js?v={$venix_asset_version}'), 'The cloud application entry must use the shared Venix asset version.');