diff --git a/extensions/BUILD b/extensions/BUILD index d9f8d7684..f0ca9f778 100644 --- a/extensions/BUILD +++ b/extensions/BUILD @@ -961,3 +961,52 @@ cc_test( "@com_google_protobuf//:protobuf", ], ) + +cc_library( + name = "network_ext", + srcs = ["network_ext.cc"], + hdrs = ["network_ext.h"], + deps = [ + "//checker:type_checker_builder", + "//checker/internal:builtins_arena", + "//common:constant", + "//common:decl", + "//common:expr", + "//common:navigable_ast", + "//common:standard_definitions", + "//common:type", + "//compiler", + "//internal:network_addr", + "//internal:status_macros", + "//validator", + "@com_google_absl//absl/base:no_destructor", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/strings:string_view", + "@com_google_absl//absl/types:span", + ], +) + +cc_test( + name = "network_ext_test", + srcs = ["network_ext_test.cc"], + deps = [ + ":network_ext", + "//checker:standard_library", + "//checker:validation_result", + "//common:ast", + "//common:decl", + "//common:source", + "//common:type", + "//compiler", + "//compiler:compiler_factory", + "//internal:status_macros", + "//internal:testing", + "//internal:testing_descriptor_pool", + "//validator", + "@com_google_absl//absl/status:status_matchers", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings:string_view", + ], +) diff --git a/extensions/network_ext.cc b/extensions/network_ext.cc new file mode 100644 index 000000000..58508483f --- /dev/null +++ b/extensions/network_ext.cc @@ -0,0 +1,212 @@ +// 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. + +#include "extensions/network_ext.h" + +#include +#include + +#include "absl/base/no_destructor.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "checker/internal/builtins_arena.h" +#include "checker/type_checker_builder.h" +#include "common/constant.h" +#include "common/decl.h" +#include "common/expr.h" +#include "common/navigable_ast.h" +#include "common/standard_definitions.h" +#include "common/type.h" +#include "compiler/compiler.h" +#include "internal/network_addr.h" +#include "internal/status_macros.h" +#include "validator/validator.h" + +namespace cel::extensions { +namespace { + +using ::cel::checker_internal::BuiltinsArena; + +constexpr absl::string_view kNetworkExtensionName = "cel.lib.ext.network"; +constexpr absl::string_view kNetworkValidatorId = "cel.validator.network"; +constexpr absl::string_view kNetIpTypeName = "net.IP"; +constexpr absl::string_view kNetCidrTypeName = "net.CIDR"; + +const Type& NetIpTypeType() { + static const absl::NoDestructor kInstance( + TypeType(BuiltinsArena(), NetIpType())); + return *kInstance; +} + +const Type& NetCidrTypeType() { + static const absl::NoDestructor kInstance( + TypeType(BuiltinsArena(), NetCidrType())); + return *kInstance; +} + +template +absl::Status AddFunctionDecl(TypeCheckerBuilder& builder, + absl::string_view name, Overloads&&... overloads) { + CEL_ASSIGN_OR_RETURN(FunctionDecl decl, + MakeFunctionDecl(std::string(name), + std::forward(overloads)...)); + return builder.AddFunction(std::move(decl)); +} + +absl::Status RegisterNetworkCheckerDecls(TypeCheckerBuilder& builder) { + CEL_RETURN_IF_ERROR( + builder.AddVariable(MakeVariableDecl(kNetIpTypeName, NetIpTypeType()))); + CEL_RETURN_IF_ERROR(builder.AddVariable( + MakeVariableDecl(kNetCidrTypeName, NetCidrTypeType()))); + + CEL_ASSIGN_OR_RETURN( + FunctionDecl string_decl, + MakeFunctionDecl( + std::string(StandardFunctions::kString), + MakeOverloadDecl("ip_to_string", StringType(), NetIpType()), + MakeOverloadDecl("cidr_to_string", StringType(), NetCidrType()))); + CEL_RETURN_IF_ERROR(builder.MergeFunction(std::move(string_decl))); + + CEL_RETURN_IF_ERROR(AddFunctionDecl( + builder, "cidr", + MakeOverloadDecl("string_to_cidr", NetCidrType(), StringType()))); + CEL_RETURN_IF_ERROR(AddFunctionDecl( + builder, "containsCIDR", + MakeMemberOverloadDecl("cidr_contains_cidr", BoolType(), NetCidrType(), + NetCidrType()), + MakeMemberOverloadDecl("cidr_contains_cidr_string", BoolType(), + NetCidrType(), StringType()))); + CEL_RETURN_IF_ERROR(AddFunctionDecl( + builder, "containsIP", + MakeMemberOverloadDecl("cidr_contains_ip_ip", BoolType(), NetCidrType(), + NetIpType()), + MakeMemberOverloadDecl("cidr_contains_ip_string", BoolType(), + NetCidrType(), StringType()))); + CEL_RETURN_IF_ERROR(AddFunctionDecl( + builder, "family", + MakeMemberOverloadDecl("ip_family", IntType(), NetIpType()))); + CEL_RETURN_IF_ERROR(AddFunctionDecl( + builder, "ip", + MakeOverloadDecl("string_to_ip", NetIpType(), StringType()), + MakeMemberOverloadDecl("cidr_ip", NetIpType(), NetCidrType()))); + CEL_RETURN_IF_ERROR(AddFunctionDecl( + builder, "ip.isCanonical", + MakeOverloadDecl("ip_is_canonical", BoolType(), StringType()))); + CEL_RETURN_IF_ERROR( + AddFunctionDecl(builder, "isCIDR", + MakeOverloadDecl("is_cidr", BoolType(), StringType()))); + CEL_RETURN_IF_ERROR(AddFunctionDecl( + builder, "isGlobalUnicast", + MakeMemberOverloadDecl("ip_is_global_unicast", BoolType(), NetIpType()))); + CEL_RETURN_IF_ERROR(AddFunctionDecl( + builder, "isIP", MakeOverloadDecl("is_ip", BoolType(), StringType()))); + CEL_RETURN_IF_ERROR( + AddFunctionDecl(builder, "isLinkLocalMulticast", + MakeMemberOverloadDecl("ip_is_link_local_multicast", + BoolType(), NetIpType()))); + CEL_RETURN_IF_ERROR( + AddFunctionDecl(builder, "isLinkLocalUnicast", + MakeMemberOverloadDecl("ip_is_link_local_unicast", + BoolType(), NetIpType()))); + CEL_RETURN_IF_ERROR(AddFunctionDecl( + builder, "isLoopback", + MakeMemberOverloadDecl("ip_is_loopback", BoolType(), NetIpType()))); + CEL_RETURN_IF_ERROR(AddFunctionDecl( + builder, "isMask", + MakeMemberOverloadDecl("cidr_is_mask", BoolType(), NetCidrType()))); + CEL_RETURN_IF_ERROR(AddFunctionDecl( + builder, "isUnspecified", + MakeMemberOverloadDecl("ip_is_unspecified", BoolType(), NetIpType()))); + CEL_RETURN_IF_ERROR(AddFunctionDecl( + builder, "masked", + MakeMemberOverloadDecl("cidr_masked", NetCidrType(), NetCidrType()))); + CEL_RETURN_IF_ERROR(AddFunctionDecl( + builder, "prefixLength", + MakeMemberOverloadDecl("cidr_prefix_length", IntType(), NetCidrType()))); + + return absl::OkStatus(); +} + +bool ValidateNetworkLiterals(ValidationContext& context) { + bool valid = true; + for (const NavigableAstNode& node : + context.navigable_ast().Root().DescendantsPostorder()) { + if (node.node_kind() != NodeKind::kCall) { + continue; + } + const CallExpr& call_expr = node.expr()->call_expr(); + if (call_expr.has_target() || call_expr.args().size() != 1) { + continue; + } + const Expr& arg_expr = call_expr.args()[0]; + if (!arg_expr.has_const_expr() || + !arg_expr.const_expr().has_string_value()) { + continue; + } + absl::string_view literal = arg_expr.const_expr().string_value(); + if (call_expr.function() == "ip") { + if (absl::Status status = internal::ParseIp(literal).status(); + !status.ok()) { + context.ReportErrorAt( + arg_expr.id(), + absl::StrCat("invalid ip argument: ", status.message())); + valid = false; + } + } else if (call_expr.function() == "cidr") { + if (absl::Status status = internal::ParseCidr(literal).status(); + !status.ok()) { + context.ReportErrorAt( + arg_expr.id(), + absl::StrCat("invalid cidr argument: ", status.message())); + valid = false; + } + } + } + return valid; +} + +} // namespace + +OpaqueType NetIpType() { + static const absl::NoDestructor kInstance( + BuiltinsArena(), kNetIpTypeName, absl::Span{}); + return *kInstance; +} + +OpaqueType NetCidrType() { + static const absl::NoDestructor kInstance( + BuiltinsArena(), kNetCidrTypeName, absl::Span{}); + return *kInstance; +} + +CheckerLibrary NetworkCheckerLibrary(int /*version*/) { + // Versions 0 and 1 expose the same initial declaration set. + return {.id = std::string(kNetworkExtensionName), + .configure = RegisterNetworkCheckerDecls}; +} + +CompilerLibrary NetworkCompilerLibrary(int version) { + return CompilerLibrary::FromCheckerLibrary(NetworkCheckerLibrary(version)); +} + +const Validation& NetworkValidator() { + static const absl::NoDestructor kInstance( + &ValidateNetworkLiterals, kNetworkValidatorId); + return *kInstance; +} + +} // namespace cel::extensions diff --git a/extensions/network_ext.h b/extensions/network_ext.h new file mode 100644 index 000000000..8e4526a99 --- /dev/null +++ b/extensions/network_ext.h @@ -0,0 +1,94 @@ +// 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. + +// Type declarations, opaque types, and compile-time literal validator for the +// CEL network extension library (`cel.lib.ext.network`), matching `cel-go`'s +// `ext.Network()` semantics. +// +// IP addresses and CIDR prefixes are parsed strictly: leading zeros, IPv6 zone +// identifiers, and IPv4-mapped IPv6 addresses (`::ffff:0:0/96`) are rejected. +// +// # Types +// +// net.IP +// net.CIDR +// +// # Global Functions +// +// ip(string) -> net.IP +// isIP(string) -> bool +// ip.isCanonical(string) -> bool +// cidr(string) -> net.CIDR +// isCIDR(string) -> bool +// string(net.IP) -> string +// string(net.CIDR) -> string +// +// # net.IP Member Functions +// +// .family() -> int +// .isUnspecified() -> bool +// .isLoopback() -> bool +// .isGlobalUnicast() -> bool +// .isLinkLocalMulticast() -> bool +// .isLinkLocalUnicast() -> bool +// +// # net.CIDR Member Functions +// +// .ip() -> net.IP +// .masked() -> net.CIDR +// .isMask() -> bool +// .prefixLength() -> int +// .containsIP(net.IP) -> bool +// .containsIP(string) -> bool +// .containsCIDR(net.CIDR) -> bool +// .containsCIDR(string) -> bool + +#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_NETWORK_EXT_H_ +#define THIRD_PARTY_CEL_CPP_EXTENSIONS_NETWORK_EXT_H_ + +#include "checker/type_checker_builder.h" +#include "common/type.h" +#include "compiler/compiler.h" +#include "validator/validator.h" + +namespace cel::extensions { + +inline constexpr int kNetworkExtensionLatestVersion = 1; + +// Returns the CEL opaque type for `net.IP`. +OpaqueType NetIpType(); + +// Returns the CEL opaque type for `net.CIDR`. +OpaqueType NetCidrType(); + +// Type check declarations for the network extension library. +CheckerLibrary NetworkCheckerLibrary( + int version = kNetworkExtensionLatestVersion); + +// Compiler declarations for the network extension library. +CompilerLibrary NetworkCompilerLibrary( + int version = kNetworkExtensionLatestVersion); + +// Returns a `Validation` (`"cel.validator.network"`) that validates string +// literal arguments passed to global `ip(...)` and `cidr(...)` calls. +// +// Unlike `cel-go`'s `ext.Network()`, `cel::CompilerLibrary` and YAML `Env` +// configurations do not auto-wire AST validators, so callers must register +// this explicitly via +// `CompilerBuilder::GetValidator().AddValidation(NetworkValidator())`. +const Validation& NetworkValidator(); + +} // namespace cel::extensions + +#endif // THIRD_PARTY_CEL_CPP_EXTENSIONS_NETWORK_EXT_H_ diff --git a/extensions/network_ext_test.cc b/extensions/network_ext_test.cc new file mode 100644 index 000000000..7f36bcc96 --- /dev/null +++ b/extensions/network_ext_test.cc @@ -0,0 +1,192 @@ +// 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. + +#include "extensions/network_ext.h" + +#include +#include +#include +#include + +#include "absl/status/status_matchers.h" +#include "absl/status/statusor.h" +#include "absl/strings/string_view.h" +#include "checker/standard_library.h" +#include "checker/validation_result.h" +#include "common/ast.h" +#include "common/decl.h" +#include "common/source.h" +#include "common/type.h" +#include "compiler/compiler.h" +#include "compiler/compiler_factory.h" +#include "internal/status_macros.h" +#include "internal/testing.h" +#include "internal/testing_descriptor_pool.h" +#include "validator/validator.h" + +namespace cel::extensions { +namespace { + +using ::absl_testing::IsOk; +using ::testing::HasSubstr; +using ::testing::IsEmpty; +using ::testing::TestWithParam; +using ::testing::ValuesIn; + +absl::StatusOr> CreateTestCompiler( + int version = kNetworkExtensionLatestVersion) { + CEL_ASSIGN_OR_RETURN( + std::unique_ptr builder, + NewCompilerBuilder(internal::GetTestingDescriptorPool())); + CEL_RETURN_IF_ERROR(builder->AddLibrary(StandardCheckerLibrary())); + CEL_RETURN_IF_ERROR(builder->AddLibrary(NetworkCompilerLibrary(version))); + return std::move(*builder).Build(); +} + +TEST(NetworkExtTest, TypeNamesAndIds) { + EXPECT_EQ(kNetworkExtensionLatestVersion, 1); + EXPECT_EQ(NetIpType().name(), "net.IP"); + EXPECT_EQ(NetCidrType().name(), "net.CIDR"); + EXPECT_EQ(NetworkCheckerLibrary().id, "cel.lib.ext.network"); + EXPECT_EQ(NetworkCheckerLibrary(0).id, "cel.lib.ext.network"); + EXPECT_EQ(NetworkCompilerLibrary().id, "cel.lib.ext.network"); + EXPECT_EQ(NetworkCompilerLibrary(0).id, "cel.lib.ext.network"); + EXPECT_EQ(NetworkValidator().id(), "cel.validator.network"); +} + +struct NetworkCheckerCase { + std::string expr; + std::string error_substr; +}; + +class NetworkExtCheckerTest : public TestWithParam {}; + +TEST_P(NetworkExtCheckerTest, CompileVersionsZeroAndLatest) { + for (int version : {0, kNetworkExtensionLatestVersion}) { + ASSERT_OK_AND_ASSIGN(std::unique_ptr compiler, + CreateTestCompiler(version)); + ASSERT_OK_AND_ASSIGN(ValidationResult result, + compiler->Compile(GetParam().expr)); + absl::string_view error_substr = GetParam().error_substr; + EXPECT_EQ(result.IsValid(), error_substr.empty()) + << "version: " << version << " expr: " << GetParam().expr + << " issues: " << result.FormatError(); + if (!error_substr.empty()) { + EXPECT_THAT(result.FormatError(), HasSubstr(error_substr)); + } + } +} + +INSTANTIATE_TEST_SUITE_P( + NetworkExtCheckerTest, NetworkExtCheckerTest, + ValuesIn(std::vector{ + // All 17 functions / 21 overloads + net.IP / net.CIDR type variables. + {"type(ip('192.168.0.1')) == net.IP"}, + {"type(cidr('192.168.0.0/24')) == net.CIDR"}, + {"isIP('192.168.0.1')"}, + {"isCIDR('192.168.0.0/24')"}, + {"ip.isCanonical('2001:db8::1')"}, + {"string(ip('192.168.0.1')) == '192.168.0.1'"}, + {"string(cidr('192.168.0.0/24')) == '192.168.0.0/24'"}, + {"string(42) == '42'"}, + {"ip('192.168.0.1').family() == 4"}, + {"ip('0.0.0.0').isUnspecified()"}, + {"ip('127.0.0.1').isLoopback()"}, + {"ip('8.8.8.8').isGlobalUnicast()"}, + {"ip('224.0.0.1').isLinkLocalMulticast()"}, + {"ip('169.254.1.1').isLinkLocalUnicast()"}, + {"cidr('192.168.0.1/24').ip() == ip('192.168.0.1')"}, + {"cidr('192.168.0.1/24').masked() == cidr('192.168.0.0/24')"}, + {"cidr('192.168.0.0/24').isMask()"}, + {"cidr('192.168.0.0/24').prefixLength() == 24"}, + {"cidr('192.168.0.0/24').containsIP(ip('192.168.0.1'))"}, + {"cidr('192.168.0.0/24').containsIP('192.168.0.1')"}, + {"cidr('192.168.0.0/24').containsCIDR(cidr('192.168.0.0/25'))"}, + {"cidr('192.168.0.0/24').containsCIDR('192.168.0.0/25')"}, + + // Static type-mismatch errors. + {"isIP(cidr('192.168.0.0/24'))", + "found no matching overload for 'isIP' applied to '(net.CIDR)'"}, + {"ip('192.168.0.1') == cidr('192.168.0.1/32')", + "found no matching overload for '_==_' applied to '(net.IP, " + "net.CIDR)'"}, + {"ip('192.168.0.1').prefixLength()", + "found no matching overload for 'prefixLength' applied to '(net.IP)'"}, + {"cidr('192.168.0.0/24').family()", + "found no matching overload for 'family' applied to '(net.CIDR)'"}, + {"string(ip('192.168.0.1')) == 1", + "found no matching overload for '_==_' applied to '(string, int)'"}, + })); + +class NetworkExtValidatorTest : public TestWithParam {}; + +TEST_P(NetworkExtValidatorTest, ValidatesLiterals) { + ASSERT_OK_AND_ASSIGN( + std::unique_ptr builder, + NewCompilerBuilder(internal::GetTestingDescriptorPool())); + ASSERT_THAT(builder->AddLibrary(StandardCheckerLibrary()), IsOk()); + ASSERT_THAT(builder->AddLibrary(NetworkCompilerLibrary()), IsOk()); + ASSERT_THAT(builder->GetCheckerBuilder().AddVariable( + MakeVariableDecl("addr", StringType())), + IsOk()); + builder->GetValidator().AddValidation(NetworkValidator()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr compiler, + std::move(*builder).Build()); + + ASSERT_OK_AND_ASSIGN(ValidationResult result, + compiler->Compile(GetParam().expr)); + EXPECT_EQ(result.IsValid(), GetParam().error_substr.empty()) + << "Expression: " << GetParam().expr + << " issues: " << result.FormatError(); + if (!GetParam().error_substr.empty()) { + EXPECT_THAT(result.FormatError(), HasSubstr(GetParam().error_substr)); + } +} + +INSTANTIATE_TEST_SUITE_P( + NetworkExtValidatorTest, NetworkExtValidatorTest, + ValuesIn(std::vector{ + {"ip('192.168.0.1')"}, + {"ip(addr)"}, + {"cidr('192.168.0.1/24').ip()"}, + {"cidr('2001:db8::/32')"}, + {"ip('192.168.0.1.0')", "invalid ip argument"}, + {"ip('fe80::1%en0')", "invalid ip argument"}, + {"ip('::ffff:192.168.0.1')", "invalid ip argument"}, + {"cidr('192.168.0.0/')", "invalid cidr argument"}, + {"cidr('10.0.0.0/08')", "invalid cidr argument"}, + {"cidr('::ffff:192.168.0.1/24')", "invalid cidr argument"}, + })); + +TEST(NetworkExtValidatorRawAstTest, IgnoresNonStringAndMemberCalls) { + ASSERT_OK_AND_ASSIGN( + std::unique_ptr builder, + NewCompilerBuilder(internal::GetTestingDescriptorPool())); + ASSERT_OK_AND_ASSIGN(std::unique_ptr compiler, + std::move(*builder).Build()); + ASSERT_OK_AND_ASSIGN( + std::unique_ptr source, + NewSource("ip(123) == x.ip('invalid') && cidr('a', 'b')")); + ASSERT_OK_AND_ASSIGN(std::unique_ptr ast, + compiler->GetParser().Parse(*source)); + + Validator validator; + validator.AddValidation(NetworkValidator()); + Validator::ValidationOutput output = validator.Validate(*ast); + EXPECT_TRUE(output.valid); + EXPECT_THAT(output.issues, IsEmpty()); +} + +} // namespace +} // namespace cel::extensions