From e33fa0711f64caacf14cec1f66f42cdcaa62eb42 Mon Sep 17 00:00:00 2001 From: codex Date: Tue, 3 Nov 2026 13:47:30 +0800 Subject: [PATCH] refactor: establish dual-stack public network contract --- agent/publicnetwork/intent.go | 175 ++++++++++++++++++ agent/publicnetwork/intent_test.go | 89 +++++++++ web/app/Services/Cloud/CloudIpAddress.php | 164 ++++++++++++++++ web/app/Services/Cloud/CloudIpPrefix.php | 131 +++++++++++++ .../Cloud/CloudPublicNetworkSnapshot.php | 131 +++++++++++++ web/tests/CloudPublicNetworkContractTest.php | 125 +++++++++++++ 6 files changed, 815 insertions(+) create mode 100644 agent/publicnetwork/intent.go create mode 100644 agent/publicnetwork/intent_test.go create mode 100644 web/app/Services/Cloud/CloudIpAddress.php create mode 100644 web/app/Services/Cloud/CloudIpPrefix.php create mode 100644 web/app/Services/Cloud/CloudPublicNetworkSnapshot.php create mode 100644 web/tests/CloudPublicNetworkContractTest.php diff --git a/agent/publicnetwork/intent.go b/agent/publicnetwork/intent.go new file mode 100644 index 00000000..d9f20e02 --- /dev/null +++ b/agent/publicnetwork/intent.go @@ -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)}) +} diff --git a/agent/publicnetwork/intent_test.go b/agent/publicnetwork/intent_test.go new file mode 100644 index 00000000..983708ef --- /dev/null +++ b/agent/publicnetwork/intent_test.go @@ -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) + } +} diff --git a/web/app/Services/Cloud/CloudIpAddress.php b/web/app/Services/Cloud/CloudIpAddress.php new file mode 100644 index 00000000..b6b5e574 --- /dev/null +++ b/web/app/Services/Cloud/CloudIpAddress.php @@ -0,0 +1,164 @@ +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; + } +} diff --git a/web/app/Services/Cloud/CloudIpPrefix.php b/web/app/Services/Cloud/CloudIpPrefix.php new file mode 100644 index 00000000..9f8855ea --- /dev/null +++ b/web/app/Services/Cloud/CloudIpPrefix.php @@ -0,0 +1,131 @@ +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); + } +} diff --git a/web/app/Services/Cloud/CloudPublicNetworkSnapshot.php b/web/app/Services/Cloud/CloudPublicNetworkSnapshot.php new file mode 100644 index 00000000..32cf3c21 --- /dev/null +++ b/web/app/Services/Cloud/CloudPublicNetworkSnapshot.php @@ -0,0 +1,131 @@ + 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.'); + } + } +} diff --git a/web/tests/CloudPublicNetworkContractTest.php b/web/tests/CloudPublicNetworkContractTest.php new file mode 100644 index 00000000..d826e009 --- /dev/null +++ b/web/tests/CloudPublicNetworkContractTest.php @@ -0,0 +1,125 @@ +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";