Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enforce content type for POST requests #689

Merged
merged 2 commits into from
May 8, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 19 additions & 8 deletions handler/graphql.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"io"
"io/ioutil"
"mime"
"net/http"
"os"
"strconv"
Expand All @@ -16,7 +17,7 @@ import (
"github.com/99designs/gqlgen/complexity"
"github.com/99designs/gqlgen/graphql"
"github.com/gorilla/websocket"
"github.com/hashicorp/golang-lru"
lru "github.com/hashicorp/golang-lru"
"github.com/vektah/gqlparser/ast"
"github.com/vektah/gqlparser/gqlerror"
"github.com/vektah/gqlparser/parser"
Expand Down Expand Up @@ -369,8 +370,20 @@ func (gh *graphqlHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
case http.MethodPost:
contentType := strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0]
if contentType == "multipart/form-data" {
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
sendErrorf(w, http.StatusBadRequest, "error parsing request Content-Type")
return
}

switch mediaType {
case "application/json":
if err := jsonDecode(r.Body, &reqParams); err != nil {
sendErrorf(w, http.StatusBadRequest, "json body could not be decoded: "+err.Error())
return
}

case "multipart/form-data":
var closers []io.Closer
var tmpFiles []string
defer func() {
Expand All @@ -385,11 +398,9 @@ func (gh *graphqlHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
sendErrorf(w, http.StatusBadRequest, "multipart body could not be decoded: "+err.Error())
return
}
} else {
if err := jsonDecode(r.Body, &reqParams); err != nil {
sendErrorf(w, http.StatusBadRequest, "json body could not be decoded: "+err.Error())
return
}
default:
sendErrorf(w, http.StatusBadRequest, "unsupported Content-Type: "+mediaType)
return
}
default:
w.WriteHeader(http.StatusMethodNotAllowed)
Expand Down
45 changes: 44 additions & 1 deletion handler/graphql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import (
"testing"

"github.com/99designs/gqlgen/graphql"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/vektah/gqlparser/ast"
Expand Down Expand Up @@ -88,6 +87,49 @@ func TestHandlerPOST(t *testing.T) {
assert.Equal(t, resp.Header().Get("Content-Type"), "application/json")
assert.Equal(t, `{"errors":[{"message":"mutations are not supported"}],"data":null}`, resp.Body.String())
})

t.Run("validate content type", func(t *testing.T) {
doReq := func(handler http.Handler, method string, target string, body string, contentType string) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, target, strings.NewReader(body))
if contentType != "" {
r.Header.Set("Content-Type", contentType)
}
w := httptest.NewRecorder()

handler.ServeHTTP(w, r)
return w
}

validContentTypes := []string{
"application/json",
"application/json; charset=utf-8",
}

for _, contentType := range validContentTypes {
t.Run(fmt.Sprintf("allow for content type %s", contentType), func(t *testing.T) {
resp := doReq(h, "POST", "/graphql", `{"query":"{ me { name } }"}`, contentType)
assert.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, `{"data":{"name":"test"}}`, resp.Body.String())
})
}

invalidContentTypes := []struct{ contentType, expectedError string }{
{"", "error parsing request Content-Type"},
{"text/plain", "unsupported Content-Type: text/plain"},

// These content types are currently not supported, but they are supported by other GraphQL servers, like express-graphql.
{"application/x-www-form-urlencoded", "unsupported Content-Type: application/x-www-form-urlencoded"},
{"application/graphql", "unsupported Content-Type: application/graphql"},
}

for _, tc := range invalidContentTypes {
t.Run(fmt.Sprintf("reject for content type %s", tc.contentType), func(t *testing.T) {
resp := doReq(h, "POST", "/graphql", `{"query":"{ me { name } }"}`, tc.contentType)
assert.Equal(t, http.StatusBadRequest, resp.Code)
assert.Equal(t, fmt.Sprintf(`{"errors":[{"message":"%s"}],"data":null}`, tc.expectedError), resp.Body.String())
})
}
})
}

func TestHandlerGET(t *testing.T) {
Expand Down Expand Up @@ -640,6 +682,7 @@ func createUploadRequest(t *testing.T, operations, mapData string, files []file)

func doRequest(handler http.Handler, method string, target string, body string) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, target, strings.NewReader(body))
r.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()

handler.ServeHTTP(w, r)
Expand Down