From fb213759e00d4ee6162e4f90dd71c17d91628999 Mon Sep 17 00:00:00 2001 From: Edward McFarlane Date: Mon, 18 Mar 2024 20:12:58 -0400 Subject: [PATCH] Fix lint for repeated protovalidate CEL expression This PR fixes linting for repeated fiels with CEL expressions. Adds a new test case for lists (and maps) to ensure a valid expression passes. Small fix to set the type 'this' to the list element type. Before: ``` testdata/protovalidate_rules/cel_field.proto:126:9:(buf.validate.field).repeated.items.cel.expression on field "allow_cidr" fails to compile: found no matching overload for 'isIpPrefix' applied to 'list(string).(int, bool)' | this.isIpPrefix(4, true) | ...............^ ``` --- .../buflint/internal/buflintvalidate/cel.go | 2 +- .../protovalidate_rules/cel_field.proto | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/private/bufpkg/bufcheck/buflint/internal/buflintvalidate/cel.go b/private/bufpkg/bufcheck/buflint/internal/buflintvalidate/cel.go index 5aeeac4d54..08198a7835 100644 --- a/private/bufpkg/bufcheck/buflint/internal/buflintvalidate/cel.go +++ b/private/bufpkg/bufcheck/buflint/internal/buflintvalidate/cel.go @@ -86,7 +86,7 @@ func checkCELForField( celEnv, err = celEnv.Extend( append( celext.RequiredCELEnvOptions(fieldDescriptor), - cel.Variable("this", celext.ProtoFieldToCELType(fieldDescriptor, false, false)), + cel.Variable("this", celext.ProtoFieldToCELType(fieldDescriptor, false, fieldDescriptor.IsList())), )..., ) if err != nil { diff --git a/private/bufpkg/bufcheck/buflint/testdata/protovalidate_rules/cel_field.proto b/private/bufpkg/bufcheck/buflint/testdata/protovalidate_rules/cel_field.proto index fc47d11d55..b99bee3ee3 100644 --- a/private/bufpkg/bufcheck/buflint/testdata/protovalidate_rules/cel_field.proto +++ b/private/bufpkg/bufcheck/buflint/testdata/protovalidate_rules/cel_field.proto @@ -119,4 +119,29 @@ message Foo { expression: "this * this" } ]; + // Valid CEL expressions for repeated fields. + repeated string allow_cidr = 14 [(buf.validate.field).repeated = { + min_items: 1, + items: { + cel: [ + { + id: "ip_prefix", + message: "value must be IPv4 prefix", + expression: "this.isIpPrefix(4, true)", + } + ], + }, + }]; + // Valid CEL expressions for map fields. + map allow_cidr_map = 15 [(buf.validate.field).map = { + keys: { + cel: [ + { + id: "ip_prefix", + message: "key must be IPv4 prefix", + expression: "this.isIpPrefix(4, true)", + } + ], + }, + }]; }