diff --git a/binding/binding.go b/binding/binding.go index eced0ae2..306a210e 100644 --- a/binding/binding.go +++ b/binding/binding.go @@ -26,6 +26,11 @@ const ( MIMEBSON = "application/bson" ) +// DefaultMaxBodySize is the maximum request body size (in bytes) that the BSON, +// Protobuf, and Plain binders will read. Requests with a body larger than this +// limit return an error. Set to 0 to disable the limit. +const DefaultMaxBodySize = 32 << 20 // 32 MB + // Binding describes the interface which needs to be implemented for binding the // data present in the request such as JSON request body, query parameters or // the form POST. diff --git a/binding/bson.go b/binding/bson.go index 464890f0..09eccc73 100644 --- a/binding/bson.go +++ b/binding/bson.go @@ -18,8 +18,11 @@ func (bsonBinding) Name() string { } func (b bsonBinding) Bind(req *http.Request, obj any) error { - buf, err := io.ReadAll(req.Body) + buf, err := io.ReadAll(io.LimitReader(req.Body, DefaultMaxBodySize+1)) if err == nil { + if len(buf) > DefaultMaxBodySize { + return http.ErrBodyReadAfterClose + } err = b.BindBody(buf, obj) } return err diff --git a/binding/plain.go b/binding/plain.go index 5d466bdd..4f6d772f 100644 --- a/binding/plain.go +++ b/binding/plain.go @@ -16,10 +16,13 @@ func (plainBinding) Name() string { } func (plainBinding) Bind(req *http.Request, obj any) error { - all, err := io.ReadAll(req.Body) + all, err := io.ReadAll(io.LimitReader(req.Body, DefaultMaxBodySize+1)) if err != nil { return err } + if len(all) > DefaultMaxBodySize { + return http.ErrBodyReadAfterClose + } return decodePlain(all, obj) } diff --git a/binding/protobuf.go b/binding/protobuf.go index 259ae8e7..0e522722 100644 --- a/binding/protobuf.go +++ b/binding/protobuf.go @@ -19,10 +19,13 @@ func (protobufBinding) Name() string { } func (b protobufBinding) Bind(req *http.Request, obj any) error { - buf, err := io.ReadAll(req.Body) + buf, err := io.ReadAll(io.LimitReader(req.Body, DefaultMaxBodySize+1)) if err != nil { return err } + if len(buf) > DefaultMaxBodySize { + return http.ErrBodyReadAfterClose + } return b.BindBody(buf, obj) }