feat(abuse): persist alert transition ledger
parent
bb29c6f2f7
commit
0a8a318291
@ -0,0 +1,301 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/**
|
||||
* Persists immutable finding-transition facts in the caller's main-database
|
||||
* transaction. This coordinator intentionally performs no external delivery.
|
||||
*/
|
||||
final class CloudAbuseAlertEventCoordinator
|
||||
{
|
||||
/**
|
||||
* @param array<string,mixed> $claim
|
||||
* @param list<array<string,mixed>> $transitions
|
||||
*/
|
||||
public function record(
|
||||
object $main,
|
||||
array $claim,
|
||||
array $transitions,
|
||||
int $now
|
||||
): void {
|
||||
if ($transitions === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$items = self::canonicalTransitions($transitions);
|
||||
foreach ($items as $item) {
|
||||
if ($item['occurred_at'] !== (int) $claim['bucket_start']) {
|
||||
throw new \LogicException(
|
||||
'Abuse alert transition bucket is inconsistent'
|
||||
);
|
||||
}
|
||||
}
|
||||
$canonicalJson = self::json($items);
|
||||
$digest = hash('sha256', $canonicalJson);
|
||||
$eventKey = hash('sha256', implode("\n", [
|
||||
'cloud-abuse-alert-event-v1',
|
||||
(string) $claim['sample_key'],
|
||||
(string) $claim['instance_id'],
|
||||
(string) $claim['bucket_start'],
|
||||
(string) $claim['rule_version'],
|
||||
(string) $claim['policy_revision'],
|
||||
(string) $claim['policy_hash'],
|
||||
$digest,
|
||||
]));
|
||||
$highestSeverity = self::highestSeverity($items);
|
||||
$eventValues = [
|
||||
'event_key' => $eventKey,
|
||||
'sample_key' => (string) $claim['sample_key'],
|
||||
'instance_id' => (int) $claim['instance_id'],
|
||||
'user_id' => (int) $claim['user_id'],
|
||||
'host_id' => (int) $claim['host_id'],
|
||||
'bucket_start' => (int) $claim['bucket_start'],
|
||||
'rule_version' => (int) $claim['rule_version'],
|
||||
'policy_revision' => (int) $claim['policy_revision'],
|
||||
'policy_hash' => (string) $claim['policy_hash'],
|
||||
'transition_digest' => $digest,
|
||||
'transition_count' => count($items),
|
||||
'highest_severity' => $highestSeverity,
|
||||
'created_at' => $now,
|
||||
];
|
||||
|
||||
$existing = $main->table('cloud_abuse_alert_events')
|
||||
->where('sample_key', $eventValues['sample_key'])
|
||||
->lockForUpdate()->first();
|
||||
if ($existing === null) {
|
||||
$eventId = (int) $main->table('cloud_abuse_alert_events')
|
||||
->insertGetId($eventValues);
|
||||
if ($eventId < 1) {
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert event insert did not return an id'
|
||||
);
|
||||
}
|
||||
foreach ($items as $item) {
|
||||
$main->table('cloud_abuse_alert_event_items')->insert(
|
||||
self::itemValues($eventId, $eventKey, $item, $now)
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
self::assertEventReplay($existing, $eventValues);
|
||||
$eventId = (int) $existing->id;
|
||||
$storedItems = $main->table('cloud_abuse_alert_event_items')
|
||||
->where('event_id', $eventId)->orderBy('item_key')->get();
|
||||
if (count($storedItems) !== count($items)) {
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert event item count conflicts with replay'
|
||||
);
|
||||
}
|
||||
$byKey = [];
|
||||
foreach ($storedItems as $stored) {
|
||||
$byKey[(string) $stored->item_key] = $stored;
|
||||
}
|
||||
foreach ($items as $item) {
|
||||
$expected = self::itemValues(
|
||||
$eventId,
|
||||
$eventKey,
|
||||
$item,
|
||||
$now
|
||||
);
|
||||
$stored = $byKey[$expected['item_key']] ?? null;
|
||||
if ($stored === null) {
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert event item is missing during replay'
|
||||
);
|
||||
}
|
||||
self::assertItemReplay($stored, $expected);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string,mixed>> $transitions
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
private static function canonicalTransitions(array $transitions): array
|
||||
{
|
||||
$canonical = [];
|
||||
foreach ($transitions as $transition) {
|
||||
$type = (string) ($transition['transition_type'] ?? '');
|
||||
$from = (string) ($transition['from_severity'] ?? '');
|
||||
$to = (string) ($transition['to_severity'] ?? '');
|
||||
$reason = (string) ($transition['resolution_reason'] ?? '');
|
||||
$validShape = ($type === 'opened' && $from === 'none'
|
||||
&& in_array($to, ['suspicious', 'high'], true)
|
||||
&& $reason === '')
|
||||
|| ($type === 'escalated' && $from === 'suspicious'
|
||||
&& $to === 'high' && $reason === '')
|
||||
|| ($type === 'resolved'
|
||||
&& in_array($from, ['suspicious', 'high'], true)
|
||||
&& $to === 'none' && $reason === 'evidence_clear');
|
||||
$findingKey = (string) ($transition['finding_key'] ?? '');
|
||||
$direction = (string) ($transition['direction'] ?? '');
|
||||
$family = (string) ($transition['ip_family'] ?? '');
|
||||
$ruleCode = (string) ($transition['rule_code'] ?? '');
|
||||
$generation = (int) ($transition['occurrence_generation'] ?? 0);
|
||||
$revision = (int) ($transition['transition_revision'] ?? 0);
|
||||
$occurredAt = (int) ($transition['occurred_at'] ?? 0);
|
||||
if (!$validShape
|
||||
|| preg_match('/^[a-f0-9]{64}$/D', $findingKey) !== 1
|
||||
|| !in_array($direction, ['inbound', 'outbound'], true)
|
||||
|| !in_array($family, ['ipv4', 'ipv6', 'mixed'], true)
|
||||
|| preg_match('/^[a-z][a-z0-9_]{0,47}$/D',
|
||||
$ruleCode) !== 1
|
||||
|| $generation < 1 || $revision < 1 || $occurredAt < 1
|
||||
|| !self::validEvidence($transition['evidence'] ?? null)) {
|
||||
throw new \LogicException(
|
||||
'Abuse alert transition is invalid'
|
||||
);
|
||||
}
|
||||
$canonical[] = [
|
||||
'finding_key' => $findingKey,
|
||||
'occurrence_generation' => $generation,
|
||||
'transition_revision' => $revision,
|
||||
'rule_code' => $ruleCode,
|
||||
'direction' => $direction,
|
||||
'ip_family' => $family,
|
||||
'transition_type' => $type,
|
||||
'from_severity' => $from,
|
||||
'to_severity' => $to,
|
||||
'evidence' => self::canonicalEvidence(
|
||||
$transition['evidence']
|
||||
),
|
||||
'resolution_reason' => $reason,
|
||||
'occurred_at' => $occurredAt,
|
||||
];
|
||||
}
|
||||
usort($canonical, static function (array $left, array $right): int {
|
||||
return [
|
||||
$left['finding_key'],
|
||||
$left['occurrence_generation'],
|
||||
$left['transition_revision'],
|
||||
$left['transition_type'],
|
||||
] <=> [
|
||||
$right['finding_key'],
|
||||
$right['occurrence_generation'],
|
||||
$right['transition_revision'],
|
||||
$right['transition_type'],
|
||||
];
|
||||
});
|
||||
return $canonical;
|
||||
}
|
||||
|
||||
/** @param list<array<string,mixed>> $items */
|
||||
private static function highestSeverity(array $items): string
|
||||
{
|
||||
$highest = 'suspicious';
|
||||
foreach ($items as $item) {
|
||||
if ($item['from_severity'] === 'high'
|
||||
|| $item['to_severity'] === 'high') {
|
||||
$highest = 'high';
|
||||
break;
|
||||
}
|
||||
}
|
||||
return $highest;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $item
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private static function itemValues(
|
||||
int $eventId,
|
||||
string $eventKey,
|
||||
array $item,
|
||||
int $now
|
||||
): array {
|
||||
$itemKey = hash('sha256', implode("\n", [
|
||||
'cloud-abuse-alert-item-v1',
|
||||
$eventKey,
|
||||
$item['finding_key'],
|
||||
(string) $item['occurrence_generation'],
|
||||
(string) $item['transition_revision'],
|
||||
$item['transition_type'],
|
||||
]));
|
||||
return [
|
||||
'event_id' => $eventId,
|
||||
'item_key' => $itemKey,
|
||||
'finding_key' => $item['finding_key'],
|
||||
'occurrence_generation' => $item['occurrence_generation'],
|
||||
'transition_revision' => $item['transition_revision'],
|
||||
'rule_code' => $item['rule_code'],
|
||||
'direction' => $item['direction'],
|
||||
'ip_family' => $item['ip_family'],
|
||||
'transition_type' => $item['transition_type'],
|
||||
'from_severity' => $item['from_severity'],
|
||||
'to_severity' => $item['to_severity'],
|
||||
'evidence_json' => self::json($item['evidence']),
|
||||
'resolution_reason' => $item['resolution_reason'],
|
||||
'occurred_at' => $item['occurred_at'],
|
||||
'created_at' => $now,
|
||||
];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $expected */
|
||||
private static function assertEventReplay(
|
||||
object $stored,
|
||||
array $expected
|
||||
): void {
|
||||
foreach ([
|
||||
'event_key', 'sample_key', 'instance_id', 'user_id', 'host_id',
|
||||
'bucket_start', 'rule_version', 'policy_revision', 'policy_hash',
|
||||
'transition_digest', 'transition_count', 'highest_severity',
|
||||
] as $column) {
|
||||
if ((string) $stored->{$column} !== (string) $expected[$column]) {
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert event conflicts with replay'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $expected */
|
||||
private static function assertItemReplay(
|
||||
object $stored,
|
||||
array $expected
|
||||
): void {
|
||||
foreach ([
|
||||
'event_id', 'item_key', 'finding_key', 'occurrence_generation',
|
||||
'transition_revision', 'rule_code', 'direction', 'ip_family',
|
||||
'transition_type', 'from_severity', 'to_severity',
|
||||
'evidence_json', 'resolution_reason', 'occurred_at',
|
||||
] as $column) {
|
||||
if ((string) $stored->{$column} !== (string) $expected[$column]) {
|
||||
throw new \RuntimeException(
|
||||
'Abuse alert event item conflicts with replay'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static function validEvidence(mixed $value): bool
|
||||
{
|
||||
if (!is_array($value)) {
|
||||
return false;
|
||||
}
|
||||
foreach ($value as $key => $item) {
|
||||
if (!is_string($key)
|
||||
|| preg_match('/^[a-z][a-z0-9_]{0,63}$/D', $key) !== 1
|
||||
|| !is_int($item) || $item < 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @param array<string,int> $value @return array<string,int> */
|
||||
private static function canonicalEvidence(array $value): array
|
||||
{
|
||||
ksort($value, SORT_STRING);
|
||||
return $value;
|
||||
}
|
||||
|
||||
private static function json(mixed $value): string
|
||||
{
|
||||
return json_encode(
|
||||
$value,
|
||||
JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
|
||||
| JSON_PRESERVE_ZERO_FRACTION | JSON_THROW_ON_ERROR
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,198 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Cloud\CloudAbuseAlertEventCoordinator;
|
||||
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();
|
||||
$main = $capsule->connection('default');
|
||||
$main->statement('PRAGMA foreign_keys = ON');
|
||||
$schema = $capsule->schema('default');
|
||||
$schema->create('cloud_instances', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
});
|
||||
$schema->create('cloud_abuse_alert_events',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('event_key')->unique();
|
||||
$table->string('sample_key')->unique();
|
||||
$table->integer('instance_id');
|
||||
$table->integer('user_id');
|
||||
$table->integer('host_id');
|
||||
$table->integer('bucket_start');
|
||||
$table->integer('rule_version');
|
||||
$table->integer('policy_revision');
|
||||
$table->string('policy_hash');
|
||||
$table->string('transition_digest');
|
||||
$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('item_key')->unique();
|
||||
$table->string('finding_key');
|
||||
$table->integer('occurrence_generation');
|
||||
$table->integer('transition_revision');
|
||||
$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->string('resolution_reason')->default('');
|
||||
$table->integer('occurred_at');
|
||||
$table->integer('created_at');
|
||||
$table->foreign('event_id')->references('id')
|
||||
->on('cloud_abuse_alert_events')->cascadeOnDelete();
|
||||
});
|
||||
|
||||
$main->table('cloud_instances')->insert(['id' => 41]);
|
||||
$policyHash = str_repeat('a', 64);
|
||||
$claim = [
|
||||
'sample_key' => str_repeat('b', 64),
|
||||
'instance_id' => 41,
|
||||
'user_id' => 9,
|
||||
'host_id' => 3,
|
||||
'bucket_start' => 120,
|
||||
'rule_version' => 1,
|
||||
'policy_revision' => 7,
|
||||
'policy_hash' => $policyHash,
|
||||
];
|
||||
$transitions = [[
|
||||
'finding_key' => str_repeat('c', 64),
|
||||
'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' => 'suspicious',
|
||||
'evidence' => ['tcp_syn_flows' => 900, 'unique_remote_ips' => 140],
|
||||
'resolution_reason' => '',
|
||||
'occurred_at' => 120,
|
||||
], [
|
||||
'finding_key' => str_repeat('d', 64),
|
||||
'occurrence_generation' => 2,
|
||||
'transition_revision' => 4,
|
||||
'rule_code' => 'inbound_udp_flood',
|
||||
'direction' => 'inbound',
|
||||
'ip_family' => 'ipv6',
|
||||
'transition_type' => 'resolved',
|
||||
'from_severity' => 'high',
|
||||
'to_severity' => 'none',
|
||||
'evidence' => ['udp_active_flows' => 0, 'udp_new_flows' => 0],
|
||||
'resolution_reason' => 'evidence_clear',
|
||||
'occurred_at' => 120,
|
||||
]];
|
||||
|
||||
$coordinator = new CloudAbuseAlertEventCoordinator();
|
||||
$main->transaction(static function () use (
|
||||
$coordinator,
|
||||
$main,
|
||||
$claim,
|
||||
$transitions
|
||||
): void {
|
||||
$coordinator->record($main, $claim, array_reverse($transitions), 1000);
|
||||
});
|
||||
$event = $main->table('cloud_abuse_alert_events')->first();
|
||||
$items = $main->table('cloud_abuse_alert_event_items')
|
||||
->orderBy('finding_key')->get();
|
||||
$assert($event !== null
|
||||
&& (int) $event->transition_count === 2
|
||||
&& $event->highest_severity === 'high'
|
||||
&& count($items) === 2
|
||||
&& $items[0]->finding_key === str_repeat('c', 64)
|
||||
&& $items[0]->evidence_json
|
||||
=== '{"tcp_syn_flows":900,"unique_remote_ips":140}',
|
||||
'Multiple transitions were not frozen in one canonical event batch.');
|
||||
|
||||
$coordinator->record($main, $claim, $transitions, 1001);
|
||||
$assert($main->table('cloud_abuse_alert_events')->count() === 1
|
||||
&& $main->table('cloud_abuse_alert_event_items')->count() === 2,
|
||||
'An identical event replay duplicated the durable ledger.');
|
||||
|
||||
$invalidEvidence = $transitions;
|
||||
$invalidEvidence[0]['evidence'] = ['remote_ip' => '203.0.113.4'];
|
||||
$threw = false;
|
||||
try {
|
||||
$coordinator->record($main, $claim + [
|
||||
'sample_key' => str_repeat('e', 64),
|
||||
], $invalidEvidence, 1002);
|
||||
} catch (LogicException) {
|
||||
$threw = true;
|
||||
}
|
||||
$assert($threw && $main->table('cloud_abuse_alert_events')->count() === 1,
|
||||
'Non-aggregate evidence was accepted by the alert ledger.');
|
||||
|
||||
$wrongBucket = $transitions;
|
||||
$wrongBucket[0]['occurred_at'] = 60;
|
||||
$threw = false;
|
||||
try {
|
||||
$coordinator->record($main, $claim + [
|
||||
'sample_key' => str_repeat('f', 64),
|
||||
], $wrongBucket, 1003);
|
||||
} catch (LogicException) {
|
||||
$threw = true;
|
||||
}
|
||||
$assert($threw, 'A transition from another sample bucket was accepted.');
|
||||
|
||||
$rollbackClaim = $claim;
|
||||
$rollbackClaim['sample_key'] = str_repeat('1', 64);
|
||||
$rolledBack = false;
|
||||
try {
|
||||
$main->transaction(static function () use (
|
||||
$coordinator,
|
||||
$main,
|
||||
$rollbackClaim,
|
||||
$transitions
|
||||
): void {
|
||||
$coordinator->record(
|
||||
$main,
|
||||
$rollbackClaim,
|
||||
$transitions,
|
||||
1004
|
||||
);
|
||||
throw new RuntimeException('force rollback');
|
||||
});
|
||||
} catch (RuntimeException $error) {
|
||||
$rolledBack = $error->getMessage() === 'force rollback';
|
||||
}
|
||||
$assert($rolledBack
|
||||
&& !$main->table('cloud_abuse_alert_events')
|
||||
->where('sample_key', $rollbackClaim['sample_key'])->exists(),
|
||||
'A rolled-back alert event left a partial durable ledger.');
|
||||
|
||||
$main->table('cloud_instances')->where('id', 41)->delete();
|
||||
$assert($main->table('cloud_abuse_alert_events')->count() === 1
|
||||
&& $main->table('cloud_abuse_alert_event_items')->count() === 2,
|
||||
'Deleting an instance erased an alert before delivery finality exists.');
|
||||
$main->table('cloud_abuse_alert_events')->where('id', $event->id)->delete();
|
||||
$assert($main->table('cloud_abuse_alert_event_items')->count() === 0,
|
||||
'Deleting an alert event did not cascade its immutable items.');
|
||||
$source = file_get_contents(dirname(__DIR__)
|
||||
. '/app/Services/Cloud/CloudAbuseAlertEventCoordinator.php');
|
||||
$assert(is_string($source)
|
||||
&& !str_contains($source, 'Telegram')
|
||||
&& !str_contains($source, 'TicketTelegram')
|
||||
&& !str_contains($source, 'Http::'),
|
||||
'Phase-6 event recording gained an external delivery dependency.');
|
||||
|
||||
echo "Cloud abuse alert event coordinator tests passed.\n";
|
||||
Loading…
Reference in New Issue