From 6c9972ee06587c527a8a0dbb6031e5a1295728a4 Mon Sep 17 00:00:00 2001 From: Sean Huh Date: Wed, 25 Nov 2026 12:13:21 -0800 Subject: [PATCH] Compare optionals by CEL equality in the verifier PiperOrigin-RevId: 1030107353 --- verifier/README.md | 39 ++-- .../main/java/dev/cel/verifier/BUILD.bazel | 6 +- .../cel/verifier/CelAstToZ3Translator.java | 45 +++- .../verifier/CelPolicyVerifierFactory.java | 5 +- .../dev/cel/verifier/CelVerifierBuilder.java | 17 +- .../dev/cel/verifier/CelVerifierFactory.java | 12 +- .../dev/cel/verifier/CelVerifierZ3Impl.java | 122 ++++------ .../CelZ3CounterexampleGenerator.java | 8 + .../cel/verifier/CelZ3OperatorTranslator.java | 70 +++++- .../CelZ3TypeConstraintGenerator.java | 3 + .../dev/cel/verifier/CelZ3TypeSystem.java | 62 +++++- .../java/dev/cel/verifier/RuntimeOracle.java | 165 ++++++++++---- .../dev/cel/verifier/axioms/TypeAxiom.java | 29 +-- .../verifier/CelPolicyVerifierImplTest.java | 122 +++++++++- .../cel/verifier/CelVerifierZ3ImplTest.java | 209 ++++++++++++++---- 15 files changed, 662 insertions(+), 252 deletions(-) diff --git a/verifier/README.md b/verifier/README.md index b3b376d52..ef3c59775 100644 --- a/verifier/README.md +++ b/verifier/README.md @@ -56,7 +56,7 @@ properties about your expressions. runtime partial evaluation. ```java -CelVerifier verifier = CelVerifierFactory.newVerifier() +CelVerifier verifier = CelVerifierFactory.newVerifier(cel) .addUnknownIdentifier("request.headers") // Exclude unknown fields from failure paths .build(); ``` @@ -85,10 +85,10 @@ The following example demonstrates how to verify if two CEL expressions are logically equivalent. ```java +import dev.cel.bundle.Cel; +import dev.cel.bundle.CelFactory; import dev.cel.common.CelAbstractSyntaxTree; import dev.cel.common.types.SimpleType; -import dev.cel.compiler.CelCompiler; -import dev.cel.compiler.CelCompilerFactory; import dev.cel.verifier.CelVerificationException; import dev.cel.verifier.CelVerificationResult; import dev.cel.verifier.CelVerificationResult.VerificationStatus; @@ -98,16 +98,16 @@ import java.time.Duration; public class VerifierExample { public static void main(String[] args) throws Exception { - CelCompiler compiler = CelCompilerFactory.standardCelCompilerBuilder() + Cel cel = CelFactory.plannerCelBuilder() .addVar("x", SimpleType.INT) .build(); // Compile two logically equivalent expressions - CelAbstractSyntaxTree astA = compiler.compile("x > 10").getAst(); - CelAbstractSyntaxTree astB = compiler.compile("10 < x").getAst(); + CelAbstractSyntaxTree astA = cel.compile("x > 10").getAst(); + CelAbstractSyntaxTree astB = cel.compile("10 < x").getAst(); // Create and configure the verifier - CelVerifier verifier = CelVerifierFactory.newVerifier() + CelVerifier verifier = CelVerifierFactory.newVerifier(cel) .setTimeout(Duration.ofSeconds(2)) .build(); @@ -142,7 +142,8 @@ public class VerifierExample { ### 2. Policy Equivalence Verification -You can also verify the equivalence of two structured CEL Policies. +You can also verify the equivalence of two structured CEL Policies. Build the +policy compiler and the AST verifier from the same `Cel` environment. ```java import dev.cel.bundle.Cel; @@ -176,7 +177,7 @@ public class PolicyVerifierExample { CelPolicyCompilerFactory.newPolicyCompiler(CEL).build(); // Verifiers are immutable and thread-safe, making them safe to store as static constants - private static final CelVerifier AST_VERIFIER = CelVerifierFactory.newVerifier().build(); + private static final CelVerifier AST_VERIFIER = CelVerifierFactory.newVerifier(CEL).build(); private static final CelPolicyVerifier POLICY_VERIFIER = CelPolicyVerifierFactory.newVerifier(POLICY_COMPILER, AST_VERIFIER).build(); @@ -245,10 +246,10 @@ provides concrete satisfying model assignments (witness/test case generation), and `result.witness()` exposes them as CEL runtime values. ```java +import dev.cel.bundle.Cel; +import dev.cel.bundle.CelFactory; import dev.cel.common.CelAbstractSyntaxTree; import dev.cel.common.types.SimpleType; -import dev.cel.compiler.CelCompiler; -import dev.cel.compiler.CelCompilerFactory; import dev.cel.verifier.CelVerificationResult; import dev.cel.verifier.CelVerificationResult.VerificationStatus; import dev.cel.verifier.CelVerifier; @@ -256,16 +257,16 @@ import dev.cel.verifier.CelVerifierFactory; public class SatisfiabilityExample { public static void main(String[] args) throws Exception { - CelCompiler compiler = CelCompilerFactory.standardCelCompilerBuilder() + Cel cel = CelFactory.plannerCelBuilder() .addVar("role", SimpleType.STRING) .addVar("port", SimpleType.INT) .build(); // Check if an authorization condition can ever be met CelAbstractSyntaxTree ast = - compiler.compile("role == 'editor' && port > 1024 && port < 65535").getAst(); + cel.compile("role == 'editor' && port > 1024 && port < 65535").getAst(); - CelVerifier verifier = CelVerifierFactory.newVerifier().build(); + CelVerifier verifier = CelVerifierFactory.newVerifier(cel).build(); CelVerificationResult result = verifier.isSatisfiable(ast); switch (result.status()) { @@ -322,7 +323,7 @@ public class InvariantsExample { private static final CelPolicyCompiler POLICY_COMPILER = CelPolicyCompilerFactory.newPolicyCompiler(CEL).build(); - private static final CelVerifier AST_VERIFIER = CelVerifierFactory.newVerifier().build(); + private static final CelVerifier AST_VERIFIER = CelVerifierFactory.newVerifier(CEL).build(); private static final CelPolicyVerifier POLICY_VERIFIER = CelPolicyVerifierFactory.newVerifier(POLICY_COMPILER, AST_VERIFIER).build(); @@ -415,10 +416,10 @@ runtime of the verifier's environment: a confirmed `INCONCLUSIVE` counterexample (or satisfying input) becomes `VIOLATED` (or `VERIFIED`), and any refuted one becomes `INCONCLUSIVE` with no witness. Only exact inputs are checked, when no unknown identifiers are registered; when the runtime can't evaluate them (e.g. a -function has no binding), the message says why. Policy invariants aren't -checked yet. The runtime must follow the CEL spec (e.g. `CelOptions.DEFAULT`, which has no -iteration limit), and a function with bindings must have one for each overload, -which is synchronous, deterministic and doesn't throw. +function has no binding), the message says why. The runtime must follow the CEL +spec (e.g. `CelOptions.DEFAULT`, which has no iteration limit), and a function +with bindings must have one for each overload, which is synchronous, +deterministic and doesn't throw. ### Comprehensions and Bounded Model Checking diff --git a/verifier/src/main/java/dev/cel/verifier/BUILD.bazel b/verifier/src/main/java/dev/cel/verifier/BUILD.bazel index b23b6f2c5..5a979e22b 100644 --- a/verifier/src/main/java/dev/cel/verifier/BUILD.bazel +++ b/verifier/src/main/java/dev/cel/verifier/BUILD.bazel @@ -22,7 +22,6 @@ java_library( deps = [ "//:auto_value", "//common:cel_ast", - "//common/types:type_providers", "@maven//:com_google_errorprone_error_prone_annotations", "@maven//:com_google_guava_guava", ], @@ -189,12 +188,12 @@ java_library( "//common:operator", "//common/ast", "//common/ast:cel_block", - "//common/internal:cel_descriptor_pools", + "//common/exceptions:runtime_exception", "//common/internal:map_keys", "//common/internal:proto_time_utils", - "//common/internal:well_known_proto", "//common/types", "//common/types:cel_types", + "//common/types:default_type_provider", "//common/types:type_providers", "//common/values", "//common/values:cel_byte_string", @@ -208,7 +207,6 @@ java_library( "//verifier/axioms", "@maven//:com_google_errorprone_error_prone_annotations", "@maven//:com_google_guava_guava", - "@maven//:com_google_protobuf_protobuf_java", "@maven//:org_jspecify_jspecify", "@maven//:tools_aqua_z3_turnkey", ], diff --git a/verifier/src/main/java/dev/cel/verifier/CelAstToZ3Translator.java b/verifier/src/main/java/dev/cel/verifier/CelAstToZ3Translator.java index 7fec67e94..e9e82f585 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelAstToZ3Translator.java +++ b/verifier/src/main/java/dev/cel/verifier/CelAstToZ3Translator.java @@ -15,6 +15,7 @@ package dev.cel.verifier; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -39,6 +40,9 @@ import dev.cel.common.types.CelKind; import dev.cel.common.types.CelType; import dev.cel.common.types.CelTypeProvider; +import dev.cel.common.types.CelTypes; +import dev.cel.common.types.DefaultTypeProvider; +import dev.cel.common.types.StructType; import dev.cel.common.types.TypeType; import java.util.ArrayList; import java.util.Arrays; @@ -49,6 +53,7 @@ import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.stream.Stream; /** * Internal translator from CEL AST to Z3 SMT expressions using a 4-valued logic tagged union. @@ -139,11 +144,16 @@ TranslatedValue translate(CelAbstractSyntaxTree ast) { CelZ3ExtensionalityAxioms.generateAxioms(ctx, typeSystem, listRefs, mapRefs, msgRefs) .forEach(context::addConstraint); - // A present optional holds a CEL value, even when the optional is held by a dyn. + // A present optional holds a CEL value, even when the optional is held by a dyn, and is the + // optional of that value. for (Expr ref : optRefs) { - context.constrainValidValue( - ctx.mkAnd(typeSystem.isOptional(ref.getArgs()[0]), typeSystem.optHasValue(ref)), - typeSystem.getOptionalValue(ref)); + BoolExpr isPresent = + ctx.mkAnd(typeSystem.isOptional(ref.getArgs()[0]), typeSystem.optHasValue(ref)); + Expr value = typeSystem.getOptionalValue(ref); + context.constrainValidValue(isPresent, value); + context.addConstraint( + ctx.mkImplies( + isPresent, ctx.mkEq(ctx.mkApp(typeSystem.optionalOfRefFunc(), value), ref))); } return result; @@ -250,12 +260,21 @@ private TranslatedValue translateIdent(CelExpr celExpr, CelAbstractSyntaxTree as // Nothing binds `n`, so if it's typed type(T), it names T (e.g. `int`). if (type instanceof TypeType) { TypeType typeType = (TypeType) type; - if (typeType.type().kind() != CelKind.DYN) { + if (typeType.type().kind() != CelKind.DYN || n.equals("type")) { return TranslatedValue.create( - typeSystem.mkString(typeType.containingTypeName()), + typeSystem.mkType(typeType.containingTypeName()), typeSystem, /* isApproximate= */ ctx.mkFalse()); } + // `dyn` and variables holding a type check as type(dyn). + if (n.equals("dyn")) { + // The spec says `dyn` has no value at runtime. + return TranslatedValue.create( + ctx.mkConst("!dyn", typeSystem.celValueSort()), + typeSystem, + context.recordApproximation( + "the `dyn` type as a value", /* condition= */ ctx.mkTrue())); + } } Expr v = ctx.mkConst(n, typeSystem.celValueSort()); context.addInputVariable(v, type); @@ -524,7 +543,7 @@ private static String uninterpretedFunctionSymbol(long exprId, CelAbstractSyntax */ private static boolean mayEmbedArgs(String functionName, CelType resultType) { return (!CelZ3OperatorTranslator.isStaticallyKnown(resultType) - || !resultType.parameters().isEmpty()) + || (!resultType.parameters().isEmpty() && resultType.kind() != CelKind.TYPE)) && !functionName.equals(Operator.INDEX.getFunction()) && !functionName.equals(Operator.CONDITIONAL.getFunction()); } @@ -537,7 +556,17 @@ private static boolean mayEmbedArgs(String functionName, CelType resultType) { CelTypeProvider typeProvider, boolean parameterizeUnknowns) { this.ctx = ctx; - this.typeSystem = new CelZ3TypeSystem(ctx, parameterizeUnknowns); + this.typeSystem = + new CelZ3TypeSystem( + ctx, + parameterizeUnknowns, + Stream.concat( + DefaultTypeProvider.getInstance().types().stream(), + typeProvider.types().stream() + .filter( + t -> t instanceof StructType && !CelTypes.isWellKnownType(t.name()))) + .map(CelType::name) + .collect(toImmutableSet())); this.context = new CelZ3TranslationContext(ctx, typeSystem, comprehensionUnrollLimit); this.typeConstraintGenerator = context.typeConstraintGenerator(); this.operatorTranslator = new CelZ3OperatorTranslator(context, functionRegistry); diff --git a/verifier/src/main/java/dev/cel/verifier/CelPolicyVerifierFactory.java b/verifier/src/main/java/dev/cel/verifier/CelPolicyVerifierFactory.java index cb323d3e0..8dc01a5e2 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelPolicyVerifierFactory.java +++ b/verifier/src/main/java/dev/cel/verifier/CelPolicyVerifierFactory.java @@ -19,7 +19,10 @@ /** Factory class for producing policy verifiers. */ public final class CelPolicyVerifierFactory { - /** Create a new {@link CelPolicyVerifierBuilder} instance. */ + /** + * Create a new {@link CelPolicyVerifierBuilder} instance. {@code astVerifier} must be built from + * the same {@code Cel} environment as {@code compiler}. + */ public static CelPolicyVerifierBuilder newVerifier( CelPolicyCompiler compiler, CelVerifier astVerifier) { return CelPolicyVerifierImpl.newBuilder(compiler, astVerifier); diff --git a/verifier/src/main/java/dev/cel/verifier/CelVerifierBuilder.java b/verifier/src/main/java/dev/cel/verifier/CelVerifierBuilder.java index e520ea647..4439a8758 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelVerifierBuilder.java +++ b/verifier/src/main/java/dev/cel/verifier/CelVerifierBuilder.java @@ -15,7 +15,6 @@ package dev.cel.verifier; import com.google.errorprone.annotations.CanIgnoreReturnValue; -import dev.cel.common.types.CelTypeProvider; import java.time.Duration; /** Interface for building an instance of CelVerifier. */ @@ -41,16 +40,6 @@ public interface CelVerifierBuilder { @CanIgnoreReturnValue CelVerifierBuilder addUnknownIdentifier(String identifier); - /** - * Sets the type provider for looking up {@code CelType} definitions by name. - * - *

The verifier uses this to resolve structural type definitions (such as protocol buffer - * messages) during verification. If not set, the verifier will fall back to type information - * present in the AST, which may lose details such as wrapper types. - */ - @CanIgnoreReturnValue - CelVerifierBuilder setTypeProvider(CelTypeProvider typeProvider); - /** * Sets the unroll limit for comprehensions (such as {@code map}, {@code filter}, {@code all}, * {@code exists}). @@ -92,9 +81,9 @@ public interface CelVerifierBuilder { * *

Inputs are checked only when all their values are exact and no unknown identifiers are * registered. When the runtime can't evaluate them, e.g. a function has no binding, the message - * says why. Policy invariants aren't checked yet. The runtime must follow the CEL spec (e.g. - * {@code CelOptions.DEFAULT}, which has no iteration limit), and a function with bindings must - * have one for each overload, which is synchronous, deterministic and doesn't throw. + * says why. The runtime must follow the CEL spec (e.g. {@code CelOptions.DEFAULT}, which has no + * iteration limit), and a function with bindings must have one for each overload, which is + * synchronous, deterministic and doesn't throw. */ @CanIgnoreReturnValue CelVerifierBuilder enableCegar(boolean value); diff --git a/verifier/src/main/java/dev/cel/verifier/CelVerifierFactory.java b/verifier/src/main/java/dev/cel/verifier/CelVerifierFactory.java index d761428d6..245e52e30 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelVerifierFactory.java +++ b/verifier/src/main/java/dev/cel/verifier/CelVerifierFactory.java @@ -26,17 +26,9 @@ public final class CelVerifierFactory { /** - * Create a builder for configuring a {@link CelVerifier}. - * - * @deprecated Prefer passing a {@link Cel} environment using {@link #newVerifier(Cel)} to enable - * canonicalization and expression re-typechecking during verification. + * Create a builder for configuring a {@link CelVerifier} with a CEL environment. The ASTs to + * verify must be compiled in {@code cel}. */ - @Deprecated - public static CelVerifierBuilder newVerifier() { - return CelVerifierZ3Impl.newBuilder(); - } - - /** Create a builder for configuring a {@link CelVerifier} with a CEL environment. */ public static CelVerifierBuilder newVerifier(Cel cel) { return CelVerifierZ3Impl.newBuilder(cel); } diff --git a/verifier/src/main/java/dev/cel/verifier/CelVerifierZ3Impl.java b/verifier/src/main/java/dev/cel/verifier/CelVerifierZ3Impl.java index 41d64c19d..e520bbe4b 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelVerifierZ3Impl.java +++ b/verifier/src/main/java/dev/cel/verifier/CelVerifierZ3Impl.java @@ -16,16 +16,13 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.collect.ImmutableList.toImmutableList; import com.google.auto.value.AutoValue; -import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.Immutable; -import com.google.protobuf.Descriptors.Descriptor; import com.microsoft.z3.BoolExpr; import com.microsoft.z3.Context; import com.microsoft.z3.Model; @@ -33,12 +30,7 @@ import com.microsoft.z3.Solver; import com.microsoft.z3.Status; import dev.cel.bundle.Cel; -import dev.cel.bundle.CelFactory; import dev.cel.common.CelAbstractSyntaxTree; -import dev.cel.common.internal.DefaultDescriptorPool; -import dev.cel.common.internal.WellKnownProto; -import dev.cel.common.types.CelType; -import dev.cel.common.types.CelTypeProvider; import dev.cel.optimizer.CelOptimizationException; import dev.cel.optimizer.CelOptimizer; import dev.cel.optimizer.CelOptimizerFactory; @@ -46,6 +38,7 @@ import dev.cel.verifier.axioms.CelZ3FunctionAxiom; import dev.cel.verifier.axioms.CelZ3StandardAxioms; import java.time.Duration; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; @@ -56,55 +49,15 @@ @Immutable final class CelVerifierZ3Impl implements CelVerifier { - @VisibleForTesting - static final CelTypeProvider EMPTY_TYPE_PROVIDER = - new CelTypeProvider() { - @Override - public ImmutableList types() { - return ImmutableList.of(); - } - - @Override - public Optional findType(String typeName) { - return Optional.empty(); - } - }; - - private static final ImmutableList WELL_KNOWN_DESCRIPTORS = - ImmutableList.of( - WellKnownProto.DURATION, - WellKnownProto.JSON_LIST_VALUE, - WellKnownProto.JSON_STRUCT_VALUE, - WellKnownProto.JSON_VALUE, - WellKnownProto.TIMESTAMP, - WellKnownProto.FLOAT_VALUE, - WellKnownProto.INT32_VALUE, - WellKnownProto.INT64_VALUE, - WellKnownProto.STRING_VALUE, - WellKnownProto.BOOL_VALUE, - WellKnownProto.BYTES_VALUE, - WellKnownProto.DOUBLE_VALUE, - WellKnownProto.UINT32_VALUE, - WellKnownProto.UINT64_VALUE) - .stream() - .map(DefaultDescriptorPool::getWellKnownProtoDescriptor) - .collect(toImmutableList()); - private final Duration timeout; private final int comprehensionUnrollLimit; private final ImmutableSet unknownIdentifiers; private final CelZ3FunctionRegistry functionRegistry; - private final CelTypeProvider typeProvider; private final boolean enableCegar; @SuppressWarnings("Immutable") // Cel environment is immutable, just not marked as such private final Cel cel; - static Builder newBuilder() { - return new Builder( - CelFactory.plannerCelBuilder().addMessageTypes(WELL_KNOWN_DESCRIPTORS).build()); - } - static Builder newBuilder(Cel cel) { return new Builder(checkNotNull(cel)); } @@ -115,7 +68,6 @@ static final class Builder implements CelVerifierBuilder { private final ImmutableSet.Builder unknownIdentifiers; private final ImmutableList.Builder functionAxioms; private final Cel cel; - private CelTypeProvider typeProvider; private boolean enableCegar; @Override @@ -135,13 +87,6 @@ public CelVerifierBuilder addUnknownIdentifier(String identifier) { return this; } - @Override - @CanIgnoreReturnValue - public CelVerifierBuilder setTypeProvider(CelTypeProvider typeProvider) { - this.typeProvider = checkNotNull(typeProvider); - return this; - } - @Override @CanIgnoreReturnValue public CelVerifierBuilder setComprehensionUnrollLimit(int unrollLimit) { @@ -182,7 +127,6 @@ public CelVerifier build() { comprehensionUnrollLimit, unknownIdentifiers.build(), registry, - typeProvider, enableCegar, cel); } @@ -192,7 +136,6 @@ private Builder(Cel cel) { this.comprehensionUnrollLimit = 5; this.unknownIdentifiers = ImmutableSet.builder(); this.functionAxioms = ImmutableList.builder(); - this.typeProvider = cel.getTypeProvider(); this.cel = cel; } } @@ -260,14 +203,15 @@ public CelVerificationResult verifyEquivalence( /* isCounterexample= */ true, /* candidate= */ "a divergence", /* exactMatchMessage= */ "Equivalence violation detected.", - runtimeCheck(results -> !results.get(0).equals(results.get(1)), astA, astB)); + runtimeCheck( + ImmutableMap.of(), results -> !results.get(0).equals(results.get(1)), astA, astB)); } } CelVerificationResult verifyImplication( CelAbstractSyntaxTree assumeAst, CelAbstractSyntaxTree assertAst, - Map boundSymbols, + ImmutableMap boundSymbols, String subjectName) throws CelVerificationException { checkArgument(assumeAst.isChecked(), "assumeAst must be type-checked."); @@ -313,7 +257,11 @@ CelVerificationResult verifyImplication( /* isCounterexample= */ true, /* candidate= */ "a counterexample", /* exactMatchMessage= */ String.format("%s violation detected.", subjectName), - /* runtimeCheck= */ RuntimeChecker.UNCHECKED); + runtimeCheck( + boundSymbols, + results -> results.get(0).equals(true) && !results.get(1).equals(true), + assumeAst, + assertAst)); } } @@ -335,7 +283,7 @@ private CelVerificationResult checkSatisfiability( /* isCounterexample= */ true, /* candidate= */ "a counterexample", /* exactMatchMessage= */ "Condition is not always true.", - runtimeCheck(results -> !results.get(0).equals(true), ast)); + runtimeCheck(ImmutableMap.of(), results -> !results.get(0).equals(true), ast)); } BoolExpr isUnmodeledUnknown = ctx.mkAnd(tv.isZ3Unknown(), tv.isApproximate()); return search( @@ -347,7 +295,7 @@ private CelVerificationResult checkSatisfiability( /* isCounterexample= */ false, /* candidate= */ "a satisfying input", /* exactMatchMessage= */ "Condition is satisfiable.", - runtimeCheck(results -> results.get(0).equals(true), ast)); + runtimeCheck(ImmutableMap.of(), results -> results.get(0).equals(true), ast)); } } @@ -433,8 +381,6 @@ private static CelVerificationResult match( } private interface RuntimeChecker { - RuntimeChecker UNCHECKED = (witness, countInternalErrors) -> RuntimeCheck.UNCHECKED; - RuntimeCheck check(CelWitness witness, boolean countInternalErrors); } @@ -462,9 +408,11 @@ static RuntimeCheck failed(String reason) { // Checks the witness's inputs with the runtime, if refinement is on and they're exact. Unknowns // aren't inputs the runtime can take. private RuntimeChecker runtimeCheck( - Predicate> isMatch, CelAbstractSyntaxTree... asts) { + ImmutableMap boundSymbols, + Predicate> isMatch, + CelAbstractSyntaxTree... asts) { if (!enableCegar || !unknownIdentifiers.isEmpty()) { - return RuntimeChecker.UNCHECKED; + return (witness, countInternalErrors) -> RuntimeCheck.UNCHECKED; } return (witness, countInternalErrors) -> { Optional> inputs = RuntimeOracle.exactInputs(witness); @@ -473,7 +421,9 @@ private RuntimeChecker runtimeCheck( } try { return RuntimeCheck.of( - isMatch.test(RuntimeOracle.evaluate(cel, inputs.get(), countInternalErrors, asts))); + isMatch.test( + RuntimeOracle.evaluate( + cel, inputs.get(), boundSymbols, countInternalErrors, asts))); } catch (CelEvaluationException e) { return RuntimeCheck.failed(e.getMessage()); } @@ -487,19 +437,31 @@ private static Status checkSat(Solver solver, CelZ3TypeSystem typeSystem, BoolEx solver.push(); solver.add(assertions); Status status = solver.check(); - // Each round defines at least one more double, so this terminates. Each round gets the full - // timeout; the rounds are bounded by the doubles in int/double comparisons. + List preferences = new ArrayList<>(); + // Each round defines at least one more double or prefers one more type value's name, so this + // terminates. Each round gets the full timeout; the rounds are bounded by the doubles in + // int/double comparisons and the values that may be types. while (status == Status.SATISFIABLE) { - ImmutableList definitions = - typeSystem.defineDoublesContradictedBy(solver.getModel()); + Model model = solver.getModel(); + ImmutableList definitions = typeSystem.defineDoublesContradictedBy(model); if (definitions.isEmpty()) { - break; + ImmutableList moreKnownNames = typeSystem.preferKnownTypeNamesOver(model); + if (moreKnownNames.isEmpty()) { + break; + } + preferences.addAll(moreKnownNames); + } else { + solver.pop(); + solver.add(definitions.toArray(new BoolExpr[0])); + solver.push(); + solver.add(assertions); + } + status = solver.check(preferences.toArray(new BoolExpr[0])); + if (status != Status.SATISFIABLE && !preferences.isEmpty()) { + // No model avoids the unknown names, so they may well be real. + preferences.clear(); + status = solver.check(); } - solver.pop(); - solver.add(definitions.toArray(new BoolExpr[0])); - solver.push(); - solver.add(assertions); - status = solver.check(); } if (status == Status.UNSATISFIABLE) { solver.pop(); @@ -531,7 +493,7 @@ private CelAstToZ3Translator newTranslator(Context ctx, boolean parameterizeUnkn comprehensionUnrollLimit, unknownIdentifiers, functionRegistry, - typeProvider, + cel.getTypeProvider(), parameterizeUnknowns); } @@ -558,14 +520,12 @@ private CelVerifierZ3Impl( int comprehensionUnrollLimit, ImmutableSet unknownIdentifiers, CelZ3FunctionRegistry functionRegistry, - CelTypeProvider typeProvider, boolean enableCegar, Cel cel) { this.timeout = timeout; this.comprehensionUnrollLimit = comprehensionUnrollLimit; this.unknownIdentifiers = unknownIdentifiers; this.functionRegistry = functionRegistry; - this.typeProvider = typeProvider; this.enableCegar = enableCegar; this.cel = cel; } diff --git a/verifier/src/main/java/dev/cel/verifier/CelZ3CounterexampleGenerator.java b/verifier/src/main/java/dev/cel/verifier/CelZ3CounterexampleGenerator.java index 94bcef460..f9e2e10b7 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelZ3CounterexampleGenerator.java +++ b/verifier/src/main/java/dev/cel/verifier/CelZ3CounterexampleGenerator.java @@ -16,6 +16,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; +import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.primitives.UnsignedLong; @@ -30,6 +31,7 @@ import dev.cel.common.internal.ProtoTimeUtils; import dev.cel.common.values.CelByteString; import dev.cel.common.values.NullValue; +import dev.cel.runtime.CelAttribute; import java.math.BigInteger; import java.time.Duration; import java.time.Instant; @@ -126,6 +128,12 @@ private Value extractValue(Expr expr) { return extractString(args[0], /* isBytes= */ false); } else if (decl.equals(typeSystem.bytesCons().ConstructorDecl())) { return extractString(args[0], /* isBytes= */ true); + } else if (decl.equals(typeSystem.typeCons().ConstructorDecl())) { + String name = args[0].getString(); + return Value.inexact( + Splitter.on('.').splitToStream(name).allMatch(CelAttribute.Qualifier::isLegalIdentifier) + ? name + : ""); } else if (decl.equals(typeSystem.timestampCons().ConstructorDecl())) { BigInteger nanos = ((IntNum) args[0]).getBigInteger(); BigInteger nanoAdjustment = nanos.mod(NANOS_PER_SECOND); diff --git a/verifier/src/main/java/dev/cel/verifier/CelZ3OperatorTranslator.java b/verifier/src/main/java/dev/cel/verifier/CelZ3OperatorTranslator.java index 6f1e17e43..f7667367d 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelZ3OperatorTranslator.java +++ b/verifier/src/main/java/dev/cel/verifier/CelZ3OperatorTranslator.java @@ -314,6 +314,8 @@ private BoolExpr mkTypeGuard(Expr arg, CelType expectedType) { return typeSystem.isStruct(arg); case NULL_TYPE: return typeSystem.isNull(arg); + case TYPE: + return typeSystem.isType(arg); case OPAQUE: if (expectedType.name().equals(OptionalType.NAME)) { return typeSystem.isOptional(arg); @@ -997,6 +999,8 @@ private TranslatedValue translateEquality( } else { BoolExpr bothLists = ctx.mkAnd(typeSystem.isList(z3Arg0), typeSystem.isList(z3Arg1)); BoolExpr bothMaps = ctx.mkAnd(typeSystem.isMap(z3Arg0), typeSystem.isMap(z3Arg1)); + BoolExpr bothOptionals = + ctx.mkAnd(typeSystem.isOptional(z3Arg0), typeSystem.isOptional(z3Arg1)); BoolExpr structuralEq; if (isShallow) { structuralEq = @@ -1008,14 +1012,14 @@ private TranslatedValue translateEquality( bothLists, bothMaps, ctx.mkAnd(typeSystem.isMessage(z3Arg0), typeSystem.isMessage(z3Arg1)), - ctx.mkAnd(typeSystem.isOptional(z3Arg0), typeSystem.isOptional(z3Arg1)))), + bothOptionals)), z3Arg0, z3Arg1, /* exact= */ ctx.mkEq(z3Arg0, z3Arg1), taints); } else { - // Lists and maps compare by CEL equality, unless their guaranteed types make it their - // terms'. + // Lists, maps and optionals compare by CEL equality, unless their guaranteed types make it + // their terms'. structuralEq = typeSystem.getStructuralEquality(z3Arg0, z3Arg1); if (!isExact(guaranteedType(arg0, ast), guaranteedType(arg1, ast))) { if (type0.kind() == CelKind.LIST || type1.kind() == CelKind.LIST) { @@ -1029,12 +1033,20 @@ private TranslatedValue translateEquality( ? mapEqualityAtLiteralKeys(arg0, arg1) : unrollMapEquality(arg0, arg1, ast, taints); structuralEq = (BoolExpr) ctx.mkITE(bothMaps, mapEquality, structuralEq); + } else if (type0 instanceof OptionalType || type1 instanceof OptionalType) { + structuralEq = + (BoolExpr) + ctx.mkITE( + bothOptionals, + optionalEquality(arg0, arg1, bothOptionals, ast, taints), + structuralEq); } else if (!isStaticallyKnown(type0) && !isStaticallyKnown(type1)) { - // Performance only: a side with a known type isn't a list or map here. + // Performance only: a side with a known type isn't a list, map or optional here. structuralEq = approximateEqualityWhere( context.recordApproximation( - "comparisons of lists or maps typed dyn", ctx.mkOr(bothLists, bothMaps)), + "comparisons of lists, maps or optionals typed dyn", + ctx.mkOr(bothLists, bothMaps, bothOptionals)), z3Arg0, z3Arg1, structuralEq, @@ -1062,6 +1074,49 @@ private TranslatedValue translateEquality( .withApproximation(CelZ3Exprs.mkOrFlattened(ctx, taints)); } + // Both empty, or both holding CEL-equal values. + private BoolExpr optionalEquality( + TranslatedValue opt0, + TranslatedValue opt1, + BoolExpr bothOptionals, + CelAbstractSyntaxTree ast, + List taints) { + Expr ref0 = typeSystem.getOptionalRef(opt0.z3Expr()); + Expr ref1 = typeSystem.getOptionalRef(opt1.z3Expr()); + BoolExpr hasValue0 = typeSystem.optHasValue(ref0); + BoolExpr hasValue1 = typeSystem.optHasValue(ref1); + TranslatedValue valueEquality = + translateEquality( + optionalValue(opt0, ref0, ast), + optionalValue(opt1, ref1, ast), + ast, + /* isEquals= */ true, + /* shallow= */ false); + taints.add(ctx.mkAnd(bothOptionals, hasValue0, hasValue1, valueEquality.isApproximate())); + return ctx.mkAnd( + ctx.mkEq(hasValue0, hasValue1), + ctx.mkImplies(hasValue0, typeSystem.isTrue(valueEquality.z3Expr()))); + } + + // opt's value, typed by its argument if opt is an `optional.of` call. + private TranslatedValue optionalValue( + TranslatedValue opt, Expr ref, CelAbstractSyntaxTree ast) { + Optional arg = + opt.celExpr() + .filter(e -> + ast.getReference(e.id()) + .map(CelReference::overloadIds) + .equals(Optional.of(ImmutableList.of("optional_of")))) + .map(e -> e.call().args().get(0)); + // A variable keeps its own term, so its declared type is still trusted. + Expr value = + arg.filter(e -> e.getKind() == ExprKind.Kind.IDENT) + .flatMap(e -> context.lookupSymbol(e.ident().name())) + .>map(TranslatedValue::z3Expr) + .orElseGet(() -> typeSystem.getOptionalValue(ref)); + return TranslatedValue.create(value, arg, typeSystem, /* isApproximate= */ ctx.mkFalse()); + } + /** A list element or map value, read without regard to optionals. */ private static final class IndexAccess { private final BoolExpr valid; @@ -1243,6 +1298,10 @@ static boolean hasConcreteElements(CelType type) { /** Whether {@code type} and, recursively, its type parameters are statically known. */ private static boolean isConcrete(CelType type) { + if (type.kind() == CelKind.TYPE) { + // A type value holds no value of its parameter. + return true; + } return isStaticallyKnown(type) && type.parameters().stream().allMatch(CelZ3OperatorTranslator::isConcrete); } @@ -1261,6 +1320,7 @@ private static boolean hasStructuralEquality(CelType type) { case BYTES: case TIMESTAMP: case DURATION: + case TYPE: return true; case LIST: case MAP: diff --git a/verifier/src/main/java/dev/cel/verifier/CelZ3TypeConstraintGenerator.java b/verifier/src/main/java/dev/cel/verifier/CelZ3TypeConstraintGenerator.java index 386e2f6f6..58535d7b3 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelZ3TypeConstraintGenerator.java +++ b/verifier/src/main/java/dev/cel/verifier/CelZ3TypeConstraintGenerator.java @@ -194,6 +194,9 @@ BoolExpr createTypeConstraintForType(Expr val, CelType type) { return CelZ3Exprs.mkAndFlattened(ctx, boundsAndTypes); } + if (type.kind() == CelKind.TYPE) { + return ctx.mkAnd(typeSystem.isType(val), typeSystem.isValidScalar(val)); + } if (type.kind() == CelKind.STRUCT) { return ctx.mkAnd( typeSystem.isMessage(val), diff --git a/verifier/src/main/java/dev/cel/verifier/CelZ3TypeSystem.java b/verifier/src/main/java/dev/cel/verifier/CelZ3TypeSystem.java index f5fd569cc..10445db38 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelZ3TypeSystem.java +++ b/verifier/src/main/java/dev/cel/verifier/CelZ3TypeSystem.java @@ -18,6 +18,7 @@ import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; import com.google.common.collect.ObjectArrays; import com.google.common.math.DoubleMath; import com.google.common.primitives.UnsignedLongs; @@ -100,6 +101,10 @@ public final class CelZ3TypeSystem { private static final String IS_STRING = "isString"; private static final String GET_STRING = "getString"; + private static final String CONS_TYPE = "CelType"; + private static final String IS_TYPE = "isType"; + private static final String GET_TYPE = "getType"; + private static final String CONS_BYTES = "Bytes"; private static final String IS_BYTES = "isBytes"; private static final String GET_BYTES = "getBytes"; @@ -168,6 +173,7 @@ public final class CelZ3TypeSystem { private final Constructor doubleCons; private final Constructor stringCons; private final Constructor bytesCons; + private final Constructor typeCons; private final Constructor timestampCons; private final Constructor durationCons; private final Constructor errorCons; @@ -200,6 +206,10 @@ public final class CelZ3TypeSystem { private final FuncDecl hasFractionFunc; // Doubles whose truncation and fraction are still uninterpreted, in order of first use. private final Set undefinedDoubles; + // The names of the runtime types the environment declares. + private final ImmutableSet typeNames; + // Valid values that preferKnownTypeNamesOver may still steer away from unknown type names. + private final Set> unrestrictedTypeValues; private final boolean parameterizeUnknowns; @@ -264,6 +274,10 @@ Constructor bytesCons() { return bytesCons; } + Constructor typeCons() { + return typeCons; + } + Constructor timestampCons() { return timestampCons; } @@ -435,6 +449,21 @@ public Expr mkString(String val) { return ctx.mkApp(stringCons.ConstructorDecl(), ctx.mkString(val)); } + /** Creates a CelValue for the type named {@code name}. */ + public Expr mkType(String name) { + return wrapType(ctx.mkString(name)); + } + + /** Wraps a Z3 string type name into a CelValue type. */ + public Expr wrapType(Expr name) { + return ctx.mkApp(typeCons.ConstructorDecl(), name); + } + + /** Checks if the given CelValue is a type. */ + public BoolExpr isType(Expr val) { + return (BoolExpr) ctx.mkApp(typeCons.getTesterDecl(), val); + } + /** Creates a CelValue containing bytes. */ public Expr mkBytes(String val) { return ctx.mkApp(bytesCons.ConstructorDecl(), ctx.mkString(val)); @@ -822,6 +851,7 @@ public BoolExpr checkDurationOverflow(ArithExpr result) { *

Values of other kinds always qualify. */ BoolExpr isValidScalar(Expr val) { + unrestrictedTypeValues.add(val); FPExpr d = getDouble(val); return CelZ3Exprs.mkAndFlattened( ctx, @@ -1006,6 +1036,30 @@ ImmutableList defineDoublesContradictedBy(Model model) { return definitions.build(); } + /** + * Returns assumptions that the valid values {@code model} makes types of unknown names (bogus in + * a witness) have known names instead. They only pick a better model: constraining every value + * eagerly slows the solver down a lot, and an unknown name may still be real. + */ + ImmutableList preferKnownTypeNamesOver(Model model) { + ImmutableList.Builder constraints = ImmutableList.builder(); + for (Iterator> it = unrestrictedTypeValues.iterator(); it.hasNext(); ) { + Expr val = it.next(); + Expr value = model.evaluate(val, /* completion= */ true); + if (value.getFuncDecl().equals(typeCons.ConstructorDecl()) + && !typeNames.contains(value.getArgs()[0].getString())) { + it.remove(); + Expr name = ctx.mkApp(typeCons.getAccessorDecls()[0], val); + constraints.add( + ctx.mkOr( + typeNames.stream() + .map(n -> ctx.mkEq(name, ctx.mkString(n))) + .toArray(BoolExpr[]::new))); + } + } + return constraints.build(); + } + /** Converts a Z3 double to the Java double with the same IEEE 754 bits (or NaN). */ double toJavaDouble(FPNum fpNum) { // Z3 doesn't simplify the bits of NaN to a numeral. @@ -1082,7 +1136,7 @@ private static FuncDeclKey create(String name, Sort[] domain, Sort range) { } } - CelZ3TypeSystem(Context ctx, boolean parameterizeUnknowns) { + CelZ3TypeSystem(Context ctx, boolean parameterizeUnknowns, ImmutableSet typeNames) { this.ctx = ctx; this.funcDeclCache = new HashMap<>(); this.boolCons = @@ -1113,6 +1167,9 @@ private static FuncDeclKey create(String name, Sort[] domain, Sort range) { this.bytesCons = ctx.mkConstructor( CONS_BYTES, IS_BYTES, new String[] {GET_BYTES}, new Sort[] {ctx.getStringSort()}, null); + this.typeCons = + ctx.mkConstructor( + CONS_TYPE, IS_TYPE, new String[] {GET_TYPE}, new Sort[] {ctx.getStringSort()}, null); this.timestampCons = ctx.mkConstructor( CONS_TIMESTAMP, @@ -1173,6 +1230,7 @@ private static FuncDeclKey create(String name, Sort[] domain, Sort range) { this.doubleCons, this.stringCons, this.bytesCons, + this.typeCons, this.timestampCons, this.durationCons, this.errorCons, @@ -1231,6 +1289,8 @@ private static FuncDeclKey create(String name, Sort[] domain, Sort range) { this.hasFractionFunc = ctx.mkFuncDecl(FUNC_HAS_FRACTION, ctx.mkFPSortDouble(), ctx.getBoolSort()); this.undefinedDoubles = new LinkedHashSet<>(); + this.typeNames = typeNames; + this.unrestrictedTypeValues = new LinkedHashSet<>(); this.parameterizeUnknowns = parameterizeUnknowns; } } diff --git a/verifier/src/main/java/dev/cel/verifier/RuntimeOracle.java b/verifier/src/main/java/dev/cel/verifier/RuntimeOracle.java index 00ac15ca3..40c0c76c8 100644 --- a/verifier/src/main/java/dev/cel/verifier/RuntimeOracle.java +++ b/verifier/src/main/java/dev/cel/verifier/RuntimeOracle.java @@ -14,11 +14,14 @@ package dev.cel.verifier; +import com.google.common.base.Supplier; +import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import dev.cel.common.CelAbstractSyntaxTree; import dev.cel.common.CelErrorCode; +import dev.cel.common.exceptions.CelRuntimeException; import dev.cel.runtime.CelEvaluationException; import dev.cel.runtime.CelFunctionResolver; import dev.cel.runtime.CelResolvedOverload; @@ -28,7 +31,7 @@ import java.util.Collection; import java.util.Map; import java.util.Optional; -import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; /** * Evaluates expressions with the CEL runtime on a witness's inputs, to check the solver's @@ -41,6 +44,14 @@ private enum EvaluationError { ERROR } + private final CelRuntime runtime; + private final Map inputs; + private final ImmutableMap> boundSymbols; + private final boolean countInternalErrors; + // Why the runtime can't evaluate the expression, even if `||` or `&&` keeps another error. + private final AtomicReference uncheckableCause; + private final CelFunctionResolver lateBoundFunctions; + /** The witness's inputs, if every value is exact. */ static Optional> exactInputs(CelWitness witness) { return witness.variables().values().stream().allMatch(v -> v.value().isPresent()) @@ -50,59 +61,133 @@ static Optional> exactInputs(CelWitness witness) { } /** - * Returns the values of {@code asts} for {@code inputs}, with errors as one value. Throws if the - * runtime can't evaluate one, e.g. a function has no binding or its iteration limit is hit, or if - * it fails with an internal error and {@code countInternalErrors} is false. + * Returns the values of {@code asts} for {@code inputs} and {@code boundSymbols}, with errors as + * one value. Throws if the runtime can't evaluate one, e.g. a function has no binding or its + * iteration limit is hit, or if it fails with an internal error and {@code countInternalErrors} + * is false. */ static ImmutableList evaluate( CelRuntime runtime, Map inputs, + ImmutableMap boundSymbols, boolean countInternalErrors, CelAbstractSyntaxTree... asts) throws CelEvaluationException { + RuntimeOracle oracle = new RuntimeOracle(runtime, inputs, boundSymbols, countInternalErrors); ImmutableList.Builder results = ImmutableList.builder(); for (CelAbstractSyntaxTree ast : asts) { - Program program = runtime.createProgram(ast); - // Notes calls to late-bound functions, which have no binding here. The legacy interpreter - // also consults them after any failed dispatch, so its dispatch errors go unchecked. - AtomicBoolean callsLateBound = new AtomicBoolean(); - CelFunctionResolver lateBoundFunctions = - new CelFunctionResolver() { - @Override - public Optional findOverloadMatchingArgs( - String functionName, Collection overloadIds, Object[] args) { - return findOverloadMatchingArgs(functionName, args); - } - - @Override - public Optional findOverloadMatchingArgs( - String functionName, Object[] args) { - callsLateBound.set(true); - return Optional.empty(); - } - }; - Object result; try { - result = program.eval(inputs, lateBoundFunctions); - } catch (CelEvaluationException e) { - CelErrorCode code = e.getErrorCode(); - // The runtime reports some CEL errors as internal, but also misused bindings (e.g. async). - if (callsLateBound.get() - || code == CelErrorCode.ITERATION_BUDGET_EXCEEDED - || (!countInternalErrors && code == CelErrorCode.INTERNAL_ERROR)) { - throw e; + results.add(oracle.eval(ast, oracle.boundSymbols)); + } catch (CelEvaluationException unused) { + CelEvaluationException cause = oracle.uncheckableCause.get(); + if (cause != null) { + throw cause; } - result = EvaluationError.ERROR; - } - // A binding may return null or unknowns. - if (result == null || result instanceof CelUnknownSet) { - throw new CelEvaluationException( - result == null ? "a function returned null" : "it evaluated to unknowns"); + results.add(EvaluationError.ERROR); } - results.add(result); } return results.build(); } - private RuntimeOracle() {} + private Object eval(CelAbstractSyntaxTree ast, ImmutableMap> symbols) + throws CelEvaluationException { + Program program; + try { + program = runtime.createProgram(ast); + } catch (CelEvaluationException e) { + uncheckableCause.compareAndSet(null, e); + throw e; + } + CelEvaluationException outer = uncheckableCause.get(); + Object result; + try { + result = + program.eval( + name -> { + Supplier symbol = symbols.get(name); + return symbol == null + ? Optional.ofNullable(inputs.get(name)) + : Optional.of(symbol.get()); + }, + lateBoundFunctions); + } catch (CelEvaluationException e) { + CelErrorCode code = e.getErrorCode(); + // The runtime reports some CEL errors as internal, but also misused bindings (e.g. async). + if (code == CelErrorCode.ITERATION_BUDGET_EXCEEDED + || (!countInternalErrors && code == CelErrorCode.INTERNAL_ERROR)) { + uncheckableCause.compareAndSet(null, e); + } + throw e; + } + if (result == null || result instanceof CelUnknownSet) { + CelEvaluationException e = + new CelEvaluationException( + result == null ? "a function returned null" : "it evaluated to unknowns"); + uncheckableCause.compareAndSet(null, e); + throw e; + } + // An expression with a value doesn't pass on errors it absorbed. + uncheckableCause.set(outer); + return result; + } + + // Keeps the error code, so a symbol's CEL errors aren't taken for internal ones. + private static final class SymbolError extends CelRuntimeException { + private SymbolError(CelEvaluationException e) { + super(e, e.getErrorCode()); + } + } + + private RuntimeOracle( + CelRuntime runtime, + Map inputs, + ImmutableMap boundSymbols, + boolean countInternalErrors) { + this.runtime = runtime; + this.inputs = inputs; + this.countInternalErrors = countInternalErrors; + this.uncheckableCause = new AtomicReference<>(); + // Like the verifier, a symbol reads only the symbols before it. + ImmutableMap.Builder> symbols = ImmutableMap.builder(); + for (Map.Entry symbol : boundSymbols.entrySet()) { + ImmutableMap> visible = symbols.buildOrThrow(); + symbols.put( + symbol.getKey(), + Suppliers.memoize(() -> { + CelEvaluationException outer = uncheckableCause.get(); + try { + return eval(symbol.getValue(), visible); + } catch (CelEvaluationException e) { + CelEvaluationException cause = uncheckableCause.get(); + if (cause != outer) { + uncheckableCause.set( + new CelEvaluationException( + String.format("reading `%s`: %s", symbol.getKey(), cause.getMessage()), + cause)); + } + throw new SymbolError(e); + } + })); + } + this.boundSymbols = symbols.buildOrThrow(); + // Late-bound functions have no binding here. + this.lateBoundFunctions = + new CelFunctionResolver() { + @Override + public Optional findOverloadMatchingArgs( + String functionName, Collection overloadIds, Object[] args) { + return findOverloadMatchingArgs(functionName, args); + } + + @Override + public Optional findOverloadMatchingArgs( + String functionName, Object[] args) { + uncheckableCause.compareAndSet( + null, + new CelEvaluationException( + "No matching overload for function '" + functionName + "'")); + return Optional.empty(); + } + }; + } } diff --git a/verifier/src/main/java/dev/cel/verifier/axioms/TypeAxiom.java b/verifier/src/main/java/dev/cel/verifier/axioms/TypeAxiom.java index baebfff60..00b6f914d 100644 --- a/verifier/src/main/java/dev/cel/verifier/axioms/TypeAxiom.java +++ b/verifier/src/main/java/dev/cel/verifier/axioms/TypeAxiom.java @@ -22,6 +22,7 @@ import dev.cel.common.types.MapType; import dev.cel.common.types.OptionalType; import dev.cel.common.types.SimpleType; +import dev.cel.common.types.TypeType; import dev.cel.verifier.CelZ3Exprs; import dev.cel.verifier.CelZ3TypeSystem; import java.util.Optional; @@ -31,6 +32,7 @@ final class TypeAxiom { private static final String TYPE_NAME_LIST = ListType.create().name(); private static final String TYPE_NAME_MAP = MapType.create(SimpleType.DYN, SimpleType.DYN).name(); + private static final String TYPE_NAME_TYPE = TypeType.create(SimpleType.DYN).name(); static final CelZ3FunctionAxiom INSTANCE = CelZ3FunctionAxiom.newBuilder(StandardFunction.TYPE.functionDecl()) @@ -52,19 +54,20 @@ private static Expr getTypeExpression(Context ctx, CelZ3TypeSystem typeSystem return CelZ3Exprs.SwitchBuilder.newBuilder(ctx) .addCase( typeSystem.isStruct(val), - typeSystem.wrapString(typeSystem.getMsgTypeName(typeSystem.getMessageRef(val)))) - .addCase(typeSystem.isOptional(val), typeSystem.mkString(OptionalType.NAME)) - .addCase(typeSystem.isNull(val), typeSystem.mkString(SimpleType.NULL_TYPE.name())) - .addCase(typeSystem.isTimestamp(val), typeSystem.mkString(SimpleType.TIMESTAMP.name())) - .addCase(typeSystem.isDuration(val), typeSystem.mkString(SimpleType.DURATION.name())) - .addCase(typeSystem.isMap(val), typeSystem.mkString(TYPE_NAME_MAP)) - .addCase(typeSystem.isList(val), typeSystem.mkString(TYPE_NAME_LIST)) - .addCase(typeSystem.isBytes(val), typeSystem.mkString(SimpleType.BYTES.name())) - .addCase(typeSystem.isString(val), typeSystem.mkString(SimpleType.STRING.name())) - .addCase(typeSystem.isDouble(val), typeSystem.mkString(SimpleType.DOUBLE.name())) - .addCase(typeSystem.isUint(val), typeSystem.mkString(SimpleType.UINT.name())) - .addCase(typeSystem.isInt(val), typeSystem.mkString(SimpleType.INT.name())) - .addCase(typeSystem.isBool(val), typeSystem.mkString(SimpleType.BOOL.name())) + typeSystem.wrapType(typeSystem.getMsgTypeName(typeSystem.getMessageRef(val)))) + .addCase(typeSystem.isOptional(val), typeSystem.mkType(OptionalType.NAME)) + .addCase(typeSystem.isNull(val), typeSystem.mkType(SimpleType.NULL_TYPE.name())) + .addCase(typeSystem.isTimestamp(val), typeSystem.mkType(SimpleType.TIMESTAMP.name())) + .addCase(typeSystem.isDuration(val), typeSystem.mkType(SimpleType.DURATION.name())) + .addCase(typeSystem.isMap(val), typeSystem.mkType(TYPE_NAME_MAP)) + .addCase(typeSystem.isList(val), typeSystem.mkType(TYPE_NAME_LIST)) + .addCase(typeSystem.isBytes(val), typeSystem.mkType(SimpleType.BYTES.name())) + .addCase(typeSystem.isString(val), typeSystem.mkType(SimpleType.STRING.name())) + .addCase(typeSystem.isDouble(val), typeSystem.mkType(SimpleType.DOUBLE.name())) + .addCase(typeSystem.isUint(val), typeSystem.mkType(SimpleType.UINT.name())) + .addCase(typeSystem.isInt(val), typeSystem.mkType(SimpleType.INT.name())) + .addCase(typeSystem.isBool(val), typeSystem.mkType(SimpleType.BOOL.name())) + .addCase(typeSystem.isType(val), typeSystem.mkType(TYPE_NAME_TYPE)) .build(typeSystem.mkError()); } diff --git a/verifier/src/test/java/dev/cel/verifier/CelPolicyVerifierImplTest.java b/verifier/src/test/java/dev/cel/verifier/CelPolicyVerifierImplTest.java index cd16e7d50..04bdd1fb5 100644 --- a/verifier/src/test/java/dev/cel/verifier/CelPolicyVerifierImplTest.java +++ b/verifier/src/test/java/dev/cel/verifier/CelPolicyVerifierImplTest.java @@ -47,6 +47,7 @@ import dev.cel.policy.CelPolicyParserFactory; import dev.cel.policy.CelPolicyValidationException; import dev.cel.policy.testing.K8sTagHandler; +import dev.cel.runtime.CelFunctionBinding; import dev.cel.testing.testdata.SingleFile; import dev.cel.testing.testdata.proto3.StandaloneGlobalEnum; import dev.cel.verifier.CelVerificationResult.VerificationStatus; @@ -62,10 +63,7 @@ public final class CelPolicyVerifierImplTest { private static final Cel CEL = CelFactory.plannerCelBuilder() - .setOptions( - CelOptions.current() - .populateMacroCalls(true) - .build()) + .setOptions(CelOptions.current().populateMacroCalls(true).build()) .setStandardMacros(CelStandardMacro.STANDARD_MACROS) .addCompilerLibraries(CelExtensions.bindings()) .addMessageTypes(TestAllTypes.getDescriptor()) @@ -80,6 +78,15 @@ public final class CelPolicyVerifierImplTest { .addVar( "test_all_types", StructTypeReference.create("cel.expr.conformance.proto3.TestAllTypes")) + .addVar("variables.s", SimpleType.INT) + .addFunctionDeclarations( + CelFunctionDecl.newFunctionDeclaration( + "zero", + CelOverloadDecl.newGlobalOverload("zero_int", SimpleType.INT, SimpleType.INT)), + CelFunctionDecl.newFunctionDeclaration( + "unbound", + CelOverloadDecl.newGlobalOverload("unbound_int", SimpleType.INT, SimpleType.INT))) + .addFunctionBindings(CelFunctionBinding.from("zero_int", Long.class, v -> 0L)) .build(); private static final CelPolicyCompiler POLICY_COMPILER = @@ -89,6 +96,13 @@ public final class CelPolicyVerifierImplTest { private static final CelPolicyVerifier VERIFIER = CelPolicyVerifierFactory.newVerifier(POLICY_COMPILER, AST_VERIFIER).build(); + private static final String CONFIRMED = "The CEL runtime confirmed"; + private static final String REFUTED = "doesn't model exactly: calls to `zero`."; + private static final CelPolicyVerifier CEGAR_VERIFIER = + CelPolicyVerifierFactory.newVerifier( + POLICY_COMPILER, CelVerifierFactory.newVerifier(CEL).enableCegar(true).build()) + .build(); + @Before public void setUp() { System.setProperty("z3.skipLibraryLoad", "true"); @@ -359,7 +373,8 @@ public void verifyInvariants_secureResourceAccess_verified() throws Exception { .build(); CelPolicyVerifier verifier = CelPolicyVerifierFactory.newVerifier( - CelPolicyCompilerFactory.newPolicyCompiler(extendedCel).build(), AST_VERIFIER) + CelPolicyCompilerFactory.newPolicyCompiler(extendedCel).build(), + CelVerifierFactory.newVerifier(extendedCel).build()) .build(); CelPolicy policy = @@ -434,7 +449,8 @@ public void verifyInvariants_restrictedDestinationsPolicy_verified() throws Exce .build(); CelPolicyVerifier verifier = CelPolicyVerifierFactory.newVerifier( - CelPolicyCompilerFactory.newPolicyCompiler(extendedCel).build(), AST_VERIFIER) + CelPolicyCompilerFactory.newPolicyCompiler(extendedCel).build(), + CelVerifierFactory.newVerifier(extendedCel).build()) .build(); CelPolicy policy = @@ -498,6 +514,94 @@ public void verifyInvariants_variableRead(@TestParameter VariableReadTestCase te assertThat(results.get("reads_variable").status()).isEqualTo(testCase.expectedStatus); } + private enum CegarInvariantTestCase { + COUNTEREXAMPLE_CONFIRMED("rule.result == 1", VerificationStatus.VIOLATED, CONFIRMED), + ASSERTION_HOLDS("rule.result == 0", VerificationStatus.INCONCLUSIVE, REFUTED), + ASSUMPTION_FAILS( + /* assumption= */ "rule.result == 1", + /* assertion= */ "rule.result == 2", + VerificationStatus.INCONCLUSIVE, + REFUTED), + RULE_VARIABLE("variables.r == 0", VerificationStatus.INCONCLUSIVE, REFUTED), + VARIABLE_READS_VARIABLE("variables.w == 3", VerificationStatus.INCONCLUSIVE, REFUTED), + VARIABLE_SHADOWS_INPUT( + "variables.t == variables.s", + VerificationStatus.VIOLATED, + "violation detected. Counterexample input:"), + VARIABLE_ERROR_CONFIRMED( + "rule.result == 1 || variables.bad == 0", VerificationStatus.VIOLATED, CONFIRMED), + VARIABLE_ERROR_ABSORBED( + "variables.bad == 0 || rule.result == 0", VerificationStatus.INCONCLUSIVE, REFUTED), + UNBOUND_VARIABLE_FUNCTION( + "variables.u == 1", + VerificationStatus.INCONCLUSIVE, + "The CEL runtime couldn't check it: reading `variables.u`: "), + UNBOUND_VARIABLE_BETWEEN_ERRORS( + "1 / rule.result == 0 || variables.u == 1 || variables.r == 5 || variables.bad == 0", + VerificationStatus.INCONCLUSIVE, + "reading `variables.u`: evaluation error at :7: No matching overload for function" + + " 'unbound'"), + UNBOUND_VARIABLE_ABSORBED_IN_ASSUMPTION( + /* assumption= */ "variables.u == 1 || rule.result == 0", + /* assertion= */ "1 / rule.result == 0", + VerificationStatus.VIOLATED, + CONFIRMED), + UNBOUND_VARIABLE_ABSORBED_IN_VARIABLE( + "variables.ok && 1 / rule.result == 0", VerificationStatus.VIOLATED, CONFIRMED); + + private final String assumption; + private final String assertion; + private final VerificationStatus status; + private final String message; + + CegarInvariantTestCase(String assertion, VerificationStatus status, String message) { + this("true", assertion, status, message); + } + + CegarInvariantTestCase( + String assumption, String assertion, VerificationStatus status, String message) { + this.assumption = assumption; + this.assertion = assertion; + this.status = status; + this.message = message; + } + } + + // Unread variables must not be evaluated. + @Test + public void verifyInvariants_cegar_checksWitnessWithRuntime( + @TestParameter CegarInvariantTestCase testCase) throws Exception { + CelPolicy policy = + PARSER.parse( + String.format( + "name: cegar_policy\n" + + "rule:\n" + + " variables:\n" + + " - r: zero(x)\n" + + " - unread: unbound(x)\n" + + " match:\n" + + " - output: variables.r\n" + + "verification:\n" + + " variables:\n" + + " - v: rule.result + 2\n" + + " - w: variables.v + 1\n" + + " - t: variables.s\n" + + " - s: variables.s + 1\n" + + " - bad: 1 / rule.result\n" + + " - u: unbound(x)\n" + + " - ok: variables.u == 1 || rule.result == 0\n" + + " invariants:\n" + + " - id: invariant\n" + + " assume: '%s'\n" + + " assert: '%s'", + testCase.assumption, testCase.assertion)); + + CelVerificationResult result = CEGAR_VERIFIER.verifyInvariants(policy).get("invariant"); + + assertWithMessage(result.message()).that(result.status()).isEqualTo(testCase.status); + assertThat(result.message()).contains(testCase.message); + } + @Test public void verifyInvariants_invariantReferencesPolicyVariable_verified() throws Exception { String policySource = @@ -565,7 +669,8 @@ public void verifyInvariants_workloadAdmissionFlawed_violationsDetected() throws .build(); CelPolicyVerifier verifier = CelPolicyVerifierFactory.newVerifier( - CelPolicyCompilerFactory.newPolicyCompiler(extendedCel).build(), AST_VERIFIER) + CelPolicyCompilerFactory.newPolicyCompiler(extendedCel).build(), + CelVerifierFactory.newVerifier(extendedCel).build()) .build(); CelPolicy policy = @@ -601,7 +706,8 @@ public void verifyInvariants_workloadAdmissionFixed_verified() throws Exception .build(); CelPolicyVerifier verifier = CelPolicyVerifierFactory.newVerifier( - CelPolicyCompilerFactory.newPolicyCompiler(extendedCel).build(), AST_VERIFIER) + CelPolicyCompilerFactory.newPolicyCompiler(extendedCel).build(), + CelVerifierFactory.newVerifier(extendedCel).build()) .build(); CelPolicy policy = diff --git a/verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java b/verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java index a1ef49882..c75c3180a 100644 --- a/verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java +++ b/verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java @@ -25,6 +25,7 @@ import com.google.errorprone.annotations.Immutable; import com.google.testing.junit.testparameterinjector.TestParameter; import com.google.testing.junit.testparameterinjector.TestParameterInjector; +import com.google.testing.junit.testparameterinjector.TestParameters; // import com.google.testing.testsize.MediumTest; import com.microsoft.z3.ArrayExpr; import com.microsoft.z3.BoolExpr; @@ -66,6 +67,7 @@ import dev.cel.parser.CelStandardMacro; import dev.cel.runtime.CelFunctionBinding; import dev.cel.runtime.CelUnknownSet; +import dev.cel.testing.testdata.proto3.StandaloneGlobalEnum; import dev.cel.verifier.CelVerificationResult.VerificationStatus; import dev.cel.verifier.axioms.CelZ3FunctionAxiom; import dev.cel.verifier.axioms.CelZ3OverloadResult; @@ -74,6 +76,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.stream.IntStream; import org.junit.Before; @@ -121,6 +124,7 @@ public final class CelVerifierZ3ImplTest { .addVar("dyn_var", SimpleType.DYN) .addVar("dyn_var2", SimpleType.DYN) .addVar("type_var", TypeType.create(SimpleType.DYN)) + .addVar("type_list", ListType.create(TypeType.create(SimpleType.DYN))) .addVar("opt_var", OptionalType.create(SimpleType.INT)) .addVar("opt_dyn_var", OptionalType.create(SimpleType.DYN)) .addVar("nullable_int", NullableType.create(SimpleType.INT)) @@ -185,6 +189,16 @@ public void setUp() { private enum IsSatisfiableTestCase { SATISFIABLE("x > 5", "x = (?:[6-9]|[1-9]\\d+)"), + TYPE_VALUE("type_var == int", "type_var = int$"), + TYPE_VALUE_OF_DECLARED_TYPE( + "type_var != int && type_var != uint && type_var != double && type_var != bool" + + " && type_var != string && type_var != bytes && type_var != null_type" + + " && type_var != list && type_var != map && type_var != type" + + " && type_var != optional_type && type_var != google.protobuf.Timestamp" + + " && type_var != google.protobuf.Duration", + "type_var = (cel\\.expr\\.conformance|google\\.protobuf)\\.[\\w.]+$"), + TYPE_OF_TRUNCATED_LIST("size(int_list) == 6 && dyn(type(int_list)) == list", "int_list = "), + TRUNCATED_TYPE_LIST_EQUALITY("size(type_list) == 6 && type_list == type_list", "type_list = "), OPTIONAL_OR_VALUE_SKIPS_APPROXIMATE_ALTERNATIVE( "optional.of(x).orValue(int('123')) == 7", "x = 7"), DYNAMIC_ARITHMETIC("request == 1 && request + 2 == 3", "request = 1"), @@ -247,6 +261,10 @@ private enum IsSatisfiableTestCase { OR_VALUE_OF_DYN_NAN( "dyn_var.orValue(1) != dyn_var.orValue(1)", "dyn_var = optional\\.of\\(double\\(\"NaN\"\\)\\)"), + OPTIONAL_OF_NAN_NEQ_ITSELF( + "opt_dyn_var != opt_dyn_var", "opt_dyn_var = optional\\.of\\(double\\(\"NaN\"\\)\\)"), + OPTIONAL_PAST_UNROLL_LIMIT_NEQ_NONE( + "size(dyn_list) == 6 && optional.of(dyn_list) != optional.none()", "dyn_list = "), // Indexing and conditionals return existing values, so they do not inherit truncated type // constraints from their operands. DYN_ELEMENT_OF_LONG_NESTED_LIST_EQUALITY( @@ -386,7 +404,8 @@ private enum InexactWitnessTestCase { LIST_WITH_INEXACT_ELEMENT("dyn_list == [b'\\xc3\\xa9']", "dyn_list"), MAP_WITH_INEXACT_KEY("b'\\xc3\\xa9' in dyn_int_map", "dyn_int_map"), MAP_WITH_INEXACT_VALUE("string_dyn_map == {'a': b'\\xc3\\xa9'}", "string_dyn_map"), - OPTIONAL_WITH_INEXACT_VALUE("opt_dyn_var == optional.of(b'\\xc3\\xa9')", "opt_dyn_var"); + OPTIONAL_WITH_INEXACT_VALUE("opt_dyn_var == optional.of(b'\\xc3\\xa9')", "opt_dyn_var"), + TYPE_VALUE("type_var == int", "type_var"); private final String expr; private final String variableName; @@ -431,33 +450,83 @@ private enum InexactMapTestCase { @SuppressWarnings({"unchecked", "rawtypes"}) // Z3 Java API uses raw types. public void generateWitness_mapWithoutExactValue_valueEmpty( @TestParameter InexactMapTestCase testCase) { + CelWitness.Variable variable = + generateWitness( + "map", + (typeSystem, map) -> { + Context ctx = typeSystem.ctx(); + Expr mapRef = typeSystem.getMapRef(map); + SeqExpr keys = ctx.mkEmptySeq(ctx.mkSeqSort(typeSystem.celValueSort())); + for (String key : testCase.keySequence) { + keys = ctx.mkConcat(keys, ctx.mkUnit(typeSystem.mkString(key))); + } + ArrayExpr presence = ctx.mkConstArray(typeSystem.celValueSort(), ctx.mkFalse()); + for (String key : testCase.presentKeys) { + presence = ctx.mkStore(presence, (Expr) typeSystem.mkString(key), ctx.mkTrue()); + } + return ctx.mkAnd( + typeSystem.isMap(map), + ctx.mkEq(typeSystem.getMapKeys(mapRef), keys), + ctx.mkEq(typeSystem.getMapPresence(mapRef), presence)); + }); + + assertThat(variable.value()).isEmpty(); + } + + @Test + @TestParameters({ + "{name: 'int', expectedDisplay: 'int'}", + "{name: 'google.protobuf.Timestamp', expectedDisplay: 'google.protobuf.Timestamp'}", + "{name: '', expectedDisplay: ''}", + "{name: 'a b', expectedDisplay: ''}", + }) + public void generate_typeValue_displaysNameOrQuotesIt(String name, String expectedDisplay) { + CelWitness.Variable variable = + generateWitness("t", (typeSystem, t) -> typeSystem.ctx().mkEq(t, typeSystem.mkType(name))); + + assertThat(variable.displayValue()).isEqualTo(expectedDisplay); + } + + @Test + public void isSatisfiable_typeExcludingAllKnownTypes_remainsSatisfiable() throws Exception { + Cel cel = + CelFactory.plannerCelBuilder() + .addCompilerLibraries(CelOptionalLibrary.INSTANCE) + .addRuntimeLibraries(CelOptionalLibrary.INSTANCE) + .addFileTypes(StandaloneGlobalEnum.getDescriptor().getFile()) + .addMessageTypes( + TestAllTypes.getDescriptor() + .findFieldByName("single_int64_wrapper") + .getMessageType()) + .addVar("type_var", TypeType.create(SimpleType.DYN)) + .build(); + CelAbstractSyntaxTree ast = + cel.compile(IsSatisfiableTestCase.TYPE_VALUE_OF_DECLARED_TYPE.expr).getAst(); + + CelVerificationResult result = checkedVerifier(cel).build().isSatisfiable(ast); + + assertExact(result, VerificationStatus.VERIFIED); + assertThat(result.message()).doesNotContain("StandaloneGlobalEnum"); + assertThat(result.message()).doesNotContain("google.protobuf."); + } + + private static CelWitness.Variable generateWitness( + String name, BiFunction, BoolExpr> constraint) { try (Context ctx = new Context()) { - CelZ3TypeSystem typeSystem = new CelZ3TypeSystem(ctx, /* parameterizeUnknowns= */ false); - Expr map = ctx.mkConst("map", typeSystem.celValueSort()); - Expr mapRef = typeSystem.getMapRef(map); - SeqExpr keys = ctx.mkEmptySeq(ctx.mkSeqSort(typeSystem.celValueSort())); - for (String key : testCase.keySequence) { - keys = ctx.mkConcat(keys, ctx.mkUnit(typeSystem.mkString(key))); - } - ArrayExpr presence = ctx.mkConstArray(typeSystem.celValueSort(), ctx.mkFalse()); - for (String key : testCase.presentKeys) { - presence = ctx.mkStore(presence, (Expr) typeSystem.mkString(key), ctx.mkTrue()); - } + CelZ3TypeSystem typeSystem = + new CelZ3TypeSystem(ctx, /* parameterizeUnknowns= */ false, ImmutableSet.of()); + Expr variable = ctx.mkConst(name, typeSystem.celValueSort()); Solver solver = ctx.mkSolver(); - solver.add(typeSystem.isMap(map)); - solver.add(ctx.mkEq(typeSystem.getMapKeys(mapRef), keys)); - solver.add(ctx.mkEq(typeSystem.getMapPresence(mapRef), presence)); + solver.add(constraint.apply(typeSystem, variable)); assertThat(solver.check()).isEqualTo(Status.SATISFIABLE); - - CelWitness witness = - CelZ3CounterexampleGenerator.generate( + return CelZ3CounterexampleGenerator.generate( ctx, typeSystem, solver.getModel(), /* comprehensionUnrollLimit= */ 5, - ImmutableSet.of(map)); - - assertThat(witness.variables().get("map").value()).isEmpty(); + ImmutableSet.of(variable)) + .variables() + .get(name); } } @@ -591,6 +660,7 @@ public void isSatisfiable_unconditional_returnsUnconditionalMessage() throws Exc private enum ApproximationSourceTestCase { PARTIALLY_MODELED_FUNCTION("int(string_var) == 5", "calls to `int`"), + DYN_TYPE_VALUE("type(x) == dyn", "the `dyn` type as a value"), EMPTY_LIST_DYN_FIELD( "has(TestAllTypes{list_value: []}.list_value)", "whether empty `list(dyn)` and `map(string, dyn)` fields are set"), @@ -646,7 +716,13 @@ private enum ApproximationSourceTestCase { "comparisons of lists, maps, messages or optionals read out of lists and maps"), DYN_LIST_VARIABLES( "size(dyn_var) == 1 && dyn_var[0] == 1 && dyn_var == dyn_var2", - "comparisons of lists or maps typed dyn"); + "comparisons of lists, maps or optionals typed dyn"), + DYN_OPTIONAL_VARIABLES( + "dyn_var.hasValue() && dyn_var == dyn_var2", + "comparisons of lists, maps or optionals typed dyn"), + OPTIONAL_VALUES_TYPED_DYN( + "size(dyn_var) == 1 && dyn_var[0] == 1 && opt_dyn_var == optional.of(dyn_var)", + "comparisons of lists, maps or optionals typed dyn"); private final String expr; private final String expectedSources; @@ -857,10 +933,7 @@ public void isSatisfiable_maskedByBmcNested_inconclusive() throws Exception { CelAbstractSyntaxTree ast = CEL.compile(expr).getAst(); CelVerifier customVerifier = - CelVerifierFactory.newVerifier(CEL) - .setComprehensionUnrollLimit(3) - .setTypeProvider(TYPE_PROVIDER) - .build(); + CelVerifierFactory.newVerifier(CEL).setComprehensionUnrollLimit(3).build(); CelVerificationResult result = customVerifier.isSatisfiable(ast); @@ -1012,7 +1085,8 @@ public void isSatisfiable_failure(@TestParameter IsUnsatisfiableTestCase testCas @Test public void isSatisfiable_timeout_throwsException() throws Exception { - CelVerifier verifier = CelVerifierZ3Impl.newBuilder().setTimeout(Duration.ofMillis(1)).build(); + CelVerifier verifier = + CelVerifierZ3Impl.newBuilder(CEL).setTimeout(Duration.ofMillis(1)).build(); String expr = "int_list.all(x, int_list.all(y, int_list.all(z, x + y + z > 0)))"; CelAbstractSyntaxTree ast = CEL.compile(expr).getAst(); @@ -1023,6 +1097,13 @@ public void isSatisfiable_timeout_throwsException() throws Exception { private enum IsAlwaysTrueTestCase { LOGICAL_OR_CONSTANTS("true || false"), + TYPE_NOT_STRING("dyn('int') != int && type(x) != dyn('int')"), + TYPE_OF_TYPE( + "type(type) == type && [int, string].all(t, type(t) == type) && type(type(dyn_var)) ==" + + " type && type(type_var) == type"), + TYPE_IN_LIST("int in [int, string]"), + TYPE_LIST_EQUALITY("type_list == type_list"), + TYPE_OF_MESSAGE("type(TestAllTypes{}) == TestAllTypes"), // Elements of `dyn` inputs are never unknown. DYN_LIST_ELEMENT_NOT_UNKNOWN( "size(dyn_list) == 1 ? (dyn_list.exists(x, x == 1) || !dyn_list.exists(x, x == 1)) : true"), @@ -1263,6 +1344,22 @@ private enum IsAlwaysTrueTestCase { OPTIONAL_NONE_EQ_NONE("optional.none() == optional.none()"), OPTIONAL_OF_EQ_OF("optional.of(1) == optional.of(1)"), OPTIONAL_OF_NEQ_NONE("optional.of(1) != optional.none()"), + OPTIONAL_OF_NUMERICALLY_EQUAL("dyn(optional.of(1)) == optional.of(1.0)"), + OPTIONAL_OF_NAN_NEQ_ITSELF("optional.of(0.0 / 0.0) != optional.of(0.0 / 0.0)"), + OPTIONAL_OF_NEG_ZERO_EQ("optional.of(0.0) == optional.of(-0.0)"), + OPTIONAL_OF_LIST_NUMERICALLY_EQUAL("optional.of([dyn(1)]) == optional.of([dyn(1.0)])"), + OPTIONAL_NEQ_NON_OPTIONAL("dyn_var == 1 ? opt_var != dyn_var : true"), + OPTIONAL_OF_LIST_VAR_EQ_ITSELF("optional.of(int_list) == optional.of(int_list)"), + OPTIONAL_LIST_IN_LIST_LITERAL_NUMERICALLY_EQUAL( + "[optional.of([dyn(1)])] == [optional.of([dyn(1.0)])]"), + OPTIONAL_SELECT_NUMERICALLY_EQUAL("optional.of({'a': dyn(1)}).a == optional.of(1.0)"), + OPTIONAL_MAP_VAR_IN_MAP_LITERAL( + "string_int_map == {'k': 1}" + + " ? {'a': optional.of(string_int_map)} == {'a': optional.of({'k': 1})} : true"), + // `int_list` holds ints past the unroll limit too. + OPTIONAL_OF_LIST_VAR_PAST_UNROLL_LIMIT( + "optional.of(int_list) == optional.of([1, 2, 3, 4, 5, 6]) && int_list_2 == [1, 2, 3, 4, 5," + + " 6] ? int_list == int_list_2 : true"), OPTIONAL_VALUE("optional.of('test').value() == 'test'"), OPTIONAL_HAS_VALUE_TRUE("optional.of(true).hasValue()"), OPTIONAL_HAS_VALUE_FALSE("!optional.none().hasValue()"), @@ -2045,6 +2142,7 @@ public void verifyEquivalence_infinityConstants_notEquivalent() throws Exception } private enum IsAlwaysTrueViolationTestCase { + STRING_NAMING_TYPE("!(dyn_var == 'int' && dyn_var != int)", "dyn_var = \"int\""), // `[NaN]` differs from itself. DYNAMIC_LIST_VARIABLE_EQUALITY("dyn_list == dyn_list", "dyn_list = \\[double\\(\"NaN\"\\)\\]"), DYNAMIC_MAP_VARIABLE_EQUALITY( @@ -2064,16 +2162,16 @@ private enum IsAlwaysTrueViolationTestCase { NARROWED_TYPE_NUMERIC_EQUALITY( "dyn_var == optional.of(1) ? optional.ofNonZeroValue('').or(dyn_var).value() != dyn(1.0)" + " : true", - "dyn_var = optional\\.of\\(1\\)"), + "dyn_var = optional\\.of\\(1(u|\\.0)?\\)"), NARROWED_OPTIONAL_INDEX_NOT_CONTAINER( "dyn_var == optional.of(42) ? dyn_var.orValue(optional.of([1]))[0] in [42, optional.of(42)]" + " : true", - "dyn_var = optional\\.of\\(42\\)"), + "dyn_var = optional\\.of\\(42(u|\\.0)?\\)"), NARROWED_OPTIONAL_MAP_SELECTED( "dyn_var == optional.of(optional.of(42))" + " ? (dyn_var.orValue(optional.of({'a': 1})).a.hasValue()" + " || !dyn_var.orValue(optional.of({'a': 1})).a.hasValue()) : true", - "dyn_var = optional\\.of\\(optional\\.of\\(42\\)\\)"), + "dyn_var = optional\\.of\\(optional\\.of\\(42(u|\\.0)?\\)\\)"), // Map literal keys must be strings, ints, uints or bools, and can't repeat. MAP_LITERAL_RANGE_REPEATED_KEY("x == 1 ? {x: 'a', 1u: 'b'}.all(k, true) : true", "x = 1"), MAP_LITERAL_DOUBLE_KEY("{1.0: 'a'}[dyn(1)] == 'a'", "Condition is not always true\\."), @@ -2531,6 +2629,10 @@ private enum IsInconclusiveTestCase { "{\"key\": request.matches('a') ? 1 : 2}.all(k, v, v == 1)"), BIND_APPROXIMATE_ACCU("cel.bind(x, request.matches('a') ? 1 : 2, x == 1)"), BIND_APPROXIMATE_BODY("cel.bind(x, 1, x == 1 && request.matches('a'))"), + // The optionals are typed dyn, and optional.of(1.0) equals optional.of(1). + OR_WITH_DYN_ALTERNATIVE( + "dyn_var == optional.of(optional.of(1)) && type(dyn_var.value().value()) == double" + + " ? optional.ofNonZeroValue('').or(dyn_var).value() != dyn(optional.of(1)) : true"), COMPREHENSION_OPTIONAL_MAP_ENTRY( "size(int_list) == 6 ? size(int_list.map(x, {? x: optional.of(1)})) == 6 : true"), COMPREHENSION_OPTIONAL_STRUCT_ENTRY( @@ -2801,6 +2903,8 @@ private enum EquivalenceTestCase { OPTIONAL_NONE_HAS_VALUE_EQUIVALENCE("optional.none().hasValue()", "false"), OPTIONAL_OF_NON_ZERO_VALUE_ARITHMETIC_EQUIVALENCE( "[optional.ofNonZeroValue(1 + 2 + 3)]", "[optional.of(6)]"), + OPTIONAL_EQUAL_TO_LITERAL( + "opt_var == optional.of(1) ? opt_var : optional.of(1)", "optional.of(1)"), OPTIONAL_OF_NON_ZERO_VALUE_INT_ZERO_EQUIVALENCE( "optional.ofNonZeroValue(0)", "optional.none()"), OPTIONAL_OF_NON_ZERO_VALUE_INT_NON_ZERO_EQUIVALENCE( @@ -2979,7 +3083,8 @@ private enum EquivalenceTestCase { "optional.of(TestAllTypes{repeated_string: ['foo']}).?repeated_string[0]", "optional.of('foo')"), OPTIONAL_CHAINING_DYN( - "dyn_var == optional.of({'a': [1]}) ? dyn_var.a[0] : optional.of(1)", "optional.of(1)"), + "dyn_var == optional.of({'a': ['x']}) ? dyn_var.a[0] : optional.of('x')", + "optional.of('x')"), OPTIONAL_CHAINING_DYN_NONE( "request == optional.none() ? request.l : optional.none()", "optional.none()"), JSON_VALUE_BOOL("google.protobuf.Value{bool_value: true}", "true"), @@ -3815,7 +3920,7 @@ public void addFunctionAxioms_iterable_addsToAxioms() throws Exception { typeSystem.wrap(typeSystem.intCons(), ctx.mkInt(42)), ctx.mkFalse()))) .build(); CelVerifier verifier = - CelVerifierZ3Impl.newBuilder().addFunctionAxioms(ImmutableList.of(dummyAxiom)).build(); + CelVerifierZ3Impl.newBuilder(CEL).addFunctionAxioms(ImmutableList.of(dummyAxiom)).build(); CelAbstractSyntaxTree ast = celCompiler.compile("dummy() == 42").getAst(); CelVerificationResult result = verifier.isAlwaysTrue(ast); @@ -3835,7 +3940,7 @@ public void isAlwaysTrue_functionAxiomWithErrorArgument_bubblesUpError() throws (ctx, typeSystem, constraintSink, arg) -> Optional.of(typeSystem.mkInt(42))) .build(); CelVerifier verifier = - CelVerifierZ3Impl.newBuilder().addFunctionAxioms(ImmutableList.of(dummyAxiom)).build(); + CelVerifierZ3Impl.newBuilder(CEL).addFunctionAxioms(ImmutableList.of(dummyAxiom)).build(); CelCompiler celCompiler = CEL.toCompilerBuilder() .setContainer(CelContainer.ofName("cel.expr.conformance.proto3")) @@ -3867,9 +3972,9 @@ public void addFunctionAxioms_axiomHandlesNothing_fallsBackToUninterpretedFuncti "dummy_add_overload", (ctx, typeSystem, constraintSink, arg1, arg2) -> Optional.empty()) .build(); - CelVerifier verifier = - CelVerifierZ3Impl.newBuilder().addFunctionAxioms(ImmutableList.of(dummyAxiom)).build(); Cel cel = CelFactory.plannerCelBuilder().addFunctionDeclarations(dummyAddDecl).build(); + CelVerifier verifier = + CelVerifierZ3Impl.newBuilder(cel).addFunctionAxioms(ImmutableList.of(dummyAxiom)).build(); CelAbstractSyntaxTree ast = cel.compile("dummy_add(1, 1) == 2").getAst(); CelVerificationResult result = verifier.isAlwaysTrue(ast); @@ -3913,8 +4018,6 @@ public void addFunctionAxioms_ternaryOverload_approximation_inconclusive( (IntExpr) ctx.mkAdd(ts.getInt(arg1), ts.getInt(arg2), ts.getInt(arg3))))) .build(); - CelVerifier verifier = - CelVerifierZ3Impl.newBuilder().addFunctionAxioms(ImmutableList.of(dummyAxiom)).build(); CelFunctionDecl uninterpretedIntDecl = CelFunctionDecl.newFunctionDeclaration( @@ -3925,6 +4028,8 @@ public void addFunctionAxioms_ternaryOverload_approximation_inconclusive( .addFunctionDeclarations(dummyDecl) .addFunctionDeclarations(uninterpretedIntDecl) .build(); + CelVerifier verifier = + CelVerifierZ3Impl.newBuilder(cel).addFunctionAxioms(ImmutableList.of(dummyAxiom)).build(); CelAbstractSyntaxTree ast = cel.compile(testCase.expr).getAst(); CelVerificationResult result = verifier.isAlwaysTrue(ast); @@ -3956,13 +4061,13 @@ public void addFunctionAxioms_heterogeneousArguments_checksAllTypes() throws Exc (ctx, typeSystem, constraintSink, arg1, arg2) -> Optional.of(typeSystem.wrap(typeSystem.intCons(), ctx.mkInt(2)))) .build(); - CelVerifier verifier = - CelVerifierZ3Impl.newBuilder().addFunctionAxioms(ImmutableList.of(dummyAxiom)).build(); Cel cel = CelFactory.plannerCelBuilder() .addVar("int_var", SimpleType.INT) .addFunctionDeclarations(dummyDecl) .build(); + CelVerifier verifier = + CelVerifierZ3Impl.newBuilder(cel).addFunctionAxioms(ImmutableList.of(dummyAxiom)).build(); // The call dummy_func(int_var, [1]) should match dummy_func_int, returning 2. // If index 0 type check is skipped, it will match dummy_func_list, returning 1. CelAbstractSyntaxTree ast = @@ -4003,7 +4108,7 @@ public void addFunctionAxioms_duplicateFunctionNames_throwsException() throws Ex .build(); CelVerifierZ3Impl.Builder builder = - CelVerifierZ3Impl.newBuilder() + CelVerifierZ3Impl.newBuilder(CEL) .addFunctionAxioms(ImmutableList.of(dummyAxiom1, dummyAxiom2)); IllegalArgumentException exception = @@ -4025,7 +4130,8 @@ public void addFunctionAxioms_allPrimitiveTypes_checksAllTypes() throws Exceptio SimpleType.BOOL, SimpleType.STRING, SimpleType.BYTES, - StructTypeReference.create("test.Message"))); + StructTypeReference.create("test.Message"), + TypeType.create(SimpleType.DYN))); CelZ3FunctionAxiom dummyAxiom = CelZ3FunctionAxiom.newBuilder(dummyDecl) .addOverloadTranslator( @@ -4035,8 +4141,6 @@ public void addFunctionAxioms_allPrimitiveTypes_checksAllTypes() throws Exceptio CelZ3OverloadResult.create( typeSystem.wrap(typeSystem.boolCons(), ctx.mkTrue()), ctx.mkFalse()))) .build(); - CelVerifier verifier = - CelVerifierZ3Impl.newBuilder().addFunctionAxioms(ImmutableList.of(dummyAxiom)).build(); Cel cel = CelFactory.plannerCelBuilder() .addVar("uint_var", SimpleType.UINT) @@ -4045,18 +4149,27 @@ public void addFunctionAxioms_allPrimitiveTypes_checksAllTypes() throws Exceptio .addVar("string_var", SimpleType.STRING) .addVar("bytes_var", SimpleType.BYTES) .addVar("msg_var", StructTypeReference.create("test.Message")) + .addVar("type_var", TypeType.create(SimpleType.DYN)) .addFunctionDeclarations(dummyDecl) .build(); + CelVerifier verifier = + CelVerifierZ3Impl.newBuilder(cel).addFunctionAxioms(ImmutableList.of(dummyAxiom)).build(); CelAbstractSyntaxTree ast = cel.compile( - "dummy_all_types(uint_var, double_var, bool_var, string_var, bytes_var, msg_var) ==" - + " true") + "dummy_all_types(uint_var, double_var, bool_var, string_var, bytes_var, msg_var," + + " type_var) == true") .getAst(); CelVerificationResult result = verifier.isAlwaysTrue(ast); assertWithMessage(result.message()) .that(result.status()) .isEqualTo(VerificationStatus.VERIFIED); + CelAbstractSyntaxTree badTypeAst = + cel.compile( + "dummy_all_types(uint_var, double_var, bool_var, string_var, bytes_var, msg_var," + + " dyn('int')) == true") + .getAst(); + assertThat(verifier.isAlwaysTrue(badTypeAst).status()).isEqualTo(VerificationStatus.VIOLATED); } @Test @@ -4436,9 +4549,9 @@ public Optional translate( .addOverloadTranslator("spy_func_int", new SpyTranslator("spy_func_int")) .addOverloadTranslator("spy_func_string", new SpyTranslator("spy_func_string")) .build(); - CelVerifier verifier = CelVerifierZ3Impl.newBuilder().addFunctionAxioms(spyAxiom).build(); Cel cel = CelFactory.plannerCelBuilder().addFunctionDeclarations(spyFuncDecl).build(); + CelVerifier verifier = CelVerifierZ3Impl.newBuilder(cel).addFunctionAxioms(spyAxiom).build(); CelAbstractSyntaxTree ast = cel.compile("spy_func(42) == true").getAst(); @@ -4457,7 +4570,7 @@ public void getNumericEqualityWithConstant_skipsIntForDouble() throws Exception /* comprehensionUnrollLimit= */ 3, /* unknownIdentifiers= */ ImmutableSet.of(), /* functionRegistry= */ CelZ3FunctionRegistry.create(ImmutableList.of()), - /* typeProvider= */ CelVerifierZ3Impl.EMPTY_TYPE_PROVIDER, + /* typeProvider= */ CEL.getTypeProvider(), /* parameterizeUnknowns= */ false); Expr result = translator.translate(ast).z3Expr(); @@ -4479,7 +4592,7 @@ public void getNumericEqualityWithConstant_skipsDoubleForInt() throws Exception /* comprehensionUnrollLimit= */ 3, /* unknownIdentifiers= */ ImmutableSet.of(), /* functionRegistry= */ CelZ3FunctionRegistry.create(ImmutableList.of()), - /* typeProvider= */ CelVerifierZ3Impl.EMPTY_TYPE_PROVIDER, + /* typeProvider= */ CEL.getTypeProvider(), /* parameterizeUnknowns= */ false); Expr result = translator.translate(ast).z3Expr();