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/tests/CloudAbuseAlertDeliveryServ...

233 lines
11 KiB
PHP

<?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_instances', static function (Blueprint $t): void {
$t->increments('id'); $t->integer('user_id'); $t->integer('host_id');
});
$schema->create('cloud_network_findings', static function (Blueprint $t): void {
$t->increments('id'); $t->integer('instance_id'); $t->integer('policy_revision');
$t->string('rule_code');
$t->string('direction'); $t->string('ip_family');
});
$schema->create('cloud_network_alert_events', static function (Blueprint $t): void {
$t->increments('id'); $t->integer('finding_id');
$t->integer('transition_revision');
$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_network_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);
$instanceId = 100 + $number;
$db->table('cloud_instances')->insert([
'id' => $instanceId, 'user_id' => 10, 'host_id' => 20,
]);
$findingId = (int) $db->table('cloud_network_findings')->insertGetId([
'instance_id' => $instanceId, 'policy_revision' => 1,
'rule_code' => 'outbound_tcp_syn_sweep', 'direction' => 'outbound',
'ip_family' => 'ipv4',
]);
return (int) $db->table('cloud_network_alert_events')->insertGetId([
'finding_id' => $findingId, 'transition_revision' => 1,
'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,
]);
};
$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_network_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_network_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_network_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_network_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_network_alert_deliveries')
->where('event_id', $payload)->value('state') === 'failed'
&& $db->table('cloud_network_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_network_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_network_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_network_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_network_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_network_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_network_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_network_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";