You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudAdminAbuseAlertHistory...

484 lines
18 KiB
PHP

<?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();
$rows = [];
foreach ($records as $record) {
$rows[] = $this->eventRow($record);
}
$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_network_alert_events as event')
->join('cloud_network_findings as finding',
'finding.id', '=', 'event.finding_id')
->leftJoin('cloud_network_alert_deliveries as delivery',
'delivery.event_id', '=', 'event.id')
->leftJoin('cloud_instances as instance',
'instance.id', '=', 'finding.instance_id')
->leftJoin('cloud_hosts as host',
'host.id', '=', 'instance.host_id')
->leftJoin('user as current_owner',
'current_owner.id', '=', 'instance.user_id');
}
/** @return list<string> */
private static function columns(): array
{
return [
'event.id as event_id', 'finding.instance_id',
'instance.user_id', 'instance.host_id',
'event.occurred_at', 'event.created_at',
'event.transition_type', 'event.from_severity',
'event.to_severity', 'event.evidence_json',
'event.resolution_reason',
'finding.rule_code', 'finding.direction', 'finding.ip_family',
'instance.name as instance_name',
'current_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'] !== '') {
$severity = $filters['severity'];
$query->where(static function ($severityQuery) use (
$severity
): void {
$severityQuery->where('event.to_severity', $severity)
->orWhere('event.from_severity', $severity);
});
}
foreach ([
'event_id' => 'event.id',
'instance_id' => 'finding.instance_id',
'user_id' => 'instance.user_id',
'host_id' => 'instance.host_id',
] as $filter => $column) {
if ($filters[$filter] !== null) {
$query->where($column, $filters[$filter]);
}
}
foreach ([
'transition' => 'event.transition_type',
'direction' => 'finding.direction',
'ip_family' => 'finding.ip_family',
] as $filter => $column) {
if ($filters[$filter] !== '') {
$query->where($column, $filters[$filter]);
}
}
if ($filters['query'] !== '') {
$id = (int) $filters['query'];
$query->where(static function ($ids) use ($id): void {
$ids->where('event.id', $id)
->orWhere('finding.instance_id', $id)
->orWhere('instance.user_id', $id)
->orWhere('instance.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;
}
/** @return array<string,mixed> */
private function eventRow(object $record): 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' => false,
'bucket_start' => self::timestamp((int) $record->occurred_at),
'created_at' => self::timestamp((int) $record->created_at),
'transition_count' => 1,
'highest_severity' => self::severityRow(
(string) $record->to_severity === 'high'
|| (string) $record->from_severity === 'high'
? 'high' : 'suspicious'
),
'delivery' => $delivery,
'items' => [self::itemRow($record)],
];
}
/** @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;
}
}