feat(vpc): manage regional cidr pools
parent
5d52af8e3c
commit
f2f5bdda74
@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Services\Cloud\CloudAccess;
|
||||
use App\Services\Cloud\CloudAdminVpcCidrPoolService;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudInput;
|
||||
|
||||
/** Administrator API for the region-owned VPC address catalog. */
|
||||
final class CloudAdminVpcController
|
||||
{
|
||||
private function actor($request, bool $write): void
|
||||
{
|
||||
$actor = $request->getAttribute('cloud_actor') ?? CloudAccess::actor(false);
|
||||
if (!($actor['is_admin'] ?? false)) {
|
||||
throw new CloudError('需要管理员权限', 403);
|
||||
}
|
||||
if ($write) {
|
||||
CloudAccess::manage($actor);
|
||||
}
|
||||
}
|
||||
|
||||
public function pools($request, $response, $args = [])
|
||||
{
|
||||
$method = strtoupper((string) $request->getMethod());
|
||||
$write = $method !== 'GET';
|
||||
$this->actor($request, $write);
|
||||
$id = isset($args['id']) ? (int) $args['id'] : null;
|
||||
if (!$write) {
|
||||
$result = $id === null
|
||||
? CloudAdminVpcCidrPoolService::listing()
|
||||
: CloudAdminVpcCidrPoolService::read($id);
|
||||
$status = 200;
|
||||
} else {
|
||||
$body = CloudInput::object($request);
|
||||
CloudInput::only($body, [
|
||||
'region_id', 'name', 'cidr', 'allocation_prefix', 'state',
|
||||
'request_key', 'expected_revision',
|
||||
]);
|
||||
$result = $id === null
|
||||
? CloudAdminVpcCidrPoolService::create($body)
|
||||
: CloudAdminVpcCidrPoolService::update($id, $body);
|
||||
$status = $id === null ? 201 : 200;
|
||||
}
|
||||
return $response->withJson($result, $status)
|
||||
->withHeader('Cache-Control', 'private, no-store');
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,323 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudRegion;
|
||||
use App\Models\CloudVpc;
|
||||
use App\Models\CloudVpcCidrPool;
|
||||
|
||||
/** Region-scoped, non-overlapping RFC1918 allocation boundaries for VPCs. */
|
||||
final class CloudAdminVpcCidrPoolService
|
||||
{
|
||||
private const STATES = ['active', 'disabled'];
|
||||
|
||||
public static function listing(): array
|
||||
{
|
||||
$regions = CloudRegion::query()->orderBy('sort')->orderBy('id')
|
||||
->get(['id', 'code', 'name', 'country_code', 'status'])
|
||||
->map(static fn ($region): array => [
|
||||
'id' => (int) $region->id,
|
||||
'code' => (string) $region->code,
|
||||
'name' => (string) $region->name,
|
||||
'country_code' => (string) $region->country_code,
|
||||
'status' => (string) $region->status,
|
||||
])->all();
|
||||
$regionNames = [];
|
||||
foreach ($regions as $region) {
|
||||
$regionNames[$region['id']] = $region['name'];
|
||||
}
|
||||
$usage = CloudVpc::query()->where('active_claim', 1)
|
||||
->selectRaw('cidr_pool_id, COUNT(*) AS row_count')
|
||||
->groupBy('cidr_pool_id')->pluck('row_count', 'cidr_pool_id');
|
||||
$items = CloudVpcCidrPool::query()->orderBy('region_id')->orderBy('id')
|
||||
->get()->map(static fn ($pool): array => self::dto(
|
||||
$pool,
|
||||
(string) ($regionNames[(int) $pool->region_id]
|
||||
?? '地区已缺失'),
|
||||
(int) ($usage[(int) $pool->id] ?? 0)
|
||||
))->all();
|
||||
return [
|
||||
'regions' => $regions,
|
||||
'items' => $items,
|
||||
'feature_enabled' => CloudVpcFeature::enabled(),
|
||||
];
|
||||
}
|
||||
|
||||
public static function read(int $id): array
|
||||
{
|
||||
$pool = self::pool($id);
|
||||
$region = CloudRegion::find((int) $pool->region_id);
|
||||
return ['item' => self::dto(
|
||||
$pool,
|
||||
(string) ($region?->name ?? '地区已缺失'),
|
||||
self::activeUsage((int) $pool->id)
|
||||
)];
|
||||
}
|
||||
|
||||
public static function create(array $input): array
|
||||
{
|
||||
$requestKey = $input['request_key'] ?? null;
|
||||
if (!is_string($requestKey)
|
||||
|| preg_match('/^[0-9a-f]{32}$/D', $requestKey) !== 1) {
|
||||
throw new CloudError('请提供有效的 VPC 地址池创建请求标识');
|
||||
}
|
||||
$desired = self::normalize($input);
|
||||
$poolKey = substr(hash('sha256', "vpc-cidr-pool\0" . $requestKey),
|
||||
0, 32);
|
||||
return self::persist(null, $poolKey, 0, $desired);
|
||||
}
|
||||
|
||||
public static function update(int $id, array $input): array
|
||||
{
|
||||
$expected = $input['expected_revision'] ?? null;
|
||||
if (is_bool($expected) || !is_int($expected) || $expected < 1) {
|
||||
throw new CloudError('VPC 地址池版本无效,请刷新后重试', 409);
|
||||
}
|
||||
return self::persist($id, '', $expected, self::normalize($input));
|
||||
}
|
||||
|
||||
private static function persist(?int $id, string $poolKey,
|
||||
int $expectedRevision, array $desired): array
|
||||
{
|
||||
$connection = (new CloudVpcCidrPool())->getConnection();
|
||||
$pool = $connection->transaction(static function () use (
|
||||
$id, $poolKey, $expectedRevision, $desired
|
||||
): CloudVpcCidrPool {
|
||||
$region = CloudRegion::query()->where('id', $desired['region_id'])
|
||||
->lockForUpdate()->first();
|
||||
if ($region === null) {
|
||||
throw new CloudError('VPC 地址池所属地区不存在', 404);
|
||||
}
|
||||
$rows = CloudVpcCidrPool::query()
|
||||
->where('region_id', $desired['region_id'])
|
||||
->orderBy('id')->lockForUpdate()->get();
|
||||
$pool = $id === null
|
||||
? $rows->first(static fn ($row): bool =>
|
||||
hash_equals((string) $row->pool_key, $poolKey))
|
||||
: $rows->first(static fn ($row): bool =>
|
||||
(int) $row->id === $id);
|
||||
|
||||
if ($id === null && $pool !== null) {
|
||||
if (self::same($pool, $desired)) {
|
||||
return $pool;
|
||||
}
|
||||
throw new CloudError(
|
||||
'同一创建请求标识不能用于不同的 VPC 地址池配置', 409
|
||||
);
|
||||
}
|
||||
if ($id !== null && $pool === null) {
|
||||
if (CloudVpcCidrPool::find($id) !== null) {
|
||||
throw new CloudError('VPC 地址池不允许更换所属地区', 409);
|
||||
}
|
||||
throw new CloudError('VPC 地址池不存在', 404);
|
||||
}
|
||||
if ($pool !== null
|
||||
&& (int) $pool->revision !== $expectedRevision) {
|
||||
throw new CloudError(
|
||||
'VPC 地址池配置已被修改,请刷新后重试', 409
|
||||
);
|
||||
}
|
||||
|
||||
$usage = $pool === null ? 0 : CloudVpc::query()
|
||||
->where('cidr_pool_id', (int) $pool->id)
|
||||
->where('active_claim', 1)->orderBy('id')
|
||||
->lockForUpdate()->get(['id'])->count();
|
||||
if ($pool !== null && $usage > 0
|
||||
&& ((string) $pool->cidr !== $desired['cidr']
|
||||
|| (int) $pool->allocation_prefix
|
||||
!== $desired['allocation_prefix'])) {
|
||||
throw new CloudError(
|
||||
'该地址池仍有 VPC 占用,不能修改 CIDR 或分配前缀', 409
|
||||
);
|
||||
}
|
||||
foreach ($rows as $other) {
|
||||
if ($pool !== null && (int) $other->id === (int) $pool->id) {
|
||||
continue;
|
||||
}
|
||||
if (self::overlaps($desired['cidr'], (string) $other->cidr)) {
|
||||
throw new CloudError(
|
||||
'同一地区的 VPC 地址池不能重叠', 409
|
||||
);
|
||||
}
|
||||
}
|
||||
if ($pool !== null && self::same($pool, $desired)) {
|
||||
return $pool;
|
||||
}
|
||||
$now = time();
|
||||
if ($pool === null) {
|
||||
$pool = new CloudVpcCidrPool();
|
||||
$pool->pool_key = $poolKey;
|
||||
$pool->created_at = $now;
|
||||
$pool->revision = 1;
|
||||
} else {
|
||||
$pool->revision = (int) $pool->revision + 1;
|
||||
}
|
||||
foreach ($desired as $field => $value) {
|
||||
$pool->{$field} = $value;
|
||||
}
|
||||
$pool->updated_at = $now;
|
||||
$pool->save();
|
||||
return $pool;
|
||||
}, 3);
|
||||
$region = CloudRegion::find((int) $pool->region_id);
|
||||
return ['item' => self::dto(
|
||||
$pool,
|
||||
(string) ($region?->name ?? '地区已缺失'),
|
||||
self::activeUsage((int) $pool->id)
|
||||
)];
|
||||
}
|
||||
|
||||
private static function normalize(array $input): array
|
||||
{
|
||||
$regionId = $input['region_id'] ?? null;
|
||||
$name = $input['name'] ?? null;
|
||||
$cidr = $input['cidr'] ?? null;
|
||||
$allocationPrefix = $input['allocation_prefix'] ?? null;
|
||||
$state = $input['state'] ?? null;
|
||||
if (is_bool($regionId) || !is_int($regionId) || $regionId < 1) {
|
||||
throw new CloudError('请选择有效的 VPC 地址池所属地区');
|
||||
}
|
||||
if (!is_string($name) || ($name = trim($name)) === ''
|
||||
|| mb_strlen($name) > 80
|
||||
|| preg_match('/[\x00-\x1f\x7f]/u', $name) === 1) {
|
||||
throw new CloudError('VPC 地址池名称需为 1 至 80 个字符');
|
||||
}
|
||||
[$normalizedCidr, $prefix] = self::normalizeCidr($cidr);
|
||||
if (is_bool($allocationPrefix) || !is_int($allocationPrefix)
|
||||
|| $allocationPrefix < $prefix || $allocationPrefix > 28) {
|
||||
throw new CloudError(
|
||||
'VPC 分配前缀必须不小于地址池前缀,且不能大于 28'
|
||||
);
|
||||
}
|
||||
if (!is_string($state) || !in_array($state, self::STATES, true)) {
|
||||
throw new CloudError('VPC 地址池状态无效');
|
||||
}
|
||||
return [
|
||||
'region_id' => $regionId,
|
||||
'name' => $name,
|
||||
'cidr' => $normalizedCidr,
|
||||
'prefix_length' => $prefix,
|
||||
'allocation_prefix' => $allocationPrefix,
|
||||
'state' => $state,
|
||||
];
|
||||
}
|
||||
|
||||
private static function normalizeCidr(mixed $value): array
|
||||
{
|
||||
if (!is_string($value)
|
||||
|| preg_match('/^([^\/]+)\/([0-9]{1,2})$/D', trim($value),
|
||||
$match) !== 1
|
||||
|| filter_var($match[1], FILTER_VALIDATE_IP,
|
||||
FILTER_FLAG_IPV4) === false) {
|
||||
throw new CloudError('VPC 地址池必须填写有效的 RFC1918 IPv4 CIDR');
|
||||
}
|
||||
$prefix = (int) $match[2];
|
||||
if ($prefix < 8 || $prefix > 28) {
|
||||
throw new CloudError('VPC 地址池前缀必须为 /8 至 /28');
|
||||
}
|
||||
$address = self::number($match[1]);
|
||||
$mask = self::mask($prefix);
|
||||
$network = $address & $mask;
|
||||
if ($network !== $address) {
|
||||
throw new CloudError('VPC 地址池 CIDR 必须填写规范网络地址');
|
||||
}
|
||||
$end = $network | (~$mask & 0xffffffff);
|
||||
if (!self::insidePrivateRange($network, $end)) {
|
||||
throw new CloudError('VPC 地址池必须完整位于 RFC1918 私网范围');
|
||||
}
|
||||
return [long2ip($network) . '/' . $prefix, $prefix];
|
||||
}
|
||||
|
||||
private static function insidePrivateRange(int $start, int $end): bool
|
||||
{
|
||||
foreach ([['10.0.0.0', 8], ['172.16.0.0', 12],
|
||||
['192.168.0.0', 16]] as [$address, $prefix]) {
|
||||
$base = self::number($address);
|
||||
$last = $base | (~self::mask($prefix) & 0xffffffff);
|
||||
if ($start >= $base && $end <= $last) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function overlaps(string $left, string $right): bool
|
||||
{
|
||||
[$leftStart, $leftEnd] = self::bounds($left);
|
||||
[$rightStart, $rightEnd] = self::bounds($right);
|
||||
return $leftStart <= $rightEnd && $rightStart <= $leftEnd;
|
||||
}
|
||||
|
||||
private static function bounds(string $cidr): array
|
||||
{
|
||||
[$address, $prefix] = explode('/', $cidr, 2);
|
||||
$start = self::number($address) & self::mask((int) $prefix);
|
||||
return [$start,
|
||||
$start | (~self::mask((int) $prefix) & 0xffffffff)];
|
||||
}
|
||||
|
||||
private static function number(string $address): int
|
||||
{
|
||||
$packed = inet_pton($address);
|
||||
if ($packed === false || strlen($packed) !== 4) {
|
||||
throw new CloudError('VPC IPv4 地址格式无效');
|
||||
}
|
||||
return (int) unpack('Naddress', $packed)['address'];
|
||||
}
|
||||
|
||||
private static function mask(int $prefix): int
|
||||
{
|
||||
return (0xffffffff << (32 - $prefix)) & 0xffffffff;
|
||||
}
|
||||
|
||||
private static function same(CloudVpcCidrPool $pool,
|
||||
array $desired): bool
|
||||
{
|
||||
foreach ($desired as $field => $value) {
|
||||
if ((string) $pool->{$field} !== (string) $value) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static function activeUsage(int $poolId): int
|
||||
{
|
||||
return (int) CloudVpc::query()->where('cidr_pool_id', $poolId)
|
||||
->where('active_claim', 1)->count();
|
||||
}
|
||||
|
||||
private static function pool(int $id): CloudVpcCidrPool
|
||||
{
|
||||
$pool = $id > 0 ? CloudVpcCidrPool::find($id) : null;
|
||||
if ($pool === null) {
|
||||
throw new CloudError('VPC 地址池不存在', 404);
|
||||
}
|
||||
return $pool;
|
||||
}
|
||||
|
||||
private static function dto(CloudVpcCidrPool $pool, string $regionName,
|
||||
int $used): array
|
||||
{
|
||||
$capacity = 1 << ((int) $pool->allocation_prefix
|
||||
- (int) $pool->prefix_length);
|
||||
return [
|
||||
'id' => (int) $pool->id,
|
||||
'pool_key' => (string) $pool->pool_key,
|
||||
'region_id' => (int) $pool->region_id,
|
||||
'region_name' => $regionName,
|
||||
'name' => (string) $pool->name,
|
||||
'cidr' => (string) $pool->cidr,
|
||||
'prefix_length' => (int) $pool->prefix_length,
|
||||
'allocation_prefix' => (int) $pool->allocation_prefix,
|
||||
'state' => (string) $pool->state,
|
||||
'revision' => (int) $pool->revision,
|
||||
'used' => $used,
|
||||
'capacity' => $capacity,
|
||||
'available' => max(0, $capacity - $used),
|
||||
'address_locked' => $used > 0,
|
||||
'created_at' => (int) $pool->created_at,
|
||||
'updated_at' => (int) $pool->updated_at,
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,66 @@
|
||||
const root = document.querySelector('[data-admin-vpc]');
|
||||
const byId = id => document.getElementById(id);
|
||||
const canManage = root?.dataset.canManage === '1';
|
||||
const state = { csrf: window.ADMIN_CSRF_TOKEN || '', regions: [], items: [], busy: false, requestKey: '' };
|
||||
|
||||
function notice(message, error = false) {
|
||||
const box = byId('admin-vpc-status'); box.textContent = message; box.className = `alert ${error ? 'alert-danger' : 'alert-info'} cloud-admin-notice`;
|
||||
}
|
||||
function errorMessage(payload, status) { return String(payload?.detail || payload?.error || `请求失败 (${status})`); }
|
||||
async function api(path, options = {}) {
|
||||
const method = (options.method || 'GET').toUpperCase(); const headers = new Headers({ Accept: 'application/json' });
|
||||
if (!['GET', 'HEAD'].includes(method)) { headers.set('Content-Type', 'application/json'); headers.set('X-CSRF-Token', state.csrf); }
|
||||
const response = await fetch(path, { method, headers, credentials: 'same-origin', cache: 'no-store', body: options.body === undefined ? undefined : JSON.stringify(options.body) });
|
||||
let payload; try { payload = await response.json(); } catch { throw new Error('服务返回非 JSON 响应。'); }
|
||||
if (response.status === 401) { location.assign('/auth/login'); throw new Error('登录已过期。'); }
|
||||
if (!response.ok) throw new Error(errorMessage(payload, response.status)); return payload;
|
||||
}
|
||||
function newRequestKey() {
|
||||
if (!globalThis.crypto?.getRandomValues) throw new Error('浏览器无法生成安全创建标识,请升级浏览器。');
|
||||
const bytes = new Uint8Array(16); globalThis.crypto.getRandomValues(bytes); return Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
function renderRegions(selected = '') {
|
||||
const select = byId('admin-vpc-pool-region'); select.replaceChildren();
|
||||
const empty = document.createElement('option'); empty.value = ''; empty.textContent = state.regions.length ? '请选择地区' : '请先创建地区'; select.append(empty);
|
||||
for (const region of state.regions) { const option = document.createElement('option'); option.value = String(region.id); option.textContent = `${region.name} · ${region.country_code}${region.status === 'active' ? '' : '(停用)'}`; option.selected = String(region.id) === String(selected); select.append(option); }
|
||||
}
|
||||
function lockAddressFields(editing) {
|
||||
byId('admin-vpc-pool-region').disabled = !canManage || editing;
|
||||
byId('admin-vpc-pool-cidr').disabled = !canManage || (editing && byId('admin-vpc-pool-cidr').dataset.locked === '1');
|
||||
byId('admin-vpc-pool-prefix').disabled = !canManage || (editing && byId('admin-vpc-pool-prefix').dataset.locked === '1');
|
||||
}
|
||||
function resetForm() {
|
||||
byId('admin-vpc-pool-form').reset(); byId('admin-vpc-pool-id').value = ''; byId('admin-vpc-pool-revision').value = '0'; byId('admin-vpc-pool-prefix').value = '24'; byId('admin-vpc-pool-state').value = 'active'; byId('admin-vpc-pool-title').textContent = '添加 VPC 地址池'; byId('admin-vpc-pool-capacity').textContent = '保存后显示可分配子网数量。'; delete byId('admin-vpc-pool-cidr').dataset.locked; delete byId('admin-vpc-pool-prefix').dataset.locked; state.requestKey = newRequestKey(); renderRegions(); lockAddressFields(false);
|
||||
}
|
||||
function editPool(pool) {
|
||||
byId('admin-vpc-pool-id').value = pool.id; byId('admin-vpc-pool-revision').value = pool.revision; byId('admin-vpc-pool-title').textContent = `编辑地址池 · ${pool.name}`; renderRegions(pool.region_id); byId('admin-vpc-pool-name').value = pool.name; byId('admin-vpc-pool-cidr').value = pool.cidr; byId('admin-vpc-pool-prefix').value = pool.allocation_prefix; byId('admin-vpc-pool-state').value = pool.state; byId('admin-vpc-pool-cidr').dataset.locked = pool.address_locked ? '1' : '0'; byId('admin-vpc-pool-prefix').dataset.locked = pool.address_locked ? '1' : '0'; byId('admin-vpc-pool-capacity').textContent = `${pool.used} 个已占用 · ${pool.available} 个可用 · 共 ${pool.capacity} 个 /${pool.allocation_prefix} 子网${pool.address_locked ? ';地址边界已锁定' : ''}`; lockAddressFields(true);
|
||||
}
|
||||
function renderList() {
|
||||
const list = byId('admin-vpc-pool-list'); list.replaceChildren();
|
||||
if (!state.items.length) { const empty = document.createElement('p'); empty.className = 'text-muted'; empty.textContent = '暂无 VPC 地址池。'; list.append(empty); return; }
|
||||
for (const pool of state.items) { const button = document.createElement('button'); button.type = 'button'; button.className = 'btn btn-light cloud-admin-host'; const strong = document.createElement('strong'); strong.textContent = pool.name; const detail = document.createElement('div'); detail.className = 'text-muted'; detail.textContent = `${pool.region_name} · ${pool.cidr} → /${pool.allocation_prefix} · ${pool.used}/${pool.capacity} · ${pool.state === 'active' ? '启用' : '停用'}`; button.append(strong, detail); button.addEventListener('click', () => editPool(pool)); list.append(button); }
|
||||
}
|
||||
async function load() {
|
||||
const payload = await api('/api/v1/admin/vpc-cidr-pools'); state.regions = Array.isArray(payload.regions) ? payload.regions : []; state.items = Array.isArray(payload.items) ? payload.items : []; renderList();
|
||||
}
|
||||
function requestBody() {
|
||||
const regionId = Number(byId('admin-vpc-pool-region').value); const prefix = Number(byId('admin-vpc-pool-prefix').value); const id = byId('admin-vpc-pool-id').value;
|
||||
if (!Number.isInteger(regionId) || regionId < 1) throw new Error('请选择所属地区。');
|
||||
if (!Number.isInteger(prefix) || prefix < 8 || prefix > 28) throw new Error('VPC 分配前缀必须是 8 至 28 的整数。');
|
||||
const result = { region_id: regionId, name: byId('admin-vpc-pool-name').value.trim(), cidr: byId('admin-vpc-pool-cidr').value.trim(), allocation_prefix: prefix, state: byId('admin-vpc-pool-state').value };
|
||||
if (id) result.expected_revision = Number(byId('admin-vpc-pool-revision').value); else result.request_key = state.requestKey;
|
||||
return result;
|
||||
}
|
||||
async function save(event) {
|
||||
event.preventDefault(); if (!canManage || state.busy) return; let payload; try { payload = requestBody(); } catch (error) { notice(error.message, true); return; }
|
||||
const id = byId('admin-vpc-pool-id').value; state.busy = true; byId('admin-vpc-pool-save').disabled = true; notice('正在保存 VPC 地址池…');
|
||||
try { const result = await api(`/api/v1/admin/vpc-cidr-pools${id ? '/' + encodeURIComponent(id) : ''}`, { method: id ? 'PATCH' : 'POST', body: payload }); await load(); editPool(result.item); notice(id ? 'VPC 地址池已更新。' : 'VPC 地址池已创建。'); }
|
||||
catch (error) { try { await load(); } catch {} notice(error.message, true); }
|
||||
finally { state.busy = false; byId('admin-vpc-pool-save').disabled = !canManage; }
|
||||
}
|
||||
async function initialize() {
|
||||
if (!root) return;
|
||||
try { const session = await api('/api/v1/session'); state.csrf = session.csrf_token || state.csrf; if (!session.admin || !state.csrf) throw new Error('管理员会话无效,请重新登录。'); await load(); resetForm(); byId('admin-vpc-pool-new').addEventListener('click', resetForm); byId('admin-vpc-pool-form').addEventListener('submit', save); notice('VPC 地址池目录已读取。功能开关仍保持关闭。'); }
|
||||
catch (error) { notice(error.message, true); }
|
||||
}
|
||||
void initialize();
|
||||
@ -1,2 +1,2 @@
|
||||
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
|
||||
{assign var=venix_asset_version value='2026102805' scope='global'}
|
||||
{assign var=venix_asset_version value='2026102806' scope='global'}
|
||||
|
||||
@ -0,0 +1,146 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Cloud\CloudAdminVpcCidrPoolService;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$expectConflict = static function (callable $callback, string $message) use (
|
||||
$assert
|
||||
): void {
|
||||
try {
|
||||
$callback();
|
||||
throw new RuntimeException($message);
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === 409,
|
||||
$message . ' (status ' . $error->httpStatus . ')');
|
||||
}
|
||||
};
|
||||
|
||||
$capsule = new Capsule();
|
||||
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
|
||||
$capsule->setAsGlobal();
|
||||
$capsule->bootEloquent();
|
||||
$schema = $capsule->schema('default');
|
||||
$schema->create('cloud_regions', static function (Blueprint $table): void {
|
||||
$table->increments('id'); $table->string('code'); $table->string('name');
|
||||
$table->string('country_code', 2); $table->string('status');
|
||||
$table->integer('sort'); $table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
$schema->create('cloud_vpc_cidr_pools',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id'); $table->string('pool_key', 32)->unique();
|
||||
$table->integer('region_id'); $table->string('name');
|
||||
$table->string('cidr', 18); $table->integer('prefix_length');
|
||||
$table->integer('allocation_prefix'); $table->string('state');
|
||||
$table->integer('revision'); $table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
$schema->create('cloud_vpcs', static function (Blueprint $table): void {
|
||||
$table->increments('id'); $table->string('vpc_key', 32);
|
||||
$table->integer('user_id'); $table->integer('region_id');
|
||||
$table->integer('cidr_pool_id'); $table->string('name');
|
||||
$table->string('cidr', 18); $table->integer('prefix_length');
|
||||
$table->string('gateway', 15); $table->integer('active_claim')->nullable();
|
||||
$table->string('state'); $table->integer('desired_revision');
|
||||
$table->integer('deleted_at')->nullable(); $table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
Capsule::table('cloud_regions')->insert([
|
||||
['id' => 1, 'code' => 'hkg', 'name' => 'Hong Kong',
|
||||
'country_code' => 'HK', 'status' => 'active', 'sort' => 0,
|
||||
'created_at' => 1, 'updated_at' => 1],
|
||||
['id' => 2, 'code' => 'nrt', 'name' => 'Tokyo',
|
||||
'country_code' => 'JP', 'status' => 'active', 'sort' => 1,
|
||||
'created_at' => 1, 'updated_at' => 1],
|
||||
]);
|
||||
|
||||
$created = CloudAdminVpcCidrPoolService::create([
|
||||
'request_key' => str_repeat('a', 32), 'region_id' => 1,
|
||||
'name' => 'HKG Private', 'cidr' => '10.64.0.0/12',
|
||||
'allocation_prefix' => 24, 'state' => 'active',
|
||||
]);
|
||||
$pool = $created['item'];
|
||||
$assert($pool['revision'] === 1 && $pool['capacity'] === 4096
|
||||
&& $pool['available'] === 4096 && $pool['address_locked'] === false,
|
||||
'VPC pool capacity or initial revision is incorrect.');
|
||||
|
||||
$replay = CloudAdminVpcCidrPoolService::create([
|
||||
'request_key' => str_repeat('a', 32), 'region_id' => 1,
|
||||
'name' => 'HKG Private', 'cidr' => '10.64.0.0/12',
|
||||
'allocation_prefix' => 24, 'state' => 'active',
|
||||
]);
|
||||
$assert($replay['item']['id'] === $pool['id']
|
||||
&& Capsule::table('cloud_vpc_cidr_pools')->count() === 1,
|
||||
'Idempotent VPC pool creation produced a duplicate.');
|
||||
|
||||
$expectConflict(static fn () => CloudAdminVpcCidrPoolService::create([
|
||||
'request_key' => str_repeat('b', 32), 'region_id' => 1,
|
||||
'name' => 'Overlap', 'cidr' => '10.64.16.0/20',
|
||||
'allocation_prefix' => 24, 'state' => 'active',
|
||||
]), 'Overlapping pools in one region were accepted.');
|
||||
|
||||
$otherRegion = CloudAdminVpcCidrPoolService::create([
|
||||
'request_key' => str_repeat('c', 32), 'region_id' => 2,
|
||||
'name' => 'NRT Private', 'cidr' => '10.64.0.0/12',
|
||||
'allocation_prefix' => 24, 'state' => 'active',
|
||||
]);
|
||||
$assert($otherRegion['item']['region_id'] === 2,
|
||||
'Identical private ranges in isolated regions were incorrectly rejected.');
|
||||
|
||||
try {
|
||||
CloudAdminVpcCidrPoolService::create([
|
||||
'request_key' => str_repeat('d', 32), 'region_id' => 1,
|
||||
'name' => 'Noncanonical', 'cidr' => '10.80.1.1/16',
|
||||
'allocation_prefix' => 24, 'state' => 'active',
|
||||
]);
|
||||
throw new RuntimeException('Noncanonical private CIDR was accepted.');
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === 422,
|
||||
'Noncanonical CIDR rejection used the wrong status.');
|
||||
}
|
||||
|
||||
$updated = CloudAdminVpcCidrPoolService::update($pool['id'], [
|
||||
'region_id' => 1, 'name' => 'HKG Primary', 'cidr' => '10.64.0.0/12',
|
||||
'allocation_prefix' => 24, 'state' => 'active',
|
||||
'expected_revision' => 1,
|
||||
]);
|
||||
$assert($updated['item']['revision'] === 2
|
||||
&& $updated['item']['name'] === 'HKG Primary',
|
||||
'VPC pool update did not advance the revision.');
|
||||
|
||||
Capsule::table('cloud_vpcs')->insert([
|
||||
'id' => 1, 'vpc_key' => str_repeat('e', 32), 'user_id' => 7,
|
||||
'region_id' => 1, 'cidr_pool_id' => $pool['id'], 'name' => 'prod',
|
||||
'cidr' => '10.64.0.0/24', 'prefix_length' => 24,
|
||||
'gateway' => '10.64.0.1', 'active_claim' => 1, 'state' => 'active',
|
||||
'desired_revision' => 1, 'deleted_at' => null,
|
||||
'created_at' => 2, 'updated_at' => 2,
|
||||
]);
|
||||
$expectConflict(static fn () => CloudAdminVpcCidrPoolService::update(
|
||||
$pool['id'], [
|
||||
'region_id' => 1, 'name' => 'HKG Primary',
|
||||
'cidr' => '10.96.0.0/12', 'allocation_prefix' => 24,
|
||||
'state' => 'active', 'expected_revision' => 2,
|
||||
]
|
||||
), 'Occupied VPC pool boundary was editable.');
|
||||
|
||||
$disabled = CloudAdminVpcCidrPoolService::update($pool['id'], [
|
||||
'region_id' => 1, 'name' => 'HKG Primary', 'cidr' => '10.64.0.0/12',
|
||||
'allocation_prefix' => 24, 'state' => 'disabled',
|
||||
'expected_revision' => 2,
|
||||
]);
|
||||
$assert($disabled['item']['revision'] === 3
|
||||
&& $disabled['item']['used'] === 1
|
||||
&& $disabled['item']['address_locked'] === true,
|
||||
'Occupied pool could not be safely disabled or usage was lost.');
|
||||
|
||||
echo "Administrator VPC CIDR pool service passed.\n";
|
||||
@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$routes = file_get_contents($root . '/config/routes.php');
|
||||
$apiRoutes = file_get_contents($root . '/config/routes_cloud.php');
|
||||
$pageController = file_get_contents(
|
||||
$root . '/app/Controllers/Admin/CloudPageController.php'
|
||||
);
|
||||
$apiController = file_get_contents(
|
||||
$root . '/app/Controllers/CloudAdminVpcController.php'
|
||||
);
|
||||
$sidebar = file_get_contents(
|
||||
$root . '/resources/views/venix/admin/static_header.tpl'
|
||||
);
|
||||
$template = file_get_contents(
|
||||
$root . '/resources/views/venix/admin/cloud/vpc.tpl'
|
||||
);
|
||||
$javascript = file_get_contents($root . '/public/cloud/admin-vpc.js');
|
||||
$assets = file_get_contents(
|
||||
$root . '/resources/views/venix/layout_assets.tpl'
|
||||
);
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$assert(str_contains($routes, "'/vpc'")
|
||||
&& str_contains($pageController, "display('admin/cloud/vpc.tpl')")
|
||||
&& str_contains($sidebar, 'href="/admin/vpc"'),
|
||||
'Administrator VPC page is not reachable from the virtualization sidebar.');
|
||||
$assert(str_contains($apiRoutes, "'/admin/vpc-cidr-pools'")
|
||||
&& str_contains($apiRoutes, "'/admin/vpc-cidr-pools/{id:")
|
||||
&& str_contains($apiController, 'CloudAccess::manage($actor)')
|
||||
&& str_contains($apiController,
|
||||
"'Cache-Control', 'private, no-store'"),
|
||||
'Administrator VPC CIDR pool API contract is incomplete.');
|
||||
$assert(str_contains($template, 'data-admin-vpc')
|
||||
&& str_contains($template, 'id="admin-vpc-pool-form"')
|
||||
&& str_contains($template, '/cloud/admin-vpc.js?v={$venix_asset_version}')
|
||||
&& str_contains($javascript, 'globalThis.crypto?.getRandomValues')
|
||||
&& str_contains($javascript, "method: id ? 'PATCH' : 'POST'"),
|
||||
'Administrator VPC CIDR pool UI lost its versioned or idempotent workflow.');
|
||||
$assert(preg_match("/venix_asset_version value='([0-9]+)'/", $assets,
|
||||
$version) === 1
|
||||
&& (int) $version[1] >= 2026102806,
|
||||
'Administrator VPC browser assets were not cache-busted.');
|
||||
|
||||
echo "Administrator VPC CIDR pool page and API contracts passed.\n";
|
||||
Loading…
Reference in New Issue