diff --git a/binding/binding.go b/binding/binding.go index eced0ae2..c6142d5c 100644 --- a/binding/binding.go +++ b/binding/binding.go @@ -125,3 +125,9 @@ func validate(obj any) error { } return Validator.ValidateStruct(obj) } + +// MaxBodySize is the maximum request body size in bytes that BSON and +// Protobuf binders will read. If the request body exceeds this limit, +// the binding returns an error. Defaults to 32 MB. +var MaxBodySize int64 = 32 << 20 + diff --git a/binding/bson.go b/binding/bson.go index 464890f0..37736d06 100644 --- a/binding/bson.go +++ b/binding/bson.go @@ -5,6 +5,7 @@ package binding import ( + "errors" "io" "net/http" @@ -18,11 +19,14 @@ func (bsonBinding) Name() string { } func (b bsonBinding) Bind(req *http.Request, obj any) error { - buf, err := io.ReadAll(req.Body) - if err == nil { - err = b.BindBody(buf, obj) + body, err := io.ReadAll(io.LimitReader(req.Body, MaxBodySize+1)) + if err != nil { + return err } - return err + if int64(len(body)) > MaxBodySize { + return errors.New("request body too large") + } + return b.BindBody(body, obj) } func (bsonBinding) BindBody(body []byte, obj any) error { diff --git a/binding/protobuf.go b/binding/protobuf.go index 259ae8e7..2d35ae1f 100644 --- a/binding/protobuf.go +++ b/binding/protobuf.go @@ -19,11 +19,14 @@ func (protobufBinding) Name() string { } func (b protobufBinding) Bind(req *http.Request, obj any) error { - buf, err := io.ReadAll(req.Body) + body, err := io.ReadAll(io.LimitReader(req.Body, MaxBodySize+1)) if err != nil { return err } - return b.BindBody(buf, obj) + if int64(len(body)) > MaxBodySize { + return errors.New("request body too large") + } + return b.BindBody(body, obj) } func (protobufBinding) BindBody(body []byte, obj any) error {