refactor: establish dual-stack public network contract

go
codex 2 weeks ago
parent 6d96e4540a
commit e33fa0711f

@ -0,0 +1,175 @@
package publicnetwork
import (
"errors"
"fmt"
"net/netip"
"regexp"
)
const ContractVersion uint64 = 1
var poolKeyPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
var networkSelectorPattern = regexp.MustCompile(`^(?:bridge:[A-Za-z0-9][A-Za-z0-9_.-]{0,14}|network:[A-Za-z0-9][A-Za-z0-9_.-]{0,63})$`)
// AddressIntent is one address-family member of an immutable public-network
// identity. PoolCIDR and AddressCIDR always use canonical CIDR notation.
type AddressIntent struct {
PoolKey string `json:"pool_key"`
PoolCIDR string `json:"pool_cidr"`
AddressCIDR string `json:"address_cidr"`
Gateway string `json:"gateway"`
GatewayOnLink bool `json:"gateway_on_link"`
}
// Intent is the only public-network contract shared by the panel, Agent,
// NoCloud seed and libvirt metadata. New instances are always dual stack.
type Intent struct {
Contract uint64 `json:"contract"`
NetworkSelector string `json:"network_selector"`
IPv4 AddressIntent `json:"ipv4"`
IPv6 AddressIntent `json:"ipv6"`
DNSServers []string `json:"dns_servers"`
}
// Canonical validates the complete dual-stack identity and returns the only
// representation that callers may persist, sign or compare.
func (value Intent) Canonical() (Intent, error) {
if value.Contract != ContractVersion {
return Intent{}, fmt.Errorf("public network contract must be %d", ContractVersion)
}
if !networkSelectorPattern.MatchString(value.NetworkSelector) {
return Intent{}, errors.New("network selector is required")
}
ipv4, err := canonicalAddress(value.IPv4, 4)
if err != nil {
return Intent{}, fmt.Errorf("ipv4: %w", err)
}
ipv6, err := canonicalAddress(value.IPv6, 6)
if err != nil {
return Intent{}, fmt.Errorf("ipv6: %w", err)
}
dns, err := canonicalDNS(value.DNSServers)
if err != nil {
return Intent{}, err
}
value.IPv4 = ipv4
value.IPv6 = ipv6
value.DNSServers = dns
return value, nil
}
func (value Intent) IdentityCIDRs() []string {
return []string{value.IPv4.AddressCIDR, value.IPv6.AddressCIDR}
}
func canonicalAddress(value AddressIntent, family int) (AddressIntent, error) {
if !poolKeyPattern.MatchString(value.PoolKey) {
return AddressIntent{}, errors.New("pool key must contain 32 lowercase hexadecimal characters")
}
pool, err := netip.ParsePrefix(value.PoolCIDR)
if err != nil || pool != pool.Masked() || familyOf(pool.Addr()) != family {
return AddressIntent{}, errors.New("pool CIDR is not a canonical address-family network")
}
if family == 4 && (pool.Bits() < 1 || pool.Bits() > 30) {
return AddressIntent{}, errors.New("IPv4 pool prefix must be between /1 and /30")
}
if family == 6 && (pool.Bits() < 1 || pool.Bits() > 120) {
return AddressIntent{}, errors.New("IPv6 pool prefix must be between /1 and /120")
}
requested, err := netip.ParsePrefix(value.AddressCIDR)
if err != nil || familyOf(requested.Addr()) != family || requested.Bits() != pool.Bits() ||
!pool.Contains(requested.Addr()) || requested.Addr() == pool.Addr() {
return AddressIntent{}, errors.New("address CIDR must be a usable host inside its pool")
}
if family == 4 && requested.Addr() == lastIPv4(pool) {
return AddressIntent{}, errors.New("IPv4 address cannot be the broadcast address")
}
if !validPublicAddress(requested.Addr()) {
return AddressIntent{}, errors.New("address must be globally routable unicast")
}
gateway, err := netip.ParseAddr(value.Gateway)
if err != nil || familyOf(gateway) != family || !validPublicAddress(gateway) {
return AddressIntent{}, errors.New("gateway is invalid")
}
if family == 4 && (gateway == pool.Addr() || gateway == lastIPv4(pool)) {
return AddressIntent{}, errors.New("gateway cannot select the network or broadcast address")
}
if gateway == requested.Addr() {
return AddressIntent{}, errors.New("gateway cannot equal the assigned address")
}
if !pool.Contains(gateway) && !value.GatewayOnLink {
return AddressIntent{}, errors.New("off-prefix gateway requires gateway_on_link")
}
value.PoolCIDR = pool.String()
value.AddressCIDR = netip.PrefixFrom(requested.Addr(), requested.Bits()).String()
value.Gateway = gateway.String()
return value, nil
}
func canonicalDNS(values []string) ([]string, error) {
if len(values) < 1 || len(values) > 4 {
return nil, errors.New("dns_servers must contain one to four addresses")
}
result := make([]string, 0, len(values))
seen := make(map[netip.Addr]struct{}, len(values))
for _, raw := range values {
address, err := netip.ParseAddr(raw)
if err != nil || address.Is4In6() || !validPublicAddress(address) {
return nil, errors.New("dns_servers contains an invalid address")
}
if _, exists := seen[address]; exists {
return nil, errors.New("dns_servers contains a duplicate address")
}
seen[address] = struct{}{}
result = append(result, address.String())
}
return result, nil
}
func familyOf(address netip.Addr) int {
if address.Is4() {
return 4
}
if address.Is6() {
return 6
}
return 0
}
func validPublicAddress(address netip.Addr) bool {
if !address.IsGlobalUnicast() || address.IsPrivate() || address.IsLinkLocalUnicast() {
return false
}
if address.Is4() {
for _, prefix := range []netip.Prefix{
netip.MustParsePrefix("0.0.0.0/8"),
netip.MustParsePrefix("10.0.0.0/8"),
netip.MustParsePrefix("100.64.0.0/10"),
netip.MustParsePrefix("127.0.0.0/8"),
netip.MustParsePrefix("169.254.0.0/16"),
netip.MustParsePrefix("172.16.0.0/12"),
netip.MustParsePrefix("192.0.0.0/24"),
netip.MustParsePrefix("192.0.2.0/24"),
netip.MustParsePrefix("192.168.0.0/16"),
netip.MustParsePrefix("198.18.0.0/15"),
netip.MustParsePrefix("198.51.100.0/24"),
netip.MustParsePrefix("203.0.113.0/24"),
netip.MustParsePrefix("224.0.0.0/4"),
netip.MustParsePrefix("240.0.0.0/4"),
} {
if prefix.Contains(address) {
return false
}
}
}
return true
}
func lastIPv4(prefix netip.Prefix) netip.Addr {
address := prefix.Masked().Addr().As4()
bits := uint32(address[0])<<24 | uint32(address[1])<<16 | uint32(address[2])<<8 | uint32(address[3])
bits |= ^uint32(0) >> prefix.Bits()
return netip.AddrFrom4([4]byte{byte(bits >> 24), byte(bits >> 16), byte(bits >> 8), byte(bits)})
}

@ -0,0 +1,89 @@
package publicnetwork
import (
"encoding/json"
"reflect"
"testing"
)
func validIntent() Intent {
return Intent{
Contract: ContractVersion,
NetworkSelector: "bridge:br0",
IPv4: AddressIntent{
PoolKey: "0123456789abcdef0123456789abcdef", PoolCIDR: "8.8.8.0/24",
AddressCIDR: "8.8.8.10/24", Gateway: "8.8.8.1",
},
IPv6: AddressIntent{
PoolKey: "abcdef0123456789abcdef0123456789", PoolCIDR: "2404:c140:156:3a::/64",
AddressCIDR: "2404:c140:156:3a::1000/64", Gateway: "2404:c140:156::1",
GatewayOnLink: true,
},
DNSServers: []string{"1.1.1.1", "2606:4700:4700::1111"},
}
}
func TestIntentCanonicalizesACompleteDualStackIdentity(t *testing.T) {
value := validIntent()
value.IPv6.PoolCIDR = "2404:C140:156:3A:0:0:0:0/64"
value.IPv6.AddressCIDR = "2404:C140:156:3A:0:0:0:1000/64"
canonical, err := value.Canonical()
if err != nil {
t.Fatalf("canonicalize intent: %v", err)
}
if canonical.IPv6.PoolCIDR != "2404:c140:156:3a::/64" ||
canonical.IPv6.AddressCIDR != "2404:c140:156:3a::1000/64" {
t.Fatalf("canonical IPv6 identity = %#v", canonical.IPv6)
}
if got := canonical.IdentityCIDRs(); !reflect.DeepEqual(got, []string{"8.8.8.10/24", "2404:c140:156:3a::1000/64"}) {
t.Fatalf("identity CIDRs = %v", got)
}
}
func TestIntentRequiresBothFamiliesAndExplicitOffPrefixGateway(t *testing.T) {
tests := map[string]func(*Intent){
"missing IPv4": func(v *Intent) { v.IPv4 = AddressIntent{} },
"missing IPv6": func(v *Intent) { v.IPv6 = AddressIntent{} },
"IPv6 in IPv4 slot": func(v *Intent) { v.IPv4.AddressCIDR = v.IPv6.AddressCIDR },
"IPv4 in IPv6 slot": func(v *Intent) { v.IPv6.AddressCIDR = v.IPv4.AddressCIDR },
"off-prefix without onlink": func(v *Intent) { v.IPv6.GatewayOnLink = false },
"duplicate DNS": func(v *Intent) { v.DNSServers = []string{"1.1.1.1", "1.1.1.1"} },
"unsafe selector": func(v *Intent) { v.NetworkSelector = "bridge:br0;reboot" },
"special-use IPv4": func(v *Intent) {
v.IPv4.PoolCIDR, v.IPv4.AddressCIDR, v.IPv4.Gateway = "198.51.100.0/24", "198.51.100.10/24", "198.51.100.1"
},
"legacy contract": func(v *Intent) { v.Contract = 0 },
}
for name, mutate := range tests {
t.Run(name, func(t *testing.T) {
value := validIntent()
mutate(&value)
if _, err := value.Canonical(); err == nil {
t.Fatal("invalid dual-stack intent was accepted")
}
})
}
}
func TestIntentWireContractHasNoLegacyFlatFields(t *testing.T) {
encoded, err := json.Marshal(validIntent())
if err != nil {
t.Fatalf("marshal intent: %v", err)
}
var wire map[string]any
if err := json.Unmarshal(encoded, &wire); err != nil {
t.Fatalf("decode intent: %v", err)
}
for _, key := range []string{"public_ip_cidr", "public_pool_cidr", "public_pool_key", "gateway"} {
if _, exists := wire[key]; exists {
t.Fatalf("legacy flat field %q escaped: %#v", key, wire)
}
}
if _, ok := wire["ipv4"].(map[string]any); !ok {
t.Fatalf("missing IPv4 object: %#v", wire)
}
if _, ok := wire["ipv6"].(map[string]any); !ok {
t.Fatalf("missing IPv6 object: %#v", wire)
}
}

@ -0,0 +1,164 @@
<?php
namespace App\Services\Cloud;
/** Canonical IPv4/IPv6 value used by the panel-owned public-network contract. */
final class CloudIpAddress
{
private function __construct(
private readonly string $binary,
private readonly string $text,
private readonly int $family
) {
}
public static function parse(mixed $value): self
{
if (!is_string($value) || $value === '' || trim($value) !== $value
|| str_contains($value, '%')) {
throw new \InvalidArgumentException('IP address is invalid.');
}
$binary = @inet_pton($value);
if ($binary === false || !in_array(strlen($binary), [4, 16], true)) {
throw new \InvalidArgumentException('IP address is invalid.');
}
$text = @inet_ntop($binary);
if (!is_string($text) || $text === '') {
throw new \InvalidArgumentException('IP address is invalid.');
}
return new self($binary, strtolower($text), strlen($binary) === 4 ? 4 : 6);
}
public static function fromBinary(string $binary): self
{
if (!in_array(strlen($binary), [4, 16], true)) {
throw new \InvalidArgumentException('Binary IP address is invalid.');
}
$text = @inet_ntop($binary);
if (!is_string($text) || $text === '') {
throw new \InvalidArgumentException('Binary IP address is invalid.');
}
return new self($binary, strtolower($text), strlen($binary) === 4 ? 4 : 6);
}
public function text(): string
{
return $this->text;
}
public function binary(): string
{
return $this->binary;
}
public function family(): int
{
return $this->family;
}
public function equals(self $other): bool
{
return $this->family === $other->family
&& hash_equals($this->binary, $other->binary);
}
public function compare(self $other): int
{
if ($this->family !== $other->family) {
throw new \InvalidArgumentException('IP families do not match.');
}
return strcmp($this->binary, $other->binary);
}
public function next(): self
{
$bytes = array_values(unpack('C*', $this->binary));
for ($index = count($bytes) - 1; $index >= 0; $index--) {
if ($bytes[$index] < 255) {
$bytes[$index]++;
return self::fromBinary(pack('C*', ...$bytes));
}
$bytes[$index] = 0;
}
throw new \OverflowException('IP address space is exhausted.');
}
public function isUnspecified(): bool
{
return $this->binary === str_repeat("\0", strlen($this->binary));
}
public function isLoopback(): bool
{
if ($this->family === 4) {
return ord($this->binary[0]) === 127;
}
return $this->binary === str_repeat("\0", 15) . "\1";
}
public function isMulticast(): bool
{
$first = ord($this->binary[0]);
return $this->family === 4 ? ($first & 0xf0) === 0xe0 : $first === 0xff;
}
public function isLinkLocal(): bool
{
if ($this->family === 4) {
return ord($this->binary[0]) === 169 && ord($this->binary[1]) === 254;
}
return ord($this->binary[0]) === 0xfe
&& (ord($this->binary[1]) & 0xc0) === 0x80;
}
public function isIpv4Mapped(): bool
{
return $this->family === 6
&& substr($this->binary, 0, 10) === str_repeat("\0", 10)
&& substr($this->binary, 10, 2) === "\xff\xff";
}
public function isUsableUnicast(): bool
{
return !$this->isUnspecified() && !$this->isLoopback()
&& !$this->isMulticast() && !$this->isLinkLocal()
&& !$this->isIpv4Mapped();
}
/** Public-network intents never accept private or special-use addresses. */
public function isPublicUnicast(): bool
{
if (!$this->isUsableUnicast()) {
return false;
}
if ($this->family === 6) {
// fc00::/7 unique-local addresses are not public Internet space.
return (ord($this->binary[0]) & 0xfe) !== 0xfc;
}
$number = unpack('Nvalue', $this->binary);
if (!is_array($number) || !isset($number['value'])) {
return false;
}
$value = (int) sprintf('%u', $number['value']);
foreach ([
['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10],
['127.0.0.0', 8], ['169.254.0.0', 16], ['172.16.0.0', 12],
['192.0.0.0', 24], ['192.0.2.0', 24], ['192.168.0.0', 16],
['198.18.0.0', 15], ['198.51.100.0', 24],
['203.0.113.0', 24], ['224.0.0.0', 4], ['240.0.0.0', 4],
] as [$network, $prefix]) {
$packed = inet_pton($network);
$baseParts = is_string($packed) ? unpack('Nvalue', $packed) : false;
if (!is_array($baseParts) || !isset($baseParts['value'])) {
return false;
}
$base = (int) sprintf('%u', $baseParts['value']);
$size = 2 ** (32 - $prefix);
if ($value >= $base && $value < $base + $size) {
return false;
}
}
return true;
}
}

@ -0,0 +1,131 @@
<?php
namespace App\Services\Cloud;
/** Canonical address/prefix pair with family-safe containment operations. */
final class CloudIpPrefix
{
private function __construct(
private readonly CloudIpAddress $address,
private readonly CloudIpAddress $network,
private readonly int $prefixLength
) {
}
public static function address(mixed $value): self
{
return self::parse($value, false);
}
public static function network(mixed $value): self
{
return self::parse($value, true);
}
private static function parse(mixed $value, bool $requireNetwork): self
{
if (!is_string($value) || substr_count($value, '/') !== 1
|| trim($value) !== $value) {
throw new \InvalidArgumentException('IP prefix is invalid.');
}
[$rawAddress, $rawPrefix] = explode('/', $value, 2);
if ($rawPrefix === '' || preg_match('/^(?:0|[1-9][0-9]{0,2})$/D',
$rawPrefix) !== 1) {
throw new \InvalidArgumentException('IP prefix is invalid.');
}
$address = CloudIpAddress::parse($rawAddress);
$prefix = (int) $rawPrefix;
$maximum = $address->family() === 4 ? 32 : 128;
if ($prefix < 1 || $prefix > $maximum) {
throw new \InvalidArgumentException('IP prefix length is invalid.');
}
$network = CloudIpAddress::fromBinary(
self::maskedBinary($address->binary(), $prefix)
);
if ($requireNetwork && !$address->equals($network)) {
throw new \InvalidArgumentException('Network prefix has host bits set.');
}
return new self($address, $network, $prefix);
}
public function family(): int
{
return $this->address->family();
}
public function prefixLength(): int
{
return $this->prefixLength;
}
public function addressValue(): CloudIpAddress
{
return $this->address;
}
public function networkAddress(): CloudIpAddress
{
return $this->network;
}
public function canonical(): string
{
return $this->address->text() . '/' . $this->prefixLength;
}
public function networkCidr(): string
{
return $this->network->text() . '/' . $this->prefixLength;
}
public function contains(CloudIpAddress $address): bool
{
return $address->family() === $this->family()
&& hash_equals(
$this->network->binary(),
self::maskedBinary($address->binary(), $this->prefixLength)
);
}
public function overlaps(self $other): bool
{
if ($other->family() !== $this->family()) {
return false;
}
$bits = min($this->prefixLength, $other->prefixLength);
return hash_equals(
self::maskedBinary($this->network->binary(), $bits),
self::maskedBinary($other->network->binary(), $bits)
);
}
public function lastAddress(): CloudIpAddress
{
$bytes = array_values(unpack('C*', $this->network->binary()));
$totalBits = count($bytes) * 8;
for ($bit = $this->prefixLength; $bit < $totalBits; $bit++) {
$index = intdiv($bit, 8);
$offset = 7 - ($bit % 8);
$bytes[$index] |= 1 << $offset;
}
return CloudIpAddress::fromBinary(pack('C*', ...$bytes));
}
private static function maskedBinary(string $binary, int $prefix): string
{
$bytes = array_values(unpack('C*', $binary));
foreach ($bytes as $index => $byte) {
$start = $index * 8;
$remaining = $prefix - $start;
if ($remaining >= 8) {
continue;
}
if ($remaining <= 0) {
$bytes[$index] = 0;
continue;
}
$bytes[$index] = $byte & (0xff << (8 - $remaining));
}
return pack('C*', ...$bytes);
}
}

@ -0,0 +1,131 @@
<?php
namespace App\Services\Cloud;
/** Immutable, canonical IPv4+IPv6 identity frozen into every new VM intent. */
final class CloudPublicNetworkSnapshot
{
private function __construct(private readonly array $snapshot)
{
}
public static function fromArray(mixed $value): self
{
if (!is_array($value) || array_is_list($value)) {
throw new \InvalidArgumentException('Public network must be an object.');
}
self::exactKeys($value, [
'contract', 'network_selector', 'ipv4', 'ipv6', 'dns_servers',
]);
if (($value['contract'] ?? null) !== 1
|| !CloudNetworkSelector::isValid($value['network_selector'] ?? null)) {
throw new \InvalidArgumentException('Public network contract is invalid.');
}
$ipv4 = self::leg($value['ipv4'] ?? null, 4);
$ipv6 = self::leg($value['ipv6'] ?? null, 6);
$dns = self::dns($value['dns_servers'] ?? null);
return new self([
'contract' => 1,
'network_selector' => $value['network_selector'],
'ipv4' => $ipv4,
'ipv6' => $ipv6,
'dns_servers' => $dns,
]);
}
public function toArray(): array
{
return $this->snapshot;
}
public function fingerprint(): string
{
return hash('sha256', json_encode(
$this->snapshot,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
));
}
public function address(int $family): string
{
$key = $family === 4 ? 'ipv4' : ($family === 6 ? 'ipv6' : null);
if ($key === null) {
throw new \InvalidArgumentException('Address family is invalid.');
}
return $this->snapshot[$key]['address_cidr'];
}
private static function leg(mixed $value, int $family): array
{
if (!is_array($value) || array_is_list($value)) {
throw new \InvalidArgumentException('Public network leg is invalid.');
}
self::exactKeys($value, [
'pool_key', 'pool_cidr', 'address_cidr', 'gateway',
'gateway_on_link',
]);
$poolKey = $value['pool_key'] ?? null;
if (!is_string($poolKey)
|| preg_match('/^[a-f0-9]{32}$/D', $poolKey) !== 1
|| !is_bool($value['gateway_on_link'] ?? null)) {
throw new \InvalidArgumentException('Public network leg is invalid.');
}
$pool = CloudIpPrefix::network($value['pool_cidr'] ?? null);
$address = CloudIpPrefix::address($value['address_cidr'] ?? null);
$gateway = CloudIpAddress::parse($value['gateway'] ?? null);
if ($pool->family() !== $family || $address->family() !== $family
|| $gateway->family() !== $family
|| ($family === 4 && $pool->prefixLength() > 30)
|| ($family === 6 && $pool->prefixLength() > 120)
|| $address->prefixLength() !== $pool->prefixLength()
|| !$pool->contains($address->addressValue())
|| !$address->addressValue()->isPublicUnicast()
|| !$gateway->isPublicUnicast()
|| $address->addressValue()->equals($pool->networkAddress())
|| ($family === 4
&& $address->addressValue()->equals($pool->lastAddress()))
|| ($family === 4
&& ($gateway->equals($pool->networkAddress())
|| $gateway->equals($pool->lastAddress())))
|| $address->addressValue()->equals($gateway)
|| (!$pool->contains($gateway)
&& $value['gateway_on_link'] !== true)) {
throw new \InvalidArgumentException('Public network leg is inconsistent.');
}
return [
'pool_key' => $poolKey,
'pool_cidr' => $pool->networkCidr(),
'address_cidr' => $address->canonical(),
'gateway' => $gateway->text(),
'gateway_on_link' => $value['gateway_on_link'],
];
}
private static function dns(mixed $value): array
{
if (!is_array($value) || !array_is_list($value)
|| $value === [] || count($value) > 4) {
throw new \InvalidArgumentException('DNS server list is invalid.');
}
$result = [];
foreach ($value as $raw) {
$address = CloudIpAddress::parse($raw);
if (!$address->isPublicUnicast()
|| isset($result[$address->text()])) {
throw new \InvalidArgumentException('DNS server list is invalid.');
}
$result[$address->text()] = $address->text();
}
return array_values($result);
}
private static function exactKeys(array $value, array $expected): void
{
$actual = array_keys($value);
sort($actual, SORT_STRING);
sort($expected, SORT_STRING);
if ($actual !== $expected) {
throw new \InvalidArgumentException('Public network fields are invalid.');
}
}
}

@ -0,0 +1,125 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudIpAddress;
use App\Services\Cloud\CloudIpPrefix;
use App\Services\Cloud\CloudPublicNetworkSnapshot;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$rejects = static function (callable $callback, string $message): void {
try {
$callback();
} catch (InvalidArgumentException) {
return;
}
throw new RuntimeException($message);
};
$ipv4 = CloudIpAddress::parse('198.51.100.10');
$assert($ipv4->family() === 4 && $ipv4->text() === '198.51.100.10'
&& strlen($ipv4->binary()) === 4,
'IPv4 canonicalization changed.');
$ipv6 = CloudIpAddress::parse('2404:0c140:0156:003a:0:0:0:1000');
$assert($ipv6->family() === 6
&& $ipv6->text() === '2404:c140:156:3a::1000'
&& strlen($ipv6->binary()) === 16,
'IPv6 RFC 5952 canonicalization changed.');
$rejects(static fn () => CloudIpAddress::parse('fe80::1%br0'),
'A scoped IPv6 address crossed the public-network contract.');
$pool6 = CloudIpPrefix::network('2404:c140:156:3a::/64');
$assert($pool6->family() === 6 && $pool6->prefixLength() === 64
&& $pool6->canonical() === '2404:c140:156:3a::/64'
&& $pool6->contains($ipv6),
'IPv6 pool containment changed.');
$assert($pool6->overlaps(CloudIpPrefix::network(
'2404:c140:156:3a:8000::/65'
)) && !$pool6->overlaps(CloudIpPrefix::network(
'2404:c140:156:3b::/64'
)),
'IPv6 prefix-overlap detection changed.');
$rejects(static fn () => CloudIpPrefix::network(
'2404:c140:156:3a::1/64'
), 'A non-canonical network prefix was accepted.');
$snapshot = CloudPublicNetworkSnapshot::fromArray([
'contract' => 1,
'network_selector' => 'bridge:br0',
'ipv4' => [
'pool_key' => str_repeat('a', 32),
'pool_cidr' => '8.8.8.0/24',
'address_cidr' => '8.8.8.10/24',
'gateway' => '8.8.8.1',
'gateway_on_link' => false,
],
'ipv6' => [
'pool_key' => str_repeat('b', 32),
'pool_cidr' => '2404:c140:156:3a::/64',
'address_cidr' => '2404:0c140:0156:003a::1000/64',
'gateway' => '2404:c140:156::1',
'gateway_on_link' => true,
],
'dns_servers' => [
'1.1.1.1',
'2606:4700:4700:0000:0000:0000:0000:1111',
],
]);
$expected = [
'contract' => 1,
'network_selector' => 'bridge:br0',
'ipv4' => [
'pool_key' => str_repeat('a', 32),
'pool_cidr' => '8.8.8.0/24',
'address_cidr' => '8.8.8.10/24',
'gateway' => '8.8.8.1',
'gateway_on_link' => false,
],
'ipv6' => [
'pool_key' => str_repeat('b', 32),
'pool_cidr' => '2404:c140:156:3a::/64',
'address_cidr' => '2404:c140:156:3a::1000/64',
'gateway' => '2404:c140:156::1',
'gateway_on_link' => true,
],
'dns_servers' => ['1.1.1.1', '2606:4700:4700::1111'],
];
$assert($snapshot->toArray() === $expected,
'The frozen dual-stack network snapshot is not canonical.');
$assert($snapshot->fingerprint() === hash('sha256', json_encode(
$expected,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
)), 'The network fingerprint is not derived from the canonical contract.');
$rejects(static fn () => CloudPublicNetworkSnapshot::fromArray([
'contract' => 1,
'network_selector' => 'bridge:br0',
'ipv4' => $expected['ipv4'],
'ipv6' => array_merge($expected['ipv6'], [
'gateway_on_link' => false,
]),
'dns_servers' => $expected['dns_servers'],
]), 'An off-prefix IPv6 gateway was accepted without on-link intent.');
$rejects(static fn () => CloudPublicNetworkSnapshot::fromArray([
'contract' => 1,
'network_selector' => 'bridge:br0',
'ipv4' => $expected['ipv4'],
'dns_servers' => $expected['dns_servers'],
]), 'An IPv4-only network crossed the new-instance contract.');
$rejects(static fn () => CloudPublicNetworkSnapshot::fromArray([
'contract' => 1,
'network_selector' => 'bridge:br0',
'ipv4' => array_merge($expected['ipv4'], [
'pool_cidr' => '198.51.100.0/24',
'address_cidr' => '198.51.100.10/24',
'gateway' => '198.51.100.1',
]),
'ipv6' => $expected['ipv6'],
'dns_servers' => $expected['dns_servers'],
]), 'A special-use IPv4 range crossed the public-network contract.');
echo "Dual-stack public network contract tests passed.\n";
Loading…
Cancel
Save