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/CloudPlatformDefaultNetwork...

251 lines
10 KiB
PHTML

<?php
namespace App\Services\Cloud;
/**
* Strict reader for the versioned, cross-language platform network manifest.
*
* The checked-in JSON document is the sole source of rule definitions. This
* service validates its complete schema before exposing either enforcement or
* administrator-view data; callers must never silently fall back to an empty
* policy when the document is missing or malformed.
*/
final class CloudPlatformDefaultNetworkPolicy
{
private const MAX_MANIFEST_BYTES = 65536;
private const MAX_RULES = 100;
private const MAX_EXPANDED_RULES = 70;
private const TOP_LEVEL_KEYS = [
'schema_version', 'policy_version', 'scope', 'applies_to',
'migrate_existing', 'rules', 'explicitly_unrestricted',
];
private const RULE_KEYS = [
'id', 'label', 'category', 'protocols', 'port_from', 'port_to',
'directions', 'reason',
];
private const UNRESTRICTED_KEYS = ['protocol', 'port', 'reason'];
public static function manifest(): array
{
$path = dirname(__DIR__, 4)
. '/config/platform_default_network_policy.json';
if (!is_file($path) || !is_readable($path)) {
throw new \RuntimeException('平台默认网络策略清单无法读取');
}
$raw = file_get_contents($path);
if (!is_string($raw) || $raw === ''
|| strlen($raw) > self::MAX_MANIFEST_BYTES) {
throw new \RuntimeException('平台默认网络策略清单大小无效');
}
try {
$manifest = json_decode($raw, true, 32, JSON_THROW_ON_ERROR);
} catch (\JsonException $exception) {
throw new \RuntimeException('平台默认网络策略清单不是有效 JSON', 0,
$exception);
}
if (!is_array($manifest) || array_is_list($manifest)) {
throw new \RuntimeException('平台默认网络策略清单根节点无效');
}
return self::validate($manifest);
}
/** Validate a decoded document for deployment checks and contract tests. */
public static function validate(array $manifest): array
{
self::assertExactKeys($manifest, self::TOP_LEVEL_KEYS, '策略清单');
if (($manifest['schema_version'] ?? null) !== 1
|| ($manifest['policy_version'] ?? null) !== 1) {
throw new \RuntimeException('平台默认网络策略版本不受支持');
}
if (($manifest['scope'] ?? null) !== 'public_ipv4_interface'
|| ($manifest['applies_to'] ?? null)
!== 'new_public_cloud_image_instances_only'
|| ($manifest['migrate_existing'] ?? null) !== false) {
throw new \RuntimeException('平台默认网络策略适用范围无效');
}
$rules = $manifest['rules'] ?? null;
if (!is_array($rules) || !array_is_list($rules) || $rules === []
|| count($rules) > self::MAX_RULES) {
throw new \RuntimeException('平台默认网络策略规则列表无效');
}
$ids = [];
$expanded = [];
$categories = ['permanent' => 0, 'default' => 0];
foreach ($rules as $index => $rule) {
$context = '策略规则 #' . ($index + 1);
if (!is_array($rule) || array_is_list($rule)) {
throw new \RuntimeException($context . ' 格式无效');
}
self::assertExactKeys($rule, self::RULE_KEYS, $context);
$id = $rule['id'] ?? null;
if (!is_string($id)
|| preg_match('/^[a-z0-9][a-z0-9_-]{0,63}$/D', $id) !== 1
|| isset($ids[$id])) {
throw new \RuntimeException($context . ' 标识无效或重复');
}
$ids[$id] = true;
self::assertText($rule['label'] ?? null, 120,
$context . ' 名称');
self::assertText($rule['reason'] ?? null, 500,
$context . ' 原因');
$category = $rule['category'] ?? null;
if (!is_string($category)
|| !array_key_exists($category, $categories)) {
throw new \RuntimeException($context . ' 分类无效');
}
$categories[$category]++;
self::assertEnumList($rule['protocols'] ?? null,
['tcp', 'udp'], $context . ' 协议');
self::assertEnumList($rule['directions'] ?? null,
['ingress', 'egress'], $context . ' 方向');
$from = $rule['port_from'] ?? null;
$to = $rule['port_to'] ?? null;
if (!is_int($from) || !is_int($to) || $from < 1 || $to > 65535
|| $from > $to) {
throw new \RuntimeException($context . ' 端口范围无效');
}
foreach ($rule['protocols'] as $protocol) {
foreach ($rule['directions'] as $direction) {
$identity = implode(':', [
$protocol, (string) $from, (string) $to, $direction,
]);
if (isset($expanded[$identity])) {
throw new \RuntimeException('平台默认网络策略包含重复规则');
}
$expanded[$identity] = true;
if (count($expanded) > self::MAX_EXPANDED_RULES) {
throw new \RuntimeException(
'平台默认网络策略展开后超过 70 条规则');
}
}
}
}
if ($categories['permanent'] < 1 || $categories['default'] < 1) {
throw new \RuntimeException('平台默认网络策略缺少必要分类');
}
$unrestricted = $manifest['explicitly_unrestricted'] ?? null;
if (!is_array($unrestricted) || !array_is_list($unrestricted)
|| count($unrestricted) > self::MAX_RULES) {
throw new \RuntimeException('平台默认网络策略未限制元数据无效');
}
$seenUnrestricted = [];
foreach ($unrestricted as $index => $entry) {
$context = '未限制端口 #' . ($index + 1);
if (!is_array($entry) || array_is_list($entry)) {
throw new \RuntimeException($context . ' 格式无效');
}
self::assertExactKeys($entry, self::UNRESTRICTED_KEYS, $context);
$protocol = $entry['protocol'] ?? null;
$port = $entry['port'] ?? null;
if (!is_string($protocol) || !in_array($protocol, ['tcp', 'udp'], true)
|| !is_int($port) || $port < 1 || $port > 65535) {
throw new \RuntimeException($context . ' 协议或端口无效');
}
self::assertText($entry['reason'] ?? null, 500,
$context . ' 原因');
$identity = $protocol . ':' . $port;
if (isset($seenUnrestricted[$identity])) {
throw new \RuntimeException($context . ' 重复');
}
$seenUnrestricted[$identity] = true;
foreach ($rules as $rule) {
if (in_array($protocol, $rule['protocols'], true)
&& $port >= $rule['port_from']
&& $port <= $rule['port_to']) {
throw new \RuntimeException(
$context . ' 与受限规则相互冲突');
}
}
}
return $manifest;
}
public static function page(): array
{
$manifest = self::manifest();
$permanent = [];
$defaults = [];
foreach ($manifest['rules'] as $rule) {
$display = self::displayRule($rule);
if ($rule['category'] === 'permanent') {
$permanent[] = $display;
} else {
$defaults[] = $display;
}
}
$unrestricted = [];
foreach ($manifest['explicitly_unrestricted'] as $entry) {
$unrestricted[] = $entry + [
'protocol_label' => strtoupper($entry['protocol']),
'port_label' => (string) $entry['port'],
];
}
return [
'schema_version' => $manifest['schema_version'],
'policy_version' => $manifest['policy_version'],
'scope' => $manifest['scope'],
'applies_to' => $manifest['applies_to'],
'migrate_existing' => $manifest['migrate_existing'],
'permanent_rules' => $permanent,
'default_rules' => $defaults,
'explicitly_unrestricted' => $unrestricted,
];
}
private static function displayRule(array $rule): array
{
$directions = $rule['directions'];
$directionLabel = count($directions) === 2
? '公网入站、出站'
: ($directions[0] === 'ingress' ? '仅公网入站' : '仅公网出站');
return $rule + [
'protocol_label' => strtoupper(implode('/', $rule['protocols'])),
'port_label' => $rule['port_from'] === $rule['port_to']
? (string) $rule['port_from']
: $rule['port_from'] . '–' . $rule['port_to'],
'direction_label' => $directionLabel,
];
}
private static function assertExactKeys(array $value, array $expected,
string $context): void
{
$actual = array_keys($value);
sort($actual, SORT_STRING);
$wanted = $expected;
sort($wanted, SORT_STRING);
if ($actual !== $wanted) {
throw new \RuntimeException($context . ' 字段集合无效');
}
}
private static function assertEnumList($value, array $allowed,
string $context): void
{
if (!is_array($value) || !array_is_list($value) || $value === []) {
throw new \RuntimeException($context . '列表无效');
}
$seen = [];
foreach ($value as $item) {
if (!is_string($item) || !in_array($item, $allowed, true)
|| isset($seen[$item])) {
throw new \RuntimeException($context . '列表无效');
}
$seen[$item] = true;
}
}
private static function assertText($value, int $maxBytes,
string $context): void
{
if (!is_string($value) || $value === '' || trim($value) !== $value
|| strlen($value) > $maxBytes || preg_match('//u', $value) !== 1
|| preg_match('/[\x00-\x1F\x7F]/u', $value) === 1) {
throw new \RuntimeException($context . '无效');
}
}
}