1
0

bodylimit_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package middleware
  2. import (
  3. "bytes"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "strings"
  8. "testing"
  9. "github.com/gin-gonic/gin"
  10. )
  11. func TestMaxBodyBytes(t *testing.T) {
  12. gin.SetMode(gin.TestMode)
  13. const limit = 16
  14. r := gin.New()
  15. r.Use(MaxBodyBytes(limit))
  16. r.POST("/x", func(c *gin.Context) {
  17. if _, err := io.ReadAll(c.Request.Body); err != nil {
  18. c.String(http.StatusRequestEntityTooLarge, "too big")
  19. return
  20. }
  21. c.String(http.StatusOK, "ok")
  22. })
  23. r.GET("/x", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
  24. // Body within the limit is read normally.
  25. w := httptest.NewRecorder()
  26. r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/x", strings.NewReader("0123456789")))
  27. if w.Code != http.StatusOK {
  28. t.Errorf("under-limit POST: got %d, want 200", w.Code)
  29. }
  30. // Body over the limit makes the handler's read fail (no unbounded buffer).
  31. w = httptest.NewRecorder()
  32. r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/x", bytes.NewReader(make([]byte, limit*4))))
  33. if w.Code == http.StatusOK {
  34. t.Errorf("over-limit POST should not succeed, got 200")
  35. }
  36. // Bodyless methods pass through untouched.
  37. w = httptest.NewRecorder()
  38. r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/x", nil))
  39. if w.Code != http.StatusOK {
  40. t.Errorf("GET should pass through, got %d", w.Code)
  41. }
  42. }
  43. func TestMaxBodyBytesSkipSuffix(t *testing.T) {
  44. gin.SetMode(gin.TestMode)
  45. const limit = 16
  46. r := gin.New()
  47. r.Use(MaxBodyBytes(limit, "/server/importDB"))
  48. read := func(c *gin.Context) {
  49. if _, err := io.ReadAll(c.Request.Body); err != nil {
  50. c.String(http.StatusRequestEntityTooLarge, "too big")
  51. return
  52. }
  53. c.String(http.StatusOK, "ok")
  54. }
  55. r.POST("/server/importDB", read)
  56. r.POST("/x", read)
  57. // Exempt route reads an over-limit body without error.
  58. w := httptest.NewRecorder()
  59. r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/server/importDB", bytes.NewReader(make([]byte, limit*4))))
  60. if w.Code != http.StatusOK {
  61. t.Errorf("exempt route should pass through over-limit body, got %d", w.Code)
  62. }
  63. // Non-exempt route is still capped.
  64. w = httptest.NewRecorder()
  65. r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/x", bytes.NewReader(make([]byte, limit*4))))
  66. if w.Code == http.StatusOK {
  67. t.Errorf("non-exempt over-limit POST should not succeed, got 200")
  68. }
  69. }