feat: add admin fabric topology console
parent
7082107662
commit
ab1a04d297
@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Services\Cloud\CloudAccess;
|
||||
use App\Services\Cloud\CloudAdminFabricService;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudInput;
|
||||
|
||||
/** Administrator-only Fabric topology and reconciliation API. */
|
||||
final class CloudAdminFabricController
|
||||
{
|
||||
private function actor($request, bool $write = false): array
|
||||
{
|
||||
$actor = $request->getAttribute('cloud_actor') ?? CloudAccess::actor(false);
|
||||
if (!($actor['is_admin'] ?? false)) {
|
||||
throw new CloudError('需要管理员权限', 403);
|
||||
}
|
||||
if ($write) {
|
||||
CloudAccess::manage($actor);
|
||||
if (!($actor['is_super_admin'] ?? false)) {
|
||||
throw new CloudError('仅超级管理员可以修改 Fabric', 403);
|
||||
}
|
||||
}
|
||||
return $actor;
|
||||
}
|
||||
|
||||
private function json($response, array $payload, int $status = 200)
|
||||
{
|
||||
return $response->withJson($payload, $status)
|
||||
->withHeader('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function index($request, $response)
|
||||
{
|
||||
return $this->json($response,
|
||||
CloudAdminFabricService::listing($this->actor($request)));
|
||||
}
|
||||
|
||||
public function detail($request, $response, $args)
|
||||
{
|
||||
return $this->json($response,
|
||||
CloudAdminFabricService::detail(
|
||||
(string) ($args['fabric_id'] ?? ''), $this->actor($request)
|
||||
));
|
||||
}
|
||||
|
||||
public function apply($request, $response)
|
||||
{
|
||||
$actor = $this->actor($request, true);
|
||||
$body = CloudInput::object($request, 131072);
|
||||
return $this->json($response,
|
||||
CloudAdminFabricService::apply($body, $actor), 200);
|
||||
}
|
||||
|
||||
public function reconcile($request, $response, $args)
|
||||
{
|
||||
$actor = $this->actor($request, true);
|
||||
$body = trim((string) $request->getBody());
|
||||
if ($body !== '' && $body !== '{}') {
|
||||
throw new CloudError('Fabric reconcile 不接受请求体', 422);
|
||||
}
|
||||
return $this->json($response,
|
||||
CloudAdminFabricService::reconcile(
|
||||
(string) ($args['fabric_id'] ?? ''), $actor
|
||||
));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,613 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudHost;
|
||||
use App\Models\CloudRegion;
|
||||
use App\Models\CloudRegionFabric;
|
||||
|
||||
/**
|
||||
* Administrator projection and mutation boundary for the host WireGuard
|
||||
* Fabric. Engine responses are treated as untrusted DTOs at this boundary:
|
||||
* only the bounded status fields needed by the admin page are returned.
|
||||
*/
|
||||
final class CloudAdminFabricService
|
||||
{
|
||||
private const FABRIC_ID = '/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/D';
|
||||
private const HOST_ID = '/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/D';
|
||||
private const KEY = '/^[A-Za-z0-9+\/]{42}==\z|^[A-Za-z0-9+\/]{43}=\z/D';
|
||||
private const STATES = ['applying', 'active', 'degraded', 'uncertain'];
|
||||
private const FABRIC_WRITE_TIMEOUT_SECONDS = 120.0;
|
||||
private const ERROR_CODES = [
|
||||
'fabric_apply_unconfirmed', 'fabric_host_capability_missing',
|
||||
'fabric_host_capability_probe_failed', 'fabric_host_capability_probe_invalid',
|
||||
'fabric_host_capability_probe_unsupported', 'fabric_host_connection_failed',
|
||||
'fabric_host_identity_mismatch', 'fabric_host_interface_conflict',
|
||||
'fabric_host_key_locked', 'fabric_host_network_manager_conflict',
|
||||
'fabric_host_not_configured', 'fabric_host_unavailable',
|
||||
'fabric_identity_conflict', 'fabric_identity_invalid', 'fabric_invalid',
|
||||
'fabric_membership_conflict', 'fabric_not_found', 'fabric_overlay_conflict',
|
||||
'fabric_plan_corrupt', 'fabric_readback_invalid', 'fabric_record_corrupt',
|
||||
'fabric_region_mismatch', 'fabric_remote_command_failed',
|
||||
'fabric_revision_conflict', 'fabric_runner_unsupported',
|
||||
];
|
||||
|
||||
public static function listing(array $actor, ?CloudEngineClient $engine = null): array
|
||||
{
|
||||
self::assertReadActor($actor);
|
||||
$engine ??= new CloudEngineClient();
|
||||
try {
|
||||
$raw = $engine->fabricStatuses($actor);
|
||||
} catch (CloudError $exception) {
|
||||
// Keep the platform-owned region mapping visible when a host or
|
||||
// engine is unavailable. This is a diagnostic snapshot, never a
|
||||
// claim that the Fabric is active.
|
||||
return [
|
||||
'fabrics' => [],
|
||||
'mappings' => self::mappings([]),
|
||||
'generated_at' => time(),
|
||||
'engine_available' => false,
|
||||
'engine_error' => 'Fabric 引擎状态暂时无法读取,请稍后重试。',
|
||||
];
|
||||
}
|
||||
if (!is_array($raw)) {
|
||||
throw new CloudError('Fabric 状态响应无效,请稍后重试', 502);
|
||||
}
|
||||
$hostNames = self::hostNames($raw);
|
||||
$fabrics = [];
|
||||
foreach ($raw as $item) {
|
||||
if (!is_array($item)) {
|
||||
continue;
|
||||
}
|
||||
$fabrics[] = self::project($item, $hostNames);
|
||||
}
|
||||
usort($fabrics, static fn (array $a, array $b): int =>
|
||||
strcmp((string) $a['fabric_id'], (string) $b['fabric_id']));
|
||||
return [
|
||||
'fabrics' => $fabrics,
|
||||
'mappings' => self::mappings($fabrics),
|
||||
'generated_at' => time(),
|
||||
'engine_available' => true,
|
||||
];
|
||||
}
|
||||
|
||||
public static function detail(string $fabricId, array $actor,
|
||||
?CloudEngineClient $engine = null): array
|
||||
{
|
||||
self::assertReadActor($actor);
|
||||
$fabricId = self::fabricId($fabricId);
|
||||
$engine ??= new CloudEngineClient();
|
||||
$raw = $engine->fabricStatus($fabricId, $actor);
|
||||
if (!is_array($raw)) {
|
||||
throw new CloudError('Fabric 状态响应无效,请稍后重试', 502);
|
||||
}
|
||||
$hostNames = self::hostNames([$raw]);
|
||||
$fabric = self::project($raw, $hostNames);
|
||||
return [
|
||||
'fabric' => $fabric,
|
||||
'mapping' => self::mappingForFabric($fabricId),
|
||||
];
|
||||
}
|
||||
|
||||
public static function apply(array $body, array $actor,
|
||||
?CloudEngineClient $engine = null): array
|
||||
{
|
||||
self::assertWriteActor($actor);
|
||||
$plan = self::plan($body);
|
||||
self::assertMappedPlanCanApply($plan);
|
||||
// Applying/reconciling runs a bounded host loop. Give it a longer
|
||||
// transport window than a read, while still returning an explicit
|
||||
// uncertain result if the PHP request itself loses the response.
|
||||
$engine ??= new CloudEngineClient(null, self::FABRIC_WRITE_TIMEOUT_SECONDS);
|
||||
$raw = $engine->fabricApply($plan, $actor);
|
||||
if (!is_array($raw)) {
|
||||
throw new CloudError('Fabric 应用响应无效,请稍后核对', 502);
|
||||
}
|
||||
$hostNames = self::hostNames([$raw]);
|
||||
$fabric = self::project($raw, $hostNames);
|
||||
return [
|
||||
'fabric' => $fabric,
|
||||
'mapping' => self::mappingForFabric((string) $fabric['fabric_id']),
|
||||
];
|
||||
}
|
||||
|
||||
public static function reconcile(string $fabricId, array $actor,
|
||||
?CloudEngineClient $engine = null): array
|
||||
{
|
||||
self::assertWriteActor($actor);
|
||||
$fabricId = self::fabricId($fabricId);
|
||||
$engine ??= new CloudEngineClient(null, self::FABRIC_WRITE_TIMEOUT_SECONDS);
|
||||
$raw = $engine->fabricReconcile($fabricId, $actor);
|
||||
if (!is_array($raw)) {
|
||||
throw new CloudError('Fabric 核对响应无效,请稍后刷新', 502);
|
||||
}
|
||||
$hostNames = self::hostNames([$raw]);
|
||||
return [
|
||||
'fabric' => self::project($raw, $hostNames),
|
||||
'mapping' => self::mappingForFabric($fabricId),
|
||||
];
|
||||
}
|
||||
|
||||
private static function assertReadActor(array $actor): void
|
||||
{
|
||||
if (!($actor['is_admin'] ?? false)) {
|
||||
throw new CloudError('需要管理员权限', 403);
|
||||
}
|
||||
}
|
||||
|
||||
private static function assertWriteActor(array $actor): void
|
||||
{
|
||||
if (!($actor['is_admin'] ?? false)
|
||||
|| !($actor['is_super_admin'] ?? false)
|
||||
|| !($actor['can_manage'] ?? false)) {
|
||||
throw new CloudError('仅超级管理员可以修改 Fabric', 403);
|
||||
}
|
||||
}
|
||||
|
||||
private static function fabricId($value): string
|
||||
{
|
||||
if (!is_string($value) || preg_match(self::FABRIC_ID, $value) !== 1) {
|
||||
throw new CloudError('Fabric 标识无效', 422);
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
/** Validate the exact engine plan vocabulary before forwarding it. */
|
||||
private static function plan(array $body): array
|
||||
{
|
||||
CloudInput::only($body, [
|
||||
'schema_version', 'fabric_id', 'region', 'overlay_cidr',
|
||||
'revision', 'listen_port', 'nodes',
|
||||
]);
|
||||
if (($body['schema_version'] ?? 1) !== 1) {
|
||||
throw new CloudError('Fabric 计划版本不支持', 422);
|
||||
}
|
||||
$fabricId = self::fabricId($body['fabric_id'] ?? null);
|
||||
$region = self::safeText($body['region'] ?? null, 'Fabric 地区', 64);
|
||||
$network = self::network($body['overlay_cidr'] ?? null);
|
||||
$revision = self::positiveInt($body['revision'] ?? null, 'Fabric 版本');
|
||||
$listenPort = self::port($body['listen_port'] ?? 51820);
|
||||
$nodes = $body['nodes'] ?? null;
|
||||
if (!is_array($nodes) || array_is_list($nodes) !== true
|
||||
|| count($nodes) < 2 || count($nodes) > 64) {
|
||||
throw new CloudError('Fabric 至少需要两个且最多支持 64 个宿主机', 422);
|
||||
}
|
||||
$seenHosts = [];
|
||||
$seenIps = [];
|
||||
$normalized = [];
|
||||
foreach ($nodes as $node) {
|
||||
if (!is_array($node)) {
|
||||
throw new CloudError('Fabric 节点字段无效', 422);
|
||||
}
|
||||
CloudInput::only($node, ['host_id', 'overlay_ip', 'endpoint', 'listen_port']);
|
||||
$hostId = $node['host_id'] ?? null;
|
||||
if (!is_string($hostId) || preg_match(self::HOST_ID, $hostId) !== 1
|
||||
|| isset($seenHosts[$hostId])) {
|
||||
throw new CloudError('Fabric 宿主机标识无效或重复', 422);
|
||||
}
|
||||
$overlayIp = self::ipv4($node['overlay_ip'] ?? null, 'Fabric overlay 地址');
|
||||
if (isset($seenIps[$overlayIp])) {
|
||||
throw new CloudError('Fabric overlay 地址不能重复', 422);
|
||||
}
|
||||
if (!self::containsHost($network, $overlayIp)) {
|
||||
throw new CloudError('Fabric overlay 地址必须位于 overlay CIDR 内', 422);
|
||||
}
|
||||
$endpoint = self::endpoint($node['endpoint'] ?? null);
|
||||
[$endpointIp] = explode(':', $endpoint, 2);
|
||||
if (self::containsAddress($network, $endpointIp)) {
|
||||
throw new CloudError('WireGuard endpoint 不能位于 Fabric overlay 网段', 422);
|
||||
}
|
||||
$nodePort = self::port($node['listen_port'] ?? $listenPort);
|
||||
$seenHosts[$hostId] = true;
|
||||
$seenIps[$overlayIp] = true;
|
||||
$normalized[] = [
|
||||
'host_id' => $hostId,
|
||||
'overlay_ip' => $overlayIp,
|
||||
'endpoint' => $endpoint,
|
||||
'listen_port' => $nodePort,
|
||||
];
|
||||
}
|
||||
usort($normalized, static fn (array $a, array $b): int =>
|
||||
strcmp($a['host_id'], $b['host_id']));
|
||||
return [
|
||||
'schema_version' => 1,
|
||||
'fabric_id' => $fabricId,
|
||||
'region' => $region,
|
||||
'overlay_cidr' => $network,
|
||||
'revision' => $revision,
|
||||
'listen_port' => $listenPort,
|
||||
'nodes' => $normalized,
|
||||
];
|
||||
}
|
||||
|
||||
private static function assertMappedPlanCanApply(array $plan): void
|
||||
{
|
||||
$connection = (new CloudRegionFabric())->getConnection();
|
||||
if (!$connection->getSchemaBuilder()->hasTable('cloud_region_fabrics')) {
|
||||
return;
|
||||
}
|
||||
$mapping = CloudRegionFabric::where('fabric_id', $plan['fabric_id'])->first();
|
||||
if ($mapping === null || (string) $mapping->state !== 'active') {
|
||||
return;
|
||||
}
|
||||
if ((string) $mapping->fabric_region !== $plan['region']
|
||||
|| (int) $mapping->fabric_revision !== (int) $plan['revision']) {
|
||||
throw new CloudError(
|
||||
'活动 Fabric 映射仍引用其他地区或版本,请先停用映射并完成迁移', 409
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static function project(array $value, array $hostNames): array
|
||||
{
|
||||
$fabricId = self::fabricId($value['fabric_id'] ?? null);
|
||||
$region = self::safeText($value['region'] ?? null, 'Fabric 地区', 64);
|
||||
$overlay = self::network($value['overlay_cidr'] ?? null);
|
||||
$revision = self::positiveInt($value['revision'] ?? null, 'Fabric 版本');
|
||||
$state = self::choice($value['state'] ?? null, self::STATES, 'Fabric 状态');
|
||||
$result = [
|
||||
'fabric_id' => $fabricId,
|
||||
'region' => $region,
|
||||
'overlay_cidr' => $overlay,
|
||||
'revision' => $revision,
|
||||
'listen_port' => self::port($value['listen_port'] ?? 51820),
|
||||
'plan_digest' => self::digest($value['plan_digest'] ?? null),
|
||||
'interface' => self::safeText($value['interface'] ?? 'wg-fabric0', 'Fabric 网卡', 32),
|
||||
'state' => $state,
|
||||
'next_stage_allowed' => ($value['next_stage_allowed'] ?? false) === true,
|
||||
'updated_at' => max(0, (int) ($value['updated_at'] ?? 0)),
|
||||
'nodes' => [],
|
||||
];
|
||||
$nodes = $value['nodes'] ?? [];
|
||||
if (!is_array($nodes) || count($nodes) > 64) {
|
||||
throw new CloudError('Fabric 节点状态无效', 502);
|
||||
}
|
||||
foreach ($nodes as $node) {
|
||||
if (!is_array($node)) {
|
||||
continue;
|
||||
}
|
||||
$hostId = self::safeText($node['host_id'] ?? null, '宿主机标识', 64);
|
||||
$row = [
|
||||
'host_id' => $hostId,
|
||||
'host_name' => $hostNames[$hostId]['name'] ?? null,
|
||||
'host_region' => $hostNames[$hostId]['region'] ?? null,
|
||||
'overlay_ip' => self::ipv4($node['overlay_ip'] ?? null, 'Fabric overlay 地址'),
|
||||
'endpoint' => self::endpoint($node['endpoint'] ?? null),
|
||||
'listen_port' => self::port($node['listen_port'] ?? 51820),
|
||||
'public_key' => self::key($node['public_key'] ?? null),
|
||||
'state' => self::choice($node['state'] ?? null, self::STATES, 'Fabric 节点状态'),
|
||||
'transport_verified' => ($node['transport_verified'] ?? false) === true,
|
||||
'observed_revision' => max(0, (int) ($node['observed_revision'] ?? 0)),
|
||||
'observed_plan_digest' => self::nullableDigest($node['observed_plan_digest'] ?? null),
|
||||
'last_error_code' => self::errorCode($node['last_error_code'] ?? null),
|
||||
'observed' => self::observed($node['observed'] ?? []),
|
||||
];
|
||||
$result['nodes'][] = $row;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function observed($value): array
|
||||
{
|
||||
if (!is_array($value)) {
|
||||
return [];
|
||||
}
|
||||
$result = [];
|
||||
foreach ([
|
||||
'owner', 'config_fabric', 'config_revision', 'config_digest',
|
||||
'config_network', 'config_overlay', 'config_ok', 'interface',
|
||||
'listen_port', 'enabled', 'service_active', 'timer_enabled',
|
||||
'timer_active', 'nft_guard', 'key_secure', 'nft_persistence',
|
||||
'config_secure', 'helper_marker', 'unit_marker', 'repair_marker',
|
||||
'timer_marker', 'manager_mode', 'manager_owner', 'manager_active',
|
||||
'admin_state', 'vpc_state', 'peer_allowed_exact', 'vpc_nft_state',
|
||||
'vpc_nft_exact',
|
||||
] as $key) {
|
||||
if (array_key_exists($key, $value)) {
|
||||
$item = $value[$key];
|
||||
$result[$key] = is_string($item)
|
||||
? substr($item, 0, 128)
|
||||
: (is_scalar($item) ? $item : null);
|
||||
}
|
||||
}
|
||||
foreach ([
|
||||
'addresses', 'routes', 'paths', 'pings', 'endpoint_paths',
|
||||
'config_routes', 'route_overlaps', 'vpc_tenants', 'vpc_nft_ips',
|
||||
] as $key) {
|
||||
if (!is_array($value[$key] ?? null)) {
|
||||
continue;
|
||||
}
|
||||
$result[$key] = array_values(array_filter(
|
||||
array_map(static fn ($item): ?string => is_string($item)
|
||||
? substr($item, 0, 128) : null, $value[$key]),
|
||||
static fn ($item): bool => $item !== null
|
||||
));
|
||||
}
|
||||
foreach (['sysctls', 'rp_filters'] as $key) {
|
||||
if (!is_array($value[$key] ?? null)) {
|
||||
continue;
|
||||
}
|
||||
$result[$key] = [];
|
||||
foreach ($value[$key] as $name => $item) {
|
||||
if (is_string($name) && strlen($name) <= 64
|
||||
&& in_array((string) $item, ['0', '1', '2', 'unknown'], true)) {
|
||||
$result[$key][$name] = (string) $item;
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (['config_peers', 'peers', 'overlay_peers'] as $key) {
|
||||
if (!is_array($value[$key] ?? null)) {
|
||||
continue;
|
||||
}
|
||||
$result[$key] = [];
|
||||
foreach ($value[$key] as $item) {
|
||||
if (!is_array($item) || count($item) !== 3) {
|
||||
continue;
|
||||
}
|
||||
$result[$key][] = array_map(static fn ($part): string =>
|
||||
substr((string) $part, 0, 128), array_values($item));
|
||||
}
|
||||
}
|
||||
if (is_array($value['handshakes'] ?? null)) {
|
||||
$result['handshakes'] = [];
|
||||
foreach ($value['handshakes'] as $key => $stamp) {
|
||||
if (is_string($key) && strlen($key) <= 128 && is_numeric($stamp)) {
|
||||
$result['handshakes'][$key] = (int) $stamp;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function mappings(array $fabrics): array
|
||||
{
|
||||
$connection = (new CloudRegionFabric())->getConnection();
|
||||
if (!$connection->getSchemaBuilder()->hasTable('cloud_region_fabrics')) {
|
||||
return [];
|
||||
}
|
||||
$regions = CloudRegion::orderBy('id')->get();
|
||||
$byFabric = [];
|
||||
foreach ($fabrics as $fabric) {
|
||||
$byFabric[(string) $fabric['fabric_id']] = $fabric;
|
||||
}
|
||||
$fabricRows = CloudRegionFabric::get()->keyBy('region_id');
|
||||
$rows = [];
|
||||
foreach ($regions as $region) {
|
||||
$row = $fabricRows[(int) $region->id] ?? null;
|
||||
if ($row === null) {
|
||||
$rows[] = self::unconfiguredMapping($region);
|
||||
continue;
|
||||
}
|
||||
$fabric = $byFabric[(string) $row->fabric_id] ?? null;
|
||||
$rows[] = self::mappingRow($row, $region, $fabric);
|
||||
}
|
||||
return $rows;
|
||||
}
|
||||
|
||||
private static function mappingForFabric(string $fabricId): ?array
|
||||
{
|
||||
$connection = (new CloudRegionFabric())->getConnection();
|
||||
if (!$connection->getSchemaBuilder()->hasTable('cloud_region_fabrics')) {
|
||||
return null;
|
||||
}
|
||||
$row = CloudRegionFabric::where('fabric_id', $fabricId)->first();
|
||||
if ($row === null) {
|
||||
return null;
|
||||
}
|
||||
$region = CloudRegion::find((int) $row->region_id);
|
||||
return self::mappingRow($row, $region, null);
|
||||
}
|
||||
|
||||
private static function mappingRow($row, $region, ?array $fabric): array
|
||||
{
|
||||
return [
|
||||
'region_id' => (int) $row->region_id,
|
||||
'region_code' => (string) ($region->code ?? ''),
|
||||
'region_name' => (string) ($region->name ?? ''),
|
||||
'region_status' => (string) ($region->status ?? 'disabled'),
|
||||
'fabric_id' => (string) $row->fabric_id,
|
||||
'fabric_region' => (string) $row->fabric_region,
|
||||
'fabric_revision' => (int) $row->fabric_revision,
|
||||
'state' => (string) $row->state,
|
||||
'engine_state' => is_array($fabric) ? ($fabric['state'] ?? null) : null,
|
||||
'engine_revision' => is_array($fabric) ? ($fabric['revision'] ?? null) : null,
|
||||
'next_stage_allowed' => is_array($fabric)
|
||||
? ($fabric['next_stage_allowed'] ?? false) : false,
|
||||
'updated_at' => (int) $row->updated_at,
|
||||
];
|
||||
}
|
||||
|
||||
private static function unconfiguredMapping($region): array
|
||||
{
|
||||
return [
|
||||
'region_id' => (int) ($region->id ?? 0),
|
||||
'region_code' => (string) ($region->code ?? ''),
|
||||
'region_name' => (string) ($region->name ?? ''),
|
||||
'region_status' => (string) ($region->status ?? 'disabled'),
|
||||
'fabric_id' => null,
|
||||
'fabric_region' => null,
|
||||
'fabric_revision' => null,
|
||||
'state' => 'unconfigured',
|
||||
'engine_state' => null,
|
||||
'engine_revision' => null,
|
||||
'next_stage_allowed' => false,
|
||||
'updated_at' => null,
|
||||
];
|
||||
}
|
||||
|
||||
private static function hostNames(array $fabrics): array
|
||||
{
|
||||
$ids = [];
|
||||
foreach ($fabrics as $fabric) {
|
||||
foreach (($fabric['nodes'] ?? []) as $node) {
|
||||
$id = is_array($node) ? (string) ($node['host_id'] ?? '') : '';
|
||||
if (ctype_digit($id) && (int) $id > 0) {
|
||||
$ids[(int) $id] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($ids === []) {
|
||||
return [];
|
||||
}
|
||||
$result = [];
|
||||
foreach (CloudHost::whereIn('id', array_keys($ids))->get() as $host) {
|
||||
$result[(string) $host->id] = [
|
||||
'name' => (string) $host->name,
|
||||
'region' => (string) $host->region,
|
||||
];
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function network($value): string
|
||||
{
|
||||
if (!is_string($value)) {
|
||||
throw new CloudError('Fabric overlay CIDR 无效', 422);
|
||||
}
|
||||
[$ip, $prefix] = array_pad(explode('/', trim($value), 2), 2, null);
|
||||
$prefix = filter_var($prefix, FILTER_VALIDATE_INT);
|
||||
if ($prefix === false || $prefix < 10 || $prefix > 24
|
||||
|| self::ipv4($ip, 'Fabric overlay CIDR') !== $ip) {
|
||||
throw new CloudError('Fabric overlay CIDR 无效', 422);
|
||||
}
|
||||
$parts = array_map('intval', explode('.', $ip));
|
||||
if ($parts[0] !== 100 || $parts[1] < 64 || $parts[1] > 127) {
|
||||
throw new CloudError('Fabric overlay 必须位于 100.64.0.0/10 内', 422);
|
||||
}
|
||||
$mask = $prefix === 0 ? 0 : (0xffffffff << (32 - $prefix)) & 0xffffffff;
|
||||
$number = (($parts[0] << 24) | ($parts[1] << 16) | ($parts[2] << 8) | $parts[3]) & 0xffffffff;
|
||||
if (($number & $mask) !== $number) {
|
||||
throw new CloudError('Fabric overlay CIDR 必须使用规范网络地址', 422);
|
||||
}
|
||||
return $ip . '/' . $prefix;
|
||||
}
|
||||
|
||||
private static function containsHost(string $network, string $ip): bool
|
||||
{
|
||||
if (!self::containsAddress($network, $ip)) {
|
||||
return false;
|
||||
}
|
||||
[$base, $prefix] = explode('/', $network);
|
||||
$toInt = static function (string $value): int {
|
||||
$parts = array_map('intval', explode('.', $value));
|
||||
return (($parts[0] << 24) | ($parts[1] << 16) | ($parts[2] << 8) | $parts[3]) & 0xffffffff;
|
||||
};
|
||||
$mask = (0xffffffff << (32 - (int) $prefix)) & 0xffffffff;
|
||||
$value = $toInt($ip);
|
||||
$baseValue = $toInt($base);
|
||||
return (($value & $mask) === $baseValue) && $value !== $baseValue
|
||||
&& $value !== ($baseValue | ((1 << (32 - (int) $prefix)) - 1));
|
||||
}
|
||||
|
||||
private static function containsAddress(string $network, string $ip): bool
|
||||
{
|
||||
[$base, $prefix] = explode('/', $network);
|
||||
$toInt = static function (string $value): int {
|
||||
$parts = array_map('intval', explode('.', $value));
|
||||
return (($parts[0] << 24) | ($parts[1] << 16) | ($parts[2] << 8) | $parts[3]) & 0xffffffff;
|
||||
};
|
||||
$mask = (0xffffffff << (32 - (int) $prefix)) & 0xffffffff;
|
||||
return (($toInt($ip) & $mask) === $toInt($base));
|
||||
}
|
||||
|
||||
private static function ipv4($value, string $label): string
|
||||
{
|
||||
if (!is_string($value) || filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
|
||||
throw new CloudError($label . '无效', 422);
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
private static function endpoint($value): string
|
||||
{
|
||||
if (!is_string($value) || substr_count($value, ':') !== 1) {
|
||||
throw new CloudError('WireGuard endpoint 无效', 422);
|
||||
}
|
||||
[$ip, $port] = explode(':', $value, 2);
|
||||
$ip = self::ipv4($ip, 'WireGuard endpoint 地址');
|
||||
$parts = array_map('intval', explode('.', $ip));
|
||||
if ($ip === '0.0.0.0' || $parts[0] === 127 || $parts[0] >= 224
|
||||
|| ($parts[0] === 169 && $parts[1] === 254)) {
|
||||
throw new CloudError('WireGuard endpoint 地址不可路由', 422);
|
||||
}
|
||||
$port = self::port($port);
|
||||
return $ip . ':' . $port;
|
||||
}
|
||||
|
||||
private static function port($value): int
|
||||
{
|
||||
if (is_string($value) && ctype_digit($value)) {
|
||||
$value = (int) $value;
|
||||
}
|
||||
if (is_bool($value) || !is_int($value) || $value < 1 || $value > 65535) {
|
||||
throw new CloudError('WireGuard 端口无效', 422);
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
private static function positiveInt($value, string $label): int
|
||||
{
|
||||
if (is_string($value) && ctype_digit($value)) {
|
||||
$value = (int) $value;
|
||||
}
|
||||
if (is_bool($value) || !is_int($value) || $value < 1 || $value > 9223372036854775807) {
|
||||
throw new CloudError($label . '无效', 422);
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
private static function safeText($value, string $label, int $maximum): string
|
||||
{
|
||||
if (!is_string($value) || $value === '' || strlen($value) > $maximum
|
||||
|| trim($value) !== $value || preg_match('/[\x00-\x1f\x7f]/', $value) === 1) {
|
||||
throw new CloudError($label . '无效', 422);
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
private static function choice($value, array $choices, string $label): string
|
||||
{
|
||||
if (!is_string($value) || !in_array($value, $choices, true)) {
|
||||
throw new CloudError($label . '无效', 502);
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
private static function key($value): ?string
|
||||
{
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
if (!is_string($value) || preg_match(self::KEY, $value) !== 1) {
|
||||
throw new CloudError('Fabric 公钥回读无效', 502);
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
private static function digest($value): ?string
|
||||
{
|
||||
if ($value === null || $value === '') {
|
||||
return null;
|
||||
}
|
||||
if (!is_string($value) || preg_match('/^[0-9a-f]{64}$/D', $value) !== 1) {
|
||||
throw new CloudError('Fabric 摘要回读无效', 502);
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
private static function nullableDigest($value): ?string
|
||||
{
|
||||
return $value === null || $value === '' ? null : self::digest($value);
|
||||
}
|
||||
|
||||
private static function errorCode($value): ?string
|
||||
{
|
||||
if ($value === null || $value === '') {
|
||||
return null;
|
||||
}
|
||||
if (!is_string($value) || !in_array($value, self::ERROR_CODES, true)) {
|
||||
return 'fabric_readback_invalid';
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
@ -1,2 +1,2 @@
|
||||
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
|
||||
{assign var=venix_asset_version value='2026100701' scope='global'}
|
||||
{assign var=venix_asset_version value='2026100801' scope='global'}
|
||||
|
||||
@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
// Static contract coverage for the administrator Fabric boundary. This test
|
||||
// deliberately does not boot the application or call a host: the engine is
|
||||
// reached only through the PHP HMAC client at runtime.
|
||||
$root = dirname(__DIR__);
|
||||
$read = static function (string $relative) use ($root): string {
|
||||
$value = file_get_contents($root . '/' . $relative);
|
||||
if (!is_string($value)) {
|
||||
throw new RuntimeException('Unable to read ' . $relative);
|
||||
}
|
||||
return $value;
|
||||
};
|
||||
$assert = static function ($condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$routes = $read('config/routes.php');
|
||||
$cloudRoutes = $read('config/routes_cloud.php');
|
||||
$middleware = $read('app/Middleware/CloudApi.php');
|
||||
$client = $read('app/Services/Cloud/CloudEngineClient.php');
|
||||
$controller = $read('app/Controllers/CloudAdminFabricController.php');
|
||||
$service = $read('app/Services/Cloud/CloudAdminFabricService.php');
|
||||
$page = $read('app/Controllers/Admin/CloudPageController.php');
|
||||
$template = $read('resources/views/venix/admin/cloud/fabric.tpl');
|
||||
$script = $read('public/cloud/admin-fabric.js');
|
||||
$header = $read('resources/views/venix/admin/static_header.tpl');
|
||||
|
||||
$assert(str_contains($routes, "\$this->get('/fabric', 'App\\Controllers\\Admin\\CloudPageController:fabric')")
|
||||
&& str_contains($header, 'href="/admin/fabric"')
|
||||
&& str_contains($page, "fetch('admin/cloud/fabric.tpl')"),
|
||||
'Fabric administrator page route, navigation or renderer is missing.');
|
||||
$assert(str_contains($cloudRoutes, "\$this->post('/admin/fabric/apply'")
|
||||
&& str_contains($cloudRoutes, "\$this->get('/admin/fabric'")
|
||||
&& str_contains($cloudRoutes, "\$this->get('/admin/fabric/{fabric_id:")
|
||||
&& str_contains($cloudRoutes, "\$this->post('/admin/fabric/{fabric_id:")
|
||||
&& strpos($cloudRoutes, "\$this->post('/admin/fabric/apply'") < strpos($cloudRoutes, "\$this->get('/admin/fabric/{fabric_id:"),
|
||||
'Fabric API routes or static apply ordering is incomplete.');
|
||||
$assert(str_contains($middleware, "/api/v1/admin/fabric(?:/|$)")
|
||||
&& str_contains($client, "function fabricStatuses")
|
||||
&& str_contains($client, "function fabricApply")
|
||||
&& str_contains($client, "function fabricReconcile")
|
||||
&& str_contains($client, "safeFabricErrorMessage"),
|
||||
'Fabric API must use the database-only PHP boundary and bounded engine client.');
|
||||
$assert(str_contains($controller, 'CloudAccess::manage')
|
||||
&& str_contains($controller, 'CloudInput::object')
|
||||
&& str_contains($controller, "body !== '{}'"),
|
||||
'Fabric controller lost the super-admin, typed-body or empty reconcile guards.');
|
||||
$assert(str_contains($service, 'CloudInput::only')
|
||||
&& str_contains($service, "'schema_version', 'fabric_id', 'region', 'overlay_cidr'")
|
||||
&& str_contains($service, "'revision', 'listen_port', 'nodes'")
|
||||
&& str_contains($service, "'listen_port' => self::port(")
|
||||
&& str_contains($service, 'next_stage_allowed')
|
||||
&& str_contains($service, 'observed_plan_digest')
|
||||
&& str_contains($service, 'handshakes')
|
||||
&& str_contains($service, 'host_name'),
|
||||
'Fabric service must project typed plans, host capabilities and desired/observed evidence.');
|
||||
$assert(!str_contains($service, "'private_key'")
|
||||
&& !str_contains($service, "'ssh_command'")
|
||||
&& !str_contains($service, "'raw_output'"),
|
||||
'Fabric admin projection must not accept or expose private credentials or raw commands.');
|
||||
$assert(str_contains($template, 'Fabric 拓扑')
|
||||
&& str_contains($template, '参与宿主机与能力探测')
|
||||
&& str_contains($template, 'Peer')
|
||||
&& str_contains($template, 'Route')
|
||||
&& str_contains($template, 'Handshake')
|
||||
&& str_contains($template, 'desired / observed')
|
||||
&& str_contains($template, 'apply')
|
||||
&& str_contains($template, 'reconcile')
|
||||
&& str_contains($template, '地区到 Fabric 映射'),
|
||||
'Fabric page is missing one of the required topology, evidence or mapping sections.');
|
||||
$assert(str_contains($script, '/api/v1/admin/fabric')
|
||||
&& str_contains($script, 'X-CSRF-Token')
|
||||
&& str_contains($script, 'fabric.listen_port || fabric.nodes[0].listen_port')
|
||||
&& str_contains($script, 'next_stage_allowed')
|
||||
&& str_contains($script, 'textContent')
|
||||
&& !str_contains($script, '/internal/v1/'),
|
||||
'Fabric browser module must use the PHP API, CSRF and safe DOM rendering.');
|
||||
|
||||
echo "Administrator Fabric page and API boundary contracts passed.\n";
|
||||
Loading…
Reference in New Issue