Skip to content

Commit

Permalink
fix(fieldmask): traverse repeated fields with wildcard in validation
Browse files Browse the repository at this point in the history
  • Loading branch information
oscarmuhr committed Dec 19, 2023
1 parent 0041801 commit 3214947
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
14 changes: 13 additions & 1 deletion fieldmask/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,24 @@ func Validate(fm *fieldmaskpb.FieldMask, m proto.Message) error {
md0 := m.ProtoReflect().Descriptor()
for _, path := range fm.GetPaths() {
md := md0
var fd protoreflect.FieldDescriptor
if !rangeFields(path, func(field string) bool {
// Search the field within the message.
if md == nil {
return false // not within a message
}
fd := md.Fields().ByName(protoreflect.Name(field))
// Parent message is a repeated field.
// Targeting sub-fields is allowed with the use of wildcard
// https://google.aip.dev/161#wildcards
if fd != nil && fd.IsList() {
if field == WildcardPath {
fd = nil
return true
}

return false
}
fd = md.Fields().ByName(protoreflect.Name(field))
// The real field name of a group is the message name.
if fd == nil {
gd := md.Fields().ByName(protoreflect.Name(strings.ToLower(field)))
Expand Down
18 changes: 18 additions & 0 deletions fieldmask/validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package fieldmask
import (
"testing"

freightv1 "go.einride.tech/aip/proto/gen/einride/example/freight/v1"
"google.golang.org/genproto/googleapis/example/library/v1"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/fieldmaskpb"
Expand Down Expand Up @@ -71,6 +72,23 @@ func TestValidate(t *testing.T) {
message: &library.CreateBookRequest{},
errorContains: "invalid field path: book.foo",
},

{
name: "invalid nested in repeated field",
fieldMask: &fieldmaskpb.FieldMask{
Paths: []string{"shipment.line_items.title"},
},
message: &freightv1.CreateShipmentRequest{},
errorContains: "invalid field path: shipment.line_items.title",
},

{
name: "valid nested in repeated field",
fieldMask: &fieldmaskpb.FieldMask{
Paths: []string{"shipment.line_items.*.title"},
},
message: &freightv1.CreateShipmentRequest{},
},
} {
tt := tt
t.Run(tt.name, func(t *testing.T) {
Expand Down

0 comments on commit 3214947

Please sign in to comment.