diff --git a/web/app/Services/Cloud/CloudPublicNetworkAddressPolicy.php b/web/app/Services/Cloud/CloudPublicNetworkAddressPolicy.php new file mode 100644 index 00000000..21e71498 --- /dev/null +++ b/web/app/Services/Cloud/CloudPublicNetworkAddressPolicy.php @@ -0,0 +1,84 @@ +family() !== $expectedFamily) { + throw new \InvalidArgumentException( + 'Public IP pool family does not match.' + ); + } + return $contract; + } + + /** Validate immutable row identity without applying mutable exclusions. */ + public static function assertIdentity( + object $row, + object $pool, + CloudPublicIpPoolContract $contract + ): CloudIpAddress { + $address = CloudIpAddress::parse((string) ($row->address ?? '')); + if ((int) ($row->host_id ?? 0) !== (int) ($pool->host_id ?? 0) + || (int) ($row->public_ip_pool_id ?? 0) + !== (int) ($pool->id ?? 0) + || (int) ($row->address_family ?? 0) + !== (int) ($pool->address_family ?? 0) + || $contract->family() !== (int) ($pool->address_family ?? 0) + || (int) ($row->prefix_length ?? 0) + !== $contract->guestPrefixLength() + || !hash_equals($address->text(), (string) $row->address) + || !is_string($row->address_binary ?? null) + || !hash_equals($address->binary(), $row->address_binary) + || !$contract->addressBelongs($address)) { + throw new \InvalidArgumentException( + 'Public IP address identity is invalid.' + ); + } + return $address; + } + + /** Validate an address row as a current allocation candidate. */ + public static function assertSelectable( + object $row, + object $pool, + CloudPublicIpPoolContract $contract, + ?string $managementAddress + ): CloudIpAddress { + $address = self::assertIdentity($row, $pool, $contract); + if (!self::addressSelectable( + $address, + $contract, + $managementAddress + )) { + throw new \InvalidArgumentException( + 'Public IP address is not selectable.' + ); + } + return $address; + } + + public static function addressSelectable( + CloudIpAddress $address, + CloudPublicIpPoolContract $contract, + ?string $managementAddress + ): bool { + if (!$contract->addressAllowed($address)) { + return false; + } + $managementAddress = trim((string) $managementAddress); + if ($managementAddress === '') { + return true; + } + $management = CloudIpAddress::parse($managementAddress); + return $management->family() !== $address->family() + || !$management->equals($address); + } +} diff --git a/web/app/Services/Cloud/CloudPublicNetworkAllocationService.php b/web/app/Services/Cloud/CloudPublicNetworkAllocationService.php index 12e2377e..703cdc76 100644 --- a/web/app/Services/Cloud/CloudPublicNetworkAllocationService.php +++ b/web/app/Services/Cloud/CloudPublicNetworkAllocationService.php @@ -1126,7 +1126,7 @@ final class CloudPublicNetworkAllocationService || (int) $pool->network_attachment_id !== (int) $attachment->id) { throw new CloudError('双栈公网地址池边界损坏', 409); } - $contracts[$family] = self::validatePool($pool, $family); + $contracts[$family] = self::requirePoolContract($pool, $family); $pools[$family] = $pool; } if (!isset($pools[4], $pools[6])) { @@ -1187,29 +1187,21 @@ final class CloudPublicNetworkAllocationService CloudPublicIpPoolContract $contract): CloudIpAddress { try { - $address = self::assertConcreteAddressIdentity( + if ((string) $row->state === 'disabled') { + return CloudPublicNetworkAddressPolicy::assertIdentity( + $row, + $pool, + $contract + ); + } + return CloudPublicNetworkAddressPolicy::assertSelectable( $row, $pool, - $contract + $contract, + CloudPanelUsageService::managementAddress( + CloudHost::find((int) $pool->host_id) + ) ); - if (((string) $row->state !== 'disabled' - && !self::rawAddressAllowedByPool( - $address, - $pool, - $contract - ))) { - throw new \InvalidArgumentException(); - } - if ($address->family() === 6 - && (string) $row->state !== 'disabled') { - $start = CloudIpAddress::parse($pool->allocation_start ?? null); - $end = CloudIpAddress::parse($pool->allocation_end ?? null); - if ($address->compare($start) < 0 - || $address->compare($end) > 0) { - throw new \InvalidArgumentException(); - } - } - return $address; } catch (\Throwable) { throw new CloudError('公网地址具体身份与地址池不一致', 409); } @@ -1220,24 +1212,11 @@ final class CloudPublicNetworkAllocationService object $pool, CloudPublicIpPoolContract $contract): CloudIpAddress { try { - $address = CloudIpAddress::parse((string) $row->address); - if ((int) $row->host_id !== (int) $pool->host_id - || (int) $row->public_ip_pool_id !== (int) $pool->id - || (int) $row->address_family - !== (int) $pool->address_family - || (int) $row->prefix_length - !== (int) $pool->guest_prefix_length - || !hash_equals($address->text(), (string) $row->address) - || !is_string($row->address_binary) - || !hash_equals($address->binary(), $row->address_binary) - || !self::rawAddressBelongsToPool( - $address, - $pool, - $contract - )) { - throw new \InvalidArgumentException(); - } - return $address; + return CloudPublicNetworkAddressPolicy::assertIdentity( + $row, + $pool, + $contract + ); } catch (\Throwable) { throw new CloudError('公网地址具体身份与地址池不一致', 409); } @@ -1433,7 +1412,10 @@ final class CloudPublicNetworkAllocationService !== (int) $pool->desired_revision) { throw new CloudError('公网地址池目录尚未精确收敛', 409); } - $contracts[(int) $pool->id] = self::validatePool($pool, $family); + $contracts[(int) $pool->id] = self::requirePoolContract( + $pool, + $family + ); $pools[$attachmentId][] = $pool; } foreach ($pools as &$attachmentPools) { @@ -1654,16 +1636,19 @@ final class CloudPublicNetworkAllocationService + $contract->maxAllocations() + count($contract->reservedAddresses()) + count($contract->dnsServers()) + 2); + $managementAddress = CloudPanelUsageService::managementAddress( + CloudHost::find((int) $pool->host_id) + ); for ($attempt = 0; $attempt < $attempts; $attempt++) { $existing = DB::table('cloud_public_ips') ->where('address_family', 6) ->where('address_binary', $candidate->binary()) ->lockForUpdate()->first(); if ($existing === null - && self::rawAddressAllowedByPool( + && CloudPublicNetworkAddressPolicy::addressSelectable( $candidate, - $pool, - $contract + $contract, + $managementAddress )) { return [ 'row' => null, @@ -1755,45 +1740,16 @@ final class CloudPublicNetworkAllocationService } } - private static function validatePool(object $pool, + private static function requirePoolContract(object $pool, int $family): CloudPublicIpPoolContract { try { - $contract = CloudPublicIpPoolContract::fromRow($pool); - if ($contract->family() !== $family) { - throw new \InvalidArgumentException(); - } - return $contract; + return CloudPublicNetworkAddressPolicy::contract($pool, $family); } catch (\Throwable) { throw new CloudError('公网地址池配置损坏', 409); } } - private static function rawAddressAllowedByPool(CloudIpAddress $address, - object $pool, CloudPublicIpPoolContract $contract): bool - { - if (!$contract->addressAllowed($address)) { - return false; - } - $management = CloudPanelUsageService::managementAddress( - CloudHost::find((int) $pool->host_id) - ); - if (is_string($management) && $management !== '') { - $managementAddress = CloudIpAddress::parse($management); - if ($managementAddress->family() === $address->family() - && $managementAddress->equals($address)) { - return false; - } - } - return true; - } - - private static function rawAddressBelongsToPool(CloudIpAddress $address, - object $pool, CloudPublicIpPoolContract $contract): bool - { - return $contract->addressBelongs($address); - } - private static function decodedAddresses(string $json, bool $allowEmpty, int $maximum = 256): array { @@ -1922,7 +1878,7 @@ final class CloudPublicNetworkAllocationService || (int) $ip->public_ip_pool_id !== (int) $pool->id) { throw new CloudError('双栈公网地址引用损坏', 409); } - $contract = self::validatePool($pool, $family); + $contract = self::requirePoolContract($pool, $family); self::assertConcreteAddressIdentity($ip, $pool, $contract); $addresses[(int) $ip->id] = $ip; $reservationIds[(int) $claim->reservation_id] = true; diff --git a/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php b/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php index 770f09d0..9bd26850 100644 --- a/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php +++ b/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php @@ -2808,7 +2808,10 @@ final class CloudPublicNetworkTransitionWorkflow int $lineId): bool { try { - $contract = CloudPublicIpPoolContract::fromRow($pool); + $contract = CloudPublicNetworkAddressPolicy::contract( + $pool, + (int) $pool->address_family + ); } catch (\Throwable) { return false; } @@ -2950,28 +2953,20 @@ final class CloudPublicNetworkTransitionWorkflow CloudPublicIpPool $pool, ?CloudHost $lockedHost = null): void { try { - $contract = CloudPublicIpPoolContract::fromRow($pool); - $address = CloudIpAddress::parse((string) $ip->address); - if ((int) $ip->host_id !== (int) $pool->host_id - || (int) $ip->public_ip_pool_id !== (int) $pool->id - || (int) $ip->address_family !== (int) $pool->address_family - || (int) $ip->prefix_length - !== $contract->guestPrefixLength() - || !hash_equals($address->text(), (string) $ip->address) - || !$contract->addressAllowed($address) - || !is_string($ip->address_binary) - || !hash_equals($address->binary(), $ip->address_binary)) { - throw new \InvalidArgumentException(); - } - $management = CloudPanelUsageService::managementAddress( - $lockedHost instanceof CloudHost - ? $lockedHost - : CloudHost::find((int) $pool->host_id) + $contract = CloudPublicNetworkAddressPolicy::contract( + $pool, + (int) $pool->address_family + ); + CloudPublicNetworkAddressPolicy::assertSelectable( + $ip, + $pool, + $contract, + CloudPanelUsageService::managementAddress( + $lockedHost instanceof CloudHost + ? $lockedHost + : CloudHost::find((int) $pool->host_id) + ) ); - if (is_string($management) && $management !== '' - && $address->equals(CloudIpAddress::parse($management))) { - throw new \InvalidArgumentException(); - } } catch (\Throwable) { throw new CloudError('公网地址具体身份与地址池不一致', 409); } @@ -2981,7 +2976,10 @@ final class CloudPublicNetworkTransitionWorkflow private static function dns(CloudPublicIpPool $pool): array { try { - return CloudPublicIpPoolContract::fromRow($pool)->dnsServers(); + return CloudPublicNetworkAddressPolicy::contract( + $pool, + (int) $pool->address_family + )->dnsServers(); } catch (\Throwable) { throw new CloudError('公网地址池 DNS 配置损坏', 409); } diff --git a/web/tests/CloudNetworkIpLedgerContractTest.php b/web/tests/CloudNetworkIpLedgerContractTest.php index a3a89696..97630a02 100644 --- a/web/tests/CloudNetworkIpLedgerContractTest.php +++ b/web/tests/CloudNetworkIpLedgerContractTest.php @@ -17,6 +17,9 @@ $placementNetwork = file_get_contents( $allocation = file_get_contents( $root . '/app/Services/Cloud/CloudPublicNetworkAllocationService.php' ); +$addressPolicy = file_get_contents( + $root . '/app/Services/Cloud/CloudPublicNetworkAddressPolicy.php' +); $adminInstanceService = file_get_contents( $root . '/app/Services/Cloud/CloudAdminInstanceService.php' ); @@ -167,8 +170,14 @@ $assert(is_string($placement) && !str_contains($placement, 'availablePublicIpQuery(') && !str_contains($placement, 'publicIpBelongsToPool('), 'Placement retained a retired scalar network writer.'); -$assert(str_contains($allocation, 'lockReservableAddressCandidate(') - && str_contains($allocation, 'rawAddressAllowedByPool(') +$assert(is_string($addressPolicy) + && str_contains($addressPolicy, 'public static function assertIdentity(') + && str_contains($addressPolicy, 'public static function assertSelectable(') + && str_contains($addressPolicy, 'public static function addressSelectable(') + && !str_contains($addressPolicy, 'lockForUpdate(') + && !str_contains($addressPolicy, 'DB::') + && str_contains($allocation, 'CloudPublicNetworkAddressPolicy::') + && str_contains($workflow, 'CloudPublicNetworkAddressPolicy::') && str_contains($placementNetwork, 'addressAllowedByPool('), 'Canonical allocation lost address-level pool validation.'); $assert(str_contains($pendingMethod, 'CloudPanelUsageService::forHosts($candidateIds)') diff --git a/web/tests/CloudPublicNetworkAddressPolicyTest.php b/web/tests/CloudPublicNetworkAddressPolicyTest.php new file mode 100644 index 00000000..f3e51147 --- /dev/null +++ b/web/tests/CloudPublicNetworkAddressPolicyTest.php @@ -0,0 +1,177 @@ + (int) $pool->host_id, + 'public_ip_pool_id' => (int) $pool->id, + 'address_family' => (int) $pool->address_family, + 'address' => $address, + 'address_binary' => inet_pton($address), + 'prefix_length' => (int) $pool->guest_prefix_length, + ]; +}; + +$ipv4 = (object) [ + 'id' => 10, + 'pool_key' => str_repeat('a', 32), + 'host_id' => 1, + 'address_family' => 4, + 'cidr' => '8.8.8.0/24', + 'gateway' => '8.8.8.1', + 'gateway_on_link' => 0, + 'guest_prefix_length' => 24, + 'dns_servers_json' => '["1.1.1.1","8.8.8.8"]', + 'reserved_ips_json' => '["8.8.8.9"]', + 'allocation_start' => null, + 'allocation_end' => null, + 'allocation_cursor' => null, + 'max_allocations' => 0, +]; +$ipv6 = (object) [ + 'id' => 20, + 'pool_key' => str_repeat('b', 32), + 'host_id' => 1, + 'address_family' => 6, + 'cidr' => '2404:c140:156:3a::/64', + 'gateway' => '2404:c140:156:3a::1', + 'gateway_on_link' => 0, + 'guest_prefix_length' => 64, + 'dns_servers_json' => '["2606:4700:4700::1111"]', + 'reserved_ips_json' => '["2404:c140:156:3a::5"]', + 'allocation_start' => '2404:c140:156:3a::10', + 'allocation_end' => '2404:c140:156:3a::ff', + 'allocation_cursor' => null, + 'max_allocations' => 8, +]; + +$v4Contract = CloudPublicNetworkAddressPolicy::contract($ipv4, 4); +$v6Contract = CloudPublicNetworkAddressPolicy::contract($ipv6, 6); +$v4 = $row($ipv4, '8.8.8.10'); +$v6 = $row($ipv6, '2404:c140:156:3a::10'); +$assert( + CloudPublicNetworkAddressPolicy::assertSelectable( + $v4, + $ipv4, + $v4Contract, + null + )->text() === '8.8.8.10' + && CloudPublicNetworkAddressPolicy::assertSelectable( + $v6, + $ipv6, + $v6Contract, + '103.138.75.126' + )->text() === '2404:c140:156:3a::10', + 'Canonical IPv4/IPv6 candidates were not accepted.' +); + +foreach (['8.8.8.1', '8.8.8.8', '8.8.8.9'] as $excluded) { + $excludedRow = $row($ipv4, $excluded); + $assert( + CloudPublicNetworkAddressPolicy::assertIdentity( + $excludedRow, + $ipv4, + $v4Contract + )->text() === $excluded, + 'Immutable identity rejected a historical excluded address.' + ); + $rejects( + static fn () => CloudPublicNetworkAddressPolicy::assertSelectable( + $excludedRow, + $ipv4, + $v4Contract, + null + ), + 'A gateway or reserved IPv4 was selectable.' + ); +} +$rejects( + static fn () => CloudPublicNetworkAddressPolicy::assertSelectable( + $v4, + $ipv4, + $v4Contract, + '8.8.8.10' + ), + 'The host management IPv4 was selectable.' +); +$historicalV6 = $row($ipv6, '2404:c140:156:3a::6'); +$assert( + CloudPublicNetworkAddressPolicy::assertIdentity( + $historicalV6, + $ipv6, + $v6Contract + )->text() === '2404:c140:156:3a::6', + 'Immutable identity rejected a historical out-of-range IPv6.' +); +$rejects( + static fn () => CloudPublicNetworkAddressPolicy::assertSelectable( + $historicalV6, + $ipv6, + $v6Contract, + null + ), + 'An IPv6 outside the sparse allocation range was selectable.' +); +$rejects( + static fn () => CloudPublicNetworkAddressPolicy::assertSelectable( + $row($ipv4, '1.1.1.1'), + $ipv4, + $v4Contract, + null + ), + 'An out-of-pool DNS address passed row identity.' +); + +foreach (['host_id', 'public_ip_pool_id', 'address_family', 'prefix_length'] as $field) { + $broken = clone $v4; + $broken->{$field} = (int) $broken->{$field} + 1; + $rejects( + static fn () => CloudPublicNetworkAddressPolicy::assertIdentity( + $broken, + $ipv4, + $v4Contract + ), + 'A mismatched ' . $field . ' passed immutable identity.' + ); +} +$brokenBinary = clone $v4; +$brokenBinary->address_binary = inet_pton('8.8.8.11'); +$rejects( + static fn () => CloudPublicNetworkAddressPolicy::assertIdentity( + $brokenBinary, + $ipv4, + $v4Contract + ), + 'A mismatched address binary passed immutable identity.' +); +$rejects( + static fn () => CloudPublicNetworkAddressPolicy::contract($ipv6, 4), + 'A pool contract was accepted for the wrong family.' +); +$rejects( + static fn () => CloudPublicNetworkAddressPolicy::addressSelectable( + CloudIpAddress::parse('8.8.8.10'), + $v4Contract, + 'not-an-address' + ), + 'An invalid management address was silently ignored.' +); + +echo "Public-network address policy tests passed.\n"; diff --git a/web/tests/CloudPublicNetworkPoolReuseContractTest.php b/web/tests/CloudPublicNetworkPoolReuseContractTest.php index 83c40d38..23c0b492 100644 --- a/web/tests/CloudPublicNetworkPoolReuseContractTest.php +++ b/web/tests/CloudPublicNetworkPoolReuseContractTest.php @@ -1,36 +1,66 @@ $method->getName(), + array_filter( + (new ReflectionClass(CloudPublicNetworkAddressPolicy::class)) + ->getMethods(ReflectionMethod::IS_PUBLIC), + static fn (ReflectionMethod $method): bool => + $method->getDeclaringClass()->getName() + === CloudPublicNetworkAddressPolicy::class + ) +)); +sort($methods, SORT_STRING); +if ($methods !== [ + 'addressSelectable', + 'assertIdentity', + 'assertSelectable', + 'contract', +]) { + throw new RuntimeException('Address policy public seam drifted.'); } foreach ([ - 'assertPoolLedger(object $pool,' => 'pool-ledger contract parameter', - 'CloudPublicIpPoolContract $contract, array $rows' => - 'shared parsed contract in ledger validation', - "lockReservableAddressCandidate(\n object \$pool,\n" - . ' CloudPublicIpPoolContract $contract,' => - 'shared parsed contract in candidate selection', - "'contracts' => \$contracts" => 'per-catalog contract cache', - "'contracts' => \$selectedContracts" => - 'per-selection contract propagation', -] as $needle => $label) { - if (!str_contains($source, $needle)) { - throw new RuntimeException('Missing ' . $label . '.'); + 'DB::', + 'lockForUpdate(', + '::find(', + '->save(', + '->update(', + '->insert(', + '->delete(', +] as $forbidden) { + if (str_contains($policy, $forbidden)) { + throw new RuntimeException( + 'Pure address policy performs persistence: ' . $forbidden + ); } } - -$rawAllowed = strstr($source, - 'private static function rawAddressAllowedByPool'); -if (!is_string($rawAllowed) - || !str_contains($rawAllowed, 'CloudPublicIpPoolContract $contract') - || str_contains(substr($rawAllowed, 0, 1200), - 'CloudPublicIpPoolContract::fromRow')) { +if (!str_contains($allocator, 'CloudPublicNetworkAddressPolicy::') + || !str_contains($transition, 'CloudPublicNetworkAddressPolicy::') + || str_contains($allocator, 'rawAddressAllowedByPool') + || str_contains($allocator, 'rawAddressBelongsToPool') + || !str_contains($allocator, "'contracts' => \$contracts") + || !str_contains($allocator, "'contracts' => \$selectedContracts")) { throw new RuntimeException( - 'Hot address validation reconstructs the pool contract per row.' + 'Allocation and transition do not share the pure address policy.' ); } -echo "Public-network allocator pool-contract reuse checks passed.\n"; +echo "Public-network shared address-policy contracts passed.\n";