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..370807151 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,10 @@ 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")); 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..62ab1525e 100644 --- a/extensions/src/main/java/dev/cel/extensions/BUILD.bazel +++ b/extensions/src/main/java/dev/cel/extensions/BUILD.bazel @@ -599,6 +599,32 @@ cel_android_library( ], ) +java_library( + name = "network_types", + srcs = ["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 = ["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/CelIp.java b/extensions/src/main/java/dev/cel/extensions/CelIp.java new file mode 100644 index 000000000..64e0f13ea --- /dev/null +++ b/extensions/src/main/java/dev/cel/extensions/CelIp.java @@ -0,0 +1,417 @@ +// 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"); + + static final byte IPV4_FAMILY = 4; + static final byte IPV6_FAMILY = 6; + static final int IPV4_BITS = 32; + static final int IPV6_BITS = 128; + + private static final int IPV6_HEXTET_COUNT = 8; + private static final int MAX_IPV6_STRING_LENGTH = 39; + + 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 ASCII IPv4 dotted-quad or RFC 4291 IPv6 address string. + * + *

Leading zeros in IPv4 octets, IPv6 zone identifiers ({@code %zone}), and IPv4-mapped IPv6 + * addresses ({@code ::ffff:x.x.x.x}) are rejected, matching CEL {@code net.IP} and Go {@code + * netip.ParseAddr} semantics. + * + * @throws IllegalArgumentException if {@code raw} is not a valid IPv4 or IPv6 literal, contains a + * zone identifier, or is an IPv4-mapped IPv6 address + */ + public static CelIp parse(String 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.indexOf(':') >= 0) { + return parseIpv6WithOptionalZone(raw, errorPrefix, rawForError); + } + if (raw.indexOf('.') >= 0) { + long ipv4 = parseIpv4(raw, errorPrefix, rawForError); + return new ParsedIp(new CelIp(IPV4_FAMILY, 0L, ipv4), 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 long parseIpv4(String s, String errorPrefix, String rawForError) { + int octet = 0; + int digits = 0; + int dotCount = 0; + long 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[IPV6_HEXTET_COUNT]; + int count = 0; + boolean hasEllipsis = false; + int ellipsisIndex = 0; + int i = 0; + + if (s.charAt(0) == ':') { + if (s.charAt(1) != ':') { + throw parseError(errorPrefix, rawForError, "each colon-separated field must have a digit"); + } + hasEllipsis = true; + 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; + if (c >= '0' && c <= '9') { + digit = c - '0'; + } else if (c >= 'a' && c <= 'f') { + digit = 10 + (c - 'a'); + } else if (c >= 'A' && c <= 'F') { + digit = 10 + (c - 'A'); + } else if (c == ':') { + break; + } else if (c == '.') { + hitDot = true; + break; + } else { + throw parseError(errorPrefix, rawForError, "unexpected character"); + } + if (hexDigits == 4) { + throw parseError(errorPrefix, rawForError, "IPv6 field has too many digits"); + } + val = (val << 4) | digit; + hexDigits++; + i++; + } + + if (hitDot) { + if (segStart == 0) { + throw parseError(errorPrefix, rawForError, "unexpected IPv4 prefix in IPv6 address"); + } + if (count > 6 || (hasEllipsis && count >= 6)) { + throw parseError(errorPrefix, rawForError, "address too long"); + } + long v4 = parseIpv4(s.substring(segStart), errorPrefix, rawForError); + hextets[count++] = (int) ((v4 >>> 16) & 0xFFFFL); + hextets[count++] = (int) (v4 & 0xFFFFL); + break; + } + + if (hexDigits == 0) { + if (hasEllipsis) { + throw parseError(errorPrefix, rawForError, "multiple :: in IPv6 address"); + } + hasEllipsis = true; + ellipsisIndex = count; + i++; + continue; + } + + if (count >= IPV6_HEXTET_COUNT) { + throw parseError(errorPrefix, rawForError, "address too long"); + } + hextets[count++] = val; + + if (i == len - 1) { + throw parseError(errorPrefix, rawForError, "trailing colon"); + } + i++; + } + + int[] full; + if (!hasEllipsis) { + if (count != IPV6_HEXTET_COUNT) { + throw parseError(errorPrefix, rawForError, "address too short"); + } + full = hextets; + } else { + if (count >= IPV6_HEXTET_COUNT) { + throw parseError(errorPrefix, rawForError, "address too long for :: compression"); + } + int zeros = IPV6_HEXTET_COUNT - count; + full = new int[IPV6_HEXTET_COUNT]; + System.arraycopy(hextets, 0, full, 0, ellipsisIndex); + System.arraycopy(hextets, ellipsisIndex, full, ellipsisIndex + zeros, count - ellipsisIndex); + } + + 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(IPV6_FAMILY, hiVal, loVal); + } + + private static IllegalArgumentException parseError( + String errorPrefix, String raw, String detail) { + return new IllegalArgumentException( + errorPrefix + " '" + raw + "' parse error during conversion from string: " + detail); + } + + @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() { + 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 == IPV4_FAMILY) { + return (lo >>> 24) == 127L; + } + return hi == 0L && lo == 1L; + } + + /** + * Returns true if the IP address is a link-local unicast address ({@code 169.254.0.0/16} or + * {@code fe80::/10}). + */ + public boolean isLinkLocalUnicast() { + if (family == IPV4_FAMILY) { + return (lo >>> 24) == 169L && ((lo >>> 16) & 0xFFL) == 254L; + } + return (hi >>> 56) == 0xFEL && ((hi >>> 48) & 0xC0L) == 0x80L; + } + + /** + * Returns true if the IP address is a link-local multicast address ({@code 224.0.0.0/24} or + * {@code ffX2::/16}, multicast scope {@code 0x2}). + */ + public boolean isLinkLocalMulticast() { + if (family == IPV4_FAMILY) { + return (lo >>> 24) == 224L && ((lo >>> 16) & 0xFFL) == 0L && ((lo >>> 8) & 0xFFL) == 0L; + } + return (hi >>> 56) == 0xFFL && ((hi >>> 48) & 0x0FL) == 0x02L; + } + + /** + * Returns true if the IP address is a global unicast address (neither unspecified, loopback, + * multicast, link-local unicast, nor the IPv4 limited broadcast {@code 255.255.255.255}). + */ + public boolean isGlobalUnicast() { + // Exclude IPv4 limited broadcast 255.255.255.255 per Go netip.Addr.IsGlobalUnicast. + if (family == IPV4_FAMILY && lo == 0xFFFFFFFFL) { + return false; + } + return !isUnspecified() && !isLoopback() && !isMulticast() && !isLinkLocalUnicast(); + } + + /** Returns the canonical string form of this IP address (RFC 5952 for IPv6). */ + public String toCanonicalString() { + if (family == IPV4_FAMILY) { + return ((lo >>> 24) & 0xFFL) + + "." + + ((lo >>> 16) & 0xFFL) + + "." + + ((lo >>> 8) & 0xFFL) + + "." + + (lo & 0xFFL); + } + int[] hextets = { + (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), + }; + // Initialize [bestStart, bestEnd) to width 1 so strictly '>' only matches runs of >= 2 zero + // hextets (RFC 5952 section 4.2.2) and breaks ties in favor of the leftmost run (RFC 5952 + // section 4.2.3). + int bestStart = 0; + int bestEnd = 1; + int curLen = 0; + for (int i = 0; i < IPV6_HEXTET_COUNT; i++) { + if (hextets[i] == 0) { + curLen++; + if (curLen > bestEnd - bestStart) { + bestStart = i - curLen + 1; + bestEnd = i + 1; + } + } else { + curLen = 0; + } + } + + boolean compress = bestEnd > 1; + StringBuilder sb = new StringBuilder(MAX_IPV6_STRING_LENGTH); + for (int i = 0; i < IPV6_HEXTET_COUNT; i++) { + if (compress && i == bestStart) { + sb.append("::"); + i = bestEnd - 1; + continue; + } + // Skip leading ':' right after "::" since "::" already includes the separator. + if (i > 0 && !(compress && i == bestEnd)) { + sb.append(':'); + } + sb.append(Integer.toHexString(hextets[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); + } + + boolean is4In6() { + return hi == 0L && (lo >>> 32) == 0xFFFFL; + } + + // Multicast: 224.0.0.0/4 for IPv4 or ff00::/8 for IPv6. + private boolean isMulticast() { + if (family == IPV4_FAMILY) { + return ((lo >>> 24) & 0xF0L) == 0xE0L; + } + return (hi >>> 56) == 0xFFL; + } + + 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..2b5d790c0 --- /dev/null +++ b/extensions/src/test/java/dev/cel/extensions/CelNetworkTypesTest.java @@ -0,0 +1,216 @@ +// 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.types()).contains(CelIp.IP_TYPE); + assertThat(provider.findType("net.Unknown")).isEmpty(); + } + + @Test + public void nullContracts_throwNullPointerException() { + assertThrows(NullPointerException.class, () -> CelIp.parse(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: '0.9.0.9', canonical: '0.9.0.9'}") + @TestParameters("{raw: '255.255.255.255', canonical: '255.255.255.255'}") + @TestParameters("{raw: '::', canonical: '::'}") + @TestParameters("{raw: '::1', canonical: '::1'}") + @TestParameters("{raw: '0:0:2:3:4:5:6:7', canonical: '::2:3:4:5:6:7'}") + @TestParameters("{raw: '2001:db8::', canonical: '2001:db8::'}") + @TestParameters("{raw: '2001:db8::dead:BEEF', canonical: '2001:db8::dead:beef'}") + @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:2:3:4:5', canonical: '2001::1:2:3:4:5'}") + @TestParameters("{raw: '2001:0:1:0:2:3:4:5', canonical: '2001:0:1:0:2:3:4:5'}") + @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::192.168.0.1', canonical: '1:2:3:4:5:0:c0a8:1'}") + @TestParameters("{raw: '1:2:3:4:5:6:192.168.0.1', canonical: '1:2:3:4:5:6:c0a8:1'}") + @TestParameters("{raw: '1:2:3:4::5:6:7', canonical: '1:2:3:4:0:5:6:7'}") + @TestParameters( + "{raw: 'fedc:ba98:7654:fedc:89ab:cdef:0123:ffff'," + + " canonical: 'fedc:ba98:7654:fedc:89ab:cdef:123:ffff'}") + @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', 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::`', 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: '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_isUnspecified_returnsExpected() { + 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(); + } + + @Test + public void celIp_isLoopback_returnsExpected() { + assertThat(CelIp.parse("126.255.255.255").isLoopback()).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(); + } + + @Test + public void celIp_isLinkLocalUnicast_returnsExpected() { + 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(); + } + + @Test + public void celIp_isLinkLocalMulticast_returnsExpected() { + 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(); + } + + @Test + public void celIp_isGlobalUnicast_returnsExpected() { + 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 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")) + .testEquals(); + } +} diff --git a/runtime/src/main/java/dev/cel/runtime/TypeResolver.java b/runtime/src/main/java/dev/cel/runtime/TypeResolver.java index f44ddb727..31f910362 100644 --- a/runtime/src/main/java/dev/cel/runtime/TypeResolver.java +++ b/runtime/src/main/java/dev/cel/runtime/TypeResolver.java @@ -157,11 +157,16 @@ static Optional resolveWellKnownObjectType(Object obj) { public static String resolveTypeName(Object obj) { checkNotNull(obj); Optional resolvedType = resolveWellKnownObjectType(obj); - if (!resolvedType.isPresent()) { - resolvedType = resolveExtendableObjectType(obj.getClass()); + if (resolvedType.isPresent()) { + return resolvedType.get().containingTypeName(); + } + if (obj instanceof CelValue) { + return ((CelValue) obj).celType().name(); } - return resolvedType.map(TypeType::containingTypeName).orElseGet(() -> obj.getClass().getName()); + return resolveExtendableObjectType(obj.getClass()) + .map(TypeType::containingTypeName) + .orElseGet(() -> obj.getClass().getName()); } /** Resolves types that the client may have extended, walking superclasses and interfaces. */ diff --git a/runtime/src/test/java/dev/cel/runtime/TypeResolverTest.java b/runtime/src/test/java/dev/cel/runtime/TypeResolverTest.java index bff9b1fb5..de77e0bf8 100644 --- a/runtime/src/test/java/dev/cel/runtime/TypeResolverTest.java +++ b/runtime/src/test/java/dev/cel/runtime/TypeResolverTest.java @@ -25,9 +25,11 @@ import dev.cel.common.internal.ProtoTimeUtils; import dev.cel.common.types.ListType; import dev.cel.common.types.MapType; +import dev.cel.common.types.OpaqueType; import dev.cel.common.types.OptionalType; import dev.cel.common.types.SimpleType; import dev.cel.common.types.TypeType; +import dev.cel.common.values.OpaqueValue; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; @@ -67,6 +69,14 @@ public void resolveTypeName_wellKnownObjectType(@TestParameter WellKnownObjectTe .isEqualTo(testCase.expectedTypeType.containingTypeName()); } + @Test + public void resolveTypeName_celValue_returnsCelTypeName() { + CustomOpaqueValue opaqueValue = new CustomOpaqueValue(); + + assertThat(opaqueValue.value()).isSameInstanceAs(opaqueValue); + assertThat(TypeResolver.resolveTypeName(opaqueValue)).isEqualTo("custom_opaque"); + } + @Test public void resolveTypeName_extendableObjectType() { // LinkedHashMap is not in the exact-class table, so this exercises the interface walk. This is @@ -79,6 +89,20 @@ public void resolveTypeName_unknownObjectType_returnsJavaClassName() { assertThat(TypeResolver.resolveTypeName(new Object())).isEqualTo("java.lang.Object"); } + private static final class CustomOpaqueValue extends OpaqueValue { + private static final OpaqueType CUSTOM_OPAQUE_TYPE = OpaqueType.create("custom_opaque"); + + @Override + public CustomOpaqueValue value() { + return this; + } + + @Override + public OpaqueType celType() { + return CUSTOM_OPAQUE_TYPE; + } + } + @SuppressWarnings("ImmutableEnumChecker") // Test only private enum WellKnownObjectTestCase { BOOLEAN(true, TypeType.create(SimpleType.BOOL)),