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/AdminFabricContractTest.php

372 lines
20 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
// Static contract coverage for the administrator region-readiness boundary.
// This test deliberately does not boot the application or contact a host.
$root = dirname(__DIR__);
$read = static function (string $relative) use ($root): string {
$value = file_get_contents($root . '/' . $relative);
if (!is_string($value)) {
throw new RuntimeException('Unable to read ' . $relative);
}
return $value;
};
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$section = static function (string $source, string $start, string $end): string {
$offset = strpos($source, $start);
if ($offset === false) {
throw new RuntimeException('Unable to find section start: ' . $start);
}
$limit = strpos($source, $end, $offset + strlen($start));
if ($limit === false) {
throw new RuntimeException('Unable to find section end: ' . $end);
}
return substr($source, $offset, $limit - $offset);
};
$routes = $read('config/routes.php');
$cloudRoutes = $read('config/routes_cloud.php');
$middleware = $read('app/Middleware/CloudApi.php');
$client = $read('app/Services/Cloud/CloudEngineClient.php');
$controller = $read('app/Controllers/CloudAdminFabricController.php');
$resourceController = $read('app/Controllers/CloudAdminResourceController.php');
$service = $read('app/Services/Cloud/CloudAdminFabricService.php');
$page = $read('app/Controllers/Admin/CloudPageController.php');
$template = $read('resources/views/venix/admin/cloud/fabric.tpl');
$script = $read('public/cloud/admin-fabric.js');
$styles = $read('public/cloud/admin.css');
$assets = $read('resources/views/venix/layout_assets.tpl');
$header = $read('resources/views/venix/admin/static_header.tpl');
$assert(str_contains($routes, "\$this->get('/fabric', 'App\\Controllers\\Admin\\CloudPageController:fabric')")
&& str_contains($header, 'href="/admin/fabric"')
&& str_contains($header, '<span>地区私网</span>')
&& str_contains($page, "fetch('admin/cloud/fabric.tpl')"),
'Fabric administrator page route, navigation or renderer is missing.');
foreach (['probe', 'apply', 'reconcile'] as $operation) {
$assert(str_contains(
$cloudRoutes,
"/admin/fabric/regions/{region_id:[0-9]+}/{$operation}"
), 'Region Fabric route is missing: ' . $operation);
}
$assert(str_contains($cloudRoutes, "\$this->get('/admin/fabric'")
&& strpos($cloudRoutes, "/admin/fabric/regions/{region_id:[0-9]+}/apply")
< strpos($cloudRoutes, "\$this->get('/admin/fabric/{fabric_id:"),
'Region workflows must be registered before the dynamic Fabric detail route.');
$assert(!str_contains($cloudRoutes, "'/admin/fabric/apply'")
&& !str_contains($controller, 'public function apply(')
&& !str_contains($cloudRoutes,
'/admin/fabric/{fabric_id:[A-Za-z0-9][A-Za-z0-9_.-]{0,63}}/reconcile')
&& !str_contains($controller, 'public function reconcile('),
'Retired generic raw-plan/reconcile administrator endpoints remain reachable.');
$assert(str_contains($cloudRoutes,
"\$this->get('/admin/regions/{id:[0-9]+}/fabric'")
&& !str_contains($cloudRoutes,
"\$this->map(['GET', 'PUT', 'PATCH'], '/admin/regions/{id:[0-9]+}/fabric'")
&& !str_contains($cloudRoutes,
"\$this->post('/admin/regions/{id:[0-9]+}/fabric'")
&& !str_contains($cloudRoutes,
"\$this->put('/admin/regions/{id:[0-9]+}/fabric'")
&& !str_contains($cloudRoutes,
"\$this->patch('/admin/regions/{id:[0-9]+}/fabric'"),
'Region Fabric mapping must be read-only outside the region wizard.');
$regionFabricController = $section($resourceController,
'public function regionFabric(', 'public function networkLines(');
$assert(!str_contains($regionFabricController, 'getMethod')
&& !str_contains($regionFabricController, 'CloudInput')
&& !str_contains($regionFabricController, 'saveRegionFabric'),
'The resource controller retained a manual region mapping write path.');
$assert(str_contains($middleware, "/api/v1/admin/fabric(?:/|$)")
&& str_contains($client, 'function fabricStatuses')
&& str_contains($client, 'function fabricProbe')
&& str_contains($client, 'function fabricApply')
&& str_contains($client, 'function fabricReconcile')
&& str_contains($client, 'safeFabricErrorMessage')
&& str_contains($client,
"'fabric_probe_busy' => '已有地区宿主机检测正在运行,请稍后重试'"),
'Region Fabric actions must use the protected PHP boundary and bounded engine client.');
$assert(str_contains($controller, 'CloudAccess::manage')
&& str_contains($controller, "['is_super_admin']")
&& str_contains($controller, 'assertEmptyBody')
&& str_contains($controller, 'probeRegion')
&& str_contains($controller, 'applyRegion')
&& str_contains($controller, 'reconcileRegion'),
'Region Fabric actions lost the super-admin or empty-body boundary.');
$assert(str_contains($service, "'regions' => self::readinessRegions")
&& str_contains($service, 'function probeRegion')
&& str_contains($service, 'function applyRegion')
&& str_contains($service, 'function reconcileRegion')
&& str_contains($service, 'assertConfigurableProbes')
&& str_contains($service, 'automaticFabricId')
&& str_contains($service, 'automaticOverlay')
&& str_contains($service, 'automaticNodes')
&& str_contains($service, 'CloudAdminResourceService::saveRegionFabric')
&& str_contains($service, "'ready_host_count'")
&& str_contains($service, "'blocked_host_count'")
&& str_contains($service, "'network_manager_expected'")
&& str_contains($service, "'fabric_member'"),
'Fabric service must own automatic plans and project region/host readiness.');
$assert(!str_contains($service, 'public static function apply(')
&& !str_contains($service, 'public static function reconcile(')
&& str_contains($service, 'public static function applyRegion(')
&& str_contains($service, 'public static function reconcileRegion(')
&& str_contains($client, 'function fabricApply')
&& str_contains($client, 'function fabricReconcile'),
'Generic PHP plan writes survived or the region-owned engine boundary was removed.');
$applyWorkflow = $section($service,
'public static function applyRegion(',
'/** Reconcile only the fixed desired Fabric; never generate a new plan. */');
$reconcileWorkflow = $section($service,
'public static function reconcileRegion(',
'/** Return immediately without a second Engine round trip after accept. */');
$assert(str_contains($applyWorkflow, "['operation'] ?? null, ['apply']")
&& str_contains($applyWorkflow, 'return self::operationReceipt($operation);')
&& !str_contains($applyWorkflow, 'saveRegionFabric')
&& str_contains($reconcileWorkflow, 'saveRegionFabric')
&& str_contains($service, 'private static function mutationOperation(')
&& str_contains($service, "preg_match('/^[0-9a-f]{32}$/D'")
&& str_contains($service,
'Fabric operation 回执无效,已阻止发布地区映射'),
'Fabric writes must require a bounded operation receipt and defer mapping to reconcile.');
$listingProjection = $section($service,
'public static function listing(', 'public static function detail(');
$detailProjection = $section($service,
'public static function detail(', 'public static function probeRegion(');
$regionProjection = $section($service,
'private static function readinessRegions(',
'private static function workflowProjection(');
$assert(!str_contains($listingProjection, "'fabrics' =>")
&& !str_contains($regionProjection, "'fabric' =>")
&& str_contains($detailProjection, "'fabric' =>"),
'List workflows exposed raw plans or the explicit detail readback disappeared.');
$workflowProjection = $section($service,
'private static function workflowProjection(',
'private static function probeRows(');
foreach (['stage', 'can_probe', 'can_apply', 'can_reconcile',
'blocking_reasons', 'action_mode'] as $key) {
$assert(str_contains($workflowProjection, "'{$key}' =>"),
'Workflow projection key is missing: ' . $key);
}
foreach (['engine_unavailable', 'no_hosts', 'needs_probe', 'blocked',
'ready_to_apply', 'needs_reconcile', 'active', 'migration_required',
'recovery_required', 'operation_running'] as $stage) {
$assert(str_contains($workflowProjection, "'{$stage}'"),
'Workflow projection stage is missing: ' . $stage);
}
$assert(str_contains($workflowProjection,
"\$result('operation_running', false, true)")
&& str_contains($workflowProjection,
"['needs_reconcile', 'operation_running']")
&& !str_contains($workflowProjection,
"\$result('operation_running', false, false)"),
'A running Fabric operation must expose only explicit reconcile recovery.');
foreach (['vpc_fabric_pin_mismatch', 'vpc_fabric_mapping_missing'] as $reason) {
$assert(str_contains($workflowProjection, "'{$reason}'")
&& str_contains($script, $reason . ':'),
'VPC Fabric migration reason is missing from service/UI: ' . $reason);
}
foreach ([
'fabric_endpoint_interface_unverified',
'fabric_endpoint_interface_unsafe_or_drifted',
'fabric_endpoint_rp_filter_unverified',
] as $reason) {
$assert(str_contains($script, $reason . ':'),
'Fabric endpoint readiness reason is missing from the UI: ' . $reason);
}
foreach (['mode', 'fabric_id', 'fabric_region', 'revision', 'listen_port',
'overlay_cidr', 'host_count'] as $key) {
$assert(str_contains($workflowProjection, "'{$key}' =>"),
'Plan preview key is missing: ' . $key);
}
$assert(!str_contains($workflowProjection, "'nodes' =>")
&& !str_contains($workflowProjection, "'endpoints' =>")
&& !str_contains($workflowProjection, "'host_ids' =>"),
'Plan preview exposes raw node, endpoint or host-id arrays.');
$assert(!str_contains($service, "'private_key'")
&& !str_contains($service, "'ssh_command'")
&& !str_contains($service, "'raw_output'"),
'Fabric admin projection must not accept or expose private credentials or raw commands.');
$assert(str_contains($service,
"private const ERROR_PHASES = ['identity', 'observe', 'apply'];")
&& str_contains($service, 'private const OPERATION_KINDS')
&& str_contains($service, 'private const OPERATION_STATES')
&& str_contains($service, 'private const NODE_OPERATION_STATES')
&& str_contains($service, 'private const OPERATION_CHECKPOINTS')
&& str_contains($service, 'private const OPERATION_REASONS')
&& str_contains($service, "'operation' => self::operation(")
&& str_contains($service, "'operation' => \$fabric['operation'] ?? null")
&& str_contains($controller, "['queued', 'running']")
&& str_contains($controller, 'operationStatus($payload)')
&& str_contains($service,
"\$lastErrorPhase = self::errorPhase(\$node['last_error_phase'] ?? null)")
&& str_contains($service, "'last_error_phase' => \$lastErrorPhase")
&& str_contains($service,
"'last_error_phase' => \$observedNode['last_error_phase'] ?? null")
&& str_contains($script,
"fabric_remote_command_failed: '宿主机远程配置命令失败'")
&& str_contains($script, "identity: 'identity(身份)'")
&& str_contains($script, "observe: 'observe(回读)'")
&& str_contains($script, "apply: 'apply(应用)'")
&& str_contains($script, 'const lastErrorPhase = host.last_error_code')
&& str_contains($script, "'上次 Fabric 失败阶段:' + lastErrorPhase")
&& !str_contains($script, '本次探测失败阶段'),
'Fabric failure phases are not safely projected as persisted diagnostics.');
$assert(str_contains($script, 'operationsByRegion: new Map()')
&& str_contains($script, 'function pollOperations()')
&& str_contains($script, "api('/api/v1/admin/fabric')")
&& str_contains($script, 'operationForHost(region, host)')
&& str_contains($script, 'hostOperation.id === rootOperation.id')
&& str_contains($script, "unknown: '未知检查点'")
&& str_contains($script, "unknown: '未识别原因(已隐藏原始值)'")
&& str_contains($script, 'fabric_operation_not_found')
&& str_contains($script, 'fabric_operation_reconcile_required')
&& str_contains($script, 'fabric_operation_status_timeout')
&& str_contains($script, "'本轮 operation:'")
&& str_contains($script, "'本轮检查点:'")
&& !str_contains($script, 'operation.stderr')
&& !str_contains($script, 'operation.command')
&& !str_contains($script, 'operation.path'),
'Fabric asynchronous operations lost polling, correlation, redaction or safe labels.');
foreach ([
'journal_dispatch' => '调度事务恢复',
'journal_artifact_restore' => '恢复事务文件',
'journal_nft_restore' => '恢复 nft 规则',
'journal_runtime_restore' => '恢复宿主机运行态',
'journal_finalize' => '收尾事务恢复',
'preflight' => '执行前检查',
'preflight_sysctl' => '检查内核网络参数',
'preflight_tools' => '检查必要工具',
'preflight_artifacts' => '检查配置文件归属',
'preflight_firewall' => '检查防火墙归属',
'preflight_vpc' => '检查 VPC 状态',
'preflight_underlay' => '检查传输网络',
'preflight_routes' => '检查路由',
'preflight_persistence' => '检查持久化配置',
] as $checkpoint => $label) {
$assert(str_contains($service, "'{$checkpoint}'")
&& str_contains($script, "{$checkpoint}: '{$label}'"),
'Fabric operation checkpoint is missing from service/UI: ' . $checkpoint);
}
foreach ([
'sysctl_conflict' => '内核网络参数不符合要求',
'persistence_conflict' => '持久化配置冲突',
] as $reason => $label) {
$assert(str_contains($service, "'{$reason}'")
&& str_contains($script, "{$reason}: '{$label}'"),
'Fabric preflight reason is missing from service/UI: ' . $reason);
}
$assert(str_contains($script,
"iproute2_missing: '缺少 ip 命令(Debian 包 iproute2 / AlmaLinux 包 iproute)'")
&& str_contains($script,
"iproute2_probe_failed: 'ip 命令 JSON 能力回读无效'"),
'Host readiness must distinguish the ip command from distribution package names.');
$rpFilterFields = [
'rp_filter_all', 'rp_filter_default', 'rp_filter_default_effective',
'rp_filter_underlay_raw', 'rp_filter_underlay_effective',
'rp_filter_fabric_raw', 'rp_filter_fabric_effective',
];
foreach ($rpFilterFields as $field) {
$assert(str_contains($service, "'{$field}'")
&& str_contains($script, $field),
'The Fabric readiness projection dropped rp_filter evidence: ' . $field);
}
$assert(str_contains($script, 'function rpFilterLines(capabilities)')
&& str_contains($script,
"rp_filter_not_compatible: 'rp_filter 必要回读缺失或无效,无法安全自动配置'")
&& str_contains($script, "'rp_filter all:'")
&& str_contains($script, "'rp_filter default:'")
&& str_contains($script, "'Endpoint '")
&& str_contains($script, "'wg-fabric0:'")
&& str_contains($script,
"'策略:all/default/公网接口只读;仅平台自有 wg-fabric0 与 VPC bridge 设为 2'")
&& str_contains($script, "'(strict,自动配置将收敛为 2)'")
&& !str_contains($script, "'rp_filter:' + sysctl(capabilities.rp_filter)"),
'The administrator page still hides the interface-specific rp_filter decision.');
preg_match_all('/<button\b[^>]*>/', $template, $allButtons);
preg_match_all('/<button\b[^>]*data-fabric-primary-action\b[^>]*>/', $template, $primaryButtons);
$assert(count($allButtons[0]) === 3 && count($primaryButtons[0]) === 3
&& str_contains($template, 'id="fabric-detect-hosts"')
&& str_contains($template, '>检测宿主机')
&& str_contains($template, 'id="fabric-auto-configure"')
&& str_contains($template, '>自动配置地区私网')
&& str_contains($template, 'id="fabric-reconcile"')
&& str_contains($template, '>重新核对'),
'The normal Fabric page must expose exactly the three approved operations.');
$assert(str_contains($template, 'id="fabric-region-select"')
&& str_contains($template, '地区私网配置向导')
&& substr_count($template, 'data-fabric-wizard-step=') === 4
&& str_contains($template, 'id="fabric-wizard-blockers"')
&& str_contains($template, 'id="fabric-plan-preview-grid"')
&& str_contains($template, '服务端只读方案')
&& str_contains($template, '地区宿主机 readiness 清单')
&& str_contains($template, 'Fabric 只读回读')
&& str_contains($template, 'data-fabric-readonly-notice')
&& str_contains($template, '{if !$fabric_can_manage|default:false}disabled{/if}')
&& !str_contains($template, 'fabric-apply-form')
&& !str_contains($template, 'fabric-mapping-editor')
&& !str_contains($template, '参与宿主机 JSON')
&& !str_contains($template, '<textarea')
&& !str_contains($template, '地区到 Fabric 映射'),
'The Fabric page did not expose the four-step region wizard or retained raw plan fields.');
$assert(str_contains($script, "api('/api/v1/admin/fabric')")
&& str_contains($script, "'/api/v1/admin/fabric/regions/'")
&& str_contains($script, "{ method: 'POST', body: '{}' }")
&& str_contains($script, "headers['X-CSRF-Token']")
&& str_contains($script, 'state.selectionVersion')
&& str_contains($script, 'state.loadVersion')
&& str_contains($script, 'state.pendingAction')
&& str_contains($script, 'outcomeUnknownRegionIds: new Set()')
&& str_contains($script, 'state.outcomeUnknownRegionIds')
&& str_contains($script, 'outcomeUnknownRegionIds.has(')
&& str_contains($script, 'outcomeUnknownRegionIds.add(regionId)')
&& str_contains($script, 'outcomeUnknownRegionIds.delete(regionId)')
&& !str_contains($script, 'outcomeUnknownRegionId:')
&& str_contains($script, 'workflowOf')
&& str_contains($script, 'planPreviewOf')
&& str_contains($script, 'workflow.can_probe')
&& str_contains($script, 'workflow.can_apply')
&& str_contains($script, 'workflow.can_reconcile')
&& str_contains($script,
"action === 'reconcile' && permissions.reconcile === true")
&& str_contains($script, "state.pendingAction !== ''")
&& str_contains($script, 'actionOutcome')
&& str_contains($script, "stage === 'active'")
&& str_contains($script, 'error.outcomeUnknown === true')
&& str_contains($script, 'const allowed = !outcomeUnknown && serverAllowed')
&& str_contains($script, 'const allowed = outcomeUnknown ? false : operationIsRunning')
&& str_contains($script, 'receiptRecoveriesByRegion: new Map()')
&& str_contains($script, 'startReceiptRecovery(regionId, action, previousOperation)')
&& str_contains($script, 'receiptRecoveryMatches(recovery, observed)')
&& str_contains($script, 'const receiptRecoveryMaxReads = 36')
&& str_contains($script, 'const receiptRecoveryMaxDuration = 180000')
&& str_contains($script, "dispatched && method !== 'GET'")
&& str_contains($script, 'httpStatus >= 500 && httpStatus <= 599')
&& str_contains($script, 'applyActionProjection')
&& str_contains($script, 'originSelectionVersion')
&& str_contains($script, 'button.disabled = !canManage')
&& str_contains($script, 'payload.engine_available === false')
&& preg_match('/payload\.engine_available === false\)[\s\S]{0,500}return false;/',
$script) === 1
&& str_contains($script, "method === 'GET' ? 30000 : 240000")
&& str_contains($script, 'network_manager_expected')
&& str_contains($script, 'transport_verified')
&& str_contains($script, 'next_stage_allowed')
&& str_contains($script, 'textContent')
&& !str_contains($script, 'innerHTML')
&& !str_contains($script, '/internal/v1/')
&& !str_contains($script, "api('/api/v1/admin/fabric/apply'")
&& !str_contains($script, 'JSON.stringify({ fabric_id')
&& !str_contains($script, 'fabric-apply-form')
&& !str_contains($script, 'fabric-mapping-editor'),
'Fabric browser module lost CSRF, stale-response, duplicate-action or safe-DOM guards.');
$assert(str_contains($styles, '.fabric-wizard-steps')
&& str_contains($styles, '.fabric-plan-preview-grid')
&& preg_match("/venix_asset_version value='[0-9]+'/", $assets) === 1,
'The inline region wizard lost its responsive styles or shared cache key.');
echo "Administrator region Fabric readiness contracts passed.\n";