Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions extensions/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -774,6 +774,8 @@ cc_library(
"//runtime:runtime_builder",
"//runtime/internal:runtime_friend_access",
"//runtime/internal:runtime_impl",
"//validator",
"//validator:regex_validator",
"@com_google_absl//absl/base:no_destructor",
"@com_google_absl//absl/base:nullability",
"@com_google_absl//absl/functional:bind_front",
Expand Down Expand Up @@ -814,6 +816,7 @@ cc_test(
"//runtime:reference_resolver",
"//runtime:runtime_options",
"//runtime:standard_runtime_builder_factory",
"//validator",
"@com_google_absl//absl/status",
"@com_google_absl//absl/status:status_matchers",
"@com_google_absl//absl/status:statusor",
Expand Down
8 changes: 8 additions & 0 deletions extensions/regex_ext.cc
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@
#include "runtime/internal/runtime_friend_access.h"
#include "runtime/internal/runtime_impl.h"
#include "runtime/runtime_builder.h"
#include "validator/regex_validator.h"
#include "validator/validator.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/message.h"
Expand Down Expand Up @@ -341,4 +343,10 @@ CompilerLibrary RegexExtCompilerLibrary() {
return CompilerLibrary::FromCheckerLibrary(RegexExtCheckerLibrary());
}

Validation RegexExtValidator() {
return RegexPatternValidator(
/*id=*/"",
{{"regex.extract", 1}, {"regex.extractAll", 1}, {"regex.replace", 1}});
}

} // namespace cel::extensions
8 changes: 8 additions & 0 deletions extensions/regex_ext.h
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
#include "eval/public/cel_function_registry.h"
#include "eval/public/cel_options.h"
#include "runtime/runtime_builder.h"
#include "validator/validator.h"

namespace cel::extensions {

Expand Down Expand Up @@ -119,5 +120,12 @@ CheckerLibrary RegexExtCheckerLibrary();
// regex.extractAll(target: str, pattern: str) -> list<str>
CompilerLibrary RegexExtCompilerLibrary();

// Returns a `Validation` that checks all calls to the CEL regex extension
// functions.
//
// It validates that if the pattern is a literal string, it is a valid regular
// expression.
Validation RegexExtValidator();

} // namespace cel::extensions
#endif // THIRD_PARTY_CEL_CPP_EXTENSIONS_REGEX_EXT_H_
40 changes: 40 additions & 0 deletions extensions/regex_ext_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
#include "runtime/runtime.h"
#include "runtime/runtime_options.h"
#include "runtime/standard_runtime_builder_factory.h"
#include "validator/validator.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/extension_set.h"

Expand Down Expand Up @@ -497,5 +498,44 @@ std::vector<RegexCheckerTestCase> createRegexCheckerParams() {

INSTANTIATE_TEST_SUITE_P(RegexExtCheckerLibraryTest, RegexExtCheckerLibraryTest,
ValuesIn(createRegexCheckerParams()));

absl::StatusOr<std::unique_ptr<Compiler>> CreateRegexExtCompiler() {
CEL_ASSIGN_OR_RETURN(
auto builder, NewCompilerBuilder(internal::GetTestingDescriptorPool()));
CEL_RETURN_IF_ERROR(builder->AddLibrary(StandardCheckerLibrary()));
CEL_RETURN_IF_ERROR(builder->AddLibrary(RegexExtCompilerLibrary()));
return std::move(*builder).Build();
}

class RegexExtValidatorTest : public TestWithParam<RegexCheckerTestCase> {};

TEST_P(RegexExtValidatorTest, Basic) {
ASSERT_OK_AND_ASSIGN(auto compiler, CreateRegexExtCompiler());

Validator validator;
validator.AddValidation(RegexExtValidator());

ASSERT_OK_AND_ASSIGN(auto result, compiler->Compile(GetParam().expr_string));
validator.UpdateValidationResult(result);

EXPECT_EQ(result.IsValid(), GetParam().error_substr.empty())
<< "Expression: " << GetParam().expr_string;
if (!GetParam().error_substr.empty()) {
EXPECT_THAT(result.FormatError(), HasSubstr(GetParam().error_substr));
}
}

INSTANTIATE_TEST_SUITE_P(RegexExtValidatorTest, RegexExtValidatorTest,
testing::ValuesIn(std::vector<RegexCheckerTestCase>{
{"regex.extract('hello world', 'hello (.*)')"},
{"regex.extract('hello world', 'hello ([') ",
"invalid regular expression"},
{"regex.extractAll('hello world', 'hello (.*)')"},
{"regex.extractAll('hello world', 'hello ([') ",
"invalid regular expression"},
{"regex.replace('hello world', 'hello', 'hi')"},
{"regex.replace('hello world', 'he([', 'hi') ",
"invalid regular expression"},
}));
} // namespace
} // namespace cel::extensions
35 changes: 35 additions & 0 deletions validator/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,24 @@ cc_library(
],
)

cc_library(
name = "regex_validator",
srcs = ["regex_validator.cc"],
hdrs = ["regex_validator.h"],
deps = [
":validator",
"//common:ast",
"//common:constant",
"//common:expr",
"//common:navigable_ast",
"//common:standard_definitions",
"//internal:re2_options",
"@com_google_absl//absl/log:absl_check",
"@com_google_absl//absl/strings",
"@com_googlesource_code_re2//:re2",
],
)

cc_test(
name = "homogeneous_literal_validator_test",
srcs = ["homogeneous_literal_validator_test.cc"],
Expand Down Expand Up @@ -147,4 +165,21 @@ cc_test(
],
)

cc_test(
name = "regex_validator_test",
srcs = ["regex_validator_test.cc"],
deps = [
":regex_validator",
":validator",
"//common:decl",
"//common:type",
"//compiler",
"//compiler:compiler_factory",
"//compiler:standard_library",
"//internal:testing",
"//internal:testing_descriptor_pool",
"@com_google_absl//absl/status:statusor",
],
)

licenses(["notice"])
96 changes: 96 additions & 0 deletions validator/regex_validator.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// 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 "validator/regex_validator.h"

#include <utility>
#include <vector>

#include "absl/log/absl_check.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "common/constant.h"
#include "common/expr.h"
#include "common/navigable_ast.h"
#include "internal/re2_options.h"
#include "validator/validator.h"
#include "re2/re2.h"

namespace cel {

namespace {

bool CheckPattern(ValidationContext& context, const NavigableAstNode& node,
int arg_index) {
ABSL_DCHECK(node.expr()->has_call_expr());
const auto& call_expr = node.expr()->call_expr();

const Expr* pattern_expr = nullptr;

if (call_expr.has_target()) {
if (arg_index == 0) {
pattern_expr = &call_expr.target();
} else if (call_expr.args().size() > arg_index - 1) {
pattern_expr = &call_expr.args()[arg_index - 1];
}
} else if (call_expr.args().size() > arg_index) {
pattern_expr = &call_expr.args()[arg_index];
}

if (pattern_expr == nullptr || !pattern_expr->has_const_expr()) {
return true;
}

const auto& const_expr = pattern_expr->const_expr();
if (!const_expr.has_string_value()) {
return true;
}

absl::string_view pattern_string = const_expr.string_value();
RE2 re(pattern_string, internal::MakeRE2Options());
if (!re.ok()) {
context.ReportErrorAt(
pattern_expr->id(),
absl::StrCat("invalid regular expression: ", re.error()));
return false;
}
return true;
}

} // namespace

Validation RegexPatternValidator(
absl::string_view id, std::vector<RegexPatternValidatorConfig> config) {
return Validation(
[config = std::move(config)](ValidationContext& context) -> bool {
bool result = true;
for (const auto& node :
context.navigable_ast().Root().DescendantsPostorder()) {
if (node.node_kind() == NodeKind::kCall) {
for (const auto& config : config) {
if (node.expr()->call_expr().function() == config.function_name) {
if (!CheckPattern(context, node, config.pattern_arg_index)) {
result = false;
}
break;
}
}
}
}
return result;
},
id);
}

} // namespace cel
53 changes: 53 additions & 0 deletions validator/regex_validator.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// 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.

#ifndef THIRD_PARTY_CEL_CPP_VALIDATOR_REGEX_VALIDATOR_H_
#define THIRD_PARTY_CEL_CPP_VALIDATOR_REGEX_VALIDATOR_H_

#include <string>
#include <vector>

#include "absl/strings/string_view.h"
#include "common/standard_definitions.h"
#include "validator/validator.h"

namespace cel {

// Configuration for the regex pattern validator.
struct RegexPatternValidatorConfig {
// The resolved function name.
std::string function_name;
// the index of the pattern argument (counting the receiver as arg 0 if
// present).
int pattern_arg_index;
};

// Returns a `Validation` that checks all calls to the given regex functions
// It validates that the specified argument is a valid regular expression if it
// is a literal string.
Validation RegexPatternValidator(
absl::string_view id, std::vector<RegexPatternValidatorConfig> config);

// Returns a `Validation` that checks all calls to the CEL `matches` function.
// It validates that if the pattern is a literal string, it is a valid regular
// expression.
inline Validation MatchesValidator() {
return RegexPatternValidator(
"cel.validator.matches",
{{std::string(StandardFunctions::kRegexMatch), 1}});
}

} // namespace cel

#endif // THIRD_PARTY_CEL_CPP_VALIDATOR_REGEX_VALIDATOR_H_
Loading