chore(bind): return 413 status code when error is `http.MaxBytesError` (#4227)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Bind: return 413 status code when error is `http.MaxBytesError` The Go standard library includes a method `http.MaxBytesReader` that allows limiting the request body. For example, users can create a middleware like: ```go func MiddlewareMaxBodySize(c *gin.Context) { // Limit request body to 100 bytes c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 100) c.Next() } ``` When the body exceeds the limit, reading from the request body returns an error of type `http.MaxBytesError`. This PR makes sure that when the error is of kind `http.MaxBytesError`, Gin returns the correct status code 413 (Request Entity Too Large) instead of a generic 400 (Bad Request). * Disable test when using sonic * Fix * Disable for go-json too * Add references to GitHub issues * Test that the response is 400 for sonic and go-json
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+80 added−24 removed
- other:+80 added−24 removed
Provenance
- Commit
40725d8- Tree
d891af6- Author
Alessandro (Ale) Segala <43508+ItalyPaleAle@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
c4287b1
6 files changed+80 added−24 removed
modified:internal/json/go_json.go+3 added
18 unmodified lines19 NewDecoder = json.NewDecoder20 // NewEncoder is exported by gin/json package.21 NewEncoder = json.NewEncoder22 )23+24+// Package indicates what library is being used for JSON encoding.25+const Package = "github.com/goccy/go-json"modified:internal/json/json.go+3 added
18 unmodified lines19 NewDecoder = json.NewDecoder20 // NewEncoder is exported by gin/json package.21 NewEncoder = json.NewEncoder22 )23+24+// Package indicates what library is being used for JSON encoding.25+const Package = "encoding/json"modified:internal/json/jsoniter.go+3 added
19 unmodified lines20 NewDecoder = json.NewDecoder21 // NewEncoder is exported by gin/json package.22 NewEncoder = json.NewEncoder23 )24+25+// Package indicates what library is being used for JSON encoding.26+const Package = "github.com/json-iterator/go"modified:internal/json/sonic.go+3 added
19 unmodified lines20 NewDecoder = json.NewDecoder21 // NewEncoder is exported by gin/json package.22 NewEncoder = json.NewEncoder23 )24+25+// Package indicates what library is being used for JSON encoding.26+const Package = "github.com/bytedance/sonic"modified:context_test.go+55 added-22 removed
26 unmodified lines27 "time"28 29 "github.com/gin-contrib/sse"30 "github.com/gin-gonic/gin/binding"31+ "github.com/gin-gonic/gin/internal/json"32 testdata "github.com/gin-gonic/gin/testdata/protoexample"33 "github.com/stretchr/testify/assert"34 "github.com/stretchr/testify/require"35 "google.golang.org/protobuf/proto"635 unmodified lines671 }672 673 func TestContextQueryAndPostForm(t *testing.T) {674 c, _ := CreateTestContext(httptest.NewRecorder())674- body := bytes.NewBufferString("foo=bar&page=11&both=&foo=second")675+ body := strings.NewReader("foo=bar&page=11&both=&foo=second")676 c.Request, _ = http.NewRequest(http.MethodPost,677 "/?both=GET&id=main&id=omit&array[]=first&array[]=second&ids[a]=hi&ids[b]=3.14", body)678 c.Request.Header.Add("Content-Type", MIMEPOSTForm)679 266 unmodified lines946 947 c.JSONP(http.StatusCreated, H{"foo": "bar"})948 949 assert.Equal(t, http.StatusCreated, w.Code)949- assert.JSONEq(t, "{\"foo\":\"bar\"}", w.Body.String())950+ assert.JSONEq(t, `{"foo":"bar"}`, w.Body.String())951 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))952 }953 954 // Tests that no JSON is rendered if code is 20417 unmodified lines972 c.Header("Content-Type", "application/vnd.api+json")973 c.JSON(http.StatusCreated, H{"foo": "bar"})974 975 assert.Equal(t, http.StatusCreated, w.Code)975- assert.JSONEq(t, "{\"foo\":\"bar\"}", w.Body.String())976+ assert.JSONEq(t, `{"foo":"bar"}`, w.Body.String())977 assert.Equal(t, "application/vnd.api+json", w.Header().Get("Content-Type"))978 }979 980 // Tests that no Custom JSON is rendered if code is 204451 unmodified lines1432 Data: H{"foo": "bar"},1433 })1434 1435 assert.Equal(t, http.StatusOK, w.Code)1435- assert.JSONEq(t, "{\"foo\":\"bar\"}", w.Body.String())1436+ assert.JSONEq(t, `{"foo":"bar"}`, w.Body.String())1437 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))1438 }1439 1440 func TestContextNegotiationWithXML(t *testing.T) {407 unmodified lines1848 1849 assert.Equal(t, "application/json", c.ContentType())1850 }1851 1852+func TestContextBindRequestTooLarge(t *testing.T) {1853+ // When using sonic or go-json as JSON encoder, they do not propagate the http.MaxBytesError error1854+ // The response will fail with a generic 400 instead of 4131855+ // https://github.com/goccy/go-json/issues/4851856+ // https://github.com/bytedance/sonic/issues/8001857+ var expectedCode int1858+ switch json.Package {1859+ case "github.com/goccy/go-json", "github.com/bytedance/sonic":1860+ expectedCode = http.StatusBadRequest1861+ default:1862+ expectedCode = http.StatusRequestEntityTooLarge1863+ }1864+1865+ w := httptest.NewRecorder()1866+ c, _ := CreateTestContext(w)1867+1868+ c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`{"foo":"bar", "bar":"foo"}`))1869+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 10)1870+1871+ var obj struct {1872+ Foo string `json:"foo"`1873+ Bar string `json:"bar"`1874+ }1875+ require.Error(t, c.BindJSON(&obj))1876+ c.Writer.WriteHeaderNow()1877+1878+ assert.Empty(t, obj.Bar)1879+ assert.Empty(t, obj.Foo)1880+ assert.Equal(t, expectedCode, w.Code)1881+ assert.True(t, c.IsAborted())1882+}1883+1884 func TestContextAutoBindJSON(t *testing.T) {1885 c, _ := CreateTestContext(httptest.NewRecorder())1853- c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))1886+ c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`{"foo":"bar", "bar":"foo"}`))1887 c.Request.Header.Add("Content-Type", MIMEJSON)1888 1889 var obj struct {1890 Foo string `json:"foo"`8 unmodified lines1899 func TestContextBindWithJSON(t *testing.T) {1900 w := httptest.NewRecorder()1901 c, _ := CreateTestContext(w)1902 1870- c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))1903+ c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`{"foo":"bar", "bar":"foo"}`))1904 c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type1905 1906 var obj struct {1907 Foo string `json:"foo"`8 unmodified lines1916 func TestContextBindWithXML(t *testing.T) {1917 w := httptest.NewRecorder()1918 c, _ := CreateTestContext(w)1919 1887- c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(`<?xml version="1.0" encoding="UTF-8"?>1920+ c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`<?xml version="1.0" encoding="UTF-8"?>1921 <root>1922 <foo>FOO</foo>1923 <bar>BAR</bar>1924 </root>`))58 unmodified lines1983 func TestContextBindWithQuery(t *testing.T) {1984 w := httptest.NewRecorder()1985 c, _ := CreateTestContext(w)1986 1954- c.Request, _ = http.NewRequest(http.MethodPost, "/?foo=bar&bar=foo", bytes.NewBufferString("foo=unused"))1987+ c.Request, _ = http.NewRequest(http.MethodPost, "/?foo=bar&bar=foo", strings.NewReader("foo=unused"))1988 1989 var obj struct {1990 Foo string `form:"foo"`1991 Bar string `form:"bar"`7 unmodified lines1999 func TestContextBindWithYAML(t *testing.T) {2000 w := httptest.NewRecorder()2001 c, _ := CreateTestContext(w)2002 1970- c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("foo: bar\nbar: foo"))2003+ c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader("foo: bar\nbar: foo"))2004 c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type2005 2006 var obj struct {2007 Foo string `yaml:"foo"`8 unmodified lines2016 func TestContextBindWithTOML(t *testing.T) {2017 w := httptest.NewRecorder()2018 c, _ := CreateTestContext(w)2019 1987- c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("foo = 'bar'\nbar = 'foo'"))2020+ c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader("foo = 'bar'\nbar = 'foo'"))2021 c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type2022 2023 var obj struct {2024 Foo string `toml:"foo"`8 unmodified lines2033 func TestContextBadAutoBind(t *testing.T) {2034 w := httptest.NewRecorder()2035 c, _ := CreateTestContext(w)2036 2004- c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))2037+ c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", strings.NewReader("\"foo\":\"bar\", \"bar\":\"foo\"}"))2038 c.Request.Header.Add("Content-Type", MIMEJSON)2039 var obj struct {2040 Foo string `json:"foo"`2041 Bar string `json:"bar"`10 unmodified lines2052 }2053 2054 func TestContextAutoShouldBindJSON(t *testing.T) {2055 c, _ := CreateTestContext(httptest.NewRecorder())2023- c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))2056+ c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`{"foo":"bar", "bar":"foo"}`))2057 c.Request.Header.Add("Content-Type", MIMEJSON)2058 2059 var obj struct {2060 Foo string `json:"foo"`8 unmodified lines2069 func TestContextShouldBindWithJSON(t *testing.T) {2070 w := httptest.NewRecorder()2071 c, _ := CreateTestContext(w)2072 2040- c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))2073+ c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`{"foo":"bar", "bar":"foo"}`))2074 c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type2075 2076 var obj struct {2077 Foo string `json:"foo"`8 unmodified lines2086 func TestContextShouldBindWithXML(t *testing.T) {2087 w := httptest.NewRecorder()2088 c, _ := CreateTestContext(w)2089 2057- c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(`<?xml version="1.0" encoding="UTF-8"?>2090+ c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`<?xml version="1.0" encoding="UTF-8"?>2091 <root>2092 <foo>FOO</foo>2093 <bar>BAR</bar>2094 </root>`))58 unmodified lines2153 func TestContextShouldBindWithQuery(t *testing.T) {2154 w := httptest.NewRecorder()2155 c, _ := CreateTestContext(w)2156 2124- c.Request, _ = http.NewRequest(http.MethodPost, "/?foo=bar&bar=foo&Foo=bar1&Bar=foo1", bytes.NewBufferString("foo=unused"))2157+ c.Request, _ = http.NewRequest(http.MethodPost, "/?foo=bar&bar=foo&Foo=bar1&Bar=foo1", strings.NewReader("foo=unused"))2158 2159 var obj struct {2160 Foo string `form:"foo"`2161 Bar string `form:"bar"`11 unmodified lines2173 func TestContextShouldBindWithYAML(t *testing.T) {2174 w := httptest.NewRecorder()2175 c, _ := CreateTestContext(w)2176 2144- c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("foo: bar\nbar: foo"))2177+ c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader("foo: bar\nbar: foo"))2178 c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type2179 2180 var obj struct {2181 Foo string `yaml:"foo"`8 unmodified lines2190 func TestContextShouldBindWithTOML(t *testing.T) {2191 w := httptest.NewRecorder()2192 c, _ := CreateTestContext(w)2193 2161- c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("foo='bar'\nbar= 'foo'"))2194+ c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader("foo='bar'\nbar= 'foo'"))2195 c.Request.Header.Add("Content-Type", MIMETOML) // set fake content-type2196 2197 var obj struct {2198 Foo string `toml:"foo"`8 unmodified lines2207 func TestContextBadAutoShouldBind(t *testing.T) {2208 w := httptest.NewRecorder()2209 c, _ := CreateTestContext(w)2210 2178- c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))2211+ c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", strings.NewReader(`"foo":"bar", "bar":"foo"}`))2212 c.Request.Header.Add("Content-Type", MIMEJSON)2213 var obj struct {2214 Foo string `json:"foo"`2215 Bar string `json:"bar"`55 unmodified lines2271 {2272 w := httptest.NewRecorder()2273 c, _ := CreateTestContext(w)2274 c.Request, _ = http.NewRequest(2242- http.MethodPost, "http://example.com", bytes.NewBufferString(tt.bodyA),2275+ http.MethodPost, "http://example.com", strings.NewReader(tt.bodyA),2276 )2277 // When it binds to typeA and typeB, it finds the body is2278 // not typeB but typeA.2279 objA := typeA{}9 unmodified lines2289 // not typeA but typeB.2290 w := httptest.NewRecorder()2291 c, _ := CreateTestContext(w)2292 c.Request, _ = http.NewRequest(2260- http.MethodPost, "http://example.com", bytes.NewBufferString(tt.bodyB),2293+ http.MethodPost, "http://example.com", strings.NewReader(tt.bodyB),2294 )2295 objA := typeA{}2296 require.Error(t, c.ShouldBindBodyWith(&objA, tt.bindingA))2297 assert.NotEqual(t, typeA{"FOO"}, objA)337 unmodified lines2635 }2636 2637 func TestContextGolangContext(t *testing.T) {2638 c, _ := CreateTestContext(httptest.NewRecorder())2606- c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))2639+ c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`{"foo":"bar", "bar":"foo"}`))2640 require.NoError(t, c.Err())2641 assert.Nil(t, c.Done())2642 ti, ok := c.Deadline()2643 assert.Equal(t, time.Time{}, ti)39 unmodified lines2683 }2684 2685 func TestContextGetRawData(t *testing.T) {2686 c, _ := CreateTestContext(httptest.NewRecorder())2654- body := bytes.NewBufferString("Fetch binary post data")2687+ body := strings.NewReader("Fetch binary post data")2688 c.Request, _ = http.NewRequest(http.MethodPost, "/", body)2689 c.Request.Header.Add("Content-Type", MIMEPOSTForm)2690 2691 data, err := c.GetRawData()593 unmodified linesmodified:context.go+13 added-2 removed
767 unmodified lines768 // MustBindWith binds the passed struct pointer using the specified binding engine.769 // It will abort the request with HTTP 400 if any error occurs.770 // See the binding package.771 func (c *Context) MustBindWith(obj any, b binding.Binding) error {772- if err := c.ShouldBindWith(obj, b); err != nil {773- c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) //nolint: errcheck772+ err := c.ShouldBindWith(obj, b)773+ if err != nil {774+ var maxBytesErr *http.MaxBytesError775+776+ // Note: When using sonic or go-json as JSON encoder, they do not propagate the http.MaxBytesError error777+ // https://github.com/goccy/go-json/issues/485778+ // https://github.com/bytedance/sonic/issues/800779+ switch {780+ case errors.As(err, &maxBytesErr):781+ c.AbortWithError(http.StatusRequestEntityTooLarge, err).SetType(ErrorTypeBind) //nolint: errcheck782+ default:783+ c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) //nolint: errcheck784+ }785 return err786 }787 return nil788 }596 unmodified lines