From 971a4c15ee57fa3c84fa60451e0eec378972dba1 Mon Sep 17 00:00:00 2001 From: Muhammad Askri Date: Wed, 18 Nov 2026 14:40:41 -0800 Subject: [PATCH] Add the `CelCidr` opaque value representation (`net.CIDR`) to support CIDR prefix parsing, host-bit masking, and IP/CIDR containment checks in CEL Java with parity against `cel-go` and `cel-spec`. `CelCidr` extends `OpaqueValue` directly using immutable fields, rejects leading zeros in prefix lengths, zone identifiers, and IPv4-mapped IPv6 addresses, and preserves unmasked host bits while masking during prefix containment checks via `CelIp` prefix helpers. Also register `net.CIDR` in `DefaultTypeProvider` so type identifiers resolve during evaluation. PiperOrigin-RevId: 1024996981 --- .../cel/common/types/DefaultTypeProvider.java | 8 + extensions/BUILD.bazel | 10 + .../main/java/dev/cel/extensions/BUILD.bazel | 32 ++ .../main/java/dev/cel/extensions/CelCidr.java | 174 +++++++ .../main/java/dev/cel/extensions/CelIp.java | 462 ++++++++++++++++++ .../test/java/dev/cel/extensions/BUILD.bazel | 3 + .../cel/extensions/CelNetworkTypesTest.java | 289 +++++++++++ 7 files changed, 978 insertions(+) create mode 100644 extensions/src/main/java/dev/cel/extensions/CelCidr.java create mode 100644 extensions/src/main/java/dev/cel/extensions/CelIp.java create mode 100644 extensions/src/test/java/dev/cel/extensions/CelNetworkTypesTest.java diff --git a/common/src/main/java/dev/cel/common/types/DefaultTypeProvider.java b/common/src/main/java/dev/cel/common/types/DefaultTypeProvider.java index 372a50e73..16bcd31df 100644 --- a/common/src/main/java/dev/cel/common/types/DefaultTypeProvider.java +++ b/common/src/main/java/dev/cel/common/types/DefaultTypeProvider.java @@ -50,6 +50,14 @@ private DefaultTypeProvider() { "optional_type", // TODO: Move to CelOptionalLibrary and register it on demand OptionalType.create(SimpleType.DYN)); + typeMapBuilder.put( + "net.IP", + // TODO: Move to CelNetworkExtensions and register it on demand + OpaqueType.create("net.IP")); + typeMapBuilder.put( + "net.CIDR", + // TODO: Move to CelNetworkExtensions and register it on demand + OpaqueType.create("net.CIDR")); this.commonTypes = typeMapBuilder.buildOrThrow(); } } diff --git a/extensions/BUILD.bazel b/extensions/BUILD.bazel index 1f9f792f0..f97d020fd 100644 --- a/extensions/BUILD.bazel +++ b/extensions/BUILD.bazel @@ -197,3 +197,13 @@ cel_android_library( name = "regex_runtime_library_android", exports = ["//extensions/src/main/java/dev/cel/extensions:regex_runtime_library_android"], ) + +java_library( + name = "network_types", + exports = ["//extensions/src/main/java/dev/cel/extensions:network_types"], +) + +cel_android_library( + name = "network_types_android", + exports = ["//extensions/src/main/java/dev/cel/extensions:network_types_android"], +) diff --git a/extensions/src/main/java/dev/cel/extensions/BUILD.bazel b/extensions/src/main/java/dev/cel/extensions/BUILD.bazel index 3cded5e17..6ae4e2f60 100644 --- a/extensions/src/main/java/dev/cel/extensions/BUILD.bazel +++ b/extensions/src/main/java/dev/cel/extensions/BUILD.bazel @@ -599,6 +599,38 @@ cel_android_library( ], ) +java_library( + name = "network_types", + srcs = [ + "CelCidr.java", + "CelIp.java", + ], + tags = [ + ], + deps = [ + "//common/types", + "//common/values", + "@maven//:com_google_errorprone_error_prone_annotations", + "@maven//:org_jspecify_jspecify", + ], +) + +cel_android_library( + name = "network_types_android", + srcs = [ + "CelCidr.java", + "CelIp.java", + ], + tags = [ + ], + deps = [ + "//common/types:types_android", + "//common/values:values_android", + "@maven//:com_google_errorprone_error_prone_annotations", + "@maven//:org_jspecify_jspecify", + ], +) + java_library( name = "comprehensions", srcs = ["CelComprehensionsExtensions.java"], diff --git a/extensions/src/main/java/dev/cel/extensions/CelCidr.java b/extensions/src/main/java/dev/cel/extensions/CelCidr.java new file mode 100644 index 000000000..1d7d3eb7d --- /dev/null +++ b/extensions/src/main/java/dev/cel/extensions/CelCidr.java @@ -0,0 +1,174 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package dev.cel.extensions; + +import com.google.errorprone.annotations.CheckReturnValue; +import com.google.errorprone.annotations.Immutable; +import dev.cel.common.types.OpaqueType; +import dev.cel.common.values.OpaqueValue; +import java.util.Objects; +import org.jspecify.annotations.Nullable; + +/** Immutable CEL opaque value representing an IPv4 or IPv6 CIDR prefix ({@code net.CIDR}). */ +@Immutable +@CheckReturnValue +public final class CelCidr extends OpaqueValue { + + /** CEL opaque type for {@code net.CIDR}. */ + public static final OpaqueType CIDR_TYPE = OpaqueType.create("net.CIDR"); + + private final CelIp ip; + private final int prefixLength; + + private CelCidr(CelIp ip, int prefixLength) { + this.ip = ip; + this.prefixLength = prefixLength; + } + + /** + * Parses a CIDR string strictly according to Go {@code netip.ParsePrefix} semantics, preserving + * host bits and disallowing zone identifiers and IPv4-mapped IPv6 addresses. + */ + public static CelCidr parse(String raw) { + Objects.requireNonNull(raw, "raw"); + int slash = raw.lastIndexOf('/'); + if (slash < 0) { + throw new IllegalArgumentException( + "CIDR '" + raw + "' parse error during conversion from string: no '/'"); + } + String ipPart = raw.substring(0, slash); + String prefixPart = raw.substring(slash + 1); + + CelIp.ParsedIp parsed = CelIp.parseWithOptionalZone(ipPart, "CIDR", raw); + if (parsed.zone != null) { + throw new IllegalArgumentException("CIDR '" + raw + "' with zone value is not allowed"); + } + if (parsed.ip.is4In6()) { + throw new IllegalArgumentException("IPv4-mapped IPv6 address '" + raw + "' is not allowed"); + } + + int maxBits = parsed.ip.family() == 4L ? 32 : 128; + int prefixLen = parsePrefixLength(prefixPart, maxBits, raw); + return new CelCidr(parsed.ip, prefixLen); + } + + private static int parsePrefixLength(String prefixPart, int maxBits, String rawForError) { + if (prefixPart.isEmpty()) { + throw new IllegalArgumentException( + "CIDR '" + rawForError + "' parse error during conversion from string: empty prefix"); + } + if (prefixPart.length() > 1 && prefixPart.charAt(0) == '0') { + throw new IllegalArgumentException( + "CIDR '" + + rawForError + + "' parse error during conversion from string: prefix length has leading zero"); + } + if (prefixPart.length() > 3) { + throw new IllegalArgumentException( + "CIDR '" + + rawForError + + "' parse error during conversion from string: prefix length out of range"); + } + int value = 0; + for (int i = 0; i < prefixPart.length(); i++) { + char c = prefixPart.charAt(i); + if (c < '0' || c > '9') { + throw new IllegalArgumentException( + "CIDR '" + + rawForError + + "' parse error during conversion from string: invalid prefix length"); + } + value = value * 10 + (c - '0'); + } + if (value > maxBits) { + throw new IllegalArgumentException( + "CIDR '" + + rawForError + + "' parse error during conversion from string: prefix length out of range"); + } + return value; + } + + @Override + public CelCidr value() { + return this; + } + + @Override + public OpaqueType celType() { + return CIDR_TYPE; + } + + /** Returns the underlying {@link CelIp} address, preserving any unmasked host bits. */ + public CelIp ip() { + return ip; + } + + /** Returns the CIDR prefix length in bits. */ + public long prefixLength() { + return prefixLength; + } + + /** Returns a new {@link CelCidr} with host bits beyond {@link #prefixLength()} zeroed out. */ + public CelCidr masked() { + return new CelCidr(ip.mask(prefixLength), prefixLength); + } + + /** Returns true iff all host bits beyond {@link #prefixLength()} are zero. */ + public boolean isMask() { + return ip.equals(ip.mask(prefixLength)); + } + + /** Returns true iff {@code other} belongs to the network masked by this CIDR. */ + public boolean containsIp(CelIp other) { + Objects.requireNonNull(other, "other"); + return ip.matchesPrefix(other, prefixLength); + } + + /** Returns true iff this CIDR contains all addresses in {@code child}. */ + public boolean containsCidr(CelCidr child) { + Objects.requireNonNull(child, "child"); + return this.ip.family() == child.ip.family() + && this.prefixLength <= child.prefixLength + && this.containsIp(child.ip); + } + + /** Returns the canonical string form {@code "/"}. */ + public String toCanonicalString() { + return ip.toCanonicalString() + "/" + prefixLength; + } + + @Override + public String toString() { + return toCanonicalString(); + } + + @Override + public boolean equals(@Nullable Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof CelCidr)) { + return false; + } + CelCidr other = (CelCidr) obj; + return this.prefixLength == other.prefixLength && this.ip.equals(other.ip); + } + + @Override + public int hashCode() { + return Objects.hash(ip, prefixLength); + } +} diff --git a/extensions/src/main/java/dev/cel/extensions/CelIp.java b/extensions/src/main/java/dev/cel/extensions/CelIp.java new file mode 100644 index 000000000..2d5c7ab03 --- /dev/null +++ b/extensions/src/main/java/dev/cel/extensions/CelIp.java @@ -0,0 +1,462 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package dev.cel.extensions; + +import com.google.errorprone.annotations.CheckReturnValue; +import com.google.errorprone.annotations.Immutable; +import dev.cel.common.types.OpaqueType; +import dev.cel.common.values.OpaqueValue; +import java.util.Objects; +import org.jspecify.annotations.Nullable; + +/** Immutable CEL opaque value representing an IPv4 or IPv6 address ({@code net.IP}). */ +@Immutable +@CheckReturnValue +public final class CelIp extends OpaqueValue { + + /** CEL opaque type for {@code net.IP}. */ + public static final OpaqueType IP_TYPE = OpaqueType.create("net.IP"); + + private final byte family; + private final long hi; + private final long lo; + + private CelIp(byte family, long hi, long lo) { + this.family = family; + this.hi = hi; + this.lo = lo; + } + + /** + * Parses an IPv4 or IPv6 address string strictly according to Go {@code netip.ParseAddr} / RFC + * 4291 semantics, disallowing zone identifiers and IPv4-mapped IPv6 addresses. + */ + public static CelIp parse(String raw) { + Objects.requireNonNull(raw, "raw"); + ParsedIp parsed = parseWithOptionalZone(raw, "IP Address", raw); + if (parsed.zone != null) { + throw new IllegalArgumentException("IP address '" + raw + "' with zone value is not allowed"); + } + if (parsed.ip.is4In6()) { + throw new IllegalArgumentException("IPv4-mapped IPv6 address '" + raw + "' is not allowed"); + } + return parsed.ip; + } + + static ParsedIp parseWithOptionalZone(String raw, String errorPrefix, String rawForError) { + if (raw.isEmpty()) { + throw parseError(errorPrefix, rawForError, "unable to parse IP"); + } + if (raw.indexOf(':') >= 0) { + return parseIpv6WithOptionalZone(raw, errorPrefix, rawForError); + } + if (raw.indexOf('.') >= 0) { + int ipv4 = parseIpv4(raw, errorPrefix, rawForError); + return new ParsedIp(new CelIp((byte) 4, 0L, ipv4 & 0xFFFFFFFFL), null); + } + throw parseError(errorPrefix, rawForError, "unable to parse IP"); + } + + private static ParsedIp parseIpv6WithOptionalZone( + String raw, String errorPrefix, String rawForError) { + String ipPart = raw; + String zone = null; + int pctIdx = raw.indexOf('%'); + if (pctIdx >= 0) { + ipPart = raw.substring(0, pctIdx); + zone = raw.substring(pctIdx + 1); + if (zone.isEmpty()) { + throw parseError(errorPrefix, rawForError, "zone must be non-empty"); + } + } + CelIp ip = parseIpv6Body(ipPart, errorPrefix, rawForError); + return new ParsedIp(ip, zone); + } + + private static int parseIpv4(String s, String errorPrefix, String rawForError) { + int octet = 0; + int digits = 0; + int dotCount = 0; + int addr = 0; + int len = s.length(); + for (int i = 0; i < len; i++) { + char c = s.charAt(i); + if (c >= '0' && c <= '9') { + if (digits == 1 && octet == 0) { + throw parseError(errorPrefix, rawForError, "IPv4 field has octet with leading zero"); + } + octet = octet * 10 + (c - '0'); + digits++; + if (octet > 255) { + throw parseError(errorPrefix, rawForError, "IPv4 field has value >255"); + } + } else if (c == '.') { + if (digits == 0) { + throw parseError(errorPrefix, rawForError, "IPv4 field must have at least one digit"); + } + if (dotCount == 3) { + throw parseError(errorPrefix, rawForError, "IPv4 address too long"); + } + addr = (addr << 8) | octet; + octet = 0; + digits = 0; + dotCount++; + } else { + throw parseError(errorPrefix, rawForError, "unexpected character"); + } + } + if (dotCount != 3 || digits == 0) { + throw parseError(errorPrefix, rawForError, "IPv4 address too short"); + } + return (addr << 8) | octet; + } + + private static CelIp parseIpv6Body(String s, String errorPrefix, String rawForError) { + int len = s.length(); + if (len < 2) { + throw parseError(errorPrefix, rawForError, "address too short"); + } + + int[] hextets = new int[8]; + int count = 0; + int ellipsis = -1; + int i = 0; + + if (s.charAt(0) == ':') { + if (s.charAt(1) != ':') { + throw parseError(errorPrefix, rawForError, "each colon-separated field must have a digit"); + } + ellipsis = 0; + i = 2; + } + + while (i < len) { + int segStart = i; + int val = 0; + int hexDigits = 0; + boolean hitDot = false; + + while (i < len) { + char c = s.charAt(i); + int digit = hexValue(c); + if (digit >= 0) { + if (hexDigits == 4) { + throw parseError(errorPrefix, rawForError, "IPv6 field has too many digits"); + } + val = (val << 4) | digit; + hexDigits++; + i++; + } else if (c == ':') { + break; + } else if (c == '.') { + hitDot = true; + break; + } else { + throw parseError(errorPrefix, rawForError, "unexpected character"); + } + } + + if (hitDot) { + if (segStart == 0) { + throw parseError(errorPrefix, rawForError, "unexpected IPv4 prefix in IPv6 address"); + } + if (count > 6 || (ellipsis >= 0 && count >= 6)) { + throw parseError(errorPrefix, rawForError, "address too long"); + } + int v4 = parseIpv4(s.substring(segStart), errorPrefix, rawForError); + hextets[count++] = (v4 >>> 16) & 0xFFFF; + hextets[count++] = v4 & 0xFFFF; + i = len; + break; + } + + if (hexDigits == 0) { + // Encountered ':' immediately after consuming the previous ':' -> "::". + if (ellipsis >= 0) { + throw parseError(errorPrefix, rawForError, "multiple :: in IPv6 address"); + } + ellipsis = count; + i++; + continue; + } + + if (count >= 8) { + throw parseError(errorPrefix, rawForError, "address too long"); + } + hextets[count++] = val; + + if (i == len) { + break; + } + // Must be ':' because '.', invalid chars, and hex digits were handled above. + i++; + if (i == len) { + throw parseError(errorPrefix, rawForError, "trailing colon"); + } + } + + int[] full; + if (ellipsis < 0) { + if (count != 8) { + throw parseError(errorPrefix, rawForError, "address too short"); + } + full = hextets; + } else { + if (count >= 8) { + throw parseError(errorPrefix, rawForError, "address too long for :: compression"); + } + int zeros = 8 - count; + full = new int[8]; + for (int idx = 0; idx < ellipsis; idx++) { + full[idx] = hextets[idx]; + } + for (int idx = ellipsis; idx < count; idx++) { + full[idx + zeros] = hextets[idx]; + } + } + + long hiVal = + ((long) full[0] << 48) + | ((long) full[1] << 32) + | ((long) full[2] << 16) + | (full[3] & 0xFFFFL); + long loVal = + ((long) full[4] << 48) + | ((long) full[5] << 32) + | ((long) full[6] << 16) + | (full[7] & 0xFFFFL); + return new CelIp((byte) 6, hiVal, loVal); + } + + private static int hexValue(char c) { + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'a' && c <= 'f') { + return 10 + (c - 'a'); + } + if (c >= 'A' && c <= 'F') { + return 10 + (c - 'A'); + } + return -1; + } + + private static IllegalArgumentException parseError( + String errorPrefix, String raw, String detail) { + return new IllegalArgumentException( + errorPrefix + " '" + raw + "' parse error during conversion from string: " + detail); + } + + boolean is4In6() { + return family == 6 && hi == 0L && (lo >>> 32) == 0xFFFFL; + } + + @Override + public CelIp value() { + return this; + } + + @Override + public OpaqueType celType() { + return IP_TYPE; + } + + /** Returns the IP address family: {@code 4} for IPv4 or {@code 6} for IPv6. */ + public long family() { + return family; + } + + /** Returns true if the IP address is unspecified ({@code 0.0.0.0} or {@code ::}). */ + public boolean isUnspecified() { + if (family == 4) { + return lo == 0L; + } + return hi == 0L && lo == 0L; + } + + /** Returns true if the IP address is a loopback address ({@code 127.0.0.0/8} or {@code ::1}). */ + public boolean isLoopback() { + if (family == 4) { + return ((lo >>> 24) & 0xFFL) == 127L; + } + return hi == 0L && lo == 1L; + } + + /** Returns true if the IP address is a link-local unicast address. */ + public boolean isLinkLocalUnicast() { + if (family == 4) { + return ((lo >>> 24) & 0xFFL) == 169L && ((lo >>> 16) & 0xFFL) == 254L; + } + return ((hi >>> 56) & 0xFFL) == 0xFEL && ((hi >>> 48) & 0xC0L) == 0x80L; + } + + /** Returns true if the IP address is a link-local multicast address. */ + public boolean isLinkLocalMulticast() { + if (family == 4) { + return ((lo >>> 24) & 0xFFL) == 224L + && ((lo >>> 16) & 0xFFL) == 0L + && ((lo >>> 8) & 0xFFL) == 0L; + } + return ((hi >>> 56) & 0xFFL) == 0xFFL && ((hi >>> 48) & 0x0FL) == 0x02L; + } + + private boolean isMulticast() { + if (family == 4) { + return ((lo >>> 24) & 0xF0L) == 0xE0L; + } + return ((hi >>> 56) & 0xFFL) == 0xFFL; + } + + /** Returns true if the IP address is a global unicast address per Go {@code netip} semantics. */ + public boolean isGlobalUnicast() { + if (family == 4 && lo == 0xFFFFFFFFL) { + return false; + } + return !isUnspecified() && !isLoopback() && !isMulticast() && !isLinkLocalUnicast(); + } + + CelIp mask(int prefixLength) { + if (family == 4) { + long v4Mask = prefixLength == 0 ? 0L : (0xFFFFFFFFL << (32 - prefixLength)) & 0xFFFFFFFFL; + return new CelIp((byte) 4, 0L, lo & v4Mask); + } + long hiMask = ipv6HiMask(prefixLength); + long loMask = ipv6LoMask(prefixLength); + return new CelIp((byte) 6, hi & hiMask, lo & loMask); + } + + boolean matchesPrefix(CelIp other, int prefixLength) { + if (this.family != other.family) { + return false; + } + if (family == 4) { + long v4Mask = prefixLength == 0 ? 0L : (0xFFFFFFFFL << (32 - prefixLength)) & 0xFFFFFFFFL; + return ((this.lo ^ other.lo) & v4Mask) == 0L; + } + long hiMask = ipv6HiMask(prefixLength); + long loMask = ipv6LoMask(prefixLength); + return ((this.hi ^ other.hi) & hiMask) == 0L && ((this.lo ^ other.lo) & loMask) == 0L; + } + + private static long ipv6HiMask(int prefixLength) { + if (prefixLength == 0) { + return 0L; + } + if (prefixLength < 64) { + return -1L << (64 - prefixLength); + } + return -1L; + } + + private static long ipv6LoMask(int prefixLength) { + if (prefixLength <= 64) { + return 0L; + } + if (prefixLength < 128) { + return -1L << (128 - prefixLength); + } + return -1L; + } + + /** Returns the canonical string form of this IP address (RFC 5952 for IPv6). */ + public String toCanonicalString() { + if (family == 4) { + return ((lo >>> 24) & 0xFFL) + + "." + + ((lo >>> 16) & 0xFFL) + + "." + + ((lo >>> 8) & 0xFFL) + + "." + + (lo & 0xFFL); + } + int[] h = { + (int) ((hi >>> 48) & 0xFFFFL), + (int) ((hi >>> 32) & 0xFFFFL), + (int) ((hi >>> 16) & 0xFFFFL), + (int) (hi & 0xFFFFL), + (int) ((lo >>> 48) & 0xFFFFL), + (int) ((lo >>> 32) & 0xFFFFL), + (int) ((lo >>> 16) & 0xFFFFL), + (int) (lo & 0xFFFFL), + }; + int bestStart = -1; + int bestLen = 0; + int curStart = -1; + int curLen = 0; + for (int i = 0; i < 8; i++) { + if (h[i] == 0) { + if (curStart < 0) { + curStart = i; + curLen = 1; + } else { + curLen++; + } + if (curLen > bestLen && curLen >= 2) { + bestStart = curStart; + bestLen = curLen; + } + } else { + curStart = -1; + curLen = 0; + } + } + + StringBuilder sb = new StringBuilder(39); + for (int i = 0; i < 8; i++) { + if (i == bestStart) { + sb.append("::"); + i += bestLen - 1; + continue; + } + if (i > 0 && !(bestStart >= 0 && i == bestStart + bestLen)) { + sb.append(':'); + } + sb.append(Integer.toHexString(h[i])); + } + return sb.toString(); + } + + @Override + public String toString() { + return toCanonicalString(); + } + + @Override + public boolean equals(@Nullable Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof CelIp)) { + return false; + } + CelIp other = (CelIp) obj; + return this.family == other.family && this.hi == other.hi && this.lo == other.lo; + } + + @Override + public int hashCode() { + return Objects.hash(family, hi, lo); + } + + static final class ParsedIp { + final CelIp ip; + final @Nullable String zone; + + ParsedIp(CelIp ip, @Nullable String zone) { + this.ip = ip; + this.zone = zone; + } + } +} diff --git a/extensions/src/test/java/dev/cel/extensions/BUILD.bazel b/extensions/src/test/java/dev/cel/extensions/BUILD.bazel index 99d40146c..d56330a44 100644 --- a/extensions/src/test/java/dev/cel/extensions/BUILD.bazel +++ b/extensions/src/test/java/dev/cel/extensions/BUILD.bazel @@ -27,6 +27,7 @@ java_library( "//common/exceptions:index_out_of_bounds", "//common/exceptions:invalid_argument", "//common/types", + "//common/types:default_type_provider", "//common/types:message_type_provider", "//common/types:type_providers", "//common/values", @@ -49,6 +50,7 @@ java_library( "//extensions:math_compiler_library", "//extensions:math_runtime_library", "//extensions:native", + "//extensions:network_types", "//extensions:optional_compiler_library", "//extensions:optional_library", "//extensions:optional_runtime_library", @@ -85,6 +87,7 @@ java_library( "@cel_conformance//proto/cel/expr/conformance/test:simple_java_proto", "@maven//:com_google_errorprone_error_prone_annotations", "@maven//:com_google_guava_guava", + "@maven//:com_google_guava_guava_testlib", "@maven//:com_google_protobuf_protobuf_java", # unuseddeps: keep "@maven//:com_google_testparameterinjector_test_parameter_injector", "@maven//:junit_junit", diff --git a/extensions/src/test/java/dev/cel/extensions/CelNetworkTypesTest.java b/extensions/src/test/java/dev/cel/extensions/CelNetworkTypesTest.java new file mode 100644 index 000000000..5fb0d31f6 --- /dev/null +++ b/extensions/src/test/java/dev/cel/extensions/CelNetworkTypesTest.java @@ -0,0 +1,289 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package dev.cel.extensions; + +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; + +import com.google.common.testing.EqualsTester; +import com.google.testing.junit.testparameterinjector.TestParameterInjector; +import com.google.testing.junit.testparameterinjector.TestParameters; +import dev.cel.common.types.DefaultTypeProvider; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(TestParameterInjector.class) +public final class CelNetworkTypesTest { + + @Test + public void defaultTypeProvider_registersNetworkOpaqueTypes() { + DefaultTypeProvider provider = DefaultTypeProvider.getInstance(); + assertThat(provider.findType("net.IP")).hasValue(CelIp.IP_TYPE); + assertThat(provider.findType("net.CIDR")).hasValue(CelCidr.CIDR_TYPE); + assertThat(provider.types()).containsAtLeast(CelIp.IP_TYPE, CelCidr.CIDR_TYPE); + assertThat(provider.findType("net.Unknown")).isEmpty(); + } + + @Test + public void nullContracts_throwNullPointerException() { + assertThrows(NullPointerException.class, () -> CelIp.parse(null)); + assertThrows(NullPointerException.class, () -> CelCidr.parse(null)); + + CelCidr cidr = CelCidr.parse("10.0.0.0/8"); + assertThrows(NullPointerException.class, () -> cidr.containsIp(null)); + assertThrows(NullPointerException.class, () -> cidr.containsCidr(null)); + } + + @Test + public void celIp_opaqueValueAndFormatting() { + CelIp ipv4 = CelIp.parse("192.168.1.42"); + assertThat(ipv4.value()).isSameInstanceAs(ipv4); + assertThat(ipv4.celType()).isEqualTo(CelIp.IP_TYPE); + assertThat(ipv4.family()).isEqualTo(4L); + assertThat(ipv4.toCanonicalString()).isEqualTo("192.168.1.42"); + assertThat(ipv4.toString()).isEqualTo("192.168.1.42"); + + CelIp ipv6 = CelIp.parse("2001:0DB8:0:0:1:0:0:1"); + assertThat(ipv6.value()).isSameInstanceAs(ipv6); + assertThat(ipv6.celType()).isEqualTo(CelIp.IP_TYPE); + assertThat(ipv6.family()).isEqualTo(6L); + // RFC 5952: leftmost tie-break for equal-length zero runs, lowercase hex, no leading zeros. + assertThat(ipv6.toCanonicalString()).isEqualTo("2001:db8::1:0:0:1"); + assertThat(ipv6.toString()).isEqualTo("2001:db8::1:0:0:1"); + } + + @Test + @TestParameters("{raw: '0.0.0.0', canonical: '0.0.0.0'}") + @TestParameters("{raw: '255.255.255.255', canonical: '255.255.255.255'}") + @TestParameters("{raw: '::', canonical: '::'}") + @TestParameters("{raw: '::1', canonical: '::1'}") + @TestParameters("{raw: '2001:db8::', canonical: '2001:db8::'}") + @TestParameters("{raw: '1:2:3:4:5:6:7:8', canonical: '1:2:3:4:5:6:7:8'}") + @TestParameters("{raw: '2001:db8:0:1:1:1:1:1', canonical: '2001:db8:0:1:1:1:1:1'}") + @TestParameters("{raw: '2001:0:0:1:0:0:0:1', canonical: '2001:0:0:1::1'}") + @TestParameters("{raw: '2001:db8:abcd:ABCD::09af:AF', canonical: '2001:db8:abcd:abcd::9af:af'}") + @TestParameters("{raw: '::192.168.0.1', canonical: '::c0a8:1'}") + @TestParameters("{raw: '64:ff9b::192.0.2.1', canonical: '64:ff9b::c000:201'}") + @TestParameters("{raw: '1:2:3:4:5:6:192.168.0.1', canonical: '1:2:3:4:5:6:c0a8:1'}") + @TestParameters("{raw: '::fffe:192.168.0.1', canonical: '::fffe:c0a8:1'}") + @TestParameters("{raw: '1::ffff:192.168.0.1', canonical: '1::ffff:c0a8:1'}") + public void celIp_parseValidAndCanonicalize(String raw, String canonical) { + CelIp ip = CelIp.parse(raw); + assertThat(ip.toCanonicalString()).isEqualTo(canonical); + assertThat(ip.toString()).isEqualTo(canonical); + } + + @Test + @TestParameters("{raw: '', errSubstr: 'unable to parse IP'}") + @TestParameters("{raw: 'not-an-ip', errSubstr: 'unable to parse IP'}") + @TestParameters("{raw: '01.2.3.4', errSubstr: 'leading zero'}") + @TestParameters("{raw: '256.0.0.1', errSubstr: '>255'}") + @TestParameters("{raw: '999.999.999.999', errSubstr: '>255'}") + @TestParameters("{raw: '.1.2.3', errSubstr: 'at least one digit'}") + @TestParameters("{raw: '1..2.3.4', errSubstr: 'at least one digit'}") + @TestParameters("{raw: '1.2.3.4.5', errSubstr: 'too long'}") + @TestParameters("{raw: '1.2.3.a', errSubstr: 'unexpected character'}") + @TestParameters("{raw: '1.2.3.-1', errSubstr: 'unexpected character'}") + @TestParameters("{raw: '1.2.3', errSubstr: 'too short'}") + @TestParameters("{raw: '1.2.3.', errSubstr: 'too short'}") + @TestParameters("{raw: '1.2.3.4:80', errSubstr: 'unexpected IPv4 prefix'}") + @TestParameters("{raw: ':', errSubstr: 'address too short'}") + @TestParameters("{raw: ':1:2:3:4:5:6:7', errSubstr: 'must have a digit'}") + @TestParameters("{raw: '20011::1', errSubstr: 'too many digits'}") + @TestParameters("{raw: '0:0:0:0:0:ffff:0:00000', errSubstr: 'too many digits'}") + @TestParameters("{raw: '2001:db8::!', errSubstr: 'unexpected character'}") + @TestParameters("{raw: '2001:db8::@', errSubstr: 'unexpected character'}") + @TestParameters("{raw: '2001:db8::G', errSubstr: 'unexpected character'}") + @TestParameters("{raw: '2001:db8::g', errSubstr: 'unexpected character'}") + @TestParameters("{raw: '2001:db8::/', errSubstr: 'unexpected character'}") + @TestParameters("{raw: 'gggg::1%en0', errSubstr: 'unexpected character'}") + @TestParameters("{raw: 'fe80::1%', errSubstr: 'zone must be non-empty'}") + @TestParameters("{raw: 'fe80::1%en0', errSubstr: 'with zone value is not allowed'}") + @TestParameters("{raw: '::ffff:192.168.0.1', errSubstr: 'IPv4-mapped IPv6 address'}") + @TestParameters("{raw: '::ffff:c0a8:1', errSubstr: 'IPv4-mapped IPv6 address'}") + @TestParameters("{raw: '::ffff:192.168.0.1%en0', errSubstr: 'with zone value is not allowed'}") + @TestParameters("{raw: '1:2:3:4:5:6:7:1.2.3.4', errSubstr: 'address too long'}") + @TestParameters("{raw: '1:2:3:4:5:6::1.2.3.4', errSubstr: 'address too long'}") + @TestParameters("{raw: '1:2:3:4:5:192.168.0.1', errSubstr: 'address too short'}") + @TestParameters("{raw: '2001::db8::1', errSubstr: 'multiple ::'}") + @TestParameters("{raw: ':::', errSubstr: 'multiple ::'}") + @TestParameters("{raw: '1:2:3:4:5:6:7:8:9', errSubstr: 'address too long'}") + @TestParameters("{raw: '2001:db8:1:', errSubstr: 'trailing colon'}") + @TestParameters("{raw: '1:2:3:4:5:6:7', errSubstr: 'address too short'}") + @TestParameters("{raw: '::1:2:3:4:5:6:7:8', errSubstr: 'too long for :: compression'}") + @TestParameters("{raw: '1:2:3:4::5:6:7:8', errSubstr: 'too long for :: compression'}") + public void celIp_parseInvalid_throwsIllegalArgumentException(String raw, String errSubstr) { + IllegalArgumentException e = + assertThrows(IllegalArgumentException.class, () -> CelIp.parse(raw)); + assertThat(e).hasMessageThat().contains(errSubstr); + } + + @Test + public void celIp_predicatesCoverAllBranches() { + assertThat(CelIp.parse("0.0.0.0").isUnspecified()).isTrue(); + assertThat(CelIp.parse("0.0.0.1").isUnspecified()).isFalse(); + assertThat(CelIp.parse("::").isUnspecified()).isTrue(); + assertThat(CelIp.parse("::1").isUnspecified()).isFalse(); + assertThat(CelIp.parse("2001:db8::").isUnspecified()).isFalse(); + + assertThat(CelIp.parse("127.0.0.1").isLoopback()).isTrue(); + assertThat(CelIp.parse("127.255.255.254").isLoopback()).isTrue(); + assertThat(CelIp.parse("128.0.0.1").isLoopback()).isFalse(); + assertThat(CelIp.parse("::1").isLoopback()).isTrue(); + assertThat(CelIp.parse("::2").isLoopback()).isFalse(); + assertThat(CelIp.parse("2001:db8::1").isLoopback()).isFalse(); + + assertThat(CelIp.parse("169.254.1.1").isLinkLocalUnicast()).isTrue(); + assertThat(CelIp.parse("169.255.0.1").isLinkLocalUnicast()).isFalse(); + assertThat(CelIp.parse("192.168.0.1").isLinkLocalUnicast()).isFalse(); + assertThat(CelIp.parse("fe80::1").isLinkLocalUnicast()).isTrue(); + assertThat(CelIp.parse("febf::1").isLinkLocalUnicast()).isTrue(); + assertThat(CelIp.parse("fe00::1").isLinkLocalUnicast()).isFalse(); + assertThat(CelIp.parse("fec0::1").isLinkLocalUnicast()).isFalse(); + assertThat(CelIp.parse("fd00::1").isLinkLocalUnicast()).isFalse(); + + assertThat(CelIp.parse("224.0.0.1").isLinkLocalMulticast()).isTrue(); + assertThat(CelIp.parse("224.0.1.1").isLinkLocalMulticast()).isFalse(); + assertThat(CelIp.parse("224.1.0.1").isLinkLocalMulticast()).isFalse(); + assertThat(CelIp.parse("239.0.0.1").isLinkLocalMulticast()).isFalse(); + assertThat(CelIp.parse("ff02::1").isLinkLocalMulticast()).isTrue(); + assertThat(CelIp.parse("ff12::1").isLinkLocalMulticast()).isTrue(); + assertThat(CelIp.parse("ff05::1").isLinkLocalMulticast()).isFalse(); + assertThat(CelIp.parse("fe80::1").isLinkLocalMulticast()).isFalse(); + + assertThat(CelIp.parse("255.255.255.255").isGlobalUnicast()).isFalse(); + assertThat(CelIp.parse("0.0.0.0").isGlobalUnicast()).isFalse(); + assertThat(CelIp.parse("127.0.0.1").isGlobalUnicast()).isFalse(); + assertThat(CelIp.parse("224.0.0.1").isGlobalUnicast()).isFalse(); + assertThat(CelIp.parse("239.255.255.255").isGlobalUnicast()).isFalse(); + assertThat(CelIp.parse("169.254.0.1").isGlobalUnicast()).isFalse(); + assertThat(CelIp.parse("192.168.1.1").isGlobalUnicast()).isTrue(); + assertThat(CelIp.parse("::").isGlobalUnicast()).isFalse(); + assertThat(CelIp.parse("::1").isGlobalUnicast()).isFalse(); + assertThat(CelIp.parse("ff00::1").isGlobalUnicast()).isFalse(); + assertThat(CelIp.parse("fe80::1").isGlobalUnicast()).isFalse(); + assertThat(CelIp.parse("::ffff:ffff").isGlobalUnicast()).isTrue(); + assertThat(CelIp.parse("2001:db8::1").isGlobalUnicast()).isTrue(); + } + + @Test + public void celCidr_opaqueValueMaskingAndContainment() { + CelCidr v4 = CelCidr.parse("192.168.1.5/24"); + assertThat(v4.value()).isSameInstanceAs(v4); + assertThat(v4.celType()).isEqualTo(CelCidr.CIDR_TYPE); + assertThat(v4.ip()).isEqualTo(CelIp.parse("192.168.1.5")); + assertThat(v4.prefixLength()).isEqualTo(24L); + assertThat(v4.isMask()).isFalse(); + assertThat(v4.toCanonicalString()).isEqualTo("192.168.1.5/24"); + assertThat(v4.toString()).isEqualTo("192.168.1.5/24"); + + CelCidr v4Masked = v4.masked(); + assertThat(v4Masked).isEqualTo(CelCidr.parse("192.168.1.0/24")); + assertThat(v4Masked.isMask()).isTrue(); + assertThat(CelCidr.parse("192.168.1.5/0").masked()).isEqualTo(CelCidr.parse("0.0.0.0/0")); + assertThat(CelCidr.parse("192.168.1.5/32").masked()).isEqualTo(CelCidr.parse("192.168.1.5/32")); + + // IPv4 /0 vs IPv6 containment + CelCidr v4Zero = CelCidr.parse("0.0.0.0/0"); + assertThat(v4Zero.containsIp(CelIp.parse("192.168.1.1"))).isTrue(); + assertThat(v4Zero.containsIp(CelIp.parse("::1"))).isFalse(); + + // IPv6 masking across /0, /32 (<64), /64, /96 and /112 (65..127), and /128 + assertThat(CelCidr.parse("2001:db8::1/0").masked()).isEqualTo(CelCidr.parse("::/0")); + assertThat(CelCidr.parse("2001:db8:abcd::1/32").masked()) + .isEqualTo(CelCidr.parse("2001:db8::/32")); + assertThat(CelCidr.parse("2001:db8:1:2:3:4:5:6/64").masked()) + .isEqualTo(CelCidr.parse("2001:db8:1:2::/64")); + assertThat(CelCidr.parse("2001:db8::1234:dead:beef/96").masked()) + .isEqualTo(CelCidr.parse("2001:db8::1234:0:0/96")); + assertThat(CelCidr.parse("2001:db8::dead:beef/112").masked()) + .isEqualTo(CelCidr.parse("2001:db8::dead:0/112")); + assertThat(CelCidr.parse("2001:db8::dead:beef/128").masked()) + .isEqualTo(CelCidr.parse("2001:db8::dead:beef/128")); + + // IPv6 /112 containment: hi match + lo match vs hi match + lo mismatch vs hi mismatch + CelCidr v6Slash112 = CelCidr.parse("2001:db8::dead:0/112"); + assertThat(v6Slash112.containsIp(CelIp.parse("2001:db8::dead:beef"))).isTrue(); + assertThat(v6Slash112.containsIp(CelIp.parse("2001:db8::beef:0"))).isFalse(); + assertThat(v6Slash112.containsIp(CelIp.parse("2001:db9::dead:0"))).isFalse(); + + // containsCidr branches: cross-family, narrower parent, disjoint, equal, and unmasked parent + assertThat(v4Zero.containsCidr(CelCidr.parse("::/0"))).isFalse(); + assertThat(CelCidr.parse("10.0.0.0/16").containsCidr(CelCidr.parse("10.0.0.0/8"))).isFalse(); + assertThat(CelCidr.parse("10.0.0.0/8").containsCidr(CelCidr.parse("11.0.0.0/16"))).isFalse(); + assertThat(CelCidr.parse("10.0.0.5/8").containsCidr(CelCidr.parse("10.1.2.0/24"))).isTrue(); + } + + @Test + @TestParameters("{raw: '1.2.3.4', errSubstr: \"no '/'\"}") + @TestParameters("{raw: 'invalid/24', errSubstr: 'unable to parse IP'}") + @TestParameters("{raw: '/24', errSubstr: 'unable to parse IP'}") + @TestParameters("{raw: '999.0.0.1/24', errSubstr: '>255'}") + @TestParameters("{raw: '10.0.0.0/8/16', errSubstr: 'unexpected character'}") + @TestParameters("{raw: 'fe80::1%/64', errSubstr: 'zone must be non-empty'}") + @TestParameters("{raw: 'fe80::1%en0/64', errSubstr: 'with zone value is not allowed'}") + @TestParameters("{raw: 'fe80::1%en0/999', errSubstr: 'with zone value is not allowed'}") + @TestParameters("{raw: '::ffff:192.168.0.1/24', errSubstr: 'IPv4-mapped IPv6 address'}") + @TestParameters("{raw: '::ffff:192.168.0.1/999', errSubstr: 'IPv4-mapped IPv6 address'}") + @TestParameters("{raw: '192.168.0.0/', errSubstr: 'empty prefix'}") + @TestParameters("{raw: '2001:db8::/', errSubstr: 'empty prefix'}") + @TestParameters("{raw: '10.0.0.0/08', errSubstr: 'leading zero'}") + @TestParameters("{raw: '10.0.0.0/00', errSubstr: 'leading zero'}") + @TestParameters("{raw: '10.0.0.0/1000', errSubstr: 'out of range'}") + @TestParameters("{raw: 'fe80::1/64%en0', errSubstr: 'out of range'}") + @TestParameters("{raw: '10.0.0.0/-1', errSubstr: 'invalid prefix length'}") + @TestParameters("{raw: '10.0.0.0/2a', errSubstr: 'invalid prefix length'}") + @TestParameters("{raw: '10.0.0.0/33', errSubstr: 'out of range'}") + @TestParameters("{raw: '2001:db8::/129', errSubstr: 'out of range'}") + public void celCidr_parseInvalid_throwsSinglePrefixedIllegalArgumentException( + String raw, String errSubstr) { + IllegalArgumentException e = + assertThrows(IllegalArgumentException.class, () -> CelCidr.parse(raw)); + assertThat(e).hasMessageThat().contains(errSubstr); + // Verify no double "CIDR '...'" error prefix wrapping on invalid IP portions. + String msg = e.getMessage(); + int firstIdx = msg.indexOf("parse error during conversion from string:"); + if (firstIdx >= 0) { + assertThat(msg.indexOf("parse error during conversion from string:", firstIdx + 1)) + .isEqualTo(-1); + assertThat(msg).startsWith("CIDR '" + raw + "' parse error during conversion from string:"); + } + } + + @Test + public void equalsAndHashCode() { + new EqualsTester() + .addEqualityGroup(CelIp.parse("0.0.0.0")) + .addEqualityGroup(CelIp.parse("::"), CelIp.parse("0:0:0:0:0:0:0:0")) + .addEqualityGroup(CelIp.parse("0.0.0.1")) + .addEqualityGroup(CelIp.parse("::1"), CelIp.parse("0:0:0:0:0:0:0:1")) + .addEqualityGroup( + CelIp.parse("2001:db8::1"), + CelIp.parse("2001:DB8::1"), + CelIp.parse("2001:0db8:0:0:0:0:0:1")) + .addEqualityGroup(CelIp.parse("2001:db8::2")) + .addEqualityGroup(CelIp.parse("2001:db9::1")) + .addEqualityGroup(CelCidr.parse("0.0.0.0/0")) + .addEqualityGroup(CelCidr.parse("::/0"), CelCidr.parse("0:0:0:0:0:0:0:0/0")) + .addEqualityGroup(CelCidr.parse("10.0.0.0/8")) + .addEqualityGroup(CelCidr.parse("10.0.0.0/16")) + .addEqualityGroup(CelCidr.parse("10.0.0.1/8")) + .addEqualityGroup( + CelCidr.parse("2001:db8::/32"), + CelCidr.parse("2001:DB8::/32"), + CelCidr.parse("2001:0db8:0:0:0:0:0:0/32")) + .testEquals(); + } +}