feat(admin): expose abuse alert delivery history
parent
b54bde8bce
commit
bddd36b533
@ -0,0 +1,513 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\User;
|
||||
|
||||
/**
|
||||
* Read-only administrator projection of immutable abuse-alert history.
|
||||
*
|
||||
* This boundary intentionally owns no delivery or replay operation. It reads
|
||||
* only frozen alert facts plus the minimal delivery state needed for operator
|
||||
* visibility, and projects a bounded aggregate-evidence allowlist.
|
||||
*/
|
||||
final class CloudAdminAbuseAlertHistoryService
|
||||
{
|
||||
private const STATUSES = [
|
||||
'queued', 'pending', 'dispatching', 'sent',
|
||||
'skipped', 'failed', 'unknown',
|
||||
];
|
||||
private const TRANSITIONS = ['opened', 'escalated', 'resolved'];
|
||||
private const SEVERITIES = ['suspicious', 'high'];
|
||||
private const DIRECTIONS = ['inbound', 'outbound'];
|
||||
private const IP_FAMILIES = ['ipv4', 'ipv6', 'mixed'];
|
||||
private const JSON_LIMIT = 32768;
|
||||
private const RULE_LABELS = [
|
||||
'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',
|
||||
];
|
||||
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<string,mixed> $actor @param array<string,mixed> $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<string,mixed> $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<string,mixed> $input @return array<string,mixed> */
|
||||
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<string> */
|
||||
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<string,mixed> $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<string,int> */
|
||||
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<int> $eventIds
|
||||
* @return array<int,list<array<string,mixed>>>
|
||||
*/
|
||||
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<array<string,mixed>> $items @return array<string,mixed> */
|
||||
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<string,mixed> */
|
||||
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<string,mixed> */
|
||||
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<array{key:string,label:string,value:int}> */
|
||||
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;
|
||||
}
|
||||
}
|
||||
@ -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,
|
||||
};
|
||||
@ -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'}
|
||||
|
||||
@ -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.');
|
||||
@ -0,0 +1,88 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Controllers\CloudAdminAbuseMonitoringController;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use Slim\Http\Environment;
|
||||
use Slim\Http\Request;
|
||||
use Slim\Http\Response;
|
||||
|
||||
ob_start();
|
||||
require __DIR__ . '/CloudAdminAbuseAlertHistoryServiceTest.php';
|
||||
ob_end_clean();
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$request = static function (array $actor, array $query = []): Request {
|
||||
$uri = '/api/v1/admin/abuse-monitoring/alerts';
|
||||
if ($query !== []) {
|
||||
$uri .= '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986);
|
||||
}
|
||||
return Request::createFromEnvironment(Environment::mock([
|
||||
'REQUEST_METHOD' => '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";
|
||||
@ -0,0 +1,247 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Cloud\CloudAdminAbuseAlertHistoryService;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$capsule = new Capsule();
|
||||
$capsule->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";
|
||||
@ -0,0 +1,88 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$read = static function (string $path): string {
|
||||
$source = file_get_contents($path);
|
||||
if (!is_string($source)) {
|
||||
throw new RuntimeException('Unable to read ' . $path);
|
||||
}
|
||||
return $source;
|
||||
};
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$template = $read($root
|
||||
. '/resources/views/venix/admin/cloud/abuse_monitoring.tpl');
|
||||
$script = $read($root . '/public/cloud/admin-abuse-alert-history.js');
|
||||
$styles = $read($root . '/public/cloud/admin-abuse-monitoring.css');
|
||||
$service = $read($root
|
||||
. '/app/Services/Cloud/CloudAdminAbuseAlertHistoryService.php');
|
||||
|
||||
$assert(str_contains($template, 'data-admin-abuse-alert-history')
|
||||
&& str_contains($template,
|
||||
'data-alert-api="/api/v1/admin/abuse-monitoring/alerts"')
|
||||
&& str_contains($template, 'admin-abuse-alert-history.js')
|
||||
&& str_contains($template, '实例监控与策略配置不受影响'),
|
||||
'Alert history must be an independently loaded monitoring card.');
|
||||
|
||||
foreach ([
|
||||
'name="status"', 'name="transition"', 'name="severity"',
|
||||
'name="direction"', 'name="ip_family"', 'name="event_id"',
|
||||
'name="instance_id"', 'name="user_id"', 'name="host_id"',
|
||||
] as $filter) {
|
||||
$assert(str_contains($template, $filter),
|
||||
'Alert history is missing filter ' . $filter . '.');
|
||||
}
|
||||
|
||||
$assert(str_contains($script,
|
||||
'window.VenixAdminRequestRuntime?.create?.()')
|
||||
&& str_contains($script, 'historyRuntime.read(url')
|
||||
&& str_contains($script, 'timeoutMs: 10000')
|
||||
&& !preg_match('/historyRuntime\.(?:mutate|commit|enqueue)\s*\(/',
|
||||
$script)
|
||||
&& !str_contains($script, '.innerHTML'),
|
||||
'Alert history must remain a safe, read-only asynchronous module.');
|
||||
|
||||
foreach ([
|
||||
'chat_id', 'binding_generation', 'telegram_message_id',
|
||||
'message_text', 'content_hash', 'policy_hash', 'sample_key',
|
||||
'finding_key', 'item_key', 'evidence_json',
|
||||
] as $privateField) {
|
||||
$assert(!str_contains($script, $privateField),
|
||||
'Browser module references private field ' . $privateField . '.');
|
||||
}
|
||||
|
||||
$assert(str_contains($template, '效果未知的发送不会自动重放')
|
||||
&& str_contains($script,
|
||||
'远端效果未知;系统禁止自动重放,请人工核对 Telegram。')
|
||||
&& str_contains($script,
|
||||
'页面不提供重试或重新发送入口。')
|
||||
&& preg_match('/<button[^>]*>[^<]*(?:重试|重新发送)/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";
|
||||
Loading…
Reference in New Issue