From 15427d3d42748631afbbd129cc768cb173f41bd8 Mon Sep 17 00:00:00 2001 From: Tevic Date: Tue, 7 Sep 2021 10:10:32 +0800 Subject: [PATCH] fix: check obj type in protobufBinding (#2851) * fix: check obj type in protobufBinding * fix: UnitTest for invalid proto obj --- binding/binding_test.go | 7 +++++++ binding/protobuf.go | 7 ++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/binding/binding_test.go b/binding/binding_test.go index 17df7dc59d..5b0ce39d3e 100644 --- a/binding/binding_test.go +++ b/binding/binding_test.go @@ -1339,6 +1339,13 @@ func testProtoBodyBindingFail(t *testing.T, b Binding, name, path, badPath, body err := b.Bind(req, &obj) assert.Error(t, err) + invalid_obj := FooStruct{} + req.Body = ioutil.NopCloser(strings.NewReader(`{"msg":"hello"}`)) + req.Header.Add("Content-Type", MIMEPROTOBUF) + err = b.Bind(req, &invalid_obj) + assert.Error(t, err) + assert.Equal(t, err.Error(), "obj is not ProtoMessage") + obj = protoexample.Test{} req = requestWithBody("POST", badPath, badBody) req.Header.Add("Content-Type", MIMEPROTOBUF) diff --git a/binding/protobuf.go b/binding/protobuf.go index ca02897a9f..a4e471535c 100644 --- a/binding/protobuf.go +++ b/binding/protobuf.go @@ -5,6 +5,7 @@ package binding import ( + "errors" "io/ioutil" "net/http" @@ -26,7 +27,11 @@ func (b protobufBinding) Bind(req *http.Request, obj interface{}) error { } func (protobufBinding) BindBody(body []byte, obj interface{}) error { - if err := proto.Unmarshal(body, obj.(proto.Message)); err != nil { + msg, ok := obj.(proto.Message) + if !ok { + return errors.New("obj is not ProtoMessage") + } + if err := proto.Unmarshal(body, msg); err != nil { return err } // Here it's same to return validate(obj), but util now we can't add