feat(abuse): persist alert transition ledger

go
codex 2 weeks ago
parent bb29c6f2f7
commit 0a8a318291

@ -160,7 +160,11 @@ libvirt 的持久 pool 定义就是 Agent 后续使用的映射,不另写存
公网网络接入在宿主机的“网络接入”中按资源池线路独立配置,可使用 `bridge:br0`、其他 Linux 网桥或 `network:default` 这样的 libvirt network。名称以字母或数字开头,后续只能包含字母、数字、点、下划线和短横线,bridge 名称为 1~15 字符,libvirt network 名称为 1~64 字符。宿主机上的公网网桥或 libvirt network 必须由运维预先准备。Agent 只发现、验证和使用现有公网网络,不创建公网网桥、不启动 libvirt network,也不修改公网地址、上游网关或挂载。`cloud_hosts.default_network` 仅保留为兼容展示值,不参与 Agent 就绪、调度、恢复、迁移或换 IP 决策;真正的运行时权威是资源池线路、当前 Agent 代次已验证的网络接入,以及绑定该接入的公网地址池。VPC 使用下述独立的 Agent 受管 bridge 和 L3 路由,不改变这一公网边界。
当前完整 schema 版本为 `go-agent-wss-v44-abuse-policy-projection`。从 v43 升级时,必须先停止滥用观测与投影 worker,再用经过审核的一次性迁移把当时生效的 `rule_version`、`policy_revision` 和 `policy_hash` 冻结到既有 outbox、baseline、instance state、finding 与 receipt。所有既有 `cloud_abuse_findings.finding_key` 必须在恢复 worker 前按 `SHA-256(instance_id + "\n" + rule_version + "\n" + policy_hash + "\n" + rule_code + "\n" + ip_family + "\n" + direction)` 重新计算;完成回填、重算和约束核对后才能启动新版进程。运行时代码不兼容旧 finding key,也不会用旧 key 查找或合并 finding;省略重算会让同一规则在新 policy 身份下生成另一条记录。
当前完整 schema 版本为 `go-agent-wss-v45-abuse-alert-events`。从 v44 升级时,必须先停止滥用观测与投影 worker,为既有 finding 回填 `occurrence_generation = 1` 与 `transition_revision = 1`,再创建 `cloud_abuse_alert_events` 和 `cloud_abuse_alert_event_items`。历史 finding 不反向合成事件;事件只从升级后主库事务内真实发生的 `opened`、`escalated` 和 `evidence_clear` 解决转移产生。完成列、约束、索引和外键核对后才能恢复 worker。
事件 header 与 projection receipt 在同一个主库事务中写入,且事件先于 receipt;同一实例同一采样桶的多规则、双协议族转移合并为一个 header 和多个 item。`continued` 不产生事件,`policy_replaced` 与 `owner_changed` 只关闭 finding,不能伪造“恢复”事件。item 已冻结当时的聚合 evidence、规则身份和 finding 代次,后续投递不得回读会变化的 finding。v45 尚未加入 Telegram 投递状态,因此这些事件暂不进入 180 天清理;待投递账本具有明确终态后再启用保留策略。删除用户时按事件冻结的 `user_id` 显式删除 header,item 由外键级联,避免实例转交后遗留原租户数据。
`occurrence_generation` 与 `transition_revision` 只描述当前仍保留的 finding 生命周期,不是跨 retention 的全局幂等键;旧 finding 被清理后,同一规则以后允许从 `1/1` 重新建立。未来投递只能以不可变的 `event_id` / `item_key` 建立幂等边界,不能使用 generation/revision 猜测是否已经外发。账户删除与投影都必须遵循“先锁 user、再锁 instance”的顺序;正式部署还应在真实 MySQL 双连接下验收删除和投影并发,SQLite 行为测试不等价于 InnoDB 行锁门禁。
自动备份订阅通过独立的延期字段保留原逻辑执行时隙;只有已确认未应用且可安全重试的救援或磁盘切换竞态,才会退休空白制品并以递增的 `schedule_attempt` 建立新代次。每个资源预留的当前公网权威只来自 `cloud_resource_reservation_ips.active_claim = 1` 的一组 IPv4+IPv6 精确声明;两族允许具有各自的 generation 和 operation ID,但必须绑定同一资源预留和网络接入,并各自与具体 IP、地址池、宿主机、实例状态双向一致。`cloud_resource_reservations` 中旧的单地址列只保留审计形态,不参与当前地址读取、释放或管理员投影。释放时历史声明保留并把 `active_claim` 置空,具体 IP 同时清空 claim、operation、reservation 和 instance 归属。普通换 IP、独立恢复和维护迁移分别只允许 transition ledger、restore attempt 与 migration source debt 所有的完整双栈流程;旧 `CloudPlacementService` 单地址恢复、旧换 IP writer,以及缺少或损坏冻结身份的任务仍会在派发 CAS 前拒绝,不能绕过新账本。
@ -262,9 +266,9 @@ systemctl enable --now virt-cloud-worker.service \
`virt-cloud-storage-health-worker.service` 与副本复制 worker 彻底隔离:它每次只领取一个到期后端,在数据库事务外执行最长 15 秒的 `HeadBucket`,并且只能按领取时冻结的配置版本结算。成功只恢复健康证据,不会把人工设置的 `read_only`、`draining` 或 `disabled` 改回 `active`;失败使正在 `active` 的后端转为 `read_only`、按 60 秒到 1 小时退避,新写入随即停止选择它。这个 worker 不执行 PUT、COPY、DELETE 或 Abort,也不把凭据写入心跳、日志或命令行。
`virt-cloud-abuse-monitor.service` 是独立、只读宿主机的网络滥用观测进程。Agent 仅发布每分钟公网接口与 conntrack 的有界聚合计数,不采集报文正文、远端 IP 列表或远端端口列表;PHP 将样本、投影意图与宿主机游标原子写入日志库,再用幂等 receipt 投影管理员只读状态。该服务不进入 `cloud_jobs`,不会自动断网、限速、修改防火墙、实例生命周期或账单。采集缺口、Agent generation 变化及不完整样本均按异常证据显示,不会当作正常零值参与判定。正式启用前需确认宿主机 conntrack 可读、Agent 网络观测能力可用,并同时检查 `abuse_monitor` 心跳与后台采集健康状态。
`virt-cloud-abuse-monitor.service` 是独立、只读宿主机的网络滥用观测进程。Agent 仅发布每分钟公网接口与 conntrack 的有界聚合计数,不采集报文正文、远端 IP 列表或远端端口列表;PHP 将样本、投影意图与宿主机游标原子写入日志库,再用幂等 receipt 投影管理员只读状态和不可变转移事件。该服务不进入 `cloud_jobs`,不会自动断网、限速、修改防火墙、实例生命周期或账单。当前事件账本也不发送 Telegram;外发决策和投递效果将在独立阶段加入,不能从事件存在本身推断已经通知。采集缺口、Agent generation 变化及不完整样本均按异常证据显示,不会当作正常零值参与判定。正式启用前需确认宿主机 conntrack 可读、Agent 网络观测能力可用,并同时检查 `abuse_monitor` 心跳与后台采集健康状态。
实例补偿的批次、明细和收件人账本已包含在当前 v42 完整 schema 中。`php xcat cloudInit` 只能为全新空数据库创建和验证当前全部结构,不能冒充既有数据库的增量升级。既有安装发布前必须备份数据库,使用经过审核的一次性迁移落地完整 v42 结构并核对 schema 指纹;升级成功后删除迁移脚本。然后按本节重启普通、通知及对象存储 workers。补偿本身不调用 Agent/Gateway,因此仅补偿功能不要求更新或重新编译宿主机 Agent 和面板 Gateway。完整语义见 [`SERVICE_COMPENSATION.md`](SERVICE_COMPENSATION.md)。
实例补偿的批次、明细和收件人账本已包含在当前完整 schema 中。`php xcat cloudInit` 只能为全新空数据库创建和验证当前全部结构,不能冒充既有数据库的增量升级。既有安装发布前必须备份数据库,使用经过审核的一次性迁移落地当前完整结构并核对 schema 指纹;升级成功后删除迁移脚本。然后按本节重启普通、通知及对象存储 workers。补偿本身不调用 Agent/Gateway,因此仅补偿功能不要求更新或重新编译宿主机 Agent 和面板 Gateway。完整语义见 [`SERVICE_COMPENSATION.md`](SERVICE_COMPENSATION.md)。
共享流量池必须严格按 `disabled -> shadow -> enforced` 上线,并在强制执行前通过全部账本、采样和网络策略门禁。现有数据库不能使用 `php xcat cloudInit` 冒充增量升级,旧服务周期也不能通过 SQL 回填到流量池;完整步骤、验收项和故障处置见 [`TRAFFIC_POOL_ROLLOUT.md`](TRAFFIC_POOL_ROLLOUT.md)。

@ -47,7 +47,7 @@
## 部署
全新数据库必须由当前 `CloudSetup` 创建并验证 `go-agent-wss-v44-abuse-policy-projection` 完整 schema;其中补偿模块包括:
全新数据库必须由当前 `CloudSetup` 创建并验证 `go-agent-wss-v45-abuse-alert-events` 完整 schema;其中补偿模块包括:
- `cloud_service_compensations`;
- `cloud_service_compensation_items`;

@ -8,7 +8,7 @@ use App\Services\Config;
/** Initializes only the clean-break PHP business and Agent log schemas. */
final class CloudSetup
{
private const SCHEMA_VERSION = 'go-agent-wss-v44-abuse-policy-projection';
private const SCHEMA_VERSION = 'go-agent-wss-v45-abuse-alert-events';
/** Tables installed by ss.sql before cloudInit and owned by this schema. */
private const PREINSTALLED_MAIN_TABLES = [
'ui_copy_locales', 'ui_copy_entries', 'ui_copy_drafts',
@ -67,6 +67,7 @@ final class CloudSetup
'cloud_service_compensation_recipients',
'cloud_abuse_policy_revisions', 'cloud_abuse_policy_rules',
'cloud_abuse_instance_states', 'cloud_abuse_findings',
'cloud_abuse_alert_events', 'cloud_abuse_alert_event_items',
'cloud_abuse_projection_receipts',
'cloud_jobs', 'cloud_agent_completion_events',
'cloud_ssh_keys',
@ -611,10 +612,24 @@ final class CloudSetup
'rule_code', 'rule_version', 'policy_revision', 'policy_hash',
'direction', 'ip_family',
'severity', 'state', 'first_seen_at', 'last_seen_at',
'consecutive_windows', 'evidence_json', 'resolved_at',
'consecutive_windows', 'occurrence_generation',
'transition_revision', 'evidence_json', 'resolved_at',
'resolution_reason',
'created_at', 'updated_at',
],
'cloud_abuse_alert_events' => [
'id', 'event_key', 'sample_key', 'instance_id', 'user_id',
'host_id', 'bucket_start', 'rule_version', 'policy_revision',
'policy_hash', 'transition_digest', 'transition_count',
'highest_severity', 'created_at',
],
'cloud_abuse_alert_event_items' => [
'id', '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', 'created_at',
],
'cloud_abuse_projection_receipts' => [
'sample_key', 'instance_id', 'rule_version', 'policy_revision',
'policy_hash', 'bucket_start', 'projected_at',
@ -809,6 +824,16 @@ final class CloudSetup
'chk_cloud_abuse_finding_window',
'chk_cloud_abuse_finding_resolution',
],
'cloud_abuse_alert_events' => [
'chk_cloud_abuse_alert_event_identity',
'chk_cloud_abuse_alert_event_policy',
'chk_cloud_abuse_alert_event_shape',
],
'cloud_abuse_alert_event_items' => [
'chk_cloud_abuse_alert_item_identity',
'chk_cloud_abuse_alert_item_scope',
'chk_cloud_abuse_alert_item_transition',
],
'cloud_abuse_projection_receipts' => [
'chk_cloud_abuse_projection_key',
'chk_cloud_abuse_projection_policy',
@ -1121,6 +1146,20 @@ final class CloudSetup
'cloud_abuse_finding_host', 'cloud_abuse_finding_rule',
'cloud_abuse_finding_retention',
],
'cloud_abuse_alert_events' => [
'PRIMARY', 'cloud_abuse_alert_event_key',
'cloud_abuse_alert_event_sample',
'cloud_abuse_alert_event_instance',
'cloud_abuse_alert_event_owner',
'cloud_abuse_alert_event_host',
'cloud_abuse_alert_event_retention',
],
'cloud_abuse_alert_event_items' => [
'PRIMARY', 'cloud_abuse_alert_item_key',
'cloud_abuse_alert_item_finding_once',
'cloud_abuse_alert_item_event',
'cloud_abuse_alert_item_finding',
],
'cloud_abuse_projection_receipts' => [
'PRIMARY', 'cloud_abuse_projection_instance',
'cloud_abuse_projection_retention',
@ -1735,6 +1774,34 @@ final class CloudSetup
],
],
],
'cloud_abuse_alert_events' => [
'cloud_abuse_alert_event_key' => [
'non_unique' => 0,
'columns' => ['event_key'],
],
'cloud_abuse_alert_event_sample' => [
'non_unique' => 0,
'columns' => ['sample_key'],
],
'cloud_abuse_alert_event_retention' => [
'non_unique' => 1,
'columns' => ['created_at', 'id'],
],
],
'cloud_abuse_alert_event_items' => [
'cloud_abuse_alert_item_key' => [
'non_unique' => 0,
'columns' => ['item_key'],
],
'cloud_abuse_alert_item_finding_once' => [
'non_unique' => 0,
'columns' => ['event_id', 'finding_key'],
],
'cloud_abuse_alert_item_event' => [
'non_unique' => 1,
'columns' => ['event_id', 'id'],
],
],
'cloud_abuse_projection_receipts' => [
'PRIMARY' => [
'non_unique' => 0,
@ -1858,6 +1925,9 @@ final class CloudSetup
'cloud_abuse_findings' => [
'fk_cloud_abuse_finding_instance',
],
'cloud_abuse_alert_event_items' => [
'fk_cloud_abuse_alert_item_event',
],
'cloud_abuse_projection_receipts' => [
'fk_cloud_abuse_projection_instance',
],

@ -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
);
}
}

@ -24,6 +24,8 @@ final class CloudAbuseProjectionService
/** @var \Closure(int,string):CloudAbusePolicySnapshot */
private readonly \Closure $policySnapshot;
private readonly CloudAbuseAlertEventCoordinator $alertEvents;
/** @var list<string> */
private array $errors = [];
@ -34,7 +36,8 @@ final class CloudAbuseProjectionService
public function __construct(
?callable $clock = null,
?callable $afterMainCommit = null,
?callable $policySnapshot = null
?callable $policySnapshot = null,
?CloudAbuseAlertEventCoordinator $alertEvents = null
) {
$this->clock = \Closure::fromCallable(
$clock ?? static fn (): int => time()
@ -45,6 +48,8 @@ final class CloudAbuseProjectionService
?? static fn (int $revision, string $hash):
CloudAbusePolicySnapshot => (new CloudAbusePolicyService())
->snapshotByIdentity($revision, $hash));
$this->alertEvents = $alertEvents
?? new CloudAbuseAlertEventCoordinator();
}
/** Project at most one ordered sample. */
@ -671,6 +676,17 @@ final class CloudAbuseProjectionService
$policyChanged,
$now
): array {
// Account deletion locks the tenant row before deleting any
// instance-owned data. Take the same lock first so a projection
// cannot insert a durable event after deletion has swept that
// user's alert rows.
$owner = $main->table('user')
->where('id', $claim['user_id'])
->lockForUpdate()->first(['id']);
if ($owner === null) {
return ['state' => 'discarded',
'reason' => 'instance_owner_missing'];
}
$instance = $main->table('cloud_instances')
->where('id', $claim['instance_id'])
->lockForUpdate()->first();
@ -781,8 +797,9 @@ final class CloudAbuseProjectionService
->where('instance_id', $claim['instance_id'])
->update($stateValues);
}
$transitions = [];
if ($healthy) {
$this->applyFindings(
$transitions = $this->applyFindings(
$main,
$claim,
(int) $instance->host_id,
@ -790,6 +807,14 @@ final class CloudAbuseProjectionService
$now
);
}
$eventClaim = $claim;
$eventClaim['host_id'] = (int) $instance->host_id;
$this->alertEvents->record(
$main,
$eventClaim,
$transitions,
$now
);
$main->table('cloud_abuse_projection_receipts')->insert([
'sample_key' => $claim['sample_key'],
'instance_id' => $claim['instance_id'],
@ -855,6 +880,8 @@ final class CloudAbuseProjectionService
'state' => 'resolved',
'resolved_at' => $resolvedAt,
'resolution_reason' => 'policy_replaced',
'transition_revision' =>
(int) $row->transition_revision + 1,
'updated_at' => $now,
]);
if ($updated !== 1) {
@ -890,6 +917,8 @@ final class CloudAbuseProjectionService
'state' => 'resolved',
'resolved_at' => $resolvedAt,
'resolution_reason' => 'owner_changed',
'transition_revision' =>
(int) $finding->transition_revision + 1,
'updated_at' => $now,
]);
if ($updated !== 1) {
@ -944,6 +973,7 @@ final class CloudAbuseProjectionService
/**
* @param array<string,mixed> $claim
* @param array<int,array<string,mixed>> $findings
* @return list<array<string,mixed>>
*/
private function applyFindings(
object $main,
@ -951,7 +981,8 @@ final class CloudAbuseProjectionService
int $currentHostId,
array $findings,
int $now
): void {
): array {
$transitions = [];
foreach ($findings as $finding) {
$key = hash('sha256', implode("\n", [
$claim['instance_id'],
@ -964,6 +995,18 @@ final class CloudAbuseProjectionService
$row = $main->table('cloud_abuse_findings')
->where('finding_key', $key)->lockForUpdate()->first();
if (($finding['active'] ?? false) === true) {
$opened = $row === null
|| (string) $row->state === 'resolved';
$escalated = $row !== null
&& (string) $row->state === 'open'
&& (string) $row->severity === 'suspicious'
&& (string) $finding['severity'] === 'high';
$generation = $row === null ? 1
: (int) $row->occurrence_generation
+ ($opened ? 1 : 0);
$revision = $row === null ? 1
: (int) $row->transition_revision
+ (($opened || $escalated) ? 1 : 0);
$values = [
'instance_id' => $claim['instance_id'],
'user_id' => $claim['user_id'],
@ -985,6 +1028,8 @@ final class CloudAbuseProjectionService
1,
(int) $finding['consecutive_windows']
),
'occurrence_generation' => $generation,
'transition_revision' => $revision,
'evidence_json' => self::json(
(array) $finding['evidence']
),
@ -997,21 +1042,94 @@ final class CloudAbuseProjectionService
$values['created_at'] = $now;
$main->table('cloud_abuse_findings')->insert($values);
} else {
$main->table('cloud_abuse_findings')
->where('finding_key', $key)->update($values);
$updated = $main->table('cloud_abuse_findings')
->where('finding_key', $key)
->where('transition_revision',
(int) $row->transition_revision)
->update($values);
if ($updated !== 1) {
throw new \RuntimeException(
'Abuse finding transition CAS failed'
);
}
}
if ($opened || $escalated) {
$transitions[] = self::findingTransition(
$key,
$finding,
$generation,
$revision,
$opened ? 'opened' : 'escalated',
$opened ? 'none' : 'suspicious',
(string) $finding['severity'],
'',
$claim['bucket_start']
);
}
} elseif (($finding['transition'] ?? '') === 'resolved'
&& $row !== null && (string) $row->state === 'open') {
$main->table('cloud_abuse_findings')
$revision = (int) $row->transition_revision + 1;
$updated = $main->table('cloud_abuse_findings')
->where('finding_key', $key)
->where('state', 'open')->update([
->where('state', 'open')
->where('transition_revision',
(int) $row->transition_revision)->update([
'state' => 'resolved',
'resolved_at' => $claim['bucket_start'],
'resolution_reason' => 'evidence_clear',
'transition_revision' => $revision,
'updated_at' => $now,
]);
if ($updated !== 1) {
throw new \RuntimeException(
'Abuse finding resolution CAS failed'
);
}
$transitions[] = self::findingTransition(
$key,
$finding,
(int) $row->occurrence_generation,
$revision,
'resolved',
(string) $row->severity,
'none',
'evidence_clear',
$claim['bucket_start']
);
}
}
return $transitions;
}
/**
* @param array<string,mixed> $finding
* @return array<string,mixed>
*/
private static function findingTransition(
string $findingKey,
array $finding,
int $generation,
int $revision,
string $type,
string $fromSeverity,
string $toSeverity,
string $resolutionReason,
int $occurredAt
): array {
return [
'finding_key' => $findingKey,
'occurrence_generation' => $generation,
'transition_revision' => $revision,
'rule_code' => (string) $finding['rule_code'],
'direction' => (string) $finding['direction'],
'ip_family' => (string) $finding['ip_family'],
'transition_type' => $type,
'from_severity' => $fromSeverity,
'to_severity' => $toSeverity,
'evidence' => (array) ($finding['evidence'] ?? []),
'resolution_reason' => $resolutionReason,
'occurred_at' => $occurredAt,
];
}
/** @param array<string,mixed> $claim @param array<string,mixed> $baseline */

@ -34,6 +34,12 @@ class UserDataDeletionService
['cloud_backup_period_entitlements', 'user_id'],
['cloud_instance_network_policy_states', 'user_id'],
['cloud_instance_network_restrictions', 'user_id'],
// Alert items cascade from the immutable event header. Keep this
// explicit owner reference because an event may predate an instance
// ownership transfer and must be erased with its original tenant.
['cloud_abuse_alert_events', 'user_id'],
['cloud_abuse_findings', 'user_id'],
['cloud_abuse_instance_states', 'user_id'],
['cloud_traffic_instance_cursors', 'user_id'],
['cloud_traffic_ledger_events', 'user_id'],
['cloud_traffic_entitlements', 'user_id'],

@ -3030,6 +3030,8 @@ CREATE TABLE cloud_abuse_findings (
first_seen_at BIGINT UNSIGNED NOT NULL,
last_seen_at BIGINT UNSIGNED NOT NULL,
consecutive_windows INT UNSIGNED NOT NULL DEFAULT 1,
occurrence_generation INT UNSIGNED NOT NULL DEFAULT 1,
transition_revision INT UNSIGNED NOT NULL DEFAULT 1,
evidence_json JSON NOT NULL,
resolved_at BIGINT UNSIGNED DEFAULT NULL,
resolution_reason VARCHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '',
@ -3068,7 +3070,10 @@ CREATE TABLE cloud_abuse_findings (
AND policy_hash REGEXP '^[a-f0-9]{64}$'
),
CONSTRAINT chk_cloud_abuse_finding_window CHECK (
first_seen_at <= last_seen_at AND consecutive_windows >= 1
first_seen_at <= last_seen_at
AND consecutive_windows >= 1
AND occurrence_generation >= 1
AND transition_revision >= 1
),
CONSTRAINT chk_cloud_abuse_finding_resolution CHECK (
(state = 'open' AND resolved_at IS NULL AND resolution_reason = '')
@ -3082,6 +3087,101 @@ CREATE TABLE cloud_abuse_findings (
REFERENCES cloud_instances (id) ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Immutable alert facts produced from finding state transitions. One header
-- represents one instance/sample bucket; multiple rule/family transitions are
-- stored as items. This phase deliberately records no Telegram delivery state.
CREATE TABLE cloud_abuse_alert_events (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
event_key CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
sample_key CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
instance_id BIGINT UNSIGNED NOT NULL,
user_id BIGINT UNSIGNED NOT NULL,
host_id BIGINT UNSIGNED NOT NULL,
bucket_start BIGINT UNSIGNED NOT NULL,
rule_version INT UNSIGNED NOT NULL,
policy_revision BIGINT UNSIGNED NOT NULL,
policy_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
transition_digest CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
transition_count INT UNSIGNED NOT NULL,
highest_severity VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
created_at BIGINT UNSIGNED NOT NULL,
UNIQUE KEY cloud_abuse_alert_event_key (event_key),
UNIQUE KEY cloud_abuse_alert_event_sample (sample_key),
KEY cloud_abuse_alert_event_instance (
instance_id, bucket_start, id
),
KEY cloud_abuse_alert_event_owner (user_id, created_at, id),
KEY cloud_abuse_alert_event_host (host_id, created_at, id),
KEY cloud_abuse_alert_event_retention (created_at, id),
CONSTRAINT chk_cloud_abuse_alert_event_identity CHECK (
event_key REGEXP '^[a-f0-9]{64}$'
AND sample_key REGEXP '^[a-f0-9]{64}$'
AND transition_digest REGEXP '^[a-f0-9]{64}$'
),
CONSTRAINT chk_cloud_abuse_alert_event_policy CHECK (
rule_version > 0
AND policy_revision > 0
AND policy_hash REGEXP '^[a-f0-9]{64}$'
),
CONSTRAINT chk_cloud_abuse_alert_event_shape CHECK (
bucket_start % 60 = 0
AND transition_count > 0
AND highest_severity IN ('suspicious','high')
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE cloud_abuse_alert_event_items (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
event_id BIGINT UNSIGNED NOT NULL,
item_key CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
finding_key CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
occurrence_generation INT UNSIGNED NOT NULL,
transition_revision INT UNSIGNED NOT NULL,
rule_code VARCHAR(48) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
direction VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
ip_family VARCHAR(8) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
transition_type VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
from_severity VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
to_severity VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
evidence_json JSON NOT NULL,
resolution_reason VARCHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '',
occurred_at BIGINT UNSIGNED NOT NULL,
created_at BIGINT UNSIGNED NOT NULL,
UNIQUE KEY cloud_abuse_alert_item_key (item_key),
UNIQUE KEY cloud_abuse_alert_item_finding_once (event_id, finding_key),
KEY cloud_abuse_alert_item_event (event_id, id),
KEY cloud_abuse_alert_item_finding (
finding_key, occurrence_generation, transition_revision
),
CONSTRAINT chk_cloud_abuse_alert_item_identity CHECK (
item_key REGEXP '^[a-f0-9]{64}$'
AND finding_key REGEXP '^[a-f0-9]{64}$'
AND occurrence_generation >= 1
AND transition_revision >= 1
),
CONSTRAINT chk_cloud_abuse_alert_item_scope CHECK (
direction IN ('inbound','outbound')
AND ip_family IN ('ipv4','ipv6','mixed')
),
CONSTRAINT chk_cloud_abuse_alert_item_transition CHECK (
(transition_type = 'opened'
AND from_severity = 'none'
AND to_severity IN ('suspicious','high')
AND resolution_reason = '')
OR (transition_type = 'escalated'
AND from_severity = 'suspicious'
AND to_severity = 'high'
AND resolution_reason = '')
OR (transition_type = 'resolved'
AND from_severity IN ('suspicious','high')
AND to_severity = 'none'
AND resolution_reason = 'evidence_clear')
),
CONSTRAINT fk_cloud_abuse_alert_item_event FOREIGN KEY (event_id)
REFERENCES cloud_abuse_alert_events (id)
ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Main-database idempotency receipt for one log-database outbox projection.
-- The state row's last_projection_key/last_bucket_start pair is the ordering
-- fence; a replay may observe this receipt and safely mark the outbox done.

@ -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";

@ -30,6 +30,7 @@ $setup = $read('app/Command/CloudSetup.php');
$traffic = $read('app/Services/Cloud/CloudTrafficService.php');
$lifecycle = $read('app/Services/Cloud/CloudLifecycleService.php');
$deletion = $read('app/Services/UserDataDeletionService.php');
$projection = $read('app/Services/Cloud/CloudAbuseProjectionService.php');
$mainTables = [
'cloud_abuse_instance_states' => [
@ -45,9 +46,23 @@ $mainTables = [
'rule_code', 'rule_version', 'policy_revision', 'policy_hash',
'direction', 'ip_family', 'severity',
'state', 'first_seen_at', 'last_seen_at', 'consecutive_windows',
'evidence_json', 'resolved_at', 'resolution_reason',
'occurrence_generation', 'transition_revision', 'evidence_json',
'resolved_at', 'resolution_reason',
'created_at', 'updated_at',
],
'cloud_abuse_alert_events' => [
'id', 'event_key', 'sample_key', 'instance_id', 'user_id',
'host_id', 'bucket_start', 'rule_version', 'policy_revision',
'policy_hash', 'transition_digest', 'transition_count',
'highest_severity', 'created_at',
],
'cloud_abuse_alert_event_items' => [
'id', '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', 'created_at',
],
'cloud_abuse_projection_receipts' => [
'sample_key', 'instance_id', 'rule_version', 'policy_revision',
'policy_hash', 'bucket_start', 'projected_at',
@ -120,6 +135,24 @@ foreach ([
&& str_contains($setup, "'" . $index . "'"),
'Missing abuse state index: ' . $index);
}
foreach ([
'cloud_abuse_alert_event_key', 'cloud_abuse_alert_event_sample',
'cloud_abuse_alert_event_instance', 'cloud_abuse_alert_event_owner',
'cloud_abuse_alert_event_host', 'cloud_abuse_alert_event_retention',
] as $index) {
$assert(str_contains($definitions['cloud_abuse_alert_events'], $index)
&& str_contains($setup, "'" . $index . "'"),
'Missing abuse alert event index: ' . $index);
}
foreach ([
'cloud_abuse_alert_item_key', 'cloud_abuse_alert_item_finding_once',
'cloud_abuse_alert_item_event', 'cloud_abuse_alert_item_finding',
] as $index) {
$assert(str_contains(
$definitions['cloud_abuse_alert_event_items'], $index
) && str_contains($setup, "'" . $index . "'"),
'Missing abuse alert item index: ' . $index);
}
foreach ([
'cloud_abuse_finding_key', 'cloud_abuse_finding_instance',
'cloud_abuse_finding_owner', 'cloud_abuse_finding_host',
@ -212,6 +245,19 @@ $assert(str_contains($definitions['cloud_abuse_instance_states'],
&& str_contains($definitions['cloud_abuse_findings'],
"resolution_reason IN (\n 'evidence_clear','policy_replaced','owner_changed'"),
'Abuse-monitoring state constraints are incomplete.');
$assert(str_contains($definitions['cloud_abuse_alert_events'],
'chk_cloud_abuse_alert_event_identity CHECK')
&& str_contains($definitions['cloud_abuse_alert_events'],
"highest_severity IN ('suspicious','high')")
&& str_contains($definitions['cloud_abuse_alert_event_items'],
'chk_cloud_abuse_alert_item_transition CHECK')
&& str_contains($definitions['cloud_abuse_alert_event_items'],
"transition_type = 'opened'")
&& str_contains($definitions['cloud_abuse_alert_event_items'],
"transition_type = 'escalated'")
&& str_contains($definitions['cloud_abuse_alert_event_items'],
"transition_type = 'resolved'"),
'Abuse alert event transition constraints are incomplete.');
$assert(str_contains($definitions['cloud_abuse_instance_states'],
'fk_cloud_abuse_state_instance FOREIGN KEY (instance_id)')
@ -229,6 +275,13 @@ $assert(str_contains($definitions['cloud_abuse_instance_states'],
&& str_contains($setup, "'fk_cloud_abuse_finding_instance'")
&& str_contains($setup, "'fk_cloud_abuse_projection_instance'"),
'Current state or finding rows can outlive a deleted instance.');
$assert(!str_contains($definitions['cloud_abuse_alert_events'],
'REFERENCES cloud_instances')
&& str_contains($definitions['cloud_abuse_alert_event_items'],
'fk_cloud_abuse_alert_item_event FOREIGN KEY (event_id)')
&& str_contains($definitions['cloud_abuse_alert_event_items'],
'ON DELETE CASCADE ON UPDATE RESTRICT'),
'Alert events are not independent or item cleanup is not bounded.');
$outboxDelete = strpos(
$deletion, "'cloud_vm_network_projection_outbox'"
@ -240,6 +293,18 @@ $assert($outboxDelete !== false && $sampleDelete !== false
&& $outboxDelete < $sampleDelete
&& str_contains($deletion, "'cloud_vm_network_baselines'"),
'Account deletion leaves tenant observation history in the log database.');
$assert(str_contains($deletion,
"['cloud_abuse_alert_events', 'user_id']")
&& str_contains($deletion,
"['cloud_abuse_findings', 'user_id']")
&& str_contains($deletion,
"['cloud_abuse_instance_states', 'user_id']"),
'Account deletion does not erase frozen old-owner abuse data.');
$ownerLock = strpos($projection, "->table('user')");
$instanceLock = strpos($projection, "->table('cloud_instances')");
$assert($ownerLock !== false && $instanceLock !== false
&& $ownerLock < $instanceLock,
'Projection does not share the account deletion user-before-instance lock order.');
$assert(str_contains(
$definitions['cloud_vm_network_projection_outbox'],
@ -267,7 +332,7 @@ $assert(str_contains(
$assert(str_contains(
$setup,
"SCHEMA_VERSION = 'go-agent-wss-v44-abuse-policy-projection'"
"SCHEMA_VERSION = 'go-agent-wss-v45-abuse-alert-events'"
), 'CloudSetup schema version was not advanced for abuse observation.');
foreach (array_keys($mainTables + $logTables) as $table) {

@ -96,7 +96,7 @@ foreach ($defaults->rules() as $code => $rule) {
'The fresh schema rule seed drifted from PHP: ' . $code);
}
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v44-abuse-policy-projection'")
"SCHEMA_VERSION = 'go-agent-wss-v45-abuse-alert-events'")
&& str_contains($service, "->where('active_slot', 1)->lockForUpdate()")
&& str_contains($service, "->where('active_slot', 1)->update")
&& str_contains($service, 'insertGetId'),

@ -257,15 +257,15 @@ foreach ([
$assert(str_contains($projection, '->snapshotByIdentity($revision, $hash)')
&& !str_contains($projection, '->activeSnapshot()'),
'Projection can drift from the outbox identity to the current policy.');
$assert(str_contains(
$deployment,
'所有既有 `cloud_abuse_findings.finding_key` 必须'
) && str_contains($deployment, '运行时代码不兼容旧 finding key')
&& str_contains(
$deployment,
'instance_id + "\\n" + rule_version + "\\n" + policy_hash'
),
'Deployment contract does not require v44 finding-key recomputation.');
$assert(str_contains($deployment,
'`go-agent-wss-v45-abuse-alert-events`')
&& str_contains($deployment,
'`occurrence_generation = 1` 与 `transition_revision = 1`')
&& str_contains($deployment,
'历史 finding 不反向合成事件')
&& str_contains($deployment,
'`policy_replaced` 与 `owner_changed` 只关闭 finding'),
'Deployment contract does not define the v45 event-ledger cutover.');
foreach ([
'cloud_vm_network_projection_outbox',

@ -26,6 +26,9 @@ $capsule->setAsGlobal();
$capsule->bootEloquent();
$mainSchema = $capsule->schema('default');
$mainSchema->create('user', static function (Blueprint $table): void {
$table->increments('id');
});
$mainSchema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('host_id');
@ -74,12 +77,50 @@ $mainSchema->create('cloud_abuse_findings',
$table->integer('first_seen_at');
$table->integer('last_seen_at');
$table->integer('consecutive_windows');
$table->integer('occurrence_generation')->default(1);
$table->integer('transition_revision')->default(1);
$table->text('evidence_json');
$table->integer('resolved_at')->nullable();
$table->string('resolution_reason')->default('');
$table->integer('created_at');
$table->integer('updated_at');
});
$mainSchema->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');
});
$mainSchema->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');
});
$mainSchema->create('cloud_abuse_projection_receipts',
static function (Blueprint $table): void {
$table->string('sample_key')->primary();
@ -199,6 +240,9 @@ $uuid = static fn (int $id): string => sprintf(
$addInstance = static function (int $id, int $user, int $host = 7) use (
$main
): void {
if (!$main->table('user')->where('id', $user)->exists()) {
$main->table('user')->insert(['id' => $user]);
}
$main->table('cloud_instances')->insert([
'id' => $id, 'host_id' => $host, 'user_id' => $user,
]);
@ -613,6 +657,7 @@ $assert($worker()->tick()
'Baseline seed did not converge after its read model recovered.');
// Missing owners and stale buckets end explicitly instead of locking forever.
$main->table('user')->insert(['id' => 99]);
$deletedKey = $insertSample(99, 99, 240, $metrics());
$assert($worker()->tick(), 'Deleted-instance sample was not consumed.');
$deleted = $log->table('cloud_vm_network_projection_outbox')
@ -621,7 +666,26 @@ $assert($deleted->state === 'discarded'
&& $deleted->discard_reason_code === 'instance_deleted',
'Deleted instance left a retrying or locked outbox row.');
$main->table('cloud_instances')->insert([
'id' => 21, 'host_id' => 7, 'user_id' => 211,
]);
$missingOwnerKey = $insertSample(21, 211, 240, $metrics());
$assert($worker()->tick(), 'Missing-owner sample was not consumed.');
$assert($log->table('cloud_vm_network_projection_outbox')
->where('sample_key', $missingOwnerKey)
->value('discard_reason_code') === 'instance_owner_missing'
&& $main->table('cloud_abuse_instance_states')
->where('instance_id', 21)->count() === 0
&& $main->table('cloud_abuse_findings')
->where('instance_id', 21)->count() === 0
&& $main->table('cloud_abuse_alert_events')
->where('instance_id', 21)->count() === 0
&& $main->table('cloud_abuse_projection_receipts')
->where('sample_key', $missingOwnerKey)->count() === 0,
'Missing owner allowed late read-model or event insertion.');
$addInstance(8, 88);
$main->table('user')->insert(['id' => 89]);
$oldOwnerFindingKey = hash('sha256', implode("\n", [
8, CloudAbuseDetector::RULE_VERSION,
$policySnapshot->policyHash,
@ -650,6 +714,7 @@ $main->table('cloud_abuse_findings')->insert([
'resolved_at' => null, 'created_at' => $now, 'updated_at' => $now,
]);
$ownerKey = $insertSample(8, 89, 240, $metrics());
$ownerEventCount = $main->table('cloud_abuse_alert_events')->count();
$ownerWorker = $worker();
$assert($ownerWorker->tick(), 'Owner-mismatch sample was not consumed.');
$ownerMismatch = $log->table('cloud_vm_network_projection_outbox')
@ -665,6 +730,11 @@ $assert($ownerMismatch->state === 'discarded'
=== 'resolved'
&& (int) $main->table('cloud_abuse_findings')
->where('finding_key', $oldOwnerFindingKey)->value('user_id') === 89
&& (int) $main->table('cloud_abuse_findings')
->where('finding_key', $oldOwnerFindingKey)
->value('transition_revision') === 2
&& $main->table('cloud_abuse_alert_events')->count()
=== $ownerEventCount
&& (int) $main->table('cloud_instances')
->where('id', 8)->value('user_id') === 88,
'Owner mismatch left a retrying or locked outbox row.');
@ -728,17 +798,70 @@ foreach ([120, 180] as $bucket) {
$finding = $main->table('cloud_abuse_findings')
->where('instance_id', 5)->where('state', 'open')->first();
$assert($finding !== null && $finding->severity === 'high'
&& $finding->direction === 'outbound',
&& $finding->direction === 'outbound'
&& (int) $finding->occurrence_generation === 1
&& (int) $finding->transition_revision === 1,
'Two high windows did not open the deterministic finding.');
foreach ([240, 300, 360, 420, 480] as $bucket) {
$openedEvent = $main->table('cloud_abuse_alert_events')
->where('instance_id', 5)->first();
$openedItem = $openedEvent === null ? null
: $main->table('cloud_abuse_alert_event_items')
->where('event_id', (int) $openedEvent->id)->first();
$assert($openedEvent !== null
&& (int) $openedEvent->bucket_start === 180
&& (int) $openedEvent->transition_count === 1
&& $openedEvent->highest_severity === 'high'
&& $openedItem !== null
&& $openedItem->transition_type === 'opened'
&& $openedItem->from_severity === 'none'
&& $openedItem->to_severity === 'high'
&& (int) $openedItem->occurrence_generation === 1
&& (int) $openedItem->transition_revision === 1,
'Finding open was not frozen as one immutable event item.');
$insertSample(5, 55, 240, $metrics($high));
$assert($worker()->tick(), 'Continued high-risk projection did not run.');
$assert($main->table('cloud_abuse_alert_events')
->where('instance_id', 5)->count() === 1
&& (int) $main->table('cloud_abuse_findings')
->where('instance_id', 5)->value('transition_revision') === 1,
'Continued finding created an event or advanced its transition revision.');
foreach ([300, 360, 420, 480, 540] as $bucket) {
$insertSample(5, 55, $bucket, $metrics());
$assert($worker()->tick(), 'Clear projection did not run.');
}
$finding = $main->table('cloud_abuse_findings')
->where('instance_id', 5)->first();
$assert($finding->state === 'resolved'
&& (int) $finding->resolved_at === 480,
&& (int) $finding->resolved_at === 540
&& (int) $finding->transition_revision === 2,
'Five verified clear windows did not resolve the finding.');
$resolvedItem = $main->table('cloud_abuse_alert_event_items')
->where('finding_key', (string) $finding->finding_key)
->where('transition_type', 'resolved')->first();
$assert($main->table('cloud_abuse_alert_events')
->where('instance_id', 5)->count() === 2
&& $resolvedItem !== null
&& $resolvedItem->from_severity === 'high'
&& $resolvedItem->to_severity === 'none'
&& $resolvedItem->resolution_reason === 'evidence_clear'
&& (int) $resolvedItem->transition_revision === 2,
'Evidence-clear resolution was not frozen as an event.');
foreach ([600, 660] as $bucket) {
$insertSample(5, 55, $bucket, $metrics($high));
$assert($worker()->tick(), 'Reopen projection did not run.');
}
$reopened = $main->table('cloud_abuse_findings')
->where('instance_id', 5)->first();
$reopenedItem = $main->table('cloud_abuse_alert_event_items')
->where('finding_key', (string) $reopened->finding_key)
->where('occurrence_generation', 2)->first();
$assert($reopened->state === 'open'
&& (int) $reopened->occurrence_generation === 2
&& (int) $reopened->transition_revision === 3
&& $reopenedItem !== null
&& $reopenedItem->transition_type === 'opened'
&& (int) $reopenedItem->transition_revision === 3,
'Resolved finding did not reopen in a new occurrence generation.');
// A panel ring gap resets its baseline but never clears an existing finding.
$addInstance(6, 66);
@ -888,6 +1011,7 @@ $switchKey = $insertSample(
0,
$changedPolicySnapshot
);
$policyEventCount = $main->table('cloud_abuse_alert_events')->count();
$assert($worker()->tick(), 'Changed-policy projection did not run.');
$switchedBaseline = json_decode((string) $log->table(
'cloud_vm_network_baselines'
@ -909,7 +1033,10 @@ $assert($log->table('cloud_vm_network_projection_outbox')
&& $switchedBaseline['rules'] === []
&& $replacedFinding->state === 'resolved'
&& $replacedFinding->resolution_reason === 'policy_replaced'
&& (int) $replacedFinding->transition_revision === 2
&& $replacedFinding->evidence_json === '{"tcp_syn_flows":5000}'
&& $main->table('cloud_abuse_alert_events')->count()
=== $policyEventCount
&& $main->table('cloud_abuse_instance_states')
->where('instance_id', 16)->value('risk_state') === 'observing',
'Detector policy switch lost statistics or forged evidence recovery.');
@ -1068,10 +1195,187 @@ $assert($badOutbox->state === 'discarded'
=== 'projection_sample_ledger_inconsistent',
'Bad ledger candidate did not reach an attributable terminal state.');
// Event-item persistence is in the same main transaction as finding/state and
// receipt writes. A storage failure must roll all four back; retrying the same
// outbox after repair then creates exactly one event.
$addInstance(19, 199);
$rollbackBaseline = CloudAbuseDetector::initialBaseline();
$rollbackBaseline['sample_count'] = CloudAbuseDetector::WARMUP_WINDOWS;
$rollbackBaseline['last_bucket_start'] = 780;
$insertBaseline(19, 199, $rollbackBaseline, 780, str_repeat('4', 64));
$insertSample(19, 199, 840, $metrics($high));
$assert($worker()->tick(), 'Alert rollback setup projection did not run.');
$rollbackAlertKey = $insertSample(19, 199, 900, $metrics($high));
$main->statement(
'CREATE TRIGGER reject_abuse_alert_item '
. 'BEFORE INSERT ON cloud_abuse_alert_event_items '
. "BEGIN SELECT RAISE(ABORT, 'forced item failure'); END"
);
$failedAlertWorker = $worker();
$assert($failedAlertWorker->tick(), 'Alert item failure was not consumed.');
$assert($failedAlertWorker->observationErrors() === ['projection_failed']
&& $main->table('cloud_abuse_findings')
->where('instance_id', 19)->count() === 0
&& $main->table('cloud_abuse_alert_events')
->where('instance_id', 19)->count() === 0
&& $main->table('cloud_abuse_projection_receipts')
->where('sample_key', $rollbackAlertKey)->count() === 0
&& (int) $main->table('cloud_abuse_instance_states')
->where('instance_id', 19)->value('last_bucket_start') === 840,
'Alert item failure left partial state, finding, event or receipt data.');
$main->statement('DROP TRIGGER reject_abuse_alert_item');
$now += 1000;
$assert($worker()->tick(), 'Repaired alert event projection did not retry.');
$assert($main->table('cloud_abuse_findings')
->where('instance_id', 19)->count() === 1
&& $main->table('cloud_abuse_alert_events')
->where('instance_id', 19)->count() === 1
&& $main->table('cloud_abuse_alert_event_items')
->whereIn('event_id', $main->table('cloud_abuse_alert_events')
->where('instance_id', 19)->pluck('id')->all())->count() === 1
&& $main->table('cloud_abuse_projection_receipts')
->where('sample_key', $rollbackAlertKey)->count() === 1,
'Alert event retry did not converge to one durable batch.');
// A crash after the main commit leaves the event and receipt authoritative;
// log finalization replay must not duplicate either immutable row.
$addInstance(20, 200);
$eventReplayBaseline = CloudAbuseDetector::initialBaseline();
$eventReplayBaseline['sample_count'] = CloudAbuseDetector::WARMUP_WINDOWS;
$eventReplayBaseline['last_bucket_start'] = 960;
$insertBaseline(20, 200, $eventReplayBaseline, 960, str_repeat('5', 64));
$insertSample(20, 200, 1020, $metrics($high));
$assert($worker()->tick(), 'Event replay setup projection did not run.');
$eventReplayKey = $insertSample(20, 200, 1080, $metrics($high));
$eventCommitCrashed = false;
$worker(static function () use (&$eventCommitCrashed): void {
if (!$eventCommitCrashed) {
$eventCommitCrashed = true;
throw new RuntimeException('simulated event finalization crash');
}
})->tick();
$assert($main->table('cloud_abuse_alert_events')
->where('instance_id', 20)->count() === 1
&& $main->table('cloud_abuse_projection_receipts')
->where('sample_key', $eventReplayKey)->count() === 1
&& $log->table('cloud_vm_network_projection_outbox')
->where('sample_key', $eventReplayKey)->value('state') === 'pending',
'Post-commit crash did not retain the authoritative alert event.');
$now += 15;
$assert($worker()->tick(), 'Event receipt replay did not run.');
$replayEventId = (int) $main->table('cloud_abuse_alert_events')
->where('instance_id', 20)->value('id');
$assert($log->table('cloud_vm_network_projection_outbox')
->where('sample_key', $eventReplayKey)->value('state') === 'done'
&& $main->table('cloud_abuse_alert_events')
->where('instance_id', 20)->count() === 1
&& $main->table('cloud_abuse_alert_event_items')
->where('event_id', $replayEventId)->count() === 1
&& $main->table('cloud_abuse_projection_receipts')
->where('sample_key', $eventReplayKey)->count() === 1,
'Receipt replay duplicated the committed alert event batch.');
$idleWorker = $worker();
$assert(!$idleWorker->tick() && $idleWorker->observationErrors() === [],
'Idle projection worker retained an earlier observation error.');
// Detector reports suspicious-to-high as `continued`; the locked finding row
// is the transition authority. A later silent high-to-suspicious downgrade is
// not an alert transition and must not advance the transition revision.
$apply = new ReflectionMethod(
CloudAbuseProjectionService::class,
'applyFindings'
);
$escalationClaim = [
'sample_key' => str_repeat('9', 64),
'instance_id' => 18,
'user_id' => 188,
'host_id' => 7,
'bucket_start' => 720,
'rule_version' => CloudAbuseDetector::RULE_VERSION,
'policy_revision' => 1,
'policy_hash' => $policySnapshot->policyHash,
];
$escalationKey = hash('sha256', implode("\n", [
18,
CloudAbuseDetector::RULE_VERSION,
$policySnapshot->policyHash,
'outbound_tcp_syn_sweep',
'ipv4',
'outbound',
]));
$main->table('cloud_abuse_findings')->insert([
'finding_key' => $escalationKey,
'instance_id' => 18, 'user_id' => 188, 'host_id' => 7,
'rule_code' => 'outbound_tcp_syn_sweep',
'rule_version' => CloudAbuseDetector::RULE_VERSION,
'policy_revision' => 1,
'policy_hash' => $policySnapshot->policyHash,
'direction' => 'outbound', 'ip_family' => 'ipv4',
'severity' => 'suspicious', 'state' => 'open',
'first_seen_at' => 660, 'last_seen_at' => 660,
'consecutive_windows' => 3,
'occurrence_generation' => 1, 'transition_revision' => 1,
'evidence_json' => '{"tcp_syn_flows":900}',
'resolved_at' => null, 'resolution_reason' => '',
'created_at' => $now, 'updated_at' => $now,
]);
$continuedHigh = [[
'rule_code' => 'outbound_tcp_syn_sweep',
'direction' => 'outbound', 'ip_family' => 'ipv4',
'severity' => 'high', 'active' => true,
'transition' => 'continued', 'consecutive_windows' => 2,
'evidence' => ['tcp_syn_flows' => 5000,
'unique_remote_ips' => 700],
]];
$projectionWorker = $worker();
$escalated = $apply->invoke(
$projectionWorker,
$main,
$escalationClaim,
7,
$continuedHigh,
$now
);
$assert(count($escalated) === 1
&& $escalated[0]['transition_type'] === 'escalated'
&& $escalated[0]['from_severity'] === 'suspicious'
&& $escalated[0]['to_severity'] === 'high'
&& (int) $main->table('cloud_abuse_findings')
->where('finding_key', $escalationKey)
->value('transition_revision') === 2,
'Locked finding state did not derive suspicious-to-high escalation.');
(new App\Services\Cloud\CloudAbuseAlertEventCoordinator())->record(
$main,
$escalationClaim,
$escalated,
$now
);
$escalationClaim['sample_key'] = str_repeat('a', 64);
$escalationClaim['bucket_start'] = 780;
$silentDowngrade = $continuedHigh;
$silentDowngrade[0]['severity'] = 'suspicious';
$silentDowngrade[0]['evidence'] = ['tcp_syn_flows' => 900,
'unique_remote_ips' => 140];
$beforeDowngradeEvents = $main->table(
'cloud_abuse_alert_events'
)->count();
$downgraded = $apply->invoke(
$projectionWorker,
$main,
$escalationClaim,
7,
$silentDowngrade,
$now
);
$assert($downgraded === []
&& (int) $main->table('cloud_abuse_findings')
->where('finding_key', $escalationKey)
->value('transition_revision') === 2
&& $main->table('cloud_abuse_alert_events')->count()
=== $beforeDowngradeEvents,
'Silent severity downgrade advanced revision or created an event.');
$source = file_get_contents(dirname(__DIR__)
. '/app/Services/Cloud/CloudAbuseProjectionService.php');
$assert(is_string($source)

@ -60,12 +60,28 @@ $mainSchema->create('cloud_abuse_findings',
$table->integer('first_seen_at');
$table->integer('last_seen_at');
$table->integer('consecutive_windows');
$table->integer('occurrence_generation')->default(1);
$table->integer('transition_revision')->default(1);
$table->text('evidence_json');
$table->integer('resolved_at')->nullable();
$table->string('resolution_reason')->default('');
$table->integer('created_at');
$table->integer('updated_at');
});
$mainSchema->create('cloud_abuse_alert_events',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('sample_key')->unique();
$table->integer('instance_id');
$table->integer('user_id');
$table->integer('created_at');
});
$mainSchema->create('cloud_abuse_alert_event_items',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('event_id');
$table->string('finding_key');
});
$logSchema = $capsule->schema('log');
$logSchema->create(
@ -217,6 +233,19 @@ $receipt($receiptWithSample, 1, $readCutoff - 1);
$finding('resolved-old', 'resolved', $readCutoff - 1);
$finding('resolved-recent', 'resolved', $readCutoff + 1);
$finding('open-old', 'open', null);
$oldEventFindingKey = $fixtureFindingKey('resolved-old');
$main->table('cloud_abuse_alert_events')->insert([
'id' => 1,
'sample_key' => $key('old-alert-event'),
'instance_id' => 1,
'user_id' => 1,
'created_at' => $readCutoff - 1,
]);
$main->table('cloud_abuse_alert_event_items')->insert([
'id' => 1,
'event_id' => 1,
'finding_key' => $oldEventFindingKey,
]);
$service = new CloudAbuseRetentionService(static fn (): int => $now);
$result = $service->prune();
@ -263,6 +292,10 @@ $assert($main->table('cloud_abuse_findings')->count() === 2
$fixtureFindingKey('resolved-old')
)->exists(),
'Finding retention removed an open/recent finding or kept an old one.');
$assert($main->table('cloud_abuse_alert_events')->where('id', 1)->exists()
&& $main->table('cloud_abuse_alert_event_items')
->where('event_id', 1)->exists(),
'Phase-6 retention removed an alert before delivery finality exists.');
// A storage failure after terminal outbox deletion must roll the log
// transaction back, retaining both records for a later retry.

@ -64,7 +64,7 @@ foreach ([
'CloudSetup omits backup preparation contract: ' . $required);
}
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v44-abuse-policy-projection'")
"SCHEMA_VERSION = 'go-agent-wss-v45-abuse-alert-events'")
&& str_contains($setup,
"'columns' => [\n 'create_request_actor_id',\n 'create_request_idempotency_key',")
&& str_contains($setup, "'non_unique' => 0"),

@ -27,10 +27,10 @@ $assert(stripos($schema, 'compatibility import') === false
$assert(!preg_match('/\bengine_[A-Za-z0-9_]*\b/', $schema),
'cloud.sql retained an engine-prefixed identifier.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v44-abuse-policy-projection'")
"SCHEMA_VERSION = 'go-agent-wss-v45-abuse-alert-events'")
&& !str_contains($setup, "SCHEMA_VERSION = 'go-v1'")
&& str_contains($deployment, '`go-agent-wss-v44-abuse-policy-projection`')
&& str_contains($compensation, '`go-agent-wss-v44-abuse-policy-projection`'),
&& str_contains($deployment, '`go-agent-wss-v45-abuse-alert-events`')
&& str_contains($compensation, '`go-agent-wss-v45-abuse-alert-events`'),
'Outbound Agent schema must reject the incompatible earlier Go database.');
$assert(str_contains($schema,
"timezone VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'UTC'")

@ -56,7 +56,7 @@ foreach ([
}
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v44-abuse-policy-projection'"),
"SCHEMA_VERSION = 'go-agent-wss-v45-abuse-alert-events'"),
'CloudSetup schema version was not advanced for maintenance notices.');
echo "Maintenance notice schema contracts passed.\n";

@ -53,7 +53,7 @@ $assert(is_string($schema)
'Public-pool replacement lacks durable batch, child, or claim schema.');
$assert(is_string($setup)
&& str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v44-abuse-policy-projection'")
"SCHEMA_VERSION = 'go-agent-wss-v45-abuse-alert-events'")
&& str_contains($setup,
"'cloud_public_ip_pool_replacement_batches'")
&& str_contains($setup,

@ -170,7 +170,7 @@ $assert(str_contains($setup,
'CloudSetup does not verify index uniqueness and ordered columns.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v44-abuse-policy-projection'")
"SCHEMA_VERSION = 'go-agent-wss-v45-abuse-alert-events'")
&& str_contains($setup, "'cloud_public_network_transitions'")
&& str_contains($setup, "'cloud_public_network_transition_ips'")
&& str_contains($setup, "'reservation_ip_claim_id'")

@ -57,7 +57,7 @@ $assert($replica !== ''
&& str_contains($replica, 'cleanup_resolved_at BIGINT UNSIGNED'),
'Rescue replica cannot prove exact identity or retain cleanup debt.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v44-abuse-policy-projection'")
"SCHEMA_VERSION = 'go-agent-wss-v45-abuse-alert-events'")
&& str_contains($setup, "'cloud_rescue_artifact_delete_due'")
&& str_contains($setup, "'cloud_rescue_replica_cleanup'"),
'CloudSetup version or rescue catalog indexes are incomplete.');

@ -218,7 +218,7 @@ foreach ([
'CloudSetup omits restore/migration ledger contract: ' . $required);
}
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v44-abuse-policy-projection'")
"SCHEMA_VERSION = 'go-agent-wss-v45-abuse-alert-events'")
&& str_contains($attemptModel,
"protected \$table = 'cloud_backup_restore_attempts';")
&& str_contains($attemptModel, "'active_attempt' => 'int'")

@ -105,7 +105,7 @@ $assert(str_contains($setup,
'CloudSetup lost the open-compensation fence index contract.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v44-abuse-policy-projection'"),
"SCHEMA_VERSION = 'go-agent-wss-v45-abuse-alert-events'"),
'CloudSetup schema version was not advanced for service compensation.');
$appliedShape = preg_match(

@ -138,7 +138,7 @@ $assert(is_string($publicationModel)
&& str_contains($artifactModel, "'maximum_size_bytes' => 'int'"),
'Storage publication/artifact model contracts are incomplete.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v44-abuse-policy-projection'"),
"SCHEMA_VERSION = 'go-agent-wss-v45-abuse-alert-events'"),
'CloudSetup schema version was not advanced for durable publications.');
echo "Storage publication schema contracts passed.\n";

@ -63,7 +63,7 @@ $assert(str_contains($schema,
&& str_contains($schema,
'CONSTRAINT chk_cloud_template_import_completion CHECK (')
&& str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v44-abuse-policy-projection'"),
"SCHEMA_VERSION = 'go-agent-wss-v45-abuse-alert-events'"),
'Template imports are missing durable identity or terminal-state constraints.');
$assert(str_contains($routes, "'/admin/cloud-template-imports'")
&& str_contains($routes, "'/admin/cloud-template-imports/{id}'")

@ -71,7 +71,7 @@ $assert(str_contains($schema,
'Service-period traffic-pool identity is not frozen or indexed.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v44-abuse-policy-projection'")
"SCHEMA_VERSION = 'go-agent-wss-v45-abuse-alert-events'")
&& str_contains($setup, "'chk_cloud_traffic_entitlement_balance'")
&& str_contains($setup, "'cloud_traffic_ledger_sequence'"),
'CloudSetup schema version or named-object validation is incomplete.');

@ -101,7 +101,7 @@ $assert(str_contains($jobs, 'vpc_id BIGINT UNSIGNED DEFAULT NULL')
'Cloud jobs cannot be correlated to VPC or VPC-port work.');
$assert(str_contains($setup,
"private const SCHEMA_VERSION = 'go-agent-wss-v44-abuse-policy-projection'")
"private const SCHEMA_VERSION = 'go-agent-wss-v45-abuse-alert-events'")
&& str_contains($setup, "'name' => 'cloud_vpc_enabled'")
&& str_contains($setup, "'value' => 'false'")
&& str_contains($setup,

@ -25,7 +25,9 @@ $capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'defau
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'log');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->getConnection('default')->getSchemaBuilder();
$defaultConnection = $capsule->getConnection('default');
$defaultConnection->statement('PRAGMA foreign_keys = ON');
$schema = $defaultConnection->getSchemaBuilder();
$logConnection = $capsule->getConnection('log');
$logConnection->statement('PRAGMA foreign_keys = ON');
$logSchema = $logConnection->getSchemaBuilder();
@ -107,6 +109,30 @@ foreach (['yipay_callback_events', 'yipay_refunds'] as $tableName) {
$schema->create('cloud_instances', static function (Blueprint $table) {
$table->increments('id'); $table->integer('user_id'); $table->string('status');
});
$schema->create('cloud_abuse_instance_states',
static function (Blueprint $table) {
$table->integer('instance_id')->primary();
$table->integer('user_id');
});
$schema->create('cloud_abuse_findings',
static function (Blueprint $table) {
$table->increments('id');
$table->integer('instance_id');
$table->integer('user_id');
});
$schema->create('cloud_abuse_alert_events',
static function (Blueprint $table) {
$table->increments('id');
$table->integer('instance_id');
$table->integer('user_id');
});
$schema->create('cloud_abuse_alert_event_items',
static function (Blueprint $table) {
$table->increments('id');
$table->integer('event_id');
$table->foreign('event_id')->references('id')
->on('cloud_abuse_alert_events')->cascadeOnDelete();
});
$schema->create('cloud_orders', static function (Blueprint $table) {
$table->increments('id'); $table->integer('user_id'); $table->string('status');
});
@ -236,6 +262,25 @@ Capsule::table('cloud_instances')->insert([
['id' => 101, 'user_id' => 1, 'status' => 'deleted'],
['id' => 301, 'user_id' => 3, 'status' => 'active'],
]);
// Instance 301 has already been transferred to user 3. Historical abuse rows
// still frozen to old owner 1 must be erased with owner 1 without deleting the
// transferred instance or user 3's unrelated abuse history.
Capsule::table('cloud_abuse_instance_states')->insert([
['instance_id' => 301, 'user_id' => 1],
['instance_id' => 302, 'user_id' => 3],
]);
Capsule::table('cloud_abuse_findings')->insert([
['id' => 1, 'instance_id' => 301, 'user_id' => 1],
['id' => 2, 'instance_id' => 302, 'user_id' => 3],
]);
Capsule::table('cloud_abuse_alert_events')->insert([
['id' => 1, 'instance_id' => 301, 'user_id' => 1],
['id' => 2, 'instance_id' => 302, 'user_id' => 3],
]);
Capsule::table('cloud_abuse_alert_event_items')->insert([
['id' => 1, 'event_id' => 1],
['id' => 2, 'event_id' => 2],
]);
Capsule::table('cloud_orders')->insert([
['id' => 102, 'user_id' => 1, 'status' => 'completed'],
['id' => 302, 'user_id' => 3, 'status' => 'completed'],
@ -336,6 +381,16 @@ $result = (new UserDataDeletionService())->deleteUsers([1, '2', 999], false);
$assert($result['deleted_user_ids'] === [1], 'Expected only the ordinary selected account to be deleted.');
$assert($result['skipped_user_ids'] === [2, 999], 'Administrator or missing account was not excluded.');
$assert(User::find(1) === null && User::find(2) !== null && User::find(3) !== null, 'User deletion was not isolated.');
$assert(Capsule::table('cloud_instances')->where('id', 301)->exists()
&& Capsule::table('cloud_abuse_instance_states')
->orderBy('instance_id')->pluck('user_id')->all() === [3]
&& Capsule::table('cloud_abuse_findings')
->orderBy('id')->pluck('user_id')->all() === [3]
&& Capsule::table('cloud_abuse_alert_events')
->orderBy('id')->pluck('user_id')->all() === [3]
&& Capsule::table('cloud_abuse_alert_event_items')
->orderBy('id')->pluck('event_id')->all() === [2],
'Transferred instance retained old-owner abuse data or was deleted.');
$assert((int) User::find(3)->ref_by === 0, 'Deleted referrer was not cleared.');
$assert(Capsule::table('ticket')->pluck('id')->all() === [20], 'Ticket replies from the deleted thread were retained.');
$assert(Capsule::table('ticket_attachments')->pluck('id')->all() === [3],

@ -104,7 +104,7 @@ foreach ($models as $class => $modelTable) {
}
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v44-abuse-policy-projection'")
"SCHEMA_VERSION = 'go-agent-wss-v45-abuse-alert-events'")
&& str_contains($setup,
"self::schema('ss.sql') . \"\\0\" . self::schema('cloud.sql')")
&& str_contains($setup,

Loading…
Cancel
Save