Skip to content

net/http: add MaxBytesHandler(h Handler, n int64) Handler #39567

Closed
@rolandshoemaker

Description

@rolandshoemaker

Using ioutil.ReadAll on http.Request.Body is a rather common pattern (and one which is in fact used in at least one of the net/http examples) which can be somewhat dangerous as it can cause unbounded reads, leading to memory exhaustion and/or other funky behavior down the line when operating on the read contents (i.e. causing a stack overflow in encoding/json with massively nested structures being unmarshalled into an interface{}, see #31789).

The common solution to this problem is using http.MaxBytesReader (or less ideally ioutil.LimitedReader) either in a top level handler that wraps the http.Request.Body io.ReadCloser on all incoming requests (which is a bit boilerplate-y), or on each handler where you plan to read the request body (which is also quite verbose, and easy to forget to do leading to a vulnerable endpoint).

Ideally you would be able to set a field on http.Server, which when non-zero would automatically replace the request body reader with a MaxBytesReader on all incoming requests, preventing the user from having to either implement a top level handler, or a per handler reader replacement.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions