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

265 lines
9.7 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\User;
/** Publishes immutable abuse policies behind one optimistic-CAS interface. */
final class CloudAbusePolicyService
{
private readonly \Closure $clock;
public function __construct(?callable $clock = null)
{
$this->clock = \Closure::fromCallable(
$clock ?? static fn (): int => time()
);
}
public function activeSnapshot(): CloudAbusePolicySnapshot
{
$connection = $this->connection();
return $connection->transaction(function () use ($connection):
CloudAbusePolicySnapshot {
$row = $connection->table('cloud_abuse_policy_revisions')
->where('active_slot', 1)->sharedLock()->first();
if ($row === null) {
throw new CloudError(
'网络滥用检测策略尚未初始化',
503
);
}
return $this->snapshotFromRow($connection, $row);
}, 3);
}
public function snapshotByIdentity(
int $revision,
string $policyHash
): CloudAbusePolicySnapshot {
if ($revision < 1
|| preg_match('/^[a-f0-9]{64}$/D', $policyHash) !== 1) {
throw new CloudError('网络滥用检测策略身份无效', 422);
}
$connection = $this->connection();
return $connection->transaction(function () use (
$connection,
$revision,
$policyHash
): CloudAbusePolicySnapshot {
$row = $connection->table('cloud_abuse_policy_revisions')
->where('revision', $revision)->sharedLock()->first();
if ($row === null) {
throw new CloudError('网络滥用检测策略版本不存在', 409);
}
if (!hash_equals((string) $row->policy_hash, $policyHash)) {
throw new CloudError('网络滥用检测策略身份冲突', 409);
}
return $this->snapshotFromRow($connection, $row);
}, 3);
}
/**
* @param array<string,mixed> $definition
*/
public function publish(
array $definition,
int $expectedRevision,
int $actorId
): CloudAbusePolicySnapshot {
if ($expectedRevision < 1 || $actorId < 1) {
throw new CloudError('网络滥用检测策略发布参数无效', 422);
}
try {
$policy = CloudAbuseDetectionPolicy::fromDefinition($definition);
} catch (\InvalidArgumentException $error) {
throw new CloudError($error->getMessage(), 422);
}
$connection = $this->connection();
return $connection->transaction(function () use (
$connection,
$policy,
$expectedRevision,
$actorId
): CloudAbusePolicySnapshot {
$currentRow = $connection->table('cloud_abuse_policy_revisions')
->where('active_slot', 1)->lockForUpdate()->first();
if ($currentRow === null) {
throw new CloudError(
'网络滥用检测策略尚未初始化',
503
);
}
$current = $this->snapshotFromRow($connection, $currentRow);
if ($current->revision !== $expectedRevision) {
throw new CloudError(
'网络滥用检测策略已被其他管理员更新,请刷新后重试',
409
);
}
if (hash_equals($current->policyHash, $policy->hash())) {
return $current;
}
if ($current->revision === PHP_INT_MAX) {
throw new CloudError('网络滥用检测策略版本已耗尽', 409);
}
$now = ($this->clock)();
if (!is_int($now) || $now < 1) {
throw new \RuntimeException('Abuse policy clock is invalid');
}
$released = $connection->table('cloud_abuse_policy_revisions')
->where('id', (int) $currentRow->id)
->where('active_slot', 1)->update(['active_slot' => null]);
if ($released !== 1) {
throw new \RuntimeException(
'Abuse policy active revision compare-and-swap failed'
);
}
$revision = $current->revision + 1;
$revisionId = (int) $connection
->table('cloud_abuse_policy_revisions')->insertGetId([
'revision' => $revision,
'detector_version' => $policy->engineVersion(),
'policy_hash' => $policy->hash(),
'active_slot' => 1,
'warmup_windows' => $policy->windows()['warmup'],
'suspicious_windows' =>
$policy->windows()['suspicious'],
'high_windows' => $policy->windows()['high'],
'clear_windows' => $policy->windows()['clear'],
'published_by' => $actorId,
'published_at' => $now,
'created_at' => $now,
]);
$rows = [];
foreach ($policy->rules() as $code => $rule) {
$rows[] = [
'policy_revision_id' => $revisionId,
'rule_code' => $code,
'direction' => $rule['direction'],
'protocol' => $rule['protocol'],
'enabled' => $rule['enabled'] ? 1 : 0,
'suspicious_thresholds_json' => self::json(
$rule['signals']
),
'high_thresholds_json' => self::json($rule['high']),
'created_at' => $now,
];
}
$connection->table('cloud_abuse_policy_rules')->insert($rows);
$created = $connection->table('cloud_abuse_policy_revisions')
->where('id', $revisionId)->first();
if ($created === null) {
throw new \RuntimeException(
'Abuse policy revision finalization failed'
);
}
return $this->snapshotFromRow($connection, $created);
}, 3);
}
private function snapshotFromRow(
object $connection,
object $row
): CloudAbusePolicySnapshot {
$ruleRows = $connection->table('cloud_abuse_policy_rules')
->where('policy_revision_id', (int) $row->id)
->orderBy('id')->get();
$rules = [];
foreach ($ruleRows as $rule) {
$code = (string) $rule->rule_code;
if (isset($rules[$code])) {
throw new \RuntimeException(
'Duplicate network abuse policy rule'
);
}
$rules[$code] = [
'enabled' => (int) $rule->enabled === 1,
'direction' => (string) $rule->direction,
'protocol' => (string) $rule->protocol,
'signals' => self::decodeThresholds(
(string) $rule->suspicious_thresholds_json
),
'high' => self::decodeThresholds(
(string) $rule->high_thresholds_json
),
];
}
$catalog = CloudAbuseDetectionPolicy::defaults()->rules();
$orderedRules = [];
foreach (array_keys($catalog) as $code) {
if (!isset($rules[$code])) {
throw new \RuntimeException(
'Network abuse policy rule catalog is incomplete'
);
}
$orderedRules[$code] = $rules[$code];
}
if (count($rules) !== count($orderedRules)) {
throw new \RuntimeException(
'Network abuse policy rule catalog contains unknown rules'
);
}
try {
$policy = CloudAbuseDetectionPolicy::fromDefinition([
'engine_version' => (int) $row->detector_version,
'windows' => [
'warmup' => (int) $row->warmup_windows,
'suspicious' => (int) $row->suspicious_windows,
'high' => (int) $row->high_windows,
'clear' => (int) $row->clear_windows,
],
'rules' => $orderedRules,
]);
} catch (\InvalidArgumentException $error) {
throw new \RuntimeException(
'Stored network abuse policy is invalid',
0,
$error
);
}
return new CloudAbusePolicySnapshot(
(int) $row->revision,
(string) $row->policy_hash,
$policy,
$row->published_by === null ? null : (int) $row->published_by,
(int) $row->published_at
);
}
/** @return array<string,int> */
private static function decodeThresholds(string $json): array
{
try {
$value = json_decode($json, true, 16, JSON_THROW_ON_ERROR);
} catch (\JsonException $error) {
throw new \RuntimeException(
'Stored network abuse threshold JSON is invalid',
0,
$error
);
}
if (!is_array($value) || array_is_list($value)) {
throw new \RuntimeException(
'Stored network abuse thresholds are invalid'
);
}
return $value;
}
private function connection(): object
{
return User::getConnectionResolver()->connection('default');
}
/** @param array<string,int> $value */
private static function json(array $value): string
{
return json_encode(
$value,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
);
}
}