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

317 lines
20 KiB
PHP

<?php
// Static regression contract for deployment/reinstall first paint. The HTML
// response owns all data needed to draw the form; JavaScript only hydrates
// interactions and must not briefly replace the catalog with loading states.
$root = dirname(__DIR__);
$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) {
return '';
}
$limit = strpos($source, $end, $offset + strlen($start));
return $limit === false ? substr($source, $offset)
: substr($source, $offset, $limit - $offset);
};
$controller = file_get_contents($root . '/app/Controllers/CloudPageController.php');
$apiController = file_get_contents($root . '/app/Controllers/CloudApiController.php');
$service = file_get_contents($root . '/app/Services/Cloud/CloudDeploymentPageService.php');
$deployTemplate = file_get_contents($root . '/resources/views/venix/cloud/pages/deploy.tpl');
$reinstallTemplate = file_get_contents($root . '/resources/views/venix/cloud/pages/reinstall.tpl');
$deployModule = file_get_contents($root . '/public/cloud/deploy.js');
$reinstallModule = file_get_contents($root . '/public/cloud/reinstall.js');
$runtime = file_get_contents($root . '/public/cloud/runtime.js');
$cloudStyles = file_get_contents($root . '/public/cloud/styles.css');
$routes = file_get_contents($root . '/config/routes_cloud.php');
$cloudShell = file_get_contents($root . '/resources/views/venix/cloud/page.tpl');
$layoutAssets = file_get_contents($root . '/resources/views/venix/layout_assets.tpl');
$deployController = $section($controller, 'public function deploy(',
'public function isoImages(');
$reinstallController = $section($controller, 'public function reinstall(',
'private function render(');
$openCreate = $section($runtime, 'async function openCreate(',
'async function loadGlobalTemplates(');
$openReinstall = $section($runtime, 'async function openReinstall(',
'async function pollJob(');
$selectRegion = $section($runtime, 'async function selectRegion(',
'async function selectLine(');
$selectLine = $section($runtime, 'async function selectLine(',
'async function selectOffer(');
$selectOffer = $section($runtime, 'async function selectOffer(',
'async function openCreate(');
$updateCreateAvailability = $section($runtime, 'function updateCreateAvailability(',
'function strongPassword(');
$renderOfferPicker = $section($runtime, 'function renderOfferPicker(',
'async function selectRegion(');
$buy = $section($runtime, 'async function buy(',
'function clearReinstallPasswordCard(');
$saleCatalog = $section($service, 'public static function saleCatalog(',
'public static function sshKeys(');
$publicOfferDto = $section($saleCatalog, '$offers[] = [', ' ];');
$catalogApi = $section($apiController, 'public function catalog(',
'public function orders(');
$resourcesApi = $section($apiController, 'public function resources(',
'private function userIsoWriteActor(');
$sshKeyOptions = $section($controller, 'private function sshKeyOptions(',
'private function reinstallVm(');
$assert(str_contains($deployController, 'CloudAccess::actor(false)')
&& str_contains($deployController, 'CloudDeploymentPageService::saleCatalog()')
&& str_contains($deployController, "'regions' => \$regions")
&& str_contains($deployController, "'lines' => \$lines")
&& str_contains($deployController, "'offers' => \$offers")
&& str_contains($deployController, "'lines_enabled' => \$linesEnabled")
&& str_contains($deployController, 'CloudDeploymentPageService::templateCatalogForPage($actor)')
&& str_contains($deployController, '$this->sshKeyOptions((int) $actor[\'user_id\'])')
&& str_contains($deployController,
'$defaultRegionId = $regions === [] ? 0 : (int) $regions[0][\'id\']')
&& str_contains($deployController, "'default_line_id' => \$defaultLineId")
&& str_contains($deployController, "'catalog_unavailable' => \$catalogUnavailable")
&& str_contains($deployController,
"'cloud_deploy_catalog_unavailable' => \$catalogUnavailable")
&& str_contains($deployController, "'cloud_deploy_bootstrap_json' => \$this->safeJson(\$payload)"),
'Deployment controller must build one complete, actor-scoped first-paint payload.');
$assert(str_contains($sshKeyOptions, "'id' => \$key['id']")
&& str_contains($sshKeyOptions, "'name' => \$key['name']")
&& str_contains($sshKeyOptions, "'fingerprint' => \$key['fingerprint']")
&& str_contains($sshKeyOptions, 'CloudDeploymentPageService::sshKeys($userId)')
&& !str_contains($sshKeyOptions, "'public_key'")
&& !str_contains($sshKeyOptions, "'created_at'"),
'Deployment bootstraps must expose only safe SSH key display metadata.');
$assert(str_contains($deployTemplate, 'class="mdi mdi-key-variant ssh-key-choice-icon"')
&& str_contains($deployTemplate, 'class="ssh-key-choice-fingerprint"')
&& str_contains($deployTemplate, 'class="ssh-key-choice-check"')
&& str_contains($deployTemplate, ',指纹 {$key.fingerprint|escape:"html"}')
&& str_contains($reinstallTemplate, 'class="mdi mdi-key-variant ssh-key-choice-icon"')
&& str_contains($reinstallTemplate, 'class="ssh-key-choice-fingerprint"')
&& str_contains($reinstallTemplate, 'class="ssh-key-choice-check"')
&& str_contains($reinstallTemplate, ',指纹 {$key.fingerprint|escape:"html"}'),
'Deployment and reinstall first paint must render the compact SSH key picker consistently.');
$assert(str_contains($saleCatalog, "->join('shop as plan'")
&& str_contains($saleCatalog, "->join('cloud_resource_pools as pool'")
&& str_contains($saleCatalog, "->join('cloud_network_lines as line'")
&& str_contains($saleCatalog, "->join('cloud_regions as region'")
&& !str_contains($saleCatalog, "->where('offer.stock', '<>', 0)")
&& str_contains($saleCatalog, "->where('offer.currency', 'USD')")
&& str_contains($saleCatalog, "\$query->where('line.is_default', 1)")
&& str_contains($saleCatalog, "'lines_enabled' => \$linesEnabled")
&& str_contains($saleCatalog, "'currency' => 'USD'")
&& str_contains($publicOfferDto, "'sellable' =>")
&& str_contains($saleCatalog, "'traffic_tib' => self::formatDecimalUnit(\$trafficGiB, 1024, 10)")
&& str_contains($service, 'private static function formatDecimalUnit(')
&& !str_contains($publicOfferDto, "'host_id' =>")
&& !str_contains($publicOfferDto, "'plan_id' =>")
&& !str_contains($publicOfferDto, "'resource_pool_id' =>")
&& !str_contains($publicOfferDto, "'public_ip' =>")
&& !str_contains($publicOfferDto, "'capacity' =>"),
'Public sale catalog must retain sold-out offers with a sellable flag, enforce the default-line switch and omit placement or capacity details.');
$assert(str_contains($service, 'CloudTemplateCatalogService::publicCatalog()')
&& str_contains($service, "'catalog_stale' => false")
&& str_contains($service, "'catalog_unavailable' => false")
&& !str_contains($service, 'Configurations::where(')
&& str_contains($service, 'foreach (self::sanitizeTemplates($templates)')
&& str_contains($service, "\$id = \$value['id'] ?? null")
&& str_contains($service, "\$family = \$value['os_family'] ?? ''")
&& str_contains($service, "'id' => \$id")
&& str_contains($service, "'os_family' => trim(\$family)")
&& str_contains($service, "'os_version' => \$version"),
'The first-paint image catalog must use the durable PHP catalog and a sanitized public DTO.');
$assert(str_contains($deployTemplate, 'id="deploy-bootstrap" type="application/json"')
&& str_contains($deployTemplate, '{$cloud_deploy_bootstrap_json nofilter}')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_regions as $region}')
&& str_contains($deployTemplate, 'data-region-id="{$region.id|escape:"html"}"')
&& str_contains($deployTemplate, '{if !empty($cloud_deploy_lines_enabled)}')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_lines as $line}')
&& str_contains($deployTemplate, 'data-line-id="{$line.id|escape:"html"}"')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_offers as $offer}')
&& str_contains($deployTemplate, 'data-offer-id="{$offer.id|escape:"html"}"')
&& str_contains($deployTemplate, '{$offer.traffic_tib|escape:"html"} TB')
&& str_contains($deployTemplate, '${$offer.price|escape:"html"} USD')
&& str_contains($deployTemplate, 'USD</strong>')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_template_groups as $group}')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_ssh_keys as $key}')
&& str_contains($deployTemplate, '$cloud_deploy_catalog_unavailable')
&& str_contains($deployTemplate, '系统镜像目录暂时无法读取')
&& !str_contains($deployTemplate, '请先选择地区')
&& !str_contains($deployTemplate, '正在加载')
&& !str_contains($deployTemplate, 'host_id')
&& !str_contains($deployTemplate, 'plan_id'),
'Deployment HTML must immediately show regions, optional lines, offers, images and saved keys without host identities.');
$assert(str_contains($deployTemplate,
'class="offer-option{if empty($offer.sellable)} is-sold-out{/if}"')
&& str_contains($deployTemplate,
'aria-disabled="{if empty($offer.sellable)}true{else}false{/if}"')
&& str_contains($deployTemplate, '{if empty($offer.sellable)} disabled{/if}')
&& str_contains($deployTemplate, 'class="offer-option-status">暂时售罄</span>')
&& str_contains($deployTemplate, ',暂时售罄{else}选择实例规格')
&& str_contains($cloudStyles, '.offer-option.is-sold-out')
&& str_contains($cloudStyles, '.offer-option-status')
&& str_contains($cloudStyles, '.offer-option.is-sold-out::after{display:none}'),
'Deployment SSR must keep sold-out offers visible, labelled and non-interactive on desktop and mobile.');
$assert(str_contains($deployModule, "readBootstrap('deploy-bootstrap')")
&& str_contains($deployModule, "initializeSession('create', bootstrap?.user)")
&& str_contains($deployModule, 'openCreate(bootstrap)')
&& !str_contains($deployModule, '/api/v1/session')
&& !str_contains($deployModule, '/api/v1/plans')
&& !str_contains($deployModule, '/api/v1/resources')
&& !str_contains($deployModule, '/api/v1/ssh-keys'),
'Deployment page initialization must hydrate embedded data without a second data request.');
$assert(str_contains($routes,
'$this->get(\'/catalog\', \'App\\Controllers\\CloudApiController:catalog\');')
&& !str_contains($routes, '$this->get(\'/plans\'')
&& !str_contains($apiController, 'public function plans(')
&& str_contains($openCreate, "api('/api/v1/catalog')")
&& !str_contains($runtime, '/api/v1/plans')
&& !str_contains($runtime, 'payload?.plans'),
'The public sale catalog must use only the catalog endpoint and response contract.');
$deployHydrationEnd = strpos($openCreate, ' return;');
$deployFallback = strpos($openCreate, 'Promise.allSettled([');
$assert($openCreate !== ''
&& str_contains($openCreate, 'Array.isArray(bootstrap.offers)')
&& str_contains($openCreate, 'Array.isArray(bootstrap.regions)')
&& str_contains($openCreate, 'Array.isArray(bootstrap.lines)')
&& str_contains($openCreate, 'Array.isArray(bootstrap.templates)')
&& str_contains($openCreate, 'applySaleCatalog(bootstrap)')
&& str_contains($openCreate, 'bootstrap.catalog_unavailable === true')
&& str_contains($runtime, 'catalog?.default_region_id')
&& str_contains($runtime, 'catalog?.default_line_id')
&& str_contains($openCreate, "renderTemplateCatalog('vm-template')")
&& $deployHydrationEnd !== false && $deployFallback !== false
&& $deployHydrationEnd < $deployFallback
&& !str_contains(substr($openCreate, 0, $deployHydrationEnd), "api('/api/v1/"),
'Deployment hydration must select the requested/first region and line and paint all data before any fallback.');
$assert($selectRegion !== '' && $selectLine !== '' && $selectOffer !== ''
&& !str_contains($selectRegion, 'resetInstallChoices()')
&& !str_contains($selectRegion, 'renderTemplateCatalog(')
&& !str_contains($selectRegion, 'loadGlobalTemplates(')
&& !str_contains($selectRegion, "byId('vm-template').value")
&& !str_contains($selectLine, 'resetInstallChoices()')
&& !str_contains($selectLine, 'renderTemplateCatalog(')
&& !str_contains($selectLine, 'loadGlobalTemplates(')
&& !str_contains($selectLine, "byId('vm-template').value")
&& !str_contains($selectOffer, 'resetInstallChoices()')
&& !str_contains($selectOffer, 'renderTemplateCatalog(')
&& !str_contains($selectOffer, 'loadGlobalTemplates(')
&& str_contains($buy, 'offer_id: Number(byId(\'vm-offer\').value)')
&& !str_contains($buy, 'plan_id:')
&& str_contains($buy, 'provisionInvoiceFingerprint(body)')
&& str_contains($buy, 'pendingProvisionInvoiceKey(fingerprint)'),
'Changing a region, line or offer must preserve the global image and purchasing must keep offer-scoped idempotency.');
$assert(!str_contains($buy, 'confirm(')
&& !str_contains($buy, 'toast(')
&& !str_contains($buy, 'purchaseSummary')
&& !str_contains($runtime, 'function offerBillingLabel(')
&& str_contains($buy, 'if (state.mutationBusy) return;')
&& str_contains($buy, "byId('create-submit').disabled = true")
&& str_contains($buy, 'existingProvisionInvoice(invoiceIdempotency)')
&& substr_count($buy,
'navigate(`${CLOUD_PATHS.invoices}/${encodeURIComponent(String(invoiceId))}`)') === 2,
'Instance creation must skip confirmation and success cards while retaining guarded invoice reconciliation and direct navigation.');
$assert(str_contains($runtime,
'function isOfferSellable(offer) { return offer?.sellable === true; }')
&& str_contains($renderOfferPicker,
"if (!sellable) name.append(makeElement('span', 'offer-option-status', '暂时售罄'));")
&& str_contains($renderOfferPicker, "button.classList.toggle('is-sold-out', !sellable)")
&& str_contains($renderOfferPicker, 'button.disabled = !sellable')
&& str_contains($renderOfferPicker,
"button.setAttribute('aria-disabled', String(!sellable))")
&& str_contains($renderOfferPicker,
'offers.some(offer => String(offer.id) === selectedOfferId && isOfferSellable(offer))')
&& str_contains($selectOffer, 'if (!isOfferSellable(offer)) return;')
&& str_contains($updateCreateAvailability, '!isOfferSellable(offer)')
&& str_contains($buy, 'if (!isOfferSellable(selectedOffer))')
&& str_contains($buy, '该实例规格暂时售罄,请选择其他规格。'),
'Hydration and fallback rendering must never select, enable or submit a sold-out offer.');
$assert(str_contains($catalogApi, 'CloudDeploymentPageService::saleCatalog()')
&& str_contains($resourcesApi, 'CloudDeploymentPageService::freshTemplateCatalog($actor)')
&& !str_contains($resourcesApi, "\$query['plan_id']")
&& !str_contains($resourcesApi, "['host_id']")
&& str_contains($resourcesApi, 'CloudAccess::instance($query[\'vm_id\'], $actor)')
&& str_contains($resourcesApi, 'return $this->json($response, $templatePayload);')
&& !str_contains($resourcesApi, 'storage_available_gib')
&& !str_contains($resourcesApi, "'GET', 'resources'"),
'Catalog APIs must return global images and never expose a plan-derived or VM host identifier.');
$assert(str_contains($runtime, 'return `$${amount.toFixed(2)} USD`;')
&& str_contains($runtime, 'formatTrafficTiB(offer.traffic_tib)')
&& str_contains($runtime, "amount.toFixed(10).replace(/\\.?0+\$/, '')")
&& !str_contains($runtime, "amount.toLocaleString('en-US', { minimumFractionDigits: 2"),
'SSR and hydration must use the same fixed USD and trimmed ten-decimal TiB text.');
$assert(str_contains($reinstallController, 'CloudAccess::actor(false)')
&& str_contains($reinstallController, 'CloudInstancePageService::detailForActor($actor, $vmId)')
&& str_contains($reinstallController, '$vm = $this->reinstallVm($vm)')
&& str_contains($reinstallController, 'CloudDeploymentPageService::templateCatalogForPage($actor)')
&& str_contains($reinstallController, '$this->sshKeyOptions((int) $actor[\'user_id\'])')
&& str_contains($reinstallController, "'catalog_unavailable' => \$catalogUnavailable")
&& str_contains($reinstallController,
"'cloud_reinstall_catalog_unavailable' => \$catalogUnavailable")
&& str_contains($reinstallController, "'cloud_reinstall_bootstrap_json' => \$this->safeJson(\$payload)"),
'Reinstall controller must embed an owner-scoped VM plus its image and key choices.');
$assert(str_contains($reinstallTemplate, 'id="reinstall-bootstrap" type="application/json"')
&& str_contains($reinstallTemplate, '{$cloud_reinstall_bootstrap_json nofilter}')
&& str_contains($reinstallTemplate, '$cloud_reinstall_vm.name')
&& str_contains($reinstallTemplate, '{foreach $cloud_reinstall_template_groups as $group}')
&& str_contains($reinstallTemplate, '{foreach $cloud_reinstall_ssh_keys as $key}')
&& str_contains($reinstallTemplate, '$cloud_reinstall_catalog_unavailable')
&& str_contains($reinstallTemplate, '系统镜像目录暂时无法读取')
&& !str_contains($reinstallTemplate, '正在加载'),
'Reinstall HTML must immediately show the VM, image catalog and saved keys.');
$assert(str_contains($reinstallTemplate, '$cloud_reinstall_vm.can_operate')
&& str_contains($reinstallTemplate, 'inert aria-disabled="true"')
&& str_contains($reinstallTemplate, '当前不能重装系统')
&& str_contains($openReinstall, "byId('reinstall-submit').disabled = true"),
'A policy-blocked instance must expose reinstall information without an actionable destructive form.');
$assert(str_contains($reinstallModule, "readBootstrap('reinstall-bootstrap')")
&& str_contains($reinstallModule, "initializeSession('reinstall', bootstrap?.user)")
&& str_contains($reinstallModule,
'selectVmByApiId(document.body.dataset.vmId || \'\', bootstrap?.vm)')
&& str_contains($reinstallModule, 'openReinstall(vm, bootstrap)')
&& !str_contains($reinstallModule, '/api/v1/session')
&& !str_contains($reinstallModule, '/api/v1/vms')
&& !str_contains($reinstallModule, '/api/v1/resources')
&& !str_contains($reinstallModule, '/api/v1/ssh-keys'),
'Reinstall initialization must use embedded VM/catalog data without initial data APIs.');
$reinstallBootstrapStart = strpos($openReinstall,
'if (bootstrap && Array.isArray(bootstrap.templates))');
$reinstallHydrationEnd = $reinstallBootstrapStart === false ? false
: strpos($openReinstall, ' return;', $reinstallBootstrapStart);
$reinstallFallback = strpos($openReinstall, 'api(`/api/v1/resources?vm_id=');
$assert($openReinstall !== ''
&& str_contains($openReinstall, 'Array.isArray(bootstrap.templates)')
&& str_contains($openReinstall, 'bootstrap.catalog_unavailable === true')
&& str_contains($openReinstall, "bootstrapItems(bootstrap, 'ssh_keys', 'keys')")
&& str_contains($openReinstall, "renderTemplateCatalog('reinstall-template')")
&& str_contains($openReinstall, "renderKeyCards('reinstall')")
&& $reinstallHydrationEnd !== false && $reinstallFallback !== false
&& $reinstallHydrationEnd < $reinstallFallback
&& !str_contains(substr($openReinstall, 0, $reinstallHydrationEnd), '/api/v1/resources'),
'Reinstall hydration must paint embedded choices before its compatibility fallback.');
$assert(str_contains($controller, 'JSON_HEX_TAG')
&& str_contains($controller, "'csrf_token' => AdminCsrf::token()")
&& str_contains($controller, "withHeader('Cache-Control', 'private, no-store')"),
'Embedded deployment data must remain script-safe, authenticated and non-cacheable.');
$assert(preg_match("/venix_asset_version value='[0-9]+'/", $layoutAssets) === 1
&& str_contains($cloudShell, "{include file='layout_assets.tpl'}")
&& str_contains($cloudShell, '?v={$venix_asset_version}')
&& str_contains($cloudShell, 'data-asset-version="{$venix_asset_version|escape:"html"}"')
&& str_contains($deployModule,
"const assetVersion = new URL(import.meta.url).searchParams.get('v');")
&& str_contains($deployModule, "runtimeUrl.searchParams.set('v', assetVersion)")
&& str_contains($reinstallModule,
"const assetVersion = new URL(import.meta.url).searchParams.get('v');")
&& str_contains($reinstallModule, "runtimeUrl.searchParams.set('v', assetVersion)"),
'Cloud page and dynamically imported runtime assets must share one cache-busting version.');
echo "Deployment and reinstall server-rendered first-paint contract passed.\n";