diff --git a/web/app/Controllers/CloudAdminInstanceController.php b/web/app/Controllers/CloudAdminInstanceController.php index f9d5ab57..4d8d998d 100644 --- a/web/app/Controllers/CloudAdminInstanceController.php +++ b/web/app/Controllers/CloudAdminInstanceController.php @@ -11,6 +11,9 @@ use App\Services\Cloud\CloudInput; use App\Services\Cloud\CloudInstanceMigrationService; use App\Services\Cloud\CloudJobService; use App\Services\Cloud\CloudNetworkChangeOptionsService; +use App\Services\Cloud\CloudPublicNetworkTransitionCommand; +use App\Services\Cloud\CloudPublicNetworkTransitionWorkflow; +use App\Services\Cloud\CloudInstanceSettingsGuard; use App\Services\Cloud\CloudSecrets; use App\Services\Cloud\CloudSSHKeys; @@ -28,7 +31,7 @@ final class CloudAdminInstanceController $key = trim((string) $request->getHeaderLine('Idempotency-Key')); if ($key === '' || preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $key) !== 1) { - throw new CloudError('备份写操作需要有效的幂等标识', 400); + throw new CloudError('管理员写操作需要有效的幂等标识', 400); } $actor['request_idempotency_key'] = $key; return $actor; @@ -270,12 +273,12 @@ final class CloudAdminInstanceController $actor ); return $response->withJson( - CloudNetworkChangeOptionsService::forInstance($instance) + CloudNetworkChangeOptionsService::adminOptions($instance) )->withHeader('Cache-Control', 'private, no-store'); } /** - * Queue a controlled same-host public IPv4 replacement. + * Queue one exact same-host dual-stack public-network transition. * * PHP/IPAM owns the pool and claim swap. The Agent applies the signed * network intent on the selected host. PHP updates spec_json only after @@ -283,42 +286,48 @@ final class CloudAdminInstanceController */ public function network($request, $response, $args) { - $actor = $request->getAttribute('cloud_actor') ?? CloudAccess::actor(false); - CloudAccess::manage($actor); + $actor = $this->actor($request, true); $instance = CloudAccess::instance((string) ($args['id'] ?? ''), $actor, true); - if ((string) $instance->status !== 'active') { - throw new CloudError('只有处于活动状态的虚拟机可以更换公网 IP', 409); - } $body = CloudInput::object($request); - CloudInput::only($body, - ['public_ip_cidr', 'public_pool_key', 'confirm_restart']); + CloudInput::only($body, ['targets', 'confirm_restart']); if (($body['confirm_restart'] ?? false) !== true) { throw new CloudError('更换公网 IP 前必须确认虚拟机会短暂重启'); } - $cidr = CloudInput::publicIpCidr($body['public_ip_cidr'] ?? null); - $publicPoolKey = CloudInput::publicPoolKey( - $body['public_pool_key'] ?? null - ); - $spec = json_decode((string) $instance->spec_json, true); - if (!is_array($spec) || array_is_list($spec) - || ($spec['managed'] ?? false) !== true - || ($spec['os_source'] ?? null) !== 'cloud_template') { - throw new CloudError('当前虚拟机不是支持网络配置的面板云镜像实例', 409); + $submitted = $body['targets'] ?? null; + if (!is_array($submitted) || array_is_list($submitted) + || $submitted === [] + || array_diff(array_keys($submitted), ['ipv4', 'ipv6']) !== []) { + throw new CloudError('请选择有效的双栈公网目标', 422); + } + $targets = []; + foreach (['ipv4' => 4, 'ipv6' => 6] as $key => $family) { + if (!array_key_exists($key, $submitted)) { + continue; + } + $target = $submitted[$key]; + if (!is_array($target) || array_is_list($target)) { + throw new CloudError('公网目标格式无效', 422); + } + CloudInput::only($target, ['pool_key', 'address_cidr']); + $targets[$family] = [ + 'pool_key' => $target['pool_key'] ?? null, + 'address_cidr' => $target['address_cidr'] ?? null, + ]; } - $current = is_string($spec['public_ip_cidr'] ?? null) - ? trim($spec['public_ip_cidr']) : ''; - if ($current !== '' && $current === $cidr) { - throw new CloudError('新公网 IP 与当前配置相同', 409); + try { + $command = CloudPublicNetworkTransitionCommand::adminExact( + (int) $instance->id, + (int) $actor['user_id'], + (string) $actor['request_idempotency_key'], + $targets + ); + } catch (\InvalidArgumentException) { + throw new CloudError('公网目标格式无效', 422); } - $job = CloudJobService::enqueue($instance, $actor, 'network_change', 'POST', - '/network', [ - 'public_ip_cidr' => $cidr, - 'public_pool_key' => $publicPoolKey, - 'confirm_restart' => true, - ]); + $dispatch = CloudPublicNetworkTransitionWorkflow::begin($command); return $response->withJson([ - 'task_id' => (string) $job->id, - 'status_url' => '/api/v1/tasks/' . $job->id, + 'task_id' => (string) $dispatch->jobId(), + 'status_url' => '/api/v1/tasks/' . $dispatch->jobId(), ], 202)->withHeader('Cache-Control', 'no-store'); } @@ -335,7 +344,8 @@ final class CloudAdminInstanceController $actor = $request->getAttribute('cloud_actor') ?? CloudAccess::actor(false); CloudAccess::manage($actor); $instance = CloudAccess::instance((string) ($args['id'] ?? ''), $actor, true); - if ((string) $instance->status !== 'active') { + if ((string) $instance->status !== 'active' + || !$instance->serviceAvailable()) { throw new CloudError('只有处于活动状态的虚拟机可以修改实例设置', 409); } $body = CloudInput::object($request); @@ -344,14 +354,7 @@ final class CloudAdminInstanceController throw new CloudError('修改实例设置前必须确认虚拟机会短暂重启'); } - $spec = json_decode((string) $instance->spec_json, true); - if (!is_array($spec) || array_is_list($spec) - || ($spec['managed'] ?? false) !== true - || ($spec['os_source'] ?? null) !== 'cloud_template' - || (!is_string($spec['public_ip_cidr'] ?? null) - && !is_string($spec['public_ip'] ?? null))) { - throw new CloudError('当前虚拟机不是支持实例设置的面板云镜像实例', 409); - } + CloudInstanceSettingsGuard::assertSupported($instance); $agentBody = ['confirm_restart' => true]; $existingCredential = self::credentialSnapshot($instance); diff --git a/web/app/Controllers/CloudApiController.php b/web/app/Controllers/CloudApiController.php index d1dd5230..9e633383 100644 --- a/web/app/Controllers/CloudApiController.php +++ b/web/app/Controllers/CloudApiController.php @@ -31,6 +31,7 @@ use App\Services\Cloud\CloudInstanceMetadata; use App\Services\Cloud\CloudInstanceNameService; use App\Services\Cloud\CloudInstancePageService; use App\Services\Cloud\CloudInstanceRuntimeService; +use App\Services\Cloud\CloudInstanceSettingsGuard; use App\Services\Cloud\CloudJobService; use App\Services\Cloud\CloudMoney; use App\Services\Cloud\CloudNetworkChangeOptionsService; @@ -43,6 +44,8 @@ use App\Services\Cloud\CloudInvoicePaymentService; use App\Services\Cloud\CloudInvoiceService; use App\Services\Cloud\CloudOrderService; use App\Services\Cloud\CloudPlanUpgradeService; +use App\Services\Cloud\CloudPublicNetworkTransitionCommand; +use App\Services\Cloud\CloudPublicNetworkTransitionWorkflow; use App\Services\Cloud\CloudSecrets; use App\Services\Cloud\CloudSSHKeys; use App\Services\Cloud\CloudSnapshotService; @@ -1408,6 +1411,7 @@ final class CloudApiController $actor = $this->actor($request); $instance = CloudAccess::instance($args['id'], $actor, true); $this->requireService($instance, $actor); + CloudInstanceSettingsGuard::assertSupported($instance); $body = CloudInput::object($request); CloudInput::only($body, ['hostname', 'ssh_key_id', 'reset_password', 'confirm_restart']); if (($body['confirm_restart'] ?? false) !== true) { @@ -1465,7 +1469,7 @@ final class CloudApiController throw new CloudError('只能为自己持有的实例更换 IP', 403); } $this->requireService($instance, $actor); - $options = CloudNetworkChangeOptionsService::forInstance($instance); + $options = CloudNetworkChangeOptionsService::tenantQuote($instance); $user = User::where('id', (int) $actor['user_id'])->first(); if ($user === null || (int) $user->enable !== 1) { throw new CloudError('账户不可用', 403); @@ -1578,28 +1582,21 @@ final class CloudApiController } catch (\InvalidArgumentException $error) { throw new CloudError($error->getMessage(), 422); } - $spec = json_decode((string) $instance->spec_json, true); - if (!is_array($spec) || array_is_list($spec) - || ($spec['managed'] ?? false) !== true - || ($spec['os_source'] ?? null) !== 'cloud_template') { - throw new CloudError( - '当前虚拟机不是支持网络配置的面板云镜像实例', - 409 - ); + try { + $command = CloudPublicNetworkTransitionCommand:: + userPaidAutomatic( + (int) $instance->id, + (int) $actor['user_id'], + (string) $actor['request_idempotency_key'], + $expectedAmount + ); + } catch (\InvalidArgumentException) { + throw new CloudError('付费更换 IP 请求无效', 422); } - $job = CloudJobService::enqueue( - $instance, - $actor, - 'network_change', - 'POST', - '/network', - ['confirm_restart' => true], - null, - $expectedAmount - ); + $dispatch = CloudPublicNetworkTransitionWorkflow::begin($command); return $this->json($response, [ - 'task_id' => (string) $job->id, - 'status_url' => '/api/v1/tasks/' . $job->id, + 'task_id' => (string) $dispatch->jobId(), + 'status_url' => '/api/v1/tasks/' . $dispatch->jobId(), ], 202); } diff --git a/web/app/Services/Cloud/CloudAdminInstanceService.php b/web/app/Services/Cloud/CloudAdminInstanceService.php index 399ee5c2..22d96828 100644 --- a/web/app/Services/Cloud/CloudAdminInstanceService.php +++ b/web/app/Services/Cloud/CloudAdminInstanceService.php @@ -173,7 +173,8 @@ final class CloudAdminInstanceService $ipv6Gateway = self::ip($spec['public_network']['ipv6']['gateway'] ?? null); $managedCloudTemplate = ($spec['managed'] ?? false) === true && ($spec['os_source'] ?? null) === 'cloud_template'; - $canMutate = $row['instance_status'] === 'active'; + $canMutate = $row['instance_status'] === 'active' + && $instance->serviceAvailable($now); $row += [ 'public_ip_cidr' => $publicIpCidr, 'public_ipv4' => self::ip($spec['public_ipv4'] ?? null) ?? '', @@ -189,9 +190,8 @@ final class CloudAdminInstanceService 'bandwidth_mbps' => self::positiveOrNull($spec['bandwidth_mbps'] ?? null), 'os_source' => self::text($spec['os_source'] ?? null, 32), 'login_name' => self::text($spec['login_name'] ?? null, 32), - // Re-enabled only when every address-changing writer uses the - // dual-stack transition ledger. - 'network_change_supported' => false, + 'network_change_supported' => $canMutate + && $managedCloudTemplate && $networkValid, 'instance_settings_supported' => $canMutate && $managedCloudTemplate && $networkValid, // The Agent can extend its UUID-derived name on collisions. Do diff --git a/web/app/Services/Cloud/CloudInstanceSettingsGuard.php b/web/app/Services/Cloud/CloudInstanceSettingsGuard.php new file mode 100644 index 00000000..b718ebab --- /dev/null +++ b/web/app/Services/Cloud/CloudInstanceSettingsGuard.php @@ -0,0 +1,34 @@ +spec_json, + true, + 64, + JSON_THROW_ON_ERROR + ); + if (!is_array($spec) || array_is_list($spec) + || ($spec['managed'] ?? false) !== true + || ($spec['os_source'] ?? null) !== 'cloud_template') { + throw new \InvalidArgumentException(); + } + CloudPublicNetworkSnapshot::fromArray( + $spec['public_network'] ?? null + ); + } catch (\Throwable) { + throw new CloudError( + '当前虚拟机不是支持实例设置的面板云镜像实例', + 409 + ); + } + } +} diff --git a/web/app/Services/Cloud/CloudJobService.php b/web/app/Services/Cloud/CloudJobService.php index 6426ff55..89c291b8 100644 --- a/web/app/Services/Cloud/CloudJobService.php +++ b/web/app/Services/Cloud/CloudJobService.php @@ -2527,12 +2527,11 @@ final class CloudJobService public static function enqueue(CloudInstance $instance, array $actor, string $kind, string $method, string $suffix, array $body = [], - ?array $credential = null, - ?string $paidNetworkChangeExpectedAmount = null): CloudJob + ?array $credential = null): CloudJob { CloudAccess::vmActor($instance, $actor); if ($kind === 'network_change') { - CloudPublicNetworkTransitionGate::assertWriterReady(); + throw new CloudError('旧公网网络写入口已停用', 409); } if (in_array($kind, ['delete', 'expiry_delete'], true)) { CloudPublicNetworkTransitionGate::assertInstanceDeleteReady( @@ -2540,18 +2539,9 @@ final class CloudJobService ); } $requestKey = self::requestKey($actor); - $paidNetworkChange = $paidNetworkChangeExpectedAmount !== null; - if ($paidNetworkChange && ($kind !== 'network_change' - || $requestKey === null)) { - throw new CloudError( - '付费更换 IP 必须提供请求幂等标识', - 400 - ); - } return $instance->getConnection()->transaction(function () use ( $instance, $actor, $kind, $method, $suffix, $body, $credential, - $requestKey, $paidNetworkChange, - $paidNetworkChangeExpectedAmount + $requestKey ) { $templateMetadata = null; $settingsFields = []; @@ -2563,23 +2553,8 @@ final class CloudJobService // is not part of the strict Agent ReinstallRequest schema. unset($body['confirmation_name']); } - if ($kind === 'network_change') { - CloudInput::only($body, $paidNetworkChange - ? ['confirm_restart'] - : ['public_ip_cidr', 'public_pool_key', 'confirm_restart']); - if (($body['confirm_restart'] ?? false) !== true) { - throw new CloudError('更换公网 IP 前必须确认虚拟机会短暂重启'); - } - if (!$paidNetworkChange) { - $body['public_ip_cidr'] = CloudInput::publicIpCidr( - $body['public_ip_cidr'] ?? null - ); - $body['public_pool_key'] = CloudInput::publicPoolKey( - $body['public_pool_key'] ?? null - ); - } - } if ($kind === 'instance_settings') { + CloudInstanceSettingsGuard::assertSupported($instance); CloudInput::only($body, ['hostname', 'root_password', 'ssh_public_key', 'confirm_restart']); if (($body['confirm_restart'] ?? false) !== true) { throw new CloudError('修改实例设置前必须确认虚拟机会短暂重启'); @@ -2615,26 +2590,10 @@ final class CloudJobService 'suffix' => $suffix, 'body' => $body, ]; - if ($paidNetworkChange) { - $requestValue['billing_purpose'] = - CloudIpChangeBillingService::PURPOSE; - $requestValue['expected_amount'] = CloudMoney::decimal( - CloudMoney::cents( - (string) $paidNetworkChangeExpectedAmount - ) - ); - } $requestFingerprint = hash('sha256', json_encode( self::canonicalRequestValue($requestValue), JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES )); - // Financial writers use the global wallet-first lock order. The - // ordinary administrator path remains free and does not lock a - // tenant wallet. - $billingUser = $paidNetworkChange - ? User::where('id', (int) $actor['user_id']) - ->lockForUpdate()->first() - : null; $locked = CloudInstance::where('id', $instance->id)->lockForUpdate()->first(); if ($locked === null || (string) $locked->status === 'deleted') { throw new CloudError('虚拟机不存在', 404); @@ -2658,40 +2617,6 @@ final class CloudJobService return $prior; } } - $priceCents = null; - if ($paidNetworkChange) { - if ($billingUser === null || (int) $billingUser->enable !== 1) { - throw new CloudError('账户不可用', 403); - } - if ((int) $locked->user_id !== (int) $billingUser->id) { - throw new CloudError('只能为自己持有的实例更换 IP', 403); - } - if (!$locked->serviceAvailable()) { - throw new CloudError( - '实例服务已到期或正在恢复,请先续费并等待恢复完成', - 409 - ); - } - $priceCents = CloudIpChangeBillingService::priceCents(); - if ($priceCents < 1) { - throw new CloudError( - '管理员尚未启用付费更换 IP', - 409 - ); - } - if (CloudMoney::cents( - (string) $paidNetworkChangeExpectedAmount - ) !== $priceCents) { - throw new CloudError( - '更换 IP 价格已变化,请刷新后重新确认', - 409 - ); - } - if (CloudMoney::cents((string) $billingUser->money) - < $priceCents) { - throw new CloudError('账户余额不足', 409); - } - } if ((string) $locked->status !== 'active') { throw new CloudError('实例正在执行到期销毁流程,不能提交其他操作', 409); } @@ -2732,166 +2657,6 @@ final class CloudJobService if ($activeJobs->exists()) { throw new CloudError('虚拟机已有任务,请等待完成', 409); } - $networkLedger = null; - if ($kind === 'network_change') { - $host = CloudHost::where('id', (int) $locked->host_id) - ->lockForUpdate()->first(); - // The host row is the sentinel for all of these references. - // Read their identifiers first, then lock attachment/pools, - // reservation and IP rows in the scheduler's fixed order. - $reservationRef = $locked->reservation_id === null ? null - : CloudResourceReservation::where('id', (int) $locked->reservation_id) - ->first(); - if ($host === null || $reservationRef === null - || (int) $reservationRef->host_id !== (int) $host->id - || (int) ($reservationRef->network_attachment_id ?? 0) < 1 - || (int) ($reservationRef->public_ip_pool_id ?? 0) < 1) { - throw new CloudError('虚拟机缺少有效的公网 IP 资源预留', 409); - } - if ($paidNetworkChange) { - // The host row serializes IP allocation on this host. Pick - // from the same validated ledger used by the availability - // quote, but never expose or accept the target in the - // tenant request. - $networkOptions = - CloudNetworkChangeOptionsService::forInstance($locked); - $automaticTarget = - $networkOptions['available_ip_options'][0] ?? null; - if (!is_array($automaticTarget)) { - throw new CloudError( - '当前公网地址池没有可用 IP', - 409 - ); - } - $body['public_ip_cidr'] = CloudInput::publicIpCidr( - $automaticTarget['public_ip_cidr'] ?? null - ); - $body['public_pool_key'] = CloudInput::publicPoolKey( - $automaticTarget['public_pool_key'] ?? null - ); - } - $parts = explode('/', (string) $body['public_ip_cidr'], 2); - $targetPoolRef = CloudPublicIpPool::where('host_id', (int) $host->id) - ->where('pool_key', (string) $body['public_pool_key'])->first(); - if ($targetPoolRef === null) { - throw new CloudError('所选公网地址池已不可用,请刷新后重试', 409); - } - $targetRef = CloudPublicIp::where('host_id', (int) $host->id) - ->where('public_ip_pool_id', (int) $targetPoolRef->id) - ->where('address', $parts[0]) - ->where('prefix_length', (int) $parts[1])->first(); - if ($targetRef === null) { - throw new CloudError('所选公网 IP 不在指定地址池的可用账本中', 409); - } - - $sourceAttachmentId = - (int) $reservationRef->network_attachment_id; - $targetAttachmentId = - (int) $targetPoolRef->network_attachment_id; - $sourcePoolId = (int) $reservationRef->public_ip_pool_id; - $targetPoolId = (int) $targetPoolRef->id; - $agent = CloudHostAgent::where('host_id', (int) $host->id) - ->lockForUpdate()->first(); - $attachmentIds = array_values(array_unique([ - $sourceAttachmentId, - $targetAttachmentId, - ])); - sort($attachmentIds, SORT_NUMERIC); - $attachments = CloudHostNetworkAttachment::whereIn( - 'id', - $attachmentIds - )->orderBy('id')->lockForUpdate()->get()->keyBy('id'); - $sourceAttachment = $attachments->get($sourceAttachmentId); - $targetAttachment = $attachments->get($targetAttachmentId); - $poolIds = array_values(array_unique([$sourcePoolId, $targetPoolId])); - sort($poolIds, SORT_NUMERIC); - $pools = CloudPublicIpPool::whereIn('id', $poolIds)->orderBy('id') - ->lockForUpdate()->get()->keyBy('id'); - $sourcePool = $pools->get($sourcePoolId); - $targetPool = $pools->get($targetPoolId); - $reservation = CloudResourceReservation::where( - 'id', (int) $reservationRef->id - )->lockForUpdate()->first(); - $reservationPool = $reservation === null ? null - : CloudResourcePool::find((int) $reservation->resource_pool_id); - if ($reservation === null) { - throw new CloudError('虚拟机缺少有效的公网 IP 资源预留', 409); - } - $ipIds = array_values(array_unique([ - (int) $reservation->public_ip_id, (int) $targetRef->id, - ])); - sort($ipIds, SORT_NUMERIC); - $ips = CloudPublicIp::whereIn('id', $ipIds)->orderBy('id') - ->lockForUpdate()->get()->keyBy('id'); - $source = $ips->get((int) $reservation->public_ip_id); - $target = $ips->get((int) $targetRef->id); - if ($agent === null || $sourceAttachment === null - || $targetAttachment === null || $sourcePool === null - || $targetPool === null || $source === null || $target === null - || $reservationPool === null - || (int) $sourceAttachment->host_id !== (int) $host->id - || (int) $targetAttachment->host_id !== (int) $host->id - || (int) $reservation->resource_pool_id - !== (int) ($locked->resource_pool_id ?? 0) - || (int) $sourceAttachment->line_id - !== (int) $reservationPool->line_id - || (int) $targetAttachment->line_id - !== (int) $reservationPool->line_id - || !CloudPlacementNetworkService:: - attachmentReadyForAgent($targetAttachment, $agent) - || (int) $sourcePool->host_id !== (int) $host->id - || (int) $targetPool->host_id !== (int) $host->id - || (int) $sourcePool->network_attachment_id - !== $sourceAttachmentId - || (int) $targetPool->network_attachment_id - !== $targetAttachmentId - || (string) $targetPool->pool_key - !== (string) $body['public_pool_key'] - || (string) $targetPool->state !== 'active' - || (string) $targetPool->sync_state !== 'applied' - || (int) $targetPool->observed_revision - < (int) $targetPool->desired_revision - || (int) $reservation->host_id !== (int) $host->id - || (int) ($reservation->instance_id ?? 0) !== (int) $locked->id - || (string) $reservation->state !== 'committed' - || (int) ($reservation->network_attachment_id ?? 0) - !== $sourceAttachmentId - || (int) ($reservation->public_ip_pool_id ?? 0) !== $sourcePoolId - || (int) $source->host_id !== (int) $host->id - || (int) ($source->public_ip_pool_id ?? 0) !== $sourcePoolId - || (int) ($target->public_ip_pool_id ?? 0) !== $targetPoolId - || (int) $target->prefix_length - !== (int) $targetPool->guest_prefix_length - || !self::publicIpBelongsToPool($target, $targetPool) - || !self::instancePublicIpMatches($locked, $source) - || (string) $source->state !== 'assigned' - || (int) ($source->reservation_id ?? 0) !== (int) $reservation->id - || (int) ($source->instance_id ?? 0) !== (int) $locked->id - || !hash_equals((string) $reservation->operation_id, - (string) ($source->operation_id ?? ''))) { - throw new CloudError('虚拟机当前公网 IP 账本关联不一致', 409); - } - if ((int) $target->id === (int) $source->id - || (string) $target->state !== 'available' - || $target->reservation_id !== null - || $target->instance_id !== null - || $target->operation_id !== null) { - throw new CloudError('所选公网 IP 已不可分配,请刷新后重试', 409); - } - $body['network'] = - (string) $targetAttachment->network_selector; - $body['public_pool_cidr'] = (string) $targetPool->cidr; - $body['gateway'] = (string) $targetPool->gateway; - $body['dns_servers'] = self::poolDnsServers($targetPool); - $networkLedger = [ - 'source' => $source, - 'target' => $target, - 'source_network_attachment_id' => $sourceAttachmentId, - 'target_network_attachment_id' => $targetAttachmentId, - 'source_public_ip_pool_id' => $sourcePoolId, - 'target_public_ip_pool_id' => $targetPoolId, - ]; - } $job = new CloudJob(); $job->operation_id = bin2hex(random_bytes(16)); $job->instance_id = $locked->id; @@ -2920,41 +2685,11 @@ final class CloudJobService // body is the exact strict Go ReinstallRequest DTO. $jobPayload['template_metadata'] = $templateMetadata; } - if ($networkLedger !== null) { - $source = $networkLedger['source']; - $target = $networkLedger['target']; - $jobPayload['source_public_ip_id'] = (int) $source->id; - $jobPayload['target_public_ip_id'] = (int) $target->id; - $jobPayload['source_network_attachment_id'] = - $networkLedger['source_network_attachment_id']; - $jobPayload['target_network_attachment_id'] = - $networkLedger['target_network_attachment_id']; - $jobPayload['source_public_ip_pool_id'] = - $networkLedger['source_public_ip_pool_id']; - $jobPayload['target_public_ip_pool_id'] = - $networkLedger['target_public_ip_pool_id']; - // reservation_id is deliberately left NULL until the swap - // succeeds because cloud_public_ips enforces one current IP - // per reservation. - $target->state = 'changing'; - $target->instance_id = (int) $locked->id; - $target->operation_id = $job->operation_id; - $target->updated_at = time(); - $target->save(); - } $job->sealed_payload = CloudSecrets::encrypt( $jobPayload, 'job-payload' ); $job->available_at = $job->created_at = $job->updated_at = time(); $job->save(); - if ($paidNetworkChange) { - CloudIpChangeBillingService::chargeLocked( - $job, - $locked, - $billingUser, - (int) $priceCents - ); - } return $job; }, 3); } diff --git a/web/app/Services/Cloud/CloudNetworkChangeOptionsService.php b/web/app/Services/Cloud/CloudNetworkChangeOptionsService.php index 5e1939ae..2e01681f 100644 --- a/web/app/Services/Cloud/CloudNetworkChangeOptionsService.php +++ b/web/app/Services/Cloud/CloudNetworkChangeOptionsService.php @@ -6,344 +6,415 @@ use App\Models\CloudHost; use App\Models\CloudHostAgent; use App\Models\CloudHostNetworkAttachment; use App\Models\CloudInstance; +use App\Models\CloudJob; use App\Models\CloudPublicIp; use App\Models\CloudPublicIpPool; +use App\Models\CloudPublicNetworkTransition; use App\Models\CloudResourcePool; -use App\Models\CloudResourceReservation; -/** Read-only, ledger-backed public IPv4 choices for one managed instance. */ +/** Read-only, dual-stack network-change capability projection. */ final class CloudNetworkChangeOptionsService { private const MAX_ATTACHMENTS = 64; - private const MAX_PUBLIC_POOLS = 32; - private const MAX_AVAILABLE_IPS_PER_POOL = 254; + private const MAX_POOLS = 32; + private const MAX_IPV4_OPTIONS = self::MAX_POOLS * 254; - public static function forInstance(CloudInstance $instance): array + /** Tenant quote intentionally omits host, pool and address inventory. */ + public static function tenantQuote(CloudInstance $instance): array { - CloudPublicNetworkTransitionGate::assertWriterReady(); - $spec = json_decode((string) $instance->spec_json, true); + $context = self::context($instance); + $catalog = self::catalog($context); + $sourceId = $context['claim_set']->networkAttachmentId(); + $source = $catalog['attachments'][$sourceId] ?? null; + $hasAutomaticIpv4 = is_array($source) + && self::ipv4OptionCount($source) > 0; + $state = $catalog['malformed'] + ? 'invalid' + : ($hasAutomaticIpv4 ? 'ready' : 'not_configured'); + $availability = self::availability($instance, $state); + + return [ + 'instance_id' => (string) $instance->id, + 'configuration_state' => $state, + 'active_job' => $availability['active_job'], + 'can_change' => $availability['can_change'], + 'message' => $availability['message'], + ]; + } + + /** Administrator inventory is explicit and never used as write authority. */ + public static function adminOptions(CloudInstance $instance): array + { + $context = self::context($instance); + $catalog = self::catalog($context); + $currentAttachmentId = + $context['claim_set']->networkAttachmentId(); + $attachments = array_values($catalog['attachments']); + $hasCandidate = false; + foreach ($attachments as $attachment) { + $hasIpv4 = self::ipv4OptionCount($attachment) > 0; + $hasIpv6 = ($attachment['ipv6']['pools'] ?? []) !== []; + if (($attachment['current'] && ($hasIpv4 || $hasIpv6)) + || (!$attachment['current'] && $hasIpv4 && $hasIpv6)) { + $hasCandidate = true; + break; + } + } + $state = $catalog['malformed'] + ? 'invalid' : ($hasCandidate ? 'ready' : 'not_configured'); + $availability = self::availability($instance, $state); + + return [ + 'instance_id' => (string) $instance->id, + 'host_id' => (string) $context['host']->id, + 'host_name' => (string) $context['host']->name, + 'region' => (string) $context['host']->region, + 'current_attachment_id' => (string) $currentAttachmentId, + 'current_public_network' => + $context['claim_set']->publicNetwork()->toArray(), + 'attachments' => $attachments, + 'configuration_state' => $state, + 'active_job' => $availability['active_job'], + 'can_change' => $availability['can_change'], + 'message' => $availability['message'], + ]; + } + + private static function context(CloudInstance $instance): array + { + try { + $spec = json_decode( + (string) $instance->spec_json, + true, + 64, + JSON_THROW_ON_ERROR + ); + $projected = CloudPublicNetworkSnapshot::fromArray( + is_array($spec) ? ($spec['public_network'] ?? null) : null + ); + } catch (\Throwable) { + throw new CloudError( + '虚拟机双栈公网配置损坏,暂不能更换地址', + 409 + ); + } if (!is_array($spec) || array_is_list($spec) || ($spec['managed'] ?? false) !== true || ($spec['os_source'] ?? null) !== 'cloud_template' - || !is_string($spec['public_ip_cidr'] ?? null) - || trim($spec['public_ip_cidr']) === '') { + || (int) ($instance->host_id ?? 0) < 1 + || (int) ($instance->reservation_id ?? 0) < 1 + || (int) ($instance->resource_pool_id ?? 0) < 1) { throw new CloudError( '当前虚拟机不是支持网络配置的面板云镜像实例', 409 ); } - $host = CloudHost::find($instance->host_id); - if ($host === null) { - throw new CloudError('虚拟机所属宿主机不存在,无法读取地址池', 409); + $claimSet = CloudPublicNetworkAllocationService::currentClaimSet( + (int) $instance->reservation_id, + 'committed', + (int) $instance->id + ); + if (!hash_equals( + $claimSet->publicNetwork()->fingerprint(), + $projected->fingerprint() + )) { + throw new CloudError('虚拟机双栈公网投影与地址账本不一致', 409); } - $agent = CloudHostAgent::find((int) $host->id); - $testedSelectors = $agent === null ? [] - : CloudAgentSettingsService::testedNetworkSelectors($agent); - $reservation = $instance->reservation_id === null ? null - : CloudResourceReservation::find((int) $instance->reservation_id); - $currentPool = $reservation === null ? null - : CloudPublicIpPool::find( - (int) ($reservation->public_ip_pool_id ?? 0) - ); - $attachment = $reservation === null ? null - : CloudHostNetworkAttachment::find( - (int) ($reservation->network_attachment_id ?? 0) - ); - $currentIp = $reservation === null ? null - : CloudPublicIp::find((int) $reservation->public_ip_id); - $reservationPool = $reservation === null ? null - : CloudResourcePool::find((int) $reservation->resource_pool_id); - if ($reservation === null || $currentPool === null - || $attachment === null || $currentIp === null - || $reservationPool === null - || (string) $reservation->state !== 'committed' - || (int) $reservation->host_id !== (int) $host->id - || (int) ($reservation->instance_id ?? 0) !== (int) $instance->id - || (int) $reservation->resource_pool_id - !== (int) ($instance->resource_pool_id ?? 0) - || (int) $attachment->line_id !== (int) $reservationPool->line_id - || (int) $currentPool->host_id !== (int) $host->id - || (int) $currentPool->network_attachment_id - !== (int) $attachment->id - || (int) $currentIp->host_id !== (int) $host->id - || (int) ($currentIp->public_ip_pool_id ?? 0) - !== (int) $currentPool->id - || (string) $currentIp->state !== 'assigned' - || (int) ($currentIp->reservation_id ?? 0) - !== (int) $reservation->id - || (int) ($currentIp->instance_id ?? 0) !== (int) $instance->id - || preg_match('/^[a-f0-9]{32}$/D', - (string) $currentPool->pool_key) !== 1 - || (int) $attachment->host_id !== (int) $host->id) { - throw new CloudError( - '虚拟机公网 IP 资源预留不完整,暂不能更换地址', - 409 - ); + $host = CloudHost::find((int) $instance->host_id); + $agent = CloudHostAgent::find((int) $instance->host_id); + $resourcePool = CloudResourcePool::find( + (int) $instance->resource_pool_id + ); + if (!$host instanceof CloudHost || !(bool) $host->enabled + || !$agent instanceof CloudHostAgent || !$agent->isReady() + || !$resourcePool instanceof CloudResourcePool + || (int) ($resourcePool->line_id ?? 0) < 1) { + throw new CloudError('宿主机公网网络变更能力不可用', 409); } + return [ + 'instance' => $instance, + 'host' => $host, + 'agent' => $agent, + 'resource_pool' => $resourcePool, + 'claim_set' => $claimSet, + 'line_id' => (int) $resourcePool->line_id, + ]; + } - $profileMalformed = false; - $candidateAttachments = collect(); - if ($agent !== null && $agent->isReady()) { - $candidateAttachments = CloudHostNetworkAttachment::where( - 'host_id', (int) $host->id - )->where('line_id', (int) $reservationPool->line_id) - ->where('state', 'active') - ->where('verification_state', 'verified') - ->where('verified_agent_revision', (int) $agent->revision) - ->where('last_verified_at', '>', 0) - ->whereIn('network_selector', $testedSelectors) - ->orderBy('priority')->orderBy('id') - ->limit(self::MAX_ATTACHMENTS + 1)->get(); + private static function catalog(array $context): array + { + $instance = $context['instance']; + $agent = $context['agent']; + $testedSelectors = CloudAgentSettingsService::testedNetworkSelectors( + $agent + ); + $attachmentRows = CloudHostNetworkAttachment::where( + 'host_id', + (int) $instance->host_id + )->where('line_id', $context['line_id']) + ->where('state', 'active') + ->where('verification_state', 'verified') + ->where('verified_agent_revision', (int) $agent->revision) + ->where('last_verified_at', '>', 0) + ->whereIn('network_selector', $testedSelectors) + ->orderBy('priority')->orderBy('id') + ->limit(self::MAX_ATTACHMENTS + 1)->get(); + $malformed = $attachmentRows->count() > self::MAX_ATTACHMENTS; + $attachmentRows = $attachmentRows->take(self::MAX_ATTACHMENTS); + $attachments = []; + foreach ($attachmentRows as $attachment) { + if (!CloudPlacementNetworkService::attachmentReadyForAgent( + $attachment, + $agent + ) || !CloudAgentSettingsService::publicNetworkReady( + $agent, + (string) $attachment->network_selector, + (int) $attachment->verified_agent_revision + )) { + continue; + } + $id = (int) $attachment->id; + $name = trim((string) ($attachment->name ?? '')); + $attachments[$id] = [ + 'attachment_id' => (string) $id, + 'label' => $name !== '' ? $name + : (string) $attachment->network_selector, + 'network_selector' => + (string) $attachment->network_selector, + 'current' => $id === + $context['claim_set']->networkAttachmentId(), + 'ipv4' => ['pools' => []], + 'ipv6' => ['pools' => []], + ]; } - if ($candidateAttachments->count() > self::MAX_ATTACHMENTS) { - $profileMalformed = true; - $candidateAttachments = $candidateAttachments->take( - self::MAX_ATTACHMENTS - ); + if ($attachments === []) { + return ['attachments' => [], 'malformed' => $malformed]; } - $attachmentIds = $candidateAttachments->pluck('id')->map( - static fn ($id): int => (int) $id - )->all(); - $databasePools = CloudPublicIpPool::query() - ->from('cloud_public_ip_pools as public_pool') - ->join( - 'cloud_host_network_attachments as candidate_attachment', - 'candidate_attachment.id', '=', - 'public_pool.network_attachment_id' - )->where('public_pool.host_id', (int) $host->id) - ->whereIn('public_pool.network_attachment_id', $attachmentIds) - ->where('public_pool.state', 'active') - ->where('public_pool.sync_state', 'applied') + + $poolRows = CloudPublicIpPool::where( + 'host_id', + (int) $instance->host_id + )->whereIn('network_attachment_id', array_keys($attachments)) + ->where('state', 'active') + ->where('sync_state', 'applied') ->whereColumn( - 'public_pool.observed_revision', - '>=', - 'public_pool.desired_revision' - )->orderBy('candidate_attachment.priority') - ->orderBy('candidate_attachment.id') - ->orderBy('public_pool.priority') - ->orderBy('public_pool.id') - ->limit(self::MAX_PUBLIC_POOLS + 1)->get(['public_pool.*']); - if ($databasePools->count() > self::MAX_PUBLIC_POOLS) { - $profileMalformed = true; - $databasePools = $databasePools->take(self::MAX_PUBLIC_POOLS); + 'observed_revision', + '=', + 'desired_revision' + ) + ->orderBy('network_attachment_id')->orderBy('address_family') + ->orderBy('priority')->orderBy('id') + ->limit(self::MAX_POOLS + 1)->get(); + if ($poolRows->count() > self::MAX_POOLS) { + $malformed = true; + $poolRows = $poolRows->take(self::MAX_POOLS); } - - $availableOptions = []; - $safePools = []; - foreach ($databasePools as $databasePool) { - $poolKey = (string) $databasePool->pool_key; - $poolCidr = self::safeText($databasePool->cidr, 18); - $poolPrefix = self::safePrefix($databasePool->guest_prefix_length); - $poolGateway = self::safeIpv4($databasePool->gateway); - $poolDns = self::decodeIpList($databasePool->dns_servers_json, 4); - $poolReserved = self::decodeIpList( - $databasePool->reserved_ips_json, - self::MAX_AVAILABLE_IPS_PER_POOL - ); - if (preg_match('/^[a-f0-9]{32}$/D', $poolKey) !== 1 - || $poolCidr === null || $poolPrefix === null - || $poolGateway === null || $poolDns === null - || $poolReserved === null || !self::cidrInPool( - $poolGateway . '/' . $poolPrefix, - $poolCidr - )) { - $profileMalformed = true; + $pools = []; + $ipv4Ids = []; + $ipv6Ids = []; + foreach ($poolRows as $pool) { + $parsed = self::pool($pool, $context['host']); + if ($parsed === null + || !isset($attachments[(int) $pool->network_attachment_id])) { + $malformed = true; continue; } - $blocked = array_values(array_unique([ - $poolGateway, - ...$poolDns, - ...$poolReserved, - ...array_filter([ - CloudPanelUsageService::managementAddress($host), - ]), - ])); - $ips = CloudPublicIp::where('host_id', (int) $host->id) - ->where('public_ip_pool_id', (int) $databasePool->id) - ->where('state', 'available') - ->whereNull('reservation_id')->whereNull('instance_id') - ->whereNull('operation_id')->orderBy('id') - ->limit(self::MAX_AVAILABLE_IPS_PER_POOL + 1)->get(); - if ($ips->count() > self::MAX_AVAILABLE_IPS_PER_POOL) { - $profileMalformed = true; - $ips = $ips->take(self::MAX_AVAILABLE_IPS_PER_POOL); + $dto = $parsed['dto']; + $pools[(int) $pool->id] = [ + 'row' => $pool, + 'dto' => $dto, + 'contract' => $parsed['contract'], + 'excluded' => $dto['excluded_addresses'], + ]; + if ((int) $pool->address_family === 4) { + $ipv4Ids[] = (int) $pool->id; + } else { + $ipv6Ids[] = (int) $pool->id; } - $poolAvailable = 0; - foreach ($ips as $ip) { - $cidr = (string) $ip->address . '/' - . (int) $ip->prefix_length; - if ((int) $ip->prefix_length !== $poolPrefix - || !self::cidrInPool($cidr, $poolCidr) - || in_array((string) $ip->address, $blocked, true)) { - continue; - } - $availableOptions[$poolKey . ':' . $cidr] = [ - 'public_pool_key' => $poolKey, - 'public_ip_cidr' => $cidr, - ]; - ++$poolAvailable; + } + + $ipv6Occupied = []; + if ($ipv6Ids !== []) { + $rows = CloudPublicIp::where('host_id', (int) $instance->host_id) + ->whereIn('public_ip_pool_id', $ipv6Ids) + ->whereIn('state', [ + 'reserved', 'assigned', 'changing', 'uncertain', + ])->selectRaw( + 'public_ip_pool_id, COUNT(*) AS aggregate' + )->groupBy('public_ip_pool_id')->get(); + foreach ($rows as $row) { + $ipv6Occupied[(int) $row->public_ip_pool_id] = + (int) $row->aggregate; + } + } + + $available = $ipv4Ids === [] ? collect() + : CloudPublicIp::where('host_id', (int) $instance->host_id) + ->whereIn('public_ip_pool_id', $ipv4Ids) + ->where('address_family', 4) + ->where('state', 'available') + ->whereNull('reservation_id') + ->whereNull('reservation_ip_claim_id') + ->whereNull('instance_id')->whereNull('operation_id') + ->orderBy('id')->limit(self::MAX_IPV4_OPTIONS + 1)->get(); + if ($available->count() > self::MAX_IPV4_OPTIONS) { + $malformed = true; + $available = $available->take(self::MAX_IPV4_OPTIONS); + } + $options = []; + foreach ($available as $ip) { + $poolId = (int) $ip->public_ip_pool_id; + $pool = $pools[$poolId] ?? null; + if (!is_array($pool) + || !self::availableIpv4( + $ip, + $pool['row'], + $pool['contract'], + $pool['excluded'] + )) { + $malformed = true; + continue; } - $safePools[] = [ - 'public_pool_key' => $poolKey, - 'pool_cidr' => $poolCidr, - 'guest_prefix' => $poolPrefix, - 'gateway' => $poolGateway, - 'dns_servers' => $poolDns, - 'available_count' => $poolAvailable, + $options[$poolId][] = [ + 'address_cidr' => (string) $ip->address . '/' + . (int) $ip->prefix_length, ]; } - $availableOptions = array_values($availableOptions); - $available = array_values(array_map( - static fn (array $option): string => $option['public_ip_cidr'], - $availableOptions - )); - $configurationState = $profileMalformed - ? 'invalid' : ($safePools === [] ? 'not_configured' : 'ready'); - $message = $profileMalformed - ? '面板公网地址池配置异常,请先修复资源池和地址账本。' - : ($available === [] ? '当前公网地址池没有可用 IP。' : ''); - $activeJob = CloudJobService::blockingQueryForInstance( - (int) $instance->id - )->orderByDesc('id')->first(['id', 'kind', 'status', 'updated_at']); - $active = (string) $instance->status === 'active'; + foreach ($pools as $poolId => $pool) { + $row = $pool['row']; + $family = (int) $row->address_family; + if ($family === 6 + && ($ipv6Occupied[$poolId] ?? 0) + >= (int) $row->max_allocations) { + continue; + } + $attachmentId = (int) $row->network_attachment_id; + $dto = $pool['dto']; + if ($family === 4) { + $dto['available_options'] = $options[$poolId] ?? []; + } + $familyKey = $family === 6 ? 'ipv6' : 'ipv4'; + $attachments[$attachmentId][$familyKey]['pools'][] = $dto; + } return [ - 'instance_id' => (string) $instance->id, - 'host_id' => (string) $host->id, - 'host_name' => (string) $host->name, - 'region' => (string) $host->region, - 'current_ip_cidr' => self::safePublicIpCidr( - $spec['public_ip_cidr'] - ), - 'current_public_pool_key' => (string) $currentPool->pool_key, - 'pool_cidr' => self::safeText($currentPool->cidr, 32), - 'guest_prefix' => self::safePrefix( - $currentPool->guest_prefix_length - ), - 'gateway' => self::safeIpv4($currentPool->gateway), - 'dns_servers' => self::decodeIpList( - $currentPool->dns_servers_json, - 4 - ) ?? [], - 'available_ips' => $available, - 'available_ip_options' => $availableOptions, - 'available_count' => count($available), - 'pools' => $safePools, - 'configuration_state' => $configurationState, - 'active_job' => $activeJob === null ? null : [ - 'id' => (string) $activeJob->id, - 'kind' => (string) $activeJob->kind, - 'status' => (string) $activeJob->status, - 'updated_at' => max(0, (int) $activeJob->updated_at), - ], - 'can_change' => $active && $activeJob === null - && $configurationState === 'ready' && $available !== [], - 'message' => $message, + 'attachments' => $attachments, + 'malformed' => $malformed, ]; } - private static function safeText($value, int $length): ?string - { - if (!is_string($value) || trim($value) !== $value || $value === '' - || strlen($value) > $length - || preg_match('/[\x00-\x1f\x7f]/', $value) === 1) { - return null; - } - return $value; - } - - private static function safePrefix($value): ?int - { - return is_int($value) && $value >= 24 && $value <= 30 - ? $value : null; - } - - private static function safeIpv4($value): ?string - { - return is_string($value) && trim($value) === $value - && filter_var( - $value, - FILTER_VALIDATE_IP, - FILTER_FLAG_IPV4 - ) !== false ? $value : null; - } - - private static function decodeIpList($value, int $limit): ?array + private static function pool(CloudPublicIpPool $pool, + CloudHost $host): ?array { try { - $decoded = json_decode( - (string) $value, - true, - 16, - JSON_THROW_ON_ERROR - ); - } catch (\Throwable $error) { - return null; - } - if (!is_array($decoded) || !array_is_list($decoded) - || count($decoded) > $limit) { - return null; - } - $result = []; - foreach ($decoded as $item) { - $ip = self::safeIpv4($item); - if ($ip === null) { - return null; + $contract = CloudPublicIpPoolContract::fromRow($pool); + $family = $contract->family(); + $network = $contract->network(); + $gateway = $contract->gateway(); + $dns = $contract->dnsServers(); + $reserved = $contract->reservedAddresses(); + $allocationStart = $contract->allocationStart()?->text(); + $allocationEnd = $contract->allocationEnd()?->text(); + $excluded = []; + foreach (array_merge($reserved, $dns, [$gateway->text()]) + as $raw) { + $address = CloudIpAddress::parse($raw); + if ($address->family() === $family) { + $excluded[$address->text()] = $address->text(); + } + } + $management = CloudPanelUsageService::managementAddress($host); + if (is_string($management) && $management !== '') { + $managementAddress = CloudIpAddress::parse($management); + if ($managementAddress->family() === $family) { + $excluded[$managementAddress->text()] = + $managementAddress->text(); + } } - $result[] = $ip; + return ['contract' => $contract, 'dto' => [ + 'pool_key' => $contract->poolKey(), + 'name' => trim((string) ($pool->name ?? '')), + 'cidr' => $network->canonical(), + 'guest_prefix' => $contract->guestPrefixLength(), + 'gateway' => $gateway->text(), + 'gateway_on_link' => $contract->gatewayOnLink(), + 'dns_servers' => $dns, + 'sparse' => $family === 6, + 'allocation_start' => $allocationStart, + 'allocation_end' => $allocationEnd, + 'excluded_addresses' => array_values($excluded), + ]]; + } catch (\Throwable) { + return null; } - return array_values(array_unique($result)); } - private static function safePublicIpCidr($value): ?string + private static function availableIpv4(CloudPublicIp $ip, + CloudPublicIpPool $pool, CloudPublicIpPoolContract $contract, + array $excluded): bool { try { - $cidr = CloudInput::publicIpCidr($value); - } catch (\Throwable $error) { - return null; + $address = CloudIpAddress::parse((string) $ip->address); + return (int) $ip->host_id === (int) $pool->host_id + && (int) $ip->public_ip_pool_id === (int) $pool->id + && $contract->family() === 4 + && (int) $ip->address_family === 4 + && (int) $ip->prefix_length + === $contract->guestPrefixLength() + && hash_equals($address->text(), (string) $ip->address) + && is_string($ip->address_binary) + && hash_equals($address->binary(), $ip->address_binary) + && $contract->addressAllowed($address) + && !in_array($address->text(), $excluded, true); + } catch (\Throwable) { + return false; } - [$address, $prefix] = explode('/', $cidr, 2); - $prefix = (int) $prefix; - return $prefix >= 24 && $prefix <= 30 - ? $address . '/' . $prefix : null; } - private static function cidrInPool(string $cidr, $pool): bool + private static function ipv4OptionCount(array $attachment): int { - $target = self::ipv4Number(explode('/', $cidr, 2)[0]); - $parts = is_string($pool) ? explode('/', trim($pool), 2) : []; - $network = isset($parts[0], $parts[1]) - ? self::ipv4Number($parts[0]) : null; - $prefix = isset($parts[1]) && ctype_digit($parts[1]) - ? (int) $parts[1] : -1; - if ($target === null || $network === null - || $prefix < 24 || $prefix > 30) { - return false; + $count = 0; + foreach ($attachment['ipv4']['pools'] ?? [] as $pool) { + $count += count($pool['available_options'] ?? []); } - $block = 2 ** (32 - $prefix); - if (floor($target / $block) !== floor($network / $block)) { - return false; - } - $networkBase = floor($network / $block) * $block; - return $target !== $networkBase - && $target !== $networkBase + $block - 1; + return $count; } - private static function ipv4Number($value): ?int + private static function availability(CloudInstance $instance, + string $configurationState): array { - if (!is_string($value) || filter_var( - $value, - FILTER_VALIDATE_IP, - FILTER_FLAG_IPV4 - ) === false) { - return null; - } - $packed = inet_pton($value); - if ($packed === false || strlen($packed) !== 4) { - return null; - } - $parts = unpack('Nnumber', $packed); - return is_array($parts) && isset($parts['number']) - ? (int) sprintf('%u', $parts['number']) : null; + $activeJob = CloudJobService::blockingQueryForInstance( + (int) $instance->id + )->orderByDesc('id')->first([ + 'id', 'kind', 'status', 'updated_at', + ]); + $activeTransition = CloudPublicNetworkTransition::where( + 'instance_id', + (int) $instance->id + )->where('active_transition', 1)->exists(); + $active = (string) $instance->status === 'active' + && $instance->serviceAvailable(); + $canChange = $active && $activeJob === null && !$activeTransition + && $configurationState === 'ready'; + $message = match (true) { + $configurationState === 'invalid' => + '面板公网地址池配置异常,请先修复双栈地址账本。', + !$active => '实例服务不可用,暂不能更换公网地址。', + $activeJob !== null || $activeTransition => + '实例已有任务,请等待完成。', + $configurationState !== 'ready' => + '当前公网地址池没有可用目标地址。', + default => '', + }; + return [ + 'active_job' => $activeJob instanceof CloudJob ? [ + 'id' => (string) $activeJob->id, + 'kind' => (string) $activeJob->kind, + 'status' => (string) $activeJob->status, + 'updated_at' => max(0, (int) $activeJob->updated_at), + ] : null, + 'can_change' => $canChange, + 'message' => $message, + ]; } } diff --git a/web/app/Services/Cloud/CloudPublicIpPoolContract.php b/web/app/Services/Cloud/CloudPublicIpPoolContract.php new file mode 100644 index 00000000..c731c8b2 --- /dev/null +++ b/web/app/Services/Cloud/CloudPublicIpPoolContract.php @@ -0,0 +1,370 @@ +address_family ?? 0); + $poolKey = (string) ($pool->pool_key ?? ''); + $network = CloudIpPrefix::network($pool->cidr ?? null); + $gateway = CloudIpAddress::parse($pool->gateway ?? null); + $gatewayOnLink = self::strictBoolean( + method_exists($pool, 'getRawOriginal') + ? $pool->getRawOriginal('gateway_on_link') + : ($pool->gateway_on_link ?? null) + ); + $guestPrefix = (int) ($pool->guest_prefix_length ?? 0); + if (!in_array($family, [4, 6], true) + || preg_match('/^[a-f0-9]{32}$/D', $poolKey) !== 1 + || $network->family() !== $family + || !hash_equals( + $network->networkCidr(), + (string) $pool->cidr + ) + || !$network->networkAddress()->isPublicUnicast() + || $guestPrefix !== $network->prefixLength() + || ($family === 4 + && ($guestPrefix < 24 || $guestPrefix > 30)) + || ($family === 6 + && ($guestPrefix < 48 || $guestPrefix > 120)) + || $gateway->family() !== $family + || !$gateway->isPublicUnicast() + || !hash_equals( + $gateway->text(), + (string) $pool->gateway + )) { + throw new \InvalidArgumentException(); + } + + $gatewayInPool = self::usableInPrefix($network, $gateway); + if (($family === 4 && ($gatewayOnLink || !$gatewayInPool)) + || ($family === 6 && !$gatewayInPool && !$gatewayOnLink)) { + throw new \InvalidArgumentException(); + } + + $dns = self::addressList( + $pool->dns_servers_json ?? null, + false, + 4, + null, + null + ); + $reserved = self::addressList( + $pool->reserved_ips_json ?? null, + true, + 256, + $family, + $network + ); + + $max = (int) ($pool->max_allocations ?? -1); + $start = null; + $end = null; + $cursor = null; + if ($family === 4) { + if (($pool->allocation_start ?? null) !== null + || ($pool->allocation_end ?? null) !== null + || ($pool->allocation_cursor ?? null) !== null + || $max !== 0) { + throw new \InvalidArgumentException(); + } + } else { + if ($max < 1 || $max > self::MAX_IPV6_ALLOCATIONS) { + throw new \InvalidArgumentException(); + } + $start = self::canonicalAddress( + $pool->allocation_start ?? null, + 6 + ); + $end = self::canonicalAddress( + $pool->allocation_end ?? null, + 6 + ); + if (!self::usableInPrefix($network, $start) + || !self::usableInPrefix($network, $end) + || $start->compare($end) > 0) { + throw new \InvalidArgumentException(); + } + if (($pool->allocation_cursor ?? null) !== null) { + $cursor = self::canonicalAddress( + $pool->allocation_cursor, + 6 + ); + if ($cursor->compare($start) < 0 + || $cursor->compare($end) > 0) { + throw new \InvalidArgumentException(); + } + } + self::assertSparseCapacity( + $start, + $end, + $max, + $gateway, + $dns, + $reserved + ); + } + + return new self( + $family, + $poolKey, + $network, + $gateway, + $gatewayOnLink, + $dns, + $reserved, + $start, + $end, + $cursor, + $max + ); + } catch (\Throwable $error) { + if ($error instanceof \InvalidArgumentException + && $error->getMessage() === 'Public IP pool contract is invalid.') { + throw $error; + } + throw new \InvalidArgumentException( + 'Public IP pool contract is invalid.', + 0, + $error + ); + } + } + + public function family(): int + { + return $this->family; + } + + public function poolKey(): string + { + return $this->poolKey; + } + + public function network(): CloudIpPrefix + { + return $this->network; + } + + public function gateway(): CloudIpAddress + { + return $this->gateway; + } + + public function gatewayOnLink(): bool + { + return $this->gatewayOnLink; + } + + /** @return list */ + public function dnsServers(): array + { + return array_keys($this->dns); + } + + /** @return list */ + public function reservedAddresses(): array + { + return array_keys($this->reserved); + } + + public function allocationStart(): ?CloudIpAddress + { + return $this->allocationStart; + } + + public function allocationEnd(): ?CloudIpAddress + { + return $this->allocationEnd; + } + + public function allocationCursor(): ?CloudIpAddress + { + return $this->allocationCursor; + } + + public function maxAllocations(): int + { + return $this->maxAllocations; + } + + public function guestPrefixLength(): int + { + return $this->network->prefixLength(); + } + + public function addressBelongs(CloudIpAddress $address): bool + { + return $address->family() === $this->family + && self::usableInPrefix($this->network, $address); + } + + public function addressAllowed(CloudIpAddress $address): bool + { + if (!$this->addressBelongs($address) + || $address->equals($this->gateway) + || isset($this->dns[$address->text()]) + || isset($this->reserved[$address->text()])) { + return false; + } + return $this->family === 4 + || ($this->allocationStart instanceof CloudIpAddress + && $this->allocationEnd instanceof CloudIpAddress + && $address->compare($this->allocationStart) >= 0 + && $address->compare($this->allocationEnd) <= 0); + } + + private static function canonicalAddress(mixed $raw, + ?int $family): CloudIpAddress + { + $address = CloudIpAddress::parse($raw); + if (($family !== null && $address->family() !== $family) + || !$address->isPublicUnicast() + || !is_string($raw) + || !hash_equals($address->text(), $raw)) { + throw new \InvalidArgumentException(); + } + return $address; + } + + private static function strictBoolean(mixed $value): bool + { + if ($value === true || $value === 1 || $value === '1') { + return true; + } + if ($value === false || $value === 0 || $value === '0') { + return false; + } + throw new \InvalidArgumentException(); + } + + /** @return array */ + private static function addressList(mixed $json, bool $allowEmpty, + int $maximum, ?int $family, ?CloudIpPrefix $network): array + { + if (!is_string($json)) { + throw new \InvalidArgumentException(); + } + $values = json_decode($json, true, 16, JSON_THROW_ON_ERROR); + if (!is_array($values) || !array_is_list($values) + || (!$allowEmpty && $values === []) + || count($values) > $maximum) { + throw new \InvalidArgumentException(); + } + $result = []; + foreach ($values as $raw) { + $address = self::canonicalAddress($raw, $family); + if (isset($result[$address->text()]) + || ($network instanceof CloudIpPrefix + && !self::usableInPrefix($network, $address))) { + throw new \InvalidArgumentException(); + } + $result[$address->text()] = $address; + } + return $result; + } + + private static function usableInPrefix(CloudIpPrefix $network, + CloudIpAddress $address): bool + { + return $address->isPublicUnicast() + && $network->contains($address) + && !$address->equals($network->networkAddress()) + && ($address->family() !== 4 + || !$address->equals($network->lastAddress())); + } + + /** @param array $dns + * @param array $reserved */ + private static function assertSparseCapacity(CloudIpAddress $start, + CloudIpAddress $end, int $maximum, CloudIpAddress $gateway, + array $dns, array $reserved): void + { + $blocked = $dns + $reserved; + if ($gateway->family() === 6) { + $blocked[$gateway->text()] = $gateway; + } + $blockedInRange = 0; + foreach ($blocked as $address) { + if ($address->family() === 6 + && $address->compare($start) >= 0 + && $address->compare($end) <= 0) { + $blockedInRange++; + } + } + if (!self::inclusiveRangeContainsAtLeast( + $start, + $end, + $maximum + $blockedInRange + )) { + throw new \InvalidArgumentException(); + } + } + + /** Compare a 128-bit inclusive range with a small bounded cardinality. */ + private static function inclusiveRangeContainsAtLeast( + CloudIpAddress $start, + CloudIpAddress $end, + int $needed + ): bool { + if ($needed <= 1) { + return true; + } + $left = array_values(unpack('C*', $start->binary())); + $right = array_values(unpack('C*', $end->binary())); + $difference = array_fill(0, count($left), 0); + $borrow = 0; + for ($index = count($left) - 1; $index >= 0; $index--) { + $byte = $right[$index] - $left[$index] - $borrow; + if ($byte < 0) { + $byte += 256; + $borrow = 1; + } else { + $borrow = 0; + } + $difference[$index] = $byte; + } + if ($borrow !== 0) { + return false; + } + $requiredDistance = $needed - 1; + $distance = 0; + foreach ($difference as $byte) { + if ($distance > intdiv($requiredDistance, 256)) { + return true; + } + $distance = ($distance * 256) + $byte; + if ($distance > $requiredDistance) { + return true; + } + } + return $distance >= $requiredDistance; + } +} diff --git a/web/app/Services/Cloud/CloudPublicNetworkAllocationService.php b/web/app/Services/Cloud/CloudPublicNetworkAllocationService.php index 6991c0ac..4f68cf80 100644 --- a/web/app/Services/Cloud/CloudPublicNetworkAllocationService.php +++ b/web/app/Services/Cloud/CloudPublicNetworkAllocationService.php @@ -2,6 +2,7 @@ namespace App\Services\Cloud; +use App\Models\CloudHost; use App\Models\CloudHostAgent; use Illuminate\Database\Capsule\Manager as DB; use Illuminate\Database\Connection; @@ -518,6 +519,7 @@ final class CloudPublicNetworkAllocationService throw new CloudError('双栈公网地址不属于预期网络', 409); } $pools = []; + $contracts = []; foreach ($poolRows as $pool) { $family = (int) $pool->address_family; if (!in_array($family, self::FAMILIES, true) @@ -526,13 +528,17 @@ final class CloudPublicNetworkAllocationService || (int) $pool->network_attachment_id !== (int) $attachment->id) { throw new CloudError('双栈公网地址池边界损坏', 409); } - self::validatePool($pool, $family); + $contracts[$family] = self::validatePool($pool, $family); $pools[$family] = $pool; } if (!isset($pools[4], $pools[6])) { throw new CloudError('双栈公网地址池不完整', 409); } - return ['attachment' => $attachment, 'pools' => $pools]; + return [ + 'attachment' => $attachment, + 'pools' => $pools, + 'contracts' => $contracts, + ]; } private static function assertClaimsUseSelection(array $claims, @@ -570,11 +576,12 @@ final class CloudPublicNetworkAllocationService return $result; } - private static function assertPoolLedger(object $pool, array $rows, + private static function assertPoolLedger(object $pool, + CloudPublicIpPoolContract $contract, array $rows, array $retainedSourceEvidence): void { foreach ($rows as $row) { - self::assertConcreteAddress($row, $pool); + self::assertConcreteAddress($row, $pool, $contract); self::assertAddressOwnership( $row, $pool, @@ -583,13 +590,21 @@ final class CloudPublicNetworkAllocationService } } - private static function assertConcreteAddress(object $row, - object $pool): CloudIpAddress + private static function assertConcreteAddress(object $row, object $pool, + CloudPublicIpPoolContract $contract): CloudIpAddress { try { - $address = self::assertConcreteAddressIdentity($row, $pool); + $address = self::assertConcreteAddressIdentity( + $row, + $pool, + $contract + ); if (((string) $row->state !== 'disabled' - && !self::rawAddressAllowedByPool($address, $pool))) { + && !self::rawAddressAllowedByPool( + $address, + $pool, + $contract + ))) { throw new \InvalidArgumentException(); } if ($address->family() === 6 @@ -609,7 +624,7 @@ final class CloudPublicNetworkAllocationService /** Validate immutable identity without reapplying mutable allowlists. */ private static function assertConcreteAddressIdentity(object $row, - object $pool): CloudIpAddress + object $pool, CloudPublicIpPoolContract $contract): CloudIpAddress { try { $address = CloudIpAddress::parse((string) $row->address); @@ -622,7 +637,11 @@ final class CloudPublicNetworkAllocationService || !hash_equals($address->text(), (string) $row->address) || !is_string($row->address_binary) || !hash_equals($address->binary(), $row->address_binary) - || !self::rawAddressBelongsToPool($address, $pool)) { + || !self::rawAddressBelongsToPool( + $address, + $pool, + $contract + )) { throw new \InvalidArgumentException(); } return $address; @@ -714,7 +733,10 @@ final class CloudPublicNetworkAllocationService $allowedIpStates = $allowedPairs[$claimState] ?? []; $family = (int) $claim->address_family; $pool = $selection['pools'][$family] ?? null; - if ($ip === null || $pool === null || $allowedIpStates === [] + $contract = $selection['contracts'][$family] ?? null; + if ($ip === null || $pool === null + || !$contract instanceof CloudPublicIpPoolContract + || $allowedIpStates === [] || !in_array((string) $ip->state, $allowedIpStates, true) || (int) $ip->reservation_id !== (int) $claim->reservation_id || (int) ($ip->reservation_ip_claim_id ?? 0) @@ -729,7 +751,7 @@ final class CloudPublicNetworkAllocationService (string) ($ip->operation_id ?? ''))) { throw new CloudError('公网地址与预留账本不一致', 409); } - self::assertConcreteAddress($ip, $pool); + self::assertConcreteAddress($ip, $pool, $contract); self::assertAddressOwnership($ip); if ((string) $ip->state === 'assigned') { $actualInstanceId = (int) ($ip->instance_id ?? 0); @@ -830,6 +852,7 @@ final class CloudPublicNetworkAllocationService ->whereIn('address_family', self::FAMILIES) ->orderBy('id')->lockForUpdate()->get()->all(); $pools = []; + $contracts = []; foreach ($poolRows as $pool) { $attachmentId = (int) $pool->network_attachment_id; $family = (int) $pool->address_family; @@ -843,7 +866,7 @@ final class CloudPublicNetworkAllocationService !== (int) $pool->desired_revision) { throw new CloudError('公网地址池目录尚未精确收敛', 409); } - self::validatePool($pool, $family); + $contracts[(int) $pool->id] = self::validatePool($pool, $family); $pools[$attachmentId][] = $pool; } foreach ($pools as &$attachmentPools) { @@ -880,6 +903,7 @@ final class CloudPublicNetworkAllocationService return [ 'attachments' => $eligible, 'pools' => $pools, + 'contracts' => $contracts, 'retained_source_evidence' => $retainedSourceEvidence, ]; } @@ -906,8 +930,13 @@ final class CloudPublicNetworkAllocationService $rowsByPool[$poolId][] = $row; } foreach ($allPools as $poolId => $pool) { + $contract = $catalog['contracts'][$poolId] ?? null; + if (!$contract instanceof CloudPublicIpPoolContract) { + throw new CloudError('公网地址池合同缺失', 409); + } self::assertPoolLedger( $pool, + $contract, $rowsByPool[$poolId], $catalog['retained_source_evidence'] ?? [] ); @@ -915,18 +944,25 @@ final class CloudPublicNetworkAllocationService foreach ($catalog['attachments'] as $attachmentId => $attachment) { $selectedPools = []; + $selectedContracts = []; $addressCandidates = []; foreach ($catalog['pools'][$attachmentId] ?? [] as $pool) { $family = (int) $pool->address_family; if (isset($selectedPools[$family])) { continue; } + $contract = $catalog['contracts'][(int) $pool->id] ?? null; + if (!$contract instanceof CloudPublicIpPoolContract) { + throw new CloudError('公网地址池合同缺失', 409); + } $candidate = self::lockReservableAddressCandidate( $pool, + $contract, $rowsByPool[(int) $pool->id] ?? [] ); if ($candidate !== null) { $selectedPools[$family] = $pool; + $selectedContracts[$family] = $contract; $addressCandidates[$family] = $candidate; } } @@ -934,6 +970,7 @@ final class CloudPublicNetworkAllocationService return [ 'attachment' => $attachment, 'pools' => $selectedPools, + 'contracts' => $selectedContracts, 'address_candidates' => $addressCandidates, ]; } @@ -954,6 +991,7 @@ final class CloudPublicNetworkAllocationService */ private static function lockReservableAddressCandidate( object $pool, + CloudPublicIpPoolContract $contract, array $rows ): ?array { $family = (int) $pool->address_family; @@ -984,33 +1022,30 @@ final class CloudPublicNetworkAllocationService if ($family !== 6) { return null; } - $rangeStart = CloudIpAddress::parse($pool->allocation_start ?? null); - $rangeEnd = CloudIpAddress::parse($pool->allocation_end ?? null); - $candidate = $pool->allocation_cursor === null - ? $rangeStart : CloudIpAddress::parse($pool->allocation_cursor); - if ($candidate->compare($rangeStart) < 0 - || $candidate->compare($rangeEnd) > 0) { - $candidate = $rangeStart; + $rangeStart = $contract->allocationStart(); + $rangeEnd = $contract->allocationEnd(); + $candidate = $contract->allocationCursor() ?? $rangeStart; + if (!$rangeStart instanceof CloudIpAddress + || !$rangeEnd instanceof CloudIpAddress + || !$candidate instanceof CloudIpAddress) { + throw new CloudError('公网 IPv6 稀疏分配合同损坏', 409); } $materializedCount = count($rows); $attempts = max(1, $materializedCount - + (int) $pool->max_allocations - + count(self::decodedAddresses( - (string) $pool->reserved_ips_json, - true - )) - + count(self::decodedAddresses( - (string) $pool->dns_servers_json, - false, - 4 - )) + 2); + + $contract->maxAllocations() + + count($contract->reservedAddresses()) + + count($contract->dnsServers()) + 2); for ($attempt = 0; $attempt < $attempts; $attempt++) { $existing = DB::table('cloud_public_ips') ->where('address_family', 6) ->where('address_binary', $candidate->binary()) ->lockForUpdate()->first(); if ($existing === null - && self::rawAddressAllowedByPool($candidate, $pool)) { + && self::rawAddressAllowedByPool( + $candidate, + $pool, + $contract + )) { return [ 'row' => null, 'candidate' => $candidate, @@ -1101,98 +1136,43 @@ final class CloudPublicNetworkAllocationService } } - private static function validatePool(object $pool, int $family): void + private static function validatePool(object $pool, + int $family): CloudPublicIpPoolContract { try { - $prefix = CloudIpPrefix::network((string) $pool->cidr); - $gateway = CloudIpAddress::parse((string) $pool->gateway); - if ($prefix->family() !== $family || $gateway->family() !== $family - || (int) $pool->guest_prefix_length !== $prefix->prefixLength() - || !$prefix->networkAddress()->isPublicUnicast() - || !$gateway->isPublicUnicast() - || (!$prefix->contains($gateway) - && !(bool) $pool->gateway_on_link)) { + $contract = CloudPublicIpPoolContract::fromRow($pool); + if ($contract->family() !== $family) { throw new \InvalidArgumentException(); } - self::decodedAddresses( - (string) $pool->dns_servers_json, - false, - 4 - ); - $reserved = self::decodedAddresses( - (string) $pool->reserved_ips_json, - true - ); - foreach (array_keys($reserved) as $text) { - $address = CloudIpAddress::parse($text); - if ($address->family() !== $family - || !$prefix->contains($address)) { - throw new \InvalidArgumentException(); - } - } - if ($family === 4) { - if ($pool->allocation_start !== null - || $pool->allocation_end !== null - || $pool->allocation_cursor !== null - || (int) $pool->max_allocations !== 0) { - throw new \InvalidArgumentException(); - } - } else { - $start = CloudIpAddress::parse($pool->allocation_start ?? null); - $end = CloudIpAddress::parse($pool->allocation_end ?? null); - if ($start->family() !== 6 || $end->family() !== 6 - || !$start->isPublicUnicast() || !$end->isPublicUnicast() - || !$prefix->contains($start) || !$prefix->contains($end) - || $start->compare($end) > 0 - || (int) $pool->max_allocations < 1) { - throw new \InvalidArgumentException(); - } - if ($pool->allocation_cursor !== null) { - $cursor = CloudIpAddress::parse($pool->allocation_cursor); - if ($cursor->family() !== 6 - || $cursor->compare($start) < 0 - || $cursor->compare($end) > 0) { - throw new \InvalidArgumentException(); - } - } - } + return $contract; } catch (\Throwable) { throw new CloudError('公网地址池配置损坏', 409); } } private static function rawAddressAllowedByPool(CloudIpAddress $address, - object $pool): bool + object $pool, CloudPublicIpPoolContract $contract): bool { - if (!self::rawAddressBelongsToPool($address, $pool)) { + if (!$contract->addressAllowed($address)) { return false; } - $blocked = self::decodedAddresses( - (string) $pool->reserved_ips_json, - true + $management = CloudPanelUsageService::managementAddress( + CloudHost::find((int) $pool->host_id) ); - $gateway = CloudIpAddress::parse((string) $pool->gateway); - $blocked[$gateway->text()] = true; - foreach (self::decodedAddresses( - (string) $pool->dns_servers_json, - false, - 4 - ) as $text => $_) { - $blocked[$text] = true; + if (is_string($management) && $management !== '') { + $managementAddress = CloudIpAddress::parse($management); + if ($managementAddress->family() === $address->family() + && $managementAddress->equals($address)) { + return false; + } } - return !isset($blocked[$address->text()]); + return true; } private static function rawAddressBelongsToPool(CloudIpAddress $address, - object $pool): bool + object $pool, CloudPublicIpPoolContract $contract): bool { - $prefix = CloudIpPrefix::network((string) $pool->cidr); - return $address->family() === (int) $pool->address_family - && $address->isPublicUnicast() - && $prefix->contains($address) - && !$address->equals($prefix->networkAddress()) - && ($address->family() !== 4 - || !$address->equals($prefix->lastAddress())); + return $contract->addressBelongs($address); } private static function decodedAddresses(string $json, @@ -1320,7 +1300,8 @@ final class CloudPublicNetworkAllocationService || (int) $ip->public_ip_pool_id !== (int) $pool->id) { throw new CloudError('双栈公网地址引用损坏', 409); } - self::assertConcreteAddressIdentity($ip, $pool); + $contract = self::validatePool($pool, $family); + self::assertConcreteAddressIdentity($ip, $pool, $contract); $addresses[(int) $ip->id] = $ip; $reservationIds[(int) $claim->reservation_id] = true; $legs[$family] = [ @@ -1331,10 +1312,7 @@ final class CloudPublicNetworkAllocationService 'gateway' => (string) $pool->gateway, 'gateway_on_link' => (bool) $pool->gateway_on_link, ]; - foreach (self::decodedAddresses( - (string) $pool->dns_servers_json, - false - ) as $text => $_) { + foreach ($contract->dnsServers() as $text) { $dns[$text] = $text; } } diff --git a/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php b/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php index d91d02cb..8049b4aa 100644 --- a/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php +++ b/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php @@ -19,10 +19,9 @@ use Illuminate\Database\Capsule\Manager as DB; /** * Durable seam for public-network transitions. * - * Stage 4 keeps dispatch, evidence, local finalization and recovery behind the - * same deep module seam as begin(). Controllers still cannot route new writes - * here until the later writer-gate stage; legacy in-flight jobs remain isolated - * by their missing public_network_transition_id. + * Controllers, dispatch, evidence, local finalization and recovery all use + * this seam. Legacy in-flight jobs remain isolated by their missing + * public_network_transition_id. */ final class CloudPublicNetworkTransitionWorkflow { @@ -79,11 +78,24 @@ final class CloudPublicNetworkTransitionWorkflow if ($active instanceof CloudPublicNetworkTransition) { throw new CloudError('虚拟机已有公网网络变更正在处理', 409); } + try { + $spec = json_decode( + (string) $instance->spec_json, + true, + 64, + JSON_THROW_ON_ERROR + ); + } catch (\Throwable) { + $spec = null; + } if ((string) $instance->status !== 'active' || !$instance->serviceAvailable() || (int) ($instance->host_id ?? 0) < 1 || (int) ($instance->reservation_id ?? 0) < 1 - || (int) ($instance->resource_pool_id ?? 0) < 1) { + || (int) ($instance->resource_pool_id ?? 0) < 1 + || !is_array($spec) || array_is_list($spec) + || ($spec['managed'] ?? false) !== true + || ($spec['os_source'] ?? null) !== 'cloud_template') { throw new CloudError('虚拟机不满足公网网络变更条件', 409); } CloudInstanceMigrationService::assertInstanceMutationAvailable( @@ -2199,6 +2211,14 @@ final class CloudPublicNetworkTransitionWorkflow break; } } + if ($ip instanceof CloudPublicIp + && (int) $pool->address_family === 6 + && !self::sparseCapacityAvailableLocked( + $pool, + $ips + )) { + $ip = null; + } if (!$ip instanceof CloudPublicIp && (int) $pool->address_family === 6) { $ip = self::materializeSparseTargetLocked( @@ -2349,6 +2369,11 @@ final class CloudPublicNetworkTransitionWorkflow CloudInstance $instance, CloudHostAgent $agent, $attachments, int $lineId): bool { + try { + $contract = CloudPublicIpPoolContract::fromRow($pool); + } catch (\Throwable) { + return false; + } $attachment = $attachments->get((int) $pool->network_attachment_id); return $attachment instanceof CloudHostNetworkAttachment && (int) $pool->host_id === (int) $instance->host_id @@ -2358,6 +2383,7 @@ final class CloudPublicNetworkTransitionWorkflow && (string) $pool->sync_state === 'applied' && (int) $pool->observed_revision === (int) $pool->desired_revision + && $contract->family() === (int) $pool->address_family && CloudPlacementNetworkService::attachmentReadyForAgent( $attachment, $agent @@ -2420,23 +2446,22 @@ final class CloudPublicNetworkTransitionWorkflow return null; } $address = $prefix->addressValue(); - $occupied = 0; + if (!self::sparseCapacityAvailableLocked($pool, $lockedIps)) { + return null; + } + $matching = null; foreach ($lockedIps as $row) { if ((int) $row->public_ip_pool_id !== (int) $pool->id) { continue; } if (is_string($row->address_binary) && hash_equals($address->binary(), $row->address_binary)) { - return self::ipAvailableForPool($row, $pool) - ? $row : null; - } - if (in_array((string) $row->state, - ['reserved', 'assigned', 'changing', 'uncertain'], true)) { - $occupied++; + $matching = $row; } } - if ($occupied >= (int) $pool->max_allocations) { - return null; + if ($matching instanceof CloudPublicIp) { + return self::ipAvailableForPool($matching, $pool) + ? $matching : null; } // All rows in the candidate pool are already locked. Do not take // a late global address lock that can reverse primary-key order; @@ -2467,51 +2492,46 @@ final class CloudPublicNetworkTransitionWorkflow } } + private static function sparseCapacityAvailableLocked( + CloudPublicIpPool $pool, + $lockedIps + ): bool { + $occupied = 0; + foreach ($lockedIps as $row) { + if ((int) $row->public_ip_pool_id === (int) $pool->id + && in_array((string) $row->state, + ['reserved', 'assigned', 'changing', 'uncertain'], true)) { + $occupied++; + } + } + return (int) $pool->max_allocations > 0 + && $occupied < (int) $pool->max_allocations; + } + private static function assertAddressInPool(CloudPublicIp $ip, CloudPublicIpPool $pool): void { try { - $network = CloudIpPrefix::network((string) $pool->cidr); + $contract = CloudPublicIpPoolContract::fromRow($pool); $address = CloudIpAddress::parse((string) $ip->address); - $gateway = CloudIpAddress::parse((string) $pool->gateway); if ((int) $ip->host_id !== (int) $pool->host_id || (int) $ip->public_ip_pool_id !== (int) $pool->id || (int) $ip->address_family !== (int) $pool->address_family || (int) $ip->prefix_length - !== (int) $pool->guest_prefix_length - || $address->family() !== (int) $pool->address_family - || !$address->isPublicUnicast() - || !$network->contains($address) - || $address->equals($network->networkAddress()) - || ($address->family() === 4 - && $address->equals($network->lastAddress())) - || $address->equals($gateway) + !== $contract->guestPrefixLength() + || !hash_equals($address->text(), (string) $ip->address) + || !$contract->addressAllowed($address) || !is_string($ip->address_binary) || !hash_equals($address->binary(), $ip->address_binary)) { throw new \InvalidArgumentException(); } - $reserved = json_decode( - (string) $pool->reserved_ips_json, - true, - 16, - JSON_THROW_ON_ERROR + $management = CloudPanelUsageService::managementAddress( + CloudHost::find((int) $pool->host_id) ); - if (!is_array($reserved) || !array_is_list($reserved)) { + if (is_string($management) && $management !== '' + && $address->equals(CloudIpAddress::parse($management))) { throw new \InvalidArgumentException(); } - foreach ($reserved as $raw) { - if ($address->equals(CloudIpAddress::parse($raw))) { - throw new \InvalidArgumentException(); - } - } - if ($address->family() === 6) { - $start = CloudIpAddress::parse($pool->allocation_start); - $end = CloudIpAddress::parse($pool->allocation_end); - if ($address->compare($start) < 0 - || $address->compare($end) > 0) { - throw new \InvalidArgumentException(); - } - } } catch (\Throwable) { throw new CloudError('公网地址具体身份与地址池不一致', 409); } @@ -2521,26 +2541,7 @@ final class CloudPublicNetworkTransitionWorkflow private static function dns(CloudPublicIpPool $pool): array { try { - $values = json_decode( - (string) $pool->dns_servers_json, - true, - 16, - JSON_THROW_ON_ERROR - ); - if (!is_array($values) || !array_is_list($values) - || $values === [] || count($values) > 4) { - throw new \InvalidArgumentException(); - } - $result = []; - foreach ($values as $raw) { - $address = CloudIpAddress::parse($raw); - if (!$address->isPublicUnicast() - || isset($result[$address->text()])) { - throw new \InvalidArgumentException(); - } - $result[$address->text()] = $address->text(); - } - return array_values($result); + return CloudPublicIpPoolContract::fromRow($pool)->dnsServers(); } catch (\Throwable) { throw new CloudError('公网地址池 DNS 配置损坏', 409); } diff --git a/web/app/Services/Cloud/CloudWorkerService.php b/web/app/Services/Cloud/CloudWorkerService.php index 412ac9ae..7778fa77 100644 --- a/web/app/Services/Cloud/CloudWorkerService.php +++ b/web/app/Services/Cloud/CloudWorkerService.php @@ -428,7 +428,8 @@ final class CloudWorkerService return true; } } - if ((string) $job->kind === 'network_change') { + if ((string) $job->kind === 'network_change' + && $job->public_network_transition_id === null) { CloudPublicNetworkTransitionGate::assertWriterReady(); } elseif ((string) $job->kind === 'backup_restore') { CloudPublicNetworkTransitionGate::assertPortableRestoreReady(); diff --git a/web/public/cloud/admin-instance-configuration.js b/web/public/cloud/admin-instance-configuration.js index f8333d07..ebd5017d 100644 --- a/web/public/cloud/admin-instance-configuration.js +++ b/web/public/cloud/admin-instance-configuration.js @@ -52,90 +52,218 @@ function publicPoolKey(value) { return /^[a-f0-9]{32}$/.test(key) ? key : ''; } -function networkOptionsFromVm(vm) { - const current = normalizeCidr(vm.public_ip_cidr || vm.public_ip, 24); - const prefix = current?.prefix || 24; +function parseIPv6(value) { + const raw = String(value ?? '').trim().toLowerCase(); + if (!raw || raw.includes('%') || !/^[0-9a-f:]+$/.test(raw) + || (raw.match(/::/g) || []).length > 1) return null; + const halves = raw.split('::'); + const left = halves[0] ? halves[0].split(':') : []; + const right = halves.length === 2 && halves[1] ? halves[1].split(':') : []; + if ([...left, ...right].some(part => !/^[0-9a-f]{1,4}$/.test(part))) return null; + const missing = 8 - left.length - right.length; + if ((halves.length === 1 && missing !== 0) || (halves.length === 2 && missing < 1)) return null; + const words = [...left, ...Array(Math.max(0, missing)).fill('0'), ...right].map(part => Number.parseInt(part, 16)); + return words.length === 8 && words.every(part => Number.isInteger(part) && part >= 0 && part <= 0xffff) + ? words : null; +} + +function ipv6Number(words) { + return words.reduce((value, word) => (value << 16n) | BigInt(word), 0n); +} + +function normalizeIPv6Cidr(value, fallbackPrefix = 64) { + const raw = String(value ?? '').trim(); + if (!raw) return null; + const parts = raw.split('/'); + if (parts.length > 2 || (parts.length === 2 && !/^\d+$/.test(parts[1]))) return null; + const words = parseIPv6(parts[0]); + const prefix = parts.length === 2 ? Number(parts[1]) : Number(fallbackPrefix); + if (!words || !Number.isInteger(prefix) || prefix < 1 || prefix > 128) return null; + return { address: parts[0].toLowerCase(), prefix, value: `${parts[0].toLowerCase()}/${prefix}`, number: ipv6Number(words) }; +} + +function ipv6CidrContains(cidr, address) { + const network = normalizeIPv6Cidr(cidr, null); + const target = parseIPv6(String(address ?? '').split('/')[0]); + if (!network || !target) return false; + const shift = 128n - BigInt(network.prefix); + return (network.number >> shift) === (ipv6Number(target) >> shift); +} + +function normalizeAddressCidr(value, family, fallbackPrefix = family === 4 ? 24 : 64) { + return family === 4 ? normalizeCidr(value, fallbackPrefix) : normalizeIPv6Cidr(value, fallbackPrefix); +} + +function currentNetworkFromVm(vm = {}) { + const source = vm.public_network && typeof vm.public_network === 'object' ? vm.public_network : {}; + const ipv4 = normalizeCidr(source.ipv4?.address_cidr || vm.public_ipv4_cidr || vm.public_ip_cidr || vm.public_ipv4 || vm.public_ip, 24); + const ipv6 = normalizeIPv6Cidr(source.ipv6?.address_cidr || vm.public_ipv6_cidr || vm.public_ipv6, 64); return { - configured: false, current_ip_cidr: current?.value || '', guest_prefix: prefix, - gateway: vm.gateway || '', dns_servers: Array.isArray(vm.dns_servers) ? vm.dns_servers : [], - current_public_pool_key: '', public_pool_cidr: '', available_count: 0, - available_ips: [], available_ip_options: [], pools: [], - configuration_state: 'not_configured', can_change: false, + ipv4: { pool_key: publicPoolKey(source.ipv4?.pool_key), address_cidr: ipv4?.value || '' }, + ipv6: { pool_key: publicPoolKey(source.ipv6?.pool_key), address_cidr: ipv6?.value || '' }, }; } -function networkOptionsPayload(payload, vm) { - const source = payload?.network_options || payload?.network || payload || {}; - const fallback = networkOptionsFromVm(vm); - const current = normalizeCidr(source.current_ip_cidr || vm.public_ip_cidr || vm.public_ip, fallback.guest_prefix); - const guestPrefix = Number(source.guest_prefix ?? source.public_vm_prefix ?? current?.prefix ?? fallback.guest_prefix); - const dns = Array.isArray(source.dns_servers) - ? source.dns_servers.filter(value => parseIPv4(value)) : fallback.dns_servers; - const normalizedGuestPrefix = Number.isInteger(guestPrefix) && guestPrefix >= 24 && guestPrefix <= 30 - ? guestPrefix : fallback.guest_prefix; - const pools = []; const poolsByKey = new Map(); - for (const value of Array.isArray(source.pools) ? source.pools : []) { - if (!value || typeof value !== 'object' || Array.isArray(value)) continue; - const key = publicPoolKey(value.public_pool_key || value.pool_key); - const poolCidr = normalizeCidr(value.pool_cidr, null); - const poolPrefix = Number(value.guest_prefix); - const poolGateway = parseIPv4(value.gateway)?.join('.') || ''; - if (!key || !poolCidr || !Number.isInteger(poolPrefix) - || poolPrefix < 24 || poolPrefix > 30 || !poolGateway) continue; - const pool = { - public_pool_key: key, pool_cidr: poolCidr.value, guest_prefix: poolPrefix, - gateway: poolGateway, - dns_servers: Array.isArray(value.dns_servers) - ? value.dns_servers.map(item => parseIPv4(item)?.join('.')).filter(Boolean) : [], - available_count: Math.max(0, Number(value.available_count) || 0), - }; - pools.push(pool); poolsByKey.set(key, pool); +function normalizePool(value, family) { + if (!value || typeof value !== 'object' || Array.isArray(value)) return null; + const poolKey = publicPoolKey(value.pool_key || value.public_pool_key); + const poolCidr = normalizeAddressCidr(value.pool_cidr || value.cidr, family, null); + const guestPrefix = Number(value.guest_prefix ?? value.prefix_length ?? poolCidr?.prefix); + if (!poolKey || !poolCidr || !Number.isInteger(guestPrefix) + || guestPrefix !== poolCidr.prefix + || guestPrefix > (family === 4 ? 30 : 120)) return null; + const pool = { + pool_key: poolKey, pool_cidr: poolCidr.value, guest_prefix: guestPrefix, + gateway: String(value.gateway || '').trim(), + dns_servers: Array.isArray(value.dns_servers) ? value.dns_servers.map(item => String(item).trim()).filter(Boolean) : [], + sparse: family === 6 && value.sparse === true, + allocation_start: '', + allocation_end: '', + allocation_start_number: null, + allocation_end_number: null, + excluded_addresses: [], + excluded_address_numbers: [], + available_options: [], + }; + if (family === 4) { + const seen = new Set(); + for (const option of Array.isArray(value.available_options) ? value.available_options : []) { + const cidr = normalizeCidr(option?.address_cidr || option?.public_ip_cidr, guestPrefix); + if (!cidr || cidr.prefix !== guestPrefix || !cidrContains(pool.pool_cidr, cidr.address) + || seen.has(cidr.value)) continue; + seen.add(cidr.value); pool.available_options.push({ address_cidr: cidr.value }); + } + } else { + const start = parseIPv6(value.allocation_start); + const end = parseIPv6(value.allocation_end); + const excluded = Array.isArray(value.excluded_addresses) + ? value.excluded_addresses.map(item => parseIPv6(item)) : null; + if (!pool.sparse || !start || !end || !excluded || excluded.some(item => !item) + || !ipv6CidrContains(pool.pool_cidr, value.allocation_start) + || !ipv6CidrContains(pool.pool_cidr, value.allocation_end)) return null; + pool.allocation_start_number = ipv6Number(start); + pool.allocation_end_number = ipv6Number(end); + if (pool.allocation_start_number > pool.allocation_end_number) return null; + pool.allocation_start = String(value.allocation_start).trim().toLowerCase(); + pool.allocation_end = String(value.allocation_end).trim().toLowerCase(); + pool.excluded_addresses = value.excluded_addresses.map(item => String(item).trim().toLowerCase()); + pool.excluded_address_numbers = excluded.map(ipv6Number); } - const availableOptions = []; const seenOptions = new Set(); - for (const value of Array.isArray(source.available_ip_options) ? source.available_ip_options : []) { - if (!value || typeof value !== 'object' || Array.isArray(value)) continue; - const key = publicPoolKey(value.public_pool_key || value.pool_key); - const pool = poolsByKey.get(key); - const cidr = normalizeCidr(value.public_ip_cidr || value.cidr, pool?.guest_prefix); - const optionKey = cidr ? `${key}:${cidr.value}` : ''; - if (!pool || !cidr || cidr.prefix !== pool.guest_prefix - || !cidrContains(pool.pool_cidr, cidr.address) || seenOptions.has(optionKey)) continue; - seenOptions.add(optionKey); - availableOptions.push({ public_pool_key: key, public_ip_cidr: cidr.value }); + return pool; +} + +function normalizeAttachment(value, currentAttachmentId) { + if (!value || typeof value !== 'object' || Array.isArray(value)) return null; + const attachmentId = String(value.attachment_id ?? '').trim(); + if (!/^[1-9]\d*$/.test(attachmentId)) return null; + const families = {}; + for (const [name, family] of [['ipv4', 4], ['ipv6', 6]]) { + const pools = []; + for (const poolValue of Array.isArray(value[name]?.pools) ? value[name].pools : []) { + const pool = normalizePool(poolValue, family); if (pool) pools.push(pool); + } + families[name] = { pools }; } - const availableIps = availableOptions.map(value => value.public_ip_cidr); return { - ...fallback, ...source, - current_ip_cidr: current?.value || fallback.current_ip_cidr, - current_public_pool_key: publicPoolKey(source.current_public_pool_key), - guest_prefix: normalizedGuestPrefix, - public_pool_cidr: String(source.public_pool_cidr || source.pool_cidr || '').trim(), - gateway: String(source.gateway || fallback.gateway || '').trim(), dns_servers: dns, - available_count: Number.isFinite(Number(source.available_count)) - ? Math.max(0, Number(source.available_count)) : availableIps.length, - available_ips: availableIps, available_ip_options: availableOptions, pools, - configuration_state: ['ready', 'not_configured', 'invalid', 'drift', 'unavailable'] - .includes(source.configuration_state) ? source.configuration_state : 'unavailable', - can_change: source.can_change === true, + attachment_id: attachmentId, + label: String(value.label || value.network_selector || `网络接入 #${attachmentId}`).trim(), + current: value.current === true || attachmentId === currentAttachmentId, + ...families, + }; +} + +function networkOptionsFromVm(vm = {}) { + return { + current_public_network: currentNetworkFromVm(vm), current_attachment_id: '', + attachments: [], configuration_state: 'not_configured', can_change: false, + active_job: vm.active_job || null, message: '', }; } -function networkOptionSummary(options, selectedPool = null) { - const pools = Array.isArray(options.pools) ? options.pools : []; - const selected = selectedPool || (pools.length === 1 ? pools[0] : null); - const pool = selected?.pool_cidr || (pools.length > 1 ? `${pools.length} 个启用地址池` - : (options.public_pool_cidr - || (options.configuration_state === 'not_configured' ? '未配置' : '提交时由 Agent 校验'))); - const prefix = selected?.guest_prefix ? `/${selected.guest_prefix}` - : (pools.length > 1 ? '按所选地址池' : (options.guest_prefix ? `/${options.guest_prefix}` : '未记录')); - const gateway = selected?.gateway || (pools.length > 1 ? '按所选地址池' - : (options.gateway || '提交时由宿主机配置决定')); - const dnsValues = selected?.dns_servers || (pools.length > 1 ? [] : options.dns_servers); - const dns = dnsValues?.length ? dnsValues.join('、') - : (pools.length > 1 ? '按所选地址池' : '宿主机默认 DNS'); - const available = options.available_ip_options?.length - ? `${options.available_ip_options.length} 个` : '暂无可用地址'; - return { pool, prefix, gateway, dns, available }; +export function normalizeAdminNetworkOptions(payload, vm = {}) { + const source = payload?.network_options || payload?.network || payload || {}; + const fallback = networkOptionsFromVm(vm); + const snapshot = source.current_public_network && typeof source.current_public_network === 'object' + ? source.current_public_network : (source.public_network || {}); + const current = currentNetworkFromVm({ ...vm, public_network: snapshot }); + const requestedCurrent = String(source.current_attachment_id ?? '').trim(); + const rawAttachments = Array.isArray(source.attachments) ? source.attachments : []; + let currentAttachmentId = /^[1-9]\d*$/.test(requestedCurrent) ? requestedCurrent : ''; + let attachments = rawAttachments.map(value => normalizeAttachment(value, currentAttachmentId)).filter(Boolean); + if (!currentAttachmentId) currentAttachmentId = attachments.find(value => value.current)?.attachment_id || ''; + attachments = attachments.map(value => ({ ...value, current: value.attachment_id === currentAttachmentId })); + const state = ['ready', 'not_configured', 'invalid', 'drift', 'unavailable'] + .includes(source.configuration_state) ? source.configuration_state : 'unavailable'; + const hasCandidate = attachments.some((attachment) => { + const hasIpv4 = attachment.ipv4.pools.some(pool => pool.available_options.length > 0); + const hasIpv6 = attachment.ipv6.pools.some(pool => pool.sparse); + return attachment.current ? (hasIpv4 || hasIpv6) : (hasIpv4 && hasIpv6); + }); + return { + ...fallback, + current_public_network: current, + current_attachment_id: currentAttachmentId, + attachments, + configuration_state: state, + can_change: source.can_change === true && state === 'ready' && hasCandidate, + active_job: source.active_job || fallback.active_job, + message: String(source.message || ''), + }; +} + +function encodedIpv4Target(poolKey, cidr) { + return `${poolKey}|${cidr}`; +} + +function attachmentById(options, id) { + return (options.attachments || []).find(value => value.attachment_id === String(id)); +} + +export function buildAdminNetworkTargets(options, values = {}) { + if (options?.can_change !== true || options.configuration_state !== 'ready') { + throw new Error('宿主机网络配置尚未就绪,暂不能更换公网地址。'); + } + const attachment = attachmentById(options, values.attachment_id); + if (!attachment) throw new Error('请选择有效的目标网络接入。'); + const crossAttachment = attachment.attachment_id !== options.current_attachment_id; + const targets = {}; + const ipv4Value = String(values.ipv4_target || '').trim(); + if (ipv4Value) { + const separator = ipv4Value.indexOf('|'); + const poolKey = publicPoolKey(ipv4Value.slice(0, separator)); + const cidr = normalizeCidr(ipv4Value.slice(separator + 1), null); + const pool = attachment.ipv4.pools.find(item => item.pool_key === poolKey); + const available = pool && cidr && pool.available_options.some(item => item.address_cidr === cidr.value); + if (!pool || !cidr || !available) throw new Error('请选择列表中的可用 IPv4 地址。'); + if (cidr.value === options.current_public_network.ipv4.address_cidr) throw new Error('新 IPv4 与当前地址相同。'); + targets.ipv4 = { pool_key: poolKey, address_cidr: cidr.value }; + } + const ipv6PoolKey = publicPoolKey(values.ipv6_pool_key); + const ipv6Raw = String(values.ipv6_address_cidr || '').trim(); + if (ipv6PoolKey || ipv6Raw) { + if (!ipv6PoolKey || !ipv6Raw) throw new Error('选择 IPv6 地址池后必须填写完整的 IPv6 CIDR。'); + const pool = attachment.ipv6.pools.find(item => item.pool_key === ipv6PoolKey); + const cidr = normalizeIPv6Cidr(ipv6Raw, pool?.guest_prefix); + if (!pool || !pool.sparse || !cidr || cidr.prefix !== pool.guest_prefix + || !ipv6CidrContains(pool.pool_cidr, cidr.address)) { + throw new Error('IPv6 地址必须属于所选地址池,并使用该地址池的前缀。'); + } + if (cidr.number < pool.allocation_start_number + || cidr.number > pool.allocation_end_number) { + throw new Error('IPv6 地址必须位于所选地址池的可分配范围内。'); + } + if (pool.excluded_address_numbers.some(value => value === cidr.number)) { + throw new Error('IPv6 地址属于网关、DNS、保留或管理地址,不能分配。'); + } + const current = normalizeIPv6Cidr(options.current_public_network.ipv6.address_cidr, cidr.prefix); + if (current && current.number === cidr.number && current.prefix === cidr.prefix) throw new Error('新 IPv6 与当前地址相同。'); + targets.ipv6 = { pool_key: ipv6PoolKey, address_cidr: cidr.value }; + } + if (crossAttachment && (!targets.ipv4 || !targets.ipv6)) { + throw new Error('切换网络接入时必须同时指定新的 IPv4 和 IPv6。'); + } + if (!targets.ipv4 && !targets.ipv6) throw new Error('请至少选择一项要更换的公网地址。'); + return { attachment, targets }; } export function createAdminInstanceConfiguration({ @@ -321,53 +449,115 @@ export function createAdminInstanceConfiguration({ } function networkOptionsView(section, options) { - const summary = networkOptionSummary(options); const status = section.querySelector('[data-network-options-status]'); if (status) { - status.textContent = options.message || '已读取宿主机地址池约束,提交前仍会再次实时校验。'; + status.textContent = options.message || '已读取双栈地址账本;提交时会再次锁定并校验精确目标。'; status.className = 'text-muted fs-12 mb-0'; } const values = section.querySelector('[data-network-options-values]'); if (!values) return; values.replaceChildren(); - [['地址池', summary.pool], ['虚拟机前缀', summary.prefix], ['网关', summary.gateway], - ['DNS', summary.dns], ['可用地址', summary.available]].forEach(([label, value]) => { + const currentAttachment = attachmentById(options, options.current_attachment_id); + const ipv4Count = (options.attachments || []).reduce((total, attachment) => total + + attachment.ipv4.pools.reduce((count, pool) => count + pool.available_options.length, 0), 0); + const ipv6Pools = (options.attachments || []).reduce((total, attachment) => total + + attachment.ipv6.pools.filter(pool => pool.sparse).length, 0); + [['当前接入', currentAttachment?.label || '未记录'], ['候选接入', `${options.attachments.length} 个`], + ['可用 IPv4', `${ipv4Count} 个`], ['可选 IPv6 池', `${ipv6Pools} 个`]].forEach(([label, value]) => { values.append(el('dt', '', label), el('dd', 'admin-mono', value)); }); - const select = section.querySelector('[name="public_ip_cidr"]'); + const attachmentSelect = section.querySelector('[name="attachment_id"]'); const submit = section.querySelector('button[type="submit"]'); - const hasAvailable = options.available_ip_options?.length > 0; - const canChange = options.can_change === true && options.configuration_state === 'ready' && hasAvailable; - if (select instanceof HTMLSelectElement) { - select.replaceChildren(new Option(hasAvailable ? '请选择新的公网 IP' : '当前没有可用公网 IP', '')); - const poolsByKey = new Map((options.pools || []).map(pool => [pool.public_pool_key, pool])); - for (const value of options.available_ip_options || []) { - const pool = poolsByKey.get(value.public_pool_key); - const label = options.pools?.length > 1 && pool?.pool_cidr - ? `${value.public_ip_cidr} · ${pool.pool_cidr}` : value.public_ip_cidr; - const option = new Option(label, value.public_ip_cidr); - option.dataset.publicPoolKey = value.public_pool_key; select.add(option); + const canChange = options.can_change === true && options.configuration_state === 'ready'; + if (attachmentSelect instanceof HTMLSelectElement) { + attachmentSelect.replaceChildren(new Option( + options.attachments.length ? '请选择目标网络接入' : '当前没有可用网络接入', '' + )); + for (const attachment of options.attachments) { + attachmentSelect.add(new Option( + `${attachment.label}${attachment.current ? ' · 当前' : ''}`, + attachment.attachment_id + )); } - select.disabled = !canChange; - if (!hasAvailable || !canChange) select.setAttribute('aria-describedby', 'network-options-empty'); - else select.removeAttribute('aria-describedby'); + attachmentSelect.value = options.current_attachment_id; + attachmentSelect.disabled = !canChange; } + populateNetworkTargetControls(section, options); if (submit instanceof HTMLButtonElement) submit.disabled = !canChange; const empty = section.querySelector('[data-network-options-empty]'); if (empty) { empty.id = 'network-options-empty'; const blockingJob = options.active_job?.blocks_mutation === true ? options.active_job : null; empty.textContent = blockingJob ? blockMessage(blockingJob, '更换公网 IP') - : (!hasAvailable ? '当前没有可用地址,无法提交更换;请先检查地址池和占用记录。' - : (!canChange ? ({ + : (!canChange ? ({ invalid: '宿主机公网地址池配置无效,暂不能更换;请先修正宿主机配置。', drift: '实例当前网络与宿主机地址池不一致,暂不能更换;请先核对网络配置。', }[options.configuration_state] || '当前宿主机网络配置未就绪或实例已有任务,暂不能更换。') - : '只显示该宿主机当前未分配的公网 IP。')); + : '当前网络接入可以只更换一个地址族;切换到其他接入时必须同时指定 IPv4 和 IPv6。'); empty.className = `form-text mb-2${canChange ? '' : ' text-warning'}`; } } + function populateNetworkTargetControls(section, options) { + const attachmentSelect = section.querySelector('[name="attachment_id"]'); + const ipv4Select = section.querySelector('[name="ipv4_target"]'); + const ipv6PoolSelect = section.querySelector('[name="ipv6_pool_key"]'); + const ipv6Input = section.querySelector('[name="ipv6_address_cidr"]'); + const attachment = attachmentById(options, attachmentSelect?.value); + const isCurrent = attachment?.attachment_id === options.current_attachment_id; + if (ipv4Select instanceof HTMLSelectElement) { + ipv4Select.replaceChildren(new Option( + isCurrent ? '保持当前 IPv4' : '请选择新的 IPv4', '' + )); + for (const pool of attachment?.ipv4.pools || []) { + for (const option of pool.available_options) { + ipv4Select.add(new Option( + `${option.address_cidr} · ${pool.pool_cidr}`, + encodedIpv4Target(pool.pool_key, option.address_cidr) + )); + } + } + ipv4Select.disabled = !attachment || attachment.ipv4.pools.every(pool => pool.available_options.length === 0); + ipv4Select.required = !isCurrent; + } + if (ipv6PoolSelect instanceof HTMLSelectElement) { + ipv6PoolSelect.replaceChildren(new Option( + isCurrent ? '保持当前 IPv6' : '请选择 IPv6 地址池', '' + )); + for (const pool of attachment?.ipv6.pools || []) { + if (!pool.sparse) continue; + ipv6PoolSelect.add(new Option( + `${pool.pool_cidr} · 地址 /${pool.guest_prefix}`, + pool.pool_key + )); + } + ipv6PoolSelect.disabled = !attachment || ipv6PoolSelect.options.length === 1; + ipv6PoolSelect.required = !isCurrent; + } + if (ipv6Input instanceof HTMLInputElement) { + ipv6Input.value = ''; + ipv6Input.disabled = !ipv6PoolSelect?.value; + ipv6Input.required = !isCurrent; + ipv6Input.placeholder = '例如 2404:c140:156:3a::20/64'; + } + updateIpv6TargetHelp(section, options); + } + + function updateIpv6TargetHelp(section, options) { + const attachment = attachmentById(options, section.querySelector('[name="attachment_id"]')?.value); + const poolKey = publicPoolKey(section.querySelector('[name="ipv6_pool_key"]')?.value); + const pool = attachment?.ipv6.pools.find(item => item.pool_key === poolKey); + const hint = section.querySelector('[data-ipv6-target-help]'); + if (!hint) return; + if (pool) { + hint.textContent = `可分配范围 ${pool.allocation_start} – ${pool.allocation_end},必须使用 /${pool.guest_prefix};网关、DNS、保留和管理地址不可用。`; + return; + } + hint.textContent = attachment?.attachment_id === options.current_attachment_id + ? '如只更换 IPv4,可保持 IPv6 不变;选择 IPv6 地址池后填写完整 CIDR。' + : '切换网络接入时 IPv4 和 IPv6 都是必填项。'; + } + function networkOptionsErrorView(section, message) { section._networkOptions = null; section.querySelector('[data-network-options-values]')?.replaceChildren(); @@ -378,7 +568,10 @@ export function createAdminInstanceConfiguration({ edit.disabled = true; edit.setAttribute('aria-expanded', 'false'); edit.title = message; } const form = section.querySelector('.admin-instance-network-form'); - if (form) form.hidden = true; + if (form) { + form.hidden = true; + for (const control of form.querySelectorAll('select, input, button')) control.disabled = true; + } } async function loadNetworkOptions(vm, section) { @@ -387,7 +580,7 @@ export function createAdminInstanceConfiguration({ try { const payload = await read(`/api/v1/admin/instances/${encodeURIComponent(vm.id)}/network-options`, controller); if (serial !== state.networkSerial || controller.signal.aborted) return; - const options = networkOptionsPayload(payload, vm); + const options = normalizeAdminNetworkOptions(payload, vm); if (state.currentId !== String(vm.id)) return; section._networkOptions = options; networkOptionsView(section, options); } catch (error) { @@ -402,45 +595,28 @@ export function createAdminInstanceConfiguration({ function targetNetworkValue(section, vm) { const options = section._networkOptions || networkOptionsFromVm(vm); - const input = section.querySelector('[name="public_ip_cidr"]'); - if (options.can_change === false || options.configuration_state !== 'ready') { - throw new Error('宿主机网络配置尚未就绪,暂不能更换公网 IP。'); - } - if (!Array.isArray(options.available_ip_options) || options.available_ip_options.length === 0) { - throw new Error('当前宿主机没有可用公网 IP,请先补充地址池或释放地址后重试。'); - } - if (!input?.value) throw new Error('请选择新的公网 IP。'); - const selectedOption = input instanceof HTMLSelectElement ? input.selectedOptions[0] : null; - const selectedPoolKey = publicPoolKey(selectedOption?.dataset.publicPoolKey); - const selectedPool = (options.pools || []).find(pool => pool.public_pool_key === selectedPoolKey); - const parsed = normalizeCidr(input.value, selectedPool?.guest_prefix); - const available = parsed && options.available_ip_options.some(option => ( - option.public_ip_cidr === parsed.value && option.public_pool_key === selectedPoolKey - )); - if (!parsed || !selectedPool || !available) throw new Error('请选择列表中的可用公网 IP,不支持手动填写。'); - if (parsed.prefix !== Number(selectedPool.guest_prefix)) { - throw new Error(`地址前缀必须为 /${selectedPool.guest_prefix},请不要修改宿主机分配的前缀。`); - } - if (!cidrContains(selectedPool.pool_cidr, parsed.address)) { - throw new Error(`目标地址不在宿主机地址池 ${selectedPool.pool_cidr} 内。`); - } - const current = normalizeCidr(vm.public_ip_cidr || vm.public_ip, parsed.prefix); - if (current?.value === parsed.value) throw new Error('新公网 IP 与当前配置相同。'); - const blocked = [selectedPool.gateway, ...(selectedPool.dns_servers || [])] - .map(value => parseIPv4(value)?.join('.')).filter(Boolean); - if (blocked.includes(parsed.address)) throw new Error('目标地址是网关、DNS 或保留地址,不能分配给虚拟机。'); - return { public_ip_cidr: parsed.value, public_pool_key: selectedPoolKey, pool: selectedPool }; + return buildAdminNetworkTargets(options, { + attachment_id: section.querySelector('[name="attachment_id"]')?.value, + ipv4_target: section.querySelector('[name="ipv4_target"]')?.value, + ipv6_pool_key: section.querySelector('[name="ipv6_pool_key"]')?.value, + ipv6_address_cidr: section.querySelector('[name="ipv6_address_cidr"]')?.value, + }); } function makeNetworkConfirmation(section, vm, target, options) { - const current = normalizeCidr(vm.public_ip_cidr || vm.public_ip, options.guest_prefix || 24)?.value || '未记录'; const confirmation = section.querySelector('[data-network-confirmation]'); const summary = confirmation?.querySelector('[data-network-confirm-summary]'); const check = confirmation?.querySelector('[data-network-confirm-check]'); const submit = confirmation?.querySelector('[data-network-confirm-submit]'); if (!confirmation || !summary || !check || !submit) return null; - const network = networkOptionSummary(options, target.pool); - summary.textContent = `公网地址将从 ${current} 更换为 ${target.public_ip_cidr}。运行中的实例会受控关机并重新启动,已关机实例保持关机;地址池 ${network.pool}、网关 ${network.gateway}、DNS ${network.dns} 将按宿主机配置应用。运行中实例的网络会短暂中断。`; + const changes = []; + const currentAttachment = attachmentById(options, options.current_attachment_id); + changes.push(target.attachment.attachment_id === options.current_attachment_id + ? `网络接入:保持 ${target.attachment.label}` + : `网络接入:${currentAttachment?.label || '当前接入'} → ${target.attachment.label}`); + if (target.targets.ipv4) changes.push(`IPv4:${options.current_public_network.ipv4.address_cidr || '未记录'} → ${target.targets.ipv4.address_cidr}`); + if (target.targets.ipv6) changes.push(`IPv6:${options.current_public_network.ipv6.address_cidr || '未记录'} → ${target.targets.ipv6.address_cidr}`); + summary.textContent = `${changes.join(';')}。运行中的实例会受控关机并重新启动,已关机实例保持关机;运行中连接会短暂中断。`; check.checked = false; submit.disabled = true; confirmation.hidden = false; return { confirmation, check, submit }; } @@ -491,10 +667,17 @@ export function createAdminInstanceConfiguration({ if (edit && vm.network_change_supported === true) heading.append(edit); section.append(heading); const current = el('div', 'admin-instance-network-current mt-3'); - const currentValue = el('span', 'admin-instance-network-current-value'); - currentValue.append(el('strong', 'admin-mono', text(vm.public_ip_cidr, vm.public_ip, '未记录'))); - if (vm.public_ip) currentValue.append(copyButton(vm.public_ip, '复制当前公网 IP')); - current.append(el('span', 'text-muted fs-13', '当前公网地址'), currentValue); section.append(current); + const current4 = el('span', 'admin-instance-network-current-value'); + current4.append(el('strong', 'admin-mono', text(vm.public_ipv4_cidr, vm.public_ip_cidr, vm.public_ipv4, vm.public_ip, '未记录'))); + if (vm.public_ipv4 || vm.public_ip) current4.append(copyButton(vm.public_ipv4 || vm.public_ip, '复制当前 IPv4')); + const current6 = el('span', 'admin-instance-network-current-value'); + current6.append(el('strong', 'admin-mono', text(vm.public_ipv6_cidr, vm.public_ipv6, '未记录'))); + if (vm.public_ipv6) current6.append(copyButton(vm.public_ipv6, '复制当前 IPv6')); + current.append( + el('span', 'text-muted fs-13', '当前 IPv4'), current4, + el('span', 'text-muted fs-13', '当前 IPv6'), current6 + ); + section.append(current); if (!edit) { if (controls) section.append(controls); return section; } if (vm.network_change_supported !== true) { section.append(el('p', 'text-warning fs-13 mt-3 mb-0', @@ -511,11 +694,17 @@ export function createAdminInstanceConfiguration({ section.append(optionsBox); if (controls) section.append(controls); const form = section.querySelector('.admin-instance-network-form'); if (!form) return section; - const input = form.elements.namedItem('public_ip_cidr'); + const attachmentSelect = form.elements.namedItem('attachment_id'); + const ipv4Select = form.elements.namedItem('ipv4_target'); + const ipv6PoolSelect = form.elements.namedItem('ipv6_pool_key'); + const ipv6Input = form.elements.namedItem('ipv6_address_cidr'); const feedback = section.querySelector('.admin-instance-network-feedback'); const submit = form.querySelector('button[type="submit"]'); const cancelButton = form.querySelector('[data-network-edit="cancel"]'); - input.value = ''; input.disabled = true; submit.disabled = true; + for (const control of [attachmentSelect, ipv4Select, ipv6PoolSelect, ipv6Input]) { + if (control) { control.value = ''; control.disabled = true; } + } + submit.disabled = true; const confirmation = el('div', 'admin-instance-network-confirmation mt-3'); confirmation.hidden = true; confirmation.dataset.networkConfirmation = ''; confirmation.setAttribute('role', 'alertdialog'); @@ -541,28 +730,46 @@ export function createAdminInstanceConfiguration({ edit.addEventListener('click', () => { if (edit.disabled) return; form.hidden = false; edit.setAttribute('aria-expanded', 'true'); - feedback.hidden = true; input?.focus(); + feedback.hidden = true; attachmentSelect?.focus(); + }); + attachmentSelect?.addEventListener('change', () => { + populateNetworkTargetControls(section, section._networkOptions || networkOptionsFromVm(vm)); + if (!feedback.hidden) setNetworkFeedback(section, ''); + }); + ipv6PoolSelect?.addEventListener('change', () => { + if (ipv6Input) { + ipv6Input.disabled = !ipv6PoolSelect.value; + ipv6Input.value = ''; + if (!ipv6Input.disabled) ipv6Input.focus(); + } + updateIpv6TargetHelp(section, section._networkOptions || networkOptionsFromVm(vm)); + if (!feedback.hidden) setNetworkFeedback(section, ''); }); form.addEventListener('submit', event => { event.preventDefault(); if (state.networkRequest || mutationBlocked) return; let target; try { target = targetNetworkValue(section, vm); } - catch (error) { setNetworkFeedback(section, error.message, 'danger'); input.focus(); return; } + catch (error) { setNetworkFeedback(section, error.message, 'danger'); attachmentSelect?.focus(); return; } const options = section._networkOptions || networkOptionsFromVm(vm); form.hidden = true; edit.hidden = true; setNetworkFeedback(section, ''); makeNetworkConfirmation(section, vm, target, options); section._networkTarget = target; section.querySelector('[data-network-confirm-check]')?.focus(); }); - input.addEventListener('input', () => { if (!feedback.hidden) setNetworkFeedback(section, ''); }); + for (const control of [ipv4Select, ipv6Input]) { + control?.addEventListener('input', () => { if (!feedback.hidden) setNetworkFeedback(section, ''); }); + } cancelButton?.addEventListener('click', () => { form.hidden = true; confirmation.hidden = true; edit.hidden = false; - edit.setAttribute('aria-expanded', 'false'); input.value = ''; setNetworkFeedback(section, ''); + edit.setAttribute('aria-expanded', 'false'); + populateNetworkTargetControls(section, section._networkOptions || networkOptionsFromVm(vm)); + section._networkTarget = null; + setNetworkFeedback(section, ''); }); check.addEventListener('change', () => { confirmSubmit.disabled = !check.checked; }); back.addEventListener('click', () => { confirmation.hidden = true; form.hidden = false; edit.hidden = false; - edit.setAttribute('aria-expanded', 'true'); input.focus(); + edit.setAttribute('aria-expanded', 'true'); attachmentSelect?.focus(); }); confirmSubmit.addEventListener('click', async () => { if (!check.checked || state.networkRequest || mutationBlocked) return; @@ -572,8 +779,7 @@ export function createAdminInstanceConfiguration({ setNetworkFeedback(section, '正在创建网络变更任务,请勿重复提交…', 'muted'); try { const result = await enqueue(`/api/v1/admin/instances/${encodeURIComponent(vm.id)}/network`, { - public_ip_cidr: target.public_ip_cidr, - public_pool_key: target.public_pool_key, + targets: target.targets, confirm_restart: true, }, controller); const jobId = result?.task_id; diff --git a/web/public/cloud/admin.css b/web/public/cloud/admin.css index 194c8b67..3c7d6fe4 100644 --- a/web/public/cloud/admin.css +++ b/web/public/cloud/admin.css @@ -2192,3 +2192,78 @@ gap: 4px; } } + +.admin-instance-network-current { + display: grid; + grid-template-columns: minmax(110px, 0.35fr) minmax(0, 1fr); + gap: 9px 16px; + align-items: center; +} + +.admin-instance-network-current-value { + display: flex; + min-width: 0; + align-items: center; + gap: 8px; + overflow-wrap: anywhere; +} + +.admin-instance-network-options { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 10px; + margin: 0; +} + +.admin-instance-network-options dt, +.admin-instance-network-options dd { + margin: 0; +} + +.admin-instance-network-options dd { + overflow-wrap: anywhere; +} + +.admin-instance-network-target-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; +} + +.admin-instance-network-family { + min-width: 0; + padding: 14px; + border: 1px solid #dfe7ef; + border-radius: 12px; + background: #f8fafc; +} + +.admin-instance-network-family legend { + float: none; + width: auto; + margin: 0 0 10px; + color: #26394f; + font-size: 13px; + font-weight: 800; +} + +.admin-instance-network-field { + display: block; + min-width: 0; +} + +@media (max-width: 720px) { + .admin-instance-network-options, + .admin-instance-network-target-grid { + grid-template-columns: minmax(0, 1fr); + } + + .admin-instance-network-current { + grid-template-columns: minmax(0, 1fr); + gap: 4px; + } + + .admin-instance-network-current-value + .text-muted { + margin-top: 8px; + } +} diff --git a/web/resources/views/venix/admin/cloud/instances.tpl b/web/resources/views/venix/admin/cloud/instances.tpl index 74788850..c8109124 100644 --- a/web/resources/views/venix/admin/cloud/instances.tpl +++ b/web/resources/views/venix/admin/cloud/instances.tpl @@ -78,8 +78,21 @@ {if $admin_can_manage|default:false} diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index e6306c59..397be966 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026110301' scope='global'} +{assign var=venix_asset_version value='2026110302' scope='global'} diff --git a/web/tests/AdminBillingApiContractTest.php b/web/tests/AdminBillingApiContractTest.php index cf361ecc..44698227 100644 --- a/web/tests/AdminBillingApiContractTest.php +++ b/web/tests/AdminBillingApiContractTest.php @@ -329,7 +329,7 @@ $assert(str_contains($invoicePresentation, && !str_contains($invoicePresentation, 'match (strtolower($status))'), 'User invoice statuses must translate catalog tones, not rebuild semantics.'); $assert(str_contains($layoutAssets, - "venix_asset_version value='2026110301'") + "venix_asset_version value='2026110302'") && str_contains($template, '/cloud/admin-billing.js?v={$venix_asset_version}'), 'Administrator billing asset changes must advance the shared cache key.'); diff --git a/web/tests/AdminInstanceNetworkBehaviorTest.mjs b/web/tests/AdminInstanceNetworkBehaviorTest.mjs new file mode 100644 index 00000000..e902b011 --- /dev/null +++ b/web/tests/AdminInstanceNetworkBehaviorTest.mjs @@ -0,0 +1,171 @@ +import assert from 'node:assert/strict'; +import { + buildAdminNetworkTargets, + normalizeAdminNetworkOptions, +} from '../public/cloud/admin-instance-configuration.js'; + +const key4a = 'a'.repeat(32); +const key6a = 'b'.repeat(32); +const key4b = 'c'.repeat(32); +const key6b = 'd'.repeat(32); +let fetchCalls = 0; +const originalFetch = globalThis.fetch; +globalThis.fetch = async () => { + fetchCalls += 1; + throw new Error('Target validation must not fetch.'); +}; + +const options = normalizeAdminNetworkOptions({ + current_public_network: { + contract: 1, + network_selector: 'br0', + ipv4: { pool_key: key4a, pool_cidr: '8.8.8.0/24', address_cidr: '8.8.8.10/24', gateway: '8.8.8.1', gateway_on_link: false }, + ipv6: { pool_key: key6a, pool_cidr: '2404:c140:156:3a::/64', address_cidr: '2404:c140:156:3a::10/64', gateway: '2404:c140:156::1', gateway_on_link: true }, + dns_servers: ['1.1.1.1', '2606:4700:4700::1111'], + }, + current_attachment_id: '1', + attachments: [ + { + attachment_id: '1', label: 'br0 · 当前', current: true, + ipv4: { pools: [{ pool_key: key4a, cidr: '8.8.8.0/24', guest_prefix: 24, + gateway: '8.8.8.1', available_options: [{ address_cidr: '8.8.8.22/24' }] }] }, + ipv6: { pools: [{ pool_key: key6a, cidr: '2404:c140:156:3a::/64', + guest_prefix: 64, gateway: '2404:c140:156::1', sparse: true, + allocation_start: '2404:c140:156:3a::10', + allocation_end: '2404:c140:156:3a::ff', + excluded_addresses: ['2404:c140:156:3a::20'] }] }, + }, + { + attachment_id: '2', label: 'br1 · 备用线路', current: false, + ipv4: { pools: [{ pool_key: key4b, cidr: '9.9.9.0/24', guest_prefix: 24, + gateway: '9.9.9.1', available_options: [{ address_cidr: '9.9.9.20/24' }] }] }, + ipv6: { pools: [{ pool_key: key6b, cidr: '2404:c140:156:3b::/64', + guest_prefix: 64, gateway: '2404:c140:156::1', sparse: true, + allocation_start: '2404:c140:156:3b::10', + allocation_end: '2404:c140:156:3b::ff', + excluded_addresses: ['2404:c140:156:3b::20'] }] }, + }, + ], + configuration_state: 'ready', + can_change: true, +}); + +assert.equal(options.attachments.length, 2); +assert.equal(options.current_public_network.ipv6.address_cidr, '2404:c140:156:3a::10/64'); + +const currentIpv4Only = buildAdminNetworkTargets(options, { + attachment_id: '1', ipv4_target: `${key4a}|8.8.8.22/24`, +}); +assert.deepEqual(currentIpv4Only.targets, { + ipv4: { pool_key: key4a, address_cidr: '8.8.8.22/24' }, +}); + +const currentIpv6Only = buildAdminNetworkTargets(options, { + attachment_id: '1', ipv6_pool_key: key6a, + ipv6_address_cidr: '2404:c140:156:3a::22/64', +}); +assert.deepEqual(currentIpv6Only.targets, { + ipv6: { pool_key: key6a, address_cidr: '2404:c140:156:3a::22/64' }, +}); + +assert.throws(() => buildAdminNetworkTargets(options, { + attachment_id: '2', ipv4_target: `${key4b}|9.9.9.20/24`, +}), /同时指定新的 IPv4 和 IPv6/); + +const crossAttachment = buildAdminNetworkTargets(options, { + attachment_id: '2', ipv4_target: `${key4b}|9.9.9.20/24`, + ipv6_pool_key: key6b, ipv6_address_cidr: '2404:c140:156:3b::21/64', +}); +assert.deepEqual(crossAttachment.targets, { + ipv4: { pool_key: key4b, address_cidr: '9.9.9.20/24' }, + ipv6: { pool_key: key6b, address_cidr: '2404:c140:156:3b::21/64' }, +}); + +for (const address of ['2404:c140:156:3b::10/64', '2404:c140:156:3b::ff/64']) { + const boundary = buildAdminNetworkTargets(options, { + attachment_id: '2', ipv4_target: `${key4b}|9.9.9.20/24`, + ipv6_pool_key: key6b, ipv6_address_cidr: address, + }); + assert.equal(boundary.targets.ipv6.address_cidr, address); +} + +const optionsBeforeRejectedTargets = JSON.stringify(options, (_, value) => + typeof value === 'bigint' ? value.toString() : value); +assert.throws(() => buildAdminNetworkTargets(options, { + attachment_id: '2', ipv4_target: `${key4b}|9.9.9.20/24`, + ipv6_pool_key: key6b, ipv6_address_cidr: '2404:c140:156:3b::100/64', +}), /可分配范围内/); +assert.throws(() => buildAdminNetworkTargets(options, { + attachment_id: '2', ipv4_target: `${key4b}|9.9.9.20/24`, + ipv6_pool_key: key6b, ipv6_address_cidr: '2404:c140:156:3b::20/64', +}), /网关、DNS、保留或管理地址/); + +assert.throws(() => buildAdminNetworkTargets(options, { + attachment_id: '1', ipv6_pool_key: key6a, + ipv6_address_cidr: '2404:c140:156:3b::20/64', +}), /必须属于所选地址池/); + +const singleFamilyAlternative = normalizeAdminNetworkOptions({ + current_public_network: options.current_public_network, + current_attachment_id: '1', + attachments: [ + { + attachment_id: '1', current: true, + ipv4: { pools: [] }, ipv6: { pools: [] }, + }, + { + attachment_id: '2', current: false, + ipv4: { pools: [{ + pool_key: key4b, cidr: '9.9.9.0/24', guest_prefix: 24, + gateway: '9.9.9.1', + available_options: [{ address_cidr: '9.9.9.20/24' }], + }] }, + ipv6: { pools: [] }, + }, + ], + configuration_state: 'ready', can_change: true, +}); +assert.equal(singleFamilyAlternative.can_change, false); +assert.throws(() => buildAdminNetworkTargets(singleFamilyAlternative, { + attachment_id: '2', ipv4_target: `${key4b}|9.9.9.20/24`, +}), /暂不能更换公网地址/); + +const prefixMismatch = normalizeAdminNetworkOptions({ + current_public_network: options.current_public_network, + current_attachment_id: '1', + attachments: [ + { + attachment_id: '1', current: true, + ipv4: { pools: [] }, ipv6: { pools: [] }, + }, + { + attachment_id: '2', current: false, + ipv4: { pools: [{ + pool_key: key4b, cidr: '9.9.9.0/24', guest_prefix: 24, + gateway: '9.9.9.1', + available_options: [{ address_cidr: '9.9.9.20/24' }], + }] }, + ipv6: { pools: [{ + pool_key: key6b, cidr: '2404:c140:156:3b::/56', + guest_prefix: 64, gateway: '2404:c140:156::1', sparse: true, + allocation_start: '2404:c140:156:3b::10', + allocation_end: '2404:c140:156:3b::ff', + excluded_addresses: [], + }] }, + }, + ], + configuration_state: 'ready', can_change: true, +}); +assert.equal(prefixMismatch.attachments[1].ipv6.pools.length, 0); +assert.equal(prefixMismatch.can_change, false); +assert.throws(() => buildAdminNetworkTargets(prefixMismatch, { + attachment_id: '2', ipv4_target: `${key4b}|9.9.9.20/24`, + ipv6_pool_key: key6b, ipv6_address_cidr: '2404:c140:156:3b::21/64', +}), /暂不能更换公网地址/); + +assert.equal(fetchCalls, 0); +assert.equal(JSON.stringify(options, (_, value) => + typeof value === 'bigint' ? value.toString() : value), optionsBeforeRejectedTargets); +globalThis.fetch = originalFetch; + +console.log('Administrator dual-stack network target behavior passed.'); diff --git a/web/tests/AdminInstanceViewTest.php b/web/tests/AdminInstanceViewTest.php index 43eb8648..dfff1008 100644 --- a/web/tests/AdminInstanceViewTest.php +++ b/web/tests/AdminInstanceViewTest.php @@ -153,6 +153,14 @@ $assert(is_string($configurationScript) && str_contains($configurationScript, 'return Object.freeze({ render, cancel, dispose: cancel })'), 'Network and guest settings must share one cancellable configuration interface.'); +$assert(str_contains($configurationScript, + 'export function normalizeAdminNetworkOptions(') + && str_contains($configurationScript, + 'export function buildAdminNetworkTargets(') + && str_contains($configurationScript, 'targets: target.targets') + && !str_contains($configurationScript, + 'public_ip_cidr: target.public_ip_cidr'), + 'Administrator network changes must submit one validated dual-stack target object.'); $assert(is_string($backupScript) && str_contains($clientScript, "import(versionedModuleUrl('./admin-instance-backups.js'))") @@ -201,6 +209,11 @@ $assert($xpath->query('//*[@data-admin-instance-drawer]//*[@data-instance-tab]') && !str_contains($html, 'instance-panel-basic') && !str_contains($html, 'instance-panel-invoices'), 'The instance workspace must expose five cohesive sections and open on the overview tab.'); +$assert($xpath->query('//template[@id="admin-instance-network-controls"]//select[@name="attachment_id"]')->length === 1 + && $xpath->query('//template[@id="admin-instance-network-controls"]//select[@name="ipv4_target"]')->length === 1 + && $xpath->query('//template[@id="admin-instance-network-controls"]//select[@name="ipv6_pool_key"]')->length === 1 + && $xpath->query('//template[@id="admin-instance-network-controls"]//input[@name="ipv6_address_cidr"]')->length === 1, + 'The administrator network editor must expose one attachment-bound IPv4 and sparse IPv6 target form.'); $assert(str_contains($dom->textContent, '8.8.8.101') && str_contains($dom->textContent, '2404:c140:156:3a::101') && str_contains($dom->textContent, '20 GiB / 100 GiB') diff --git a/web/tests/CloudAdminInstanceServiceTest.php b/web/tests/CloudAdminInstanceServiceTest.php index 88bbcd55..3acd1b9d 100644 --- a/web/tests/CloudAdminInstanceServiceTest.php +++ b/web/tests/CloudAdminInstanceServiceTest.php @@ -730,8 +730,10 @@ namespace { && $ids($detail['invoices']) === $expectedInvoiceIds, 'Invoice detail included a foreign owner, missed the valid order link, or silently truncated history.'); $crossOwner = CloudAdminInstanceService::detail($admin, '207'); - $assert($crossOwner['invoices'] === [], - 'A same-owner invoice joined through another owner\'s order crossed the billing boundary.'); + $assert($crossOwner['invoices'] === [] + && $crossOwner['instance']['network_change_supported'] === false + && $crossOwner['instance']['instance_settings_supported'] === false, + 'An expired instance exposed mutation controls or crossed the billing boundary.'); foreach ($detail['invoices'] as $invoice) { $assert(str_starts_with($invoice['detail_url'], '/admin/billing?detail='), 'Invoice links must target the administrator ledger, not the customer route.'); diff --git a/web/tests/CloudAdminInstanceSettingsBehaviorTest.php b/web/tests/CloudAdminInstanceSettingsBehaviorTest.php new file mode 100644 index 00000000..e2b9d3ab --- /dev/null +++ b/web/tests/CloudAdminInstanceSettingsBehaviorTest.php @@ -0,0 +1,152 @@ +id = 91; + return $job; + } + } +} + +namespace { + require dirname(__DIR__) . '/vendor/autoload.php'; + + use App\Controllers\CloudAdminInstanceController; + use App\Services\Cloud\AdminSettingsJobCapture; + use App\Services\Cloud\CloudError; + use Illuminate\Database\Capsule\Manager as Capsule; + use Illuminate\Database\Schema\Blueprint; + use Slim\Http\Environment; + use Slim\Http\Request; + use Slim\Http\Response; + + $assert = static function (bool $condition, string $message): void { + if (!$condition) { throw new RuntimeException($message); } + }; + $rejects = static function (callable $callback, string $message): void { + try { $callback(); } catch (CloudError $error) { + if ($error->httpStatus === 409) { return; } + throw new RuntimeException($message . ': unexpected status'); + } + throw new RuntimeException($message); + }; + + $capsule = new Capsule(); + $capsule->addConnection([ + 'driver' => 'sqlite', 'database' => ':memory:', + ], 'default'); + $capsule->setAsGlobal(); + $capsule->bootEloquent(); + $capsule->schema('default')->create('cloud_instances', static function ( + Blueprint $t + ): void { + $t->increments('id'); $t->integer('user_id'); $t->string('uuid'); + $t->string('status'); $t->string('service_status'); + $t->integer('expires_at')->nullable(); $t->text('spec_json'); + $t->text('sealed_credential')->nullable(); + }); + $now = time(); + $network = [ + 'contract' => 1, 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'pool_key' => str_repeat('a', 32), + 'pool_cidr' => '8.8.8.0/24', + 'address_cidr' => '8.8.8.10/24', + 'gateway' => '8.8.8.1', 'gateway_on_link' => false, + ], + 'ipv6' => [ + 'pool_key' => str_repeat('b', 32), + 'pool_cidr' => '2404:c140:156:3a::/64', + 'address_cidr' => '2404:c140:156:3a::10/64', + 'gateway' => '2404:c140:156::1', 'gateway_on_link' => true, + ], + 'dns_servers' => ['1.1.1.1', '2606:4700:4700::1111'], + ]; + $spec = json_encode([ + 'managed' => true, 'os_source' => 'cloud_template', + 'public_network' => $network, + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES); + Capsule::table('cloud_instances')->insert([ + [ + 'id' => 1, 'user_id' => 7, + 'uuid' => '00000000-0000-4000-8000-000000000001', + 'status' => 'active', 'service_status' => 'active', + 'expires_at' => $now + 3600, 'spec_json' => $spec, + 'sealed_credential' => null, + ], + [ + 'id' => 2, 'user_id' => 7, + 'uuid' => '00000000-0000-4000-8000-000000000002', + 'status' => 'active', 'service_status' => 'active', + 'expires_at' => $now + 3600, + 'spec_json' => json_encode([ + 'managed' => true, 'os_source' => 'cloud_template', + 'public_ip_cidr' => '8.8.8.20/24', + ], JSON_THROW_ON_ERROR), + 'sealed_credential' => null, + ], + [ + 'id' => 3, 'user_id' => 7, + 'uuid' => '00000000-0000-4000-8000-000000000003', + 'status' => 'active', 'service_status' => 'expired', + 'expires_at' => $now - 1, 'spec_json' => $spec, + 'sealed_credential' => null, + ], + ]); + $actor = [ + 'user_id' => 99, 'is_admin' => true, + 'is_super_admin' => true, 'can_manage' => true, + ]; + $request = static function (int $id) use ($actor): Request { + return Request::createFromEnvironment(Environment::mock([ + 'REQUEST_METHOD' => 'POST', + 'REQUEST_URI' => '/api/v1/admin/instances/' . $id . '/settings', + ]))->withAttribute('cloud_actor', $actor)->withParsedBody([ + 'hostname' => 'canonical-host', 'confirm_restart' => true, + ]); + }; + $controller = new CloudAdminInstanceController(); + $response = $controller->settings( + $request(1), new Response(), ['id' => '1'] + ); + $payload = json_decode((string) $response->getBody(), true); + $assert($response->getStatusCode() === 202 + && ($payload['task_id'] ?? null) === '91' + && (AdminSettingsJobCapture::$calls[0]['body']['hostname'] ?? null) + === 'canonical-host', + 'Canonical-only dual-stack metadata did not admit guest settings.'); + $before = count(AdminSettingsJobCapture::$calls); + $rejects( + static fn () => $controller->settings( + $request(2), new Response(), ['id' => '2'] + ), + 'Legacy scalar-only metadata admitted guest settings.' + ); + $rejects( + static fn () => $controller->settings( + $request(3), new Response(), ['id' => '3'] + ), + 'An expired instance admitted guest settings.' + ); + $assert(count(AdminSettingsJobCapture::$calls) === $before, + 'Rejected settings requests queued a job.'); + + echo "Canonical administrator settings behavior passed.\n"; +} diff --git a/web/tests/CloudAssetVersionContractTest.php b/web/tests/CloudAssetVersionContractTest.php index b27207b6..c0f9634b 100644 --- a/web/tests/CloudAssetVersionContractTest.php +++ b/web/tests/CloudAssetVersionContractTest.php @@ -15,7 +15,7 @@ $assert = static function (bool $condition, string $message): void { }; $assert(is_string($assets) - && str_contains($assets, "venix_asset_version value='2026110301'") + && str_contains($assets, "venix_asset_version value='2026110302'") && is_string($cloudShell) && str_contains($cloudShell, '/cloud/app.js?v={$venix_asset_version}'), 'The cloud application entry must use the shared Venix asset version.'); diff --git a/web/tests/CloudFinancialWorkflowTest.php b/web/tests/CloudFinancialWorkflowTest.php index 82645a23..7d4920fa 100644 --- a/web/tests/CloudFinancialWorkflowTest.php +++ b/web/tests/CloudFinancialWorkflowTest.php @@ -159,6 +159,8 @@ namespace { use App\Services\Cloud\CloudError; use App\Services\Cloud\CloudMoney; use App\Services\Cloud\CloudPlatformTestNetworkPolicy; + use App\Services\Cloud\CloudPublicNetworkTransitionCommand; + use App\Services\Cloud\CloudPublicNetworkTransitionWorkflow; use App\Services\Cloud\CloudDeploymentPageService; use App\Services\Cloud\CloudTemplateCatalogService; use App\Services\Cloud\CloudAgentSettingsService; @@ -299,7 +301,10 @@ namespace { $schema->create('cloud_order_items', function (Blueprint $t) { $t->increments('id'); $t->integer('order_id'); $t->string('code'); $t->string('label'); $t->string('amount'); $t->string('currency')->default('USD'); $t->text('snapshot_json'); $t->integer('created_at'); $t->unique(['order_id', 'code']); }); $schema->create('cloud_resource_reservations', function (Blueprint $t) { $t->increments('id'); $t->string('reservation_key')->unique(); $t->string('operation_id')->unique(); $t->integer('order_id')->nullable(); $t->integer('backup_restore_id')->nullable(); $t->integer('offer_id')->nullable(); foreach (['resource_pool_id', 'host_id', 'user_id'] as $v) { $t->integer($v); } $t->integer('instance_id')->nullable(); $t->integer('network_attachment_id')->nullable(); $t->integer('public_ip_pool_id')->nullable(); $t->integer('public_ip_id')->nullable(); foreach (['cpu_cores', 'memory_mib', 'disk_gib'] as $v) { $t->integer($v); } $t->string('state'); $t->integer('expires_at')->nullable(); $t->integer('released_at')->nullable(); $t->string('release_reason')->default(''); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); $t->unique('backup_restore_id'); }); $schema->create('cloud_resource_reservation_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('reservation_id'); $t->integer('address_family'); $t->integer('claim_generation')->default(1); $t->integer('active_claim')->nullable()->default(1); $t->integer('network_attachment_id'); $t->integer('public_ip_pool_id'); $t->integer('public_ip_id'); $t->string('operation_id'); $t->string('state'); $t->integer('created_at'); $t->integer('updated_at'); $t->integer('released_at')->nullable(); $t->string('release_reason')->default(''); $t->unique(['reservation_id', 'address_family', 'active_claim']); $t->unique(['reservation_id', 'claim_generation', 'address_family']); }); + $schema->create('cloud_public_network_transitions', function (Blueprint $t) { $t->increments('id'); $t->string('transition_key')->unique(); $t->string('operation_id')->unique(); $t->string('kind'); $t->integer('instance_id'); $t->integer('host_id'); $t->integer('reservation_id'); $t->integer('invoice_id')->nullable()->unique(); $t->integer('pool_replacement_batch_item_id')->nullable()->unique(); $t->integer('requested_by_user_id'); $t->integer('source_network_attachment_id'); $t->integer('target_network_attachment_id'); $t->string('source_claim_set_sha256'); $t->string('target_claim_set_sha256'); $t->text('source_public_network_json'); $t->string('source_public_network_sha256'); $t->text('target_public_network_json'); $t->string('target_public_network_sha256'); $t->string('state'); $t->string('effect_resolution'); $t->integer('active_transition')->nullable(); $t->string('last_error_code'); $t->integer('effect_resolved_at')->nullable(); $t->integer('terminal_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['instance_id', 'active_transition']); $t->unique(['reservation_id', 'active_transition']); }); + $schema->create('cloud_public_network_transition_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('transition_id'); $t->integer('address_family'); $t->integer('source_claim_id'); $t->integer('target_claim_id')->nullable()->unique(); $t->boolean('changed'); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['transition_id', 'address_family']); }); $schema->create('cloud_backup_restores', function (Blueprint $t) { $t->increments('id'); $t->string('restore_key')->unique(); $t->integer('backup_id'); $t->integer('target_host_id'); $t->integer('target_instance_id')->nullable(); $t->integer('reservation_id')->nullable()->unique(); $t->integer('job_id')->nullable(); $t->string('operation_id')->unique(); $t->string('new_uuid'); $t->string('new_name'); $t->string('state'); $t->string('error_code')->default(''); $t->integer('ready_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); }); + $schema->create('cloud_backup_recoveries', function (Blueprint $t) { $t->increments('id'); $t->integer('instance_id'); $t->string('state'); }); $schema->create('cloud_instance_migrations', function (Blueprint $t) { $t->increments('id'); $t->integer('instance_id'); $t->integer('restore_id'); $t->integer('source_host_id'); $t->integer('source_reservation_id'); $t->integer('target_host_id'); $t->integer('target_reservation_id'); $t->string('state'); }); $schema->create('cloud_instance_backups', function (Blueprint $t) { $t->increments('id'); $t->string('backup_key')->unique(); $t->integer('source_instance_id'); $t->integer('source_host_id'); $t->integer('user_id'); $t->string('source_uuid'); $t->string('name'); $t->string('purpose')->default('portable'); $t->string('source')->default('manual'); $t->integer('subscription_id')->nullable(); $t->integer('scheduled_for')->nullable(); $t->string('state')->default('creating'); $t->string('consistency'); $t->string('object_key')->unique(); $t->integer('object_size_bytes')->default(0); $t->integer('virtual_size_bytes')->default(0); $t->string('sha256')->default(''); $t->text('spec_json'); $t->text('sealed_storage_runtime'); $t->text('sealed_credential')->nullable(); $t->integer('storage_revision'); $t->integer('active_job_id')->nullable(); $t->string('last_operation_id')->nullable(); $t->string('error_code')->default(''); $t->integer('ready_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['subscription_id', 'scheduled_for']); }); $schema->create('cloud_deployment_snapshots', function (Blueprint $t) { $t->increments('id'); $t->string('snapshot_key')->unique(); $t->integer('user_id'); $t->integer('backup_id')->unique(); $t->integer('source_instance_id'); $t->string('name'); $t->string('state')->default('ready'); $t->string('idempotency_key'); $t->string('request_hash'); $t->string('error_code')->default(''); $t->integer('ready_at'); $t->integer('deleted_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); }); @@ -311,7 +316,7 @@ namespace { foreach ([ 'parent_job_id', 'supersedes_job_id', 'order_id', 'invoice_id', 'instance_id', 'snapshot_id', 'backup_id', 'backup_restore_id', - 'vpc_repair_root_job_id', + 'vpc_repair_root_job_id', 'public_network_transition_id', ] as $v) { $t->integer($v)->nullable(); } @@ -2374,10 +2379,140 @@ namespace { 'test fixture confirms replacement guest committed'; $partialJob->save(); - // A network change reserves only a locally available target. The encrypted - // job keeps both ledger IDs, while the Agent receives only its existing - // request body. An ambiguous response keeps both addresses unavailable and - // a reconciled success atomically moves the reservation to the target. + // A transition-owned network change crosses the complete Worker path + // exactly once and publishes only the exact typed public_network result. + $networkTargetIp = new CloudPublicIp(); + $networkTargetIp->host_id = (int) $host->id; + $networkTargetIp->public_ip_pool_id = (int) $sourcePublicPool->id; + $networkTargetIp->address_family = 4; + $networkTargetIp->address = '8.8.8.200'; + $networkTargetIp->address_binary = inet_pton('8.8.8.200'); + $networkTargetIp->prefix_length = 24; + $networkTargetIp->state = 'available'; + $networkTargetIp->created_at = $networkTargetIp->updated_at = time(); + $networkTargetIp->save(); + $networkDispatch = CloudPublicNetworkTransitionWorkflow::begin( + CloudPublicNetworkTransitionCommand::adminExact( + (int) $instance->id, + 99, + 'financial-network-transition-0001', + [4 => [ + 'pool_key' => $sourcePoolKey, + 'address_cidr' => '8.8.8.200/24', + ]] + ) + ); + $networkJob = CloudJob::find($networkDispatch->jobId()); + $networkPayload = \App\Services\Cloud\CloudSecrets::decrypt( + (string) $networkJob->sealed_payload, + 'job-payload' + ); + $networkIdentity = CloudOperationRecoveryIdentity::expectedFromPayload( + $networkJob, + $networkPayload, + true + ); + $networkTarget = $networkDispatch->target()->toArray(); + $mock->append(new Response(200, [], json_encode([ + 'operation_id' => (string) $networkJob->operation_id, + 'status' => 'succeeded', + ...$networkIdentity, + 'result' => [ + 'uuid' => (string) $instance->uuid, + 'network_changed' => true, + 'public_network' => $networkTarget, + ], + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES))); + $beforeNetworkDispatch = count($history); + $assert($worker->tick(), + 'Transition-owned network task was not consumed by the Worker.'); + $networkRequest = $agentRequest($history[$beforeNetworkDispatch]); + $networkBody = json_decode( + (string) $networkRequest['body'], + true, + 32, + JSON_THROW_ON_ERROR + ); + $networkSpec = json_decode( + (string) $instance->fresh()->spec_json, + true, + 64, + JSON_THROW_ON_ERROR + ); + $assert(count($history) === $beforeNetworkDispatch + 1 + && ($networkBody['public_network'] ?? null) === $networkTarget + && CloudJob::find($networkJob->id)->phase === 'terminal' + && CloudJob::find($networkJob->id)->outcome === 'succeeded' + && (int) CloudJob::find($networkJob->id)->dispatch_attempts === 1 + && Capsule::table('cloud_public_network_transitions') + ->where('id', $networkDispatch->transitionId()) + ->value('state') === 'succeeded' + && ($networkSpec['public_network'] ?? null) === $networkTarget, + 'Worker did not dispatch/finalize the exact transition projection.'); + $afterNetworkDispatch = count($history); + $worker->tick(); + $assert(count($history) === $afterNetworkDispatch + && (int) CloudJob::find($networkJob->id)->dispatch_attempts === 1, + 'A terminal transition-owned network task was replayed.'); + + // A legacy scalar task that lacks transition ownership fails before the + // Agent. Use an isolated instance so its durable incident cannot affect + // the canonical instance's later lifecycle tests. + $legacyNetworkInstance = $makeLifecycleInstance( + '45454545-4545-4545-8545-454545454545', + 'legacy-network-gate-vm', + 'active', + 'active' + ); + $legacyWorkerJob = new CloudJob(); + $legacyWorkerJob->operation_id = bin2hex(random_bytes(16)); + $legacyWorkerJob->request_idempotency_key = + 'legacy-network-worker-gate-0001'; + $legacyWorkerJob->request_fingerprint = hash( + 'sha256', + 'legacy-network-worker-gate-0001' + ); + $legacyWorkerJob->instance_id = (int) $legacyNetworkInstance->id; + $legacyWorkerJob->user_id = (int) $legacyNetworkInstance->user_id; + $legacyWorkerJob->host_id = (int) $legacyNetworkInstance->host_id; + $legacyWorkerJob->kind = 'network_change'; + $legacyWorkerJob->execution_mode = 'agent'; + $legacyWorkerJob->status = 'queued'; + $legacyWorkerJob->public_network_transition_id = null; + $legacyWorkerJob->sealed_payload = + \App\Services\Cloud\CloudSecrets::encrypt([ + 'method' => 'POST', + 'request_target' => '/v1/vms/' + . rawurlencode((string) $legacyNetworkInstance->uuid) + . '/network', + 'body' => [ + 'public_ip_cidr' => '9.9.9.10/24', + 'confirm_restart' => true, + ], + 'credential' => null, + 'owner_id' => (int) $legacyNetworkInstance->user_id, + 'can_manage' => false, + ], 'job-payload'); + $legacyWorkerJob->available_at = $legacyWorkerJob->created_at = + $legacyWorkerJob->updated_at = time(); + $legacyWorkerJob->save(); + $beforeLegacyWorker = count($history); + $assert($worker->tick(), + 'Legacy network task was not consumed by the local fail-closed path.'); + $legacyWorkerJob->refresh(); + $assert(count($history) === $beforeLegacyWorker + && (int) $legacyWorkerJob->dispatch_attempts === 0 + && $legacyWorkerJob->phase === 'terminal' + && $legacyWorkerJob->outcome === 'failed', + 'Legacy network task reached the Agent or remained claimable.'); + $worker->tick(); + $assert(count($history) === $beforeLegacyWorker + && (int) $legacyWorkerJob->fresh()->dispatch_attempts === 0, + 'Legacy network task was replayed after local rejection.'); + + // The ordinary job enqueue path is permanently closed to legacy scalar + // network changes. Canonical transitions have their own durable workflow + // and are tested in the dedicated begin/finalization behavior suites. $networkInput = ['public_ip_cidr' => '9.9.9.10/24', 'public_pool_key' => $targetPoolKey, 'confirm_restart' => true]; $beforeLegacyNetworkJobs = CloudJob::count(); @@ -2398,592 +2533,11 @@ namespace { && CloudJob::count() === $beforeLegacyNetworkJobs, 'Transition gate created a network job before rejecting it.'); } - // Retain the old scalar cases as a dormant migration fixture until the - // later transition-ledger stage rewrites them as all-family operations. - if (false) { - try { - CloudJobService::enqueue($instance->fresh(), $actor, - 'network_change', 'POST', '/network', - $networkInput + ['network' => 'bridge:attacker']); - throw new RuntimeException('Network change accepted a user-selected host network.'); - } catch (CloudError $error) { - $assert($error->httpStatus === 422, - 'User network injection returned the wrong status.'); - } - $host->default_network = 'public'; - $host->save(); - $targetAttachment->network_selector = 'public'; - $targetAttachment->save(); - try { - CloudJobService::enqueue($instance->fresh(), $actor, - 'network_change', 'POST', '/network', $networkInput); - throw new RuntimeException( - 'A target outside current Agent evidence queued a network change.' - ); - } catch (CloudError $error) { - $assert($error->httpStatus === 409, - 'Unverified target attachment returned the wrong status.'); - } - $targetAttachment->network_selector = 'bridge:br1'; - $targetAttachment->save(); - try { - CloudJobService::enqueue($instance->fresh(), $actor, - 'network_change', 'POST', '/network', [ - 'public_ip_cidr' => '9.9.9.10/24', - 'confirm_restart' => true, - ]); - throw new RuntimeException('Network change accepted an implicit public pool.'); - } catch (CloudError $expected) { - $assert($expected->httpStatus === 422, - 'Missing public pool key returned the wrong status.'); - } - try { - CloudJobService::enqueue($instance->fresh(), $actor, - 'network_change', 'POST', '/network', [ - 'public_ip_cidr' => '9.9.9.10/24', - 'public_pool_key' => $sourcePoolKey, - 'confirm_restart' => true, - ]); - throw new RuntimeException('Network change accepted an IP from another pool.'); - } catch (CloudError $expected) { - $assert($expected->httpStatus === 409, - 'Pool/IP mismatch returned the wrong status.'); - } - $targetAttachment->line_id = (int) $line->id + 100; - $targetAttachment->save(); - try { - CloudJobService::enqueue($instance->fresh(), $actor, - 'network_change', 'POST', '/network', [ - 'public_ip_cidr' => '9.9.9.10/24', - 'public_pool_key' => $targetPoolKey, - 'confirm_restart' => true, - ]); - throw new RuntimeException('Network change crossed the instance sales line.'); - } catch (CloudError $expected) { - $assert($expected->httpStatus === 409, - 'Sales-line mismatch returned the wrong status.'); - } - $targetAttachment->line_id = $line->id; - $targetAttachment->save(); - $attachment->state = 'draining'; - $attachment->save(); - $sourcePublicPool->state = 'draining'; - $sourcePublicPool->sync_state = 'pending'; - $sourcePublicPool->observed_revision = 0; - $sourcePublicPool->save(); - $reservationUpdatedAtBeforeNetwork = (int) $openingReservation->fresh()->updated_at; - $networkTarget = CloudPublicIp::where('address', '9.9.9.10')->first(); - $samePoolSpare = CloudPublicIp::where('address', '8.8.8.11')->first(); - $samePoolSpare->state = 'disabled'; - $samePoolSpare->updated_at = time(); - $samePoolSpare->save(); - $assert(CloudIpChangeBillingService::normalizePrice('2.5') === '2.50', - 'Paid IP-change price normalization lost exact cents.'); - foreach (['-1', '1e2', '1000000.00'] as $invalidPrice) { - try { - CloudIpChangeBillingService::normalizePrice($invalidPrice); - throw new RuntimeException('Invalid paid IP-change price accepted.'); - } catch (InvalidArgumentException $expected) { - } - } - $disabledActor = $actor + [ - 'request_idempotency_key' => 'paid-ip-disabled-0001', - ]; - try { - CloudJobService::enqueue($instance->fresh(), $disabledActor, - 'network_change', 'POST', '/network', [ - 'confirm_restart' => true, - ], null, '0.00'); - throw new RuntimeException('Disabled paid IP change was accepted.'); - } catch (CloudError $expected) { - $assert($expected->httpStatus === 409 - && CloudInvoice::where('purpose', 'ip_change')->count() === 0, - 'Disabled paid IP change altered the financial ledger.'); - } - Capsule::table('configurations')->insert([ - 'name' => 'cloud_ip_change_price', 'value' => '2.50', - ]); - $user->money = '1.00'; - $user->save(); - $insufficientActor = $actor + [ - 'request_idempotency_key' => 'paid-ip-insufficient-0001', - ]; - try { - CloudJobService::enqueue($instance->fresh(), $insufficientActor, - 'network_change', 'POST', '/network', [ - 'confirm_restart' => true, - ], null, '2.50'); - throw new RuntimeException('Paid IP change exceeded the wallet.'); - } catch (CloudError $expected) { - $assert($expected->httpStatus === 409 - && (string) User::findOrFail(1)->money === '1.00' - && CloudInvoice::where('purpose', 'ip_change')->count() === 0, - 'Insufficient paid IP change altered wallet or invoice state.'); - } - $user->money = '20.00'; - $user->save(); - $targetedPaidActor = $actor + [ - 'request_idempotency_key' => 'paid-ip-targeted-0001', - ]; - try { - CloudJobService::enqueue($instance->fresh(), $targetedPaidActor, - 'network_change', 'POST', '/network', [ - 'public_ip_cidr' => '9.9.9.10/24', - 'public_pool_key' => $targetPoolKey, - 'confirm_restart' => true, - ], null, '2.50'); - throw new RuntimeException('Paid IP change accepted a tenant-selected target.'); - } catch (CloudError $expected) { - $assert($expected->httpStatus === 422 - && CloudInvoice::where('purpose', 'ip_change')->count() === 0, - 'Rejected tenant target altered the financial ledger.'); - } - $paidNetworkActor = $actor + [ - 'request_idempotency_key' => 'paid-ip-success-0001', - ]; - $networkChange = CloudJobService::enqueue($instance->fresh(), - $paidNetworkActor, - 'network_change', 'POST', '/network', [ - 'confirm_restart' => true, - ], null, '2.50'); - $host->default_network = 'bridge:br0'; - $host->save(); - $paidNetworkInvoice = CloudInvoice::findOrFail( - (int) $networkChange->invoice_id - ); - Capsule::table('configurations')->where('name', 'cloud_ip_change_price') - ->update(['value' => '9.00']); - $serviceBeforeReplay = $instance->fresh(); - $instance->service_status = 'suspending_expired'; - $instance->expires_at = time() - 1; - $instance->save(); - $networkReplay = CloudJobService::enqueue($instance->fresh(), - $paidNetworkActor, - 'network_change', 'POST', '/network', [ - 'confirm_restart' => true, - ], null, '2.50'); - $instance->service_status = $serviceBeforeReplay->service_status; - $instance->expires_at = $serviceBeforeReplay->expires_at; - $instance->save(); - $assert((int) $networkReplay->id === (int) $networkChange->id - && CloudInvoice::where('purpose', 'ip_change')->count() === 1 - && (string) User::findOrFail(1)->money === '17.50' - && (string) $paidNetworkInvoice->amount === '2.50' - && (string) $paidNetworkInvoice->status === 'paid' - && (string) $paidNetworkInvoice->paid_via === 'balance' - && (string) $paidNetworkInvoice->payment_reference - === 'network-change-' . (int) $networkChange->id, - 'Paid network-change replay charged twice or used the new price.'); - try { - CloudJobService::enqueue($instance->fresh(), $paidNetworkActor, - 'network_change', 'POST', '/network', [ - 'confirm_restart' => true, - ], null, '9.00'); - throw new RuntimeException( - 'A paid request key was reused with a different quoted amount.' - ); - } catch (CloudError $expected) { - $assert($expected->httpStatus === 409 - && CloudInvoice::where('purpose', 'ip_change')->count() === 1 - && (string) User::findOrFail(1)->money === '17.50', - 'Quoted amount was omitted from paid request identity.'); - } - $stalePriceActor = $actor + [ - 'request_idempotency_key' => 'paid-ip-stale-price-0001', - ]; - try { - CloudJobService::enqueue($instance->fresh(), $stalePriceActor, - 'network_change', 'POST', '/network', [ - 'confirm_restart' => true, - ], null, '2.50'); - throw new RuntimeException('A stale paid IP quote was accepted.'); - } catch (CloudError $expected) { - $assert($expected->httpStatus === 409 - && CloudInvoice::where('purpose', 'ip_change')->count() === 1 - && (string) User::findOrFail(1)->money === '17.50', - 'A stale paid IP quote altered wallet or invoice state.'); - } - Capsule::table('configurations')->where('name', 'cloud_ip_change_price') - ->update(['value' => '2.50']); - $networkPayload = \App\Services\Cloud\CloudSecrets::decrypt( - $networkChange->sealed_payload, - 'job-payload' - ); - $networkTarget->refresh(); - $assert(($networkPayload['body']['network'] ?? null) === 'bridge:br1' - && (int) ($networkPayload['source_public_ip_id'] ?? 0) - === (int) $openingReservation->public_ip_id - && (int) ($networkPayload['target_public_ip_id'] ?? 0) - === (int) $networkTarget->id - && (int) ($networkPayload['source_network_attachment_id'] ?? 0) - === (int) $attachment->id - && (int) ($networkPayload['target_network_attachment_id'] ?? 0) - === (int) $targetAttachment->id - && (int) ($networkPayload['source_public_ip_pool_id'] ?? 0) - === (int) $sourcePublicPool->id - && (int) ($networkPayload['target_public_ip_pool_id'] ?? 0) - === (int) $targetPublicPool->id - && $networkTarget->state === 'changing' - && $networkTarget->reservation_id === null - && (int) $networkTarget->instance_id === (int) $instance->id - && (string) $networkTarget->operation_id === (string) $networkChange->operation_id, - 'Network-change enqueue did not durably reserve the target without violating the reservation uniqueness constraint.'); - $beforeNetwork = count($history); - $mock->append(new Response(202, [], json_encode([ - 'operation_id' => $networkChange->operation_id, - 'status' => 'reserved', 'replayed' => false, 'retryable' => false, - ...CloudOperationRecoveryIdentity::expected($networkChange), - ]))); - $worker->tick(); - $networkRequest = $agentRequest($history[$beforeNetwork]); - $networkBody = json_decode($networkRequest['body'], true); - $networkTarget->refresh(); - $assert($networkBody === [ - 'confirm_restart' => true, - 'public_ip_cidr' => '9.9.9.10/24', - 'public_pool_key' => $targetPoolKey, - 'network' => 'bridge:br1', - 'public_pool_cidr' => '9.9.9.0/24', - 'gateway' => '9.9.9.1', - 'dns_servers' => ['1.0.0.1'], - ] - && $networkTarget->state === 'changing' - && (int) CloudResourceReservation::find( - $openingReservation->id - )->public_ip_pool_id === (int) $sourcePublicPool->id - && CloudPublicIp::find($openingReservation->public_ip_id)->state === 'assigned', - 'Accepted network change exposed ledger metadata to the Agent or released either address.'); - $beforeNetworkReceipt = count($history); - $networkReceipt = CloudOperationCompletionService::accept([ - 'type' => 'completion', - 'id' => bin2hex(random_bytes(16)), - 'agent_id' => (string) $instance->host_id, - 'operation_id' => $networkChange->operation_id, - ...CloudOperationRecoveryIdentity::expected($networkChange, true), - 'status' => 'succeeded', - 'effect_may_have_applied' => false, - 'safe_to_resubmit' => false, - 'error_code' => '', - 'result' => [ - 'public_ip_cidr' => '9.9.9.10/24', - 'public_pool_key' => $targetPoolKey, - 'network_changed' => true, - ], - ]); - $networkReservation = CloudResourceReservation::find($openingReservation->id); - $networkTarget->refresh(); - $assert($networkReceipt === ['accepted' => true, - 'disposition' => 'applied'] - && count($history) === $beforeNetworkReceipt - && CloudJob::find($networkChange->id)->status === 'succeeded' - && (int) CloudJob::find($networkChange->id)->dispatch_attempts === 1 - && (int) $networkReservation->public_ip_id === (int) $networkTarget->id - && (int) $networkReservation->network_attachment_id - === (int) $targetAttachment->id - && (int) $networkReservation->public_ip_pool_id - === (int) $targetPublicPool->id - && (int) $networkReservation->updated_at - === $reservationUpdatedAtBeforeNetwork - && $networkTarget->state === 'assigned' - && (int) $networkTarget->reservation_id === (int) $networkReservation->id - && (int) $networkTarget->instance_id === (int) $instance->id - && CloudPublicIp::find($openingReservation->public_ip_id)->state === 'available' - && (json_decode((string) $instance->fresh()->spec_json, true)['public_ip_cidr'] ?? null) - === '9.9.9.10/24' - && (string) $paidNetworkInvoice->fresh()->status === 'paid' - && (string) User::findOrFail(1)->money === '17.50', - 'Completion receipt did not atomically swap the reservation and instance metadata.'); - - $releasedNetworkSource = CloudPublicIp::find( - (int) $openingReservation->public_ip_id - ); - $releasedNetworkSource->state = 'disabled'; - $releasedNetworkSource->updated_at = time(); - $releasedNetworkSource->save(); - $failedNetworkTarget = CloudPublicIp::where('address', '9.9.9.11')->first(); - $failedNetworkActor = $actor + [ - 'request_idempotency_key' => 'paid-ip-failure-0001', - ]; - $failedNetwork = CloudJobService::enqueue($instance->fresh(), - $failedNetworkActor, - 'network_change', 'POST', '/network', [ - 'confirm_restart' => true, - ], null, '2.50'); - $failedNetworkInvoice = CloudInvoice::findOrFail( - (int) $failedNetwork->invoice_id - ); - $assert((string) User::findOrFail(1)->money === '15.00' - && (string) $failedNetworkInvoice->status === 'paid', - 'Paid network failure fixture was not charged before dispatch.'); - $mock->append(new Response(422, [], json_encode([ - 'operation_id' => $failedNetwork->operation_id, 'status' => 'failed', - ...CloudOperationRecoveryIdentity::expected($failedNetwork), - 'error' => ['code' => 'invalid_request', - 'message' => 'network change rejected'], - 'effect_may_have_applied' => false, - 'safe_to_resubmit' => true, - 'replayed' => false, - 'retryable' => false, - ]))); - $worker->tick(); - $failedNetworkTarget->refresh(); - $networkTarget->refresh(); - $assert(CloudJob::find($failedNetwork->id)->status === 'failed' - && $failedNetworkTarget->state === 'available' - && $failedNetworkTarget->reservation_id === null - && $failedNetworkTarget->instance_id === null - && $failedNetworkTarget->operation_id === null - && $networkTarget->state === 'assigned' - && (int) CloudResourceReservation::find($openingReservation->id)->public_ip_id - === (int) $networkTarget->id - && (int) CloudResourceReservation::find( - $openingReservation->id - )->network_attachment_id === (int) $targetAttachment->id - && (int) CloudResourceReservation::find( - $openingReservation->id - )->public_ip_pool_id === (int) $targetPublicPool->id, - 'Explicit network failure changed the source assignment or retained its target hold.'); - $assert((string) User::findOrFail(1)->money === '17.50' - && (string) $failedNetworkInvoice->fresh()->status === 'refunded', - 'Conclusive network failure did not refund exactly once.'); - (new CloudJob())->getConnection()->transaction(function () use ( - $failedNetwork - ): void { - $lockedUser = User::where('id', 1)->lockForUpdate()->first(); - $lockedJob = CloudJob::where('id', (int) $failedNetwork->id) - ->lockForUpdate()->firstOrFail(); - CloudIpChangeBillingService::refundNotAppliedLocked( - $lockedJob, - $lockedUser, - 'not_applied' - ); - }, 3); - $assert((string) User::findOrFail(1)->money === '17.50', - 'Repeated network failure finalization refunded the charge twice.'); - - // An ambiguous Agent result must retain both the original assignment and - // the tenant charge until exact evidence resolves that same immutable - // operation. A proved no-effect recovery then releases only the target, - // restores the wallet exactly once, and keeps the source triple intact. - $unknownNotAppliedActor = $actor + [ - 'request_idempotency_key' => 'paid-ip-unknown-not-applied-0001', - ]; - $unknownNotApplied = CloudJobService::enqueue($instance->fresh(), - $unknownNotAppliedActor, - 'network_change', 'POST', '/network', [ - 'confirm_restart' => true, - ], null, '2.50'); - $unknownNotAppliedInvoice = CloudInvoice::findOrFail( - (int) $unknownNotApplied->invoice_id - ); - $mock->append(new Response(502, [], json_encode([ - 'operation_id' => $unknownNotApplied->operation_id, - 'status' => 'failed', - ...CloudOperationRecoveryIdentity::expected($unknownNotApplied), - 'error' => ['code' => 'operation_effect_unknown'], - 'effect_may_have_applied' => true, - 'safe_to_resubmit' => false, - 'replayed' => false, - 'retryable' => false, - ]))); - $worker->tick(); - $unknownNotApplied->refresh(); - $failedNetworkTarget->refresh(); - $networkTarget->refresh(); - $unknownReservation = CloudResourceReservation::findOrFail( - (int) $openingReservation->id - ); - $assert((string) $unknownNotApplied->phase === 'terminal' - && (string) $unknownNotApplied->outcome === 'failed' - && (bool) $unknownNotApplied->effect_may_have_applied - && !(bool) $unknownNotApplied->safe_to_resubmit - && (string) $unknownNotApplied->effect_resolution === 'unknown' - && $failedNetworkTarget->state === 'uncertain' - && (string) $failedNetworkTarget->operation_id - === (string) $unknownNotApplied->operation_id - && $networkTarget->state === 'assigned' - && (int) $unknownReservation->public_ip_id - === (int) $networkTarget->id - && (int) $unknownReservation->network_attachment_id - === (int) $targetAttachment->id - && (int) $unknownReservation->public_ip_pool_id - === (int) $targetPublicPool->id - && (string) User::findOrFail(1)->money === '15.00' - && (string) $unknownNotAppliedInvoice->fresh()->status === 'paid' - && CloudJobService::blockingQueryForInstance( - (int) $instance->id - )->exists(), - 'Unknown network effect released an address, refunded money, or moved the reservation before recovery.'); - $unknownNotAppliedIdentity = - CloudOperationRecoveryIdentity::expected( - $unknownNotApplied, - false - ); - $unknownNotAppliedOperation = $unknownNotAppliedIdentity + [ - 'operation_id' => (string) $unknownNotApplied->operation_id, - 'status' => 'failed', - 'effect_may_have_applied' => false, - 'safe_to_resubmit' => true, - 'error_code' => 'network_not_changed', - 'result' => [], - ]; - $unknownNotAppliedEvidence = - 'test_probe:network_change_not_applied'; - CloudOperationRecoveryService::prepareNotApplied( - (int) $unknownNotApplied->id, - $unknownNotAppliedOperation, - $unknownNotAppliedEvidence - ); - $preparedNotApplied = $unknownNotApplied->fresh(); - $failedNetworkTarget->refresh(); - $networkTarget->refresh(); - $unknownReservation->refresh(); - $assert((string) $preparedNotApplied->effect_resolution === 'unknown' - && str_starts_with( - (string) $preparedNotApplied->effect_resolution_reason, - 'prepared:' . $unknownNotAppliedEvidence . ':' - ) - && $failedNetworkTarget->state === 'available' - && $failedNetworkTarget->reservation_id === null - && $failedNetworkTarget->instance_id === null - && $failedNetworkTarget->operation_id === null - && $networkTarget->state === 'assigned' - && (int) $unknownReservation->public_ip_id - === (int) $networkTarget->id - && (int) $unknownReservation->network_attachment_id - === (int) $targetAttachment->id - && (int) $unknownReservation->public_ip_pool_id - === (int) $targetPublicPool->id - && (string) User::findOrFail(1)->money === '17.50' - && (string) $unknownNotAppliedInvoice->fresh()->status === 'refunded' - && CloudJobService::blockingQueryForInstance( - (int) $instance->id - )->exists(), - 'Not-applied recovery prepare did not restore the target and wallet while retaining the effect fence.'); - CloudOperationRecoveryService::commitNotApplied( - (int) $unknownNotApplied->id, - $unknownNotAppliedOperation, - $unknownNotAppliedEvidence - ); - $assert((string) $unknownNotApplied->fresh()->effect_resolution - === 'not_applied' - && !CloudJobService::blockingQueryForInstance( - (int) $instance->id - )->exists() - && (string) User::findOrFail(1)->money === '17.50', - 'Not-applied recovery did not publish once or release its blocker.'); - - // The opposite proof must converge through the same finalizer: apply the - // already performed change, move the reservation triple to the target, - // release the source, retain the paid invoice, and keep the fence until - // the recovery commit is published. - $unknownAppliedActor = $actor + [ - 'request_idempotency_key' => 'paid-ip-unknown-applied-0001', - ]; - $unknownApplied = CloudJobService::enqueue($instance->fresh(), - $unknownAppliedActor, - 'network_change', 'POST', '/network', [ - 'confirm_restart' => true, - ], null, '2.50'); - $unknownAppliedInvoice = CloudInvoice::findOrFail( - (int) $unknownApplied->invoice_id - ); - $mock->append(new Response(502, [], json_encode([ - 'operation_id' => $unknownApplied->operation_id, - 'status' => 'failed', - ...CloudOperationRecoveryIdentity::expected($unknownApplied), - 'error' => ['code' => 'operation_effect_unknown'], - 'effect_may_have_applied' => true, - 'safe_to_resubmit' => false, - 'replayed' => false, - 'retryable' => false, - ]))); - $worker->tick(); - $unknownApplied->refresh(); - $failedNetworkTarget->refresh(); - $networkTarget->refresh(); - $unknownReservation->refresh(); - $assert((string) $unknownApplied->effect_resolution === 'unknown' - && $failedNetworkTarget->state === 'uncertain' - && $networkTarget->state === 'assigned' - && (int) $unknownReservation->public_ip_id - === (int) $networkTarget->id - && (string) User::findOrFail(1)->money === '15.00' - && (string) $unknownAppliedInvoice->fresh()->status === 'paid', - 'Applied-recovery fixture did not retain its ambiguous ledgers.'); - $unknownAppliedIdentity = CloudOperationRecoveryIdentity::expected( - $unknownApplied, - true - ); - $unknownAppliedOperation = $unknownAppliedIdentity + [ - 'operation_id' => (string) $unknownApplied->operation_id, - 'status' => 'succeeded', - 'effect_may_have_applied' => false, - 'safe_to_resubmit' => false, - 'error_code' => '', - 'result' => [ - 'public_ip_cidr' => '9.9.9.11/24', - 'public_pool_key' => $targetPoolKey, - 'network_changed' => true, - ], - ]; - $unknownAppliedEvidence = 'test_probe:network_change_applied'; - CloudOperationRecoveryService::prepareApplied( - (int) $unknownApplied->id, - $unknownAppliedOperation, - $unknownAppliedEvidence - ); - $preparedApplied = $unknownApplied->fresh(); - $failedNetworkTarget->refresh(); - $networkTarget->refresh(); - $unknownReservation->refresh(); - $assert((string) $preparedApplied->effect_resolution === 'unknown' - && str_starts_with( - (string) $preparedApplied->effect_resolution_reason, - 'prepared:' . $unknownAppliedEvidence . ':' - ) - && $failedNetworkTarget->state === 'assigned' - && (int) $failedNetworkTarget->reservation_id - === (int) $unknownReservation->id - && (int) $failedNetworkTarget->instance_id === (int) $instance->id - && $networkTarget->state === 'available' - && (int) $unknownReservation->public_ip_id - === (int) $failedNetworkTarget->id - && (int) $unknownReservation->network_attachment_id - === (int) $targetAttachment->id - && (int) $unknownReservation->public_ip_pool_id - === (int) $targetPublicPool->id - && (json_decode( - (string) $instance->fresh()->spec_json, - true - )['public_ip_cidr'] ?? null) === '9.9.9.11/24' - && (string) User::findOrFail(1)->money === '15.00' - && (string) $unknownAppliedInvoice->fresh()->status === 'paid' - && CloudJobService::blockingQueryForInstance( - (int) $instance->id - )->exists(), - 'Applied recovery prepare did not atomically move the reservation while retaining its fence and charge.'); - CloudOperationRecoveryService::commitApplied( - (int) $unknownApplied->id, - $unknownAppliedOperation, - $unknownAppliedEvidence - ); - $assert((string) $unknownApplied->fresh()->effect_resolution === 'applied' - && !CloudJobService::blockingQueryForInstance( - (int) $instance->id - )->exists() - && (int) CloudResourceReservation::findOrFail( - (int) $openingReservation->id - )->public_ip_id === (int) $failedNetworkTarget->id - && (string) User::findOrFail(1)->money === '15.00' - && (string) $unknownAppliedInvoice->fresh()->status === 'paid', - 'Applied recovery did not publish exactly once with the recovered network and payment ledgers.'); - - } - - // The old scalar transition scenarios stay dormant until C11. Deletion - // must therefore consume the unchanged exact dual-stack authority, never - // reconstruct it from the retained singular reservation columns. + // Stage 5 keeps one executable legacy-gate assertion above; paid charge, + // idempotency, not-applied refund and unknown-effect recovery are covered + // by the canonical transition Workflow and Finalization behavior suites. + // Deletion consumes the unchanged exact dual-stack authority and never + // reconstructs it from retained singular reservation columns. $canonicalClaimSet = \App\Services\Cloud\CloudPublicNetworkAllocationService::currentClaimSet( (int) $openingReservation->id, diff --git a/web/tests/CloudNetworkChangeOptionsServiceTest.php b/web/tests/CloudNetworkChangeOptionsServiceTest.php index 3c5886c6..861208b0 100644 --- a/web/tests/CloudNetworkChangeOptionsServiceTest.php +++ b/web/tests/CloudNetworkChangeOptionsServiceTest.php @@ -1,16 +1,19 @@ addConnection([ 'driver' => 'sqlite', 'database' => ':memory:', @@ -45,93 +65,82 @@ namespace { $capsule->bootEloquent(); $schema = $capsule->schema('default'); - $schema->create('cloud_hosts', static function (Blueprint $table): void { - $table->increments('id'); - $table->string('name'); - $table->string('region'); - $table->integer('enabled'); + $schema->create('cloud_hosts', static function (Blueprint $t): void { + $t->increments('id'); $t->string('name'); $t->string('region'); + $t->boolean('enabled'); }); - $schema->create('cloud_host_agents', static function ( - Blueprint $table - ): void { - $table->integer('host_id')->primary(); - $table->integer('enabled'); - $table->integer('revision'); - $table->integer('tested_revision'); - $table->string('last_test_status'); - $table->text('network_selectors_json'); + $schema->create('cloud_host_agents', static function (Blueprint $t): void { + $t->integer('host_id')->primary(); $t->boolean('enabled'); + $t->integer('revision'); $t->integer('tested_revision'); + $t->string('last_test_status'); $t->text('network_selectors_json'); + $t->text('public_network_capabilities_json'); + }); + $schema->create('cloud_resource_pools', static function (Blueprint $t): void { + $t->increments('id'); $t->integer('line_id'); }); - $schema->create('cloud_instances', static function ( - Blueprint $table + $schema->create('cloud_host_network_attachments', static function ( + Blueprint $t ): void { - $table->increments('id'); - $table->integer('host_id'); - $table->integer('reservation_id'); - $table->integer('resource_pool_id'); - $table->string('status'); - $table->text('spec_json'); + $t->increments('id'); $t->integer('host_id'); $t->integer('line_id'); + $t->string('name'); $t->string('network_selector'); + $t->string('state'); $t->integer('priority'); + $t->string('verification_state'); + $t->integer('verified_agent_revision'); + $t->integer('last_verified_at'); }); - $schema->create('cloud_resource_pools', static function ( - Blueprint $table + $schema->create('cloud_public_ip_pools', static function ( + Blueprint $t ): void { - $table->increments('id'); - $table->integer('line_id'); + $t->increments('id'); $t->string('pool_key'); $t->integer('host_id'); + $t->integer('network_attachment_id'); $t->integer('address_family'); + $t->string('name'); $t->string('cidr'); $t->string('gateway'); + $t->boolean('gateway_on_link'); $t->integer('guest_prefix_length'); + $t->text('dns_servers_json'); $t->text('reserved_ips_json'); + $t->string('allocation_start')->nullable(); + $t->string('allocation_end')->nullable(); + $t->string('allocation_cursor')->nullable(); + $t->integer('max_allocations'); $t->string('state'); + $t->integer('priority'); $t->integer('desired_revision'); + $t->integer('observed_revision'); $t->string('sync_state'); + }); + $schema->create('cloud_public_ips', static function (Blueprint $t): void { + $t->increments('id'); $t->integer('host_id'); + $t->integer('public_ip_pool_id'); $t->integer('address_family'); + $t->string('address'); $t->binary('address_binary'); + $t->integer('prefix_length'); $t->string('state'); + $t->integer('reservation_id')->nullable(); + $t->integer('reservation_ip_claim_id')->nullable(); + $t->integer('instance_id')->nullable(); + $t->string('operation_id')->nullable(); }); $schema->create('cloud_resource_reservations', static function ( - Blueprint $table + Blueprint $t ): void { - $table->increments('id'); - $table->integer('resource_pool_id'); - $table->integer('host_id'); - $table->integer('instance_id'); - $table->integer('network_attachment_id'); - $table->integer('public_ip_pool_id'); - $table->integer('public_ip_id'); - $table->string('state'); + $t->increments('id'); $t->integer('resource_pool_id'); + $t->integer('host_id'); $t->integer('user_id'); + $t->integer('instance_id'); $t->string('state'); }); - $schema->create('cloud_host_network_attachments', static function ( - Blueprint $table + $schema->create('cloud_resource_reservation_ips', static function ( + Blueprint $t ): void { - $table->increments('id'); - $table->integer('host_id'); - $table->integer('line_id'); - $table->string('network_selector'); - $table->string('state'); - $table->integer('priority'); - $table->string('verification_state'); - $table->integer('verified_agent_revision'); - $table->integer('last_verified_at'); + $t->increments('id'); $t->integer('reservation_id'); + $t->integer('address_family'); $t->integer('claim_generation'); + $t->integer('active_claim')->nullable(); + $t->integer('network_attachment_id'); + $t->integer('public_ip_pool_id'); $t->integer('public_ip_id'); + $t->string('operation_id'); $t->string('state'); }); - $schema->create('cloud_public_ip_pools', static function ( - Blueprint $table - ): void { - $table->increments('id'); - $table->string('pool_key'); - $table->integer('host_id'); - $table->integer('network_attachment_id'); - $table->string('cidr'); - $table->string('gateway'); - $table->integer('guest_prefix_length'); - $table->text('dns_servers_json'); - $table->text('reserved_ips_json'); - $table->string('state'); - $table->integer('priority'); - $table->integer('desired_revision'); - $table->integer('observed_revision'); - $table->string('sync_state'); + $schema->create('cloud_instances', static function (Blueprint $t): void { + $t->increments('id'); $t->integer('host_id'); $t->integer('user_id'); + $t->integer('reservation_id'); $t->integer('resource_pool_id'); + $t->string('status'); $t->string('service_status'); + $t->integer('expires_at'); $t->text('spec_json'); }); - $schema->create('cloud_public_ips', static function ( - Blueprint $table + $schema->create('cloud_public_network_transitions', static function ( + Blueprint $t ): void { - $table->increments('id'); - $table->integer('host_id'); - $table->integer('public_ip_pool_id'); - $table->string('address'); - $table->integer('prefix_length'); - $table->string('state'); - $table->integer('reservation_id')->nullable(); - $table->integer('instance_id')->nullable(); - $table->string('operation_id')->nullable(); + $t->increments('id'); $t->integer('instance_id'); + $t->integer('active_transition')->nullable(); }); $now = time(); @@ -142,166 +151,464 @@ namespace { Capsule::table('cloud_host_agents')->insert([ 'host_id' => 1, 'enabled' => 1, 'revision' => 7, 'tested_revision' => 7, 'last_test_status' => 'healthy', - 'network_selectors_json' => json_encode([ - 'bridge:line-a', 'bridge:line-b', 'bridge:line-x', - 'bridge:stale', + 'network_selectors_json' => '["bridge:br0","bridge:br1",' + . '"bridge:cross-line","bridge:stale"]', + 'public_network_capabilities_json' => json_encode([ + 'contract' => 1, + 'dual_stack_required' => true, + 'project_owned_filter' => true, + 'ndp_guard' => true, ], JSON_THROW_ON_ERROR), ]); Capsule::table('cloud_resource_pools')->insert([ 'id' => 10, 'line_id' => 1, ]); - Capsule::table('cloud_host_network_attachments')->insert([ - [ - 'id' => 1, 'host_id' => 1, 'line_id' => 1, - 'network_selector' => 'bridge:line-a', 'state' => 'active', - 'priority' => 10, 'verification_state' => 'verified', - 'verified_agent_revision' => 7, 'last_verified_at' => $now, - ], - [ - 'id' => 2, 'host_id' => 1, 'line_id' => 1, - 'network_selector' => 'bridge:line-b', 'state' => 'active', - 'priority' => 0, 'verification_state' => 'verified', - 'verified_agent_revision' => 7, 'last_verified_at' => $now, - ], - [ - 'id' => 3, 'host_id' => 1, 'line_id' => 2, - 'network_selector' => 'bridge:line-x', 'state' => 'active', - 'priority' => -10, 'verification_state' => 'verified', - 'verified_agent_revision' => 7, 'last_verified_at' => $now, - ], - [ - 'id' => 4, 'host_id' => 1, 'line_id' => 1, - 'network_selector' => 'bridge:stale', 'state' => 'active', - 'priority' => -20, 'verification_state' => 'verified', - 'verified_agent_revision' => 6, 'last_verified_at' => $now, - ], - ]); - $pool = static function (int $id, int $attachmentId, string $key, - string $cidr, string $gateway): array { + foreach ([ + [1, 1, 'Current uplink', 'bridge:br0', 10, 7], + [2, 1, 'Alternative uplink', 'bridge:br1', 20, 7], + [3, 2, 'Other line', 'bridge:cross-line', 0, 7], + [4, 1, 'Stale evidence', 'bridge:stale', 0, 6], + ] as [$id, $line, $name, $selector, $priority, $revision]) { + Capsule::table('cloud_host_network_attachments')->insert([ + 'id' => $id, 'host_id' => 1, 'line_id' => $line, + 'name' => $name, 'network_selector' => $selector, + 'state' => 'active', 'priority' => $priority, + 'verification_state' => 'verified', + 'verified_agent_revision' => $revision, + 'last_verified_at' => $now, + ]); + } + $pool = static function (int $id, int $attachmentId, int $family, + string $key, string $cidr, string $gateway, + bool $gatewayOnLink = false, int $desired = 1, + int $observed = 1): array { + $base = explode('/', $cidr, 2)[0]; return [ 'id' => $id, 'pool_key' => str_repeat($key, 32), 'host_id' => 1, 'network_attachment_id' => $attachmentId, + 'address_family' => $family, 'name' => 'pool-' . $id, 'cidr' => $cidr, 'gateway' => $gateway, - 'guest_prefix_length' => 29, 'dns_servers_json' => '[]', - 'reserved_ips_json' => '[]', 'state' => 'active', - 'priority' => 0, 'desired_revision' => 1, - 'observed_revision' => 1, 'sync_state' => 'applied', + 'gateway_on_link' => $gatewayOnLink ? 1 : 0, + 'guest_prefix_length' => $family === 4 ? 24 : 64, + 'dns_servers_json' => $family === 4 + ? '["1.1.1.1"]' : '["2606:4700:4700::1111"]', + 'reserved_ips_json' => '[]', + 'allocation_start' => $family === 6 + ? str_replace('::', '::1000', $base) : null, + 'allocation_end' => $family === 6 + ? str_replace('::', '::10ff', $base) : null, + 'max_allocations' => $family === 6 ? 64 : 0, + 'state' => 'active', 'priority' => 0, + 'desired_revision' => $desired, + 'observed_revision' => $observed, + 'sync_state' => 'applied', ]; }; Capsule::table('cloud_public_ip_pools')->insert([ - $pool(11, 1, '1', '198.51.100.0/29', '198.51.100.1'), - $pool(12, 2, '2', '198.51.100.8/29', '198.51.100.9'), - $pool(13, 3, '3', '198.51.100.16/29', '198.51.100.17'), - $pool(14, 4, '4', '198.51.100.24/29', '198.51.100.25'), + $pool(11, 1, 4, 'a', '8.8.8.0/24', '8.8.8.1'), + // Real provider contract: the on-link gateway is outside this /64. + $pool(12, 1, 6, 'b', '2404:c140:156:3a::/64', + '2404:c140:156::1', true), + $pool(21, 2, 4, 'c', '9.9.9.0/24', '9.9.9.1'), + $pool(22, 2, 6, 'd', '2404:c140:156:3b::/64', + '2404:c140:156::1', true), + $pool(31, 3, 4, 'e', '11.0.0.0/24', '11.0.0.1'), + $pool(41, 4, 4, 'f', '12.0.0.0/24', '12.0.0.1'), ]); + Capsule::table('cloud_public_ip_pools')->where('id', 22)->update([ + 'dns_servers_json' => '["2404:c140:156:3b::1001"]', + 'reserved_ips_json' => '["2404:c140:156:3b::1002"]', + ]); + $ip = static function (int $id, int $poolId, int $family, + string $address, string $state = 'available', + ?int $reservationId = null, ?int $claimId = null, + ?int $instanceId = null, ?string $operationId = null): array { + return [ + 'id' => $id, 'host_id' => 1, + 'public_ip_pool_id' => $poolId, + 'address_family' => $family, + 'address' => $address, 'address_binary' => inet_pton($address), + 'prefix_length' => $family === 4 ? 24 : 64, + 'state' => $state, 'reservation_id' => $reservationId, + 'reservation_ip_claim_id' => $claimId, + 'instance_id' => $instanceId, 'operation_id' => $operationId, + ]; + }; + $op4 = str_repeat('4', 32); + $op6 = str_repeat('6', 32); Capsule::table('cloud_public_ips')->insert([ + $ip(101, 11, 4, '8.8.8.10', 'assigned', 20, 201, 30, $op4), + $ip(102, 12, 6, '2404:c140:156:3a::1000', + 'assigned', 20, 202, 30, $op6), + $ip(111, 11, 4, '8.8.8.20'), + $ip(121, 21, 4, '9.9.9.20'), + $ip(131, 31, 4, '11.0.0.20'), + $ip(141, 41, 4, '12.0.0.20'), + ]); + + Capsule::table('cloud_resource_reservations')->insert([ + 'id' => 20, 'resource_pool_id' => 10, 'host_id' => 1, + 'user_id' => 7, 'instance_id' => 30, 'state' => 'committed', + ]); + Capsule::table('cloud_resource_reservation_ips')->insert([ [ - 'id' => 21, 'host_id' => 1, 'public_ip_pool_id' => 11, - 'address' => '198.51.100.2', 'prefix_length' => 29, - 'state' => 'assigned', 'reservation_id' => 20, - 'instance_id' => 30, 'operation_id' => str_repeat('a', 32), - ], - [ - 'id' => 22, 'host_id' => 1, 'public_ip_pool_id' => 11, - 'address' => '198.51.100.3', 'prefix_length' => 29, - 'state' => 'available', 'reservation_id' => null, - 'instance_id' => null, 'operation_id' => null, + 'id' => 201, 'reservation_id' => 20, 'address_family' => 4, + 'claim_generation' => 1, 'active_claim' => 1, + 'network_attachment_id' => 1, 'public_ip_pool_id' => 11, + 'public_ip_id' => 101, 'operation_id' => $op4, + 'state' => 'committed', ], [ - 'id' => 23, 'host_id' => 1, 'public_ip_pool_id' => 12, - 'address' => '198.51.100.10', 'prefix_length' => 29, - 'state' => 'available', 'reservation_id' => null, - 'instance_id' => null, 'operation_id' => null, + 'id' => 202, 'reservation_id' => 20, 'address_family' => 6, + 'claim_generation' => 1, 'active_claim' => 1, + 'network_attachment_id' => 1, 'public_ip_pool_id' => 12, + 'public_ip_id' => 102, 'operation_id' => $op6, + 'state' => 'committed', ], - [ - 'id' => 24, 'host_id' => 1, 'public_ip_pool_id' => 13, - 'address' => '198.51.100.18', 'prefix_length' => 29, - 'state' => 'available', 'reservation_id' => null, - 'instance_id' => null, 'operation_id' => null, + ]); + $publicNetwork = [ + 'contract' => 1, + 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'pool_key' => str_repeat('a', 32), + 'pool_cidr' => '8.8.8.0/24', + 'address_cidr' => '8.8.8.10/24', + 'gateway' => '8.8.8.1', + 'gateway_on_link' => false, ], - [ - 'id' => 25, 'host_id' => 1, 'public_ip_pool_id' => 14, - 'address' => '198.51.100.26', 'prefix_length' => 29, - 'state' => 'available', 'reservation_id' => null, - 'instance_id' => null, 'operation_id' => null, + 'ipv6' => [ + 'pool_key' => str_repeat('b', 32), + 'pool_cidr' => '2404:c140:156:3a::/64', + 'address_cidr' => '2404:c140:156:3a::1000/64', + 'gateway' => '2404:c140:156::1', + 'gateway_on_link' => true, ], - ]); - Capsule::table('cloud_resource_reservations')->insert([ - 'id' => 20, 'resource_pool_id' => 10, 'host_id' => 1, - 'instance_id' => 30, 'network_attachment_id' => 1, - 'public_ip_pool_id' => 11, 'public_ip_id' => 21, - 'state' => 'committed', - ]); + 'dns_servers' => ['1.1.1.1', '2606:4700:4700::1111'], + ]; Capsule::table('cloud_instances')->insert([ - 'id' => 30, 'host_id' => 1, 'reservation_id' => 20, - 'resource_pool_id' => 10, 'status' => 'active', + 'id' => 30, 'host_id' => 1, 'user_id' => 7, + 'reservation_id' => 20, 'resource_pool_id' => 10, + 'status' => 'active', 'service_status' => 'active', + 'expires_at' => $now + 86400, 'spec_json' => json_encode([ 'managed' => true, 'os_source' => 'cloud_template', - 'public_ip_cidr' => '198.51.100.2/29', - ], JSON_THROW_ON_ERROR), + 'public_network' => $publicNetwork, + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), ]); - $instance = CloudInstance::find(30); - $options = CloudNetworkChangeOptionsService::forInstance($instance); - $targets = array_column( - $options['available_ip_options'], - 'public_ip_cidr' + $instance = CloudInstance::findOrFail(30); + $tenant = CloudNetworkChangeOptionsService::tenantQuote($instance); + $assert(($tenant['can_change'] ?? null) === true + && ($tenant['configuration_state'] ?? null) === 'ready', + 'Current-attachment automatic IPv4 availability was not projected.'); + foreach ([ + 'host_id', 'host_name', 'region', 'current_public_network', + 'current_attachment_id', 'attachments', 'available_ip_options', + 'available_count', 'public_ip_cidr', 'pool_key', + ] as $privateKey) { + $assert(!array_key_exists($privateKey, $tenant), + 'Tenant quote leaked network inventory key: ' . $privateKey); + } + + $admin = CloudNetworkChangeOptionsService::adminOptions($instance); + $assert(($admin['can_change'] ?? null) === true + && ($admin['current_attachment_id'] ?? null) === '1' + && count($admin['attachments'] ?? []) === 2, + 'Administrator attachment catalog is incomplete or unfiltered.'); + $byId = []; + foreach ($admin['attachments'] as $attachment) { + $byId[$attachment['attachment_id']] = $attachment; + } + $assert(($byId['1']['current'] ?? null) === true + && ($byId['2']['current'] ?? null) === false + && ($byId['1']['ipv4']['pools'][0]['available_options'][0] + ['address_cidr'] ?? null) === '8.8.8.20/24' + && ($byId['2']['ipv4']['pools'][0]['available_options'][0] + ['address_cidr'] ?? null) === '9.9.9.20/24', + 'Exact IPv4 choices were not grouped by verified attachment.'); + $currentV6 = $byId['1']['ipv6']['pools'][0] ?? []; + $alternativeV6 = $byId['2']['ipv6']['pools'][0] ?? []; + $assert(($currentV6['cidr'] ?? null) === '2404:c140:156:3a::/64' + && ($currentV6['gateway'] ?? null) === '2404:c140:156::1' + && ($currentV6['gateway_on_link'] ?? null) === true + && ($currentV6['sparse'] ?? null) === true + && ($currentV6['allocation_start'] ?? null) + === '2404:c140:156:3a::1000' + && ($currentV6['allocation_end'] ?? null) + === '2404:c140:156:3a::10ff' + && !array_key_exists('available_options', $currentV6), + 'Sparse IPv6 metadata rejected the real off-prefix on-link gateway.'); + $assert(in_array('2404:c140:156:3b::1001', + $alternativeV6['excluded_addresses'] ?? [], true) + && in_array('2404:c140:156:3b::1002', + $alternativeV6['excluded_addresses'] ?? [], true), + 'IPv6 DNS or reserved address was not excluded from exact input.'); + + // More than the former global 4096-row cap is still a valid catalog: + // the administrator limit permits up to 32 /24 pools. Later attachments + // must not be starved by addresses ordered earlier in the global ledger. + $scalePools = []; + $scaleIps = []; + $scaleIpId = 10000; + for ($index = 0; $index < 17; $index++) { + $poolId = 100 + $index; + $cidr = '20.' . $index . '.0.0/24'; + $row = $pool( + $poolId, + 1, + 4, + 'a', + $cidr, + '20.' . $index . '.0.1' + ); + $row['pool_key'] = substr(hash('sha256', 'scale-' . $index), 0, 32); + $scalePools[] = $row; + for ($last = 2; $last <= 243; $last++) { + $scaleIps[] = $ip( + $scaleIpId++, + $poolId, + 4, + '20.' . $index . '.0.' . $last + ); + } + } + Capsule::table('cloud_public_ip_pools')->insert($scalePools); + foreach (array_chunk($scaleIps, 100) as $chunk) { + Capsule::table('cloud_public_ips')->insert($chunk); + } + $largeTenant = CloudNetworkChangeOptionsService::tenantQuote( + $instance->fresh() ); - $assert($targets === ['198.51.100.10/29', '198.51.100.3/29'] - && ($options['available_count'] ?? null) === 2 - && ($options['can_change'] ?? null) === true, - 'Same-line verified attachments were not merged in priority order.'); - $assert(!in_array('198.51.100.18/29', $targets, true) - && !in_array('198.51.100.26/29', $targets, true), - 'A cross-line or stale-evidence attachment leaked into IP choices.'); + $largeAdmin = CloudNetworkChangeOptionsService::adminOptions( + $instance->fresh() + ); + $largeAlternative = collect($largeAdmin['attachments'] ?? []) + ->firstWhere('attachment_id', '2'); + $assert(($largeTenant['can_change'] ?? null) === true + && ($largeTenant['configuration_state'] ?? null) === 'ready' + && ($largeAdmin['configuration_state'] ?? null) === 'ready' + && ($largeAlternative['ipv4']['pools'][0]['available_options'][0] + ['address_cidr'] ?? null) === '9.9.9.20/24', + 'A valid catalog above 4096 IPv4 rows starved a later attachment.'); + Capsule::table('cloud_public_ips')->where('id', '>=', 10000)->delete(); + Capsule::table('cloud_public_ip_pools')->whereBetween('id', [100, 116]) + ->delete(); - Capsule::table('cloud_host_network_attachments')->where('id', 2)->update([ - 'verified_agent_revision' => 6, + // Pool revisions are an atomic PHP-owned contract. An observed revision + // ahead of desired is catalog drift, not a successfully applied target. + Capsule::table('cloud_public_ip_pools')->where('id', 11)->update([ + 'observed_revision' => 2, + ]); + $driftTenant = CloudNetworkChangeOptionsService::tenantQuote( + $instance->fresh() + ); + $driftAdmin = CloudNetworkChangeOptionsService::adminOptions( + $instance->fresh() + ); + $driftCurrent = collect($driftAdmin['attachments'] ?? [])->firstWhere( + 'attachment_id', + '1' + ); + $assert(($driftTenant['can_change'] ?? null) === false + && ($driftCurrent['ipv4']['pools'] ?? []) === [], + 'A pool with observed revision ahead of desired was advertised.'); + Capsule::table('cloud_public_ip_pools')->where('id', 11)->update([ + 'observed_revision' => 1, ]); - $stale = CloudNetworkChangeOptionsService::forInstance($instance); - $assert(array_column( - $stale['available_ip_options'], - 'public_ip_cidr' - ) === ['198.51.100.3/29'], - 'An attachment verified for an old Agent revision remained selectable.'); - Capsule::table('cloud_host_network_attachments')->where('id', 2)->update([ - 'verified_agent_revision' => 7, 'last_verified_at' => 0, + $validPools = [ + 21 => [ + 'cidr' => '9.9.9.0/24', 'gateway' => '9.9.9.1', + 'gateway_on_link' => 0, 'guest_prefix_length' => 24, + 'dns_servers_json' => '["1.1.1.1"]', + 'reserved_ips_json' => '[]', + 'allocation_start' => null, 'allocation_end' => null, + 'allocation_cursor' => null, 'max_allocations' => 0, + ], + 22 => [ + 'cidr' => '2404:c140:156:3b::/64', + 'gateway' => '2404:c140:156::1', 'gateway_on_link' => 1, + 'guest_prefix_length' => 64, + 'dns_servers_json' => '["2404:c140:156:3b::1001"]', + 'reserved_ips_json' => '["2404:c140:156:3b::1002"]', + 'allocation_start' => '2404:c140:156:3b::1000', + 'allocation_end' => '2404:c140:156:3b::10ff', + 'allocation_cursor' => null, 'max_allocations' => 64, + ], + ]; + $corruptPoolCases = [ + 'guest prefix drift' => [22, 2, 6, ['guest_prefix_length' => 65]], + 'IPv4 on-link gateway' => [21, 2, 4, ['gateway_on_link' => 1]], + 'IPv4 invalid boolean gateway flag' => [21, 2, 4, [ + 'gateway_on_link' => 2, + ]], + 'IPv4 /23 prefix' => [21, 2, 4, [ + 'cidr' => '9.9.8.0/23', 'guest_prefix_length' => 23, + ]], + 'IPv6 /121 prefix' => [22, 2, 6, [ + 'cidr' => '2404:c140:156:3b::/121', + 'guest_prefix_length' => 121, + ]], + 'private DNS' => [21, 2, 4, [ + 'dns_servers_json' => '["10.0.0.1"]', + ]], + 'duplicate DNS' => [21, 2, 4, [ + 'dns_servers_json' => '["1.1.1.1","1.1.1.1"]', + ]], + 'empty DNS' => [21, 2, 4, ['dns_servers_json' => '[]']], + 'five DNS addresses' => [21, 2, 4, [ + 'dns_servers_json' => '["1.1.1.1","8.8.8.8",' + . '"9.9.9.9","2606:4700:4700::1111",' + . '"2001:4860:4860::8888"]', + ]], + 'private reserved address' => [21, 2, 4, [ + 'reserved_ips_json' => '["10.0.0.1"]', + ]], + 'duplicate reserved address' => [21, 2, 4, [ + 'reserved_ips_json' => '["9.9.9.2","9.9.9.2"]', + ]], + 'off-pool reserved address' => [21, 2, 4, [ + 'reserved_ips_json' => '["8.8.8.2"]', + ]], + 'network reserved address' => [21, 2, 4, [ + 'reserved_ips_json' => '["9.9.9.0"]', + ]], + 'off-prefix gateway without on-link' => [22, 2, 6, [ + 'gateway_on_link' => 0, + ]], + 'IPv6 invalid boolean gateway flag' => [22, 2, 6, [ + 'gateway_on_link' => 'false', + ]], + 'zero sparse allocation limit' => [22, 2, 6, [ + 'max_allocations' => 0, + ]], + 'excess sparse allocation limit' => [22, 2, 6, [ + 'max_allocations' => 65536, + ]], + 'insufficient sparse range' => [22, 2, 6, [ + 'allocation_end' => '2404:c140:156:3b::1002', + 'max_allocations' => 2, + ]], + 'cursor outside sparse range' => [22, 2, 6, [ + 'allocation_cursor' => '2404:c140:156:3b::1100', + ]], + ]; + foreach ($corruptPoolCases as $label => $case) { + [$poolId, $attachmentId, $family, $corruption] = $case; + Capsule::table('cloud_public_ip_pools')->where('id', $poolId) + ->update($corruption); + $corruptPoolOptions = CloudNetworkChangeOptionsService::adminOptions( + $instance->fresh() + ); + $corruptAlternative = collect( + $corruptPoolOptions['attachments'] ?? [] + )->firstWhere('attachment_id', (string) $attachmentId); + $familyKey = $family === 4 ? 'ipv4' : 'ipv6'; + $assert(($corruptPoolOptions['configuration_state'] ?? null) + === 'invalid' + && ($corruptAlternative[$familyKey]['pools'] ?? []) === [], + 'A corrupt public-IP pool was advertised: ' . $label); + Capsule::table('cloud_public_ip_pools')->where('id', $poolId) + ->update($validPools[$poolId]); + } + + CloudPanelUsageService::$managementAddress = + '2404:c140:156:3b::1003'; + $managementOptions = CloudNetworkChangeOptionsService::adminOptions( + $instance->fresh() + ); + $managementAttachment = collect( + $managementOptions['attachments'] ?? [] + )->firstWhere('attachment_id', '2'); + $managementIpv6Pool = $managementAttachment['ipv6']['pools'][0] ?? null; + $assert(is_array($managementIpv6Pool) + && in_array( + '2404:c140:156:3b::1003', + $managementIpv6Pool['excluded_addresses'] ?? [], + true + ), 'The host management address was not excluded from sparse input.'); + CloudPanelUsageService::$managementAddress = null; + + // A tenant replacement is deliberately confined to the current + // attachment even though administrators may move both families elsewhere. + Capsule::table('cloud_public_ips')->where('id', 111)->update([ + 'state' => 'disabled', ]); - $expiredTimestamp = CloudNetworkChangeOptionsService::forInstance( - $instance + $tenantWithoutLocalIpv4 = CloudNetworkChangeOptionsService::tenantQuote( + $instance->fresh() + ); + $adminWithAlternative = CloudNetworkChangeOptionsService::adminOptions( + $instance->fresh() ); - $assert(array_column( - $expiredTimestamp['available_ip_options'], - 'public_ip_cidr' - ) === ['198.51.100.3/29'], - 'An attachment without durable verification time remained selectable.'); - Capsule::table('cloud_host_network_attachments')->where('id', 2)->update([ - 'last_verified_at' => $now, + $assert(($tenantWithoutLocalIpv4['can_change'] ?? null) === false + && ($adminWithAlternative['can_change'] ?? null) === true, + 'Tenant automatic selection escaped its current attachment boundary.'); + Capsule::table('cloud_public_ip_pools')->where('id', 12)->update([ + 'max_allocations' => 1, ]); - Capsule::table('cloud_host_network_attachments')->where('id', 1)->update([ - 'state' => 'draining', 'verified_agent_revision' => 6, + Capsule::table('cloud_public_ip_pools')->where('id', 22)->update([ + 'state' => 'disabled', ]); - Capsule::table('cloud_public_ip_pools')->where('id', 11)->update([ - 'state' => 'draining', 'sync_state' => 'failed', + $singleFamilyAlternative = + CloudNetworkChangeOptionsService::adminOptions($instance->fresh()); + $assert(($singleFamilyAlternative['can_change'] ?? null) === false, + 'A single-family alternative attachment was advertised as usable.'); + Capsule::table('cloud_public_ip_pools')->where('id', 12)->update([ + 'max_allocations' => 64, + ]); + Capsule::table('cloud_public_ip_pools')->where('id', 22)->update([ + 'state' => 'active', ]); - $moveFromDraining = CloudNetworkChangeOptionsService::forInstance( - $instance + Capsule::table('cloud_public_ips')->where('id', 111)->update([ + 'state' => 'available', + ]); + + $job = new CloudJob(); + $job->id = 88; $job->kind = 'action'; $job->status = 'running'; + $job->updated_at = $now; + NetworkOptionsJobState::$job = $job; + $busy = CloudNetworkChangeOptionsService::tenantQuote($instance->fresh()); + $assert(($busy['can_change'] ?? null) === false + && ($busy['active_job']['id'] ?? null) === '88', + 'An active instance job did not disable the network quote.'); + NetworkOptionsJobState::$job = null; + Capsule::table('cloud_public_network_transitions')->insert([ + 'id' => 1, 'instance_id' => 30, 'active_transition' => 1, + ]); + $transitionBusy = CloudNetworkChangeOptionsService::tenantQuote( + $instance->fresh() + ); + $assert(($transitionBusy['can_change'] ?? null) === false, + 'An active public-network transition did not disable the quote.'); + Capsule::table('cloud_public_network_transitions')->delete(); + + Capsule::table('cloud_public_ips')->where('id', 111)->update([ + 'address_binary' => inet_pton('8.8.8.21'), + ]); + $corrupt = CloudNetworkChangeOptionsService::tenantQuote( + $instance->fresh() ); - $assert(array_column( - $moveFromDraining['available_ip_options'], - 'public_ip_cidr' - ) === ['198.51.100.10/29'] - && ($moveFromDraining['can_change'] ?? null) === true, - 'A draining source ledger prevented migration to a valid target.'); + $assert(($corrupt['configuration_state'] ?? null) === 'invalid' + && ($corrupt['can_change'] ?? null) === false, + 'An IPv4 row with mismatched packed identity remained selectable.'); + Capsule::table('cloud_public_ips')->where('id', 111)->update([ + 'address_binary' => inet_pton('8.8.8.20'), + ]); - Capsule::table('cloud_host_agents')->where('host_id', 1)->update([ - 'revision' => 8, 'tested_revision' => 8, + $broken = $publicNetwork; + $broken['ipv4']['address_cidr'] = '8.8.8.99/24'; + Capsule::table('cloud_instances')->where('id', 30)->update([ + 'spec_json' => json_encode([ + 'managed' => true, 'os_source' => 'cloud_template', + 'public_network' => $broken, + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), ]); - $expired = CloudNetworkChangeOptionsService::forInstance($instance); - $assert(($expired['available_ip_options'] ?? null) === [] - && ($expired['can_change'] ?? null) === false, - 'Expired Agent evidence remained available for a paid IP change.'); + $rejects( + static fn () => CloudNetworkChangeOptionsService::tenantQuote( + CloudInstance::findOrFail(30) + ), + 'A spec/ledger public-network mismatch remained quotable.' + ); echo "Cloud network-change options behavior passed.\n"; } diff --git a/web/tests/CloudNetworkIpLedgerContractTest.php b/web/tests/CloudNetworkIpLedgerContractTest.php index 881080df..3f29ea9a 100644 --- a/web/tests/CloudNetworkIpLedgerContractTest.php +++ b/web/tests/CloudNetworkIpLedgerContractTest.php @@ -4,6 +4,12 @@ $root = dirname(__DIR__); $controller = file_get_contents($root . '/app/Controllers/CloudAdminInstanceController.php'); $options = file_get_contents($root . '/app/Services/Cloud/CloudNetworkChangeOptionsService.php'); $jobs = file_get_contents($root . '/app/Services/Cloud/CloudJobService.php'); +$workflow = file_get_contents( + $root . '/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php' +); +$command = file_get_contents( + $root . '/app/Services/Cloud/CloudPublicNetworkTransitionCommand.php' +); $placement = file_get_contents($root . '/app/Services/Cloud/CloudPlacementService.php'); $placementNetwork = file_get_contents( $root . '/app/Services/Cloud/CloudPlacementNetworkService.php' @@ -46,71 +52,73 @@ $assert = static function ($condition, string $message): void { }; $assert(is_string($controller) && is_string($options) - && str_contains($controller, 'CloudNetworkChangeOptionsService::forInstance') + && str_contains($controller, + 'CloudNetworkChangeOptionsService::adminOptions($instance)') + && str_contains($controller, + 'CloudPublicNetworkTransitionCommand::adminExact(') + && str_contains($controller, + 'CloudPublicNetworkTransitionWorkflow::begin($command)') + && str_contains($controller, '$this->actor($request, true)') + && str_contains($options, 'public static function tenantQuote(') + && str_contains($options, 'public static function adminOptions(') && str_contains($options, - 'CloudPublicNetworkTransitionGate::assertWriterReady()') + 'CloudPublicNetworkAllocationService::currentClaimSet(') && str_contains($options, "->where('state', 'available')") - && str_contains($options, 'CloudPublicIp::where(\'host_id\'') - && str_contains($options, "public_pool.sync_state', 'applied'") + && str_contains($options, 'CloudPublicIp::where(') + && str_contains($options, "->where('sync_state', 'applied')") && str_contains($options, 'observed_revision') && !str_contains($controller, 'CloudEngineClient') && !str_contains($controller, 'host/network-options') - && str_contains($options, 'available_ip_options') - && str_contains($options, 'current_public_pool_key') + && str_contains($options, "'available_options'") + && str_contains($options, "'current_public_network'") + && str_contains($options, "'allocation_start'") + && str_contains($options, "'allocation_end'") + && str_contains($options, "'excluded_addresses'") && str_contains($options, 'CloudJobService::blockingQueryForInstance(') - && str_contains($options, - '(int) $attachment->line_id !== (int) $reservationPool->line_id') - && str_contains($controller, "['public_ip_cidr', 'public_pool_key', 'confirm_restart']"), - 'Shared network choices no longer intersect configured pools with the local ledger or require a pool key.'); + && str_contains($controller, + "CloudInput::only(\$body, ['targets', 'confirm_restart'])"), + 'Dual-stack network options or administrator transition command drifted.'); $assert(is_string($adminInstanceService) && str_contains( $adminInstanceService, - "'network_change_supported' => false" - ), - 'Administrator network changes were exposed before the dual-stack transition ledger is ready.'); + "'network_change_supported' => \$canMutate" + ) + && str_contains($adminInstanceService, '$managedCloudTemplate') + && str_contains($adminInstanceService, '$networkValid') + && str_contains($adminInstanceService, + '$instance->serviceAvailable($now)'), + 'Administrator network admission is not tied to active canonical managed instances.'); $assert(is_string($adminInstances) - && str_contains($adminInstances, 'available_ip_options') - && str_contains($adminInstances, 'option.dataset.publicPoolKey') - && str_contains($adminInstances, 'public_pool_key: target.public_pool_key') - && str_contains($adminInstances, 'networkOptionSummary(options, target.pool)'), - 'Admin network changes no longer preserve the selected pool identity and pool-specific network summary.'); + && str_contains($adminInstances, 'buildAdminNetworkTargets(') + && str_contains($adminInstances, 'targets: target.targets') + && str_contains($adminInstances, 'ipv4_target') + && str_contains($adminInstances, 'ipv6_address_cidr') + && str_contains($adminInstances, + 'await enqueue(`/api/v1/admin/instances/'), + 'Admin UI no longer submits one idempotent attachment-bound target map.'); $assert(is_string($input) && str_contains($input, 'function publicPoolKey') && str_contains($input, '/^[a-f0-9]{32}$/D'), 'Public pool keys no longer have a fixed lowercase-hex input boundary.'); -$assert(is_string($jobs) - && str_contains($jobs, - 'CloudPublicNetworkTransitionGate::assertWriterReady()') - && str_contains($jobs, '(string) $reservation->state !== \'committed\'') - && str_contains($jobs, '(string) $source->state !== \'assigned\'') - && str_contains($jobs, '(string) $target->state !== \'available\'') - && str_contains($jobs, '(string) $targetPool->state !== \'active\'') - && str_contains($jobs, "(string) \$targetPool->sync_state !== 'applied'") - && str_contains($jobs, '$attachmentIds = array_values(array_unique([') - && str_contains($jobs, 'sort($attachmentIds, SORT_NUMERIC)') - && str_contains($jobs, '$targetPool->network_attachment_id') - && str_contains($jobs, - '(int) $sourceAttachment->line_id') - && str_contains($jobs, - '(int) $targetAttachment->line_id') - && str_contains($jobs, '(int) $reservationPool->line_id') - && str_contains($jobs, - 'attachmentReadyForAgent($targetAttachment, $agent)') - && str_contains($jobs, - '(string) $targetAttachment->network_selector') - && str_contains($jobs, 'self::instancePublicIpMatches($locked, $source)') - && str_contains($jobs, '$target->state = \'changing\'') - && str_contains($jobs, '$target->operation_id = $job->operation_id') - && str_contains($jobs, '$jobPayload[\'source_public_ip_id\']') - && str_contains($jobs, '$jobPayload[\'target_public_ip_id\']') - && str_contains($jobs, - '$jobPayload[\'source_network_attachment_id\']') - && str_contains($jobs, - '$jobPayload[\'target_network_attachment_id\']') - && str_contains($jobs, '$jobPayload[\'source_public_ip_pool_id\']') - && str_contains($jobs, '$jobPayload[\'target_public_ip_pool_id\']'), - 'Network-change enqueue no longer locks and persists the attachment/pool/address ledger identity.'); +$assert(is_string($jobs) && is_string($workflow) && is_string($command) + && str_contains($jobs, "if (\$kind === 'network_change')") + && str_contains($jobs, '旧公网网络写入口已停用') + && !str_contains($jobs, 'paidNetworkChangeExpectedAmount') + && str_contains($workflow, + "(int) (\$claim->active_claim ?? 0) === 1") + && str_contains($workflow, + "CloudPublicIp::where('host_id', (int) \$instance->host_id)") + && str_contains($workflow, + 'CloudActivePublicNetworkClaimSet::fromLedger(') + && str_contains($workflow, 'source_network_attachment_id') + && str_contains($workflow, 'target_network_attachment_id') + && str_contains($workflow, 'source_claim_set_sha256') + && str_contains($workflow, 'target_claim_set_sha256') + && str_contains($workflow, + "\$job->public_network_transition_id = (int) \$transition->id") + && str_contains($command, 'private static function normalizeTargets('), + 'Canonical workflow no longer owns and freezes the dual-stack ledger identity.'); $assert(is_string($worker) && str_contains($worker, 'CloudPublicNetworkTransitionGate::assertWriterReady()') diff --git a/web/tests/CloudPaidIpChangeContractTest.php b/web/tests/CloudPaidIpChangeContractTest.php index b820a07f..752ba946 100644 --- a/web/tests/CloudPaidIpChangeContractTest.php +++ b/web/tests/CloudPaidIpChangeContractTest.php @@ -21,6 +21,12 @@ $options = $read( ); $billing = $read('app/Services/Cloud/CloudIpChangeBillingService.php'); $jobs = $read('app/Services/Cloud/CloudJobService.php'); +$workflow = $read( + 'app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php' +); +$command = $read( + 'app/Services/Cloud/CloudPublicNetworkTransitionCommand.php' +); $worker = $read('app/Services/Cloud/CloudWorkerService.php'); $config = $read('app/Controllers/Admin/ConfigController.php'); $configView = $read('resources/views/venix/admin/config.tpl'); @@ -53,7 +59,7 @@ $assert($optionsMethod !== '' && str_contains($optionsMethod, '(int) $instance->user_id !== (int) $actor[\'user_id\']') && str_contains($optionsMethod, - 'CloudNetworkChangeOptionsService::forInstance($instance)') + 'CloudNetworkChangeOptionsService::tenantQuote($instance)') && str_contains($optionsMethod, 'CloudIpChangeBillingService::price()') && !str_contains($optionsMethod, "'available_ip_options'") && !str_contains($optionsMethod, "'available_count'") @@ -72,9 +78,15 @@ $assert($networkMethod !== '' && str_contains($networkMethod, '$expectedAmount') && !str_contains($networkMethod, "'public_ip_cidr'") && !str_contains($networkMethod, "'public_pool_key'") - && str_contains($networkMethod, "'task_id' => (string) \$job->id") && str_contains($networkMethod, - "'status_url' => '/api/v1/tasks/' . \$job->id") + 'CloudPublicNetworkTransitionCommand::') + && str_contains($networkMethod, 'userPaidAutomatic(') + && str_contains($networkMethod, + 'CloudPublicNetworkTransitionWorkflow::begin($command)') + && str_contains($networkMethod, + "'task_id' => (string) \$dispatch->jobId()") + && str_contains($networkMethod, + "'status_url' => '/api/v1/tasks/' . \$dispatch->jobId()") && !str_contains($networkMethod, "'invoice_id'") && !str_contains($networkMethod, "'balance' =>"), 'Paid IP submission lost its quote check, idempotency, or strict task receipt.'); @@ -97,31 +109,31 @@ $enqueueEnd = strpos($jobs, 'public static function enqueueExpiryDelete(', $enqueueStart === false ? 0 : $enqueueStart); $enqueue = $enqueueStart !== false && $enqueueEnd !== false ? substr($jobs, $enqueueStart, $enqueueEnd - $enqueueStart) : ''; -$walletLock = strpos($enqueue, "User::where('id'"); -$instanceLock = strpos($enqueue, "CloudInstance::where('id'"); -$priorLookup = strpos($enqueue, - "->where('request_idempotency_key', \$requestKey)"); -$priceLookup = strpos($enqueue, +$walletLock = strpos($workflow, "User::where('id', \$command->actorUserId())"); +$instanceLock = strpos($workflow, + "CloudInstance::where('id', \$command->instanceId())"); +$replayLookup = strpos($workflow, + "'transition_key', \$command->transitionKey()"); +$priceLookup = strpos($workflow, 'CloudIpChangeBillingService::priceCents()'); -$hostLock = strpos($enqueue, - "\$host = CloudHost::where('id', (int) \$locked->host_id)"); -$automaticSelection = strpos($enqueue, - 'CloudNetworkChangeOptionsService::forInstance($locked)'); +$charge = strpos($workflow, + 'CloudIpChangeBillingService::chargeTransitionLocked('); $assert($enqueue !== '' - && str_contains($enqueue, 'CloudIpChangeBillingService::PURPOSE') - && str_contains($enqueue, "\$requestValue['expected_amount']") - && str_contains($enqueue, "? ['confirm_restart']") - && str_contains($enqueue, - "\$networkOptions['available_ip_options'][0]") - && str_contains($enqueue, '$locked->serviceAvailable()') - && str_contains($enqueue, 'CloudIpChangeBillingService::chargeLocked(') + && str_contains($enqueue, "if (\$kind === 'network_change')") + && str_contains($enqueue, '旧公网网络写入口已停用') + && !str_contains($enqueue, 'paidNetworkChangeExpectedAmount') + && str_contains($command, "[4 => null]") + && str_contains($workflow, "\$command->kind() === 'user_paid'") + && str_contains($workflow, + "->where('network_attachment_id', \$sourceAttachmentId)") + && str_contains($workflow, "->where('address_family', 4)") && $walletLock !== false && $instanceLock !== false && $walletLock < $instanceLock - && $priorLookup !== false && $priceLookup !== false - && $hostLock !== false && $automaticSelection !== false - && $priorLookup < $priceLookup - && $hostLock < $automaticSelection, - 'Paid enqueue lost automatic allocation, lock order, or replay-before-charge semantics.'); + && $replayLookup !== false && $priceLookup !== false + && $charge !== false && $replayLookup < $priceLookup + && $priceLookup < $charge, + 'Paid transition lost automatic same-attachment allocation, lock order, ' + . 'or replay-before-charge semantics.'); $assert(str_contains($billing, "public const PRICE_CONFIG_KEY = 'cloud_ip_change_price'") diff --git a/web/tests/CloudPublicIpPoolContractTest.php b/web/tests/CloudPublicIpPoolContractTest.php new file mode 100644 index 00000000..55286286 --- /dev/null +++ b/web/tests/CloudPublicIpPoolContractTest.php @@ -0,0 +1,150 @@ + str_repeat('a', 32), + 'address_family' => 4, + 'cidr' => '8.8.8.0/24', + 'gateway' => '8.8.8.1', + 'gateway_on_link' => false, + 'guest_prefix_length' => 24, + 'dns_servers_json' => '["1.1.1.1","2606:4700:4700::1111"]', + 'reserved_ips_json' => '["8.8.8.2"]', + 'allocation_start' => null, + 'allocation_end' => null, + 'allocation_cursor' => null, + 'max_allocations' => 0, + ] : [ + 'pool_key' => str_repeat('b', 32), + 'address_family' => 6, + 'cidr' => '2404:c140:156:3a::/64', + 'gateway' => '2404:c140:156::1', + 'gateway_on_link' => true, + 'guest_prefix_length' => 64, + 'dns_servers_json' => '["1.1.1.1","2606:4700:4700::1111"]', + 'reserved_ips_json' => '["2404:c140:156:3a::1002"]', + 'allocation_start' => '2404:c140:156:3a::1000', + 'allocation_end' => '2404:c140:156:3a::10ff', + 'allocation_cursor' => '2404:c140:156:3a::1000', + 'max_allocations' => 64, + ]); +}; + +$ipv4 = CloudPublicIpPoolContract::fromRow($row(4)); +$ipv6 = CloudPublicIpPoolContract::fromRow($row(6)); +$assert($ipv4->family() === 4 + && $ipv4->addressAllowed(CloudIpAddress::parse('8.8.8.20')) + && !$ipv4->addressAllowed(CloudIpAddress::parse('8.8.8.2')), + 'The canonical IPv4 pool contract was not projected correctly.'); +$assert($ipv6->family() === 6 + && $ipv6->gatewayOnLink() + && $ipv6->allocationStart()?->text() + === '2404:c140:156:3a::1000' + && $ipv6->addressAllowed( + CloudIpAddress::parse('2404:c140:156:3a::1003') + ), 'The canonical off-prefix IPv6 gateway contract was rejected.'); + +foreach ([ + 'family mismatch' => static function (object $pool): void { + $pool->address_family = 6; + }, + 'noncanonical cidr' => static function (object $pool): void { + $pool->cidr = '8.8.8.0/023'; + }, + 'out-of-policy prefix' => static function (object $pool): void { + $pool->cidr = '8.8.8.0/23'; + $pool->guest_prefix_length = 23; + }, + 'guest prefix drift' => static function (object $pool): void { + $pool->guest_prefix_length = 25; + }, + 'IPv4 on-link gateway' => static function (object $pool): void { + $pool->gateway_on_link = true; + }, + 'IPv4 invalid boolean gateway flag' => static function (object $pool): void { + $pool->gateway_on_link = 2; + }, + 'IPv4 off-pool gateway' => static function (object $pool): void { + $pool->gateway = '8.8.9.1'; + }, + 'private DNS' => static function (object $pool): void { + $pool->dns_servers_json = '["10.0.0.1"]'; + }, + 'wrong-family reserved address' => static function (object $pool): void { + $pool->reserved_ips_json = '["2606:4700:4700::1111"]'; + }, + 'IPv4 sparse range' => static function (object $pool): void { + $pool->allocation_start = '8.8.8.10'; + }, +] as $label => $mutate) { + $pool = $row(4); + $mutate($pool); + $rejects( + static fn () => CloudPublicIpPoolContract::fromRow($pool), + 'Invalid IPv4 pool accepted: ' . $label + ); +} + +foreach ([ + 'off-pool gateway without on-link' => static function (object $pool): void { + $pool->gateway_on_link = false; + }, + 'IPv6 invalid boolean gateway flag' => static function (object $pool): void { + $pool->gateway_on_link = 'false'; + }, + 'range outside pool' => static function (object $pool): void { + $pool->allocation_end = '2404:c140:156:3b::10ff'; + }, + 'cursor outside range' => static function (object $pool): void { + $pool->allocation_cursor = '2404:c140:156:3a::1100'; + }, + 'maximum below one' => static function (object $pool): void { + $pool->max_allocations = 0; + }, + 'maximum above contract' => static function (object $pool): void { + $pool->max_allocations = 65536; + }, + 'wrong-family reserved address' => static function (object $pool): void { + $pool->reserved_ips_json = '["8.8.8.2"]'; + }, +] as $label => $mutate) { + $pool = $row(6); + $mutate($pool); + $rejects( + static fn () => CloudPublicIpPoolContract::fromRow($pool), + 'Invalid IPv6 pool accepted: ' . $label + ); +} + +$large = $row(6); +$large->allocation_end = '2404:c140:156:3a::1:1002'; +$large->max_allocations = 65535; +$started = microtime(true); +for ($iteration = 0; $iteration < 100; $iteration++) { + CloudPublicIpPoolContract::fromRow($large); +} +$assert(microtime(true) - $started < 1.0, + 'Maximum sparse-capacity validation regressed to per-address scanning.'); + +echo "Shared public-IP pool contract tests passed.\n"; diff --git a/web/tests/CloudPublicNetworkLegacyWriterGateContractTest.php b/web/tests/CloudPublicNetworkLegacyWriterGateContractTest.php index 8bc878c6..eadbc455 100644 --- a/web/tests/CloudPublicNetworkLegacyWriterGateContractTest.php +++ b/web/tests/CloudPublicNetworkLegacyWriterGateContractTest.php @@ -101,12 +101,22 @@ $assert(str_contains($gate, 'assertWriterReady') $enqueueStart = strpos($jobs, 'public static function enqueue('); $enqueueTransaction = strpos($jobs, 'return $instance->getConnection()->transaction', $enqueueStart === false ? 0 : $enqueueStart); -$enqueueGate = strpos($jobs, - 'CloudPublicNetworkTransitionGate::assertWriterReady()', - $enqueueStart === false ? 0 : $enqueueStart); -$assert($enqueueStart !== false && $enqueueGate !== false - && $enqueueTransaction !== false && $enqueueGate < $enqueueTransaction, - 'Network-change gate runs after its target, invoice or job transaction starts.'); +$enqueueReject = strpos($enqueue, "if (\$kind === 'network_change')"); +$enqueueRejectError = strpos($enqueue, '旧公网网络写入口已停用'); +$assert($enqueueStart !== false && $enqueueReject !== false + && $enqueueRejectError !== false && $enqueueTransaction !== false + && $enqueueReject < $enqueueTransaction + && $enqueueRejectError < $enqueueTransaction + && !str_contains($enqueue, 'paidNetworkChangeExpectedAmount') + && !str_contains($enqueue, "['public_ip_cidr', 'public_pool_key'") + && !str_contains($enqueue, '$networkLedger'), + 'Ordinary enqueue retained a scalar network writer or rejects it too late.'); +$assert(str_contains($worker, + "(string) \$job->kind === 'network_change'\n" + . ' && $job->public_network_transition_id === null') + && str_contains($worker, + 'CloudPublicNetworkTransitionGate::assertWriterReady()'), + 'Worker does not distinguish canonical transition jobs from legacy rows.'); $assert($before($worker, "(string) \$job->kind === 'network_change'", "'phase' => 'dispatching'") diff --git a/web/tests/CloudPublicNetworkPoolReuseContractTest.php b/web/tests/CloudPublicNetworkPoolReuseContractTest.php new file mode 100644 index 00000000..83c40d38 --- /dev/null +++ b/web/tests/CloudPublicNetworkPoolReuseContractTest.php @@ -0,0 +1,36 @@ + 'pool-ledger contract parameter', + 'CloudPublicIpPoolContract $contract, array $rows' => + 'shared parsed contract in ledger validation', + "lockReservableAddressCandidate(\n object \$pool,\n" + . ' CloudPublicIpPoolContract $contract,' => + 'shared parsed contract in candidate selection', + "'contracts' => \$contracts" => 'per-catalog contract cache', + "'contracts' => \$selectedContracts" => + 'per-selection contract propagation', +] as $needle => $label) { + if (!str_contains($source, $needle)) { + throw new RuntimeException('Missing ' . $label . '.'); + } +} + +$rawAllowed = strstr($source, + 'private static function rawAddressAllowedByPool'); +if (!is_string($rawAllowed) + || !str_contains($rawAllowed, 'CloudPublicIpPoolContract $contract') + || str_contains(substr($rawAllowed, 0, 1200), + 'CloudPublicIpPoolContract::fromRow')) { + throw new RuntimeException( + 'Hot address validation reconstructs the pool contract per row.' + ); +} + +echo "Public-network allocator pool-contract reuse checks passed.\n"; diff --git a/web/tests/CloudPublicNetworkTransitionFinalizationTest.php b/web/tests/CloudPublicNetworkTransitionFinalizationTest.php index 0410db07..df09cade 100644 --- a/web/tests/CloudPublicNetworkTransitionFinalizationTest.php +++ b/web/tests/CloudPublicNetworkTransitionFinalizationTest.php @@ -7,6 +7,8 @@ use App\Models\CloudJob; use App\Models\User; use App\Services\Cloud\CloudAdminOperationRecoveryService; use App\Services\Cloud\CloudOperationRecoveryIdentity; +use App\Services\Cloud\CloudNetworkChangeOptionsService; +use App\Services\Cloud\CloudPublicNetworkAllocationService; use App\Services\Cloud\CloudPublicNetworkTransitionCommand; use App\Services\Cloud\CloudPublicNetworkTransitionWorkflow; use App\Services\Cloud\CloudSecrets; @@ -150,6 +152,39 @@ $assert($source4->state === 'released' ->value('state') === 'assigned', 'Applied transition did not atomically switch only the changed leg.'); +// A successful transition must make the active claim pair authoritative even +// when intentionally stale singular reservation mirrors remain present. +$reservationRow = Capsule::table('cloud_resource_reservations') + ->where('id', 101)->first(); +$postTransitionOptions = CloudNetworkChangeOptionsService::adminOptions( + CloudInstance::find(1) +); +$assert((int) $reservationRow->network_attachment_id === 999 + && (int) $reservationRow->public_ip_pool_id === 999 + && (int) $reservationRow->public_ip_id === 999 + && ($postTransitionOptions['current_attachment_id'] ?? null) === '1' + && ($postTransitionOptions['current_public_network']['ipv4'] + ['address_cidr'] ?? null) === '8.8.9.20/24' + && ($postTransitionOptions['current_public_network']['ipv6'] + ['address_cidr'] ?? null) === '2404:c140:156:3a::1000/64', + 'Post-transition options fell back to stale singular reservation data.'); + +CloudPublicNetworkAllocationService::releaseCommittedBundle( + 101, + 1, + (string) $reservationOperation, + 'instance_deleted', + true +); +$assert(Capsule::table('cloud_resource_reservation_ips') + ->whereIn('id', [(int) $target4->id, 1002]) + ->where('state', 'released')->count() === 2 + && Capsule::table('cloud_public_ips')->whereIn('id', [201, 102]) + ->where('state', 'available')->count() === 2 + && Capsule::table('cloud_public_ips')->where('instance_id', 1) + ->where('state', 'assigned')->count() === 0, + 'Committed release used stale scalar mirrors instead of active claims.'); + // Recovery prepare may release its target projection, but wallet settlement // and transition publication wait for the later recovery commit. [$failedJob, $failedPayload] = $dispatchJob($paidDispatch->jobId()); @@ -458,7 +493,7 @@ $assert((string) $retried->phase === 'terminal' // roll the whole local projection back. Retrying the same persisted evidence // then succeeds without another Agent dispatch. $addIp(503, 21, 4, '9.9.9.32'); -$addIp(504, 22, 6, '2404:c140:156:3c::1003'); +$addIp(504, 22, 6, '2404:c140:156:3c::1004'); Capsule::table('cloud_host_network_attachments')->where('id', 1) ->update(['state' => 'draining']); $atomic = CloudPublicNetworkTransitionWorkflow::begin( @@ -473,7 +508,7 @@ $atomic = CloudPublicNetworkTransitionWorkflow::begin( ], 6 => [ 'pool_key' => str_repeat('f', 32), - 'address_cidr' => '2404:c140:156:3c::1003/64', + 'address_cidr' => '2404:c140:156:3c::1004/64', ], ] ) diff --git a/web/tests/CloudPublicNetworkTransitionWorkflowContractTest.php b/web/tests/CloudPublicNetworkTransitionWorkflowContractTest.php index 6e09992b..49314011 100644 --- a/web/tests/CloudPublicNetworkTransitionWorkflowContractTest.php +++ b/web/tests/CloudPublicNetworkTransitionWorkflowContractTest.php @@ -26,9 +26,16 @@ $worker = file_get_contents( $recovery = file_get_contents( $root . '/app/Services/Cloud/CloudOperationRecoveryService.php' ); +$tenantController = file_get_contents( + $root . '/app/Controllers/CloudApiController.php' +); +$adminController = file_get_contents( + $root . '/app/Controllers/CloudAdminInstanceController.php' +); $assert(is_string($source) && is_string($billing) && is_string($activeIdentity) && is_string($worker) - && is_string($recovery), 'Transition workflow sources are missing.'); + && is_string($recovery) && is_string($tenantController) + && is_string($adminController), 'Transition workflow sources are missing.'); $workflow = new ReflectionClass(CloudPublicNetworkTransitionWorkflow::class); $public = array_values(array_map( @@ -91,6 +98,10 @@ $assert(str_contains($source, && str_contains($source, 'CloudJobService::blockingQueryForInstance('), 'Open migration, recovery, or job work is not fenced before writes.'); +$assert(str_contains($source, "(\$spec['managed'] ?? false) !== true") + && str_contains($source, + "(\$spec['os_source'] ?? null) !== 'cloud_template'"), + 'The deep workflow seam does not enforce managed cloud-template admission.'); $assert(str_contains($source, "\$job->kind = 'network_change';") && str_contains($source, "\$job->public_network_transition_id = (int) \$transition->id;") @@ -114,6 +125,11 @@ $assert(str_contains($worker, 'markDispatched($job)') && str_contains($recovery, 'publishPreparedLocked('), 'Worker or recovery coordinator bypasses the Stage 4 transition seam.'); +$allowedBeginCallers = [ + realpath($root . '/app/Controllers/CloudApiController.php'), + realpath($root . '/app/Controllers/CloudAdminInstanceController.php'), +]; +$actualBeginCallers = []; foreach ([$root . '/app', $root . '/config'] as $directory) { $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( @@ -130,12 +146,30 @@ foreach ([$root . '/app', $root . '/config'] as $directory) { continue; } $contents = file_get_contents($file->getPathname()); - $assert(!is_string($contents) - || !str_contains($contents, - 'CloudPublicNetworkTransitionWorkflow::begin('), - 'Stage 4 writer gate was opened through a production caller: ' - . $file->getPathname()); + if (is_string($contents) && str_contains( + $contents, + 'CloudPublicNetworkTransitionWorkflow::begin(' + )) { + $actualBeginCallers[] = realpath($file->getPathname()); + } } } +$actualBeginCallers = array_values(array_unique($actualBeginCallers)); +sort($actualBeginCallers); +sort($allowedBeginCallers); +$assert($actualBeginCallers === $allowedBeginCallers, + 'Production workflow callers escaped the two Stage 5 controller seams.'); +$assert(str_contains($tenantController, + 'CloudPublicNetworkTransitionCommand::') + && str_contains($tenantController, 'userPaidAutomatic(') + && str_contains($tenantController, + 'CloudPublicNetworkTransitionWorkflow::begin($command)') + && !str_contains($tenantController, + "CloudJobService::enqueue(\n \$instance,\n \$actor,\n 'network_change'") + && str_contains($adminController, + 'CloudPublicNetworkTransitionCommand::adminExact(') + && str_contains($adminController, + 'CloudPublicNetworkTransitionWorkflow::begin($command)'), + 'A Stage 5 controller bypasses the command plus transition seam.'); echo "Public-network transition workflow contract tests passed.\n"; diff --git a/web/tests/CloudPublicNetworkTransitionWorkflowTest.php b/web/tests/CloudPublicNetworkTransitionWorkflowTest.php index 7c09414e..aa9a47ac 100644 --- a/web/tests/CloudPublicNetworkTransitionWorkflowTest.php +++ b/web/tests/CloudPublicNetworkTransitionWorkflowTest.php @@ -18,6 +18,16 @@ namespace App\Services\Cloud { return self::$values[substr($value, strlen($prefix))] ?? []; } } + + final class CloudPanelUsageService + { + public static ?string $managementAddress = null; + + public static function managementAddress($host): ?string + { + return self::$managementAddress; + } + } } namespace { @@ -32,6 +42,7 @@ namespace { use App\Services\Cloud\CloudPublicNetworkTransitionCommand; use App\Services\Cloud\CloudPublicNetworkTransitionWorkflow; use App\Services\Cloud\CloudSecrets; + use App\Services\Cloud\CloudPanelUsageService; use Illuminate\Database\Capsule\Manager as Capsule; use Illuminate\Database\Schema\Blueprint; @@ -450,6 +461,10 @@ namespace { $pool(22, 2, 6, 'f', '2404:c140:156:3c::/64', '2404:c140:156::1'), ]); + Capsule::table('cloud_public_ip_pools')->where('id', 22)->update([ + 'dns_servers_json' => '["2404:c140:156:3c::1001"]', + 'reserved_ips_json' => '["2404:c140:156:3c::1002"]', + ]); $addIp = static function (int $id, int $poolId, int $family, string $address, string $state = 'available', ?int $reservationId = null, @@ -481,6 +496,7 @@ namespace { $addIp(302, 21, 4, '9.9.9.31'); $addIp(401, 22, 6, '2404:c140:156:3c::1000'); $addIp(402, 22, 6, '2404:c140:156:3c::1001'); + $addIp(403, 22, 6, '2404:c140:156:3c::1003'); $sourceSnapshot = static function (string $ipv4, string $ipv6): array { return [ @@ -591,6 +607,8 @@ namespace { 'network_status' => 'active', 'expires_at' => $now + 86400, 'spec_json' => json_encode([ + 'managed' => true, + 'os_source' => 'cloud_template', 'public_network' => $sourceSnapshot($address4, $address6), ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), 'created_at' => $now, @@ -766,6 +784,214 @@ namespace { ->value('state') === 'available', 'Rejected cross-attachment transition left side effects.'); + $beforeDriftTransitions = Capsule::table( + 'cloud_public_network_transitions' + )->count(); + $beforeDriftJobs = Capsule::table('cloud_jobs')->count(); + Capsule::table('cloud_public_ip_pools')->whereIn('id', [21, 22]) + ->update(['observed_revision' => 2]); + $rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin( + CloudPublicNetworkTransitionCommand::adminExact( + 2, + 99, + 'admin-network-revision-drift', + [ + 4 => [ + 'pool_key' => str_repeat('e', 32), + 'address_cidr' => '9.9.9.30/24', + ], + 6 => [ + 'pool_key' => str_repeat('f', 32), + 'address_cidr' => '2404:c140:156:3c::1000/64', + ], + ] + ) + ), 'A pool with observed revision ahead of desired was accepted.'); + $assert(Capsule::table('cloud_public_network_transitions')->count() + === $beforeDriftTransitions + && Capsule::table('cloud_jobs')->count() === $beforeDriftJobs + && Capsule::table('cloud_public_ips')->where('id', 301) + ->value('state') === 'available' + && Capsule::table('cloud_public_ips')->where('id', 401) + ->value('state') === 'available', + 'Revision-drift rejection left transition, job, or IP writes.'); + Capsule::table('cloud_public_ip_pools')->whereIn('id', [21, 22]) + ->update(['observed_revision' => 1]); + + $validTargetPools = [ + 21 => [ + 'cidr' => '9.9.9.0/24', 'gateway' => '9.9.9.1', + 'gateway_on_link' => 0, 'guest_prefix_length' => 24, + 'dns_servers_json' => '["1.1.1.1"]', + 'reserved_ips_json' => '[]', + 'allocation_start' => null, 'allocation_end' => null, + 'allocation_cursor' => null, 'max_allocations' => 0, + ], + 22 => [ + 'cidr' => '2404:c140:156:3c::/64', + 'gateway' => '2404:c140:156::1', 'gateway_on_link' => 1, + 'guest_prefix_length' => 64, + 'dns_servers_json' => '["2404:c140:156:3c::1001"]', + 'reserved_ips_json' => '["2404:c140:156:3c::1002"]', + 'allocation_start' => '2404:c140:156:3c::1000', + 'allocation_end' => '2404:c140:156:3c::10ff', + 'allocation_cursor' => '2404:c140:156:3c::1000', + 'max_allocations' => 64, + ], + ]; + $corruptPoolCases = [ + 'guest prefix drift' => [22, ['guest_prefix_length' => 65]], + 'IPv4 on-link gateway' => [21, ['gateway_on_link' => 1]], + 'IPv4 invalid boolean gateway flag' => [21, [ + 'gateway_on_link' => 2, + ]], + 'IPv4 /23 prefix' => [21, [ + 'cidr' => '9.9.8.0/23', 'guest_prefix_length' => 23, + ]], + 'IPv6 /121 prefix' => [22, [ + 'cidr' => '2404:c140:156:3c::/121', + 'guest_prefix_length' => 121, + ]], + 'private DNS' => [21, [ + 'dns_servers_json' => '["10.0.0.1"]', + ]], + 'duplicate DNS' => [21, [ + 'dns_servers_json' => '["1.1.1.1","1.1.1.1"]', + ]], + 'empty DNS' => [21, ['dns_servers_json' => '[]']], + 'five DNS addresses' => [21, [ + 'dns_servers_json' => '["1.1.1.1","8.8.8.8",' + . '"9.9.9.9","2606:4700:4700::1111",' + . '"2001:4860:4860::8888"]', + ]], + 'private reserved address' => [21, [ + 'reserved_ips_json' => '["10.0.0.1"]', + ]], + 'duplicate reserved address' => [21, [ + 'reserved_ips_json' => '["9.9.9.2","9.9.9.2"]', + ]], + 'off-pool reserved address' => [21, [ + 'reserved_ips_json' => '["8.8.8.2"]', + ]], + 'network reserved address' => [21, [ + 'reserved_ips_json' => '["9.9.9.0"]', + ]], + 'off-prefix gateway without on-link' => [22, [ + 'gateway_on_link' => 0, + ]], + 'IPv6 invalid boolean gateway flag' => [22, [ + 'gateway_on_link' => 'false', + ]], + 'zero sparse allocation limit' => [22, [ + 'max_allocations' => 0, + ]], + 'excess sparse allocation limit' => [22, [ + 'max_allocations' => 65536, + ]], + 'insufficient sparse range' => [22, [ + 'allocation_end' => '2404:c140:156:3c::1002', + 'max_allocations' => 2, + ]], + 'cursor outside sparse range' => [22, [ + 'allocation_cursor' => '2404:c140:156:3c::1100', + ]], + ]; + $beforeCorruptClaims = Capsule::table( + 'cloud_resource_reservation_ips' + )->count(); + $beforeCorruptIps = Capsule::table('cloud_public_ips')->count(); + $beforeCorruptInvoices = Capsule::table('cloud_invoices')->count(); + $beforeCorruptMoney = (string) Capsule::table('user')->where('id', 10) + ->value('money'); + $caseNumber = 0; + foreach ($corruptPoolCases as $label => [$poolId, $corruption]) { + $caseNumber++; + Capsule::table('cloud_public_ip_pools')->where('id', $poolId) + ->update($corruption); + $requestKey = sprintf('admin-network-corrupt-%02d', $caseNumber); + $rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin( + CloudPublicNetworkTransitionCommand::adminExact( + 2, + 99, + $requestKey, + [ + 4 => [ + 'pool_key' => str_repeat('e', 32), + 'address_cidr' => '9.9.9.30/24', + ], + 6 => [ + 'pool_key' => str_repeat('f', 32), + 'address_cidr' => '2404:c140:156:3c::1000/64', + ], + ] + ) + ), 'A corrupt public-IP pool entered transition writes: ' . $label); + $assert(Capsule::table('cloud_public_network_transitions')->count() + === $beforeDriftTransitions + && Capsule::table('cloud_jobs')->count() === $beforeDriftJobs + && Capsule::table('cloud_resource_reservation_ips')->count() + === $beforeCorruptClaims + && Capsule::table('cloud_public_ips')->count() + === $beforeCorruptIps + && Capsule::table('cloud_invoices')->count() + === $beforeCorruptInvoices + && (string) Capsule::table('user')->where('id', 10) + ->value('money') === $beforeCorruptMoney + && Capsule::table('cloud_public_ips')->where('id', 301) + ->value('state') === 'available' + && Capsule::table('cloud_public_ips')->where('id', 401) + ->value('state') === 'available', + 'Corrupt-pool rejection left durable writes: ' . $label); + Capsule::table('cloud_public_ip_pools')->where('id', $poolId) + ->update($validTargetPools[$poolId]); + } + + CloudPanelUsageService::$managementAddress = + '2404:c140:156:3c::1003'; + $beforeManagementTransitions = Capsule::table( + 'cloud_public_network_transitions' + )->count(); + $beforeManagementJobs = Capsule::table('cloud_jobs')->count(); + $beforeManagementClaims = Capsule::table( + 'cloud_resource_reservation_ips' + )->count(); + $beforeManagementIps = Capsule::table('cloud_public_ips')->count(); + $beforeManagementInvoices = Capsule::table('cloud_invoices')->count(); + $beforeManagementMoney = (string) Capsule::table('user') + ->where('id', 10)->value('money'); + $rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin( + CloudPublicNetworkTransitionCommand::adminExact( + 2, + 99, + 'admin-network-management-blocked', + [ + 4 => [ + 'pool_key' => str_repeat('e', 32), + 'address_cidr' => '9.9.9.30/24', + ], + 6 => [ + 'pool_key' => str_repeat('f', 32), + 'address_cidr' => '2404:c140:156:3c::1003/64', + ], + ] + ) + ), 'The host management address entered sparse transition writes.'); + $assert(Capsule::table('cloud_public_network_transitions')->count() + === $beforeManagementTransitions + && Capsule::table('cloud_jobs')->count() === $beforeManagementJobs + && Capsule::table('cloud_resource_reservation_ips')->count() + === $beforeManagementClaims + && Capsule::table('cloud_public_ips')->count() + === $beforeManagementIps + && Capsule::table('cloud_invoices')->count() + === $beforeManagementInvoices + && (string) Capsule::table('user')->where('id', 10) + ->value('money') === $beforeManagementMoney + && Capsule::table('cloud_public_ips')->where('id', 403) + ->value('state') === 'available', + 'Management-address rejection left durable writes.'); + CloudPanelUsageService::$managementAddress = null; + Capsule::table('cloud_host_network_attachments')->where('id', 1) ->update(['state' => 'draining']); $cross = CloudPublicNetworkTransitionWorkflow::begin( @@ -893,8 +1119,10 @@ namespace { Capsule::table('cloud_instances')->where('id', 7)->update([ 'spec_json' => json_encode([ + 'managed' => false, + 'os_source' => 'cloud_template', 'public_network' => $sourceSnapshot( - '8.8.8.99', + '8.8.8.16', '2404:c140:156:3a::1006' ), ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), @@ -909,10 +1137,82 @@ namespace { 'address_cidr' => '8.8.9.22/24', ]] ) - ), 'A drifted frozen public-network spec entered transition writes.'); + ), 'An unmanaged instance entered transition writes.'); $assert(Capsule::table('cloud_public_ips')->where('id', 203) ->value('state') === 'available', - 'Pre-write mutation gates fenced an address despite rejection.'); + 'Managed-cloud-template gate fenced an address despite rejection.'); + + $beforeTransitions = Capsule::table('cloud_public_network_transitions') + ->count(); + $beforeJobs = Capsule::table('cloud_jobs')->count(); + $beforeIps = Capsule::table('cloud_public_ips')->count(); + // Establish the sparse-capacity precondition explicitly instead of + // depending on later readers inferring it from the cross-attachment case: + // pool 22 already owns one reserved slot while address 403 is a distinct, + // valid, pre-materialized available address. + Capsule::table('cloud_public_ip_pools')->where('id', 22)->update([ + 'max_allocations' => 1, + ]); + $assert((int) Capsule::table('cloud_public_ip_pools')->where('id', 22) + ->value('max_allocations') === 1 + && Capsule::table('cloud_public_ips')->where('id', 401) + ->value('state') === 'reserved' + && Capsule::table('cloud_public_ips')->where('id', 403) + ->value('state') === 'available', + 'Sparse-capacity fixture did not establish one occupied slot and one ' + . 'separate available address.'); + $attemptSparse = static function (string $requestKey, + string $targetIpv6): void { + CloudPublicNetworkTransitionWorkflow::begin( + CloudPublicNetworkTransitionCommand::adminExact( + 10, + 99, + $requestKey, + [ + 4 => [ + 'pool_key' => str_repeat('e', 32), + 'address_cidr' => '9.9.9.31/24', + ], + 6 => [ + 'pool_key' => str_repeat('f', 32), + 'address_cidr' => $targetIpv6, + ], + ] + ) + ); + }; + $rejects( + static fn () => $attemptSparse( + 'admin-network-ipv6-full', + '2404:c140:156:3c::1003/64' + ), + 'A full sparse pool reused a materialized available row.' + ); + $assert(Capsule::table('cloud_public_network_transitions')->count() + === $beforeTransitions + && Capsule::table('cloud_jobs')->count() === $beforeJobs + && Capsule::table('cloud_public_ips')->count() === $beforeIps, + 'Full sparse pool rejection left durable writes.'); + Capsule::table('cloud_public_ip_pools')->where('id', 22)->update([ + 'max_allocations' => 64, + ]); + foreach ([ + 'admin-network-ipv6-dns' => '2404:c140:156:3c::1001/64', + 'admin-network-ipv6-reserved' => '2404:c140:156:3c::1002/64', + 'admin-network-ipv6-range' => '2404:c140:156:3c::1100/64', + ] as $requestKey => $targetIpv6) { + $rejects( + static fn () => $attemptSparse($requestKey, $targetIpv6), + 'A blocked or out-of-range sparse IPv6 target was accepted.' + ); + } + $assert(Capsule::table('cloud_public_network_transitions')->count() + === $beforeTransitions + && Capsule::table('cloud_jobs')->count() === $beforeJobs + && Capsule::table('cloud_public_ips')->count() === $beforeIps + && Capsule::table('cloud_public_ips')->where('id', 302) + ->value('state') === 'available', + 'Rejected sparse IPv6 input left target, job, or transition writes.'); $sparse = CloudPublicNetworkTransitionWorkflow::begin( CloudPublicNetworkTransitionCommand::adminExact( @@ -926,15 +1226,15 @@ namespace { ], 6 => [ 'pool_key' => str_repeat('f', 32), - 'address_cidr' => '2404:c140:156:3c::1002/64', + 'address_cidr' => '2404:c140:156:3c::10ff/64', ], ] ) ); $sparseIp = Capsule::table('cloud_public_ips') - ->where('address', '2404:c140:156:3c::1002')->first(); + ->where('address', '2404:c140:156:3c::10ff')->first(); $assert($sparse->target()->address(6) - === '2404:c140:156:3c::1002/64' + === '2404:c140:156:3c::10ff/64' && $sparseIp !== null && (int) $sparseIp->public_ip_pool_id === 22 && $sparseIp->state === 'reserved', diff --git a/web/tests/CloudUserInstanceSettingsBehaviorTest.php b/web/tests/CloudUserInstanceSettingsBehaviorTest.php new file mode 100644 index 00000000..8d5d6be0 --- /dev/null +++ b/web/tests/CloudUserInstanceSettingsBehaviorTest.php @@ -0,0 +1,212 @@ +id = 92; + return $job; + } + } + + final class UserSettingsAgentClient + { + public function request(string $method, string $path, array $actor, + array $body): array + { + return [ + 'ticket' => str_repeat('a', 32), + 'expires_at' => time() + 30, + ]; + } + } + + final class CloudAgentSettingsService + { + public static function clientForHost(int $hostId, + float $timeoutSeconds = 20.0): UserSettingsAgentClient + { + return new UserSettingsAgentClient(); + } + } + + final class CloudConsoleTicketService + { + public static function issue(CloudInstance $instance, array $actor, + array $agentTicket): array + { + return [ + 'ticket' => 'browser-ticket', + 'expires_in' => 30, + 'websocket_path' => '/engine-console', + ]; + } + } +} + +namespace { + require dirname(__DIR__) . '/vendor/autoload.php'; + + use App\Controllers\CloudApiController; + use App\Services\Cloud\CloudError; + use App\Services\Cloud\UserSettingsJobCapture; + use Illuminate\Database\Capsule\Manager as Capsule; + use Illuminate\Database\Schema\Blueprint; + use Slim\Http\Environment; + use Slim\Http\Request; + use Slim\Http\Response; + + $assert = static function (bool $condition, string $message): void { + if (!$condition) { throw new RuntimeException($message); } + }; + $rejects = static function (callable $callback, string $message): void { + try { $callback(); } catch (CloudError $error) { + if ($error->httpStatus === 409) { return; } + throw new RuntimeException($message . ': unexpected status ' + . $error->httpStatus); + } + throw new RuntimeException($message); + }; + + $capsule = new Capsule(); + $capsule->addConnection([ + 'driver' => 'sqlite', 'database' => ':memory:', + ], 'default'); + $capsule->setAsGlobal(); + $capsule->bootEloquent(); + $capsule->schema('default')->create('cloud_instances', static function ( + Blueprint $t + ): void { + $t->increments('id'); $t->integer('host_id'); + $t->integer('user_id'); $t->string('uuid'); + $t->string('status'); $t->string('service_status'); + $t->integer('expires_at')->nullable(); $t->text('spec_json'); + $t->text('sealed_credential')->nullable(); + }); + + $network = [ + 'contract' => 1, 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'pool_key' => str_repeat('a', 32), + 'pool_cidr' => '8.8.8.0/24', + 'address_cidr' => '8.8.8.10/24', + 'gateway' => '8.8.8.1', 'gateway_on_link' => false, + ], + 'ipv6' => [ + 'pool_key' => str_repeat('b', 32), + 'pool_cidr' => '2404:c140:156:3a::/64', + 'address_cidr' => '2404:c140:156:3a::10/64', + 'gateway' => '2404:c140:156::1', 'gateway_on_link' => true, + ], + 'dns_servers' => ['1.1.1.1', '2606:4700:4700::1111'], + ]; + $canonicalSpec = [ + 'managed' => true, 'os_source' => 'cloud_template', + 'public_network' => $network, + ]; + $specs = [ + 1 => $canonicalSpec, + 2 => [ + 'managed' => true, 'os_source' => 'cloud_template', + 'public_ip_cidr' => '8.8.8.20/24', + ], + 3 => ['managed' => true, 'os_source' => 'cloud_template'], + 4 => [ + 'managed' => true, 'os_source' => 'cloud_template', + 'public_network' => ['contract' => 1], + ], + 5 => [ + 'managed' => false, 'os_source' => 'cloud_template', + 'public_network' => $network, + ], + 6 => [ + 'managed' => true, 'os_source' => 'custom_iso', + 'public_network' => $network, + ], + 7 => $canonicalSpec, + ]; + $now = time(); + foreach ($specs as $id => $spec) { + Capsule::table('cloud_instances')->insert([ + 'id' => $id, 'host_id' => 1, 'user_id' => 7, + 'uuid' => sprintf('00000000-0000-4000-8000-%012d', $id), + 'status' => 'active', + 'service_status' => $id === 7 ? 'expired' : 'active', + 'expires_at' => $id === 7 ? $now - 1 : $now + 3600, + 'spec_json' => json_encode( + $spec, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + ), + 'sealed_credential' => null, + ]); + } + + $actor = [ + 'user_id' => 7, 'is_admin' => false, + 'is_super_admin' => false, 'can_manage' => false, + 'session_id' => str_repeat('c', 64), + ]; + $settingsRequest = static function (int $id) use ($actor): Request { + return Request::createFromEnvironment(Environment::mock([ + 'REQUEST_METHOD' => 'POST', + 'REQUEST_URI' => '/api/v1/instances/' . $id . '/settings', + ]))->withAttribute('cloud_actor', $actor)->withParsedBody([ + 'hostname' => 'canonical-host', 'confirm_restart' => true, + ]); + }; + $controller = new CloudApiController(); + $response = $controller->settings( + $settingsRequest(1), new Response(), ['id' => '1'] + ); + $payload = json_decode((string) $response->getBody(), true); + $assert($response->getStatusCode() === 202 + && ($payload['task_id'] ?? null) === '92' + && (UserSettingsJobCapture::$calls[0]['kind'] ?? null) + === 'instance_settings', + 'Canonical tenant settings request was not admitted.'); + + $before = count(UserSettingsJobCapture::$calls); + foreach ([2, 3, 4, 5, 6, 7] as $id) { + $rejects( + static fn () => $controller->settings( + $settingsRequest($id), new Response(), ['id' => (string) $id] + ), + 'Unsupported tenant instance ' . $id . ' admitted settings.' + ); + } + $assert(count(UserSettingsJobCapture::$calls) === $before, + 'Rejected tenant settings request queued a job.'); + + // Console admission is intentionally independent from cloud-template and + // canonical-network eligibility; a legacy instance must not regress here. + $consoleRequest = Request::createFromEnvironment(Environment::mock([ + 'REQUEST_METHOD' => 'POST', + 'REQUEST_URI' => '/api/v1/instances/2/console-ticket', + ]))->withAttribute('cloud_actor', $actor); + $consoleResponse = $controller->consoleTicket( + $consoleRequest, + new Response(), + ['id' => '2'] + ); + $consolePayload = json_decode((string) $consoleResponse->getBody(), true); + $assert($consoleResponse->getStatusCode() === 200 + && ($consolePayload['ticket'] ?? null) === 'browser-ticket', + 'Canonical settings guard leaked into the console endpoint.'); + + echo "Canonical tenant settings behavior passed.\n"; +} diff --git a/web/tests/TicketFrontendAssetsContractTest.php b/web/tests/TicketFrontendAssetsContractTest.php index 5cc1e13f..d8398970 100644 --- a/web/tests/TicketFrontendAssetsContractTest.php +++ b/web/tests/TicketFrontendAssetsContractTest.php @@ -94,7 +94,7 @@ $assert(!str_contains($adminHomeCss, '.admin-ticket-thread') && str_contains($adminTicketCss, '.admin-ticket-thread') && str_contains($adminTicketCss, '.admin-ticket-preview-remove'), 'Administrator ticket-only styles are not isolated, or shared legacy primitives were removed.'); -$assert(preg_match("/venix_asset_version value='2026110301'/", $assets) === 1, +$assert(preg_match("/venix_asset_version value='2026110302'/", $assets) === 1, 'Ticket asset extraction must advance the shared browser cache key.'); echo "Ticket frontend asset contract passed.\n"; diff --git a/web/tests/TicketWorkflowPolishContractTest.php b/web/tests/TicketWorkflowPolishContractTest.php index f4bb4d62..97807c57 100644 --- a/web/tests/TicketWorkflowPolishContractTest.php +++ b/web/tests/TicketWorkflowPolishContractTest.php @@ -52,7 +52,7 @@ $assert(str_contains($adminCss, '.admin-ticket-table td[data-label]::before') && str_contains($adminCss, ':focus-visible') && str_contains($adminCss, 'prefers-reduced-motion: reduce'), 'Administrator ticket cards, focus treatment or reduced-motion support is missing.'); -$assert(preg_match("/venix_asset_version value='2026110301'/", $assets) === 1, +$assert(preg_match("/venix_asset_version value='2026110302'/", $assets) === 1, 'Ticket workflow polish must advance the shared browser cache key.'); echo "Ticket workflow polish contract passed.\n";