From 46c5a7b51b1eb59ddf4e6b9393e02a2d76cdc9fe Mon Sep 17 00:00:00 2001 From: codex Date: Tue, 3 Nov 2026 15:14:45 +0800 Subject: [PATCH] feat: expose canonical dual-stack instance network --- web/app/Controllers/CloudApiController.php | 29 ++- web/app/Controllers/CloudPageController.php | 34 ++-- .../Cloud/CloudAdminInstanceService.php | 146 +++++++++++---- .../Cloud/CloudAdminVpcControlService.php | 16 +- .../Services/Cloud/CloudInstanceMetadata.php | 64 +++---- .../Cloud/CloudInstancePageService.php | 44 +++-- .../CloudInstancePublicNetworkProjection.php | 136 ++++++++++++++ web/app/Services/Cloud/CloudUserPageView.php | 1 + .../Cloud/CloudVpcMembershipBatchService.php | 4 +- .../Services/Cloud/CloudVpcPortService.php | 81 ++++++--- web/app/Services/Ticket/TicketReadModel.php | 30 ++-- web/public/cloud/admin-instance-detail.js | 7 +- web/public/cloud/admin-instance-directory.js | 28 ++- web/public/cloud/admin-vpc.js | 3 +- web/public/cloud/detail.js | 19 +- web/public/cloud/instances.js | 39 ++-- web/public/cloud/runtime.js | 46 +++-- web/public/cloud/styles.css | 4 +- web/public/cloud/vpcs.js | 12 +- web/public/theme/venix/css/admin-home.css | 13 ++ .../views/venix/admin/cloud/instances.tpl | 4 +- .../views/venix/admin/ticket/view.tpl | 2 +- .../views/venix/cloud/pages/detail.tpl | 5 +- .../views/venix/cloud/pages/instances.tpl | 4 +- .../views/venix/cloud/pages/vpcs.tpl | 1 + .../views/venix/user/ticket_view.tpl | 2 +- web/tests/AdminInstanceViewTest.php | 19 +- web/tests/CloudAdminInstanceServiceTest.php | 80 ++++++++- web/tests/CloudAdminVpcControlServiceTest.php | 22 ++- .../CloudDualStackInstanceUiContractTest.php | 86 +++++++++ web/tests/CloudInstanceMetadataTest.php | 45 ++++- web/tests/CloudInstancePageServiceTest.php | 77 ++++++++ .../CloudInstancePageSsrContractTest.php | 5 +- ...oudInstancePublicNetworkProjectionTest.php | 170 ++++++++++++++++++ web/tests/CloudLegacyVmApiProjectionTest.php | 119 ++++++++++++ web/tests/CloudOperationErrorCatalogTest.php | 22 ++- web/tests/CloudVpcPortWorkflowTest.php | 138 +++++++++++++- web/tests/TicketReadModelTest.php | 28 +-- 38 files changed, 1340 insertions(+), 245 deletions(-) create mode 100644 web/app/Services/Cloud/CloudInstancePublicNetworkProjection.php create mode 100644 web/tests/CloudDualStackInstanceUiContractTest.php create mode 100644 web/tests/CloudInstancePublicNetworkProjectionTest.php create mode 100644 web/tests/CloudLegacyVmApiProjectionTest.php diff --git a/web/app/Controllers/CloudApiController.php b/web/app/Controllers/CloudApiController.php index ea5c4751..d1dd5230 100644 --- a/web/app/Controllers/CloudApiController.php +++ b/web/app/Controllers/CloudApiController.php @@ -408,14 +408,18 @@ final class CloudApiController * this boundary adds only the explicitly public, UUID-checked power state * and the validated discovery timestamp needed by the detail view. */ - private function publicVmMetadata(CloudInstance $instance, array $live): array + private function publicVmMetadata( + CloudInstance $instance, + array $live, + array $publicSpec + ): array { - $snapshot = [ + $snapshot = array_merge($publicSpec, [ 'id' => (string) $instance->id, 'api_id' => (string) $instance->id, 'uuid' => (string) $instance->uuid, 'name' => (string) $instance->name, - ]; + ]); $view = CloudInstanceMetadata::publicView($snapshot, $live); $snapshotUuid = strtolower(trim((string) $snapshot['uuid'])); $liveUuid = is_string($live['uuid'] ?? null) @@ -611,8 +615,12 @@ final class CloudApiController $period = $context['period'] ?? null; $futurePeriods = max(0, (int) ($context['future_periods'] ?? 0)); } - $publicVm = $this->publicVmMetadata($instance, - is_array($vm) ? $vm : []); + $publicSpec = $this->publicVmSpec($spec); + $publicVm = $this->publicVmMetadata( + $instance, + is_array($vm) ? $vm : [], + $publicSpec + ); $createdAt = ($spec['record_source'] ?? '') === 'discovered' ? ($publicVm['created_at'] ?? null) : gmdate('Y-m-d\TH:i:s\Z', (int) $instance->created_at); @@ -623,7 +631,10 @@ final class CloudApiController // Traffic quota enforcement only disconnects guest NICs. It must not // remove power, console or maintenance controls while the paid service // period itself is still active. - $canOperate = $canDelete && $instance->serviceAvailable(); + $publicNetworkValid = + ($publicSpec['public_network_valid'] ?? false) === true; + $canOperate = $canDelete && $instance->serviceAvailable() + && $publicNetworkValid; $trafficAccounting = is_array($context['traffic_accounting'] ?? null) ? $context['traffic_accounting'] : CloudTrafficPoolReadModel::forPeriod( @@ -631,7 +642,7 @@ final class CloudApiController $period ); return array_merge( - $this->publicVmSpec($spec), + $publicSpec, $publicVm, ['id' => (string) $instance->id, 'uuid' => $instance->uuid, 'name' => (string) $instance->name, @@ -640,7 +651,9 @@ final class CloudApiController 'created_at' => $createdAt, 'instance_status' => (string) $instance->status, 'service_status' => (string) $instance->service_status, - 'network_status' => (string) $instance->network_status, + 'network_status' => $publicNetworkValid + ? (string) $instance->network_status + : 'configuration_invalid', 'service_expires_at' => $instance->expires_at === null ? null : (int) $instance->expires_at, 'current_period_started_at' => $period === null ? null : (int) $period->starts_at, 'current_period_ends_at' => $period === null ? null : (int) $period->ends_at, diff --git a/web/app/Controllers/CloudPageController.php b/web/app/Controllers/CloudPageController.php index 324b39d4..3ea09f92 100644 --- a/web/app/Controllers/CloudPageController.php +++ b/web/app/Controllers/CloudPageController.php @@ -549,13 +549,15 @@ final class CloudPageController private function reinstallVm(array $vm): array { $keys = [ - 'id', 'api_id', 'uuid', 'name', 'state', 'public_ip_cidr', 'public_ip', + 'id', 'api_id', 'uuid', 'name', 'state', + 'public_network_valid', 'public_network', + 'public_ipv4', 'public_ipv4_cidr', 'public_ipv6', 'public_ipv6_cidr', + 'public_ip_cidr', 'public_ip', 'instance_status', 'service_status', 'network_status', 'can_operate', 'can_delete', 'is_owner', ]; $result = array_intersect_key($vm, array_flip($keys)); - $address = trim((string) ($result['public_ip_cidr'] ?? $result['public_ip'] ?? '')); - $result['public_ip'] = $address === '' ? '' : (explode('/', $address, 2)[0] ?: ''); + $result['public_ip'] = $this->vmIp($vm, 4, ''); return $result; } @@ -577,8 +579,10 @@ final class CloudPageController 'region' => trim((string) ($vm['region'] ?? '')) ?: '未设置', 'system_label' => $systemLabel, 'system_value' => $systemValue, - 'ip' => $this->vmIp($vm), - 'has_ip' => $this->vmIp($vm) !== '未获取', + 'ipv4' => $this->vmIp($vm, 4), + 'ipv6' => $this->vmIp($vm, 6), + 'has_ipv4' => $this->vmIp($vm, 4) !== '未获取', + 'has_ipv6' => $this->vmIp($vm, 6) !== '未获取', 'vcpu' => isset($vm['vcpu']) ? (int) $vm['vcpu'] : (isset($vm['cpu_cores']) ? (int) $vm['cpu_cores'] : null), 'memory_mib' => isset($vm['memory_mib']) ? (int) $vm['memory_mib'] @@ -590,6 +594,9 @@ final class CloudPageController /** Presentation for the cached list state; operation controls stay live. */ private function vmListState(array $vm): array { + if ((string) ($vm['network_status'] ?? '') === 'configuration_invalid') { + return ['网络配置异常', 'other', '', '']; + } if ((bool) ($vm['service_paused'] ?? false)) { return ['已暂停', 'other', '', '']; } @@ -667,7 +674,10 @@ final class CloudPageController 'state_sync_label' => $stateSyncLabel, 'state_sync_class' => $stateSyncClass, 'region' => trim((string) ($vm['region'] ?? '')) ?: '未设置', - 'ip' => $this->vmIp($vm), + 'ipv4' => $this->vmIp($vm, 4), + 'ipv6' => $this->vmIp($vm, 6), + 'has_ipv4' => $this->vmIp($vm, 4) !== '未获取', + 'has_ipv6' => $this->vmIp($vm, 6) !== '未获取', 'created_display' => $this->createdAgo($vm['created_at'] ?? null), 'system_label' => $systemLabel, 'system_value' => $systemValue, @@ -787,13 +797,14 @@ final class CloudPageController return ['系统', $value !== '' ? $value : '未识别']; } - private function vmIp(array $vm): string + private function vmIp(array $vm, int $family, string $missing = '未获取'): string { - $value = trim((string) ($vm['public_ip_cidr'] ?? '')); - if ($value === '') { - $value = trim((string) ($vm['public_ip'] ?? '')); + if (($vm['public_network_valid'] ?? false) !== true) { + return $missing; } - return $value === '' ? '未获取' : (explode('/', $value, 2)[0] ?: '未获取'); + $key = $family === 6 ? 'public_ipv6' : 'public_ipv4'; + $value = trim((string) ($vm[$key] ?? '')); + return $value === '' ? $missing : $value; } private function vmDisk(array $vm): string @@ -864,6 +875,7 @@ final class CloudPageController 'restoring' => ['正在恢复网络', 'warning'], 'restore_pending' => ['等待恢复网络', 'warning'], 'restore_failed' => ['网络恢复失败,请联系管理员', 'stopped'], + 'configuration_invalid' => ['网络配置异常,请联系管理员', 'stopped'], 'exempt' => ['网络不受套餐限制', 'active'], ]; return $labels[strtolower(str_replace('-', '_', trim($value)))] diff --git a/web/app/Services/Cloud/CloudAdminInstanceService.php b/web/app/Services/Cloud/CloudAdminInstanceService.php index 0a9e1aef..26a47f47 100644 --- a/web/app/Services/Cloud/CloudAdminInstanceService.php +++ b/web/app/Services/Cloud/CloudAdminInstanceService.php @@ -30,6 +30,7 @@ final class CloudAdminInstanceService 'blocking_expired' => '到期断网中', 'blocked_expired' => '到期已断网', 'restore_pending' => '等待恢复网络', 'restoring' => '网络恢复中', 'restore_failed' => '网络恢复失败', + 'configuration_invalid' => '公网配置异常', ]; public static function page(array $actor, array $input = []): array @@ -39,22 +40,32 @@ final class CloudAdminInstanceService $now = time(); $query = self::baseQuery(); self::applyFilters($query, $filters, $now); + $networkAttentionIds = self::networkAttentionIds($query); + if ($filters['attention'] === 'network') { + if ($networkAttentionIds === []) { + $query->whereRaw('1 = 0'); + } else { + $query->whereIntegerInRaw( + 'cloud_instances.id', + $networkAttentionIds + ); + } + } $summary = (clone $query)->selectRaw( 'COUNT(*) AS total, ' . "COALESCE(SUM(CASE WHEN cloud_instances.status = 'active' " . "AND cloud_instances.service_status <> 'exempt' " . 'AND cloud_instances.expires_at > ? AND cloud_instances.expires_at <= ? ' . 'THEN 1 ELSE 0 END), 0) AS expiring, ' - . "COALESCE(SUM(CASE WHEN COALESCE(cloud_instances.network_status, '') <> 'active' " - . 'THEN 1 ELSE 0 END), 0) AS network_restricted, ' . 'COALESCE(SUM(CASE WHEN ' . self::attentionSql() . ' THEN 1 ELSE 0 END), 0) AS attention', [$now, $now + 7 * 86400, $now - 86400] )->first(); $counts = []; - foreach (['total', 'expiring', 'network_restricted', 'attention'] as $key) { + foreach (['total', 'expiring', 'attention'] as $key) { $counts[$key] = max(0, (int) ($summary?->$key ?? 0)); } + $counts['network_restricted'] = count($networkAttentionIds); $pages = max(1, (int) ceil($counts['total'] / $filters['per_page'])); $filters['page'] = min($filters['page'], $pages); if ($filters['sort'] === 'expiry') { @@ -148,31 +159,43 @@ final class CloudAdminInstanceService 'detail_url' => '/admin/billing?detail=' . $invoice->id]; } $row = self::row($instance, $actor, $active === null ? null : self::jobRow($active), $now); - $spec = self::spec($instance->spec_json); + $rawSpec = self::rawSpec($instance->spec_json); + $spec = CloudInstanceMetadata::publicSpec($rawSpec); $period = $instance->current_period_id === null ? null : CloudServicePeriod::where('id', $instance->current_period_id) ->where('instance_id', $instance->id)->first(['starts_at', 'ends_at']); - $dns = is_array($spec['dns_servers'] ?? null) ? $spec['dns_servers'] : []; - $dns = array_values(array_filter(array_slice($dns, 0, 8), - static fn ($value): bool => is_string($value) - && filter_var($value, FILTER_VALIDATE_IP) !== false)); - $publicIpCidr = self::text($spec['public_ip_cidr'] ?? null, 64); + $dns = is_array($spec['dns_servers'] ?? null) + ? $spec['dns_servers'] : []; + $publicIpCidr = self::text($spec['public_ipv4_cidr'] ?? null, 64); + $publicIpv6Cidr = self::text($spec['public_ipv6_cidr'] ?? null, 64); + $networkValid = ($spec['public_network_valid'] ?? false) === true; + $ipv4Gateway = self::ip($spec['public_network']['ipv4']['gateway'] ?? null); + $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'; $row += [ 'public_ip_cidr' => $publicIpCidr, - 'gateway' => self::ip($spec['gateway'] ?? null), 'dns_servers' => $dns, + 'public_ipv4' => self::ip($spec['public_ipv4'] ?? null) ?? '', + 'public_ipv4_cidr' => $publicIpCidr, + 'public_ipv6' => self::ip($spec['public_ipv6'] ?? null) ?? '', + 'public_ipv6_cidr' => $publicIpv6Cidr, + 'public_network_valid' => $networkValid, + 'public_network' => $spec['public_network'] ?? null, + 'gateway' => $ipv4Gateway, + 'ipv4_gateway' => $ipv4Gateway, + 'ipv6_gateway' => $ipv6Gateway, + 'dns_servers' => $dns, '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), 'network_change_supported' => $canMutate && $managedCloudTemplate - && $publicIpCidr !== null, + && $networkValid && $publicIpCidr !== null, 'instance_settings_supported' => $canMutate && $managedCloudTemplate - && ($publicIpCidr !== null || $row['public_ip'] !== ''), + && $networkValid, // The Agent can extend its UUID-derived name on collisions. Do // not invent that name from a UUID when it was never persisted. - 'agent_name' => self::resourceName($spec['agent_name'] ?? null), + 'agent_name' => self::resourceName($rawSpec['agent_name'] ?? null), 'current_period_started_at' => $period === null ? null : (int) $period->starts_at, 'current_period_ends_at' => $period === null ? null : (int) $period->ends_at, 'renewal_price' => $instance->renewal_price === null ? null : self::money($instance->renewal_price), @@ -274,27 +297,46 @@ final class CloudAdminInstanceService $query->where('cloud_instances.service_status', '<>', 'exempt') ->whereNotNull('cloud_instances.expires_at')->where('cloud_instances.expires_at', '<=', $now); } - if ($filters['attention'] === 'network') { - $query->whereRaw( - "COALESCE(cloud_instances.network_status, '') <> 'active'" - ); - } elseif ($filters['attention'] === 'jobs') { + if ($filters['attention'] === 'jobs') { $query->whereRaw(self::attentionSql(), [$now - 86400]); } if ($filters['q'] === '') { return; } $like = '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $filters['q']) . '%'; - $query->where(static function ($search) use ($filters, $like): void { + $ipQuery = strtolower($filters['q']); + $ipLike = '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $ipQuery) . '%'; + $packedIp = filter_var($ipQuery, FILTER_VALIDATE_IP) === false + ? false : inet_pton($ipQuery); + $exactIp = is_string($packedIp) ? inet_ntop($packedIp) : null; + $exactIp = is_string($exactIp) ? $exactIp : null; + $query->where(static function ($search) use ( + $filters, + $like, + $ipLike, + $exactIp + ): void { $search->whereRaw("cloud_instances.name LIKE ? ESCAPE '!'", [$like]) ->orWhereRaw("cloud_instances.uuid LIKE ? ESCAPE '!'", [$like]); - foreach (['public_ip_cidr', 'public_ip'] as $key) { - // CASE also permits searching databases containing a damaged - // old specification without calling JSON_EXTRACT on it. - $search->orWhereRaw("(CASE WHEN JSON_VALID(cloud_instances.spec_json) " - . "THEN JSON_EXTRACT(cloud_instances.spec_json, '$." . $key . "') " - . "ELSE '' END) LIKE ? ESCAPE '!'", [$like]); - } + $search->orWhereExists(static function ($addresses) use ( + $ipLike, + $exactIp + ): void { + $addresses->selectRaw('1') + ->from('cloud_public_ips as searched_public_ip') + ->whereColumn( + 'searched_public_ip.instance_id', + 'cloud_instances.id' + )->where('searched_public_ip.state', 'assigned'); + if ($exactIp !== null) { + $addresses->where('searched_public_ip.address', $exactIp); + } else { + $addresses->whereRaw( + "searched_public_ip.address LIKE ? ESCAPE '!'", + [$ipLike] + ); + } + }); if (preg_match('/^[1-9][0-9]*$/D', $filters['q']) === 1 && strlen($filters['q']) < 19) { $search->orWhere('cloud_instances.id', (int) $filters['q']) @@ -309,6 +351,33 @@ final class CloudAdminInstanceService }); } + /** + * Canonical PHP classification shared by summary, filtering and paging. + * The immutable public-network parser is deliberately not reimplemented + * with database-specific JSON expressions. + * + * @return list + */ + private static function networkAttentionIds($query): array + { + $ids = []; + $records = (clone $query)->get([ + 'cloud_instances.id', + 'cloud_instances.network_status', + 'cloud_instances.spec_json', + ]); + foreach ($records as $instance) { + $spec = CloudInstanceMetadata::publicSpec( + self::rawSpec($instance->spec_json) + ); + if ((string) $instance->network_status !== 'active' + || ($spec['public_network_valid'] ?? false) !== true) { + $ids[(int) $instance->id] = (int) $instance->id; + } + } + return array_values($ids); + } + private static function jobRelationSql(string $alias): string { return '(' . $alias . '.instance_id = cloud_instances.id OR (' . $alias @@ -411,8 +480,9 @@ final class CloudAdminInstanceService private static function row($instance, array $actor, ?array $job, int $now): array { $spec = self::spec($instance->spec_json); - $cidr = self::text($spec['public_ip_cidr'] ?? null, 64); - $publicIp = self::ip($cidr === null ? ($spec['public_ip'] ?? null) : explode('/', $cidr, 2)[0]); + $networkValid = ($spec['public_network_valid'] ?? false) === true; + $publicIpv4 = self::ip($spec['public_ipv4'] ?? null); + $publicIpv6 = self::ip($spec['public_ipv6'] ?? null); $service = (string) $instance->service_status; $expires = $instance->expires_at === null ? null : (int) $instance->expires_at; $used = max(0, (int) $instance->traffic_download_bytes) + max(0, (int) $instance->traffic_upload_bytes); @@ -431,18 +501,23 @@ final class CloudAdminInstanceService ?? self::text($instance->plan_name, 120) ?? '', 'os_name' => self::text($spec['os_name'] ?? $spec['install_iso'] ?? null, 255) ?? '', 'guest_hostname' => self::hostname($spec['guest_hostname'] ?? $spec['hostname'] ?? null), - 'public_ip' => $publicIp ?? '', + 'public_ip' => $publicIpv4 ?? '', + 'public_ipv4' => $publicIpv4 ?? '', + 'public_ipv6' => $publicIpv6 ?? '', + 'public_network_valid' => $networkValid, 'vcpu' => self::positiveOrNull($spec['vcpu'] ?? null), 'memory_mib' => self::positiveOrNull($spec['memory_mib'] ?? null), 'disk_gib' => self::positiveOrNull($spec['disk_gib'] ?? null), 'instance_status' => (string) $instance->status, 'service_status' => $service, - 'network_status' => (string) $instance->network_status, 'service_expires_at' => $expires, + 'network_status' => $networkValid + ? (string) $instance->network_status : 'configuration_invalid', + 'service_expires_at' => $expires, 'traffic_used_bytes' => $used, 'traffic_quota_bytes' => $quota, 'traffic_synced_at' => max(0, (int) $instance->traffic_synced_at), 'created_at' => max(0, (int) $instance->created_at), 'active_job' => $job, 'state' => 'unknown', 'can_manage' => ($actor['is_admin'] ?? false) && ($actor['is_super_admin'] ?? false) - && ($actor['can_manage'] ?? false), + && ($actor['can_manage'] ?? false) && $networkValid, 'detail_url' => '/user/cloud/instances/' . $instance->id, ]; $row['display'] = [ @@ -456,7 +531,7 @@ final class CloudAdminInstanceService 'service' => $service === 'active' && $expires === null ? '期限未记录' : ($service === 'active' && $expires <= $now ? '已到期' : (self::SERVICE_LABELS[$service] ?? '未知')), - 'network' => self::NETWORK_LABELS[(string) $instance->network_status] ?? '未知', + 'network' => self::NETWORK_LABELS[$row['network_status']] ?? '未知', 'lifecycle' => ['active' => '在管', 'deleting' => '删除中', 'delete_failed' => '删除失败'] [(string) $instance->status] ?? '未知', ]; @@ -464,9 +539,14 @@ final class CloudAdminInstanceService } private static function spec($json): array + { + return CloudInstanceMetadata::publicSpec(self::rawSpec($json)); + } + + private static function rawSpec($json): array { $value = json_decode((string) $json, true); - return CloudInstanceMetadata::sanitizeSpec(is_array($value) && !array_is_list($value) ? $value : []); + return is_array($value) && !array_is_list($value) ? $value : []; } private static function positiveInteger(string $value, string $label): int diff --git a/web/app/Services/Cloud/CloudAdminVpcControlService.php b/web/app/Services/Cloud/CloudAdminVpcControlService.php index 9c22942c..e3ffe80c 100644 --- a/web/app/Services/Cloud/CloudAdminVpcControlService.php +++ b/web/app/Services/Cloud/CloudAdminVpcControlService.php @@ -169,10 +169,10 @@ final class CloudAdminVpcControlService ])->map(static function ($port): array { $spec = json_decode((string) ($port->instance_spec_json ?? ''), true); - $public = is_array($spec) - ? (string) ($spec['public_ip'] - ?? explode('/', (string) ($spec['public_ip_cidr'] ?? ''), - 2)[0]) : ''; + $public = CloudInstanceMetadata::publicSpec( + is_array($spec) && !array_is_list($spec) ? $spec : [] + ); + $networkValid = ($public['public_network_valid'] ?? false) === true; return [ 'id' => (int) $port->id, 'instance_id' => (int) $port->instance_id, @@ -182,7 +182,13 @@ final class CloudAdminVpcControlService ?? $port->current_host_id ?? 0), 'host_name' => (string) ($port->migration_host_name ?? $port->host_name ?? ''), - 'public_ip' => $public, + 'public_ip' => $networkValid + ? (string) ($public['public_ipv4'] ?? '') : '', + 'public_ipv4' => $networkValid + ? (string) ($public['public_ipv4'] ?? '') : '', + 'public_ipv6' => $networkValid + ? (string) ($public['public_ipv6'] ?? '') : '', + 'public_network_valid' => $networkValid, 'private_ip' => (string) $port->private_ip, 'mac_address' => (string) $port->mac_address, 'state' => (string) $port->state, diff --git a/web/app/Services/Cloud/CloudInstanceMetadata.php b/web/app/Services/Cloud/CloudInstanceMetadata.php index 13a17fc4..9bbf728b 100644 --- a/web/app/Services/Cloud/CloudInstanceMetadata.php +++ b/web/app/Services/Cloud/CloudInstanceMetadata.php @@ -17,9 +17,12 @@ final class CloudInstanceMetadata private const VERSION = 1; private const STATIC_KEYS = [ 'vcpu', 'memory_mib', 'disk_gib', 'disks', 'autostart', 'managed', - 'public_ip_cidr', 'os_source', 'os_name', 'install_iso', 'login_name', + 'os_source', 'os_name', 'install_iso', 'login_name', 'agent_metadata_version', ]; + private const LEGACY_PUBLIC_NETWORK_KEYS = [ + 'public_ip', 'public_ip_cidr', 'gateway', 'dns_servers', + ]; private const FORBIDDEN_AGENT_KEYS = [ 'state', 'hostname', 'console_port', 'credential_generation', 'rescue_mode', 'rescue_staged', 'rescue_volume_name', 'auth_mode', @@ -33,7 +36,10 @@ final class CloudInstanceMetadata */ private const PUBLIC_SPEC_KEYS = [ 'region', 'location', 'country_code', 'plan_name', 'os_source', - 'os_name', 'install_iso', 'guest_hostname', 'public_ip', 'public_ip_cidr', 'login_name', + 'os_name', 'install_iso', 'guest_hostname', 'login_name', + 'public_network_valid', 'public_network', + 'public_ipv4', 'public_ipv4_cidr', 'public_ipv6', 'public_ipv6_cidr', + 'public_ip', 'public_ip_cidr', 'gateway', 'dns_servers', 'vcpu', 'cpu_cores', 'memory_mib', 'ram_mib', 'disks', 'disk_gib', 'bandwidth_mbps', 'autostart', 'managed', 'agent_metadata_version', @@ -68,7 +74,11 @@ final class CloudInstanceMetadata $existing = self::metadata($spec); $version = self::integer($spec['agent_metadata_version'] ?? null, 1, self::VERSION); - foreach (array_merge(self::STATIC_KEYS, self::FORBIDDEN_AGENT_KEYS) as $key) { + foreach (array_merge( + self::STATIC_KEYS, + self::FORBIDDEN_AGENT_KEYS, + self::LEGACY_PUBLIC_NETWORK_KEYS + ) as $key) { unset($spec[$key]); } $spec = array_merge($spec, $existing); @@ -129,14 +139,10 @@ final class CloudInstanceMetadata $public['guest_hostname'] = $hostname; } - $ip = self::ip($safe['public_ip'] ?? null); - if ($ip !== null) { - $public['public_ip'] = $ip; - } - $cidr = self::cidr($safe['public_ip_cidr'] ?? null); - if ($cidr !== null) { - $public['public_ip_cidr'] = $cidr; - } + $public = array_merge( + $public, + CloudInstancePublicNetworkProjection::fromSpec($safe) + ); foreach (['vcpu' => [1, 64], 'cpu_cores' => [1, 64], 'memory_mib' => [1, 262144], 'ram_mib' => [1, 262144], @@ -196,6 +202,7 @@ final class CloudInstanceMetadata public static function publicView(array $snapshot, array $live): array { $view = self::identity($snapshot); + $view = array_merge($view, self::networkProjection($snapshot)); $view = array_merge($view, self::metadata($snapshot)); if (self::sameUuid($snapshot['uuid'] ?? null, $live['uuid'] ?? null)) { $metadata = self::metadata($live); @@ -207,6 +214,12 @@ final class CloudInstanceMetadata return $view; } + /** Copy only the browser-safe projection previously produced by publicSpec(). */ + private static function networkProjection(array $snapshot): array + { + return CloudInstancePublicNetworkProjection::fromProjection($snapshot); + } + /** * Persist Agent metadata for only the caller-provided, actor-visible rows. * @@ -329,10 +342,6 @@ final class CloudInstanceMetadata } } - $cidr = self::cidr($value['public_ip_cidr'] ?? null); - if ($cidr !== null) { - $result['public_ip_cidr'] = $cidr; - } $source = $value['os_source'] ?? null; if (is_string($source) && in_array($source, ['cloud_template', 'iso', 'unknown'], true)) { @@ -407,31 +416,6 @@ final class CloudInstanceMetadata return $value >= $minimum && $value <= $maximum ? $value : null; } - private static function cidr($value): ?string - { - if (!is_string($value) || strlen($value) > 64 || trim($value) !== $value) { - return null; - } - $parts = explode('/', $value, 2); - if (count($parts) !== 2 || filter_var($parts[0], FILTER_VALIDATE_IP) === false - || preg_match('/^[0-9]{1,3}$/D', $parts[1]) !== 1) { - return null; - } - $maximum = filter_var($parts[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) - !== false ? 32 : 128; - $prefix = (int) $parts[1]; - return $prefix <= $maximum ? $parts[0] . '/' . $prefix : null; - } - - private static function ip($value): ?string - { - if (!is_string($value) || trim($value) !== $value - || filter_var($value, FILTER_VALIDATE_IP) === false) { - return null; - } - return $value; - } - private static function hostname($value): ?string { if (!is_string($value)) { diff --git a/web/app/Services/Cloud/CloudInstancePageService.php b/web/app/Services/Cloud/CloudInstancePageService.php index 692cbcbc..592e0484 100644 --- a/web/app/Services/Cloud/CloudInstancePageService.php +++ b/web/app/Services/Cloud/CloudInstancePageService.php @@ -72,7 +72,7 @@ final class CloudInstancePageService 'id', 'uuid', 'host_id', 'user_id', 'current_period_id', 'name', 'status', 'service_status', 'network_status', 'expires_at', 'traffic_quota_bytes', 'traffic_download_bytes', - 'traffic_upload_bytes', + 'traffic_upload_bytes', 'spec_json', ]); if ($instance === null) { throw new CloudError('虚拟机不存在或无权访问', 404); @@ -97,6 +97,11 @@ final class CloudInstancePageService && ($actor['can_manage'] ?? false); $lifecycleActive = (string) $instance->status === 'active'; $canDelete = $lifecycleActive && ($owner || $global); + $decoded = json_decode((string) $instance->spec_json, true); + $publicNetwork = CloudInstanceMetadata::publicSpec( + is_array($decoded) && !array_is_list($decoded) ? $decoded : [] + ); + $publicNetworkValid = ($publicNetwork['public_network_valid'] ?? false) === true; $download = max(0, (int) $instance->traffic_download_bytes); $upload = max(0, (int) $instance->traffic_upload_bytes); $used = $download + $upload; @@ -140,7 +145,8 @@ final class CloudInstancePageService 'state_label_hint' => $runtimeHint, 'instance_status' => (string) $instance->status, 'service_status' => (string) $instance->service_status, - 'network_status' => (string) $instance->network_status, + 'network_status' => $publicNetworkValid + ? (string) $instance->network_status : 'configuration_invalid', 'service_expires_at' => $instance->expires_at === null ? null : (int) $instance->expires_at, 'service_paused' => self::servicePaused( @@ -155,7 +161,8 @@ final class CloudInstancePageService 'traffic_quota_bytes' => $quota, 'traffic_remaining_bytes' => $quota === 0 ? 0 : max(0, $quota - $used), 'is_owner' => $owner, - 'can_operate' => $canDelete && $instance->serviceAvailable(), + 'can_operate' => $canDelete && $instance->serviceAvailable() + && $publicNetworkValid, 'can_delete' => $canDelete, 'can_rename' => $canDelete, ], $trafficAccounting, self::transitionProjection( @@ -188,6 +195,7 @@ final class CloudInstancePageService ->whereIn('id', array_keys($ordered)) ->get([ 'id', 'uuid', 'host_id', 'name', 'service_status', 'expires_at', + 'spec_json', ]); $transitions = self::operationTransitions($records); $runtime = []; @@ -203,6 +211,10 @@ final class CloudInstancePageService } $vms = []; foreach ($records as $instance) { + $decoded = json_decode((string) $instance->spec_json, true); + $publicNetwork = CloudInstanceMetadata::publicSpec( + is_array($decoded) && !array_is_list($decoded) ? $decoded : [] + ); $cached = $runtime[(string) $instance->id] ?? [ 'state' => 'unknown', 'state_transitioning' => false, @@ -212,7 +224,7 @@ final class CloudInstancePageService 'state_sync_status' => 'pending', 'state_label_hint' => '等待宿主机同步', ]; - $vms[] = [ + $vms[] = array_merge($publicNetwork, [ 'id' => (string) $instance->id, 'api_id' => (string) $instance->id, 'uuid' => (string) $instance->uuid, @@ -228,11 +240,11 @@ final class CloudInstancePageService $transitions[(int) $instance->id]['transition'] ?? null, 'shutdown_convergence_until' => $transitions[(int) $instance->id]['shutdown_until'] ?? null, - ] + array_intersect_key($cached, array_flip([ + ], array_intersect_key($cached, array_flip([ 'state', 'state_transitioning', 'state_transition', 'state_fresh', 'state_observed_at', 'state_sync_status', 'state_label_hint', - ])); + ]))); } usort($vms, static fn (array $left, array $right): int => ($ordered[(int) $left['id']] ?? PHP_INT_MAX) @@ -485,8 +497,12 @@ final class CloudInstancePageService 'operation_transition', 'shutdown_convergence_until', 'state_observed_at', 'state_sync_status', 'state_label_hint', 'instance_status', 'service_status', + 'network_status', 'service_expires_at', 'service_paused', - 'os_source', 'os_name', 'install_iso', 'public_ip_cidr', 'public_ip', + 'os_source', 'os_name', 'install_iso', + 'public_network_valid', 'public_network', + 'public_ipv4', 'public_ipv4_cidr', 'public_ipv6', 'public_ipv6_cidr', + 'public_ip_cidr', 'public_ip', 'login_name', 'agent_metadata_version', 'vcpu', 'cpu_cores', 'memory_mib', 'ram_mib', 'disks', 'disk_gib', ]; @@ -529,6 +545,8 @@ final class CloudInstancePageService 'name' => (string) $instance->name, 'instance_status' => (string) $instance->status, 'service_status' => (string) $instance->service_status, + 'network_status' => ($spec['public_network_valid'] ?? false) === true + ? (string) $instance->network_status : 'configuration_invalid', 'service_expires_at' => $instance->expires_at === null ? null : (int) $instance->expires_at, 'service_paused' => self::servicePaused( @@ -687,7 +705,9 @@ final class CloudInstancePageService && ($actor['can_manage'] ?? false); $lifecycleActive = (string) $instance->status === 'active'; $canDelete = $lifecycleActive && ($owner || $global); - $canOperate = $canDelete && $instance->serviceAvailable(); + $publicNetworkValid = ($spec['public_network_valid'] ?? false) === true; + $canOperate = $canDelete && $instance->serviceAvailable() + && $publicNetworkValid; $quota = max(0, (int) $instance->traffic_quota_bytes); $download = max(0, (int) $instance->traffic_download_bytes); $upload = max(0, (int) $instance->traffic_upload_bytes); @@ -744,7 +764,8 @@ final class CloudInstancePageService 'created_at' => $createdAt, 'instance_status' => (string) $instance->status, 'service_status' => (string) $instance->service_status, - 'network_status' => (string) $instance->network_status, + 'network_status' => $publicNetworkValid + ? (string) $instance->network_status : 'configuration_invalid', 'service_expires_at' => $instance->expires_at === null ? null : (int) $instance->expires_at, 'service_paused' => self::servicePaused( @@ -816,7 +837,7 @@ final class CloudInstancePageService { return [ 'id', 'uuid', 'host_id', 'name', 'status', 'service_status', - 'expires_at', 'spec_json', + 'network_status', 'expires_at', 'spec_json', ]; } @@ -851,7 +872,8 @@ final class CloudInstancePageService /** Do not count a cached state as running/stopped while its host is offline. */ private static function listStateCategory(array $vm): string { - if ((bool) ($vm['service_paused'] ?? false) + if ((string) ($vm['network_status'] ?? '') === 'configuration_invalid' + || (bool) ($vm['service_paused'] ?? false) || (bool) ($vm['state_transitioning'] ?? false)) { return 'other'; } diff --git a/web/app/Services/Cloud/CloudInstancePublicNetworkProjection.php b/web/app/Services/Cloud/CloudInstancePublicNetworkProjection.php new file mode 100644 index 00000000..9a8a9cdc --- /dev/null +++ b/web/app/Services/Cloud/CloudInstancePublicNetworkProjection.php @@ -0,0 +1,136 @@ +toArray(); + } catch (\InvalidArgumentException) { + return self::invalid(); + } + + $ipv4 = self::leg($snapshot['ipv4']); + $ipv6 = self::leg($snapshot['ipv6']); + $network = [ + 'contract' => 1, + 'network_selector' => $snapshot['network_selector'], + 'ipv4' => $ipv4, + 'ipv6' => $ipv6, + 'dns_servers' => $snapshot['dns_servers'], + ]; + + return [ + 'public_network_valid' => true, + 'public_network' => $network, + 'public_ipv4' => $ipv4['address'], + 'public_ipv4_cidr' => $ipv4['address_cidr'], + 'public_ipv6' => $ipv6['address'], + 'public_ipv6_cidr' => $ipv6['address_cidr'], + // Compatibility aliases remain derived from the immutable + // snapshot while IPv4-only mutation paths are retired in C10. + 'public_ip' => $ipv4['address'], + 'public_ip_cidr' => $ipv4['address_cidr'], + 'gateway' => $ipv4['gateway'], + 'dns_servers' => $network['dns_servers'], + ]; + } + + /** + * Re-validate a browser-safe projection before a cached snapshot is + * decorated with live Agent metadata. Aliases are always re-derived from + * the nested network object, never copied from the caller. + */ + public static function fromProjection(array $projection): array + { + if (!array_key_exists('public_network_valid', $projection)) { + return []; + } + if ($projection['public_network_valid'] !== true) { + return self::invalid(); + } + + $network = $projection['public_network'] ?? null; + if (!is_array($network) || array_is_list($network) + || !self::exactKeys($network, [ + 'contract', 'network_selector', 'ipv4', 'ipv6', + 'dns_servers', + ])) { + return self::invalid(); + } + + $raw = [ + 'contract' => $network['contract'] ?? null, + 'network_selector' => $network['network_selector'] ?? null, + 'ipv4' => self::rawLeg($network['ipv4'] ?? null, + str_repeat('1', 32)), + 'ipv6' => self::rawLeg($network['ipv6'] ?? null, + str_repeat('2', 32)), + 'dns_servers' => $network['dns_servers'] ?? null, + ]; + if ($raw['ipv4'] === null || $raw['ipv6'] === null) { + return self::invalid(); + } + $result = self::fromSpec(['public_network' => $raw]); + return ($result['public_network_valid'] ?? false) === true + && ($result['public_network'] ?? null) === $network + ? $result + : self::invalid(); + } + + private static function leg(array $leg): array + { + return [ + 'address_cidr' => $leg['address_cidr'], + 'address' => explode('/', $leg['address_cidr'], 2)[0], + 'pool_cidr' => $leg['pool_cidr'], + 'gateway' => $leg['gateway'], + 'gateway_on_link' => $leg['gateway_on_link'], + ]; + } + + private static function rawLeg(mixed $leg, string $poolKey): ?array + { + if (!is_array($leg) || array_is_list($leg) + || !self::exactKeys($leg, [ + 'address_cidr', 'address', 'pool_cidr', 'gateway', + 'gateway_on_link', + ])) { + return null; + } + return [ + 'pool_key' => $poolKey, + 'pool_cidr' => $leg['pool_cidr'] ?? null, + 'address_cidr' => $leg['address_cidr'] ?? null, + 'gateway' => $leg['gateway'] ?? null, + 'gateway_on_link' => $leg['gateway_on_link'] ?? null, + ]; + } + + private static function exactKeys(array $value, array $expected): bool + { + $actual = array_keys($value); + sort($actual, SORT_STRING); + sort($expected, SORT_STRING); + return $actual === $expected; + } + + private static function invalid(): array + { + return [ + 'public_network_valid' => false, + 'public_network' => null, + ]; + } +} diff --git a/web/app/Services/Cloud/CloudUserPageView.php b/web/app/Services/Cloud/CloudUserPageView.php index 4ec36304..dda6ae12 100644 --- a/web/app/Services/Cloud/CloudUserPageView.php +++ b/web/app/Services/Cloud/CloudUserPageView.php @@ -289,6 +289,7 @@ final class CloudUserPageView $instance['state_label'] = $label; $instance['state_class'] = $class; $instance['public_ipv4'] = self::text($instance['public_ipv4'] ?? '', '未分配'); + $instance['public_ipv6'] = self::text($instance['public_ipv6'] ?? '', '未分配'); if ($joined) $members[] = $instance; else $candidates[] = $instance; } return [ diff --git a/web/app/Services/Cloud/CloudVpcMembershipBatchService.php b/web/app/Services/Cloud/CloudVpcMembershipBatchService.php index d1515333..30dadcf4 100644 --- a/web/app/Services/Cloud/CloudVpcMembershipBatchService.php +++ b/web/app/Services/Cloud/CloudVpcMembershipBatchService.php @@ -97,7 +97,9 @@ final class CloudVpcMembershipBatchService foreach ($instanceIds as $instanceId) { $instance = $instances->get($instanceId); CloudVpcPortService::assertBatchInstanceLocked( - $instance, $actor + $instance, + $actor, + $action === 'attach' ); if (CloudVpcPortService::batchInstanceRegionId($instance) !== (int) $vpc->region_id) { diff --git a/web/app/Services/Cloud/CloudVpcPortService.php b/web/app/Services/Cloud/CloudVpcPortService.php index 756cf587..af84679f 100644 --- a/web/app/Services/Cloud/CloudVpcPortService.php +++ b/web/app/Services/Cloud/CloudVpcPortService.php @@ -225,6 +225,14 @@ final class CloudVpcPortService array $actor): array { self::assertOwnerAndInstance($instance, $actor, false); + $decoded = json_decode((string) $instance->spec_json, true); + $publicSpec = CloudInstanceMetadata::publicSpec( + is_array($decoded) && !array_is_list($decoded) ? $decoded : [] + ); + $networkValid = + ($publicSpec['public_network_valid'] ?? false) === true; + $supported = $networkValid + && ($publicSpec['os_source'] ?? null) === 'cloud_template'; $regionId = self::instanceRegionId($instance); $port = CloudVpcPort::query() ->where('instance_id', (int) $instance->id) @@ -249,7 +257,9 @@ final class CloudVpcPortService 'state' => (string) $vpc->state, 'revision' => (int) $vpc->desired_revision, ])->all(), + 'public_network_valid' => $networkValid, 'can_attach' => $port === null && $blocking === null + && $supported && (string) $instance->status === 'active' && $instance->serviceAvailable(), 'can_detach' => $port !== null && $blocking === null @@ -257,6 +267,7 @@ final class CloudVpcPortService && (string) $instance->status === 'active' && $instance->serviceAvailable(), 'can_retry_attach' => $port !== null && $blocking === null + && $supported && (string) $port->state === 'preparing' && (string) $instance->status === 'active' && $instance->serviceAvailable(), @@ -327,22 +338,17 @@ final class CloudVpcPortService $result = []; foreach ($instances as $instance) { $port = $ports->get((int) $instance->id); - $spec = json_decode((string) $instance->spec_json, true); - $supported = is_array($spec) && !array_is_list($spec) + $decoded = json_decode((string) $instance->spec_json, true); + $spec = CloudInstanceMetadata::publicSpec( + is_array($decoded) && !array_is_list($decoded) ? $decoded : [] + ); + $networkValid = ($spec['public_network_valid'] ?? false) === true; + $supported = $networkValid && ($spec['os_source'] ?? null) === 'cloud_template'; - $publicIpv4 = ''; - if (is_array($spec) && !array_is_list($spec)) { - foreach (['public_ip_cidr', 'public_ip'] as $field) { - $candidate = explode('/', trim((string) ( - $spec[$field] ?? '' - )), 2)[0]; - if (filter_var($candidate, FILTER_VALIDATE_IP, - FILTER_FLAG_IPV4) !== false) { - $publicIpv4 = $candidate; - break; - } - } - } + $publicIpv4 = $networkValid + ? (string) ($spec['public_ipv4'] ?? '') : ''; + $publicIpv6 = $networkValid + ? (string) ($spec['public_ipv6'] ?? '') : ''; // Keep a historical attached port visible for status and // diagnosis even if its immutable source metadata is damaged. if (!$supported && $port === null) { @@ -366,7 +372,11 @@ final class CloudVpcPortService && $instance->serviceAvailable(); $portState = $port === null ? '' : (string) $port->state; $reason = ''; - if (!$supported) { + if (!$networkValid) { + $reason = $port === null + ? '实例公网配置异常,暂不能加入 VPC 私网' + : '实例公网配置异常,仅允许移出 VPC 私网'; + } elseif (!$supported) { $reason = '该实例的系统来源不支持 VPC 私网网卡'; } elseif (!$serviceAvailable) { $reason = '实例服务已到期或当前不可修改'; @@ -381,6 +391,8 @@ final class CloudVpcPortService 'name' => (string) $instance->name, 'region_id' => $regionId, 'public_ipv4' => $publicIpv4, + 'public_ipv6' => $publicIpv6, + 'public_network_valid' => $networkValid, 'instance_status' => (string) $instance->status, 'service_status' => (string) $instance->service_status, 'network_status' => (string) $instance->network_status, @@ -388,13 +400,13 @@ final class CloudVpcPortService 'can_attach' => $port === null && $blocking === null && $supported && $regionId > 0 && $serviceAvailable, 'can_detach' => $port !== null && $blocking === null - && $supported && $portState === 'attached' + && $portState === 'attached' && $serviceAvailable, 'can_retry_attach' => $port !== null && $blocking === null && $supported && $portState === 'preparing' && $serviceAvailable, 'can_retry_detach' => $port !== null && $blocking === null - && $supported && $portState === 'release_pending' + && $portState === 'release_pending' && $serviceAvailable, 'operation_blocked' => $blocking !== null, 'action_unavailable_reason' => $reason, @@ -427,6 +439,7 @@ final class CloudVpcPortService ): array { $locked = CloudVpcLockOrder::instance((int) $instance->id); self::assertOwnerAndInstance($locked, $actor, true); + self::assertPublicNetworkSnapshot($locked); $vpc = CloudVpcLockOrder::vpcByKey($vpcKey); if ($vpc === null || (int) $vpc->user_id !== (int) $locked->user_id || $vpc->active_claim === null) { @@ -2039,6 +2052,7 @@ final class CloudVpcPortService self::assertOwnerAndInstance($instance, [ 'user_id' => (int) $vpc->user_id, ], true); + self::assertPublicNetworkSnapshot($instance); if (self::instanceRegionId($instance) !== (int) $vpc->region_id) { throw new CloudError('实例只能加入同一地区的 VPC', 409); } @@ -2071,9 +2085,13 @@ final class CloudVpcPortService public static function assertBatchInstanceLocked( CloudInstance $instance, - array $actor + array $actor, + bool $requirePublicNetwork = false ): void { self::assertOwnerAndInstance($instance, $actor, true); + if ($requirePublicNetwork) { + self::assertPublicNetworkSnapshot($instance); + } self::assertNoInstanceJobLocked($instance); } @@ -2437,11 +2455,30 @@ final class CloudVpcPortService || !$instance->serviceAvailable())) { throw new CloudError('实例服务已到期或正在执行策略,不能修改 VPC', 409); } - $spec = json_decode((string) $instance->spec_json, true); - if (!is_array($spec) || array_is_list($spec) - || ($spec['os_source'] ?? null) !== 'cloud_template') { + } + + /** + * A new private NIC may only be attached to an instance whose immutable + * dual-stack public identity still passes the canonical snapshot parser. + * Detach deliberately does not call this guard: damaged metadata must + * never trap an already-attached VPC port or its private address claim. + */ + private static function assertPublicNetworkSnapshot( + CloudInstance $instance + ): void { + $decoded = json_decode((string) $instance->spec_json, true); + $spec = CloudInstanceMetadata::publicSpec( + is_array($decoded) && !array_is_list($decoded) ? $decoded : [] + ); + if (($spec['os_source'] ?? null) !== 'cloud_template') { throw new CloudError('当前实例不支持 VPC 私网网卡', 409); } + if (($spec['public_network_valid'] ?? false) !== true) { + throw new CloudError( + '实例公网配置异常,暂不能修改 VPC 私网', + 409 + ); + } } private static function instanceRegionId(CloudInstance $instance): int diff --git a/web/app/Services/Ticket/TicketReadModel.php b/web/app/Services/Ticket/TicketReadModel.php index 3e2c8c7c..f4e85769 100644 --- a/web/app/Services/Ticket/TicketReadModel.php +++ b/web/app/Services/Ticket/TicketReadModel.php @@ -3,11 +3,11 @@ namespace App\Services\Ticket; use App\Models\CloudInstance; -use App\Models\CloudPublicIp; use App\Models\Ticket; use App\Models\TicketAttachment; use App\Models\User; use App\Services\AdminDataMasker; +use App\Services\Cloud\CloudInstanceMetadata; /** * Builds ticket queues and threads in a fixed number of queries. @@ -186,27 +186,31 @@ final class TicketReadModel $instance = CloudInstance::where('id', $instanceId) ->where('user_id', (int) $root->userid) ->where('status', '<>', 'deleted') - ->first(['id', 'name']); + ->first(['id', 'name', 'spec_json']); if ($instance === null) { return null; } - $publicIp = ''; - foreach (CloudPublicIp::where('instance_id', $instanceId) - ->where('state', 'assigned')->orderBy('id')->pluck('address') as $address) { - if (filter_var((string) $address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { - $publicIp = (string) $address; - break; - } - } - if ($viewer->isAdmin && !$viewer->isSuperAdmin && $publicIp !== '') { - $publicIp = AdminDataMasker::ip($publicIp); + $decoded = json_decode((string) $instance->spec_json, true); + $network = CloudInstanceMetadata::publicSpec( + is_array($decoded) && !array_is_list($decoded) ? $decoded : [] + ); + $publicIpv4 = ($network['public_network_valid'] ?? false) === true + ? (string) ($network['public_ipv4'] ?? '') : ''; + $publicIpv6 = ($network['public_network_valid'] ?? false) === true + ? (string) ($network['public_ipv6'] ?? '') : ''; + if ($viewer->isAdmin && !$viewer->isSuperAdmin) { + $publicIpv4 = $publicIpv4 === '' ? '' + : AdminDataMasker::ip($publicIpv4); + $publicIpv6 = $publicIpv6 === '' ? '' + : AdminDataMasker::ip($publicIpv6); } return (object) [ 'id' => (int) $instance->id, 'name' => (string) $instance->name, - 'public_ipv4' => $publicIp, + 'public_ipv4' => $publicIpv4, + 'public_ipv6' => $publicIpv6, 'detail_url' => $viewer->isAdmin ? '/admin/cloud/instances?q=' . (int) $instance->id : '/user/cloud/instances/' . (int) $instance->id, diff --git a/web/public/cloud/admin-instance-detail.js b/web/public/cloud/admin-instance-detail.js index 351f0f35..b493a6b2 100644 --- a/web/public/cloud/admin-instance-detail.js +++ b/web/public/cloud/admin-instance-detail.js @@ -126,7 +126,10 @@ export function createAdminInstanceDetail({ ['生命周期', vm.display?.lifecycle], ['所属用户', text(vm.user_name, `用户 #${vm.user_id}`)], ['用户 ID', vm.user_id], ['宿主机', text(vm.host_name)], ['地区', text(vm.region, '未记录')], ['操作系统', text(vm.os_name, '未记录')], ['配置', vm.display?.configuration], - ['公网地址', text(vm.public_ip_cidr, vm.public_ip, '未记录')], ['网关', text(vm.gateway, '未记录')], + ['公网 IPv4', text(vm.public_ipv4_cidr, vm.public_ipv4, '未记录')], + ['IPv4 网关', text(vm.ipv4_gateway, '未记录')], + ['公网 IPv6', text(vm.public_ipv6_cidr, vm.public_ipv6, '未记录')], + ['IPv6 网关', text(vm.ipv6_gateway, '未记录')], ['DNS', Array.isArray(vm.dns_servers) ? text(vm.dns_servers.join('、'), '未记录') : text(vm.dns_servers, '未记录')], ['带宽上限', vm.bandwidth_mbps ? `${vm.bandwidth_mbps} Mbps` : '未记录'], ['创建时间', date(vm.created_at)], @@ -182,7 +185,7 @@ export function createAdminInstanceDetail({ if (link instanceof HTMLAnchorElement) { control.href = link.href; control.hidden = false; } } onPublicIpChange?.(vm.id, - vm.public_ip || String(vm.public_ip_cidr || '').split('/', 1)[0], vm.public_ip_cidr); + vm.public_ipv4, vm.public_ipv4_cidr); } async function refresh(id = state.id) { diff --git a/web/public/cloud/admin-instance-directory.js b/web/public/cloud/admin-instance-directory.js index c7032e31..ce65a5be 100644 --- a/web/public/cloud/admin-instance-directory.js +++ b/web/public/cloud/admin-instance-directory.js @@ -116,9 +116,15 @@ export function createAdminInstanceDirectory({ function row(vm) { const tr = el('tr'); tr.dataset.instanceId = String(vm.id); - const ip = el('span', 'admin-instance-ip'); - ip.append(el('span', 'admin-mono', text(vm.public_ip, '未记录'))); - if (vm.public_ip) ip.append(copyButton(vm.public_ip, '复制公网 IP')); + const addresses = el('span', 'admin-instance-addresses'); + for (const [family, value] of [[4, vm.public_ipv4], [6, vm.public_ipv6]]) { + const ip = el('span', 'admin-instance-ip'); + ip.dataset.addressFamily = String(family); + ip.append(el('small', 'text-muted', `IPv${family}`), + el('span', 'admin-mono', text(value, '未记录'))); + if (value) ip.append(copyButton(value, `复制公网 IPv${family}`)); + addresses.append(ip); + } const statuses = el('div', 'admin-instance-status'); const power = el('span'); power.dataset.powerStatus = ''; paintPower(power, vm); statuses.append(power, el('span', 'fs-12', `服务:${text(vm.display?.service)}`), @@ -139,7 +145,7 @@ export function createAdminInstanceDirectory({ text(vm.host_name, `宿主机 #${vm.host_id}`), text(vm.region, '地区未记录'), ); - location.append(ip); + location.append(addresses); const cells = [ stack(text(vm.name), `#${vm.id} · ${text(vm.os_name, '系统未记录')}`), stack(vm.user_url ? safeLink(vm.user_url, text(vm.user_name, `用户 #${vm.user_id}`)) : text(vm.user_name), `ID ${vm.user_id}`), @@ -314,13 +320,19 @@ export function createAdminInstanceDirectory({ function updatePublicIp(id, publicIp, publicIpCidr = '') { const item = state.items.find(entry => String(entry.id) === String(id)); - if (item) { item.public_ip = publicIp; item.public_ip_cidr = publicIpCidr; } + if (item) { + item.public_ip = publicIp; + item.public_ip_cidr = publicIpCidr; + item.public_ipv4 = publicIp; + item.public_ipv4_cidr = publicIpCidr; + } const rowNode = Array.from(byId('instances-body').rows) .find(node => node.dataset.instanceId === String(id)); - const ipNode = rowNode?.querySelector('.admin-instance-ip'); + const ipNode = rowNode?.querySelector('[data-address-family="4"]'); if (!ipNode) return; - ipNode.replaceChildren(el('span', 'admin-mono', text(publicIp, '未记录'))); - if (publicIp) ipNode.append(copyButton(publicIp, '复制公网 IP')); + ipNode.replaceChildren(el('small', 'text-muted', 'IPv4'), + el('span', 'admin-mono', text(publicIp, '未记录'))); + if (publicIp) ipNode.append(copyButton(publicIp, '复制公网 IPv4')); } const handlers = { diff --git a/web/public/cloud/admin-vpc.js b/web/public/cloud/admin-vpc.js index 69955481..ec540f47 100644 --- a/web/public/cloud/admin-vpc.js +++ b/web/public/cloud/admin-vpc.js @@ -340,7 +340,8 @@ function portCard(port) { header.append(heading, detailState(labels[port.state] || port.state, healthy ? 'success' : (port.last_error_code ? 'danger' : 'warning'))); const details = create('dl'); - detailField(details, '公网 IPv4', port.public_ip); + detailField(details, '公网 IPv4', port.public_ipv4 || port.public_ip); + detailField(details, '公网 IPv6', port.public_ipv6); detailField(details, '私网 IPv4', port.private_ip); detailField(details, '所在节点', port.host_name || `节点 #${port.host_id}`); detailField(details, '版本', `${port.applied_revision} / ${port.desired_revision}`); diff --git a/web/public/cloud/detail.js b/web/public/cloud/detail.js index 0912f16c..72297a04 100644 --- a/web/public/cloud/detail.js +++ b/web/public/cloud/detail.js @@ -28,7 +28,9 @@ const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options const VM_METADATA_FIELDS = Object.freeze([ 'region', 'location', 'created_at', 'os_source', 'os_name', - 'install_iso', 'guest_hostname', 'public_ip_cidr', 'public_ip', 'login_name', 'vcpu', + 'install_iso', 'guest_hostname', 'public_network_valid', 'public_network', + 'public_ipv4', 'public_ipv4_cidr', 'public_ipv6', 'public_ipv6_cidr', + 'public_ip_cidr', 'public_ip', 'login_name', 'vcpu', 'cpu_cores', 'memory_mib', 'ram_mib', 'disks', 'disk_gib', 'agent_metadata_version', ]); @@ -306,8 +308,9 @@ function needsVmMetadata(vm) { const source = hasMetadataText(vm?.os_source) ? String(vm.os_source).trim() : ''; if (!source) return true; if (source === 'cloud_template') { - return !hasMetadataText(vm.public_ip_cidr || vm.public_ip) - || !hasMetadataText(vm.os_name) || !hasMetadataText(vm.login_name); + // The Agent may refresh guest metadata, never the frozen public network + // identity. Keep invalid snapshots failed closed without a probe loop. + return !hasMetadataText(vm.os_name) || !hasMetadataText(vm.login_name); } if (source === 'iso') return !hasMetadataText(vm.install_iso); return true; @@ -2993,10 +2996,12 @@ export async function initialize() { if (!byId('vm-settings-section-snapshots')?.hidden) await loadVmSnapshots(vmId, true); if (!byId('vm-settings-section-rescue')?.hidden) await loadRescue(vmId, true).catch(() => null); }); - byId('vm-detail-ip-copy')?.addEventListener('click', async () => { - try { await copyText(vmIp(selectedVm())); } - catch (error) { toast(error.message, 'error'); } - }); + for (const family of [4, 6]) { + byId(`vm-detail-ipv${family}-copy`)?.addEventListener('click', async () => { + try { await copyText(vmIp(selectedVm(), family)); } + catch (error) { toast(error.message, 'error'); } + }); + } byId('vm-detail-password-reveal')?.addEventListener('click', () => credential()); byId('vm-detail-password-copy')?.addEventListener('click', () => credential(true)); byId('vm-metrics-range')?.addEventListener('change', () => { diff --git a/web/public/cloud/instances.js b/web/public/cloud/instances.js index e1fc0870..97d2ad71 100644 --- a/web/public/cloud/instances.js +++ b/web/public/cloud/instances.js @@ -93,7 +93,9 @@ function normalizeVm(vm) { api_id: String(source.api_id || source.id || source.uuid || ''), vcpu: source.vcpu ?? source.cpu_cores, memory_mib: source.memory_mib ?? source.ram_mib, - public_ip_cidr: source.public_ip_cidr || source.public_ip || '', + public_network_valid: source.public_network_valid === true, + public_ipv4: source.public_network_valid === true ? String(source.public_ipv4 || '') : '', + public_ipv6: source.public_network_valid === true ? String(source.public_ipv6 || '') : '', state_fresh: fresh, state_observed_at: source.state_observed_at ?? source.last_success_at ?? null, state_sync_status: String(source.state_sync_status ?? source.sync_status @@ -154,6 +156,7 @@ function hasKnownState(vm) { } function stateCategoryForVm(vm) { + if (vm?.network_status === 'configuration_invalid') return 'other'; if (operationTransition(vm)) return 'other'; if (servicePaused(vm)) return 'other'; const sync = String(vm?.state_sync_status || '').toLowerCase(); @@ -165,6 +168,9 @@ function stateCategoryForVm(vm) { } function stateDisplay(vm) { + if (vm?.network_status === 'configuration_invalid') { + return { label: '网络配置异常', category: 'other', note: '', noteClass: '' }; + } const transition = operationTransition(vm); if (transition) { const labels = { @@ -199,8 +205,9 @@ function vmRegion(vm) { return firstText(vm.region, vm.location, '未设置'); } -function vmIp(vm) { - return firstText(vm.public_ip_cidr, vm.public_ip).split('/')[0] || '未获取'; +function vmIp(vm, family) { + if (vm?.public_network_valid !== true) return '未获取'; + return firstText(family === 6 ? vm.public_ipv6 : vm.public_ipv4) || '未获取'; } function vmSystemInfo(vm) { @@ -312,7 +319,7 @@ function matchingVms() { const query = (byId('search-input')?.value || '').trim().toLocaleLowerCase(); const filter = byId('state-filter')?.value || 'all'; return state.vms.filter(vm => { - const textMatches = !query || [vm.name, vm.uuid, vm.public_ip_cidr, vm.public_ip, + const textMatches = !query || [vm.name, vm.uuid, vm.public_ipv4, vm.public_ipv6, vm.region, vm.location, vm.os_name, vm.install_iso] .some(value => String(value || '').toLocaleLowerCase().includes(query)); const statusMatches = filter === 'all' || stateCategoryForVm(vm) === filter; @@ -388,11 +395,15 @@ function renderVms(connectionError = false) { const system = vmSystemInfo(vm); makeCell(row, system.label).append(makeElement('span', 'vm-metadata', system.value)); - const ip = vmIp(vm); - const ipRow = makeElement('span', 'vm-ip-copy-row'); - ipRow.append(makeElement('span', 'vm-metadata vm-ip', ip)); - if (ip !== '未获取') ipRow.append(copyIconButton(ip, '公网 IP')); - makeCell(row, '已配置公网 IP').append(ipRow); + const addresses = makeElement('div', 'vm-public-addresses'); + for (const [family, label] of [[4, '公网 IPv4'], [6, '公网 IPv6']]) { + const ip = vmIp(vm, family); + const ipRow = makeElement('span', 'vm-ip-copy-row'); + ipRow.append(makeElement('small', '', label), makeElement('span', 'vm-metadata vm-ip', ip)); + if (ip !== '未获取') ipRow.append(copyIconButton(ip, label)); + addresses.append(ipRow); + } + makeCell(row, '公网地址').append(addresses); const spec = makeElement('div', 'vm-spec'); spec.append(makeElement('strong', '', `${vm.vcpu ?? '—'} vCPU · ${vm.memory_mib ?? '—'} MiB`), @@ -474,7 +485,9 @@ function vmMatchesUpdate(vm, update) { const VM_METADATA_FIELDS = Object.freeze([ 'region', 'location', 'os_source', 'os_name', 'install_iso', - 'public_ip_cidr', 'public_ip', 'login_name', 'vcpu', 'cpu_cores', 'memory_mib', + 'public_network_valid', 'public_network', 'public_ipv4', 'public_ipv4_cidr', + 'public_ipv6', 'public_ipv6_cidr', 'public_ip_cidr', 'public_ip', + 'login_name', 'vcpu', 'cpu_cores', 'memory_mib', 'ram_mib', 'disks', 'disk_gib', 'agent_metadata_version', ]); @@ -483,8 +496,10 @@ function needsVmMetadata(vm) { const source = firstText(vm?.os_source); if (!source) return true; if (source === 'cloud_template') { - return !firstText(vm.public_ip_cidr, vm.public_ip) - || !firstText(vm.os_name) || !firstText(vm.login_name); + // Public addressing is a frozen panel snapshot. The Agent metadata API + // cannot repair it, so an invalid snapshot must not trigger endless + // metadata probes or be replaced by host-reported network values. + return !firstText(vm.os_name) || !firstText(vm.login_name); } if (source === 'iso') return !firstText(vm.install_iso); return true; diff --git a/web/public/cloud/runtime.js b/web/public/cloud/runtime.js index c81a9e50..c45cb584 100644 --- a/web/public/cloud/runtime.js +++ b/web/public/cloud/runtime.js @@ -92,7 +92,10 @@ function normalizeVm(vm) { const canDelete = vm.can_delete === undefined ? legacyMutation : vm.can_delete === true; const canViewCredential = vm.can_view_credential !== false; return { ...vm, uuid: String(vm.uuid || vm.id || ''), api_id: String(vm.id || vm.uuid || ''), vcpu: vm.vcpu ?? vm.cpu_cores, - memory_mib: vm.memory_mib, public_ip_cidr: vm.public_ip_cidr || vm.public_ip || '', can_operate: canOperate, can_delete: canDelete, + memory_mib: vm.memory_mib, public_network_valid: vm.public_network_valid === true, + public_ipv4: vm.public_network_valid === true ? String(vm.public_ipv4 || '') : '', + public_ipv6: vm.public_network_valid === true ? String(vm.public_ipv6 || '') : '', + can_operate: canOperate, can_delete: canDelete, can_view_credential: canViewCredential, password_available: canViewCredential && (vm.password_available === true || vm.has_initial_root_password === true) }; } @@ -178,7 +181,9 @@ function networkStatusInfo(value) { blocked_traffic: ['本期流量用尽,已断网', 'stopped'], blocked_expired: ['实例已到期,网络已停用', 'stopped'], block_failed: ['网络停用失败,请联系管理员', 'stopped'], restore_pending: ['等待恢复网络', 'warning'], restoring: ['正在恢复网络', 'warning'], expiry_block_failed: ['到期断网失败,请联系管理员', 'stopped'], block_expired_failed: ['到期断网失败,请联系管理员', 'stopped'], - restore_failed: ['网络恢复失败,请联系管理员', 'stopped'], exempt: ['网络不受套餐限制', 'active'], + restore_failed: ['网络恢复失败,请联系管理员', 'stopped'], + configuration_invalid: ['网络配置异常,请联系管理员', 'stopped'], + exempt: ['网络不受套餐限制', 'active'], }; const [label, className] = labels[status] || [value || '暂未提供', 'unknown']; return { label, className }; @@ -361,12 +366,15 @@ function renderVmDetail(vm) { syncElement.hidden = !display.note; } for (const id of ['vm-detail-region', 'vm-detail-header-region']) text(id, vmRegion(vm)); - for (const id of ['vm-detail-ip', 'vm-detail-header-ip']) text(id, vmIp(vm)); + text('vm-detail-ipv4', vmIp(vm, 4)); + text('vm-detail-ipv6', vmIp(vm, 6)); + text('vm-detail-header-ip', vmIp(vm, 4)); text('vm-detail-header-created-at', vmCreatedAgo(vm)); const system = vmSystemInfo(vm); text('vm-detail-os-label', system.label); text('vm-detail-os', system.value); text('vm-detail-spec', `${vm.vcpu ?? '—'} vCPU · ${vm.memory_mib ?? '—'} MiB`); text('vm-detail-disk', diskLabel(vm)); text('vm-detail-ssh-user', vm.login_name || (vm.os_source === 'cloud_template' ? 'root' : '未记录')); const settingsHostname = byId('vm-detail-settings-current-hostname'); if (settingsHostname) settingsHostname.textContent = vm.guest_hostname || '未记录'; - byId('vm-detail-ip-copy').hidden = vmIp(vm) === '未获取'; + byId('vm-detail-ipv4-copy').hidden = vmIp(vm, 4) === '未获取'; + byId('vm-detail-ipv6-copy').hidden = vmIp(vm, 6) === '未获取'; text('vm-detail-root-password', !vm.can_view_credential ? '无权查看' : vm.password_available ? (state.credentialVisible ? state.credentialPassword : '********') : '未记录'); for (const id of ['vm-detail-password-reveal', 'vm-detail-password-copy']) byId(id).hidden = !vm.password_available; renderVmService(vm); @@ -1337,8 +1345,9 @@ function vmRegion(vm) { return String(vm.region || "").trim() || "未设置"; } -function vmIp(vm) { - return String(vm.public_ip_cidr || "").trim().split("/")[0] || "未获取"; +function vmIp(vm, family = 4) { + if (vm?.public_network_valid !== true) return "未获取"; + return String(family === 6 ? vm.public_ipv6 : vm.public_ipv4).trim() || "未获取"; } function vmCreatedAt(vm) { @@ -1428,7 +1437,8 @@ function renderVMs(connectionError = false) { const query = byId("search-input").value.trim().toLocaleLowerCase(); const filter = byId("state-filter").value; const filtered = all.filter((vm) => { - const matchesText = !query || [vm.name, vm.uuid, vm.public_ip_cidr, vm.region, vm.os_name, vm.install_iso] + const matchesText = !query || [vm.name, vm.uuid, vm.public_ipv4, vm.public_ipv6, + vm.region, vm.os_name, vm.install_iso] .some((value) => String(value || "").toLocaleLowerCase().includes(query)); return matchesText && (filter === "all" || stateCategory(vm.state) === filter); }); @@ -1455,7 +1465,8 @@ function renderVMs(connectionError = false) { for (const vm of filtered) { const uuid = String(vm.uuid || ""); - const category = stateCategory(vm.state); + const invalidNetwork = vm?.network_status === 'configuration_invalid'; + const category = invalidNetwork ? 'other' : stateCategory(vm.state); const row = document.createElement("tr"); const identity = makeElement("div", "vm-identity"); identity.append(makeElement("div", "vm-icon", "▣")); @@ -1478,7 +1489,8 @@ function renderVMs(connectionError = false) { const stateCell = makeCell(row); stateCell.dataset.label = "状态"; - stateCell.append(makeElement("span", `state-pill ${category}`, stateLabel(vm.state))); + stateCell.append(makeElement("span", `state-pill ${category}`, + invalidNetwork ? '网络配置异常' : stateLabel(vm.state))); const regionCell = makeCell(row); regionCell.dataset.label = "地区"; regionCell.append(makeElement("span", "vm-metadata", vmRegion(vm))); @@ -1487,12 +1499,16 @@ function renderVMs(connectionError = false) { systemCell.dataset.label = system.label; systemCell.append(makeElement("span", "vm-metadata", system.value)); const ipCell = makeCell(row); - ipCell.dataset.label = "已配置公网 IP"; - const ip = vmIp(vm); - const ipRow = makeElement("span", "vm-ip-copy-row"); - ipRow.append(makeElement("span", "vm-metadata vm-ip", ip)); - if (ip !== "未获取") ipRow.append(makeCopyIconButton(ip, "公网 IP")); - ipCell.append(ipRow); + ipCell.dataset.label = "公网地址"; + const addresses = makeElement("div", "vm-public-addresses"); + for (const [family, label] of [[4, "公网 IPv4"], [6, "公网 IPv6"]]) { + const ip = vmIp(vm, family); + const ipRow = makeElement("span", "vm-ip-copy-row"); + ipRow.append(makeElement("small", "", label), makeElement("span", "vm-metadata vm-ip", ip)); + if (ip !== "未获取") ipRow.append(makeCopyIconButton(ip, label)); + addresses.append(ipRow); + } + ipCell.append(addresses); const spec = makeElement("div", "vm-spec"); spec.append(makeElement("strong", "", `${vm.vcpu ?? "—"} vCPU · ${vm.memory_mib ?? "—"} MiB`)); spec.append(makeElement("small", "", "计算资源")); diff --git a/web/public/cloud/styles.css b/web/public/cloud/styles.css index ea2b240d..c58045be 100644 --- a/web/public/cloud/styles.css +++ b/web/public/cloud/styles.css @@ -126,7 +126,7 @@ tbody tr:hover{background:#fcfefe} .footer-note{text-align:right;color:#a9b4c0;font-size:10px;margin-top:18px} .vm-detail-back{padding-left:0;margin-bottom:22px;color:#267b86}.vm-detail-heading{align-items:center}.vm-detail-heading .heading-actions{align-items:center}.vm-detail-heading .state-pill{min-height:31px}.vm-detail-summary{display:flex;align-items:center;flex-wrap:wrap;gap:5px 18px}.vm-detail-summary span{white-space:nowrap}.vm-detail-summary strong{color:#455a70;font-weight:700;margin-left:4px}.vm-detail-tabs{display:flex;width:max-content;max-width:100%;gap:4px;margin:0 0 18px;padding:5px;overflow-x:auto;border:1px solid #dfeaec;border-radius:11px;background:#f3f8f9}.vm-detail-tab{min-height:39px;padding:9px 18px;border:0;border-radius:8px;background:transparent;color:#718497;font:inherit;font-size:12px;font-weight:800;white-space:nowrap;cursor:pointer}.vm-detail-tab:hover{color:#237f88;background:#e8f4f4}.vm-detail-tab.active{background:#fff;color:#157f88;box-shadow:0 2px 9px rgba(27,71,87,.1)}.vm-detail-tab:focus-visible{outline:2px solid #25adb4;outline-offset:2px}.vm-detail-grid{display:grid;grid-template-columns:minmax(0,1.15fr) minmax(320px,.85fr);gap:18px;align-items:start}.vm-detail-panel{min-height:0}.vm-detail-facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0;margin:0;padding:6px 24px 17px}.vm-detail-facts>div{min-width:0;padding:17px 9px 17px 0;border-bottom:1px solid #edf1f5}.vm-detail-facts dt{font-size:11px;font-weight:700;color:#91a0af;margin-bottom:9px}.vm-detail-facts dd{margin:0;color:#273c52;font-size:13px;font-weight:700;line-height:1.5;overflow-wrap:anywhere}.vm-detail-operations{display:grid;gap:18px}.vm-detail-actions{display:flex;flex-wrap:wrap;gap:10px;padding:20px 24px 23px}.vm-detail-actions .row-button{min-height:39px;padding:9px 15px;border-color:#dce9ea;font-size:12px}.vm-detail-actions .row-button.primary{border-color:#cbecee}.vm-danger-panel .panel-heading h2{color:#a4434f}.vm-danger-panel .row-button.danger{border-color:#f2dfe2;background:#fff9f9}.vm-danger-panel .row-button.danger:not(:disabled):hover{background:#ffedef} .vm-detail-name-control{position:relative;width:max-content;max-width:min(100%,680px)}.vm-detail-name-display{position:relative;display:flex;align-items:center;width:max-content;max-width:100%}.vm-detail-name-display h1{min-width:0;max-width:100%}.vm-detail-name-trigger{display:block;min-width:0;max-width:100%;padding:0;border:0;background:transparent;color:inherit;font:inherit;font-weight:inherit;letter-spacing:inherit;text-align:left;cursor:pointer}.vm-detail-name-trigger:hover #vm-detail-name-value{color:#167f88}.vm-detail-name-trigger:focus-visible{outline:2px solid #25adb4;outline-offset:5px;border-radius:4px}.vm-detail-name-trigger #vm-detail-name-value{display:block;min-width:0;overflow-wrap:anywhere;transition:color .15s ease}.vm-detail-name-tooltip{position:absolute;z-index:20;top:calc(100% - 2px);left:100%;width:max-content;max-width:220px;padding:7px 10px;border:1px solid #d8e6e9;border-radius:8px;background:#29475b;color:#fff;font-size:10px;font-weight:700;line-height:1.4;box-shadow:0 8px 20px rgba(27,58,75,.16);opacity:0;pointer-events:none;transform:translate(-18px,7px);transition:opacity .15s ease,transform .15s ease}.vm-detail-name-display:hover .vm-detail-name-tooltip,.vm-detail-name-display:focus-within .vm-detail-name-tooltip{opacity:1;transform:translate(-18px,3px)}.vm-detail-name-form{display:flex;align-items:baseline;flex-wrap:wrap;gap:8px;width:max-content;max-width:100%;margin:9px 0 8px}.vm-detail-name-form input{field-sizing:content;flex:0 1 auto;width:auto;min-width:2ch;max-width:100%;height:auto;padding:0;margin:0;border:0;border-radius:0;appearance:none;background:transparent;color:inherit;box-shadow:none;caret-color:#167f88;font:inherit;font-size:28px;font-weight:750;line-height:normal;letter-spacing:-.6px}.vm-detail-name-form input:focus{border:0;background:transparent;box-shadow:inset 0 -2px 0 #267b86;outline:none}.vm-detail-name-action{flex:none;min-height:32px;padding:2px 4px;border:0;appearance:none;background:transparent;color:#445368;box-shadow:none;font:inherit;font-size:12px;font-weight:800;line-height:1.4}.vm-detail-name-action.save{color:#267b86}.vm-detail-name-action:not(:disabled):hover{background:transparent;color:#126f77;text-decoration:underline;text-underline-offset:3px}.vm-detail-name-action:focus-visible{outline:2px solid #25adb4;outline-offset:3px;border-radius:2px}.vm-detail-name-status{margin:-2px 0 8px;color:#6b8190;font-size:10px;line-height:1.5}.vm-detail-name-status.success{color:#21785b}.vm-detail-name-status.error{color:#b13f4d} -.vm-detail-inline,.vm-ip-copy-row{display:flex;align-items:center;flex-wrap:wrap;gap:7px}.vm-detail-inline{min-height:25px}.vm-detail-secret{font:600 12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.vm-detail-mini-button,.vm-copy-icon{display:inline-flex;align-items:center;justify-content:center;flex:none;border:1px solid #d9e9ea;border-radius:6px;background:#f5fbfb;color:#1b8790;font-size:11px;font-weight:700;min-height:25px;padding:3px 7px}.vm-detail-mini-button:not(:disabled):hover,.vm-copy-icon:not(:disabled):hover{background:#e6f6f7;border-color:#b6dcdf}.vm-copy-icon{width:25px;padding:3px}.vm-copy-icon svg{display:block;width:15px;height:15px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round} +.vm-detail-inline,.vm-ip-copy-row{display:flex;align-items:center;flex-wrap:wrap;gap:7px}.vm-public-addresses{display:grid;gap:7px;min-width:180px}.vm-public-addresses .vm-ip-copy-row{display:grid;grid-template-columns:42px minmax(0,1fr) 25px;align-items:center;gap:6px}.vm-public-addresses .vm-ip-copy-row small{color:#94a2b2;font-size:9px;font-weight:800}.vm-detail-inline{min-height:25px}.vm-detail-secret{font:600 12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.vm-detail-mini-button,.vm-copy-icon{display:inline-flex;align-items:center;justify-content:center;flex:none;border:1px solid #d9e9ea;border-radius:6px;background:#f5fbfb;color:#1b8790;font-size:11px;font-weight:700;min-height:25px;padding:3px 7px}.vm-detail-mini-button:not(:disabled):hover,.vm-copy-icon:not(:disabled):hover{background:#e6f6f7;border-color:#b6dcdf}.vm-copy-icon{width:25px;padding:3px}.vm-copy-icon svg{display:block;width:15px;height:15px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round} .vm-operation-log-view .panel-heading{align-items:center}.vm-operation-log-status{margin:0;padding:13px 24px;border-top:1px solid #edf1f5;background:#f7fbfc;color:#6f8496;font-size:12px;line-height:1.5}.vm-operation-log-status.warning{color:#a56c24;background:#fff8eb}.vm-operation-log-table{overflow-x:auto}.vm-operation-log-row{display:grid;grid-template-columns:minmax(120px,1fr) minmax(180px,1.35fr) minmax(75px,auto);align-items:center;gap:18px;padding:14px 24px;border-top:1px solid #edf1f5;color:#536b7e;font-size:12px}.vm-operation-log-header{border-top:0;background:#f7fbfc;color:#8a9baa;font-size:10px;font-weight:800;letter-spacing:.04em}.vm-operation-log-cell{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vm-operation-log-cell.operation{color:#2c465a;font-weight:800}.vm-operation-log-cell.result{justify-self:end;overflow:visible;padding:5px 10px;border-radius:999px;background:#f1f4f6;color:#738495;font-size:11px;font-weight:800}.vm-operation-log-cell.result.queued,.vm-operation-log-cell.result.running{background:#eaf8f8;color:#21848c}.vm-operation-log-cell.result.succeeded{background:#eaf8f1;color:#23845d}.vm-operation-log-cell.result.failed{background:#fff0f1;color:#b34b57}.vm-operation-log-cell.result.locked{background:#fff7e9;color:#9a6a22}.vm-operation-log-footer{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:14px 24px;border-top:1px solid #edf1f5;color:#7b8e9e;font-size:11px}.vm-operation-log-footer nav{display:flex;align-items:center;gap:8px}.vm-operation-log-footer .button{min-height:30px;padding:5px 10px;font-size:11px}.vm-operation-log-footer nav>span{min-width:42px;text-align:center;color:#536b7e;font-weight:700}.vm-operation-log-empty{margin:0;padding:24px;color:#8a9aa8;font-size:12px;text-align:center} .vm-credential-icon{width:30px;min-height:30px}.vm-credential-icon svg{width:17px;height:17px}.vm-credential-icon .vm-eye-slash{visibility:hidden}.vm-credential-icon[aria-pressed="true"] .vm-eye-slash{visibility:visible} .vm-settings-view{display:grid;gap:18px}.vm-settings-surface{overflow:hidden;border-block:1px solid #e7ecf2;background:#fff}.vm-settings-layout{display:grid;grid-template-columns:minmax(180px,225px) minmax(0,1fr);min-height:420px}.vm-settings-navigation{display:flex;flex-direction:column;gap:3px;padding:25px 18px;border-right:1px solid #e5ecef;background:#fbfcfd}.vm-settings-navigation-button{position:relative;width:100%;min-height:45px;padding:11px 13px 11px 17px;border:0;border-left:3px solid transparent;border-radius:0;background:transparent;color:#647487;font:inherit;font-size:12px;font-weight:700;text-align:left;cursor:pointer}.vm-settings-navigation-button:hover{background:#f1f8f8;color:#177f88}.vm-settings-navigation-button.active{border-left-color:#17a2aa;background:#edf8f8;color:#126f77}.vm-settings-navigation-button:focus-visible{outline:2px solid #25adb4;outline-offset:2px}.vm-settings-content{min-width:0;padding:35px clamp(26px,4vw,52px) 42px}.vm-settings-section{width:min(100%,780px)}.vm-settings-section-heading{margin:0 0 24px}.vm-settings-section-heading .eyebrow{display:block;margin-bottom:7px}.vm-settings-section-heading h3{margin:0 0 9px;color:#24384d;font-size:22px;letter-spacing:-.3px}.vm-settings-section-heading p{margin:0;color:#7f8f9e;font-size:12px;line-height:1.7}.vm-settings-notice{display:grid;gap:5px;margin:0 0 28px;padding:15px 18px;border-left:3px solid #1ba5ad;background:#f4f9fa;color:#66808f;font-size:11px;line-height:1.65}.vm-settings-notice strong{color:#177f88;font-size:12px}.vm-settings-notice.warning{border-left-color:#e99a34;background:#fff8ed;color:#8b714b}.vm-settings-notice.warning strong{color:#b87119}.vm-settings-form{display:grid;gap:21px}.vm-settings-field{display:grid;gap:8px}.vm-settings-field>label{color:#40566a;font-size:12px;font-weight:800}.vm-settings-field input[type=text],.vm-settings-field select{width:100%;min-width:0;height:44px}.vm-settings-field small{display:block;color:#8b9aa8;font-size:10px;line-height:1.6}.vm-settings-field small a{color:#168b94}.vm-settings-current-value{color:#7c8d9d;font-size:10px;line-height:1.5}.vm-settings-current-value code{display:inline-block;margin-left:4px;color:#1b7f88;font:700 11px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.vm-settings-restart-confirm{padding:14px 15px;border:1px solid #e2e9ed;background:#fbfcfd}.vm-settings-restart-confirm small{display:block;margin-top:3px;color:#8c9ba8;font-size:10px;line-height:1.5}.vm-settings-actions{display:flex;justify-content:flex-end;padding-top:2px}.vm-settings-actions .button{min-width:168px}.vm-settings-form .form-error{margin:0;color:#b04452;font-size:11px;line-height:1.5}.vm-settings-status{margin:0 0 24px;padding:11px 13px;border-radius:8px;background:#eaf7f7;color:#287d84;font-size:11px;line-height:1.55}.vm-settings-status.success{background:#eaf8f1;color:#267d5b}.vm-settings-status.warning{background:#fff7e8;color:#946722}.vm-settings-status.error{background:#fff0f1;color:#b04452}.vm-settings-unavailable{margin:0;padding:30px 24px;color:#8393a2;font-size:12px;line-height:1.6} @@ -177,7 +177,7 @@ tbody tr:hover{background:#fcfefe} @media(max-width:510px){.workspace-form-body{padding:22px 19px 25px}.workspace-form-actions{padding:15px 19px}.workspace-form-actions .button{flex:1 1 100%}.workspace-form-back{margin-bottom:10px}} @media(max-width:510px){.register-code-row{flex-wrap:wrap}.register-code-row input{flex-basis:100%}.register-code-row .button{width:100%}.pending-user-row{align-items:flex-start;flex-direction:column}.pending-user-row .button{width:100%}.smtp-card .form-grid{grid-template-columns:1fr}} @media(max-width:510px){.ssh-key-row{align-items:flex-start;flex-direction:column;justify-content:flex-start}.ssh-key-actions{width:100%}.ssh-key-actions .row-button{flex:1}} -@media(max-width:510px){.vm-detail-heading .heading-actions{justify-content:space-between}.vm-detail-heading .heading-actions .button{flex:0 0 auto}.vm-detail-name-control{width:100%;max-width:100%}.vm-detail-name-display{max-width:100%}.vm-detail-name-tooltip{right:0;left:auto;transform:translateY(7px)}.vm-detail-name-display:hover .vm-detail-name-tooltip,.vm-detail-name-display:focus-within .vm-detail-name-tooltip{transform:translateY(3px)}.vm-detail-name-form{max-width:100%}.vm-detail-name-form input{min-width:2ch;max-width:100%;flex:0 1 auto}.vm-detail-name-action{flex:none}.vm-detail-facts{grid-template-columns:1fr}.vm-detail-facts>div{padding:12px 0}.vm-detail-actions .row-button{flex:1 1 135px}.vm-table td{padding:10px 11px}.vm-identity{min-width:0}.vm-name-link{max-width:calc(100vw - 130px)}.vm-settings-navigation{padding-inline:8px}.vm-settings-navigation-button{padding-inline:10px;font-size:11px}.vm-settings-content{padding:24px 17px 28px}.vm-settings-actions .button{width:100%}} +@media(max-width:510px){.vm-detail-heading .heading-actions{justify-content:space-between}.vm-detail-heading .heading-actions .button{flex:0 0 auto}.vm-detail-name-control{width:100%;max-width:100%}.vm-detail-name-display{max-width:100%}.vm-detail-name-tooltip{right:0;left:auto;transform:translateY(7px)}.vm-detail-name-display:hover .vm-detail-name-tooltip,.vm-detail-name-display:focus-within .vm-detail-name-tooltip{transform:translateY(3px)}.vm-detail-name-form{max-width:100%}.vm-detail-name-form input{min-width:2ch;max-width:100%;flex:0 1 auto}.vm-detail-name-action{flex:none}.vm-detail-facts{grid-template-columns:1fr}.vm-detail-facts>div{padding:12px 0}.vm-detail-actions .row-button{flex:1 1 135px}.vm-table td{padding:10px 11px}.vm-table td[data-label="公网地址"]{grid-column:1/-1}.vm-public-addresses{min-width:0;width:100%}.vm-identity{min-width:0}.vm-name-link{max-width:calc(100vw - 130px)}.vm-settings-navigation{padding-inline:8px}.vm-settings-navigation-button{padding-inline:10px;font-size:11px}.vm-settings-content{padding:24px 17px 28px}.vm-settings-actions .button{width:100%}} @media(max-width:510px){.vm-snapshot-toolbar{display:block}.vm-snapshot-create-fields{grid-template-columns:1fr}.vm-snapshot-create-form{padding:0}.vm-snapshot-row{grid-template-columns:1fr;align-items:start;padding:14px}.vm-snapshot-actions{justify-content:stretch}.vm-snapshot-actions .button{flex:1}.vm-snapshot-heading{align-items:flex-start;justify-content:space-between}.vm-snapshot-state{flex:none}} @media(max-width:740px){.vm-firewall-facts{grid-template-columns:1fr}.vm-firewall-facts>div{grid-template-columns:minmax(100px,.8fr) minmax(0,1fr)}.vm-firewall-toolbar{align-items:stretch;flex-direction:column}.vm-firewall-presets{display:grid;grid-template-columns:repeat(3,minmax(0,1fr))}.vm-firewall-presets>span{grid-column:1/-1}.vm-firewall-toolbar>.button{width:100%}.vm-firewall-table{overflow-x:auto;overflow-y:hidden;-webkit-overflow-scrolling:touch}.vm-firewall-rule{min-width:650px}.vm-firewall-footer{align-items:stretch;flex-direction:column}.vm-firewall-footer .button{width:100%}} @media(max-width:510px){.vm-operation-log-view .panel-heading{align-items:flex-start}.vm-operation-log-view .panel-heading .button{width:100%}.vm-operation-log-status{padding-inline:17px}.vm-operation-log-row{grid-template-columns:minmax(78px,1fr) minmax(130px,1.45fr) minmax(62px,auto);gap:8px;padding-inline:17px;font-size:11px}.vm-operation-log-header{font-size:9px}.vm-operation-log-cell.result{padding:4px 7px;font-size:10px}.vm-operation-log-footer{align-items:flex-start;flex-direction:column;padding-inline:17px}.vm-operation-log-footer nav{width:100%;justify-content:space-between}} diff --git a/web/public/cloud/vpcs.js b/web/public/cloud/vpcs.js index 294665c7..91f60ef4 100644 --- a/web/public/cloud/vpcs.js +++ b/web/public/cloud/vpcs.js @@ -187,13 +187,17 @@ function publicIpv4(instance) { return String(instance?.public_ipv4 || '').trim() || '未分配'; } +function publicIpv6(instance) { + return String(instance?.public_ipv6 || '').trim() || '未分配'; +} + function normalizedMemberQuery(value) { return String(value || '').trim().toLocaleLowerCase(); } function instanceMatchesMemberQuery(instance, query) { if (!query) return true; - return [instance?.name, instanceId(instance), publicIpv4(instance)] + return [instance?.name, instanceId(instance), publicIpv4(instance), publicIpv6(instance)] .some(value => String(value || '').toLocaleLowerCase().includes(query)); } @@ -398,12 +402,16 @@ function renderInstanceRow(instance, vpc, joining, checkbox) { const publicValue = element('dd'); publicValue.append(element('code', '', publicIpv4(instance))); publicAddress.append(element('dt', '', '公网 IPv4'), publicValue); + const publicAddress6 = element('div'); + const publicValue6 = element('dd'); + publicValue6.append(element('code', '', publicIpv6(instance))); + publicAddress6.append(element('dt', '', '公网 IPv6'), publicValue6); const privateAddress = element('div', 'cloud-vpc-private-address'); const privateValue = element('dd'); privateValue.append(element(joining ? 'span' : 'code', '', joining ? '自动分配' : port.private_ip || '待分配')); privateAddress.append(element('dt', '', joining ? '私网分配' : '私网 IPv4'), privateValue); - facts.append(publicAddress, privateAddress); + facts.append(publicAddress, publicAddress6, privateAddress); if (!joining && port.mac_address) { const macAddress = element('div', 'cloud-vpc-mac-address'); const macValue = element('dd'); diff --git a/web/public/theme/venix/css/admin-home.css b/web/public/theme/venix/css/admin-home.css index c13dd6fd..e0ad9cd4 100644 --- a/web/public/theme/venix/css/admin-home.css +++ b/web/public/theme/venix/css/admin-home.css @@ -520,6 +520,19 @@ html.admin-sidebar-scroll-locked { min-width: 0; } +[data-admin-instances] .admin-instance-addresses { + display: grid; + gap: 4px; + margin-top: 3px; + min-width: 0; +} + +[data-admin-instances] .admin-instance-ip small { + min-width: 28px; + font-size: 10px; + font-weight: 700; +} + [data-admin-instances] .admin-instance-ip .btn, [data-admin-instance-drawer] .admin-instance-ip .btn { flex: 0 0 auto; diff --git a/web/resources/views/venix/admin/cloud/instances.tpl b/web/resources/views/venix/admin/cloud/instances.tpl index 7563f614..74788850 100644 --- a/web/resources/views/venix/admin/cloud/instances.tpl +++ b/web/resources/views/venix/admin/cloud/instances.tpl @@ -19,7 +19,7 @@

查找实例

常用条件始终可见;更多业务状态收纳在高级筛选中。失败任务不会自动重新提交。
- +
高级筛选用户、期限、异常、排序和分页
@@ -39,7 +39,7 @@ {$vm.name|escape}#{$vm.id|escape} · {$vm.os_name|default:'系统未记录'|escape} {if $vm.user_url}{$vm.user_name|escape}{else}{$vm.user_name|escape}{/if}ID {$vm.user_id|escape} - {$vm.host_name|escape}{$vm.region|default:'地区未记录'|escape}{$vm.public_ip|default:'未记录'|escape}{if $vm.public_ip}{/if} + {$vm.host_name|escape}{$vm.region|default:'地区未记录'|escape}公网 IPv4{$vm.public_ipv4|default:'未记录'|escape}{if $vm.public_ipv4}{/if}公网 IPv6{$vm.public_ipv6|default:'未记录'|escape}{if $vm.public_ipv6}{/if} {$vm.display.configuration|escape}{$vm.plan_name|default:'无关联套餐'|escape}
电源:待获取服务:{$vm.display.service|escape}网络:{$vm.display.network|escape}{if $vm.active_job}任务 #{$vm.active_job.id|escape} · {if isset($vm.active_job.completed) && !$vm.active_job.completed && $vm.active_job.status == 'active'}执行中{elseif isset($vm.active_job.completed) && $vm.active_job.completed && $vm.active_job.status == 'succeeded'}已成功{elseif isset($vm.active_job.completed) && $vm.active_job.completed && $vm.active_job.status == 'failed'}已失败{if $vm.active_job.blocks_mutation|default:false}{if $vm.active_job.recovery.pending|default:false} · 资源安全锁定,仍会继续自动核对{else} · 资源安全锁定,需管理员人工处理{/if}{/if}{else}任务状态协议错误 · 资源安全锁定{/if}{/if}
{$vm.display.traffic|escape}{$vm.display.expiry|escape}{if $vm.service_expires_at && $vm.service_status != 'exempt'}到期 {$vm.service_expires_at|date_format:'%Y-%m-%d'|escape}{/if} diff --git a/web/resources/views/venix/admin/ticket/view.tpl b/web/resources/views/venix/admin/ticket/view.tpl index 7ac4203a..af8a8133 100644 --- a/web/resources/views/venix/admin/ticket/view.tpl +++ b/web/resources/views/venix/admin/ticket/view.tpl @@ -40,7 +40,7 @@
状态
{if $ticket_main && $ticket_main->status==1}处理中{else}已关闭{/if}
类型
{if $ticket_main && $ticket_main->ticket_type=='pre_sales'}售前{elseif $ticket_main && $ticket_main->ticket_type=='after_sales'}售后{elseif $ticket_main && $ticket_main->ticket_type=='finance'}财务{else}技术{/if}
优先级
{if $ticket_main && $ticket_main->priority=='high'}High{elseif $ticket_main && $ticket_main->priority=='low'}Low{else}Medium{/if}
-
实例
{if isset($ticket_instance) && $ticket_instance}{$ticket_instance->name|escape:'html'}{if $ticket_instance->public_ipv4}{$ticket_instance->public_ipv4|escape:'html'}{/if}{elseif $ticket_main && $ticket_main->instance_id}#{$ticket_main->instance_id}(不可用){else}未关联{/if}
+
实例
{if isset($ticket_instance) && $ticket_instance}{$ticket_instance->name|escape:'html'}{if $ticket_instance->public_ipv4}IPv4 {$ticket_instance->public_ipv4|escape:'html'}{/if}{if $ticket_instance->public_ipv6}IPv6 {$ticket_instance->public_ipv6|escape:'html'}{/if}{elseif $ticket_main && $ticket_main->instance_id}#{$ticket_main->instance_id}(不可用){else}未关联{/if}
diff --git a/web/resources/views/venix/cloud/pages/detail.tpl b/web/resources/views/venix/cloud/pages/detail.tpl index cdb27b8f..f59fea5e 100644 --- a/web/resources/views/venix/cloud/pages/detail.tpl +++ b/web/resources/views/venix/cloud/pages/detail.tpl @@ -1,7 +1,7 @@
← 返回实例列表 -
VIRTUAL MACHINE DETAILS

{if $cloud_vm_view.can_rename|default:false}{else}{$cloud_vm_view.name|default:'虚拟机'|escape:"html"}{/if}

{if $cloud_vm_view.can_rename|default:false}点击实例名称修改{/if}
{if $cloud_vm_view.can_rename|default:false}名称以英文或数字开头,可包含英文、数字、点、下划线和连字符,最多 63 个字符。{/if}

服务器 IP:{$cloud_vm_view.ip|default:'未获取'|escape:"html"}区域:{$cloud_vm_view.region|default:'未设置'|escape:"html"}{$cloud_vm_view.created_display|default:'未记录'|escape:"html"}

{$cloud_vm_view.state_label|default:'正在读取'|escape:"html"}{$cloud_vm_view.state_sync_label|default:''|escape:"html"}
+
VIRTUAL MACHINE DETAILS

{if $cloud_vm_view.can_rename|default:false}{else}{$cloud_vm_view.name|default:'虚拟机'|escape:"html"}{/if}

{if $cloud_vm_view.can_rename|default:false}点击实例名称修改{/if}
{if $cloud_vm_view.can_rename|default:false}{/if}

公网 IPv4:{$cloud_vm_view.ipv4|default:'未获取'|escape:"html"}区域:{$cloud_vm_view.region|default:'未设置'|escape:"html"}{$cloud_vm_view.created_display|default:'未记录'|escape:"html"}

{$cloud_vm_view.state_label|default:'正在读取'|escape:"html"}{$cloud_vm_view.state_sync_label|default:''|escape:"html"}
@@ -17,7 +17,8 @@
服务状态
{$cloud_vm_view.service_status_label|default:'暂未提供'|escape:"html"}
网络状态
{$cloud_vm_view.network_status_label|default:'暂未提供'|escape:"html"}
实例到期时间
{$cloud_vm_view.service_expiry_display|default:'暂未提供'|escape:"html"}
-
已配置公网 IP
{$cloud_vm_view.ip|default:'未获取'|escape:"html"}
计算规格
{$cloud_vm_view.spec_display|default:'—'|escape:"html"}
+
公网 IPv4
{$cloud_vm_view.ipv4|default:'未获取'|escape:"html"}
+
公网 IPv6
{$cloud_vm_view.ipv6|default:'未获取'|escape:"html"}
计算规格
{$cloud_vm_view.spec_display|default:'—'|escape:"html"}
硬盘大小
{$cloud_vm_view.disk_display|default:'—'|escape:"html"}
SSH 登录名
{$cloud_vm_view.ssh_user|default:'未记录'|escape:"html"}
面板记录的初始 root 密码
{$cloud_vm_view.password_label|default:'未记录'|escape:"html"} diff --git a/web/resources/views/venix/cloud/pages/instances.tpl b/web/resources/views/venix/cloud/pages/instances.tpl index 105cb7c4..4a445e03 100644 --- a/web/resources/views/venix/cloud/pages/instances.tpl +++ b/web/resources/views/venix/cloud/pages/instances.tpl @@ -15,7 +15,7 @@

实例列表

当前页 {$cloud_vm_pagination.page_count|default:0|escape:"html"} 台 · 共 {$cloud_vm_pagination.total|escape:"html"} 台

-
+
实例状态到期时间地区系统 / 安装镜像已配置公网 IP规格磁盘
{foreach $cloud_vm_rows as $vm} @@ -23,7 +23,7 @@ - + diff --git a/web/resources/views/venix/cloud/pages/vpcs.tpl b/web/resources/views/venix/cloud/pages/vpcs.tpl index 0ed9426d..7aa9ddc9 100644 --- a/web/resources/views/venix/cloud/pages/vpcs.tpl +++ b/web/resources/views/venix/cloud/pages/vpcs.tpl @@ -61,6 +61,7 @@
公网 IPv4
{$instance.public_ipv4|escape:'html'}
+
公网 IPv6
{$instance.public_ipv6|escape:'html'}
{if $cloud_vpc_view.joining}私网分配{else}私网 IPv4{/if}
{if $cloud_vpc_view.joining}自动分配{else}{$instance.port.private_ip|default:'待分配'|escape:'html'}{/if}
{if empty($cloud_vpc_view.joining) && !empty($instance.port.mac_address)}
MAC 地址
{$instance.port.mac_address|escape:'html'}
{/if}
diff --git a/web/resources/views/venix/user/ticket_view.tpl b/web/resources/views/venix/user/ticket_view.tpl index 5e0660b7..699d76c7 100755 --- a/web/resources/views/venix/user/ticket_view.tpl +++ b/web/resources/views/venix/user/ticket_view.tpl @@ -104,7 +104,7 @@ {if isset($ticket_instance) && $ticket_instance}
关联实例 - {$ticket_instance->name|escape:'html'}{if $ticket_instance->public_ipv4}{$ticket_instance->public_ipv4|escape:'html'}{/if} + {$ticket_instance->name|escape:'html'}{if $ticket_instance->public_ipv4}IPv4 {$ticket_instance->public_ipv4|escape:'html'}{/if}{if $ticket_instance->public_ipv6}IPv6 {$ticket_instance->public_ipv6|escape:'html'}{/if}
{elseif isset($ticket_main) && $ticket_main->instance_id|default:''}
关联实例#{$ticket_main->instance_id|escape:'html'}(不可用)
diff --git a/web/tests/AdminInstanceViewTest.php b/web/tests/AdminInstanceViewTest.php index e77ae6c1..43eb8648 100644 --- a/web/tests/AdminInstanceViewTest.php +++ b/web/tests/AdminInstanceViewTest.php @@ -29,15 +29,18 @@ $common = [ ]; $items = [ array_replace($common, ['id' => '101', 'name' => 'vm-production', - 'public_ip' => '192.0.2.101', 'detail_url' => '/user/cloud/instances/101']), + 'public_ipv4' => '8.8.8.101', 'public_ipv6' => '2404:c140:156:3a::101', + 'detail_url' => '/user/cloud/instances/101']), array_replace($common, ['id' => '102', 'name' => 'vm-network-limited', - 'public_ip' => '192.0.2.102', 'detail_url' => '/user/cloud/instances/102', + 'public_ipv4' => '8.8.8.102', 'public_ipv6' => '2404:c140:156:3a::102', + 'detail_url' => '/user/cloud/instances/102', 'network_status' => 'blocked_traffic', 'traffic_used_bytes' => 107374182400, 'display' => array_replace($common['display'], [ 'traffic' => '100 GiB / 100 GiB', 'network' => '流量耗尽已断网', ])]), array_replace($common, ['id' => '103', 'name' => 'vm-task-failed', - 'public_ip' => '192.0.2.103', 'detail_url' => '/user/cloud/instances/103', + 'public_ipv4' => '8.8.8.103', 'public_ipv6' => '2404:c140:156:3a::103', + 'detail_url' => '/user/cloud/instances/103', 'active_job' => ['id' => '61', 'kind' => 'reinstall', 'completed' => true, 'status' => 'failed', 'blocks_mutation' => true, 'effect_may_have_applied' => true, 'safe_to_resubmit' => false, @@ -58,8 +61,11 @@ $page = [ ]; $detail = [ 'instance' => array_replace($items[0], [ - 'public_ip_cidr' => '192.0.2.101/24', 'gateway' => '192.0.2.1', - 'dns_servers' => ['1.1.1.1', '8.8.8.8'], 'engine_name' => 'vc-1111111111114111', + 'public_ipv4_cidr' => '8.8.8.101/24', 'ipv4_gateway' => '8.8.8.1', + 'public_ipv6_cidr' => '2404:c140:156:3a::101/64', + 'ipv6_gateway' => '2404:c140:156::1', + 'dns_servers' => ['1.1.1.1', '2606:4700:4700::1111'], + 'engine_name' => 'vc-1111111111114111', 'bandwidth_mbps' => 100, 'os_source' => 'cloud_template', 'network_change_supported' => true, 'instance_settings_supported' => true, 'login_name' => 'root', @@ -195,7 +201,8 @@ $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(str_contains($dom->textContent, '192.0.2.101') +$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') && str_contains($dom->textContent, '香港宿主机 A') && str_contains($dom->textContent, '已失败') diff --git a/web/tests/CloudAdminInstanceServiceTest.php b/web/tests/CloudAdminInstanceServiceTest.php index 77df250d..88bbcd55 100644 --- a/web/tests/CloudAdminInstanceServiceTest.php +++ b/web/tests/CloudAdminInstanceServiceTest.php @@ -142,6 +142,13 @@ namespace { $table->integer('created_at'); $table->integer('updated_at'); }); + $schema->create('cloud_public_ips', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('instance_id')->nullable(); + $table->integer('address_family'); + $table->string('address', 45); + $table->string('state')->default('available'); + }); $schema->create('cloud_service_periods', static function (Blueprint $table): void { $table->increments('id'); $table->integer('instance_id'); @@ -232,6 +239,21 @@ namespace { ]); Capsule::table('shop')->insert(['id' => 3, 'name' => 'Small Cloud']); $now = time(); + $publicNetwork = [ + 'contract' => 1, 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'pool_key' => str_repeat('1', 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('2', 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'], + ]; $base = [ 'host_id' => 7, 'user_id' => 1, 'plan_id' => 3, 'status' => 'active', 'service_status' => 'active', 'network_status' => 'active', @@ -244,7 +266,7 @@ namespace { 'vcpu' => 2, 'memory_mib' => 2048, 'disk_gib' => 40, 'os_source' => 'cloud_template', 'os_name' => 'AlmaLinux 10', 'managed' => true, - 'public_ip_cidr' => '198.51.100.10/24', + 'public_network' => $publicNetwork, 'state' => 'running', 'console_port' => 5900, 'password' => 'must-not-expose-spec-password', 'api_token' => 'must-not-expose-api-token', @@ -277,6 +299,16 @@ namespace { $insertInstance(215, [ 'status' => 'delete_failed', 'expires_at' => $now + 2 * 86400, ]); + Capsule::table('cloud_public_ips')->insert([ + ['id' => 1, 'instance_id' => 214, 'address_family' => 4, + 'address' => '8.8.8.74', 'state' => 'assigned'], + ['id' => 2, 'instance_id' => 214, 'address_family' => 6, + 'address' => '2404:c140:156:3a::74', 'state' => 'assigned'], + ['id' => 3, 'instance_id' => null, 'address_family' => 4, + 'address' => '9.9.9.9', 'state' => 'available'], + ['id' => 4, 'instance_id' => 206, 'address_family' => 4, + 'address' => '8.8.4.20', 'state' => 'released'], + ]); Capsule::table('cloud_service_periods')->insert([ 'id' => 1, 'instance_id' => 206, 'user_id' => 2, 'starts_at' => $now - 28 * 86400, 'ends_at' => $now + 2 * 86400, 'status' => 'active', @@ -368,7 +400,7 @@ namespace { && $ids($page['items']) === array_values(array_diff(range(215, 195), [211])), 'Administrator first page lost records above 200, included deleted rows, or sorted ties unstably.'); $assert($page['summary']['total'] === 214 && $page['summary']['expiring'] === 1 - && $page['summary']['network_restricted'] === 2 && $page['summary']['attention'] === 2, + && $page['summary']['network_restricted'] === 3 && $page['summary']['attention'] === 2, 'Database statistics must cover the complete filtered population and preserve state meanings.'); $assert(!isset($page['summary']['running']) && !isset($page['summary']['stopped']), 'Database-only summary fabricated a live power-state count.'); @@ -401,7 +433,9 @@ namespace { 'Empty filtered collections returned stale rows or invalid pagination.'); foreach ([ "tenant's" => [213], '100%_ready' => [213], '%' => [213], '_ready' => [213], - '203.0.113.74' => [214], "' OR 1=1 --" => [], + '8.8.8.74' => [214], '2404:C140:156:3A::74' => [214], + 'c140:156:3a' => [214], '9.9.9.9' => [], '8.8.4.20' => [], + "' OR 1=1 --" => [], '11111111-1111-4111-8111-000000000214' => [214], 'bob@example.test' => [206], ] as $query => $expected) { @@ -409,6 +443,11 @@ namespace { $assert($ids($searched['items']) === $expected, 'Search must bind quotes, escape SQL wildcards, and correctly match IP/UUID/account: ' . $query); } + $scopedIpSearch = CloudAdminInstanceService::page($admin, [ + 'q' => '8.8.8.74', 'user_id' => '2', + ]); + $assert($scopedIpSearch['items'] === [], + 'Public-address search escaped the exact owner filter through its ledger subquery.'); foreach (['soon' => [206], 'expired' => [207], 'exempt' => [208]] as $mode => $expected) { $filtered = CloudAdminInstanceService::page($admin, ['expiry' => $mode]); $assert($ids($filtered['items']) === $expected, @@ -416,14 +455,32 @@ namespace { } $exempt = CloudAdminInstanceService::page($admin, ['service_status' => 'exempt']); $assert($ids($exempt['items']) === [208], 'Exact service-status filter was ignored.'); - foreach (['network', 'jobs'] as $mode) { + foreach (['network' => [214, 210, 209], 'jobs' => [210, 209]] as $mode => $expected) { $attention = CloudAdminInstanceService::page($admin, ['attention' => $mode]); - $assert($ids($attention['items']) === [210, 209], + $assert($ids($attention['items']) === $expected, 'Attention filter included deleted/old failed jobs or omitted unresolved jobs/network restrictions.'); foreach ($attention['items'] as $item) { $assert($item['state'] === 'unknown', 'Business/network/job state was mistaken for live VM power state.'); } } + $networkPagingFixture = range(180, 199); + Capsule::table('cloud_instances')->whereIn('id', $networkPagingFixture) + ->update(['spec_json' => '{invalid-network-snapshot']); + $networkPageOne = CloudAdminInstanceService::page($admin, [ + 'attention' => 'network', 'per_page' => '20', 'page' => '1', + ]); + $networkPageTwo = CloudAdminInstanceService::page($admin, [ + 'attention' => 'network', 'per_page' => '20', 'page' => '2', + ]); + $assert($ids($networkPageOne['items']) + === array_merge([214, 210, 209], range(199, 183)) + && $ids($networkPageTwo['items']) === [182, 181, 180] + && $networkPageOne['pagination']['total'] === 23 + && $networkPageOne['summary']['network_restricted'] === 23 + && $networkPageTwo['pagination']['total'] === 23, + 'Canonical network-attention classification drifted between summary, filter and pagination.'); + Capsule::table('cloud_instances')->whereIn('id', $networkPagingFixture) + ->update(['spec_json' => $base['spec_json']]); foreach (['page', 'per_page', 'q', 'user_id', 'host_id', 'service_status', 'expiry', 'attention', 'sort'] as $key) { $expectError(static fn () => CloudAdminInstanceService::page($admin, [$key => ['1']]), 400, 'Array-valued filter must be rejected: ' . $key); @@ -452,6 +509,11 @@ namespace { $assert((string) $detail['instance']['host_id'] === '8' && $detail['instance']['host_name'] === 'Tokyo 08', 'Administrator detail lost the physical placement needed for operations.'); + $assert(($detail['instance']['public_ipv4'] ?? null) === '8.8.8.10' + && ($detail['instance']['public_ipv6'] ?? null) + === '2404:c140:156:3a::10' + && ($detail['instance']['public_network_valid'] ?? null) === true, + 'Administrator detail did not project the canonical dual-stack identity.'); $assert((int) $detail['instance']['active_job']['id'] === 26 && $detail['instance']['active_job']['completed'] === false && $detail['instance']['active_job']['status'] === 'active' @@ -646,7 +708,13 @@ namespace { } $unsupported = CloudAdminInstanceService::detail($admin, '214'); $assert($unsupported['instance']['network_change_supported'] === false - && $unsupported['instance']['instance_settings_supported'] === false, + && $unsupported['instance']['instance_settings_supported'] === false + && $unsupported['instance']['can_manage'] === false + && $unsupported['instance']['public_network_valid'] === false + && $unsupported['instance']['public_ipv4'] === '' + && $unsupported['instance']['public_ipv6'] === '' + && $unsupported['instance']['network_status'] + === 'configuration_invalid', 'Incomplete legacy metadata exposed administrator mutation controls.'); Capsule::table('cloud_instances')->where('id', 205)->update(['status' => 'deleting']); $inactive = CloudAdminInstanceService::detail($admin, '205'); diff --git a/web/tests/CloudAdminVpcControlServiceTest.php b/web/tests/CloudAdminVpcControlServiceTest.php index 4ee5d641..aaea63e2 100644 --- a/web/tests/CloudAdminVpcControlServiceTest.php +++ b/web/tests/CloudAdminVpcControlServiceTest.php @@ -187,13 +187,28 @@ Capsule::table('cloud_vpcs')->insert([ 'state' => 'degraded', 'desired_revision' => 4, 'deleted_at' => null, 'created_at' => 11, 'updated_at' => 30], ]); +$publicNetwork = static fn (int $suffix): array => ['public_network' => [ + 'contract' => 1, 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'pool_key' => str_repeat('1', 32), 'pool_cidr' => '8.8.8.0/24', + 'address_cidr' => '8.8.8.' . $suffix . '/24', + 'gateway' => '8.8.8.1', 'gateway_on_link' => false, + ], + 'ipv6' => [ + 'pool_key' => str_repeat('2', 32), + 'pool_cidr' => '2404:c140:156:3a::/64', + 'address_cidr' => '2404:c140:156:3a::' . $suffix . '/64', + 'gateway' => '2404:c140:156::1', 'gateway_on_link' => true, + ], + 'dns_servers' => ['1.1.1.1', '2606:4700:4700::1111'], +]]; Capsule::table('cloud_instances')->insert([ ['id' => 11, 'uuid' => '11111111-1111-4111-8111-111111111111', 'host_id' => 1, 'user_id' => 7, 'name' => 'vm-prod', - 'spec_json' => json_encode(['public_ip' => '192.0.2.11'])], + 'spec_json' => json_encode($publicNetwork(11), JSON_THROW_ON_ERROR)], ['id' => 12, 'uuid' => '22222222-2222-4222-8222-222222222222', 'host_id' => 1, 'user_id' => 8, 'name' => 'vm-stage', - 'spec_json' => json_encode(['public_ip_cidr' => '192.0.2.12/24'])], + 'spec_json' => json_encode($publicNetwork(12), JSON_THROW_ON_ERROR)], ]); Capsule::table('cloud_vpc_ports')->insert([ ['id' => 1, 'port_key' => str_repeat('3', 32), 'vpc_id' => 1, @@ -285,7 +300,8 @@ $assert($search['pagination']['total'] === 1 $detail = CloudAdminVpcControlService::detail($actor, 1); $assert($detail['vpc']['name'] === 'production' && count($detail['ports']) === 1 - && $detail['ports'][0]['public_ip'] === '192.0.2.11' + && $detail['ports'][0]['public_ipv4'] === '8.8.8.11' + && $detail['ports'][0]['public_ipv6'] === '2404:c140:156:3a::11' && $detail['host_states'][0]['ready'] === true && $detail['batches'] === [] && $detail['jobs'] === [], 'Healthy VPC detail projection is incomplete.'); diff --git a/web/tests/CloudDualStackInstanceUiContractTest.php b/web/tests/CloudDualStackInstanceUiContractTest.php new file mode 100644 index 00000000..332a3b03 --- /dev/null +++ b/web/tests/CloudDualStackInstanceUiContractTest.php @@ -0,0 +1,86 @@ + \$this->vmIp(\$vm, 4)") + && str_contains($controller, "'ipv6' => \$this->vmIp(\$vm, 6)") + && str_contains($controller, + "=== 'configuration_invalid') {\n return ['网络配置异常'"), + 'The user page DTO does not expose separate IPv4 and IPv6 values.'); +$assert(str_contains($instances, '公网 IPv4') + && str_contains($instances, '公网 IPv6') + && str_contains($instances, 'data-copy-label="公网 IPv4"') + && str_contains($instances, 'data-copy-label="公网 IPv6"'), + 'The instance list lacks separate dual-stack labels or copy controls.'); +$assert(str_contains($styles, + '.vm-table td[data-label="公网地址"]{grid-column:1/-1}') + && str_contains($styles, '.vm-public-addresses{min-width:0;width:100%}'), + 'The dual-stack instance list does not preserve a full-width mobile address row.'); +$assert(str_contains($detail, 'id="vm-detail-ipv4"') + && str_contains($detail, 'id="vm-detail-ipv6"') + && str_contains($detail, 'id="vm-detail-ipv4-copy"') + && str_contains($detail, 'id="vm-detail-ipv6-copy"'), + 'The instance detail lacks separate dual-stack fields or copy controls.'); +$assert(str_contains($instanceJs, 'public_ipv4') + && str_contains($instanceJs, 'public_ipv6') + && !str_contains($instanceJs, + 'return vm.public_network_valid !== true') + && str_contains($detailJs, 'vm-detail-ipv${family}-copy') + && str_contains($detailJs, 'for (const family of [4, 6])') + && !str_contains($detailJs, + 'return vm.public_network_valid !== true') + && str_contains($runtimeJs, + "configuration_invalid: ['网络配置异常,请联系管理员', 'stopped']"), + 'The user JavaScript does not retain or render both public address families.'); + +$assert(str_contains($adminTemplate, '公网 IPv4') + && str_contains($adminTemplate, '公网 IPv6') + && str_contains($adminJs, "['公网 IPv4'") + && str_contains($adminJs, "['公网 IPv6'"), + 'The administrator list/detail does not render dual-stack public addresses.'); +$assert(str_contains($vpcTemplate, '公网 IPv4') + && str_contains($vpcTemplate, '公网 IPv6') + && str_contains($vpcJs, 'publicIpv6'), + 'The VPC member view does not show both public families.'); +$assert(str_contains($ticketUser, '$ticket_instance->public_ipv4') + && str_contains($ticketUser, '$ticket_instance->public_ipv6') + && str_contains($ticketAdmin, '$ticket_instance->public_ipv4') + && str_contains($ticketAdmin, '$ticket_instance->public_ipv6'), + 'Ticket-linked instance summaries do not show both public families.'); + +$assert(!str_contains($adminService, 'JSON_EXTRACT(') + && str_contains($adminService, 'CloudInstanceMetadata::publicSpec(') + && str_contains($adminService, + "from('cloud_public_ips as searched_public_ip')") + && str_contains($adminService, + "where('searched_public_ip.state', 'assigned')"), + 'Administrator search/read-model still depends on dialect-specific JSON or flat IP parsing.'); + +echo "Cloud dual-stack instance UI contracts passed.\n"; diff --git a/web/tests/CloudInstanceMetadataTest.php b/web/tests/CloudInstanceMetadataTest.php index 6fcd3807..14209cdc 100644 --- a/web/tests/CloudInstanceMetadataTest.php +++ b/web/tests/CloudInstanceMetadataTest.php @@ -86,6 +86,28 @@ $schema->create('cloud_jobs', static function (Blueprint $table): void { $firstUuid = '11111111-1111-4111-8111-111111111111'; $secondUuid = '22222222-2222-4222-8222-222222222222'; +$publicNetwork = [ + 'contract' => 1, + 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'pool_key' => str_repeat('1', 32), + 'pool_cidr' => '8.8.8.0/24', + 'address_cidr' => '8.8.8.20/24', + 'gateway' => '8.8.8.1', + 'gateway_on_link' => false, + ], + 'ipv6' => [ + 'pool_key' => str_repeat('2', 32), + 'pool_cidr' => '2404:c140:156:3a::/64', + 'address_cidr' => '2404:c140:156:3a::20/64', + 'gateway' => '2404:c140:156::1', + 'gateway_on_link' => true, + ], + 'dns_servers' => ['1.1.1.1', '2606:4700:4700::1111'], +]; +$publicNetworkProjection = CloudInstanceMetadata::publicSpec([ + 'public_network' => $publicNetwork, +]); foreach ([1 => $firstUuid, 2 => $secondUuid] as $id => $uuid) { Capsule::table('cloud_instances')->insert([ 'id' => $id, @@ -102,6 +124,7 @@ foreach ([1 => $firstUuid, 2 => $secondUuid] as $id => $uuid) { 'state' => 'running', 'console_port' => 5999, 'password_available' => true, + 'public_network' => $publicNetwork, ], JSON_THROW_ON_ERROR), 'updated_at' => 1, ]); @@ -138,13 +161,14 @@ $live = [ 'unexpected' => ['private_key' => 'must-not-persist'], ]; -$view = CloudInstanceMetadata::publicView([ +$view = CloudInstanceMetadata::publicView(array_merge([ 'id' => '1', 'api_id' => '1', 'uuid' => $firstUuid, 'name' => 'database-name', 'disk_gib' => 20, -], $live); +], $publicNetworkProjection), $live); $assert($view['id'] === '1' && $view['uuid'] === $firstUuid && $view['name'] === 'database-name' - && $view['public_ip_cidr'] === '203.0.113.18/28' + && $view['public_ipv4_cidr'] === '8.8.8.20/24' + && $view['public_ipv6'] === '2404:c140:156:3a::20' && $view['os_source'] === 'cloud_template' && $view['os_name'] === 'AlmaLinux 10' && $view['login_name'] === 'root' @@ -186,12 +210,12 @@ $assert(($publicSpec['region'] ?? null) === 'Tokyo' && !array_key_exists('line_name', $publicSpec), 'The public specification exposed physical placement or internal sales topology.'); -$mismatch = CloudInstanceMetadata::publicView([ +$mismatch = CloudInstanceMetadata::publicView(array_merge([ 'id' => '1', 'uuid' => $firstUuid, 'name' => 'database-name', - 'public_ip_cidr' => '198.51.100.2/24', -], array_replace($live, ['uuid' => $secondUuid])); +], $publicNetworkProjection), array_replace($live, ['uuid' => $secondUuid])); $assert($mismatch['name'] === 'database-name' - && $mismatch['public_ip_cidr'] === '198.51.100.2/24' + && $mismatch['public_ipv4_cidr'] === '8.8.8.20/24' + && $mismatch['public_ipv6'] === '2404:c140:156:3a::20' && !isset($mismatch['os_name'], $mismatch['agent_metadata_version']), 'A mismatched live UUID decorated another database instance.'); @@ -214,12 +238,14 @@ $phpOwnedMerge = CloudInstanceMetadata::merge([ 'os_name' => 'AlmaLinux 10', 'login_name' => 'root', 'managed' => true, + 'public_network' => $publicNetwork, ], $goWireLive); $assert(($phpOwnedMerge['os_source'] ?? null) === 'cloud_template' && ($phpOwnedMerge['os_name'] ?? null) === 'AlmaLinux 10' && ($phpOwnedMerge['login_name'] ?? null) === 'root' && ($phpOwnedMerge['managed'] ?? null) === true - && ($phpOwnedMerge['public_ip_cidr'] ?? null) === '203.0.113.18/28' + && ($phpOwnedMerge['public_network'] ?? null) === $publicNetwork + && !isset($phpOwnedMerge['public_ip_cidr']) && ($phpOwnedMerge['agent_metadata_version'] ?? null) === 1 && !isset($phpOwnedMerge['disks'][0]['source']), 'A real Go VMMetadata response discarded PHP-owned template metadata.'); @@ -263,7 +289,8 @@ $assert($first['plan_id'] === 91 && $first['validity_days'] === 30 && $first['traffic_quota_bytes'] === 1099511627776 && $first['template_id'] === 'alma10-template' && $first['agent_metadata_version'] === 1 - && $first['public_ip_cidr'] === '203.0.113.18/28' + && $first['public_network'] === $publicNetwork + && !isset($first['public_ip_cidr']) && $first['login_name'] === 'root' && $first['guest_hostname'] === 'node-01.example.test' && $first['disks'] === [ diff --git a/web/tests/CloudInstancePageServiceTest.php b/web/tests/CloudInstancePageServiceTest.php index acde6e1f..915e252f 100644 --- a/web/tests/CloudInstancePageServiceTest.php +++ b/web/tests/CloudInstancePageServiceTest.php @@ -211,6 +211,25 @@ namespace { 'id' => 7, 'region' => 'internal-host-location', 'country_code' => 'ZZ', ]); $now = time(); + $publicNetwork = [ + 'contract' => 1, + 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'pool_key' => str_repeat('1', 32), + 'pool_cidr' => '8.8.8.0/24', + 'address_cidr' => '8.8.8.20/24', + 'gateway' => '8.8.8.1', + 'gateway_on_link' => false, + ], + 'ipv6' => [ + 'pool_key' => str_repeat('2', 32), + 'pool_cidr' => '2404:c140:156:3a::/64', + 'address_cidr' => '2404:c140:156:3a::20/64', + 'gateway' => '2404:c140:156::1', + 'gateway_on_link' => true, + ], + 'dns_servers' => ['1.1.1.1', '2606:4700:4700::1111'], + ]; $common = [ 'host_id' => 7, 'current_period_id' => null, 'status' => 'active', 'service_status' => 'active', 'network_status' => 'active', @@ -230,6 +249,7 @@ namespace { 'resource_pool_name' => 'internal-resource-pool', 'region' => 'Tokyo', 'country_code' => 'JP', + 'public_network' => $publicNetwork, 'disk_gib' => 40, 'disks' => [[ 'capacity_gib' => 40, @@ -312,6 +332,10 @@ namespace { 'Instance list SSR exposed an internal placement identifier.'); $assert($page['vms'][0]['region'] === 'Tokyo', 'Instance list did not use the immutable selling-region snapshot.'); + $assert($page['vms'][0]['public_network_valid'] === true + && $page['vms'][0]['public_ipv4'] === '8.8.8.20' + && $page['vms'][0]['public_ipv6'] === '2404:c140:156:3a::20', + 'Instance list omitted the frozen dual-stack public identity.'); $assert($page['vms'][0]['state'] === 'unknown', 'Persisted specification power state was trusted before a live UUID check.'); $assert(count($page['vms'][0]['disks']) === 1 @@ -347,6 +371,11 @@ namespace { $assert($ownedDetail['region'] === 'Tokyo' && $ownedDetail['country_code'] === 'JP', 'Instance detail did not use its safe region and country snapshot.'); + $assert($ownedDetail['public_network_valid'] === true + && $ownedDetail['public_network']['ipv4']['address'] === '8.8.8.20' + && $ownedDetail['public_network']['ipv6']['address'] + === '2404:c140:156:3a::20', + 'Instance detail omitted its canonical dual-stack projection.'); $assert($ownedDetail['can_operate'] && $ownedDetail['can_delete'] && $ownedDetail['can_rename'] && $ownedDetail['password_available'] && $ownedDetail['can_renew'], @@ -645,6 +674,54 @@ namespace { && $managed['can_view_credential'] && $managed['password_available'] && !$managed['can_renew'], 'Super administrator capabilities no longer match the legacy VM boundary.'); + $validForeignSpec = (string) Capsule::table('cloud_instances') + ->where('id', 2)->value('spec_json'); + Capsule::table('cloud_instances')->where('id', 2)->update([ + 'spec_json' => json_encode([ + 'os_source' => 'cloud_template', + 'public_ip' => '8.8.8.99', + 'public_ip_cidr' => '8.8.8.99/24', + ], JSON_THROW_ON_ERROR), + ]); + Capsule::table('cloud_instance_runtime')->insert([ + 'instance_id' => 2, + 'host_id' => 8, + 'uuid' => '22222222-2222-4222-8222-222222222222', + 'power_state' => 'running', + 'sync_state' => 'ok', + 'last_success_at' => $now - 5, + 'last_attempt_at' => $now - 5, + 'revision' => 1, + 'last_error_code' => '', + 'created_at' => $now - 10, + 'updated_at' => $now - 5, + ]); + $invalidNetworkPage = CloudInstancePageService::forActor( + $global, + 1, + 20 + ); + $invalidNetworkRow = collect($invalidNetworkPage['vms']) + ->firstWhere('id', '2'); + $assert(($invalidNetworkRow['network_status'] ?? null) + === 'configuration_invalid' + && $invalidNetworkPage['stats']['running'] === 1 + && $invalidNetworkPage['stats']['other'] === 1, + 'Invalid canonical networking disappeared from first paint or was counted as running.'); + $invalidNetwork = CloudInstancePageService::detailForActor($global, 2); + $assert($invalidNetwork['public_network_valid'] === false + && $invalidNetwork['public_network'] === null + && $invalidNetwork['network_status'] === 'configuration_invalid' + && $invalidNetwork['can_operate'] === false + && !isset($invalidNetwork['public_ip'], $invalidNetwork['public_ip_cidr']), + 'A missing canonical public-network snapshot did not fail closed.'); + $invalidStatus = CloudInstancePageService::statusForActor($global, 2); + $assert($invalidStatus['network_status'] === 'configuration_invalid' + && $invalidStatus['can_operate'] === false, + 'The mutable status poll reopened an instance with invalid public networking.'); + Capsule::table('cloud_instances')->where('id', 2)->update([ + 'spec_json' => $validForeignSpec, + ]); Capsule::connection('default')->flushQueryLog(); Capsule::connection('default')->enableQueryLog(); $mutable = CloudInstancePageService::statusForActor($global, 2); diff --git a/web/tests/CloudInstancePageSsrContractTest.php b/web/tests/CloudInstancePageSsrContractTest.php index a31a9b44..0e5d1805 100644 --- a/web/tests/CloudInstancePageSsrContractTest.php +++ b/web/tests/CloudInstancePageSsrContractTest.php @@ -175,7 +175,10 @@ $assert(str_contains($statusApi, 'CloudInstancePageService::statusForActor') 'Single VM status must keep its cache fallback and bounded, UUID-checked, write-through live path.'); $vmData = $section($api, 'private function vmData(', 'public function vms('); $assert(str_contains($vmData, "'name' => (string) \$instance->name") - && str_contains($vmData, '$this->publicVmMetadata($instance') + && str_contains($vmData, '$publicSpec = $this->publicVmSpec($spec)') + && str_contains($vmData, '$this->publicVmMetadata(') + && str_contains($vmData, '$publicNetworkValid') + && str_contains($vmData, "'configuration_invalid'") && str_contains($api, 'private function publicVmMetadata(') && str_contains($api, 'private function publicVmSpec(') && str_contains($api, 'private function publicMetrics(') diff --git a/web/tests/CloudInstancePublicNetworkProjectionTest.php b/web/tests/CloudInstancePublicNetworkProjectionTest.php new file mode 100644 index 00000000..3fd93bd0 --- /dev/null +++ b/web/tests/CloudInstancePublicNetworkProjectionTest.php @@ -0,0 +1,170 @@ + 1, + 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'pool_key' => str_repeat('1', 32), + 'pool_cidr' => '8.8.8.0/24', + 'address_cidr' => '8.8.8.20/24', + 'gateway' => '8.8.8.1', + 'gateway_on_link' => false, + ], + 'ipv6' => [ + 'pool_key' => str_repeat('2', 32), + 'pool_cidr' => '2404:c140:156:3a::/64', + 'address_cidr' => '2404:c140:156:3a::20/64', + 'gateway' => '2404:c140:156::1', + 'gateway_on_link' => true, + ], + 'dns_servers' => ['1.1.1.1', '2606:4700:4700::1111'], +]; + +$projection = CloudInstancePublicNetworkProjection::fromSpec([ + 'public_network' => $snapshot, + // Flat values are attacker-controlled legacy input and must never win. + 'public_ip' => '9.9.9.9', + 'public_ip_cidr' => '9.9.9.9/32', + 'gateway' => '9.9.9.1', +]); + +$assert(($projection['public_network_valid'] ?? null) === true, + 'A canonical dual-stack snapshot was not accepted.'); +$assert(($projection['public_network'] ?? null) === [ + 'contract' => 1, + 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'address_cidr' => '8.8.8.20/24', + 'address' => '8.8.8.20', + 'pool_cidr' => '8.8.8.0/24', + 'gateway' => '8.8.8.1', + 'gateway_on_link' => false, + ], + 'ipv6' => [ + 'address_cidr' => '2404:c140:156:3a::20/64', + 'address' => '2404:c140:156:3a::20', + 'pool_cidr' => '2404:c140:156:3a::/64', + 'gateway' => '2404:c140:156::1', + 'gateway_on_link' => true, + ], + 'dns_servers' => ['1.1.1.1', '2606:4700:4700::1111'], +], 'The browser projection was not derived exactly from the canonical snapshot.'); +$assert(($projection['public_ipv4'] ?? null) === '8.8.8.20' + && ($projection['public_ipv4_cidr'] ?? null) === '8.8.8.20/24' + && ($projection['public_ipv6'] ?? null) === '2404:c140:156:3a::20' + && ($projection['public_ipv6_cidr'] ?? null) === '2404:c140:156:3a::20/64' + && ($projection['public_ip'] ?? null) === '8.8.8.20' + && ($projection['public_ip_cidr'] ?? null) === '8.8.8.20/24' + && ($projection['gateway'] ?? null) === '8.8.8.1' + && ($projection['dns_servers'] ?? null) + === ['1.1.1.1', '2606:4700:4700::1111'], + 'Presentation aliases were not derived from the snapshot in one place.'); + +foreach ([ + [], + ['public_ip' => '8.8.8.20', 'public_ip_cidr' => '8.8.8.20/24'], + ['public_network' => array_replace($snapshot, [ + 'ipv6' => array_replace($snapshot['ipv6'], [ + 'address_cidr' => 'not-an-address', + ]), + ])], +] as $invalidSpec) { + $invalid = CloudInstancePublicNetworkProjection::fromSpec($invalidSpec); + $assert($invalid === [ + 'public_network_valid' => false, + 'public_network' => null, + ], 'A missing or damaged canonical snapshot did not fail closed.'); +} + +$publicSpec = CloudInstanceMetadata::publicSpec([ + 'region' => 'Hong Kong', + 'public_network' => $snapshot, + 'public_ip' => '9.9.9.9', + 'public_ip_cidr' => '9.9.9.9/32', +]); +$assert(($publicSpec['region'] ?? null) === 'Hong Kong' + && ($publicSpec['public_network_valid'] ?? null) === true + && ($publicSpec['public_ipv4'] ?? null) === '8.8.8.20' + && ($publicSpec['public_ipv6'] ?? null) === '2404:c140:156:3a::20' + && ($publicSpec['public_ip'] ?? null) === '8.8.8.20', + 'The public instance specification did not use the canonical projection.'); + +$closedSpec = CloudInstanceMetadata::publicSpec([ + 'region' => 'Hong Kong', + 'public_ip' => '8.8.8.20', + 'public_ip_cidr' => '8.8.8.20/24', +]); +$assert(($closedSpec['public_network_valid'] ?? null) === false + && array_key_exists('public_network', $closedSpec) + && $closedSpec['public_network'] === null + && !isset($closedSpec['public_ip'], $closedSpec['public_ip_cidr']), + 'Legacy flat fields were trusted after the canonical snapshot was missing.'); + +$merged = CloudInstanceMetadata::merge([ + 'plan_id' => 5, + 'public_network' => $snapshot, + 'public_ip' => '9.9.9.9', + 'public_ip_cidr' => '9.9.9.9/32', + 'gateway' => '9.9.9.1', + 'dns_servers' => ['9.9.9.9'], +], [ + 'public_ip_cidr' => '1.1.1.20/24', + 'public_network' => array_replace($snapshot, [ + 'network_selector' => 'bridge:evil0', + ]), + 'vcpu' => 4, +]); +$assert(($merged['public_network'] ?? null) === $snapshot + && ($merged['vcpu'] ?? null) === 4 + && !isset($merged['public_ip'], $merged['public_ip_cidr'], + $merged['gateway'], $merged['dns_servers']), + 'Agent or legacy flat metadata replaced or duplicated the frozen snapshot.'); + +$view = CloudInstanceMetadata::publicView(array_merge($publicSpec, [ + 'id' => '7', + 'api_id' => '7', + 'uuid' => '77777777-7777-4777-8777-777777777777', + 'name' => 'dual-stack-vm', +]), [ + 'uuid' => '77777777-7777-4777-8777-777777777777', + 'public_ip_cidr' => '1.1.1.20/24', + 'vcpu' => 8, +]); +$assert(($view['public_network_valid'] ?? null) === true + && ($view['public_ipv4'] ?? null) === '8.8.8.20' + && ($view['public_ipv6'] ?? null) === '2404:c140:156:3a::20' + && ($view['vcpu'] ?? null) === 8, + 'The live metadata view discarded or replaced the PHP-owned network projection.'); + +$tamperedAliases = CloudInstanceMetadata::publicView(array_merge($publicSpec, [ + 'id' => '7', 'uuid' => '77777777-7777-4777-8777-777777777777', + 'name' => 'dual-stack-vm', 'public_ipv4' => '9.9.9.9', + 'public_ipv6' => '2606:4700:4700::9999', +]), []); +$assert(($tamperedAliases['public_ipv4'] ?? null) === '8.8.8.20' + && ($tamperedAliases['public_ipv6'] ?? null) === '2404:c140:156:3a::20', + 'Cached aliases were trusted instead of being re-derived by the projection helper.'); + +$damagedProjection = $publicSpec; +$damagedProjection['public_network']['ipv6']['address'] = '2606:4700:4700::9999'; +$closedView = CloudInstanceMetadata::publicView(array_merge($damagedProjection, [ + 'id' => '7', 'uuid' => '77777777-7777-4777-8777-777777777777', + 'name' => 'dual-stack-vm', +]), []); +$assert($closedView['public_network_valid'] === false + && $closedView['public_network'] === null + && !isset($closedView['public_ipv4'], $closedView['public_ipv6']), + 'A damaged cached network projection was not rejected before display.'); + +echo "Cloud instance public-network projection tests passed.\n"; diff --git a/web/tests/CloudLegacyVmApiProjectionTest.php b/web/tests/CloudLegacyVmApiProjectionTest.php new file mode 100644 index 00000000..47ae92a8 --- /dev/null +++ b/web/tests/CloudLegacyVmApiProjectionTest.php @@ -0,0 +1,119 @@ + 1, + 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'pool_key' => str_repeat('1', 32), + 'pool_cidr' => '8.8.4.0/24', + 'address_cidr' => '8.8.4.10/24', + 'gateway' => '8.8.4.1', + 'gateway_on_link' => false, + ], + 'ipv6' => [ + 'pool_key' => str_repeat('2', 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'], +]; + +$instance = static function (int $id, array $spec): CloudInstance { + $row = new CloudInstance(); + $row->id = $id; + $row->uuid = sprintf('11111111-1111-4111-8111-%012d', $id); + $row->host_id = 1; + $row->user_id = 7; + $row->name = 'vm-' . $id; + $row->status = 'active'; + $row->service_status = 'exempt'; + $row->network_status = 'active'; + $row->expires_at = null; + $row->spec_json = json_encode($spec, JSON_THROW_ON_ERROR); + $row->traffic_download_bytes = 0; + $row->traffic_upload_bytes = 0; + $row->traffic_quota_bytes = 0; + $row->renewal_days = 0; + $row->renewal_traffic_bytes = 0; + $row->renewal_price = null; + $row->sealed_credential = null; + $row->created_at = $row->updated_at = time(); + return $row; +}; + +$controller = new CloudApiController(); +$method = new ReflectionMethod($controller, 'vmData'); +$actor = [ + 'user_id' => 7, + 'is_admin' => false, + 'is_super_admin' => false, + 'can_manage' => false, +]; +$context = static fn (CloudInstance $row): array => [ + 'vm' => [ + 'uuid' => (string) $row->uuid, + 'state' => 'running', + // Authenticated Agent metadata still cannot replace the immutable + // panel snapshot or revive an invalid one. + 'public_ip' => '203.0.113.250', + 'public_network' => ['forged' => true], + ], + 'period' => null, + 'future_periods' => 0, + 'traffic_accounting' => [ + 'traffic_accounting_mode' => 'legacy', + 'traffic_pool' => null, + ], +]; + +$valid = $instance(1, [ + 'os_source' => 'cloud_template', + 'public_network' => $canonicalNetwork, +]); +$validDto = $method->invoke($controller, $valid, $actor, $context($valid)); +$assert(($validDto['public_network_valid'] ?? null) === true + && ($validDto['public_ipv4'] ?? null) === '8.8.4.10' + && ($validDto['public_ipv6'] ?? null) === '2404:c140:156:3a::10' + && ($validDto['public_ip'] ?? null) === '8.8.4.10' + && ($validDto['network_status'] ?? null) === 'active' + && ($validDto['can_operate'] ?? null) === true, + 'The legacy VM API did not preserve the validated dual-stack projection.'); + +$invalid = $instance(2, [ + 'os_source' => 'cloud_template', + 'public_ip' => '192.0.2.20', + 'public_ip_cidr' => '192.0.2.20/24', + 'gateway' => '192.0.2.1', +]); +$invalidDto = $method->invoke( + $controller, + $invalid, + $actor, + $context($invalid) +); +$assert(($invalidDto['public_network_valid'] ?? null) === false + && array_key_exists('public_network', $invalidDto) + && $invalidDto['public_network'] === null + && !array_key_exists('public_ipv4', $invalidDto) + && !array_key_exists('public_ipv6', $invalidDto) + && ($invalidDto['network_status'] ?? null) === 'configuration_invalid' + && ($invalidDto['can_operate'] ?? null) === false, + 'The legacy VM API trusted flat/Agent network fields or left invalid network mutations enabled.'); + +echo "Legacy VM API public-network projection behavior passed.\n"; diff --git a/web/tests/CloudOperationErrorCatalogTest.php b/web/tests/CloudOperationErrorCatalogTest.php index dcaca8c0..e7962ce8 100644 --- a/web/tests/CloudOperationErrorCatalogTest.php +++ b/web/tests/CloudOperationErrorCatalogTest.php @@ -232,13 +232,31 @@ $assert($vpcBatchResult === [ 'VPC membership batch result was hidden, inconsistent, or leaked into other task kinds.'); $publicSpec = CloudInstanceMetadata::publicSpec([ - 'plan_name' => 'Basic', 'public_ip' => '203.0.113.10', + 'plan_name' => 'Basic', + 'public_network' => [ + 'contract' => 1, + 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'pool_key' => str_repeat('1', 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('2', 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'], + ], 'region' => str_repeat('x', 500), 'memory_mib' => 'not-a-number', 'host_private_path' => '/srv/libvirt/secret.qcow2', 'agent_debug' => 'libvirt traceback', ]); $publicJson = json_encode($publicSpec, JSON_UNESCAPED_UNICODE); -$assert(isset($publicSpec['plan_name'], $publicSpec['public_ip']) +$assert(isset($publicSpec['plan_name'], $publicSpec['public_network']) + && ($publicSpec['public_ipv4'] ?? null) === '8.8.8.10' + && ($publicSpec['public_ipv6'] ?? null) === '2404:c140:156:3a::10' && !isset($publicSpec['region'], $publicSpec['memory_mib']) && !isset($publicSpec['host_private_path'], $publicSpec['agent_debug']) && !str_contains($publicJson, '/srv/libvirt'), diff --git a/web/tests/CloudVpcPortWorkflowTest.php b/web/tests/CloudVpcPortWorkflowTest.php index da35058c..5d22f650 100644 --- a/web/tests/CloudVpcPortWorkflowTest.php +++ b/web/tests/CloudVpcPortWorkflowTest.php @@ -29,6 +29,7 @@ namespace { use App\Models\CloudVpcMembershipBatchItem; use App\Models\CloudVpcPort; use App\Services\Cloud\CloudSecrets; + use App\Services\Cloud\CloudError; use App\Services\Cloud\CloudJobService; use App\Services\Cloud\CloudOperationRecoveryIdentity; use App\Services\Cloud\CloudOperationRecoveryService; @@ -43,6 +44,20 @@ namespace { throw new RuntimeException($message); } }; + $expectError = static function ( + callable $callback, + int $status, + string $message + ) use ($assert): void { + try { + $callback(); + } catch (CloudError $error) { + $assert($error->httpStatus === $status, + $message . ' Unexpected status: ' . $error->httpStatus); + return; + } + throw new RuntimeException($message); + }; $terminalize = static function (CloudJob $job): void { $now = time(); $job->phase = 'terminal'; @@ -292,18 +307,54 @@ namespace { $instance->resource_pool_id = 1; $instance->name = 'vm-' . $id; $instance->status = 'active'; $instance->service_status = 'exempt'; $instance->network_status = 'active'; $instance->expires_at = null; - $networkSpec = $id === 2 - ? ['public_ip' => '203.0.113.12'] - : ['public_ip_cidr' => '203.0.113.11/24']; - $instance->spec_json = json_encode(array_merge([ + $instance->spec_json = json_encode([ 'os_source' => 'cloud_template', - ], $networkSpec), JSON_THROW_ON_ERROR); + 'public_network' => [ + 'contract' => 1, 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'pool_key' => str_repeat('1', 32), + 'pool_cidr' => '8.8.8.0/24', + 'address_cidr' => '8.8.8.' . (10 + $id) . '/24', + 'gateway' => '8.8.8.1', 'gateway_on_link' => false, + ], + 'ipv6' => [ + 'pool_key' => str_repeat('2', 32), + 'pool_cidr' => '2404:c140:156:3a::/64', + 'address_cidr' => '2404:c140:156:3a::' . (10 + $id) . '/64', + 'gateway' => '2404:c140:156::1', 'gateway_on_link' => true, + ], + 'dns_servers' => ['1.1.1.1', '2606:4700:4700::1111'], + ], + ], JSON_THROW_ON_ERROR); $instance->created_at = $instance->updated_at = time(); $instance->save(); return $instance; }; $target = $newInstance(1, 1); $peer = $newInstance(2, 2); + $invalidNetwork = $newInstance(3, 1); + $invalidNetwork->spec_json = json_encode([ + 'os_source' => 'cloud_template', + // Flat aliases are intentionally untrusted and must not authorize a + // new VPC port when the canonical snapshot is absent. + 'public_ip' => '8.8.8.13', + 'public_ip_cidr' => '8.8.8.13/24', + 'gateway' => '8.8.8.1', + ], JSON_THROW_ON_ERROR); + $invalidNetwork->save(); + $missingSource = $newInstance(4, 1); + $missingSourceSpec = json_decode( + (string) $missingSource->spec_json, + true, + 512, + JSON_THROW_ON_ERROR + ); + unset($missingSourceSpec['os_source']); + $missingSource->spec_json = json_encode( + $missingSourceSpec, + JSON_THROW_ON_ERROR + ); + $missingSource->save(); $vpc = new CloudVpc(); $vpc->id = 1; $vpc->vpc_key = str_repeat('a', 32); $vpc->user_id = 7; $vpc->region_id = 1; $vpc->cidr_pool_id = 1; @@ -344,16 +395,68 @@ namespace { $targetManagement = collect($management)->firstWhere('id', '1'); $peerManagement = collect($management)->firstWhere('id', '2'); $assert(($targetManagement['region_id'] ?? null) === 1 - && ($targetManagement['public_ipv4'] ?? null) === '203.0.113.11' + && ($targetManagement['public_ipv4'] ?? null) === '8.8.8.11' + && ($targetManagement['public_ipv6'] ?? null) === '2404:c140:156:3a::11' && array_key_exists('port', $targetManagement) && $targetManagement['port'] === null && ($targetManagement['can_attach'] ?? false) === true, 'The VPC page projection did not expose the eligible same-region instance.'); $assert(($peerManagement['port']['vpc_key'] ?? null) === (string) $vpc->vpc_key - && ($peerManagement['public_ipv4'] ?? null) === '203.0.113.12' + && ($peerManagement['public_ipv4'] ?? null) === '8.8.8.12' + && ($peerManagement['public_ipv6'] ?? null) === '2404:c140:156:3a::12' && ($peerManagement['can_detach'] ?? false) === true, 'The VPC page projection did not expose its attached instance action.'); + $assert(collect($management)->firstWhere('id', '3') === null, + 'An unattached instance without a canonical public snapshot was offered for VPC attach.'); + $invalidListing = CloudVpcPortService::listing( + $invalidNetwork, + ['user_id' => 7] + ); + $assert(($invalidListing['public_network_valid'] ?? null) === false + && ($invalidListing['can_attach'] ?? true) === false, + 'The per-instance VPC DTO enabled attach without a canonical public snapshot.'); + + $jobsBeforeInvalidAttach = CloudJob::count(); + $portsBeforeInvalidAttach = CloudVpcPort::count(); + $expectError(static fn () => CloudVpcPortService::attach( + $invalidNetwork, + [ + 'user_id' => 7, + 'request_idempotency_key' => 'vpc-invalid-direct-attach-0001', + ], + [ + 'vpc_key' => (string) $vpc->vpc_key, + 'confirm_restart' => true, + ] + ), 409, 'Direct VPC attach accepted an instance without a canonical public snapshot.'); + $assert(CloudJob::count() === $jobsBeforeInvalidAttach + && CloudVpcPort::count() === $portsBeforeInvalidAttach, + 'Rejected direct VPC attach left a job or private-IP claim behind.'); + + $expectError(static fn () => CloudVpcMembershipBatchService::start([ + 'user_id' => 7, + 'request_idempotency_key' => 'vpc-invalid-batch-attach-0001', + ], (string) $vpc->vpc_key, [ + 'action' => 'attach', + 'instance_ids' => [(int) $invalidNetwork->id], + 'confirm_restart' => true, + ]), 409, 'Batch VPC attach accepted an instance without a canonical public snapshot.'); + $assert(CloudJob::count() === $jobsBeforeInvalidAttach + && CloudVpcPort::count() === $portsBeforeInvalidAttach + && CloudVpcMembershipBatch::count() === 0, + 'Rejected batch VPC attach left a parent, batch or private-IP claim behind.'); + $expectError(static fn () => CloudVpcPortService::attach( + $missingSource, + [ + 'user_id' => 7, + 'request_idempotency_key' => 'vpc-missing-source-attach-0001', + ], + [ + 'vpc_key' => (string) $vpc->vpc_key, + 'confirm_restart' => true, + ] + ), 409, 'VPC attach accepted a canonical snapshot without cloud_template source authority.'); $actor = ['user_id' => 7, 'request_idempotency_key' => 'vpc-attach-request-0001']; @@ -613,6 +716,14 @@ namespace { $detachActor = ['user_id' => 7, 'request_idempotency_key' => 'vpc-detach-request-0001']; + $target->spec_json = '{malformed-public-network'; + $target->save(); + $damagedAttached = collect( + CloudVpcPortService::managementListing(['user_id' => 7]) + )->firstWhere('id', '1'); + $assert(($damagedAttached['public_network_valid'] ?? null) === false + && ($damagedAttached['can_detach'] ?? false) === true, + 'Damaged public metadata removed the cleanup exit for an attached VPC port.'); $detaching = CloudVpcPortService::detach($target, $detachActor, [ 'confirm_restart' => true, ]); @@ -955,6 +1066,19 @@ namespace { (int) $instance->id )->exists()), 'Completed batch left an instance operation fence behind.'); + $batchDetachSpec = json_decode( + (string) $batchInstances[0]->spec_json, + true, + 512, + JSON_THROW_ON_ERROR + ); + unset($batchDetachSpec['os_source']); + $batchInstances[0]->spec_json = json_encode( + $batchDetachSpec, + JSON_THROW_ON_ERROR + ); + $batchInstances[0]->save(); + $detachBatch = CloudVpcMembershipBatchService::start([ 'user_id' => 7, 'request_idempotency_key' => 'vpc-batch-detach-more-than-four-0001', diff --git a/web/tests/TicketReadModelTest.php b/web/tests/TicketReadModelTest.php index b8f8afc3..3c47564e 100644 --- a/web/tests/TicketReadModelTest.php +++ b/web/tests/TicketReadModelTest.php @@ -53,12 +53,7 @@ $schema->create('cloud_instances', static function (Blueprint $table): void { $table->integer('user_id'); $table->string('name'); $table->string('status')->default('active'); -}); -$schema->create('cloud_public_ips', static function (Blueprint $table): void { - $table->increments('id'); - $table->integer('instance_id')->nullable(); - $table->string('address'); - $table->string('state')->default('available'); + $table->text('spec_json'); }); Capsule::table('user')->insert([ @@ -67,9 +62,21 @@ Capsule::table('user')->insert([ ]); Capsule::table('cloud_instances')->insert([ 'id' => 33, 'user_id' => 7, 'name' => 'vm-support', 'status' => 'active', -]); -Capsule::table('cloud_public_ips')->insert([ - 'id' => 41, 'instance_id' => 33, 'address' => '203.0.113.7', 'state' => 'assigned', + 'spec_json' => json_encode(['public_network' => [ + 'contract' => 1, 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'pool_key' => str_repeat('1', 32), 'pool_cidr' => '8.8.8.0/24', + 'address_cidr' => '8.8.8.7/24', 'gateway' => '8.8.8.1', + 'gateway_on_link' => false, + ], + 'ipv6' => [ + 'pool_key' => str_repeat('2', 32), + 'pool_cidr' => '2404:c140:156:3a::/64', + 'address_cidr' => '2404:c140:156:3a::7/64', + 'gateway' => '2404:c140:156::1', 'gateway_on_link' => true, + ], + 'dns_servers' => ['1.1.1.1', '2606:4700:4700::1111'], + ]], JSON_THROW_ON_ERROR), ]); $messages = [[ 'id' => 1, 'title' => 'Cannot connect', 'content' => 'password=secret', @@ -106,7 +113,8 @@ $assert(is_array($thread), 'The owner could not read the ticket thread.'); $assert($thread['messages']->total() === 12, 'The thread did not return every message.'); $assert($queryCount <= 7, 'Thread projection query count grows past the fixed read budget.'); $assert(($thread['instance']->name ?? null) === 'vm-support' - && ($thread['instance']->public_ipv4 ?? null) === '203.0.113.7' + && ($thread['instance']->public_ipv4 ?? null) === '8.8.8.7' + && ($thread['instance']->public_ipv6 ?? null) === '2404:c140:156:3a::7' && ($thread['instance']->detail_url ?? null) === '/user/cloud/instances/33', 'The related instance is not projected with its owner-safe detail link.'); $adminThread = $model->thread(
实例状态到期时间地区系统 / 安装镜像公网地址规格磁盘
{$vm.name|escape:"html"}{$vm.uuid|escape:"html"}{if $vm.uuid != ''}{/if}
{if $vm.has_ip}{/if}
公网 IPv4{if $vm.has_ipv4}{/if}公网 IPv6{if $vm.has_ipv6}{/if}
{$vm.vcpu|default:'—'|escape:"html"} vCPU · {$vm.memory_mib|default:'—'|escape:"html"} MiB计算资源
{$vm.disk_label|escape:"html"}