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

366 lines
22 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 tenant-page contract. The VPC control plane and host dataplane have
// their own tests; this protects the user-facing page from drifting away from
// the database-only bootstrap and the versioned VPC API.
$root = dirname(__DIR__);
$read = static fn (string $path): string => (string) file_get_contents($root . '/' . $path);
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$controller = $read('app/Controllers/CloudPageController.php');
$pageService = $read('app/Services/Cloud/CloudVpcPageService.php');
$middleware = $read('app/Middleware/CloudApi.php');
$routes = $read('config/routes.php');
$shell = $read('resources/views/venix/cloud/page.tpl');
$template = $read('resources/views/venix/cloud/pages/vpcs.tpl');
$sidebar = $read('resources/views/venix/user/panel_sidebar.tpl');
$app = $read('public/cloud/app.js');
$script = $read('public/cloud/vpc.js');
$styles = $read('public/cloud/vpc.css');
$controllerStart = strpos($controller, 'public function vpcs(');
$controllerEnd = strpos($controller, 'public function detail(', $controllerStart ?: 0);
$controllerSection = $controllerStart !== false && $controllerEnd !== false
? substr($controller, $controllerStart, $controllerEnd - $controllerStart) : '';
$assert($controllerSection !== ''
&& str_contains($controllerSection, 'CloudAccess::actor(false)')
&& str_contains($controllerSection, 'CloudVpcPageService::bootstrap($actor)')
&& str_contains($controllerSection, 'CloudVpcService::listing($actor)')
&& str_contains($controllerSection, "'cloud_vpc_bootstrap_json'")
&& str_contains($controllerSection, '$this->safeJson($payload)'),
'VPC page must use an owner-scoped, safe database bootstrap and the typed listing projection.');
$assert(str_contains($controller, 'use App\\Services\\Cloud\\CloudVpcPageService;')
&& str_contains($controller, "'cloud_vpc_bootstrap_json', '{}'")
&& !str_contains($controllerSection, 'CloudEngineClient')
&& !str_contains($controllerSection, 'CloudHost'),
'VPC first paint must not contact libvirt or expose host inventory.');
$assert(str_contains($pageService, 'CloudRegionFabric')
&& str_contains($pageService, "->where('cloud_region_fabrics.state', 'active')")
&& str_contains($pageService, "->where('cloud_region_fabrics.fabric_revision', '>', 0)")
&& str_contains($pageService, "->where('region.status', 'active')")
&& str_contains($pageService, "->where('user_id', \$userId)")
&& str_contains($pageService, "->where('status', 'active')")
&& str_contains($pageService, "(string) \$row->service_status === 'active'")
&& str_contains($pageService, "(int) \$row->expires_at > time()")
&& str_contains($pageService, '->limit(200)')
&& !str_contains($pageService, 'CloudEngineClient')
&& !str_contains($pageService, "'host_id'"),
'VPC bootstrap must expose only active Fabric regions and bounded owner-scoped instances.');
$assert(str_contains($routes, "\$this->get('/cloud/vpcs', 'App\\Controllers\\CloudPageController:vpcs');"),
'Authenticated user routes must expose the VPC page.');
$assert(str_contains($middleware, "^/api/v1/vpcs(?:/[0-9a-f]{32}(?:/.*)?)?\$#D")
&& str_contains($middleware, 'CloudAccess::actor(!$databaseOnly)'),
'VPC API requests must stay in the PHP/database-only auth lane.');
$assert(str_contains($sidebar, 'href="/user/cloud/vpcs"')
&& str_contains($sidebar, "panel_cloud_active_key == 'vpcs'")
&& str_contains($sidebar, 'VPC 私网'),
'The user cloud navigation must expose and mark the VPC page.');
$assert(str_contains($shell, "cloud_page == 'vpcs'")
&& str_contains($shell, "cloud/pages/vpcs.tpl")
&& str_contains($shell, '/cloud/vpc.css'),
'The cloud shell must load the dedicated VPC view and styles.');
$assert(str_contains($app, "vpcs: '/cloud/vpc.js'"),
'Cloud page module routing must load the VPC module.');
foreach ([
'vpc-create-form', 'vpc-create-name', 'vpc-create-region',
'vpc-create-modal', 'vpc-create-cancel', 'vpc-create-submit',
'vpc-create-availability', 'vpc-list', 'vpc-detail',
'vpc-list-reconcile', 'vpc-bootstrap',
] as $id) {
$assert(str_contains($template, 'id="' . $id . '"'),
'VPC view is missing required control ' . $id . '.');
}
$assert(!str_contains($template, 'id="vpc-create-cidr"')
&& !str_contains($template, 'id="vpc-create-subnet"')
&& !str_contains($template, 'id="vpc-create-max-members"')
&& !str_contains($template, '<label>网络配置</label>')
&& str_contains($template, '分配独立 /24 网段并建立唯一子网'),
'Tenant VPC create form must leave CIDR, subnet and member capacity to platform policy.');
$assert(str_contains($template, 'class="modal-backdrop vpc-create-backdrop"')
&& str_contains($template, 'role="dialog"')
&& str_contains($template, 'aria-modal="true"')
&& str_contains($template, 'aria-haspopup="dialog"')
&& str_contains($template, 'pattern="[A-Za-z0-9][A-Za-z0-9_.-]{ldelim}0,62{rdelim}"')
&& str_contains($template, 'id="vpc-create-open"')
&& str_contains($template, 'id="vpc-create-open" class="button button-primary" type="button"')
&& str_contains($template, 'disabled><span aria-hidden="true">+</span> 创建 VPC'),
'VPC creation must use an accessible modal and stay disabled until a Fabric region is available.');
$createStart = strpos($script, 'async function createVpc(');
$createEnd = strpos($script, 'async function submitMember(', $createStart ?: 0);
$createSection = $createStart !== false && $createEnd !== false
? substr($script, $createStart, $createEnd - $createStart) : '';
$assert($createSection !== ''
&& str_contains($createSection, 'name: form.name.value.trim()')
&& str_contains($createSection, 'region_id: Number(form.region_id.value)')
&& str_contains($createSection, 'body.request_key = form.dataset.requestKey')
&& !str_contains($createSection, 'form.cidr')
&& !str_contains($createSection, 'form.subnet_cidr')
&& !str_contains($createSection, 'form.max_members'),
'Tenant create JavaScript must submit only name, region and the idempotency key.');
$createValidation = strpos($createSection, 'if (!form.checkValidity())');
$createPollStop = strpos($createSection, 'clearTimeout(state.pollTimer)');
$assert($createValidation !== false && $createPollStop !== false
&& $createValidation < $createPollStop,
'An invalid create form must not stop VPC status polling.');
$assert(str_contains($script, 'function openCreateModal()')
&& str_contains($script, 'function closeCreateModal(')
&& str_contains($script, 'function closeCreateModal(resetIntent = false')
&& str_contains($script, 'function hasPendingCreateIntent(')
&& str_contains($script, 'if (!hasPendingCreateIntent(form))')
&& str_contains($script, 'resetCreateIntent(form)')
&& str_contains($script, "event.key === 'Escape'")
&& str_contains($script, "event.key !== 'Tab'")
&& str_contains($script, "event.target === byId('vpc-create-modal')")
&& str_contains($script, 'state.createFocusReturn = document.activeElement')
&& str_contains($script, 'returnTarget.focus()')
&& str_contains($script, 'open.disabled = true')
&& str_contains($script, 'submit.disabled = true'),
'VPC create modal must support backdrop/Escape closing, focus restoration/trapping and no-region disabling.');
foreach (['成员与私网 IP', 'Route', 'VPC ACL', '最近操作'] as $label) {
$assert(str_contains($script, $label),
'VPC module is missing section ' . $label . '.');
}
$memberRenderStart = strpos($script, 'function renderMembers(');
$memberRenderEnd = strpos($script, 'function routeRow(', $memberRenderStart ?: 0);
$memberRender = $memberRenderStart !== false && $memberRenderEnd !== false
? substr($script, $memberRenderStart, $memberRenderEnd - $memberRenderStart) : '';
$memberSubmitStart = strpos($script, 'async function submitMember(');
$memberSubmitEnd = strpos($script, 'function readRoutes(', $memberSubmitStart ?: 0);
$memberSubmit = $memberSubmitStart !== false && $memberSubmitEnd !== false
? substr($script, $memberSubmitStart, $memberSubmitEnd - $memberSubmitStart) : '';
$assert(!str_contains($script, 'function renderSubnets(')
&& !str_contains($script, '子网与 CIDR')
&& !str_contains($script, 'value.subnets')
&& !str_contains($template, '查看子网、成员'),
'The platform-managed subnet must not be exposed as a tenant management panel.');
$assert($memberRender !== '' && $memberSubmit !== ''
&& !str_contains($memberRender, "name = 'subnet_key'")
&& !str_contains($memberRender, "name = 'private_ip'")
&& str_contains($memberSubmit, 'const instanceId = Number(form.instance_id.value)')
&& str_contains($memberSubmit, 'instance_id: instanceId')
&& str_contains($memberSubmit, "request_key: requestKey('member-add')")
&& !str_contains($memberSubmit, 'subnet_key')
&& !str_contains($memberSubmit, 'private_ip'),
'Tenant member attach must submit only the instance and idempotency key.');
$memberChoiceStart = strpos($script, 'function memberChoice(');
$memberChoiceEnd = strpos($script, 'function renderMembers(', $memberChoiceStart ?: 0);
$memberChoices = $memberChoiceStart !== false && $memberChoiceEnd !== false
? substr($script, $memberChoiceStart, $memberChoiceEnd - $memberChoiceStart) : '';
$assert(str_contains($memberChoices, "new Option('请选择同地区实例', '', true, true)")
&& str_contains($memberChoices, '!Number.isInteger(regionId) || regionId <= 0')
&& str_contains($memberChoices, 'regionId === Number(doc?.vpc?.region_id)')
&& str_contains($memberChoices, '地区待核验,暂不可加入')
&& str_contains($memberChoices, "attachment?.state !== 'available'")
&& str_contains($memberChoices, '已加入 VPC:')
&& str_contains($memberSubmit, 'memberChoice(row, state.selected)'),
'Tenant member choices must fail closed when the instance region is missing or mismatched.');
$assert(str_contains($template, '创建 VPC'),
'VPC view is missing the create form.');
$assert(str_contains($script, "'/api/v1/vpcs'")
&& str_contains($script, '/members')
&& str_contains($script, '/reconcile')
&& str_contains($script, "kind === 'routes'")
&& str_contains($script, ": 'acl'")
&& str_contains($script, "'DELETE'")
&& str_contains($script, "'PUT'")
&& !str_contains($script, '/subnets')
&& !str_contains($script, 'submitSubnet(')
&& !str_contains($script, 'removeSubnet(')
&& !str_contains($script, "requestKey('subnet-add')")
&& !str_contains($script, "requestKey('subnet-remove')"),
'VPC module must cover root/member/policy APIs without exposing subnet mutation.');
$assert(str_contains($script, "remove.dataset.vpcAction = 'delete'")
&& str_contains($script, 'async function deleteVpc()')
&& str_contains($script, "requestKey('vpc-delete')")
&& str_contains($script, 'confirmation_name: root.name')
&& str_contains($script, "'DELETE'")
&& str_contains($script, 'selectedRootDeleting()')
&& str_contains($script, 'lockDeletingDetail(container, reconcile)')
&& str_contains($script, 'finishVpcDeletion()')
&& str_contains($script, "rootStatus(item) !== 'deleted'")
&& str_contains($script,
'state.vpcs = state.vpcs.filter(item => item?.vpc_key !== deletedKey)')
&& str_contains($script, "state.selectedKey = ''"),
'VPC root deletion must require an exact-name confirmation, lock mutations and clear completed selections.');
$assert(str_contains($script, 'Absence from it is not a')
&& !str_contains($script, 'const deletionCompleted =')
&& !str_contains($script, "error?.status === 404 && key === state.selectedKey"),
'A bounded list omission or detail 404 must not be treated as a VPC deletion receipt.');
$deletingProjection = strpos($script, "if (raw === 'deleting') return 'deleting';");
$failedProjection = strpos($script, "if (raw === 'degraded' || sync === 'failed')");
$assert($deletingProjection !== false && $failedProjection !== false
&& $deletingProjection < $failedProjection,
'A deleting root must stay a locked tombstone when engine sync is failed or uncertain.');
$assert(str_contains($script, 'X-CSRF-Token')
&& str_contains($script, 'credentials: \'same-origin\'')
&& str_contains($script, 'request_key')
&& str_contains($script, 'function entityKey()')
&& str_contains($script, 'route_key: row.dataset.routeKey')
&& str_contains($script, 'rule_key: row.dataset.aclKey'),
'VPC mutations must use same-origin CSRF protection and separate idempotency/entity keys.');
foreach (['awaiting_members', 'applying', 'degraded', 'uncertain', 'waiting', 'active', 'suspended',
'deleting'] as $status) {
$assert(str_contains($script, $status),
'VPC UI lost state projection for ' . $status . '.');
}
$assert(str_contains($script, 'usable === true')
&& str_contains($script, 'desired_revision')
&& str_contains($script, 'observed_revision')
&& str_contains($script, 'setTimeout')
&& str_contains($script, 'visibilitychange')
&& str_contains($script, 'AbortController')
&& str_contains($script, 'loadDetail(state.selectedKey, true)')
&& str_contains($script, 'state.detailDirty')
&& str_contains($script, 'allowDirty = false'),
'VPC UI must poll desired/observed state, pause hidden tabs and only show active after usable readback.');
$detailInputStart = strpos($script, 'function handleDetailInput(');
$detailInputEnd = strpos($script, 'function readBootstrap(', $detailInputStart ?: 0);
$detailInput = $detailInputStart !== false && $detailInputEnd !== false
? substr($script, $detailInputStart, $detailInputEnd - $detailInputStart) : '';
$assert($detailInput !== ''
&& str_contains($detailInput, "#vpc-route-editor, #vpc-acl-editor")
&& !str_contains($detailInput, "closest('#vpc-detail')"),
'Selecting a member must not mark route/ACL drafts dirty.');
$assert(str_contains($script, "vpc_no_participating_hosts:")
&& str_contains($script, "setup_state || '').toLowerCase() === 'awaiting_members'")
&& str_contains($script, "projectionFieldKnown(root, 'setup_state')")
&& str_contains($script, 'setup_state_known: setupStateKnown')
&& str_contains($script, 'member_count_known: memberCountKnown')
&& str_contains($script, "!['active', 'awaiting_members'].includes(projectedStatus(item))")
&& str_contains($script, "status === 'awaiting_members'")
&& str_contains($script, "if (rootStatus(state.selected?.vpc) === 'awaiting_members' && !hasMemberCleanup())")
&& str_contains($script, "needsPolling() ? 8000 : 30000"),
'Empty VPCs must avoid reconcile unless legacy member cleanup needs proof-based release.');
$assert(str_contains($script, "element('details', `vpc-disclosure")
&& str_contains($script, "disclosure('高级网络策略'")
&& str_contains($script, "disclosure('同步与诊断'")
&& str_contains($script, "field('目标 revision'")
&& str_contains($script, "field('最近错误代码'")
&& str_contains($script, 'const policyAvailable = hasPolicyMember(doc)')
&& str_contains($script, 'if (!policyAvailable)')
&& str_contains($script, '添加首个实例并生成数据面后')
&& str_contains($script, 'advanced.body.append(renderRoutes(doc), renderAcl(doc))')
&& str_contains($script, 'diagnostics.body.append(diagnosticFacts, renderOperations(doc))'),
'Members must remain primary while policies and raw synchronization diagnostics stay collapsed.');
$renderDetailStart = strpos($script, 'function renderDetail()');
$renderDetailEnd = strpos($script, 'function renderMembers(', $renderDetailStart ?: 0);
$renderDetail = $renderDetailStart !== false && $renderDetailEnd !== false
? substr($script, $renderDetailStart, $renderDetailEnd - $renderDetailStart) : '';
$assert($renderDetail !== ''
&& str_contains($renderDetail, "container.dataset.vpcKey === root.vpc_key")
&& str_contains($renderDetail, "container.querySelector('.vpc-advanced')?.open")
&& str_contains($renderDetail, "container.querySelector('.vpc-diagnostics')?.open")
&& str_contains($renderDetail, "container.querySelector('#vpc-member-instance')?.value")
&& str_contains($renderDetail, 'memberSelect.value = previousView.memberInstance'),
'Status redraws must preserve disclosure state and a still-eligible member choice.');
$saveEditorStart = strpos($script, 'async function saveEditor(');
$saveEditorEnd = strpos($script, 'async function reconcile(', $saveEditorStart ?: 0);
$saveEditor = $saveEditorStart !== false && $saveEditorEnd !== false
? substr($script, $saveEditorStart, $saveEditorEnd - $saveEditorStart) : '';
$assert($saveEditor !== ''
&& str_contains($saveEditor, 'if (!hasPolicyMember())')
&& str_contains($saveEditor, '有可用成员后才可保存 Route 或 ACL'),
'Policy writes must fail closed whenever the current detail has no usable member.');
$assert(str_contains($script, 'data-vpc-tombstone-state="deleting"')
&& str_contains($script, 'pendingTombstones')
&& str_contains($script, 'function memberChoice(')
&& str_contains($script, "attachment?.state !== 'available'")
&& str_contains($script, 'populateMemberChoices(instance.control, doc)')
&& str_contains($script, 'option.disabled')
&& str_contains($script, 'requestFingerprint')
&& str_contains($script, 'confirmDetailMutation'),
'VPC editors must preserve dirty drafts, block only in-flight tombstones and constrain member choices.');
$assert(!str_contains($script, '/internal/v1/')
&& !str_contains($script, 'host_id')
&& !str_contains($script, 'credential_cipher'),
'Tenant VPC JavaScript must not call private engine endpoints or expose host credentials.');
$assert(str_contains($script, 'async function refreshBootstrap(')
&& str_contains($script, "headers: new Headers({ Accept: 'text/html' })")
&& str_contains($script, "page.getElementById('vpc-bootstrap')")
&& str_contains($script, 'applyBootstrapPayload(payload, false)')
&& str_contains($script, 'async function refreshWorkspace()')
&& str_contains($script, 'const epoch = ++state.refreshEpoch')
&& str_contains($script, 'Promise.all([')
&& str_contains($script, 'refreshBootstrap(true)')
&& str_contains($script, 'state.bootstrapController?.abort()'),
'Manual refresh must safely refresh current Fabric regions and instance candidates alongside VPC state.');
$cancelStart = strpos($script, 'function cancelReadbacks()');
$cancelEnd = strpos($script, 'function hasPolicyMember(', $cancelStart ?: 0);
$cancelBlock = ($cancelStart !== false && $cancelEnd !== false)
? substr($script, $cancelStart, $cancelEnd - $cancelStart) : '';
$assert($cancelBlock !== ''
&& str_contains($cancelBlock, 'state.refreshEpoch += 1')
&& str_contains($cancelBlock, 'state.bootstrapEpoch += 1')
&& str_contains($cancelBlock, 'state.listEpoch += 1')
&& str_contains($cancelBlock, 'state.detailEpoch += 1')
&& str_contains($cancelBlock, 'state.bootstrapController?.abort()')
&& str_contains($cancelBlock, 'state.listController?.abort()')
&& str_contains($cancelBlock, 'state.detailController?.abort()'),
'Mutations must invalidate and abort every in-flight read generation.');
$selectStart = strpos($script, 'async function selectVpc(');
$selectEnd = strpos($script, 'async function applyDocument(', $selectStart ?: 0);
$selectBlock = ($selectStart !== false && $selectEnd !== false)
? substr($script, $selectStart, $selectEnd - $selectStart) : '';
$assert($selectBlock !== ''
&& str_contains($selectBlock, 'state.selected = null')
&& str_contains($selectBlock, "byId('vpc-detail-panel').hidden = true")
&& str_contains($selectBlock, 'detail.replaceChildren()')
&& str_contains($selectBlock, 'delete detail.dataset.vpcKey'),
'Switching VPCs must hide stale details until the selected document is read back.');
$createStart = strpos($script, 'async function createVpc(');
$createEnd = strpos($script, 'async function submitMember(', $createStart ?: 0);
$createBlock = ($createStart !== false && $createEnd !== false)
? substr($script, $createStart, $createEnd - $createStart) : '';
$assert($createBlock !== ''
&& str_contains($createBlock, 'if (!confirmDetailMutation()) return')
&& str_contains($createBlock, 'cancelReadbacks()')
&& str_contains($createBlock, 'let acknowledged = false')
&& str_contains($createBlock, 'acknowledged = true')
&& str_contains($createBlock,
'if (acknowledged && state.selected) renderDetail()')
&& !str_contains($createBlock,
'if (!acknowledged && state.selected) renderDetail()'),
'Create must protect dirty drafts, redraw enabled controls after success and preserve drafts after failure.');
$pollStart = strpos($script, 'function schedulePoll(');
$pollEnd = strpos($script, 'function renderSummary(', $pollStart ?: 0);
$pollBlock = ($pollStart !== false && $pollEnd !== false)
? substr($script, $pollStart, $pollEnd - $pollStart) : '';
$assert($pollBlock !== ''
&& str_contains($pollBlock, 'await Promise.all([loadList(true), refreshBootstrap(true)])')
&& str_contains($pollBlock,
"if (state.stopped || state.busy || document.visibilityState === 'hidden')")
&& str_contains($pollBlock, 'await loadDetail(state.selectedKey, true)')
&& str_contains($pollBlock, 'if (state.busy) { schedulePoll(1500); return; }')
&& str_contains($script, 'function selectedDocumentCurrent()')
&& str_contains($script, 'if (!selectedDocumentCurrent())'),
'Polling and mutations must reject stale selected documents and stop across busy transitions.');
$assert(str_contains($styles, '.vpc-state-pill')
&& str_contains($styles, '.vpc-columns')
&& str_contains($styles,
'.vpc-member-form{grid-template-columns:repeat(2,minmax(0,1fr))}')
&& str_contains($styles, '.vpc-state-pill.awaiting_members')
&& str_contains($styles, '.vpc-create-backdrop')
&& str_contains($styles, '.vpc-setup-steps')
&& str_contains($styles, '.vpc-disclosure')
&& !str_contains($styles,
'.vpc-member-form{grid-template-columns:repeat(4,minmax(0,1fr))}')
&& str_contains($styles, '@media'),
'VPC page needs dedicated state/list/detail responsive styling.');
echo "Tenant VPC page, API wiring and state-polling contract passed.\n";