Enforce automatic single-subnet VPCs

venix
admin 2 months ago
parent bccb75a2ae
commit 35bff16085

@ -1,5 +1,50 @@
# 本版验证记录
## 2026-10-08:租户单自动子网与创建页简化
- 租户创建页只保留 VPC 名称和地区;CIDR、前缀、唯一子网、成员容量与成员私网 IP
均由平台管理。详情页不再显示子网管理卡片,成员加入也不再选择子网或手填地址;共享
前端资产版本已提升,避免部署后继续使用旧表单缓存。
- 删除租户 `POST/DELETE /vpcs/{vpc_key}/subnets...` 路由、Controller 入口和 Service
mutator。新成员加入意图严格只有 `instance_id` 与 `request_key`,先锁 VPC 根及其全部
子网,确认恰好一个非删除、非清理中的有效子网,再从成员租约与 route `/32` 保留地址
之后自动选择最低可用 IP。仅为滚动升级重放已存在的同 key operation 才读取旧版
`subnet_key/private_ip`;这些字段不能创建新成员,新请求携带时返回 422,且不产生
member、lease、operation 或 revision 副作用。
- 自动子网缺失或正在清理时返回 409;历史数据若存在多个活动子网或无效子网账本则
fail-closed 为 503,不静默选择任一行。数据库表、引擎多子网 DTO 读取能力、根删除和
历史 `subnet_remove` tombstone 收敛逻辑继续保留;本轮没有增加会阻断历史升级的
`UNIQUE(vpc_id)`,也没有自动合并或删除历史数据。
- 成员加入继续把服务端选出的 `subnet_key` 与 `private_ip=null` 写入旧版 request hash,
保持旧自动分配请求可重放。重放检查先于当前子网和实例状态,并从不可变 operation
payload 验证旧自动分配或旧显式 IP hash;因此丢失响应后,即使子网随后进入清理,刷新
到新版页面可用原 `request_key + instance_id` 安全读取结果,未刷新的旧页面也只能在
`subnet_key/private_ip` 与原 hash 精确一致时重放,参数变化返回 409。
- PHP 8.5/WASM + SQLite 下 `CloudVpcCreatePolicyTest`、
`CloudVpcMemberReuseTest`、`CloudPrivateCidrAllocatorTest`、
`CloudVpcRootDeletionTest` 和 `CloudVpcTombstoneConvergenceTest` 通过;源码契约
`CloudVpcControlPlaneContractTest`、`CloudVpcUserPageContractTest`、
`VirtualizationConfigTest`、272 条路由目标、105 个 Smarty/email 模板、52 个前端资产
模块及 schema 契约通过。修改 PHP 语法、`vpc.js` Node 语法和
`git diff --check` 通过。
- SQLite 不实现 MariaDB 的 `SELECT ... FOR UPDATE` 竞争语义,当前也未连接真实
MariaDB、PHP-FPM、浏览器或宿主机。上线前先只读审计所有非删除 VPC;下列查询必须
没有结果,再在隔离 MariaDB 中并发加入同一 VPC、并发重放同一 key,并确认只有一个
member、lease 和 operation:
```sql
SELECT v.id, v.vpc_key,
SUM(CASE WHEN s.state IN ('applying', 'active', 'degraded', 'uncertain')
THEN 1 ELSE 0 END) AS live_subnets,
SUM(CASE WHEN s.state = 'deleting' THEN 1 ELSE 0 END) AS deleting_subnets
FROM cloud_vpcs AS v
LEFT JOIN cloud_vpc_subnets AS s
ON s.vpc_id = v.id AND s.state <> 'deleted'
WHERE v.state <> 'deleted'
GROUP BY v.id, v.vpc_key
HAVING live_subnets <> 1 OR deleting_subnets <> 0;
```
## 2026-10-08:租户 VPC 创建策略、账户配额与幂等加固
- 租户创建 API 现在只接收 `name`、`region_id` 和 `request_key`;CIDR、前缀、首个

@ -45,20 +45,6 @@ final class CloudVpcController
return $this->json($response, $value, 202);
}
public function addSubnet($request, $response, $args)
{
$value = CloudVpcService::addSubnet((string) $args['vpc_key'],
$this->actor($request), CloudInput::object($request));
return $this->json($response, $value, 202);
}
public function removeSubnet($request, $response, $args)
{
$value = CloudVpcService::removeSubnet((string) $args['vpc_key'],
(string) $args['subnet_key'], $this->actor($request), CloudInput::object($request));
return $this->json($response, $value, 202);
}
public function attachMember($request, $response, $args)
{
$value = CloudVpcService::attachMember((string) $args['vpc_key'],

@ -31,7 +31,6 @@ use App\Services\Config;
*/
final class CloudVpcService
{
public const MAX_SUBNETS = 64;
/** Protocol/readback ceiling retained for existing large VPCs. */
public const MAX_MEMBERS = 4096;
/** Tenant creation policy for newly allocated /24 VPCs. */
@ -335,108 +334,38 @@ final class CloudVpcService
}, 3);
}
public static function addSubnet(string $vpcKey, array $actor, array $input): array
{
CloudInput::only($input, ['cidr', 'gateway_ip', 'request_key']);
$key = self::requestKey($input['request_key'] ?? null);
$vpc = self::lockOwned($vpcKey, $actor);
$value = self::cidr($input['cidr'] ?? null, (int) self::cidr(
(string) $vpc->cidr, 16, 24, 'VPC CIDR')['prefix'], 30, '子网 CIDR');
$gateway = $input['gateway_ip'] ?? null;
if ($gateway !== null) {
throw new CloudError('当前 VPC 控制面不支持子网网关');
}
$requestHash = self::requestHash('subnet_add', [
'cidr' => $value['cidr'], 'gateway_ip' => $gateway,
]);
return $vpc->getConnection()->transaction(function () use (
$vpc, $actor, $value, $gateway, $key, $requestHash
): array {
$vpc = self::lockOwned($vpc->vpc_key, $actor);
if (self::hasOperation($vpc, $key, 'subnet_add', $requestHash)) {
return self::documentView($vpc, $actor);
}
self::assertWithinVpc($value, $vpc);
// Guest gateways are intentionally deferred to the data plane.
$subnets = CloudVpcSubnet::where('vpc_id', $vpc->id)->lockForUpdate()->get();
$liveSubnetCount = $subnets->filter(static fn ($row): bool => !in_array(
(string) $row->state, ['deleted', 'deleting'], true
))->count();
if ($liveSubnetCount >= self::MAX_SUBNETS) {
throw new CloudError('VPC 子网数量已达到上限', 409);
}
foreach ($subnets as $row) {
if (self::overlap($value, [
'network' => (int) $row->network_address,
'broadcast' => (int) $row->broadcast_address,
])) {
throw new CloudError('子网 CIDR 与现有子网重叠', 409);
}
}
$now = time();
$row = new CloudVpcSubnet();
$row->subnet_key = self::randomKey();
$row->vpc_id = $vpc->id;
$row->cidr = $value['cidr'];
$row->network_address = $value['network'];
$row->broadcast_address = $value['broadcast'];
$row->prefix_length = $value['prefix'];
$row->gateway_ip = $gateway;
$row->state = 'applying';
$row->created_at = $row->updated_at = $now;
$row->save();
$result = self::touchDesiredLocked($vpc, 'subnet_add', $key, $requestHash);
return self::documentView($result['vpc'], $actor);
}, 3);
}
public static function removeSubnet(string $vpcKey, string $subnetKey,
array $actor, array $input): array
{
CloudInput::only($input, ['request_key']);
$key = self::requestKey($input['request_key'] ?? null);
$vpc = self::lockOwned($vpcKey, $actor);
self::assertKey($subnetKey, '子网');
$requestHash = self::requestHash('subnet_remove', ['subnet_key' => $subnetKey]);
return $vpc->getConnection()->transaction(function () use (
$vpc, $subnetKey, $actor, $key, $requestHash
): array {
$vpc = self::lockOwned($vpc->vpc_key, $actor);
if (self::hasOperation($vpc, $key, 'subnet_remove', $requestHash)) {
return self::documentView($vpc, $actor);
}
$subnet = CloudVpcSubnet::where('vpc_id', $vpc->id)
->where('subnet_key', $subnetKey)->lockForUpdate()->first();
if ($subnet === null || in_array((string) $subnet->state, ['deleted', 'deleting'], true)) {
throw new CloudError('子网不存在', 404);
}
if (CloudVpcMember::where('subnet_id', $subnet->id)
->where('state', '<>', 'deleted')->exists()) {
throw new CloudError('子网仍有私网成员,不能删除', 409);
}
if (CloudVpcPrivateIp::where('subnet_id', $subnet->id)
->where('state', '<>', 'deleted')->exists()) {
throw new CloudError('子网仍有私网地址租约,不能删除', 409);
}
$subnet->state = 'deleting';
$subnet->updated_at = time();
$subnet->save();
$result = self::touchDesiredLocked($vpc, 'subnet_remove', $key, $requestHash);
return self::documentView($result['vpc'], $actor);
}, 3);
}
public static function attachMember(string $vpcKey, array $actor, array $input): array
{
CloudInput::only($input, ['subnet_key', 'instance_id', 'private_ip', 'request_key']);
// Legacy subnet/IP fields are admitted only far enough to replay an
// already committed operation during a rolling UI/API deployment.
// They can never create a new member under the automatic policy.
CloudInput::only($input, [
'instance_id', 'request_key', 'subnet_key', 'private_ip',
]);
$key = self::requestKey($input['request_key'] ?? null);
$instanceId = self::positiveInt($input['instance_id'] ?? null, 1, 1000000000,
'虚拟机无效');
$requestHash = self::requestHash('member_attach', [
'subnet_key' => $input['subnet_key'] ?? null,
'instance_id' => $instanceId,
'private_ip' => $input['private_ip'] ?? null,
]);
$hasLegacySubnet = array_key_exists('subnet_key', $input);
$hasLegacyIp = array_key_exists('private_ip', $input);
if ($hasLegacyIp && !$hasLegacySubnet) {
throw new CloudError('私网 IP 只能由平台自动分配,请刷新页面后重试', 422);
}
$legacyRequestHash = null;
if ($hasLegacySubnet) {
self::assertKey($input['subnet_key'] ?? null, '子网');
$legacyIpForHash = null;
if ($hasLegacyIp && $input['private_ip'] !== null) {
self::ipv4($input['private_ip'], '私网 IP');
// The former implementation hashed the validated raw string
// before storing its canonical address in the lease row.
$legacyIpForHash = (string) $input['private_ip'];
}
$legacyRequestHash = self::requestHash('member_attach', [
'subnet_key' => (string) $input['subnet_key'],
'instance_id' => $instanceId,
'private_ip' => $legacyIpForHash,
]);
}
// Older workers could persist a locally proven `deleted` pair after
// the VPC root and every historical host had already reached the same
// exact revision. Such rows still own the database uniqueness keys.
@ -454,17 +383,44 @@ final class CloudVpcService
// legacy garbage collection. A client retry after the first response
// was lost must still resolve the original operation even if the VM's
// runtime state or host-region mapping has changed in the meantime.
$replay = $vpc->getConnection()->transaction(function () use (
$vpc, $actor, $key, $requestHash
): ?array {
$prepared = $vpc->getConnection()->transaction(function () use (
$vpc, $actor, $key, $instanceId, $legacyRequestHash
): array {
$locked = self::lockOwned($vpc->vpc_key, $actor);
return self::hasOperation(
$locked, $key, 'member_attach', $requestHash
) ? self::documentView($locked, $actor) : null;
if (self::hasMemberAttachOperation(
$locked, $key, $instanceId, $legacyRequestHash
)) {
return [
'request_hash' => null,
'subnet_key' => null,
'replay' => self::documentView($locked, $actor),
];
}
if ($legacyRequestHash !== null) {
throw new CloudError(
'子网和私网 IP 由平台自动分配,请刷新页面后重试',
422
);
}
$subnet = self::lockedAutomaticSubnet($locked);
// Preserve the historical automatic-attach hash shape so a lost
// response from the former subnet selector remains replayable.
$requestHash = self::requestHash('member_attach', [
'subnet_key' => (string) $subnet->subnet_key,
'instance_id' => $instanceId,
'private_ip' => null,
]);
return [
'request_hash' => $requestHash,
'subnet_key' => (string) $subnet->subnet_key,
'replay' => null,
];
}, 3);
if ($replay !== null) {
return $replay;
if ($prepared['replay'] !== null) {
return $prepared['replay'];
}
$requestHash = (string) $prepared['request_hash'];
$automaticSubnetKey = (string) $prepared['subnet_key'];
$instance = CloudInstance::where('id', $instanceId)
->where('status', '<>', 'deleted')->first();
if ($instance !== null
@ -477,21 +433,19 @@ final class CloudVpcService
);
}
return $vpc->getConnection()->transaction(function () use (
$vpc, $actor, $input, $key, $requestHash, $instanceId
$vpc, $actor, $key, $requestHash, $instanceId, $automaticSubnetKey,
$legacyRequestHash
): array {
$vpc = self::lockOwned($vpc->vpc_key, $actor);
if (self::hasOperation($vpc, $key, 'member_attach', $requestHash)) {
if (self::hasMemberAttachOperation(
$vpc, $key, $instanceId, $legacyRequestHash
)) {
return self::documentView($vpc, $actor);
}
$subnetKey = $input['subnet_key'] ?? null;
self::assertKey($subnetKey, '子网');
$subnet = CloudVpcSubnet::where('vpc_id', $vpc->id)
->where('subnet_key', $subnetKey)->lockForUpdate()->first();
if ($subnet === null || !in_array((string) $subnet->state, self::LIVE_STATES, true)) {
throw new CloudError('子网不存在或尚未可用', 409);
$subnet = self::lockedAutomaticSubnet($vpc);
if (!hash_equals($automaticSubnetKey, (string) $subnet->subnet_key)) {
throw new CloudError('VPC 自动子网状态已变化,请重新读取', 409);
}
$requestedIp = ($input['private_ip'] ?? null) !== null
? self::ipv4($input['private_ip'], '私网 IP') : null;
$existing = CloudVpcMember::where('vpc_id', $vpc->id)
->where('instance_id', $instanceId)->lockForUpdate()->first();
if ($existing !== null) {
@ -527,10 +481,6 @@ final class CloudVpcService
|| in_array((string) $privateIp->state, ['deleted', 'deleting'], true)) {
throw new CloudError('VPC 私网地址账本与成员不一致,请联系管理员', 503);
}
if ($requestedIp !== null
&& (string) $privateIp->private_ip !== $requestedIp) {
throw new CloudError('该虚拟机已加入 VPC 且 IP 不同', 409);
}
return self::documentView($vpc, $actor);
}
$instance = CloudInstance::where('id', $instanceId)
@ -594,9 +544,7 @@ final class CloudVpcService
$reservedRouteIps[(string) $route->next_hop_ip] = true;
}
}
$ip = $requestedIp !== null
? $requestedIp
: self::firstFreeIp($subnet, $privateIps, $reservedRouteIps);
$ip = self::firstFreeIp($subnet, $privateIps, $reservedRouteIps);
$ipInt = self::ipToInt($ip);
if ($ipInt <= (int) $subnet->network_address
|| $ipInt >= (int) $subnet->broadcast_address) {
@ -2040,9 +1988,10 @@ final class CloudVpcService
'updated_at' => $observedAt,
]);
}
// A subnet is only a control-plane address range. removeSubnet
// already requires it to have no live member or lease, so an
// empty-VPC terminal gate is sufficient absence proof. Never
// A subnet is only a control-plane address range. Historical
// subnet-removal operations were admitted only after proving
// no live member or lease, so an empty-VPC terminal gate is
// sufficient absence proof. Never
// extend this branch to member/private-IP tombstones: those
// still require libvirt removal readback from a host.
if ((string) $operation->kind === 'member_detach') {
@ -4412,6 +4361,133 @@ final class CloudVpcService
return ['vpc' => $vpc, 'operation' => $operation, 'unchanged' => false];
}
/** Lock and resolve the one platform-managed subnet used for member IPAM. */
private static function lockedAutomaticSubnet(CloudVpc $vpc): CloudVpcSubnet
{
$rows = CloudVpcSubnet::where('vpc_id', $vpc->id)
->orderBy('id')->lockForUpdate()->get();
$live = [];
$deleting = false;
foreach ($rows as $row) {
$state = (string) $row->state;
if ($state === 'deleted') {
continue;
}
if ($state === 'deleting') {
$deleting = true;
continue;
}
if (!in_array($state, self::LIVE_STATES, true)) {
throw new CloudError('VPC 自动子网账本状态无效,请联系管理员', 503);
}
$live[] = $row;
}
if ($deleting) {
throw new CloudError('VPC 自动子网正在清理,请稍后重试', 409);
}
if ($live === []) {
throw new CloudError('VPC 自动子网尚未可用', 409);
}
if (count($live) !== 1) {
throw new CloudError(
'VPC 存在多个活动子网,已停止自动分配,请联系管理员', 503
);
}
/** @var CloudVpcSubnet $subnet */
$subnet = $live[0];
try {
$root = self::cidr((string) $vpc->cidr, 16, 24, 'VPC CIDR');
$value = self::cidr(
(string) $subnet->cidr, (int) $root['prefix'], 30,
'自动子网 CIDR'
);
} catch (\Throwable) {
throw new CloudError('VPC 自动子网账本无效,请联系管理员', 503);
}
if ((string) $subnet->cidr !== $value['cidr']
|| preg_match(self::KEY_PATTERN, (string) $subnet->subnet_key) !== 1
|| (int) $subnet->network_address !== $value['network']
|| (int) $subnet->broadcast_address !== $value['broadcast']
|| (int) $subnet->prefix_length !== $value['prefix']
|| $value['network'] < $root['network']
|| $value['broadcast'] > $root['broadcast']
|| $subnet->gateway_ip !== null) {
throw new CloudError('VPC 自动子网账本无效,请联系管理员', 503);
}
return $subnet;
}
/**
* Replay automatic member attachment before consulting mutable subnet or
* instance state. The immutable signed desired payload supplies the old
* subnet/IP fields needed to verify both former request hash shapes.
*/
private static function hasMemberAttachOperation(
CloudVpc $vpc,
string $requestKey,
int $instanceId,
?string $legacyRequestHash = null
): bool {
$operation = CloudVpcOperation::where('vpc_id', $vpc->id)
->where('idempotency_key', $requestKey)
->lockForUpdate()->first();
if ($operation === null) {
return false;
}
if ((string) $operation->kind !== 'member_attach') {
throw new CloudError('同一请求幂等键的参数不一致', 409);
}
if ((int) $operation->user_id !== (int) $vpc->user_id) {
throw new CloudError('VPC 成员操作账本不完整,请联系管理员', 503);
}
if ($legacyRequestHash !== null) {
if (!hash_equals(
(string) $operation->request_hash, $legacyRequestHash
)) {
throw new CloudError('同一请求幂等键的参数不一致', 409);
}
return true;
}
try {
$payload = json_decode(
(string) $operation->payload_json, true, 64, JSON_THROW_ON_ERROR
);
} catch (\Throwable) {
throw new CloudError('VPC 成员操作账本不完整,请联系管理员', 503);
}
if (!is_array($payload) || !is_array($payload['members'] ?? null)) {
throw new CloudError('VPC 成员操作账本不完整,请联系管理员', 503);
}
foreach ($payload['members'] as $member) {
if (!is_array($member)
|| !is_string($member['subnet_id'] ?? null)
|| preg_match(self::KEY_PATTERN, (string) $member['subnet_id']) !== 1) {
continue;
}
$privateCidr = $member['private_ip_cidr'] ?? null;
if (!is_string($privateCidr)
|| preg_match('/^([0-9.]+)\/32$/D', $privateCidr, $match) !== 1
|| filter_var($match[1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
throw new CloudError('VPC 成员操作账本不完整,请联系管理员', 503);
}
$automaticHash = self::requestHash('member_attach', [
'subnet_key' => (string) $member['subnet_id'],
'instance_id' => $instanceId,
'private_ip' => null,
]);
$explicitHash = self::requestHash('member_attach', [
'subnet_key' => (string) $member['subnet_id'],
'instance_id' => $instanceId,
'private_ip' => $match[1],
]);
if (hash_equals((string) $operation->request_hash, $automaticHash)
|| hash_equals((string) $operation->request_hash, $explicitHash)) {
return true;
}
}
throw new CloudError('同一请求幂等键的参数不一致', 409);
}
/** Check a request key while the VPC root row is already locked. */
private static function hasOperation(CloudVpc $vpc, string $requestKey,
string $kind, string $requestHash): bool
@ -4914,19 +4990,6 @@ final class CloudVpcService
return $network >= $outerNetwork && $broadcast <= $outerBroadcast;
}
private static function overlap(array $left, array $right): bool
{
return $left['network'] <= $right['broadcast'] && $right['network'] <= $left['broadcast'];
}
private static function assertWithinVpc(array $value, CloudVpc $vpc): void
{
$root = self::cidr((string) $vpc->cidr, 16, 24, 'VPC CIDR');
if (!self::contains($root['network'], $root['broadcast'], $value['network'], $value['broadcast'])) {
throw new CloudError('子网必须完全位于 VPC CIDR 内');
}
}
/**
* Return the first address absent from durable leases and live routes.
*

@ -28,9 +28,6 @@ $app->group('/api/v1', function () {
$this->get('/vpcs/{vpc_key:[0-9a-f]{32}}', 'App\Controllers\CloudVpcController:show');
$this->delete('/vpcs/{vpc_key:[0-9a-f]{32}}',
'App\Controllers\CloudVpcController:delete');
$this->post('/vpcs/{vpc_key:[0-9a-f]{32}}/subnets', 'App\Controllers\CloudVpcController:addSubnet');
$this->delete('/vpcs/{vpc_key:[0-9a-f]{32}}/subnets/{subnet_key:[0-9a-f]{32}}',
'App\Controllers\CloudVpcController:removeSubnet');
$this->post('/vpcs/{vpc_key:[0-9a-f]{32}}/members', 'App\Controllers\CloudVpcController:attachMember');
$this->delete('/vpcs/{vpc_key:[0-9a-f]{32}}/members/{member_key:[0-9a-f]{32}}',
'App\Controllers\CloudVpcController:detachMember');

File diff suppressed because one or more lines are too long

@ -176,7 +176,6 @@ function normalizeDocument(value) {
if (!root) return null;
return {
vpc: root,
subnets: Array.isArray(value.subnets) ? value.subnets : [],
members: Array.isArray(value.members) ? value.members : [],
routes: Array.isArray(value.routes) ? value.routes : [],
acl_rules: Array.isArray(value.acl_rules) ? value.acl_rules : [],
@ -210,7 +209,7 @@ function selectedRootDeleting() {
function allowSelectedMutation() {
if (!selectedRootDeleting()) return true;
setError('VPC 正在删除,完成所有宿主机清理前不能再修改子网、成员、路由或 ACL。');
setError('VPC 正在删除,完成所有宿主机清理前不能再修改成员、路由或 ACL。');
return false;
}
@ -376,7 +375,6 @@ function renderDetail() {
overview.append(overviewHeading, facts);
container.append(overview);
container.append(renderSubnets(doc));
container.append(renderMembers(doc));
container.append(renderRoutes(doc));
container.append(renderAcl(doc));
@ -385,35 +383,9 @@ function renderDetail() {
lockDeletingDetail(container, reconcile);
}
function renderSubnets(doc) {
const card = section('子网与 CIDR', '子网是 VPC 内的地址范围;当前数据面使用成员精确 /32,不自动提供网关。', 'vpc-subnets');
const form = element('form', 'vpc-inline-form'); form.dataset.vpcForm = 'subnet';
const cidr = input('新增子网 CIDR', '', 'text', '10.40.1.0/24');
cidr.control.name = 'cidr'; cidr.control.required = true; cidr.control.maxLength = 18;
const save = button('添加子网', 'button button-primary small'); save.type = 'submit';
form.append(cidr.wrapper, save); card.append(form);
const list = element('div', 'vpc-row-list');
for (const row of doc.subnets) {
const item = element('div', 'vpc-data-row');
const copy = element('div', 'vpc-row-copy');
copy.append(element('strong', '', row.cidr || '未知子网'), element('small', '', `状态:${STATUS_LABELS[childStatus(row.state)] || safeText(row.state)}`));
if (row.last_error_code) copy.append(element('small', 'vpc-row-error', row.last_error_code));
const remove = button('删除', 'button button-outline small danger');
remove.dataset.vpcRemoveSubnet = row.subnet_key;
remove.disabled = state.busy || ['deleting', 'deleted'].includes(childStatus(row.state));
item.append(copy, remove); list.append(item);
}
if (!doc.subnets.length) list.append(element('p', 'vpc-empty-inline', '暂无子网。'));
card.append(list); return card;
}
function renderMembers(doc) {
const card = section('成员与私网 IP', '把同一地区的实例加入 VPC;私网 IP 由 PHP 租约账本分配并在宿主机回读后生效。', 'vpc-members');
const card = section('成员与私网 IP', '选择同一地区的实例即可加入;平台会使用唯一自动子网分配私网 IP,并在宿主机回读后生效。', 'vpc-members');
const form = element('form', 'vpc-inline-form vpc-member-form'); form.dataset.vpcForm = 'member';
const subnet = input('加入子网', '', 'select'); subnet.control.name = 'subnet_key'; subnet.control.required = true;
for (const row of doc.subnets.filter(item => !['deleting', 'deleted'].includes(childStatus(item.state)))) {
subnet.control.append(new Option(row.cidr, row.subnet_key));
}
const instance = input('选择实例', '', 'select'); instance.control.name = 'instance_id'; instance.control.required = true;
const vpcRegionId = Number(doc.vpc.region_id || 0);
const attached = new Set(doc.members
@ -428,9 +400,8 @@ function renderMembers(doc) {
option.disabled = alreadyAttached || !sameRegion;
instance.control.append(option);
}
const ip = input('指定私网 IP(可选)', '', 'text', '自动分配'); ip.control.name = 'private_ip'; ip.control.maxLength = 15;
const save = button('加入 VPC', 'button button-primary small'); save.type = 'submit';
form.append(subnet.wrapper, instance.wrapper, ip.wrapper, save); card.append(form);
form.append(instance.wrapper, save); card.append(form);
const list = element('div', 'vpc-row-list');
for (const row of doc.members.filter(item => childStatus(item.state) !== 'deleted')) {
const item = element('div', 'vpc-data-row');
@ -706,22 +677,11 @@ async function createVpc(event) {
finally { state.busy = false; createRegionOptions(); renderList(); schedulePoll(1500); }
}
async function submitSubnet(form) {
if (!allowSelectedMutation() || !confirmDetailMutation()) return;
const value = form.cidr.value.trim();
if (!value) return;
const payload = await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/subnets`, 'POST', {
cidr: value, request_key: requestKey('subnet-add'),
}, '子网目标已提交,等待宿主机回读。');
if (payload) form.reset();
}
async function submitMember(form) {
if (!allowSelectedMutation() || !confirmDetailMutation()) return;
const body = { subnet_key: form.subnet_key.value, instance_id: Number(form.instance_id.value), request_key: requestKey('member-add') };
if (form.private_ip.value.trim()) body.private_ip = form.private_ip.value.trim();
const body = { instance_id: Number(form.instance_id.value), request_key: requestKey('member-add') };
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/members`, 'POST', body,
'实例已加入 VPC 目标,私网网卡将在实际回读后显示为可用。');
'实例已加入 VPC 目标,私网 IP 已自动分配,网卡将在实际回读后显示为可用。');
}
function readRoutes() {
@ -778,13 +738,6 @@ async function reconcile() {
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/reconcile`, 'POST', {}, '已请求重新核对 VPC 状态。');
}
async function removeSubnet(key) {
if (!state.selectedKey || state.busy || !allowSelectedMutation() || !confirmDetailMutation()
|| !confirm('确认删除这个子网?子网必须没有成员和地址租约。')) return;
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/subnets/${encodeURIComponent(key)}`,
'DELETE', { request_key: requestKey('subnet-remove') }, '子网删除目标已提交。');
}
async function removeMember(key) {
if (!state.selectedKey || state.busy || !allowSelectedMutation() || !confirmDetailMutation()
|| !confirm('确认让这个实例退出 VPC?宿主机回读确认前,私网 IP 不会重新分配。')) return;
@ -818,8 +771,6 @@ async function deleteVpc() {
function handleClick(event) {
const listRow = event.target.closest('[data-vpc-key]');
if (listRow && listRow.closest('#vpc-list')) { selectVpc(listRow.dataset.vpcKey); return; }
const removeSubnetKey = event.target.closest('[data-vpc-remove-subnet]')?.dataset.vpcRemoveSubnet;
if (removeSubnetKey) { removeSubnet(removeSubnetKey); return; }
const removeMemberKey = event.target.closest('[data-vpc-remove-member]')?.dataset.vpcRemoveMember;
if (removeMemberKey) { removeMember(removeMemberKey); return; }
const action = event.target.closest('[data-vpc-action]')?.dataset.vpcAction;
@ -847,7 +798,6 @@ function handleClick(event) {
function handleSubmit(event) {
const kind = event.target.dataset.vpcForm;
if (kind === 'subnet') { event.preventDefault(); submitSubnet(event.target); }
if (kind === 'member') { event.preventDefault(); submitMember(event.target); }
}

@ -3,7 +3,7 @@
<div>
<span class="eyebrow">PRIVATE NETWORK</span>
<h1 id="vpc-page-title" tabindex="-1">VPC 私网</h1>
<p>在同一地区的实例之间建立受控三层私网。私网配置只有在宿主机实际回读确认后才会显示为可用。</p>
<p>填写名称并选择地区即可创建私网;平台会自动分配独立网段、唯一子网和成员地址,并在宿主机实际回读后标记为可用。</p>
</div>
<div class="heading-actions">
<button id="vpc-refresh" class="button button-outline" type="button"><span aria-hidden="true">↻</span> 刷新</button>
@ -32,7 +32,7 @@
<section id="vpc-detail-panel" class="inventory-panel vpc-detail-panel" aria-labelledby="vpc-detail-title" hidden>
<div class="panel-heading vpc-detail-heading">
<div><h2 id="vpc-detail-title">VPC 详情</h2><p id="vpc-detail-caption">选择左侧 VPC 查看子网、成员、路由和 ACL。</p></div>
<div><h2 id="vpc-detail-title">VPC 详情</h2><p id="vpc-detail-caption">选择左侧 VPC 查看成员、路由和 ACL。</p></div>
<div class="panel-tools"><button id="vpc-detail-refresh" class="button button-outline small" type="button">刷新详情</button></div>
</div>
<div id="vpc-detail" class="vpc-detail" aria-live="polite"></div>
@ -40,12 +40,11 @@
</div>
<section id="vpc-create-panel" class="inventory-panel vpc-create-panel" aria-labelledby="vpc-create-title" hidden>
<div class="panel-heading"><div><h2 id="vpc-create-title">创建 VPC</h2><p>平台会按地区绑定已激活的 WireGuard Fabric;浏览器不会接触宿主机密钥或地址。</p></div><button id="vpc-create-close" class="button button-ghost small" type="button">取消</button></div>
<div class="panel-heading"><div><h2 id="vpc-create-title">创建 VPC</h2><p>填写名称并选择地区,平台会自动绑定 Fabric、分配独立 /24 网段并建立唯一子网。</p></div><button id="vpc-create-close" class="button button-ghost small" type="button">取消</button></div>
<form id="vpc-create-form" class="vpc-form">
<div class="vpc-form-grid">
<div class="field"><label for="vpc-create-name">名称 <span>*</span></label><input id="vpc-create-name" name="name" type="text" maxlength="63" required placeholder="例如:prod-vpc"/><small>使用英文、数字、点、下划线或连字符。</small></div>
<div class="field"><label for="vpc-create-region">地区 <span>*</span></label><select id="vpc-create-region" name="region_id" required></select><small id="vpc-create-region-hint">只列出已完成 Fabric 映射的地区。</small></div>
<div class="field"><label>网络配置</label><small>平台将自动分配独立 /24 私网和首个子网,成员地址自动分配。</small></div>
<div class="field"><label for="vpc-create-region">地区 <span>*</span></label><select id="vpc-create-region" name="region_id" required></select><small id="vpc-create-region-hint">只列出已完成 Fabric 映射的地区;网段、子网和成员地址均自动分配。</small></div>
</div>
<div id="vpc-create-error" class="form-error" role="alert" hidden></div>
<div class="vpc-form-actions"><button class="button button-primary" type="submit">创建并自动配置</button></div>

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026100803' scope='global'}
{assign var=venix_asset_version value='2026100804' scope='global'}

@ -154,6 +154,39 @@ $assert(str_contains($service, 'public static function delete(')
&& str_contains($service, "\$vpc->state = 'deleted'")
&& str_contains($service, "\$root->state = (string) \$row->kind === 'vpc_delete'"),
'VPC root deletion lost confirmation, durable operation, exact receipt or CIDR CAS finalization.');
$assert(!str_contains($routes, "/subnets'")
&& !str_contains($routes, '/subnets/{')
&& !str_contains($controller, 'public function addSubnet(')
&& !str_contains($controller, 'public function removeSubnet(')
&& !str_contains($service, 'public static function addSubnet(')
&& !str_contains($service, 'public static function removeSubnet('),
'Tenant VPC API must not expose subnet creation or deletion mutators.');
$attachStart = strpos($service, 'public static function attachMember(');
$attachEnd = strpos($service, 'public static function detachMember(', $attachStart ?: 0);
$attachBlock = $attachStart !== false && $attachEnd !== false
? substr($service, $attachStart, $attachEnd - $attachStart) : '';
$automaticSubnetStart = strpos($service, 'private static function lockedAutomaticSubnet(');
$automaticSubnetEnd = strpos(
$service, 'private static function hasMemberAttachOperation(',
$automaticSubnetStart ?: 0
);
$automaticSubnetBlock = $automaticSubnetStart !== false && $automaticSubnetEnd !== false
? substr($service, $automaticSubnetStart,
$automaticSubnetEnd - $automaticSubnetStart) : '';
$assert($attachBlock !== ''
&& str_contains($attachBlock, "'instance_id', 'request_key', 'subnet_key', 'private_ip'")
&& str_contains($attachBlock, 'if ($legacyRequestHash !== null)')
&& str_contains($attachBlock, '子网和私网 IP 由平台自动分配')
&& str_contains($attachBlock, 'self::lockedAutomaticSubnet(')
&& str_contains($attachBlock,
'self::firstFreeIp($subnet, $privateIps, $reservedRouteIps)')
&& $automaticSubnetBlock !== ''
&& str_contains($automaticSubnetBlock, "CloudVpcSubnet::where('vpc_id', \$vpc->id)")
&& str_contains($automaticSubnetBlock, "if (\$state === 'deleting')")
&& str_contains($automaticSubnetBlock, 'if (count($live) !== 1)')
&& str_contains($automaticSubnetBlock,
'preg_match(self::KEY_PATTERN, (string) $subnet->subnet_key)'),
'Tenant member attach must select exactly one live subnet and allocate its private IP server-side.');
$missingRemovalHost = strpos(
$service, '$item = $hosts[(string) $hostId] ?? null;'
);
@ -229,7 +262,7 @@ $assert(str_contains($service, '$orphanLease')
&& str_contains($service, "(string) \$privateIp->state === 'active'")
&& str_contains($service, '$private->state = $privateState'),
'VPC private projections must fail closed on orphan/mismatched leases and require current root readback proof.');
$assert(str_contains($service, '当前 VPC 控制面不支持子网网关')
$assert(str_contains($service, '$subnet->gateway_ip !== null')
&& str_contains($service, "'private_ip_cidr'")
&& str_contains($service, "'next_hop_member_id'")
&& str_contains($service, "self::cidr(\$item['destination_cidr'] ?? null, 32, 32, '路由目标')")

@ -362,7 +362,10 @@ $alphaNetwork = $alphaRoot === null ? null : Capsule::table('cloud_private_netwo
->where('id', (int) $alphaRoot->private_network_id)->first();
$alphaSubnet = $alphaRoot === null ? null : Capsule::table('cloud_vpc_subnets')
->where('vpc_id', (int) $alphaRoot->id)->first();
$alphaSubnetCount = $alphaRoot === null ? 0 : Capsule::table('cloud_vpc_subnets')
->where('vpc_id', (int) $alphaRoot->id)->count();
$assert($alphaRoot !== null && $alphaNetwork !== null && $alphaSubnet !== null
&& $alphaSubnetCount === 1
&& (string) $alphaRoot->cidr === '10.0.0.0/24'
&& (int) $alphaRoot->max_members === CloudVpcService::DEFAULT_MAX_MEMBERS
&& (int) $alphaRoot->max_members === 200

@ -898,7 +898,7 @@ $assert(count($boundedObserved['hosts'] ?? []) === 257
'Observed proof persistence still truncates hosts, routes or peers at 256.');
// A fully proven historical pair must release both uniqueness keys before a
// same-VPC attach reserves the original explicit address again. The host stays
// same-VPC attach automatically reserves the lowest free address again. The host stays
// active for a real sibling, so absence is proven by exact NIC/route/proxy
// evidence rather than by treating an active empty bridge as a removal receipt.
$same = $seedVpc(1, '10.41.0.0/24', '10.41.0.0/29', 10, 'active', 'active', [
@ -910,8 +910,7 @@ $seedInstance(1002, 10);
$seedPair(10001, 20001, $same, 1001, 10, '10.41.0.1');
$seedPair(10002, 20002, $same, 1002, 10, '10.41.0.2', 'active');
$sameInput = [
'subnet_key' => $same['subnet_key'], 'instance_id' => 1001,
'private_ip' => '10.41.0.1', 'request_key' => 'reuse-same-vpc-0001',
'instance_id' => 1001, 'request_key' => 'reuse-same-vpc-0001',
];
CloudVpcService::attachMember($same['vpc_key'], $actor, $sameInput);
$sameMember = Capsule::table('cloud_vpc_members')->where('instance_id', 1001)->first();
@ -949,6 +948,66 @@ $assert(Capsule::table('cloud_vpc_members')->where('instance_id', 1001)->count()
&& (int) Capsule::table('cloud_vpcs')->where('id', 1)->value('desired_revision') === 2,
'An idempotent attach replay duplicated identities or advanced the VPC revision.');
// A pre-policy client could have supplied the selected address explicitly.
// Its immutable operation remains replayable even if the automatic subnet is
// now cleaning: replay identity is proven from the old signed desired payload,
// before mutable subnet/instance preconditions are consulted.
$legacyExplicitHash = hash('sha256', $canonicalJson([
'kind' => 'member_attach',
'input' => [
'subnet_key' => $same['subnet_key'],
'instance_id' => 1001,
'private_ip' => '10.41.0.1',
],
]));
Capsule::table('cloud_vpc_operations')->where('vpc_id', 1)
->where('idempotency_key', 'reuse-same-vpc-0001')
->update(['request_hash' => $legacyExplicitHash]);
Capsule::table('cloud_vpc_subnets')->where('id', $same['subnet_id'])
->update(['state' => 'deleting']);
Capsule::table('cloud_instances')->where('id', 1001)->update([
'status' => 'deleting', 'updated_at' => $now + 3,
]);
CloudVpcService::attachMember($same['vpc_key'], $actor, $sameInput);
CloudVpcService::attachMember($same['vpc_key'], $actor, [
...$sameInput,
'subnet_key' => $same['subnet_key'],
'private_ip' => '10.41.0.1',
]);
$expectCloudError(static fn () => CloudVpcService::attachMember(
$same['vpc_key'], $actor, [
...$sameInput,
'subnet_key' => $same['subnet_key'],
'private_ip' => '10.41.0.3',
]
), 409);
$legacyWhitespaceIp = ' 10.41.0.1 ';
$legacyWhitespaceHash = hash('sha256', $canonicalJson([
'kind' => 'member_attach',
'input' => [
'subnet_key' => $same['subnet_key'],
'instance_id' => 1001,
'private_ip' => $legacyWhitespaceIp,
],
]));
Capsule::table('cloud_vpc_operations')->where('vpc_id', 1)
->where('idempotency_key', 'reuse-same-vpc-0001')
->update(['request_hash' => $legacyWhitespaceHash]);
CloudVpcService::attachMember($same['vpc_key'], $actor, [
...$sameInput,
'subnet_key' => $same['subnet_key'],
'private_ip' => $legacyWhitespaceIp,
]);
Capsule::table('cloud_vpc_subnets')->where('id', $same['subnet_id'])
->update(['state' => 'active']);
Capsule::table('cloud_instances')->where('id', 1001)->update([
'status' => 'active', 'updated_at' => $now + 4,
]);
$assert(Capsule::table('cloud_vpc_members')->where('instance_id', 1001)->count() === 1
&& Capsule::table('cloud_vpc_private_ips')->where('instance_id', 1001)->count() === 1
&& (int) Capsule::table('cloud_vpcs')->where('id', 1)->value('desired_revision') === 2,
'A legacy explicit-IP attach did not replay exactly before mutable subnet checks.');
// Keep the production uniqueness barriers present and executable. The service
// succeeds above because it physically deleted the old rows, not because the
// schema or application merely stopped looking at them.
@ -1004,12 +1063,11 @@ $target = $seedVpc(3, '10.43.0.0/24', '10.43.0.0/29', 20,
$seedInstance(2001, 20);
$seedPair(20001, 30001, $source, 2001, 20, '10.42.0.1');
CloudVpcService::attachMember($target['vpc_key'], $actor, [
'subnet_key' => $target['subnet_key'], 'instance_id' => 2001,
'private_ip' => '10.43.0.5', 'request_key' => 'reuse-cross-vpc-0001',
'instance_id' => 2001, 'request_key' => 'reuse-cross-vpc-0001',
]);
$crossMember = Capsule::table('cloud_vpc_members')->where('instance_id', 2001)->first();
$assert($crossMember !== null && (int) $crossMember->vpc_id === 3
&& (string) $crossMember->private_ip === '10.43.0.5'
&& (string) $crossMember->private_ip === '10.43.0.1'
&& Capsule::table('cloud_vpc_members')->where('id', 20001)->count() === 0
&& Capsule::table('cloud_vpc_private_ips')->where('id', 30001)->count() === 0
&& Capsule::table('cloud_vpcs')->where('id', 2)->count() === 1
@ -1027,8 +1085,7 @@ $seedInstance(3001, 30);
$seedInstance(3003, 30);
$seedPair(30001, 40001, $automatic, 3001, 30, '10.44.0.1');
CloudVpcService::attachMember($automatic['vpc_key'], $actor, [
'subnet_key' => $automatic['subnet_key'], 'instance_id' => 3003,
'request_key' => 'reuse-auto-lowest-0001',
'instance_id' => 3003, 'request_key' => 'reuse-auto-lowest-0001',
]);
$assert(Capsule::table('cloud_vpc_members')->where('id', 30001)->count() === 0
&& Capsule::table('cloud_vpc_private_ips')->where('id', 40001)->count() === 0
@ -1050,8 +1107,7 @@ Capsule::table('cloud_vpcs')->where('id', 5)->update([
'last_operation_id' => $keyFor('newer-operation', 5),
]);
CloudVpcService::attachMember($rootAdvanced['vpc_key'], $actor, [
'subnet_key' => $rootAdvanced['subnet_key'], 'instance_id' => 4001,
'private_ip' => '10.45.0.1', 'request_key' => 'reuse-monotonic-root-0001',
'instance_id' => 4001, 'request_key' => 'reuse-monotonic-root-0001',
]);
$assert(Capsule::table('cloud_vpc_members')->where('id', 40001)->count() === 0
&& Capsule::table('cloud_vpc_private_ips')->where('id', 50001)->count() === 0
@ -1073,8 +1129,7 @@ Capsule::table('cloud_vpc_operations')
]);
$expectCloudError(static fn () => CloudVpcService::attachMember(
$operationIncomplete['vpc_key'], $actor, [
'subnet_key' => $operationIncomplete['subnet_key'], 'instance_id' => 5001,
'private_ip' => '10.46.0.1', 'request_key' => 'reuse-operation-block-0001',
'instance_id' => 5001, 'request_key' => 'reuse-operation-block-0001',
]
), 409);
$assert(Capsule::table('cloud_vpc_members')->where('id', 50001)->count() === 1
@ -1095,8 +1150,7 @@ $seedPair(60001, 70001, $hostIncomplete, 6001, 60, '10.47.0.1');
$seedPair(60002, 70002, $hostIncomplete, 6002, 60, '10.47.0.2', 'active');
$expectCloudError(static fn () => CloudVpcService::attachMember(
$hostIncomplete['vpc_key'], $actor, [
'subnet_key' => $hostIncomplete['subnet_key'], 'instance_id' => 6001,
'private_ip' => '10.47.0.1', 'request_key' => 'reuse-host-block-0001',
'instance_id' => 6001, 'request_key' => 'reuse-host-block-0001',
]
), 409);
$assert(Capsule::table('cloud_vpc_members')->where('id', 60001)->count() === 1
@ -1120,8 +1174,7 @@ Capsule::table('cloud_vpc_private_ips')->insert([
]);
$expectCloudError(static fn () => CloudVpcService::attachMember(
$orphanVpc['vpc_key'], $actor, [
'subnet_key' => $orphanVpc['subnet_key'], 'instance_id' => 7001,
'private_ip' => '10.48.0.1', 'request_key' => 'reuse-orphan-block-0001',
'instance_id' => 7001, 'request_key' => 'reuse-orphan-block-0001',
]
), 503);
$assert(Capsule::table('cloud_vpc_private_ips')->where('id', 80001)->count() === 1
@ -1145,8 +1198,7 @@ Capsule::table('cloud_vpc_private_ips')->where('id', 90001)->update([
]);
$expectCloudError(static fn () => CloudVpcService::attachMember(
$createdLater['vpc_key'], $actor, [
'subnet_key' => $createdLater['subnet_key'], 'instance_id' => 8001,
'private_ip' => '10.49.0.1', 'request_key' => 'reuse-created-later-block-0001',
'instance_id' => 8001, 'request_key' => 'reuse-created-later-block-0001',
]
), 409);
$assert(Capsule::table('cloud_vpc_members')->where('id', 80001)->count() === 1
@ -1184,9 +1236,7 @@ foreach ([
)->update(['created_at' => 0]);
$expectCloudError(static fn () => CloudVpcService::attachMember(
$timestampVpc['vpc_key'], $actor, [
'subnet_key' => $timestampVpc['subnet_key'],
'instance_id' => (int) $invalidCreatedAt['instance_id'],
'private_ip' => (string) $invalidCreatedAt['ip'],
'request_key' => 'reuse-zero-created-' . $invalidCreatedAt['zero'],
]
), 409);
@ -1211,8 +1261,7 @@ $seedPair(90002, 100002, $nextHopReferenced, 9002, 90, '10.50.0.2', 'active');
$seedRoute(100001, $nextHopReferenced, 90002, '10.50.0.3/32', '10.50.0.1');
$expectCloudError(static fn () => CloudVpcService::attachMember(
$nextHopReferenced['vpc_key'], $actor, [
'subnet_key' => $nextHopReferenced['subnet_key'], 'instance_id' => 9001,
'private_ip' => '10.50.0.1', 'request_key' => 'reuse-next-hop-block-0001',
'instance_id' => 9001, 'request_key' => 'reuse-next-hop-block-0001',
]
), 409);
$assert(Capsule::table('cloud_vpc_members')->where('id', 90001)->count() === 1
@ -1244,8 +1293,7 @@ $seedPair(100002, 110002, $destinationReferenced, 10002, 100, '10.51.0.2', 'acti
$seedRoute(110001, $destinationReferenced, 100002, '10.51.0.1/32', '10.51.0.2');
$expectCloudError(static fn () => CloudVpcService::attachMember(
$destinationReferenced['vpc_key'], $actor, [
'subnet_key' => $destinationReferenced['subnet_key'], 'instance_id' => 10001,
'private_ip' => '10.51.0.1', 'request_key' => 'reuse-destination-block-0001',
'instance_id' => 10001, 'request_key' => 'reuse-destination-block-0001',
]
), 409);
$assert(Capsule::table('cloud_vpc_members')->where('id', 100001)->count() === 1
@ -1256,8 +1304,8 @@ $assert(Capsule::table('cloud_vpc_members')->where('id', 100001)->count() === 1
'A live destination /32 reference released the retired member/IP pair.');
// A custom /32 is part of the same route namespace as implicit member /32s.
// Explicit attach must reject it, automatic allocation must skip it, and route
// replacement must not create the inverse conflict against a live member.
// Automatic allocation must skip it, and route replacement must not create the
// inverse conflict against a live member.
$routeReservedMemberKey = $keyFor('member', 190002);
$routeReservedPayload = [[
'route_id' => $keyFor('route', 190001),
@ -1285,15 +1333,8 @@ $expectCloudError(static fn () => CloudVpcService::replaceRoutes(
'request_key' => 'route-member-conflict-0001',
]
), 409);
$expectCloudError(static fn () => CloudVpcService::attachMember(
$routeReserved['vpc_key'], $actor, [
'subnet_key' => $routeReserved['subnet_key'], 'instance_id' => 19001,
'private_ip' => '10.59.0.1', 'request_key' => 'route-ip-explicit-0001',
]
), 409);
CloudVpcService::attachMember($routeReserved['vpc_key'], $actor, [
'subnet_key' => $routeReserved['subnet_key'], 'instance_id' => 19003,
'request_key' => 'route-ip-auto-0001',
'instance_id' => 19003, 'request_key' => 'route-ip-auto-0001',
]);
$assert(Capsule::table('cloud_vpc_members')->where('instance_id', 19001)->count() === 0
&& Capsule::table('cloud_vpc_members')->where('instance_id', 19003)
@ -1329,8 +1370,7 @@ $installCurrentProof($rejoinedHost, [
'host_id' => 120, 'private_ip' => '10.52.0.3'],
], [110, 120]);
CloudVpcService::attachMember($rejoinedHost['vpc_key'], $actor, [
'subnet_key' => $rejoinedHost['subnet_key'], 'instance_id' => 12001,
'private_ip' => '10.52.0.1', 'request_key' => 'reuse-current-host-set-0001',
'instance_id' => 12001, 'request_key' => 'reuse-current-host-set-0001',
]);
$assert(Capsule::table('cloud_vpc_members')->where('id', 120001)->count() === 0
&& Capsule::table('cloud_vpc_private_ips')->where('id', 120101)->count() === 0
@ -1367,8 +1407,7 @@ $installCurrentProof($missingRejoinedHost, [
], [130]);
$expectCloudError(static fn () => CloudVpcService::attachMember(
$missingRejoinedHost['vpc_key'], $actor, [
'subnet_key' => $missingRejoinedHost['subnet_key'], 'instance_id' => 13001,
'private_ip' => '10.53.0.1', 'request_key' => 'reuse-current-host-missing-0001',
'instance_id' => 13001, 'request_key' => 'reuse-current-host-missing-0001',
]
), 409);
$assert(Capsule::table('cloud_vpc_members')->where('id', 130001)->count() === 1
@ -1392,8 +1431,7 @@ $seedInstance(16001, 90);
$seedPair(160001, 160101, $ownerRemoval, 16001, 90, '10.56.0.1');
$installRemovalProof($ownerRemoval, 90, true);
CloudVpcService::attachMember($ownerRemoval['vpc_key'], $actor, [
'subnet_key' => $ownerRemoval['subnet_key'], 'instance_id' => 16001,
'private_ip' => '10.56.0.1', 'request_key' => 'reuse-owner-proof-0001',
'instance_id' => 16001, 'request_key' => 'reuse-owner-proof-0001',
]);
$assert(Capsule::table('cloud_vpc_members')->where('id', 160001)->count() === 0
&& Capsule::table('cloud_vpc_private_ips')->where('id', 160101)->count() === 0
@ -1480,9 +1518,7 @@ foreach ([
}
$expectCloudError(static fn () => CloudVpcService::attachMember(
$partialVpc['vpc_key'], $actor, [
'subnet_key' => $partialVpc['subnet_key'],
'instance_id' => $retiredInstanceId,
'private_ip' => '10.' . $secondOctet . '.0.1',
'request_key' => 'reuse-partial-' . $reason . '-0001',
]
), 409);
@ -1494,9 +1530,7 @@ foreach ([
continue;
}
CloudVpcService::attachMember($partialVpc['vpc_key'], $actor, [
'subnet_key' => $partialVpc['subnet_key'],
'instance_id' => $retiredInstanceId,
'private_ip' => '10.' . $secondOctet . '.0.1',
'request_key' => 'reuse-partial-owner-0001',
]);
$assert(Capsule::table('cloud_vpc_members')
@ -1509,6 +1543,134 @@ foreach ([
'A later global proof did not combine with the exact partial owner receipt.');
}
// Tenant membership intent contains only the instance and idempotency key.
// Subnet selection and private-IP allocation are platform policy, even when a
// caller guesses the current automatically managed values.
$strictAttach = $seedVpc(
22, '10.62.0.0/24', '10.62.0.0/29', 160,
'active', 'active'
);
$seedInstance(22001, 160);
foreach ([
'subnet_key' => $strictAttach['subnet_key'],
'private_ip' => '10.62.0.1',
] as $field => $value) {
$expectCloudError(static fn () => CloudVpcService::attachMember(
$strictAttach['vpc_key'], $actor, [
'instance_id' => 22001,
'request_key' => 'strict-attach-' . str_replace('_', '-', $field),
$field => $value,
]
), 422);
}
$assert(Capsule::table('cloud_vpc_members')->where('vpc_id', 22)->count() === 0
&& Capsule::table('cloud_vpc_private_ips')->where('vpc_id', 22)->count() === 0
&& Capsule::table('cloud_vpc_operations')->where('vpc_id', 22)->count() === 1
&& (int) Capsule::table('cloud_vpcs')->where('id', 22)
->value('desired_revision') === 1,
'Forbidden subnet/private-IP fields changed durable membership state.');
// A missing or cleaning automatic subnet is a retryable policy conflict. The
// service must not fabricate a subnet or allocate an address while its only
// durable subnet identity is still a tombstone.
$cleaningSubnet = $seedVpc(
23, '10.63.0.0/24', '10.63.0.0/29', 170,
'active', 'active'
);
$seedInstance(23001, 170);
Capsule::table('cloud_vpc_subnets')
->where('id', $cleaningSubnet['subnet_id'])->update(['state' => 'deleting']);
$expectCloudError(static fn () => CloudVpcService::attachMember(
$cleaningSubnet['vpc_key'], $actor, [
'instance_id' => 23001, 'request_key' => 'cleaning-subnet-0001',
]
), 409);
$assert(Capsule::table('cloud_vpc_members')->where('vpc_id', 23)->count() === 0
&& Capsule::table('cloud_vpc_private_ips')->where('vpc_id', 23)->count() === 0
&& Capsule::table('cloud_vpc_operations')->where('vpc_id', 23)->count() === 1
&& (int) Capsule::table('cloud_vpcs')->where('id', 23)
->value('desired_revision') === 1,
'A cleaning automatic subnet allowed a partial member attachment.');
// The same conflict applies if a damaged/historical root has no remaining
// subnet row at all. Absence is not permission to recreate policy state during
// an unrelated membership request.
$missingSubnet = $seedVpc(
25, '10.65.0.0/24', '10.65.0.0/29', 190,
'active', 'active'
);
$seedInstance(25001, 190);
Capsule::table('cloud_vpc_subnets')
->where('id', $missingSubnet['subnet_id'])->delete();
$expectCloudError(static fn () => CloudVpcService::attachMember(
$missingSubnet['vpc_key'], $actor, [
'instance_id' => 25001, 'request_key' => 'missing-subnet-0001',
]
), 409);
$assert(Capsule::table('cloud_vpc_members')->where('vpc_id', 25)->count() === 0
&& Capsule::table('cloud_vpc_private_ips')->where('vpc_id', 25)->count() === 0
&& Capsule::table('cloud_vpc_operations')->where('vpc_id', 25)->count() === 1
&& (int) Capsule::table('cloud_vpcs')->where('id', 25)
->value('desired_revision') === 1,
'A missing automatic subnet allowed a partial member attachment.');
// Corrupted automatic-subnet identity must fail before desired-state signing;
// otherwise the engine would reject the malformed subnet_id after local rows
// had already been allocated.
$invalidSubnetKey = $seedVpc(
26, '10.66.0.0/24', '10.66.0.0/29', 200,
'active', 'active'
);
$seedInstance(26001, 200);
Capsule::table('cloud_vpc_subnets')
->where('id', $invalidSubnetKey['subnet_id'])
->update(['subnet_key' => 'invalid-subnet-key']);
$expectCloudError(static fn () => CloudVpcService::attachMember(
$invalidSubnetKey['vpc_key'], $actor, [
'instance_id' => 26001, 'request_key' => 'invalid-subnet-key-0001',
]
), 503);
$assert(Capsule::table('cloud_vpc_members')->where('vpc_id', 26)->count() === 0
&& Capsule::table('cloud_vpc_private_ips')->where('vpc_id', 26)->count() === 0
&& Capsule::table('cloud_vpc_operations')->where('vpc_id', 26)->count() === 1
&& (int) Capsule::table('cloud_vpcs')->where('id', 26)
->value('desired_revision') === 1,
'A malformed automatic subnet identity leaked partial member state.');
// Historical multi-subnet roots remain readable/deletable, but automatic IPAM
// cannot choose between two live ranges. Fail closed before allocating any
// member or operation rather than silently selecting the oldest row.
$multipleSubnets = $seedVpc(
24, '10.64.0.0/24', '10.64.0.0/29', 180,
'active', 'active'
);
$seedInstance(24001, 180);
$secondSubnetNetwork = $ipToInt('10.64.0.8');
Capsule::table('cloud_vpc_subnets')->insert([
'id' => 2024, 'subnet_key' => $keyFor('subnet-extra', 24),
'vpc_id' => 24, 'cidr' => '10.64.0.8/29',
'network_address' => $secondSubnetNetwork,
'broadcast_address' => $secondSubnetNetwork + 7,
'prefix_length' => 29, 'gateway_ip' => null,
'state' => 'active', 'desired_revision' => 1, 'observed_revision' => 1,
'desired_digest' => $multipleSubnets['digest'],
'observed_digest' => $multipleSubnets['digest'],
'last_error_code' => null, 'created_at' => $now, 'updated_at' => $now,
]);
$expectCloudError(static fn () => CloudVpcService::attachMember(
$multipleSubnets['vpc_key'], $actor, [
'instance_id' => 24001, 'request_key' => 'multiple-subnets-0001',
]
), 503);
$assert(Capsule::table('cloud_vpc_members')->where('vpc_id', 24)->count() === 0
&& Capsule::table('cloud_vpc_private_ips')->where('vpc_id', 24)->count() === 0
&& Capsule::table('cloud_vpc_subnets')->where('vpc_id', 24)
->where('state', 'active')->count() === 2
&& Capsule::table('cloud_vpc_operations')->where('vpc_id', 24)->count() === 1
&& (int) Capsule::table('cloud_vpcs')->where('id', 24)
->value('desired_revision') === 1,
'A historical multi-subnet root was mutated or silently auto-selected.');
// A deleting member still owns its address and possible host-side device.
// It must consume capacity until exact tombstone convergence removes it.
$deletingCapacity = $seedVpc(
@ -1524,7 +1686,6 @@ $seedPair(
);
$expectCloudError(static fn () => CloudVpcService::attachMember(
$deletingCapacity['vpc_key'], $actor, [
'subnet_key' => $deletingCapacity['subnet_key'],
'instance_id' => 21002,
'request_key' => 'deleting-capacity-0001',
]

@ -79,10 +79,11 @@ foreach ([
$assert(!str_contains($template, 'id="vpc-create-cidr"')
&& !str_contains($template, 'id="vpc-create-subnet"')
&& !str_contains($template, 'id="vpc-create-max-members"')
&& str_contains($template, '平台将自动分配独立 /24 私网和首个子网'),
&& !str_contains($template, '<label>网络配置</label>')
&& str_contains($template, '分配独立 /24 网段并建立唯一子网'),
'Tenant VPC create form must leave CIDR, subnet and member capacity to platform policy.');
$createStart = strpos($script, 'async function createVpc(');
$createEnd = strpos($script, 'async function submitSubnet(', $createStart ?: 0);
$createEnd = strpos($script, 'async function submitMember(', $createStart ?: 0);
$createSection = $createStart !== false && $createEnd !== false
? substr($script, $createStart, $createEnd - $createStart) : '';
$assert($createSection !== ''
@ -93,22 +94,47 @@ $assert($createSection !== ''
&& !str_contains($createSection, 'form.subnet_cidr')
&& !str_contains($createSection, 'form.max_members'),
'Tenant create JavaScript must submit only name, region and the idempotency key.');
foreach (['子网与 CIDR', '成员与私网 IP', 'Route', 'VPC ACL', '最近操作'] as $label) {
foreach (['成员与私网 IP', 'Route', 'VPC ACL', '最近操作'] as $label) {
$assert(str_contains($script, $label),
'VPC module is missing section ' . $label . '.');
}
$memberRenderStart = strpos($script, 'function renderMembers(');
$memberRenderEnd = strpos($script, 'function routeRow(', $memberRenderStart ?: 0);
$memberRender = $memberRenderStart !== false && $memberRenderEnd !== false
? substr($script, $memberRenderStart, $memberRenderEnd - $memberRenderStart) : '';
$memberSubmitStart = strpos($script, 'async function submitMember(');
$memberSubmitEnd = strpos($script, 'function readRoutes(', $memberSubmitStart ?: 0);
$memberSubmit = $memberSubmitStart !== false && $memberSubmitEnd !== false
? substr($script, $memberSubmitStart, $memberSubmitEnd - $memberSubmitStart) : '';
$assert(!str_contains($script, 'function renderSubnets(')
&& !str_contains($script, '子网与 CIDR')
&& !str_contains($script, 'value.subnets')
&& !str_contains($template, '查看子网、成员'),
'The platform-managed subnet must not be exposed as a tenant management panel.');
$assert($memberRender !== '' && $memberSubmit !== ''
&& !str_contains($memberRender, "name = 'subnet_key'")
&& !str_contains($memberRender, "name = 'private_ip'")
&& str_contains($memberSubmit, 'instance_id: Number(form.instance_id.value)')
&& str_contains($memberSubmit, "request_key: requestKey('member-add')")
&& !str_contains($memberSubmit, 'subnet_key')
&& !str_contains($memberSubmit, 'private_ip'),
'Tenant member attach must submit only the instance and idempotency key.');
$assert(str_contains($template, '创建 VPC'),
'VPC view is missing the create form.');
$assert(str_contains($script, "'/api/v1/vpcs'")
&& str_contains($script, '/subnets')
&& str_contains($script, '/members')
&& str_contains($script, '/reconcile')
&& str_contains($script, "kind === 'routes'")
&& str_contains($script, ": 'acl'")
&& str_contains($script, "'DELETE'")
&& str_contains($script, "'PUT'"),
'VPC module must cover create, subnet, member, route, ACL, reconcile and deletion APIs.');
&& str_contains($script, "'PUT'")
&& !str_contains($script, '/subnets')
&& !str_contains($script, 'submitSubnet(')
&& !str_contains($script, 'removeSubnet(')
&& !str_contains($script, "requestKey('subnet-add')")
&& !str_contains($script, "requestKey('subnet-remove')"),
'VPC module must cover root/member/policy APIs without exposing subnet mutation.');
$assert(str_contains($script, "remove.dataset.vpcAction = 'delete'")
&& str_contains($script, 'async function deleteVpc()')
@ -173,6 +199,10 @@ $assert(!str_contains($script, '/internal/v1/')
$assert(str_contains($styles, '.vpc-state-pill')
&& str_contains($styles, '.vpc-columns')
&& str_contains($styles,
'.vpc-member-form{grid-template-columns:repeat(2,minmax(0,1fr))}')
&& !str_contains($styles,
'.vpc-member-form{grid-template-columns:repeat(4,minmax(0,1fr))}')
&& str_contains($styles, '@media'),
'VPC page needs dedicated state/list/detail responsive styling.');

Loading…
Cancel
Save