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

290 lines
14 KiB
PHTML

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudPlatformDefaultNetworkPolicy as Policy;
set_error_handler(static function (int $severity, string $message, string $file,
int $line): bool {
if ((error_reporting() & $severity)
&& ($severity & (E_WARNING | E_USER_WARNING | E_DEPRECATED))) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
return false;
});
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$reject = static function (array $manifest, string $message) use ($assert): void {
try {
Policy::validate($manifest);
} catch (RuntimeException $exception) {
return;
}
$assert(false, $message);
};
$manifest = Policy::manifest();
$expectedTopKeys = ['schema_version', 'policy_version', 'scope', 'applies_to',
'migrate_existing', 'rules', 'explicitly_unrestricted'];
$actualTopKeys = array_keys($manifest);
sort($actualTopKeys, SORT_STRING);
sort($expectedTopKeys, SORT_STRING);
$assert($actualTopKeys === $expectedTopKeys,
'Manifest top-level exact schema changed.');
$assert($manifest['schema_version'] === 1 && $manifest['policy_version'] === 1
&& $manifest['scope'] === 'public_ipv4_interface'
&& $manifest['applies_to'] === 'new_public_cloud_image_instances_only'
&& $manifest['migrate_existing'] === false,
'Manifest version or new-public-interface scope changed.');
$matrix = [];
foreach ($manifest['rules'] as $rule) {
$matrix[$rule['id']] = [
$rule['category'], $rule['protocols'], $rule['port_from'],
$rule['port_to'], $rule['directions'],
];
}
$assert($matrix === [
'qotd' => ['permanent', ['tcp', 'udp'], 17, 17, ['ingress', 'egress']],
'chargen' => ['permanent', ['tcp', 'udp'], 19, 19, ['ingress', 'egress']],
'ssdp' => ['permanent', ['tcp', 'udp'], 1900, 1900, ['ingress', 'egress']],
'memcached' => ['permanent', ['udp'], 11211, 11211, ['ingress', 'egress']],
'brand-rex-53413' => ['permanent', ['udp'], 53413, 53413, ['ingress', 'egress']],
'smtp-25' => ['default', ['tcp'], 25, 25, ['egress']],
'netbios' => ['default', ['tcp', 'udp'], 137, 139, ['ingress', 'egress']],
'smb' => ['default', ['tcp', 'udp'], 445, 445, ['ingress', 'egress']],
'kms-1688' => ['default', ['tcp'], 1688, 1688, ['ingress']],
], 'The authoritative restricted-port matrix changed.');
$assert($manifest['explicitly_unrestricted'] === [[
'protocol' => 'tcp', 'port' => 587,
'reason' => 'SMTP 提交端口当前不受平台默认策略限制。',
]], 'TCP 587 must remain explicit unrestricted metadata.');
$malformed = $manifest;
$malformed['unexpected'] = true;
$reject($malformed, 'Unknown manifest fields were accepted.');
$malformed = $manifest;
$malformed['rules'][0]['protocols'][] = 'icmp';
$reject($malformed, 'Unknown protocols were accepted.');
$malformed = $manifest;
$malformed['rules'][0]['directions'] = ['ingress', 'ingress'];
$reject($malformed, 'Duplicate directions were accepted.');
$malformed = $manifest;
$malformed['rules'][] = array_replace($manifest['rules'][0], [
'id' => 'duplicate-qotd',
]);
$reject($malformed, 'Duplicate protocol/port/direction rules were accepted.');
$malformed = $manifest;
$malformed['rules'] = [];
for ($index = 0; $index < 18; $index++) {
$malformed['rules'][] = [
'id' => 'expanded-' . $index,
'label' => 'Expanded ' . $index,
'category' => $index === 0 ? 'permanent' : 'default',
'protocols' => ['tcp', 'udp'],
'port_from' => 1000 + $index,
'port_to' => 1000 + $index,
'directions' => ['ingress', 'egress'],
'reason' => 'Expanded rule limit fixture.',
];
}
$reject($malformed, 'More than 70 expanded platform rules were accepted.');
$malformed = $manifest;
$malformed['explicitly_unrestricted'][0]['port'] = 25;
$reject($malformed, 'Unrestricted metadata was allowed to conflict with a rule.');
$malformed = $manifest;
$malformed['migrate_existing'] = true;
$reject($malformed, 'Existing-instance migration was accepted.');
$page = Policy::page();
$assert(count($page['permanent_rules']) === 5
&& count($page['default_rules']) === 4
&& count($page['explicitly_unrestricted']) === 1,
'Administrator policy projection lost a category.');
$smtp = array_values(array_filter($page['default_rules'],
static fn (array $rule): bool => $rule['id'] === 'smtp-25'))[0] ?? null;
$kms = array_values(array_filter($page['default_rules'],
static fn (array $rule): bool => $rule['id'] === 'kms-1688'))[0] ?? null;
$assert(($smtp['direction_label'] ?? null) === '仅公网出站'
&& ($kms['direction_label'] ?? null) === '仅公网入站',
'One-way restrictions were mislabeled.');
$root = dirname(__DIR__);
$routes = file_get_contents($root . '/config/routes.php');
$apiRoutes = file_get_contents($root . '/config/routes_cloud.php');
$controller = file_get_contents(
$root . '/app/Controllers/Admin/CloudPageController.php');
$apiController = file_get_contents(
$root . '/app/Controllers/CloudAdminPlatformPolicyController.php');
$middleware = file_get_contents($root . '/app/Middleware/CloudApi.php');
$browser = file_get_contents($root . '/public/cloud/admin-platform-policy.js');
$schema = file_get_contents($root . '/sql/cloud.sql');
$header = file_get_contents(
$root . '/resources/views/venix/admin/static_header.tpl');
$userSidebar = file_get_contents(
$root . '/resources/views/venix/user/panel_sidebar.tpl');
$assert(substr_count($routes,
"get('/platform-default-policy', 'App\\Controllers\\Admin\\CloudPageController:platformDefaultPolicy')") === 1
&& str_contains($routes, '})->add(new Admin());'),
'Administrator GET page route or Admin middleware is missing.');
$assert(!str_contains($routes, "post('/platform-default-policy'")
&& !str_contains($routes, "put('/platform-default-policy'")
&& !str_contains($routes, "delete('/platform-default-policy'")
&& str_contains($apiRoutes, "get('/admin/platform-test-policy'")
&& str_contains($apiRoutes, "post('/admin/platform-test-policy/rules'")
&& str_contains($apiRoutes, "put('/admin/platform-test-policy/rules/{rule_key:[a-f0-9]{32}}'")
&& str_contains($apiRoutes, "delete('/admin/platform-test-policy/rules/{rule_key:[a-f0-9]{32}}'"),
'The immutable page route or separate test-policy CRUD routes changed.');
$assert(str_contains($controller,
'public function platformDefaultPolicy(')
&& str_contains($controller, 'CloudPlatformDefaultNetworkPolicy::page()')
&& str_contains($controller, 'CloudPlatformTestNetworkPolicy::page()')
&& str_contains($controller, 'CloudAccess::actor(false)')
&& str_contains($controller, "Cache-Control', 'private, no-store"),
'The page controller lost strict local policy loading or private admin authorization.');
$assert(str_contains($apiController, 'CloudAccess::manage($actor)')
&& str_contains($apiController, 'CloudPlatformTestNetworkPolicy::create(')
&& str_contains($apiController, 'CloudPlatformTestNetworkPolicy::update(')
&& str_contains($apiController, 'CloudPlatformTestNetworkPolicy::delete(')
&& str_contains($middleware, '/api/v1/admin/platform-test-policy')
&& !str_contains($apiController, 'CloudEngineClient'),
'Test-policy writes lost super-admin enforcement or became engine-coupled.');
$assert(str_contains($schema,
'CREATE TABLE IF NOT EXISTS cloud_platform_test_policy_state (')
&& str_contains($schema,
'CREATE TABLE IF NOT EXISTS cloud_platform_test_policy_rules (')
&& str_contains($schema, 'deleted_at BIGINT UNSIGNED DEFAULT NULL')
&& str_contains($browser, 'expected_revision')
&& str_contains($browser, "method, body: payload")
&& str_contains($browser, '请求结果暂时未知'),
'The revisioned soft-delete catalog or safe browser mutation contract is missing.');
$assert(str_contains($header, 'href="/admin/platform-default-policy"')
&& str_contains($header,
"\$admin_active|default:'' == 'platform-default-policy'"),
'The audit sidebar link or active state is missing.');
$assert(!str_contains($userSidebar, '/admin/platform-default-policy')
&& !str_contains($userSidebar, '平台默认策略'),
'The administrator-only policy leaked into customer navigation.');
$smarty = new Smarty();
$compileDir = sys_get_temp_dir() . '/admin-platform-policy-view-'
. bin2hex(random_bytes(6));
mkdir($compileDir);
$smarty->setCompileDir($compileDir);
$smarty->setTemplateDir($root . '/resources/views/venix');
$smarty->assign('config', ['appName' => 'Venix Test']);
$smarty->assign('cdn', '');
$smarty->assign('user', (object) ['isLogin' => false]);
$smarty->assign('admin_can_manage', false);
$smarty->assign('admin_csrf_token', 'fixture-not-a-real-token');
$testPage = [
'revision' => 3,
'maximum_expanded_rules' => 70,
'base_expanded_rules' => 26,
'available_expanded_rules' => 43,
'rules' => [[
'id' => str_repeat('a', 32),
'service' => 'Temporary test',
'protocol' => 'tcp',
'protocol_label' => 'TCP',
'port' => '8080',
'direction' => 'ingress',
'direction_label' => '仅公网入站',
'reason' => 'Only future paid creates receive this snapshot.',
'created_at' => 1,
'updated_at' => 2,
]],
];
$render = static function (?array $value, string $error = '',
?array $testValue = null, string $testError = '',
bool $canManage = false) use ($smarty, $testPage): string {
$testValue ??= $testPage;
$smarty->assign('platform_policy', $value);
$smarty->assign('platform_policy_error', $error);
$smarty->assign('platform_test_policy', $testValue);
$smarty->assign('platform_test_policy_error', $testError);
$smarty->assign('admin_can_manage', $canManage);
$smarty->assign('platform_test_policy_bootstrap_json', json_encode(
$testValue,
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
| JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE
| JSON_THROW_ON_ERROR
));
return $smarty->fetch('admin/cloud/platform_default_policy.tpl');
};
$html = $render($page);
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('<?xml encoding="UTF-8">' . $html);
$xpath = new DOMXPath($dom);
$assert($xpath->query('//tbody[@id="platform-policy-permanent-body"]/tr')->length === 5
&& $xpath->query('//tbody[@id="platform-policy-default-body"]/tr')->length === 4
&& $xpath->query('//tbody[@id="platform-policy-unrestricted-body"]/tr')->length === 1,
'SSR did not render all policy categories.');
$restrictedText = '';
foreach ($xpath->query('//tbody[@id="platform-policy-permanent-body" or @id="platform-policy-default-body"]') as $body) {
$restrictedText .= ' ' . $body->textContent;
}
$assert(!str_contains($restrictedText, '587')
&& str_contains($xpath->query('//tbody[@id="platform-policy-unrestricted-body"]')->item(0)->textContent, '587'),
'TCP 587 appeared in the restricted tables or disappeared from metadata.');
$assert($xpath->query('//form[@id="platform-test-policy-form"]
| //*[@data-platform-test-edit]
| //*[@data-platform-test-delete]')->length === 0
&& $xpath->query('//tbody[@id="platform-test-policy-body"]/tr')->length === 1
&& $xpath->query('//script[contains(@src, "admin-platform-policy.js")]')->length === 1,
'A read-only administrator received mutation controls or lost test-policy visibility.');
$assert($xpath->query('//a[@href="/admin/platform-default-policy" and contains(concat(" ", normalize-space(@class), " "), " active ")]')->length === 1,
'The audit navigation does not identify the active policy page.');
$assert(str_contains($dom->textContent, '不迁移')
&& str_contains($dom->textContent, '拒绝 IPv6 以防绕过 IPv4 端口基线')
&& str_contains($dom->textContent, '例外申请、审核和解除逻辑尚未实现')
&& str_contains($dom->textContent, '平台拒绝优先')
&& str_contains($dom->textContent, '已排队、已创建实例')
&& str_contains($dom->textContent, '不统计宿主机实时执行状态'),
'The page overclaims migration, exceptions, observed enforcement or retroactive edits.');
$managerHtml = $render($page, '', $testPage, '', true);
$managerDom = new DOMDocument();
$managerDom->loadHTML('<?xml encoding="UTF-8">' . $managerHtml);
$managerXpath = new DOMXPath($managerDom);
$assert($managerXpath->query('//form[@id="platform-test-policy-form"]')->length === 1
&& $managerXpath->query('//*[@data-platform-test-edit]')->length === 1
&& $managerXpath->query('//*[@data-platform-test-delete]')->length === 1,
'A super administrator cannot create, edit and delete test rules.');
$unsafe = $page;
$unsafe['permanent_rules'][0]['label'] = '</script><img src=x onerror=alert(1)>';
$unsafeHtml = $render($unsafe);
$dom->loadHTML('<?xml encoding="UTF-8">' . $unsafeHtml);
$xpath = new DOMXPath($dom);
$assert($xpath->query('//*[@onerror]')->length === 0
&& str_contains($dom->textContent, '</script><img src=x onerror=alert(1)>'),
'Manifest text was rendered as executable markup.');
$unsafeTest = $testPage;
$unsafeTest['rules'][0]['service'] = '</script><img src=x onerror=alert(2)>';
$unsafeTest['rules'][0]['reason'] = '<script>alert(3)</script>';
$unsafeTestHtml = $render($page, '', $unsafeTest, '', true);
$dom->loadHTML('<?xml encoding="UTF-8">' . $unsafeTestHtml);
$xpath = new DOMXPath($dom);
$assert($xpath->query('//*[@onerror]')->length === 0
&& $xpath->query('//*[@data-platform-test-policy]//img')->length === 0
&& str_contains($dom->textContent,
'</script><img src=x onerror=alert(2)>')
&& str_contains($dom->textContent, '<script>alert(3)</script>'),
'Test-policy SSR or JSON bootstrap rendered administrator text as markup.');
$failed = $render(null, '策略清单暂时无法读取,请检查部署文件。');
$assert(str_contains($failed, '策略清单暂时无法读取,请检查部署文件。')
&& !str_contains($failed, '平台永久限制规则'),
'An unavailable manifest was disguised as an empty successful policy.');
$testFailed = $render($page, '', null,
'手动测试配置暂时无法读取,请确认数据库已升级。');
$assert(str_contains($testFailed, '手动测试配置暂时无法读取,请确认数据库已升级。')
&& !str_contains($testFailed, 'admin-platform-policy.js'),
'An unavailable test catalog exposed stale mutation controls.');
echo "Administrator platform network policy manifest, test catalog, route and SSR contracts passed.\n";