Skip to content

Commit

Permalink
Fix CEL types for repeated field item expressions (#92)
Browse files Browse the repository at this point in the history
For repeated items, CEL types were being miscalculated for variables in
the expression resulting in type-check/compilation errors

Fixes #91
  • Loading branch information
rodaine authored Jan 19, 2024
1 parent 01ec377 commit 3f1653a
Show file tree
Hide file tree
Showing 4 changed files with 123 additions and 36 deletions.
4 changes: 2 additions & 2 deletions internal/evaluator/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ func (bldr *Builder) processIgnoreEmpty(
func (bldr *Builder) processFieldExpressions(
fieldDesc protoreflect.FieldDescriptor,
fieldConstraints *validate.FieldConstraints,
_ bool,
forItems bool,
eval *value,
_ MessageCache,
) error {
Expand All @@ -279,7 +279,7 @@ func (bldr *Builder) processFieldExpressions(
return nil
}

celTyp := celext.ProtoFieldToCELType(fieldDesc, false, false)
celTyp := celext.ProtoFieldToCELType(fieldDesc, false, forItems)
opts := append(
celext.RequiredCELEnvOptions(fieldDesc),
cel.Variable("this", celTyp),
Expand Down
134 changes: 100 additions & 34 deletions internal/gen/tests/example/v1/validations.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions proto/tests/example/v1/validations.proto
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,10 @@ message CelMapOnARepeated {
string name = 1;
}
}

message RepeatedItemCel {
repeated string paths = 1 [(buf.validate.field).repeated.items.cel = {
id: "paths.no_space",
expression: "!this.startsWith(' ')"
}];
}
14 changes: 14 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,3 +184,17 @@ func TestValidator_Validate_CelMapOnARepeated(t *testing.T) {
valErr := &ValidationError{}
assert.ErrorAs(t, err, &valErr)
}

func TestValidator_Validate_RepeatedItemCel(t *testing.T) {
t.Parallel()
val, err := New()
require.NoError(t, err)
msg := &pb.RepeatedItemCel{Paths: []string{"foo"}}
err = val.Validate(msg)
require.NoError(t, err)
msg.Paths = append(msg.Paths, " bar")
err = val.Validate(msg)
valErr := &ValidationError{}
assert.ErrorAs(t, err, &valErr)
assert.Equal(t, "paths.no_space", valErr.Violations[0].ConstraintId)
}

0 comments on commit 3f1653a

Please sign in to comment.