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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -144,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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -999,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 =
Expand All @@ -1010,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) {
Expand All @@ -1031,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,
Expand Down Expand Up @@ -1064,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<BoolExpr> 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<CelExpr> 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()))
.<Expr<?>>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;
Expand Down
43 changes: 38 additions & 5 deletions verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -261,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(
Expand Down Expand Up @@ -712,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;
Expand Down Expand Up @@ -1334,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()"),
Expand Down Expand Up @@ -2136,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\\."),
Expand Down Expand Up @@ -2603,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(
Expand Down Expand Up @@ -2873,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(
Expand Down Expand Up @@ -3051,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"),
Expand Down
Loading