Skip to content

Commit

Permalink
More gracefully handle inputs that exceed the limit
Browse files Browse the repository at this point in the history
  • Loading branch information
Dynom committed Jul 7, 2018
1 parent e144927 commit e75801e
Showing 2 changed files with 59 additions and 2 deletions.
17 changes: 15 additions & 2 deletions server/http.go
Original file line number Diff line number Diff line change
@@ -24,6 +24,7 @@ var (
ErrMissingBody = errors.New("missing body")
ErrInvalidRequest = errors.New("invalid request")
ErrInvalidRequestBody = errors.New("invalid request body")
ErrBodyTooLarge = errors.New("body too large")
)

type contextKey int
@@ -215,15 +216,27 @@ func createRequestHandler(logger *logrus.Logger, svc Service, validators []Valid
func getRequestFromHTTPRequest(r *http.Request) (tySugRequest, error) {
var req tySugRequest

b, err := ioutil.ReadAll(io.LimitReader(r.Body, maxBodySize))
var maxSizePlusOne int64 = maxBodySize + 1
b, err := ioutil.ReadAll(io.LimitReader(r.Body, maxSizePlusOne))
if err != nil {
if err == io.EOF {
return req, ErrMissingBody
}
return req, ErrInvalidRequest
}

err = json.Unmarshal(b, &req)
if int64(len(b)) == maxSizePlusOne {
return req, ErrBodyTooLarge
}

var limit int
if len(b) > maxBodySize {
limit = maxBodySize
} else {
limit = len(b)
}

err = json.Unmarshal(b[:limit], &req)
if err != nil {
return req, ErrInvalidRequestBody
}
44 changes: 44 additions & 0 deletions server/http_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package server

import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)

func TestGetRequestFromHTTPRequest(t *testing.T) {

t.Run("empty payload", func(t *testing.T) {
request, err := createStubbedTySugRequest(strings.NewReader("{}"))
if err != nil {
t.Errorf("Expected error was thrown '%s'\n%+v", err, request)
}
})

t.Run("payload too large", func(t *testing.T) {
i := strings.Repeat("a", maxBodySize+1)
payload, _ := json.Marshal(tySugRequest{Input: i})
req := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(payload))

request, err := getRequestFromHTTPRequest(req)
if err != ErrBodyTooLarge {
t.Errorf("Expected an error to be thrown %+v", request)
}
})

t.Run("invalid request body", func(t *testing.T) {
request, err := createStubbedTySugRequest(strings.NewReader("{Input: nil}"))
if err != ErrInvalidRequestBody {
t.Errorf("Expected an error to be thrown %+v", request)
}
})
}

func createStubbedTySugRequest(r io.Reader) (tySugRequest, error) {
req := httptest.NewRequest(http.MethodPost, "/", r)
return getRequestFromHTTPRequest(req)
}

0 comments on commit e75801e

Please sign in to comment.