From 2a52934081264f76c8300327b602af1c08ee16cf Mon Sep 17 00:00:00 2001 From: Jonathan Tatum Date: Tue, 10 Nov 2026 16:48:54 -0800 Subject: [PATCH] Use polymorphic bind in the CEL policy compiler. PiperOrigin-RevId: 1018666435 --- policy/compiler.cc | 31 +++++---- policy/compiler_test.cc | 142 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 159 insertions(+), 14 deletions(-) diff --git a/policy/compiler.cc b/policy/compiler.cc index 4a37a04d7..e1dcc37d4 100644 --- a/policy/compiler.cc +++ b/policy/compiler.cc @@ -210,8 +210,7 @@ bool IsWrapperOf(cel::TypeKind wrapper_kind, cel::TypeKind primitive_kind) { cel::Type FilterSpecialTypes(cel::Type type) { if (type.IsTypeParam()) { - // Free type param should not appear in the output type, but if it does, - // force it to dyn. + // Type parameters are unconstrained, so we treat them like dyn. return DynType(); } if (type.IsEnum()) { @@ -237,7 +236,9 @@ bool OutputTypeIsAssignable(cel::Type from, cel::Type to) { from = FilterSpecialTypes(from); to = FilterSpecialTypes(to); - // Any and dyn are assignable to/from everything. + // Any and dyn are assignable to/from everything. Type parameters (from + // generic result types, see CheckerOptions::use_polymorphic_bind) + // are unconstrained, so they are treated like dyn. if (from.kind() == cel::TypeKind::kAny || from.kind() == cel::TypeKind::kDyn || to.kind() == cel::TypeKind::kAny || to.kind() == cel::TypeKind::kDyn) { @@ -298,6 +299,15 @@ bool OutputTypeIsCompatible(cel::Type from, cel::Type to) { return OutputTypeIsAssignable(from, to) || OutputTypeIsAssignable(to, from); } +// Returns the type of the checked expression's root. +// +// We override use_polymorphic_bind, so this is just the GenericResultType. +// +// If absent, return dyn as a fallback. +cel::Type GetResultType(const ValidationResult& validation) { + return validation.GetGenericResultType().value_or(DynType()); +} + bool HasErrors(const policy_internal::IssueReporter& issues) { for (const auto& issue : issues.issues()) { if (issue.severity() == CelPolicyIssue::Severity::kError) { @@ -392,13 +402,9 @@ class PolicyCompiler { cel::Type result_type = DynType(); if (output_validation.IsValid()) { CEL_ASSIGN_OR_RETURN(auto ast, output_validation.ReleaseAst()); - auto root_expr_id = ast->root_expr().id(); output.output_ast = EmbeddedAst{output_block.output().id(), std::move(ast)}; - if (auto it = output_validation.GetResolvedTypeMap().find(root_expr_id); - it != output_validation.GetResolvedTypeMap().end()) { - result_type = it->second; - } + result_type = GetResultType(output_validation); } if (output_block.explanation().has_value()) { CEL_ASSIGN_OR_RETURN( @@ -483,12 +489,8 @@ class PolicyCompiler { continue; } CEL_ASSIGN_OR_RETURN(auto ast, validation.ReleaseAst()); - cel::Type result_type = DynType(); + cel::Type result_type = GetResultType(validation); - if (auto it = validation.GetResolvedTypeMap().find(ast->root_expr().id()); - it != validation.GetResolvedTypeMap().end()) { - result_type = it->second; - } out->variables.push_back(CompiledVariable{ ident, EmbeddedAst{variable.expression().id(), std::move(ast)}, @@ -1211,6 +1213,9 @@ absl::StatusOr CompilePolicy( "unnesting_height_limit must be at least 2"); } auto builder = compiler.ToBuilder(); + // Preserve polymorphic bind behavior so variables act the same as though they + // were directly in the expression. + builder->GetCheckerBuilder().mutable_options().use_polymorphic_bind = true; ExpressionContainer cont; for (const auto& import : policy.imports()) { auto status = cont.AddAbbreviation(import.name().value()); diff --git a/policy/compiler_test.cc b/policy/compiler_test.cc index f99cce5e9..c38016247 100644 --- a/policy/compiler_test.cc +++ b/policy/compiler_test.cc @@ -74,11 +74,13 @@ using ::cel::test::ValueMatcher; constexpr absl::string_view kTestPolicyFilePath = "_main/policy/testdata/cel_policy.yaml"; -absl::StatusOr> BuildTestCompiler() { +absl::StatusOr> BuildTestCompiler( + bool use_polymorphic_bind = false) { CompilerOptions opts; opts.adapt_parser_errors = true; opts.parser_options.enable_optional_syntax = true; opts.parser_options.add_macro_calls = true; + opts.checker_options.use_polymorphic_bind = use_polymorphic_bind; CEL_ASSIGN_OR_RETURN( auto builder, NewCompilerBuilder(internal::GetSharedTestingDescriptorPool(), opts)); @@ -683,6 +685,144 @@ name: cel_policy EXPECT_TRUE(result.GetAst()->is_checked()); } +// Policy variables with unconstrained (free) type parameters, e.g. `[]`. +// +// The policy compiler enables CheckerOptions::use_polymorphic_bind, so +// variables are declared with their generic result type (e.g. list(T1)) in +// the compile phase and each reference is instantiated independently. +// +// Parameterized on the option in the input compiler, which should not matter. +class GenericPolicyVariableTest : public testing::TestWithParam { + protected: + absl::StatusOr Compile(absl::string_view yaml) { + CEL_ASSIGN_OR_RETURN(auto policy, ParsePolicyFromYaml(yaml)); + CEL_ASSIGN_OR_RETURN(auto compiler, BuildTestCompiler(GetParam())); + return CompilePolicy(*compiler, *policy); + } +}; + +TEST_P(GenericPolicyVariableTest, NarrowsAtUse) { + ASSERT_OK_AND_ASSIGN(auto result, Compile(R"yaml( +name: cel_policy +rule: + id: test_rule + variables: + - name: empty + expression: '[]' + match: + - output: 'variables.empty + [1]' +)yaml")); + ASSERT_TRUE(result.IsValid()) << result.FormatIssues(); + EXPECT_EQ( + result.GetAst()->GetReturnType().list_type().elem_type().primitive(), + PrimitiveType::kInt64); +} + +TEST_P(GenericPolicyVariableTest, IndependentUses) { + ASSERT_OK_AND_ASSIGN(auto result, Compile(R"yaml( +name: cel_policy +rule: + id: test_rule + variables: + - name: empty + expression: '[]' + match: + - output: > + variables.empty + [1] == [1] && variables.empty + ['a'] == ['a'] +)yaml")); + ASSERT_TRUE(result.IsValid()) << result.FormatIssues(); + EXPECT_EQ(result.GetAst()->GetReturnType().primitive(), PrimitiveType::kBool); +} + +TEST_P(GenericPolicyVariableTest, IndependentUsesInDependentVariable) { + ASSERT_OK_AND_ASSIGN(auto result, Compile(R"yaml( +name: cel_policy +rule: + id: test_rule + variables: + - name: empty + expression: '{}' + - name: ints + expression: 'variables.empty.with_int' + match: + - output: > + variables.empty['a'] == 'b' && variables.ints == 1 +)yaml")); + ASSERT_TRUE(result.IsValid()) << result.FormatIssues(); + EXPECT_EQ(result.GetAst()->GetReturnType().primitive(), PrimitiveType::kBool); +} + +// `optional.none()` has type optional_type(T) with T unconstrained, so each +// reference to the variable is inferred independently. +TEST_P(GenericPolicyVariableTest, OptionalNoneNarrowsAtUse) { + ASSERT_OK_AND_ASSIGN(auto result, Compile(R"yaml( +name: cel_policy +rule: + id: test_rule + variables: + - name: none + expression: 'optional.none()' + match: + - output: 'variables.none.orValue(1)' +)yaml")); + ASSERT_TRUE(result.IsValid()) << result.FormatIssues(); + EXPECT_EQ(result.GetAst()->GetReturnType().primitive(), + PrimitiveType::kInt64); +} + +TEST_P(GenericPolicyVariableTest, OptionalNoneIndependentUses) { + ASSERT_OK_AND_ASSIGN(auto result, Compile(R"yaml( +name: cel_policy +rule: + id: test_rule + variables: + - name: none + expression: 'optional.none()' + match: + - output: > + variables.none.orValue(1) == 1 && variables.none.orValue('a') == 'a' +)yaml")); + ASSERT_TRUE(result.IsValid()) << result.FormatIssues(); + EXPECT_EQ(result.GetAst()->GetReturnType().primitive(), PrimitiveType::kBool); +} + +TEST_P(GenericPolicyVariableTest, EmptyAndNonEmptyOutputsCompatible) { + ASSERT_OK_AND_ASSIGN(auto result, Compile(R"yaml( +name: cel_policy +rule: + id: test_rule + match: + - condition: x > 1 + output: '[]' + - output: '[1]' +)yaml")); + EXPECT_TRUE(result.IsValid()) << result.FormatIssues(); +} + +// The compile-phase output type of `variables.empty + [1]` is list(int) +// (instead of list(dyn)), so the mismatch with the other output is reported at +// the match rather than when type checking the composed expression. +TEST_P(GenericPolicyVariableTest, MismatchedOutputs) { + ASSERT_OK_AND_ASSIGN(auto result, Compile(R"yaml( +name: cel_policy +rule: + id: test_rule + variables: + - name: empty + expression: '[]' + match: + - condition: x > 1 + output: 'variables.empty + [1]' + - output: "['a']" +)yaml")); + EXPECT_FALSE(result.IsValid()); + EXPECT_THAT(result.FormatIssues(), + testing::HasSubstr("incompatible output types")); +} + +INSTANTIATE_TEST_SUITE_P(PreserveResultTypeParams, GenericPolicyVariableTest, + testing::Bool()); + struct EvaluationTestCase { std::string name; std::string yaml_policy;