You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudPublicIpPoolContract.php

371 lines
12 KiB
PHP

<?php
namespace App\Services\Cloud;
/**
* Canonical, read-only interpretation of one persisted public-IP pool.
*
* Pool lifecycle and synchronization state are deliberately caller-owned;
* this object validates only the immutable addressing contract accepted by
* the administrator writer and consumed by allocation/change workflows.
*/
final class CloudPublicIpPoolContract
{
private const MAX_IPV6_ALLOCATIONS = 65535;
private function __construct(
private readonly int $family,
private readonly string $poolKey,
private readonly CloudIpPrefix $network,
private readonly CloudIpAddress $gateway,
private readonly bool $gatewayOnLink,
private readonly array $dns,
private readonly array $reserved,
private readonly ?CloudIpAddress $allocationStart,
private readonly ?CloudIpAddress $allocationEnd,
private readonly ?CloudIpAddress $allocationCursor,
private readonly int $maxAllocations
) {
}
public static function fromRow(object $pool): self
{
try {
$family = (int) ($pool->address_family ?? 0);
$poolKey = (string) ($pool->pool_key ?? '');
$network = CloudIpPrefix::network($pool->cidr ?? null);
$gateway = CloudIpAddress::parse($pool->gateway ?? null);
$gatewayOnLink = self::strictBoolean(
method_exists($pool, 'getRawOriginal')
? $pool->getRawOriginal('gateway_on_link')
: ($pool->gateway_on_link ?? null)
);
$guestPrefix = (int) ($pool->guest_prefix_length ?? 0);
if (!in_array($family, [4, 6], true)
|| preg_match('/^[a-f0-9]{32}$/D', $poolKey) !== 1
|| $network->family() !== $family
|| !hash_equals(
$network->networkCidr(),
(string) $pool->cidr
)
|| !$network->networkAddress()->isPublicUnicast()
|| $guestPrefix !== $network->prefixLength()
|| ($family === 4
&& ($guestPrefix < 24 || $guestPrefix > 30))
|| ($family === 6
&& ($guestPrefix < 48 || $guestPrefix > 120))
|| $gateway->family() !== $family
|| !$gateway->isPublicUnicast()
|| !hash_equals(
$gateway->text(),
(string) $pool->gateway
)) {
throw new \InvalidArgumentException();
}
$gatewayInPool = self::usableInPrefix($network, $gateway);
if (($family === 4 && ($gatewayOnLink || !$gatewayInPool))
|| ($family === 6 && !$gatewayInPool && !$gatewayOnLink)) {
throw new \InvalidArgumentException();
}
$dns = self::addressList(
$pool->dns_servers_json ?? null,
false,
4,
null,
null
);
$reserved = self::addressList(
$pool->reserved_ips_json ?? null,
true,
256,
$family,
$network
);
$max = (int) ($pool->max_allocations ?? -1);
$start = null;
$end = null;
$cursor = null;
if ($family === 4) {
if (($pool->allocation_start ?? null) !== null
|| ($pool->allocation_end ?? null) !== null
|| ($pool->allocation_cursor ?? null) !== null
|| $max !== 0) {
throw new \InvalidArgumentException();
}
} else {
if ($max < 1 || $max > self::MAX_IPV6_ALLOCATIONS) {
throw new \InvalidArgumentException();
}
$start = self::canonicalAddress(
$pool->allocation_start ?? null,
6
);
$end = self::canonicalAddress(
$pool->allocation_end ?? null,
6
);
if (!self::usableInPrefix($network, $start)
|| !self::usableInPrefix($network, $end)
|| $start->compare($end) > 0) {
throw new \InvalidArgumentException();
}
if (($pool->allocation_cursor ?? null) !== null) {
$cursor = self::canonicalAddress(
$pool->allocation_cursor,
6
);
if ($cursor->compare($start) < 0
|| $cursor->compare($end) > 0) {
throw new \InvalidArgumentException();
}
}
self::assertSparseCapacity(
$start,
$end,
$max,
$gateway,
$dns,
$reserved
);
}
return new self(
$family,
$poolKey,
$network,
$gateway,
$gatewayOnLink,
$dns,
$reserved,
$start,
$end,
$cursor,
$max
);
} catch (\Throwable $error) {
if ($error instanceof \InvalidArgumentException
&& $error->getMessage() === 'Public IP pool contract is invalid.') {
throw $error;
}
throw new \InvalidArgumentException(
'Public IP pool contract is invalid.',
0,
$error
);
}
}
public function family(): int
{
return $this->family;
}
public function poolKey(): string
{
return $this->poolKey;
}
public function network(): CloudIpPrefix
{
return $this->network;
}
public function gateway(): CloudIpAddress
{
return $this->gateway;
}
public function gatewayOnLink(): bool
{
return $this->gatewayOnLink;
}
/** @return list<string> */
public function dnsServers(): array
{
return array_keys($this->dns);
}
/** @return list<string> */
public function reservedAddresses(): array
{
return array_keys($this->reserved);
}
public function allocationStart(): ?CloudIpAddress
{
return $this->allocationStart;
}
public function allocationEnd(): ?CloudIpAddress
{
return $this->allocationEnd;
}
public function allocationCursor(): ?CloudIpAddress
{
return $this->allocationCursor;
}
public function maxAllocations(): int
{
return $this->maxAllocations;
}
public function guestPrefixLength(): int
{
return $this->network->prefixLength();
}
public function addressBelongs(CloudIpAddress $address): bool
{
return $address->family() === $this->family
&& self::usableInPrefix($this->network, $address);
}
public function addressAllowed(CloudIpAddress $address): bool
{
if (!$this->addressBelongs($address)
|| $address->equals($this->gateway)
|| isset($this->dns[$address->text()])
|| isset($this->reserved[$address->text()])) {
return false;
}
return $this->family === 4
|| ($this->allocationStart instanceof CloudIpAddress
&& $this->allocationEnd instanceof CloudIpAddress
&& $address->compare($this->allocationStart) >= 0
&& $address->compare($this->allocationEnd) <= 0);
}
private static function canonicalAddress(mixed $raw,
?int $family): CloudIpAddress
{
$address = CloudIpAddress::parse($raw);
if (($family !== null && $address->family() !== $family)
|| !$address->isPublicUnicast()
|| !is_string($raw)
|| !hash_equals($address->text(), $raw)) {
throw new \InvalidArgumentException();
}
return $address;
}
private static function strictBoolean(mixed $value): bool
{
if ($value === true || $value === 1 || $value === '1') {
return true;
}
if ($value === false || $value === 0 || $value === '0') {
return false;
}
throw new \InvalidArgumentException();
}
/** @return array<string,CloudIpAddress> */
private static function addressList(mixed $json, bool $allowEmpty,
int $maximum, ?int $family, ?CloudIpPrefix $network): array
{
if (!is_string($json)) {
throw new \InvalidArgumentException();
}
$values = json_decode($json, true, 16, JSON_THROW_ON_ERROR);
if (!is_array($values) || !array_is_list($values)
|| (!$allowEmpty && $values === [])
|| count($values) > $maximum) {
throw new \InvalidArgumentException();
}
$result = [];
foreach ($values as $raw) {
$address = self::canonicalAddress($raw, $family);
if (isset($result[$address->text()])
|| ($network instanceof CloudIpPrefix
&& !self::usableInPrefix($network, $address))) {
throw new \InvalidArgumentException();
}
$result[$address->text()] = $address;
}
return $result;
}
private static function usableInPrefix(CloudIpPrefix $network,
CloudIpAddress $address): bool
{
return $address->isPublicUnicast()
&& $network->contains($address)
&& !$address->equals($network->networkAddress())
&& ($address->family() !== 4
|| !$address->equals($network->lastAddress()));
}
/** @param array<string,CloudIpAddress> $dns
* @param array<string,CloudIpAddress> $reserved */
private static function assertSparseCapacity(CloudIpAddress $start,
CloudIpAddress $end, int $maximum, CloudIpAddress $gateway,
array $dns, array $reserved): void
{
$blocked = $dns + $reserved;
if ($gateway->family() === 6) {
$blocked[$gateway->text()] = $gateway;
}
$blockedInRange = 0;
foreach ($blocked as $address) {
if ($address->family() === 6
&& $address->compare($start) >= 0
&& $address->compare($end) <= 0) {
$blockedInRange++;
}
}
if (!self::inclusiveRangeContainsAtLeast(
$start,
$end,
$maximum + $blockedInRange
)) {
throw new \InvalidArgumentException();
}
}
/** Compare a 128-bit inclusive range with a small bounded cardinality. */
private static function inclusiveRangeContainsAtLeast(
CloudIpAddress $start,
CloudIpAddress $end,
int $needed
): bool {
if ($needed <= 1) {
return true;
}
$left = array_values(unpack('C*', $start->binary()));
$right = array_values(unpack('C*', $end->binary()));
$difference = array_fill(0, count($left), 0);
$borrow = 0;
for ($index = count($left) - 1; $index >= 0; $index--) {
$byte = $right[$index] - $left[$index] - $borrow;
if ($byte < 0) {
$byte += 256;
$borrow = 1;
} else {
$borrow = 0;
}
$difference[$index] = $byte;
}
if ($borrow !== 0) {
return false;
}
$requiredDistance = $needed - 1;
$distance = 0;
foreach ($difference as $byte) {
if ($distance > intdiv($requiredDistance, 256)) {
return true;
}
$distance = ($distance * 256) + $byte;
if ($distance > $requiredDistance) {
return true;
}
}
return $distance >= $requiredDistance;
}
}