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
31 changes: 18 additions & 13 deletions policy/compiler.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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()) {
Expand All @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)},
Expand Down Expand Up @@ -1211,6 +1213,9 @@ absl::StatusOr<CelPolicyValidationResult> 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());
Expand Down
142 changes: 141 additions & 1 deletion policy/compiler_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,13 @@ using ::cel::test::ValueMatcher;
constexpr absl::string_view kTestPolicyFilePath =
"_main/policy/testdata/cel_policy.yaml";

absl::StatusOr<std::unique_ptr<Compiler>> BuildTestCompiler() {
absl::StatusOr<std::unique_ptr<Compiler>> 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));
Expand Down Expand Up @@ -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<bool> {
protected:
absl::StatusOr<CelPolicyValidationResult> 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;
Expand Down
Loading