Go: net/http: add Server.MaxBodyBytes int64 field

Created on 12 Jun 2020  路  5Comments  路  Source: golang/go

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.

Proposal Proposal-Accepted Proposal-FinalCommentPeriod

Most helpful comment

We do have MaxHeaderBytes in http.Server already.
Are you suggesting to add MaxBodyBytes int64?

All 5 comments

@bradfitz @neild

We do have MaxHeaderBytes in http.Server already.
Are you suggesting to add MaxBodyBytes int64?

Based on the discussion above, this seems like a likely accept.

Ah sorry, I completely missed the comment from two weeks ago

Are you suggesting to add MaxBodyBytes int64?

Yep, that is the meat of the proposal.

No change in consensus, so accepted.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

natefinch picture natefinch  路  3Comments

rakyll picture rakyll  路  3Comments

dominikh picture dominikh  路  3Comments

rsc picture rsc  路  3Comments

longzhizhi picture longzhizhi  路  3Comments