feat(abuse): deliver durable Telegram alerts
parent
fa66714db9
commit
b54bde8bce
@ -0,0 +1,493 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\Telegram\AdministratorTelegramChannel;
|
||||
use App\Services\Telegram\AdministratorTelegramDeliveryChannel;
|
||||
use App\Services\Telegram\AdministratorTelegramDestination;
|
||||
use App\Services\Telegram\AdministratorTelegramLocalUnavailable;
|
||||
use App\Services\Telegram\AdministratorTelegramPreflightException;
|
||||
use App\Services\Telegram\AdministratorTelegramRateBacklog;
|
||||
use App\Services\Telegram\AdministratorTelegramRemoteEffectUnknown;
|
||||
|
||||
/** Durable, at-most-once Telegram delivery for immutable abuse alerts. */
|
||||
final class CloudAbuseAlertDeliveryService
|
||||
{
|
||||
public const DISPATCH_STALE_SECONDS = 30;
|
||||
|
||||
private readonly \Closure $clock;
|
||||
private readonly \Closure $afterRemoteSuccess;
|
||||
|
||||
public function __construct(
|
||||
private readonly ?AdministratorTelegramDeliveryChannel $channel = null,
|
||||
private readonly ?CloudAbuseAlertMessageFormatter $formatter = null,
|
||||
?callable $clock = null,
|
||||
?callable $afterRemoteSuccess = null
|
||||
) {
|
||||
$this->clock = \Closure::fromCallable(
|
||||
$clock ?? static fn (): int => time()
|
||||
);
|
||||
$this->afterRemoteSuccess = \Closure::fromCallable(
|
||||
$afterRemoteSuccess ?? static function (int $messageId): void {}
|
||||
);
|
||||
}
|
||||
|
||||
/** Process at most one stale fence and one fresh event/delivery. */
|
||||
public function tick(): bool
|
||||
{
|
||||
$now = $this->now();
|
||||
if ($this->settleStaleDispatch($now)) {
|
||||
return true;
|
||||
}
|
||||
$reserved = $this->reserveNextEvent($now);
|
||||
if ($reserved === 'local_unavailable') {
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert Telegram channel is temporarily unavailable'
|
||||
);
|
||||
}
|
||||
if ($reserved === 'terminal') {
|
||||
return true;
|
||||
}
|
||||
return $this->dispatchNextPending($now)
|
||||
|| $reserved === 'pending';
|
||||
}
|
||||
|
||||
/** @return 'none'|'pending'|'terminal'|'local_unavailable' */
|
||||
private function reserveNextEvent(int $now): string
|
||||
{
|
||||
$main = self::connection();
|
||||
$event = $main->table('cloud_abuse_alert_events as event')
|
||||
->whereNotExists(static function ($query): void {
|
||||
$query->selectRaw('1')
|
||||
->from('cloud_abuse_alert_deliveries as delivery')
|
||||
->whereColumn('delivery.event_id', 'event.id');
|
||||
})->orderBy('event.id')->first(['event.*']);
|
||||
if ($event === null) {
|
||||
return 'none';
|
||||
}
|
||||
$items = $main->table('cloud_abuse_alert_event_items')
|
||||
->where('event_id', (int) $event->id)
|
||||
->orderBy('id')->get()->all();
|
||||
|
||||
$formatFailed = false;
|
||||
try {
|
||||
$message = $this->messageFormatter()->format($event, $items);
|
||||
} catch (\Throwable $error) {
|
||||
$formatFailed = true;
|
||||
$message = '网络滥用告警事件格式无效,请在管理后台核查事件 #'
|
||||
. (int) $event->id . '。';
|
||||
}
|
||||
self::assertFrozenMessage($message);
|
||||
|
||||
$destination = null;
|
||||
if (!$formatFailed) {
|
||||
try {
|
||||
$destination = $this->telegramChannel()
|
||||
->currentDestination();
|
||||
} catch (AdministratorTelegramLocalUnavailable $error) {
|
||||
return 'local_unavailable';
|
||||
}
|
||||
}
|
||||
|
||||
return $main->transaction(function () use (
|
||||
$main, $event, $message, $destination, $formatFailed, $now
|
||||
): string {
|
||||
$effectiveDestination = $destination;
|
||||
if ($effectiveDestination !== null) {
|
||||
// Lock recipient before event, matching account deletion's
|
||||
// user -> delivery/event order. This fences a late pending
|
||||
// row from appearing after that user's deletion scan.
|
||||
$administrator = $main->table('user')
|
||||
->where('id', $effectiveDestination->administratorId)
|
||||
->lockForUpdate()->first(['id', 'is_admin', 'enable']);
|
||||
if ($administrator === null
|
||||
|| (int) $administrator->is_admin !== 1
|
||||
|| (int) $administrator->enable !== 1) {
|
||||
$effectiveDestination = null;
|
||||
}
|
||||
}
|
||||
$locked = $main->table('cloud_abuse_alert_events')
|
||||
->where('id', (int) $event->id)
|
||||
->where('event_key', (string) $event->event_key)
|
||||
->lockForUpdate()->first();
|
||||
if ($locked === null || $main->table(
|
||||
'cloud_abuse_alert_deliveries'
|
||||
)->where('event_id', (int) $event->id)->exists()) {
|
||||
return 'none';
|
||||
}
|
||||
|
||||
$state = 'pending';
|
||||
$errorCode = '';
|
||||
$skipReason = '';
|
||||
$terminalAt = null;
|
||||
if ($formatFailed) {
|
||||
$state = 'failed';
|
||||
$errorCode = 'message_format_invalid';
|
||||
$terminalAt = $now;
|
||||
} elseif ($effectiveDestination === null) {
|
||||
$state = 'skipped';
|
||||
$skipReason = $destination === null
|
||||
? 'channel_unavailable' : 'destination_ineligible';
|
||||
$terminalAt = $now;
|
||||
}
|
||||
$main->table('cloud_abuse_alert_deliveries')->insert([
|
||||
'event_id' => (int) $locked->id,
|
||||
'binding_generation' =>
|
||||
$effectiveDestination?->bindingGeneration,
|
||||
'bound_admin_id' =>
|
||||
$effectiveDestination?->administratorId,
|
||||
'chat_id' => $effectiveDestination?->chatId,
|
||||
'telegram_message_id' => null,
|
||||
'state' => $state,
|
||||
'message_text' => $message,
|
||||
'content_hash' => hash('sha256', $message),
|
||||
'error_code' => $errorCode,
|
||||
'skip_reason' => $skipReason,
|
||||
'dispatch_started_at' => null,
|
||||
'sent_at' => null,
|
||||
'terminal_at' => $terminalAt,
|
||||
'destination_redacted_at' => null,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
return $state === 'pending' ? 'pending' : 'terminal';
|
||||
}, 3);
|
||||
}
|
||||
|
||||
private function dispatchNextPending(int $now): bool
|
||||
{
|
||||
$main = self::connection();
|
||||
$claim = $main->transaction(function () use ($main, $now): ?array {
|
||||
$candidate = $main->table('cloud_abuse_alert_deliveries')
|
||||
->where('state', 'pending')->orderBy('created_at')
|
||||
->orderBy('id')->first([
|
||||
'id', 'event_id', 'bound_admin_id',
|
||||
]);
|
||||
if ($candidate === null) {
|
||||
return null;
|
||||
}
|
||||
$administrator = $main->table('user')
|
||||
->where('id', (int) $candidate->bound_admin_id)
|
||||
->lockForUpdate()->first(['id', 'is_admin', 'enable']);
|
||||
$event = $main->table('cloud_abuse_alert_events')
|
||||
->where('id', (int) $candidate->event_id)
|
||||
->lockForUpdate()->first(['id']);
|
||||
if ($event === null) {
|
||||
return null;
|
||||
}
|
||||
$delivery = $main->table('cloud_abuse_alert_deliveries')
|
||||
->where('id', (int) $candidate->id)
|
||||
->where('event_id', (int) $event->id)
|
||||
->where('state', 'pending')
|
||||
->lockForUpdate()->first();
|
||||
if ($delivery === null) {
|
||||
return null;
|
||||
}
|
||||
if ($administrator === null
|
||||
|| (int) $administrator->is_admin !== 1
|
||||
|| (int) $administrator->enable !== 1
|
||||
|| !$this->telegramChannel()->eligibleAdministrator(
|
||||
(int) $administrator->id
|
||||
)) {
|
||||
$updated = $main->table('cloud_abuse_alert_deliveries')
|
||||
->where('id', (int) $delivery->id)
|
||||
->where('state', 'pending')->update([
|
||||
'state' => 'skipped',
|
||||
'skip_reason' => 'destination_ineligible',
|
||||
'terminal_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
if ($updated !== 1) {
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert recipient settlement failed'
|
||||
);
|
||||
}
|
||||
return ['terminal' => true];
|
||||
}
|
||||
$message = (string) $delivery->message_text;
|
||||
if (!self::validDestination($delivery)
|
||||
|| !self::validFrozenMessage(
|
||||
$message,
|
||||
(string) $delivery->content_hash
|
||||
)) {
|
||||
$updated = $main->table('cloud_abuse_alert_deliveries')
|
||||
->where('id', (int) $delivery->id)
|
||||
->where('state', 'pending')->update([
|
||||
'state' => 'failed',
|
||||
'error_code' => 'delivery_identity_invalid',
|
||||
'terminal_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
if ($updated !== 1) {
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert invalid delivery finalization failed'
|
||||
);
|
||||
}
|
||||
return ['terminal' => true];
|
||||
}
|
||||
$updated = $main->table('cloud_abuse_alert_deliveries')
|
||||
->where('id', (int) $delivery->id)
|
||||
->where('state', 'pending')->update([
|
||||
'state' => 'dispatching',
|
||||
'dispatch_started_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
if ($updated !== 1) {
|
||||
throw new \RuntimeException('Abuse alert delivery claim failed');
|
||||
}
|
||||
return [
|
||||
'id' => (int) $delivery->id,
|
||||
'message' => $message,
|
||||
'destination' => new AdministratorTelegramDestination(
|
||||
(int) $delivery->bound_admin_id,
|
||||
(string) $delivery->chat_id,
|
||||
(string) $delivery->binding_generation
|
||||
),
|
||||
];
|
||||
}, 3);
|
||||
|
||||
if ($claim === null) {
|
||||
return false;
|
||||
}
|
||||
if (($claim['terminal'] ?? false) === true) {
|
||||
return true;
|
||||
}
|
||||
return $this->sendClaim($claim, $now);
|
||||
}
|
||||
|
||||
/** @param array{id:int,message:string,destination:AdministratorTelegramDestination} $claim */
|
||||
private function sendClaim(array $claim, int $now): bool
|
||||
{
|
||||
$id = $claim['id'];
|
||||
try {
|
||||
$messageId = $this->telegramChannel()->send(
|
||||
$claim['destination'],
|
||||
$claim['message'],
|
||||
['disable_web_page_preview' => 'true']
|
||||
);
|
||||
} catch (AdministratorTelegramRateBacklog $error) {
|
||||
$this->returnToPending($id, $now);
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert Telegram delivery backlog is full'
|
||||
);
|
||||
} catch (AdministratorTelegramLocalUnavailable $error) {
|
||||
$this->returnToPending($id, $now);
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert Telegram channel is temporarily unavailable'
|
||||
);
|
||||
} catch (AdministratorTelegramPreflightException $error) {
|
||||
if ($error->reason
|
||||
=== AdministratorTelegramPreflightException::PAYLOAD_INVALID) {
|
||||
$this->failInvalidPayload($id, $now);
|
||||
} else {
|
||||
$this->skipPreflight(
|
||||
$id,
|
||||
$now,
|
||||
$error->reason
|
||||
=== AdministratorTelegramPreflightException::DESTINATION_CHANGED
|
||||
? 'destination_changed'
|
||||
: 'channel_disabled_or_unavailable'
|
||||
);
|
||||
}
|
||||
return true;
|
||||
} catch (AdministratorTelegramRemoteEffectUnknown $error) {
|
||||
$this->markUnknown($id, $now, null);
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert Telegram remote effect is unknown'
|
||||
);
|
||||
} catch (\Throwable $error) {
|
||||
$this->markUnknown($id, $now, null);
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert Telegram remote effect is unknown'
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
($this->afterRemoteSuccess)($messageId);
|
||||
$updated = self::connection()->table(
|
||||
'cloud_abuse_alert_deliveries'
|
||||
)->where('id', $id)->where('state', 'dispatching')->update([
|
||||
'telegram_message_id' => $messageId,
|
||||
'state' => 'sent',
|
||||
'sent_at' => $now,
|
||||
'terminal_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
if ($updated !== 1) {
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert Telegram delivery finalization failed'
|
||||
);
|
||||
}
|
||||
} catch (\Throwable $error) {
|
||||
$this->markUnknown($id, $now, $messageId);
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert Telegram local finalization is unknown'
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private function settleStaleDispatch(int $now): bool
|
||||
{
|
||||
$main = self::connection();
|
||||
return $main->transaction(function () use ($main, $now): bool {
|
||||
$row = $main->table('cloud_abuse_alert_deliveries')
|
||||
->where('state', 'dispatching')
|
||||
->where('updated_at', '<=',
|
||||
$now - self::DISPATCH_STALE_SECONDS)
|
||||
->orderBy('updated_at')->orderBy('id')
|
||||
->lockForUpdate()->first();
|
||||
if ($row === null) {
|
||||
return false;
|
||||
}
|
||||
$updated = $main->table('cloud_abuse_alert_deliveries')
|
||||
->where('id', (int) $row->id)
|
||||
->where('state', 'dispatching')->update([
|
||||
'state' => 'unknown',
|
||||
'error_code' => 'worker_interrupted',
|
||||
'terminal_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
if ($updated !== 1) {
|
||||
throw new \RuntimeException(
|
||||
'Stale abuse alert delivery settlement failed'
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}, 3);
|
||||
}
|
||||
|
||||
private function returnToPending(int $id, int $now): void
|
||||
{
|
||||
$updated = self::connection()->table(
|
||||
'cloud_abuse_alert_deliveries'
|
||||
)->where('id', $id)->where('state', 'dispatching')->update([
|
||||
'state' => 'pending',
|
||||
'dispatch_started_at' => null,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
if ($updated !== 1) {
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert local retry release failed'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function skipPreflight(
|
||||
int $id,
|
||||
int $now,
|
||||
string $reason
|
||||
): void
|
||||
{
|
||||
$updated = self::connection()->table(
|
||||
'cloud_abuse_alert_deliveries'
|
||||
)->where('id', $id)->where('state', 'dispatching')->update([
|
||||
'state' => 'skipped',
|
||||
'skip_reason' => $reason,
|
||||
'dispatch_started_at' => null,
|
||||
'terminal_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
if ($updated !== 1) {
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert destination-change settlement failed'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function failInvalidPayload(int $id, int $now): void
|
||||
{
|
||||
$updated = self::connection()->table(
|
||||
'cloud_abuse_alert_deliveries'
|
||||
)->where('id', $id)->where('state', 'dispatching')->update([
|
||||
'state' => 'failed',
|
||||
'error_code' => 'payload_invalid',
|
||||
'dispatch_started_at' => null,
|
||||
'terminal_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
if ($updated !== 1) {
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert payload failure settlement failed'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function markUnknown(
|
||||
int $id,
|
||||
int $now,
|
||||
?int $messageId
|
||||
): void {
|
||||
try {
|
||||
$updated = self::connection()->table(
|
||||
'cloud_abuse_alert_deliveries'
|
||||
)->where('id', $id)->where('state', 'dispatching')->update([
|
||||
'telegram_message_id' => $messageId,
|
||||
'state' => 'unknown',
|
||||
'error_code' => 'remote_effect_unknown',
|
||||
'terminal_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
if ($updated !== 1) {
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert unknown-effect settlement failed'
|
||||
);
|
||||
}
|
||||
} catch (\Throwable $error) {
|
||||
// A retained dispatching row remains fenced and will be converted
|
||||
// by the stale reconciler. It must never be replayed.
|
||||
error_log('Abuse alert Telegram reconciliation failed');
|
||||
}
|
||||
}
|
||||
|
||||
private static function validDestination(object $delivery): bool
|
||||
{
|
||||
return (int) $delivery->bound_admin_id > 0
|
||||
&& preg_match('/^[a-f0-9]{32}$/D',
|
||||
(string) $delivery->binding_generation) === 1
|
||||
&& preg_match('/^[1-9][0-9]{0,18}$/D',
|
||||
(string) $delivery->chat_id) === 1;
|
||||
}
|
||||
|
||||
private static function assertFrozenMessage(string $message): void
|
||||
{
|
||||
if (!self::validFrozenMessage($message, hash('sha256', $message))) {
|
||||
throw new \LogicException('Abuse alert message is invalid');
|
||||
}
|
||||
}
|
||||
|
||||
private static function validFrozenMessage(
|
||||
string $message,
|
||||
string $hash
|
||||
): bool {
|
||||
$length = mb_strlen($message, 'UTF-8');
|
||||
return $length >= 1 && $length <= 4096
|
||||
&& preg_match('/^[a-f0-9]{64}$/D', $hash) === 1
|
||||
&& hash_equals($hash, hash('sha256', $message));
|
||||
}
|
||||
|
||||
private function telegramChannel(): AdministratorTelegramDeliveryChannel
|
||||
{
|
||||
return $this->channel ?? new AdministratorTelegramChannel();
|
||||
}
|
||||
|
||||
private function messageFormatter(): CloudAbuseAlertMessageFormatter
|
||||
{
|
||||
return $this->formatter ?? new CloudAbuseAlertMessageFormatter();
|
||||
}
|
||||
|
||||
private function now(): int
|
||||
{
|
||||
$now = ($this->clock)();
|
||||
if (!is_int($now) || $now < 1) {
|
||||
throw new \LogicException('Abuse alert delivery clock is invalid');
|
||||
}
|
||||
return $now;
|
||||
}
|
||||
|
||||
private static function connection(): object
|
||||
{
|
||||
return User::getConnectionResolver()->connection('default');
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Telegram;
|
||||
|
||||
/** Narrow one-shot channel contract for durable business delivery ledgers. */
|
||||
interface AdministratorTelegramDeliveryChannel
|
||||
{
|
||||
public function eligibleAdministrator(int $administratorId): bool;
|
||||
|
||||
public function currentDestination(): ?AdministratorTelegramDestination;
|
||||
|
||||
/** @param array<string,int|string|bool> $options */
|
||||
public function send(
|
||||
AdministratorTelegramDestination $expected,
|
||||
string $text,
|
||||
array $options = []
|
||||
): int;
|
||||
}
|
||||
@ -0,0 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Telegram;
|
||||
|
||||
/** No remote call started, but the shared queue exceeded its safe wait bound. */
|
||||
final class AdministratorTelegramRateBacklog extends \RuntimeException {}
|
||||
@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Telegram;
|
||||
|
||||
/** Acquire one local permit before an administrator Telegram remote call. */
|
||||
interface AdministratorTelegramRateLimiter
|
||||
{
|
||||
public function acquire(
|
||||
AdministratorTelegramDestination $destination
|
||||
): void;
|
||||
}
|
||||
@ -0,0 +1,120 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Telegram;
|
||||
|
||||
use App\Models\Configurations;
|
||||
|
||||
/** Cross-process singleton rate gate for every administrator Telegram send. */
|
||||
final class DatabaseAdministratorTelegramRateGate
|
||||
implements AdministratorTelegramRateLimiter
|
||||
{
|
||||
public const RATE_LIMIT_SECONDS = 2;
|
||||
public const MAX_BACKLOG_SECONDS = 2;
|
||||
|
||||
private readonly \Closure $clock;
|
||||
private readonly \Closure $sleeper;
|
||||
|
||||
public function __construct(
|
||||
?callable $clock = null,
|
||||
?callable $sleeper = null
|
||||
)
|
||||
{
|
||||
$this->clock = \Closure::fromCallable(
|
||||
$clock ?? static fn (): int => time()
|
||||
);
|
||||
$this->sleeper = \Closure::fromCallable(
|
||||
$sleeper ?? static function (int $microseconds): void {
|
||||
usleep($microseconds);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
public function acquire(
|
||||
AdministratorTelegramDestination $destination
|
||||
): void {
|
||||
$now = ($this->clock)();
|
||||
if (!is_int($now) || $now < 1) {
|
||||
throw new AdministratorTelegramLocalUnavailable(
|
||||
'Administrator Telegram rate clock is unavailable'
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
$connection = (new Configurations())->getConnection();
|
||||
$reservation = $connection->transaction(function () use (
|
||||
$connection,
|
||||
$now
|
||||
): array {
|
||||
$gate = $connection->table(
|
||||
'administrator_telegram_delivery_gate'
|
||||
)->where('id', 1)->lockForUpdate()->first();
|
||||
if ($gate === null) {
|
||||
throw new \RuntimeException(
|
||||
'Administrator Telegram rate gate is missing'
|
||||
);
|
||||
}
|
||||
$oldNext = (int) $gate->next_send_at;
|
||||
$oldUpdated = (int) $gate->updated_at;
|
||||
if ($oldUpdated > $now + self::MAX_BACKLOG_SECONDS
|
||||
|| $oldNext > $now + self::MAX_BACKLOG_SECONDS
|
||||
+ self::RATE_LIMIT_SECONDS) {
|
||||
$updated = $connection->table(
|
||||
'administrator_telegram_delivery_gate'
|
||||
)->where('id', 1)->where('next_send_at', $oldNext)
|
||||
->update([
|
||||
// Quarantine one full normal collision window.
|
||||
// The current call does not receive a permit.
|
||||
'next_send_at' => $now
|
||||
+ self::MAX_BACKLOG_SECONDS
|
||||
+ self::RATE_LIMIT_SECONDS,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
if ((int) $updated !== 1) {
|
||||
throw new \RuntimeException(
|
||||
'Administrator Telegram rate gate recovery failed'
|
||||
);
|
||||
}
|
||||
return ['slot' => null, 'recovered' => true];
|
||||
}
|
||||
$slot = max($now, $oldNext);
|
||||
if ($slot - $now > self::MAX_BACKLOG_SECONDS) {
|
||||
throw new AdministratorTelegramRateBacklog(
|
||||
'Administrator Telegram delivery backlog is full'
|
||||
);
|
||||
}
|
||||
$updated = $connection->table(
|
||||
'administrator_telegram_delivery_gate'
|
||||
)->where('id', 1)
|
||||
->where('next_send_at', $oldNext)
|
||||
->update([
|
||||
'next_send_at' => $slot + self::RATE_LIMIT_SECONDS,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
if ((int) $updated !== 1) {
|
||||
throw new \RuntimeException(
|
||||
'Administrator Telegram rate gate update failed'
|
||||
);
|
||||
}
|
||||
return ['slot' => $slot, 'recovered' => false];
|
||||
}, 3);
|
||||
if ($reservation['recovered']) {
|
||||
throw new AdministratorTelegramLocalUnavailable(
|
||||
'Administrator Telegram rate clock recovered'
|
||||
);
|
||||
}
|
||||
$slot = (int) $reservation['slot'];
|
||||
$wait = $slot - $now;
|
||||
if ($wait > 0) {
|
||||
($this->sleeper)($wait * 1000000);
|
||||
}
|
||||
} catch (AdministratorTelegramRateBacklog $exception) {
|
||||
throw $exception;
|
||||
} catch (AdministratorTelegramLocalUnavailable $exception) {
|
||||
throw $exception;
|
||||
} catch (\Throwable $exception) {
|
||||
throw new AdministratorTelegramLocalUnavailable(
|
||||
'Administrator Telegram rate gate is temporarily unavailable'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,108 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Models\Configurations;
|
||||
use App\Services\Telegram\AdministratorTelegramDestination;
|
||||
use App\Services\Telegram\AdministratorTelegramLocalUnavailable;
|
||||
use App\Services\Telegram\AdministratorTelegramRateBacklog;
|
||||
use App\Services\Telegram\DatabaseAdministratorTelegramRateGate;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
$capsule = new Capsule();
|
||||
$capsule->addConnection([
|
||||
'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '',
|
||||
], 'default');
|
||||
$capsule->setAsGlobal();
|
||||
$capsule->bootEloquent();
|
||||
Configurations::setConnectionResolver($capsule->getDatabaseManager());
|
||||
$db = $capsule->getConnection('default');
|
||||
$db->getSchemaBuilder()->create(
|
||||
'administrator_telegram_delivery_gate',
|
||||
static function (Blueprint $table): void {
|
||||
$table->integer('id')->primary();
|
||||
$table->integer('next_send_at');
|
||||
$table->integer('updated_at');
|
||||
}
|
||||
);
|
||||
$db->table('administrator_telegram_delivery_gate')->insert([
|
||||
'id' => 1, 'next_send_at' => 0, 'updated_at' => 0,
|
||||
]);
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$destination = new AdministratorTelegramDestination(
|
||||
1, '123456', str_repeat('a', 32)
|
||||
);
|
||||
$now = 2000;
|
||||
$sleeps = [];
|
||||
$gate = new DatabaseAdministratorTelegramRateGate(
|
||||
static function () use (&$now): int { return $now; },
|
||||
static function (int $microseconds) use (&$sleeps, $db): void {
|
||||
if ($db->transactionLevel() !== 0) {
|
||||
throw new RuntimeException('Rate wait occurred inside transaction');
|
||||
}
|
||||
$sleeps[] = $microseconds;
|
||||
}
|
||||
);
|
||||
|
||||
$gate->acquire($destination);
|
||||
$assert($sleeps === []
|
||||
&& (int) $db->table('administrator_telegram_delivery_gate')
|
||||
->value('next_send_at') === 2002,
|
||||
'First Telegram permit was not reserved immediately.');
|
||||
$gate->acquire($destination);
|
||||
$assert($sleeps === [2000000]
|
||||
&& (int) $db->table('administrator_telegram_delivery_gate')
|
||||
->value('next_send_at') === 2004,
|
||||
'Second Telegram permit did not reserve and wait for the adjacent slot.');
|
||||
|
||||
$backlog = null;
|
||||
try {
|
||||
$gate->acquire($destination);
|
||||
} catch (Throwable $error) {
|
||||
$backlog = $error;
|
||||
}
|
||||
$assert($backlog instanceof AdministratorTelegramRateBacklog
|
||||
&& count($sleeps) === 1,
|
||||
'Third concurrent permit was not classified as known-no-remote backlog.');
|
||||
|
||||
// A stale future wall-clock value is quarantined and rewritten. The current
|
||||
// request receives no permit, while later callers can recover automatically.
|
||||
$now = 3000;
|
||||
$db->table('administrator_telegram_delivery_gate')->where('id', 1)->update([
|
||||
'next_send_at' => 9002, 'updated_at' => 9000,
|
||||
]);
|
||||
$clockFailure = null;
|
||||
try {
|
||||
$gate->acquire($destination);
|
||||
} catch (Throwable $error) {
|
||||
$clockFailure = $error;
|
||||
}
|
||||
$recovered = $db->table('administrator_telegram_delivery_gate')
|
||||
->where('id', 1)->first();
|
||||
$assert($clockFailure instanceof AdministratorTelegramLocalUnavailable
|
||||
&& (int) $recovered->updated_at === 3000
|
||||
&& (int) $recovered->next_send_at === 3004,
|
||||
'Future Telegram gate timestamp was not safely quarantined.');
|
||||
$now = 3002;
|
||||
$gate->acquire($destination);
|
||||
$assert(end($sleeps) === 2000000,
|
||||
'Recovered Telegram gate did not resume through a bounded slot.');
|
||||
|
||||
$db->getSchemaBuilder()->drop('administrator_telegram_delivery_gate');
|
||||
$missing = null;
|
||||
try {
|
||||
$gate->acquire($destination);
|
||||
} catch (Throwable $error) {
|
||||
$missing = $error;
|
||||
}
|
||||
$assert($missing instanceof AdministratorTelegramLocalUnavailable,
|
||||
'Missing shared Telegram gate was not a known local failure.');
|
||||
|
||||
echo "Administrator Telegram rate gate tests passed.\n";
|
||||
@ -0,0 +1,238 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\Config;
|
||||
use App\Services\Cloud\CloudAbuseAlertDeliveryService;
|
||||
use App\Services\Cloud\CloudAbuseAlertMessageFormatter;
|
||||
use App\Services\Telegram\AdministratorTelegramDeliveryChannel;
|
||||
use App\Services\Telegram\AdministratorTelegramDestination;
|
||||
use App\Services\Telegram\AdministratorTelegramLocalUnavailable;
|
||||
use App\Services\Telegram\AdministratorTelegramPreflightException;
|
||||
use App\Services\Telegram\AdministratorTelegramRateBacklog;
|
||||
use App\Services\Telegram\AdministratorTelegramRemoteEffectUnknown;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
$capsule = new Capsule();
|
||||
$capsule->addConnection([
|
||||
'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '',
|
||||
], 'default');
|
||||
$capsule->setAsGlobal(); $capsule->bootEloquent();
|
||||
User::setConnectionResolver($capsule->getDatabaseManager());
|
||||
$db = $capsule->getConnection('default'); $schema = $db->getSchemaBuilder();
|
||||
$schema->create('user', static function (Blueprint $t): void {
|
||||
$t->increments('id'); $t->integer('is_admin'); $t->integer('enable');
|
||||
});
|
||||
$schema->create('cloud_abuse_alert_events', static function (Blueprint $t): void {
|
||||
$t->increments('id'); $t->string('event_key'); $t->string('sample_key');
|
||||
$t->integer('instance_id'); $t->integer('user_id'); $t->integer('host_id');
|
||||
$t->integer('bucket_start'); $t->integer('rule_version');
|
||||
$t->integer('policy_revision'); $t->string('policy_hash');
|
||||
$t->string('transition_digest'); $t->integer('transition_count');
|
||||
$t->string('highest_severity'); $t->integer('created_at');
|
||||
});
|
||||
$schema->create('cloud_abuse_alert_event_items', static function (Blueprint $t): void {
|
||||
$t->increments('id'); $t->integer('event_id'); $t->string('item_key');
|
||||
$t->string('finding_key'); $t->integer('occurrence_generation');
|
||||
$t->integer('transition_revision'); $t->string('rule_code');
|
||||
$t->string('direction'); $t->string('ip_family');
|
||||
$t->string('transition_type'); $t->string('from_severity');
|
||||
$t->string('to_severity'); $t->text('evidence_json');
|
||||
$t->string('resolution_reason'); $t->integer('occurred_at');
|
||||
$t->integer('created_at');
|
||||
});
|
||||
$schema->create('cloud_abuse_alert_deliveries', static function (Blueprint $t): void {
|
||||
$t->increments('id'); $t->integer('event_id')->unique();
|
||||
$t->string('binding_generation')->nullable();
|
||||
$t->integer('bound_admin_id')->nullable(); $t->string('chat_id')->nullable();
|
||||
$t->integer('telegram_message_id')->nullable(); $t->string('state');
|
||||
$t->text('message_text'); $t->string('content_hash');
|
||||
$t->string('error_code')->default(''); $t->string('skip_reason')->default('');
|
||||
$t->integer('dispatch_started_at')->nullable(); $t->integer('sent_at')->nullable();
|
||||
$t->integer('terminal_at')->nullable(); $t->integer('destination_redacted_at')->nullable();
|
||||
$t->integer('created_at'); $t->integer('updated_at');
|
||||
});
|
||||
$db->table('user')->insert(['id' => 1, 'is_admin' => 1, 'enable' => 1]);
|
||||
Config::set('baseUrl', 'https://panel.example.test');
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) { throw new RuntimeException($message); }
|
||||
};
|
||||
|
||||
final class AbuseDeliveryFakeChannel implements AdministratorTelegramDeliveryChannel
|
||||
{
|
||||
public ?AdministratorTelegramDestination $destination;
|
||||
public string $destinationMode = 'ready'; public string $sendMode = 'success';
|
||||
public int $calls = 0; public array $messages = [];
|
||||
public function __construct() { $this->destination = new AdministratorTelegramDestination(
|
||||
1, '123456', str_repeat('a', 32)
|
||||
); }
|
||||
public function eligibleAdministrator(int $administratorId): bool
|
||||
{
|
||||
return $administratorId === 1;
|
||||
}
|
||||
public function currentDestination(): ?AdministratorTelegramDestination
|
||||
{
|
||||
if ($this->destinationMode === 'local') {
|
||||
throw new AdministratorTelegramLocalUnavailable('synthetic');
|
||||
}
|
||||
return $this->destination;
|
||||
}
|
||||
public function send(AdministratorTelegramDestination $expected,
|
||||
string $text, array $options = []): int
|
||||
{
|
||||
if ($this->sendMode === 'local') {
|
||||
throw new AdministratorTelegramLocalUnavailable('synthetic');
|
||||
}
|
||||
if ($this->sendMode === 'preflight') {
|
||||
throw new AdministratorTelegramPreflightException(
|
||||
AdministratorTelegramPreflightException::DESTINATION_CHANGED,
|
||||
'synthetic'
|
||||
);
|
||||
}
|
||||
if ($this->sendMode === 'payload') {
|
||||
throw new AdministratorTelegramPreflightException(
|
||||
AdministratorTelegramPreflightException::PAYLOAD_INVALID,
|
||||
'synthetic'
|
||||
);
|
||||
}
|
||||
if ($this->sendMode === 'channel') {
|
||||
throw new AdministratorTelegramPreflightException(
|
||||
AdministratorTelegramPreflightException::CHANNEL_UNAVAILABLE,
|
||||
'synthetic'
|
||||
);
|
||||
}
|
||||
if ($this->sendMode === 'backlog') {
|
||||
throw new AdministratorTelegramRateBacklog('synthetic');
|
||||
}
|
||||
$this->calls++; $this->messages[] = $text;
|
||||
if ($this->sendMode === 'remote') {
|
||||
throw new AdministratorTelegramRemoteEffectUnknown('synthetic');
|
||||
}
|
||||
return 7000 + $this->calls;
|
||||
}
|
||||
}
|
||||
|
||||
$identity = 1;
|
||||
$addEvent = static function () use ($db, &$identity): int {
|
||||
$number = $identity++; $bucket = 1800000000 + ($number * 60);
|
||||
$id = (int) $db->table('cloud_abuse_alert_events')->insertGetId([
|
||||
'event_key' => hash('sha256', 'event-' . $number),
|
||||
'sample_key' => hash('sha256', 'sample-' . $number),
|
||||
'instance_id' => 100 + $number, 'user_id' => 10, 'host_id' => 20,
|
||||
'bucket_start' => $bucket, 'rule_version' => 1,
|
||||
'policy_revision' => 1, 'policy_hash' => str_repeat('b', 64),
|
||||
'transition_digest' => str_repeat('c', 64), 'transition_count' => 1,
|
||||
'highest_severity' => 'high', 'created_at' => $bucket,
|
||||
]);
|
||||
$db->table('cloud_abuse_alert_event_items')->insert([
|
||||
'event_id' => $id, 'item_key' => hash('sha256', 'item-' . $number),
|
||||
'finding_key' => hash('sha256', 'finding-' . $number),
|
||||
'occurrence_generation' => 1, 'transition_revision' => 1,
|
||||
'rule_code' => 'outbound_tcp_syn_sweep', 'direction' => 'outbound',
|
||||
'ip_family' => 'ipv4', 'transition_type' => 'opened',
|
||||
'from_severity' => 'none', 'to_severity' => 'high',
|
||||
'evidence_json' => '{"tcp_syn_flows":5000,"unique_remote_ips":600}',
|
||||
'resolution_reason' => '', 'occurred_at' => $bucket,
|
||||
'created_at' => $bucket,
|
||||
]);
|
||||
return $id;
|
||||
};
|
||||
|
||||
$now = 1900000000; $channel = new AbuseDeliveryFakeChannel();
|
||||
$service = new CloudAbuseAlertDeliveryService($channel,
|
||||
new CloudAbuseAlertMessageFormatter(),
|
||||
static function () use (&$now): int { return $now; });
|
||||
$first = $addEvent();
|
||||
$assert($service->tick() && $channel->calls === 1,
|
||||
'Fresh alert was not sent exactly once.');
|
||||
$sent = $db->table('cloud_abuse_alert_deliveries')->where('event_id', $first)->first();
|
||||
$assert($sent?->state === 'sent' && (int) $sent->telegram_message_id === 7001
|
||||
&& hash_equals((string) $sent->content_hash,
|
||||
hash('sha256', (string) $sent->message_text)),
|
||||
'Sent delivery did not retain its frozen message identity.');
|
||||
$assert(!$service->tick() && $channel->calls === 1, 'Sent event was replayed.');
|
||||
|
||||
$second = $addEvent();
|
||||
$assert($service->tick() && $channel->calls === 2,
|
||||
'A second alert was not delegated to the shared channel.');
|
||||
|
||||
$channel->destination = null; $skipped = $addEvent();
|
||||
$assert($service->tick() && $db->table('cloud_abuse_alert_deliveries')
|
||||
->where('event_id', $skipped)->value('state') === 'skipped',
|
||||
'Unbound channel did not terminally skip the event.');
|
||||
$channel->destination = new AdministratorTelegramDestination(
|
||||
1, '123456', str_repeat('a', 32)
|
||||
);
|
||||
$local = $addEvent(); $channel->destinationMode = 'local'; $threw = false;
|
||||
try { $service->tick(); } catch (RuntimeException) { $threw = true; }
|
||||
$assert($threw && !$db->table('cloud_abuse_alert_deliveries')
|
||||
->where('event_id', $local)->exists(),
|
||||
'Local destination failure was hidden or consumed the event.');
|
||||
$channel->destinationMode = 'ready'; $channel->sendMode = 'preflight'; $now += 2;
|
||||
$assert($service->tick() && $db->table('cloud_abuse_alert_deliveries')
|
||||
->where('event_id', $local)->value('state') === 'skipped',
|
||||
'Destination change was not safely skipped before network I/O.');
|
||||
|
||||
$payload = $addEvent(); $channel->sendMode = 'payload'; $now += 2;
|
||||
$assert($service->tick() && $db->table('cloud_abuse_alert_deliveries')
|
||||
->where('event_id', $payload)->value('state') === 'failed'
|
||||
&& $db->table('cloud_abuse_alert_deliveries')
|
||||
->where('event_id', $payload)->value('dispatch_started_at') === null,
|
||||
'Invalid payload was not a known pre-network failure.');
|
||||
$disabled = $addEvent(); $channel->sendMode = 'channel'; $now += 2;
|
||||
$assert($service->tick() && $db->table('cloud_abuse_alert_deliveries')
|
||||
->where('event_id', $disabled)->value('skip_reason')
|
||||
=== 'channel_disabled_or_unavailable',
|
||||
'Disabled channel was mislabeled as a destination change.');
|
||||
|
||||
$backlogged = $addEvent(); $channel->sendMode = 'backlog'; $now += 2;
|
||||
$threw = false;
|
||||
try { $service->tick(); } catch (RuntimeException) { $threw = true; }
|
||||
$assert($threw && $db->table('cloud_abuse_alert_deliveries')
|
||||
->where('event_id', $backlogged)->value('state') === 'pending',
|
||||
'Known-no-remote Telegram backlog was not retained as pending.');
|
||||
$channel->sendMode = 'success'; $now += 2;
|
||||
$assert($service->tick(), 'Backlogged alert did not resume safely.');
|
||||
|
||||
$retryable = $addEvent(); $channel->sendMode = 'local'; $now += 2; $threw = false;
|
||||
try { $service->tick(); } catch (RuntimeException) { $threw = true; }
|
||||
$assert($threw && $db->table('cloud_abuse_alert_deliveries')
|
||||
->where('event_id', $retryable)->value('state') === 'pending',
|
||||
'Local send failure did not return frozen work to pending.');
|
||||
$channel->sendMode = 'remote'; $now += 2; $threw = false;
|
||||
try { $service->tick(); } catch (RuntimeException) { $threw = true; }
|
||||
$assert($threw && $db->table('cloud_abuse_alert_deliveries')
|
||||
->where('event_id', $retryable)->value('state') === 'unknown',
|
||||
'Remote-effect failure was not fenced as unknown.');
|
||||
|
||||
$afterRemote = $addEvent(); $channel->sendMode = 'success'; $now += 2;
|
||||
$failing = new CloudAbuseAlertDeliveryService($channel,
|
||||
new CloudAbuseAlertMessageFormatter(),
|
||||
static function () use (&$now): int { return $now; },
|
||||
static function (int $messageId): void { throw new RuntimeException('fail'); });
|
||||
$threw = false; try { $failing->tick(); } catch (RuntimeException) { $threw = true; }
|
||||
$row = $db->table('cloud_abuse_alert_deliveries')->where('event_id', $afterRemote)->first();
|
||||
$assert($threw && $row?->state === 'unknown'
|
||||
&& (int) $row->telegram_message_id > 0,
|
||||
'Post-send finalization failure was not retained as unknown.');
|
||||
|
||||
$stale = $addEvent();
|
||||
$db->table('cloud_abuse_alert_deliveries')->insert([
|
||||
'event_id' => $stale, 'binding_generation' => str_repeat('a', 32),
|
||||
'bound_admin_id' => 1, 'chat_id' => '123456', 'telegram_message_id' => null,
|
||||
'state' => 'dispatching', 'message_text' => 'frozen',
|
||||
'content_hash' => hash('sha256', 'frozen'), 'error_code' => '',
|
||||
'skip_reason' => '', 'dispatch_started_at' => $now - 40,
|
||||
'sent_at' => null, 'terminal_at' => null,
|
||||
'destination_redacted_at' => null, 'created_at' => $now - 40,
|
||||
'updated_at' => $now - 40,
|
||||
]);
|
||||
$assert($service->tick() && $db->table('cloud_abuse_alert_deliveries')
|
||||
->where('event_id', $stale)->value('state') === 'unknown',
|
||||
'Stale dispatch was not fenced as unknown.');
|
||||
|
||||
echo "Cloud abuse alert delivery service tests passed.\n";
|
||||
@ -0,0 +1,141 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Cloud\CloudAbuseAlertMessageFormatter;
|
||||
use App\Services\Config;
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$throws = static function (callable $callback, string $message) use ($assert): void {
|
||||
try {
|
||||
$callback();
|
||||
} catch (InvalidArgumentException) {
|
||||
return;
|
||||
}
|
||||
$assert(false, $message);
|
||||
};
|
||||
|
||||
$event = (object) [
|
||||
'id' => 41,
|
||||
'event_key' => str_repeat('a', 64),
|
||||
'instance_id' => 91,
|
||||
'user_id' => 17,
|
||||
'host_id' => 3,
|
||||
'bucket_start' => 1794182400,
|
||||
'rule_version' => 1,
|
||||
'policy_revision' => 4,
|
||||
'transition_count' => 2,
|
||||
'highest_severity' => 'high',
|
||||
];
|
||||
$item = static function (array $overrides = []): object {
|
||||
return (object) array_replace([
|
||||
'event_id' => 41,
|
||||
'item_key' => str_repeat('b', 64),
|
||||
'finding_key' => str_repeat('c', 64),
|
||||
'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' => 4321,
|
||||
'unique_remote_ips' => 600,
|
||||
], JSON_THROW_ON_ERROR),
|
||||
'resolution_reason' => '',
|
||||
'occurred_at' => 1794182400,
|
||||
], $overrides);
|
||||
};
|
||||
$items = [
|
||||
$item(),
|
||||
$item([
|
||||
'item_key' => str_repeat('d', 64),
|
||||
'finding_key' => str_repeat('e', 64),
|
||||
'rule_code' => 'inbound_udp_flood',
|
||||
'direction' => 'inbound',
|
||||
'ip_family' => 'ipv6',
|
||||
'transition_type' => 'resolved',
|
||||
'from_severity' => 'suspicious',
|
||||
'to_severity' => 'none',
|
||||
'evidence_json' => '{"udp_active_flows":0,"udp_new_flows":0}',
|
||||
'resolution_reason' => 'evidence_clear',
|
||||
]),
|
||||
];
|
||||
|
||||
$formatter = new CloudAbuseAlertMessageFormatter();
|
||||
Config::set('baseUrl', 'https://panel.example.test');
|
||||
$message = $formatter->format($event, $items);
|
||||
$assert(str_contains($message, '网络滥用高风险告警')
|
||||
&& str_contains($message, '告警:#41')
|
||||
&& str_contains($message, '实例:#91')
|
||||
&& str_contains($message, '用户:#17')
|
||||
&& str_contains($message, '宿主机:#3')
|
||||
&& str_contains($message, '出站可疑行为')
|
||||
&& str_contains($message, '入站受攻击')
|
||||
&& str_contains($message, 'TCP SYN Flow 4,321')
|
||||
&& str_contains($message,
|
||||
'https://panel.example.test/admin/abuse-monitoring?query=91'),
|
||||
'Formatter omitted immutable identity, direction or aggregate evidence.');
|
||||
$assert(!str_contains($message, '203.0.113.9')
|
||||
&& !str_contains($message, '通信正文:'),
|
||||
'Formatter exposed address or packet-content fields.');
|
||||
$assert(mb_strlen($message, 'UTF-8') <= 4096,
|
||||
'Formatter exceeded Telegram message length.');
|
||||
|
||||
$resolvedEvent = clone $event;
|
||||
$resolvedEvent->transition_count = 1;
|
||||
$resolvedEvent->highest_severity = 'suspicious';
|
||||
Config::set('baseUrl', 'http://127.0.0.1:8765');
|
||||
$resolved = $formatter->format($resolvedEvent, [$items[1]]);
|
||||
$assert(str_contains($resolved, '网络风险已恢复')
|
||||
&& str_contains($resolved, '可疑状态已解除'),
|
||||
'Resolved alert was not rendered as a recovery.');
|
||||
|
||||
$manyItems = [];
|
||||
for ($index = 0; $index < 80; $index++) {
|
||||
$manyItems[] = $item([
|
||||
'item_key' => hash('sha256', 'item-' . $index),
|
||||
'finding_key' => hash('sha256', 'finding-' . $index),
|
||||
]);
|
||||
}
|
||||
$manyEvent = clone $event;
|
||||
$manyEvent->transition_count = count($manyItems);
|
||||
Config::set('baseUrl', 'https://panel.example.test/base');
|
||||
$bounded = $formatter->format($manyEvent, $manyItems);
|
||||
$assert(mb_strlen($bounded, 'UTF-8') <= 4096
|
||||
&& str_contains($bounded, '其他规则:'),
|
||||
'Large immutable event was not summarized within Telegram limits.');
|
||||
|
||||
$invalidEvidence = array_map(static fn (object $row): object => clone $row, $items);
|
||||
$invalidEvidence[0]->evidence_json =
|
||||
'{"remote_ip":"203.0.113.9","tcp_syn_flows":5}';
|
||||
$throws(
|
||||
static fn () => $formatter->format($event, $invalidEvidence),
|
||||
'Address-bearing evidence was accepted.'
|
||||
);
|
||||
$wrongEvent = clone $event;
|
||||
$wrongEvent->transition_count = 1;
|
||||
$throws(
|
||||
static fn () => $formatter->format($wrongEvent, $items),
|
||||
'Event/item count mismatch was accepted.'
|
||||
);
|
||||
$wrongBucket = array_map(static fn (object $row): object => clone $row, $items);
|
||||
$wrongBucket[0]->occurred_at++;
|
||||
$throws(
|
||||
static fn () => $formatter->format($event, $wrongBucket),
|
||||
'Cross-bucket alert item was accepted.'
|
||||
);
|
||||
$throws(
|
||||
static function () use ($formatter, $event, $items): void {
|
||||
Config::set('baseUrl', "https://panel.example.test\n.invalid");
|
||||
$formatter->format($event, $items);
|
||||
},
|
||||
'Unsafe administrator base URL was accepted.'
|
||||
);
|
||||
|
||||
echo "Cloud abuse alert message formatter tests passed.\n";
|
||||
Loading…
Reference in New Issue