diff --git a/publish/BUILD.bazel b/publish/BUILD.bazel index 9562e22f0..4120afb75 100644 --- a/publish/BUILD.bazel +++ b/publish/BUILD.bazel @@ -75,6 +75,7 @@ VALIDATOR_TARGETS = [ "//validator/src/main/java/dev/cel/validator:ast_validator", "//validator/src/main/java/dev/cel/validator:validator_builder", "//validator/src/main/java/dev/cel/validator:validator_impl", + "//validator/src/main/java/dev/cel/validator/validators:bind_nesting_limit_validator", "//validator/src/main/java/dev/cel/validator/validators:duration", "//validator/src/main/java/dev/cel/validator/validators:homogeneous_literal", "//validator/src/main/java/dev/cel/validator/validators:regex", @@ -92,6 +93,7 @@ OPTIMIZER_TARGETS = [ "//optimizer/src/main/java/dev/cel/optimizer/optimizers:common_subexpression_elimination", "//optimizer/src/main/java/dev/cel/optimizer/optimizers:constant_folding", "//optimizer/src/main/java/dev/cel/optimizer/optimizers:inlining", + "//optimizer/src/main/java/dev/cel/optimizer/optimizers:select_optimizer", ] # keep sorted diff --git a/validator/src/main/java/dev/cel/validator/validators/BUILD.bazel b/validator/src/main/java/dev/cel/validator/validators/BUILD.bazel index 93a2c0d28..368a4ad20 100644 --- a/validator/src/main/java/dev/cel/validator/validators/BUILD.bazel +++ b/validator/src/main/java/dev/cel/validator/validators/BUILD.bazel @@ -86,6 +86,22 @@ java_library( ], ) +java_library( + name = "bind_nesting_limit_validator", + srcs = [ + "BindNestingLimitValidator.java", + ], + tags = [ + ], + deps = [ + "//bundle:cel", + "//common/ast", + "//common/navigation", + "//validator:ast_validator", + "@maven//:com_google_guava_guava", + ], +) + java_library( name = "comprehension_nesting_limit_validator", srcs = [ diff --git a/validator/src/main/java/dev/cel/validator/validators/BindNestingLimitValidator.java b/validator/src/main/java/dev/cel/validator/validators/BindNestingLimitValidator.java new file mode 100644 index 000000000..7a66f01a1 --- /dev/null +++ b/validator/src/main/java/dev/cel/validator/validators/BindNestingLimitValidator.java @@ -0,0 +1,85 @@ +// 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.validator.validators; + +import static com.google.common.base.Preconditions.checkArgument; + +import dev.cel.bundle.Cel; +import dev.cel.common.ast.CelConstant; +import dev.cel.common.ast.CelExpr.CelComprehension; +import dev.cel.common.ast.CelExpr.ExprKind; +import dev.cel.common.navigation.CelNavigableAst; +import dev.cel.common.navigation.CelNavigableExpr; +import dev.cel.validator.CelAstValidator; + +/** Enforces that {@code cel.bind} macro nesting does not exceed the configured limit. */ +public final class BindNestingLimitValidator implements CelAstValidator { + private static final String UNUSED_ITER_VAR = "#unused"; + private static final CelConstant FALSE_CONSTANT = CelConstant.ofValue(false); + + private final int nestingLimit; + + /** + * Constructs a new instance of {@link BindNestingLimitValidator} with {@code maxNesting} as its + * limit. A limit of 0 disallows all {@code cel.bind} calls. + */ + public static BindNestingLimitValidator newInstance(int maxNesting) { + checkArgument(maxNesting >= 0); + return new BindNestingLimitValidator(maxNesting); + } + + @Override + public void validate(CelNavigableAst navigableAst, Cel cel, IssuesFactory issuesFactory) { + navigableAst + .getRoot() + .allNodes() + .filter(BindNestingLimitValidator::isCelBind) + .filter(node -> nestingLevel(node) > nestingLimit) + .forEach( + node -> + issuesFactory.addError( + node.id(), + String.format( + "cel.bind nesting exceeds the configured limit: %d.", nestingLimit))); + } + + private static boolean isCelBind(CelNavigableExpr node) { + if (!node.getKind().equals(ExprKind.Kind.COMPREHENSION)) { + return false; + } + CelComprehension compre = node.expr().comprehension(); + // listOrDefault() returns an empty CelList for non-LIST nodes, so check Kind.LIST explicitly. + return compre.iterRange().getKind().equals(ExprKind.Kind.LIST) + && compre.iterRange().list().elements().isEmpty() + && compre.iterVar().equals(UNUSED_ITER_VAR) + && compre.loopCondition().constantOrDefault().equals(FALSE_CONSTANT) + && compre.loopStep().identOrDefault().name().equals(compre.accuVar()); + } + + private static int nestingLevel(CelNavigableExpr node) { + int count = 1; + while (node.parent().isPresent()) { + node = node.parent().get(); + if (isCelBind(node)) { + count++; + } + } + return count; + } + + private BindNestingLimitValidator(int maxNesting) { + this.nestingLimit = maxNesting; + } +} diff --git a/validator/src/test/java/dev/cel/validator/validators/BUILD.bazel b/validator/src/test/java/dev/cel/validator/validators/BUILD.bazel index b6e52d378..8048de480 100644 --- a/validator/src/test/java/dev/cel/validator/validators/BUILD.bazel +++ b/validator/src/test/java/dev/cel/validator/validators/BUILD.bazel @@ -17,6 +17,7 @@ java_library( "//common:compiler_common", "//common:options", "//common:proto_ast", + "//common/ast", "//common/internal:proto_time_utils", "//common/types", "//extensions", @@ -28,6 +29,7 @@ java_library( "//validator", "//validator:validator_builder", "//validator/validators:ast_depth_limit_validator", + "//validator/validators:bind_nesting_limit_validator", "//validator/validators:comprehension_nesting_limit_validator", "//validator/validators:duration", "//validator/validators:homogeneous_literal", diff --git a/validator/src/test/java/dev/cel/validator/validators/BindNestingLimitValidatorTest.java b/validator/src/test/java/dev/cel/validator/validators/BindNestingLimitValidatorTest.java new file mode 100644 index 000000000..9c83d438e --- /dev/null +++ b/validator/src/test/java/dev/cel/validator/validators/BindNestingLimitValidatorTest.java @@ -0,0 +1,194 @@ +// 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.validator.validators; + +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; + +import com.google.testing.junit.testparameterinjector.TestParameter; +import com.google.testing.junit.testparameterinjector.TestParameterInjector; +import dev.cel.bundle.Cel; +import dev.cel.bundle.CelFactory; +import dev.cel.common.CelAbstractSyntaxTree; +import dev.cel.common.CelValidationException; +import dev.cel.common.CelValidationResult; +import dev.cel.common.ast.CelExpr; +import dev.cel.common.types.OptionalType; +import dev.cel.common.types.SimpleType; +import dev.cel.extensions.CelExtensions; +import dev.cel.parser.CelMacro; +import dev.cel.parser.CelMacroExpander; +import dev.cel.parser.CelMacroExprFactory; +import dev.cel.parser.CelStandardMacro; +import dev.cel.validator.CelValidator; +import dev.cel.validator.CelValidatorFactory; +import java.util.Optional; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(TestParameterInjector.class) +public final class BindNestingLimitValidatorTest { + + private static final Cel CEL = + CelFactory.plannerCelBuilder() + .addCompilerLibraries(CelExtensions.optional(), CelExtensions.bindings()) + .setStandardMacros(CelStandardMacro.STANDARD_MACROS) + .addMacros( + newCustomMacro( + "non_list_iter_range", + (f, t, a) -> newComprehension(f, "#unused", f.newMap(), f.newIdentifier("a"))), + newCustomMacro( + "non_empty_iter_range", + (f, t, a) -> + newComprehension( + f, "#unused", f.newList(f.newIntLiteral(1)), f.newIdentifier("a"))), + newCustomMacro( + "custom_iter_var", + (f, t, a) -> newComprehension(f, "iter", f.newList(), f.newIdentifier("a"))), + newCustomMacro( + "non_ident_loop_step", + (f, t, a) -> newComprehension(f, "#unused", f.newList(), f.newIntLiteral(2))), + newCustomMacro( + "distinct_ident_loop_step", + (f, t, a) -> newComprehension(f, "#unused", f.newList(), f.newIdentifier("b")))) + .addVar("b", SimpleType.INT) + .addVar("x", OptionalType.create(SimpleType.INT)) + .build(); + + private static final CelValidator VALIDATOR_LIMIT_0 = newValidator(0); + private static final CelValidator VALIDATOR_LIMIT_2 = newValidator(2); + + @Test + public void newInstance_negativeLimit_throws() { + assertThrows(IllegalArgumentException.class, () -> BindNestingLimitValidator.newInstance(-1)); + } + + @Test + public void validate_withinLimit_succeeds( + @TestParameter({ + "1 + 1", + "cel.bind(a, 1, a + 1)", + "cel.bind(a, 1, cel.bind(b, 2, a + b))", + "cel.bind(a, 1, a) + cel.bind(b, 2, b)", + "cel.bind(a, 1, cel.bind(b, 2, a + b)) + cel.bind(c, 3, cel.bind(d, 4, c + d))", + "[1, 2, 3].exists(i, cel.bind(a, i, cel.bind(b, a, a + b) > 0))", + "cel.bind(a, [1, 2], a.map(i, cel.bind(b, i + 1, [b, b].map(j, j))))", + "optional.of(1).optMap(a, optional.of(a + 1).optMap(b, b + 1))", + }) + String expr) + throws Exception { + CelAbstractSyntaxTree ast = CEL.compile(expr).getAst(); + + CelValidationResult result = VALIDATOR_LIMIT_2.validate(ast); + + assertThat(result.getAllIssues()).isEmpty(); + } + + @Test + public void validate_exceedsLimit_populatesError( + @TestParameter({ + "cel.bind(a, 1, cel.bind(b, 2, cel.bind(c, 3, a + b + c)))", + "cel.bind(a, 1, cel.bind(b, 2, 1 + cel.bind(c, 3, a + b + c)))", + "cel.bind(c, cel.bind(b, cel.bind(a, 1, a + 1), b + 1), c + 1)", + "optional.of(1).optMap(a, optional.of(a + 1).optMap(b, optional.of(b + 1).optMap(c, c" + + " + 1)))", + }) + String expr) + throws Exception { + CelAbstractSyntaxTree ast = CEL.compile(expr).getAst(); + + CelValidationResult result = VALIDATOR_LIMIT_2.validate(ast); + + assertThat(result.getAllIssues()).hasSize(1); + assertThat(result.getErrorString()) + .contains("cel.bind nesting exceeds the configured limit: 2."); + assertThat(result.getErrorString()).contains("ERROR: :1:"); + } + + @Test + public void validate_multipleViolations_accumulatesErrors() throws Exception { + CelAbstractSyntaxTree ast = + CEL.compile("cel.bind(a, 1, cel.bind(b, 2, cel.bind(c, 3, a + b + c)))").getAst(); + CelValidator validator = newValidator(1); + + CelValidationResult result = validator.validate(ast); + + assertThat(result.getAllIssues()).hasSize(2); + assertThat(result.getErrorString()) + .isEqualTo( + "ERROR: :1:24: cel.bind nesting exceeds the configured limit: 1.\n" + + " | cel.bind(a, 1, cel.bind(b, 2, cel.bind(c, 3, a + b + c)))\n" + + " | .......................^\n" + + "ERROR: :1:39: cel.bind nesting exceeds the configured limit: 1.\n" + + " | cel.bind(a, 1, cel.bind(b, 2, cel.bind(c, 3, a + b + c)))\n" + + " | ......................................^"); + } + + @Test + public void validate_zeroLimit_disallowsAllBinds() throws Exception { + CelAbstractSyntaxTree ast = CEL.compile("cel.bind(a, 1, a + 1)").getAst(); + + CelValidationResult result = VALIDATOR_LIMIT_0.validate(ast); + + CelValidationException e = assertThrows(CelValidationException.class, result::getAst); + assertThat(e).hasMessageThat().contains("cel.bind nesting exceeds the configured limit: 0."); + } + + @Test + public void validate_zeroLimit_ignoresNonBindComprehensions( + @TestParameter({ + "[1, 2].map(y, y + 1)", + "[].map(y, y + 1)", + "{}.all(k, k != 0)", + "{1: 2}.all(k, k != 0)", + "x.optMap(y, y + 1)", + "non_list_iter_range()", + "non_empty_iter_range()", + "custom_iter_var()", + "non_ident_loop_step()", + "distinct_ident_loop_step()", + }) + String expr) + throws Exception { + CelAbstractSyntaxTree ast = CEL.compile(expr).getAst(); + + CelValidationResult result = VALIDATOR_LIMIT_0.validate(ast); + + assertThat(result.getAllIssues()).isEmpty(); + } + + private static CelValidator newValidator(int maxNesting) { + return CelValidatorFactory.standardCelValidatorBuilder(CEL) + .addAstValidators(BindNestingLimitValidator.newInstance(maxNesting)) + .build(); + } + + private static CelMacro newCustomMacro(String name, CelMacroExpander expander) { + return CelMacro.newGlobalMacro(name, /* argCount= */ 0, expander); + } + + private static Optional newComprehension( + CelMacroExprFactory f, String iterVar, CelExpr iterRange, CelExpr step) { + return Optional.of( + f.fold( + iterVar, + iterRange, + /* accuVar= */ "a", + /* accuInit= */ f.newIntLiteral(1), + /* condition= */ f.newBoolLiteral(false), + step, + /* result= */ f.newIdentifier("a"))); + } +} diff --git a/validator/validators/BUILD.bazel b/validator/validators/BUILD.bazel index 8054ae092..866242d91 100644 --- a/validator/validators/BUILD.bazel +++ b/validator/validators/BUILD.bazel @@ -30,6 +30,11 @@ java_library( exports = ["//validator/src/main/java/dev/cel/validator/validators:ast_depth_limit_validator"], ) +java_library( + name = "bind_nesting_limit_validator", + exports = ["//validator/src/main/java/dev/cel/validator/validators:bind_nesting_limit_validator"], +) + java_library( name = "comprehension_nesting_limit_validator", exports = ["//validator/src/main/java/dev/cel/validator/validators:comprehension_nesting_limit_validator"],