Skip to content

Commit f59ed35

Browse files
atoulmeholiman
andauthored
graphql: always return 400 if errors are present in the response (#21882)
* Make sure to return 400 when errors are present in the response * graphql: use less memory in chainconfig for tests Co-authored-by: Martin Holst Swende <martin@swende.se>
1 parent c92faee commit f59ed35

2 files changed

Lines changed: 84 additions & 4 deletions

File tree

‎graphql/graphql_test.go‎

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,13 @@ import (
2222
"net/http"
2323
"strings"
2424
"testing"
25+
"time"
2526

27+
"github.com/ethereum/go-ethereum/common"
28+
"github.com/ethereum/go-ethereum/consensus/ethash"
29+
"github.com/ethereum/go-ethereum/core"
2630
"github.com/ethereum/go-ethereum/eth"
31+
"github.com/ethereum/go-ethereum/miner"
2732
"github.com/ethereum/go-ethereum/node"
2833
"github.com/stretchr/testify/assert"
2934
)
@@ -61,6 +66,7 @@ func TestGraphQLHTTPOnSamePort_GQLRequest_Successful(t *testing.T) {
6166
t.Fatalf("could not read from response body: %v", err)
6267
}
6368
expected := "{\"data\":{\"block\":{\"number\":\"0x0\"}}}"
69+
assert.Equal(t, 200, resp.StatusCode)
6470
assert.Equal(t, expected, string(bodyBytes))
6571
}
6672

@@ -90,6 +96,32 @@ func TestGraphQLHTTPOnSamePort_GQLRequest_Unsuccessful(t *testing.T) {
9096
assert.Equal(t, "404 page not found\n", string(bodyBytes))
9197
}
9298

99+
// Tests that 400 is returned when an invalid RPC request is made.
100+
func TestGraphQL_BadRequest(t *testing.T) {
101+
stack := createNode(t, true)
102+
defer stack.Close()
103+
// start node
104+
if err := stack.Start(); err != nil {
105+
t.Fatalf("could not start node: %v", err)
106+
}
107+
// create http request
108+
body := strings.NewReader("{\"query\": \"{bleh{number}}\",\"variables\": null}")
109+
gqlReq, err := http.NewRequest(http.MethodGet, fmt.Sprintf("http://%s/graphql", "127.0.0.1:9393"), body)
110+
if err != nil {
111+
t.Error("could not issue new http request ", err)
112+
}
113+
gqlReq.Header.Set("Content-Type", "application/json")
114+
// read from response
115+
resp := doHTTPRequest(t, gqlReq)
116+
bodyBytes, err := ioutil.ReadAll(resp.Body)
117+
if err != nil {
118+
t.Fatalf("could not read from response body: %v", err)
119+
}
120+
expected := "{\"errors\":[{\"message\":\"Cannot query field \\\"bleh\\\" on type \\\"Query\\\".\",\"locations\":[{\"line\":1,\"column\":2}]}]}"
121+
assert.Equal(t, expected, string(bodyBytes))
122+
assert.Equal(t, 400, resp.StatusCode)
123+
}
124+
93125
func createNode(t *testing.T, gqlEnabled bool) *node.Node {
94126
stack, err := node.New(&node.Config{
95127
HTTPHost: "127.0.0.1",
@@ -110,8 +142,24 @@ func createNode(t *testing.T, gqlEnabled bool) *node.Node {
110142
}
111143

112144
func createGQLService(t *testing.T, stack *node.Node, endpoint string) {
113-
// create backend
114-
ethBackend, err := eth.New(stack, &eth.DefaultConfig)
145+
// create backend (use a config which is light on mem consumption)
146+
ethConf := &eth.Config{
147+
Genesis: core.DeveloperGenesisBlock(15, common.Address{}),
148+
Miner: miner.Config{
149+
Etherbase: common.HexToAddress("0xaabb"),
150+
},
151+
Ethash: ethash.Config{
152+
PowMode: ethash.ModeTest,
153+
},
154+
NetworkId: 1337,
155+
TrieCleanCache: 5,
156+
TrieCleanCacheJournal: "triecache",
157+
TrieCleanCacheRejournal: 60 * time.Minute,
158+
TrieDirtyCache: 5,
159+
TrieTimeout: 60 * time.Minute,
160+
SnapshotCache: 5,
161+
}
162+
ethBackend, err := eth.New(stack, ethConf)
115163
if err != nil {
116164
t.Fatalf("could not create eth backend: %v", err)
117165
}

‎graphql/service.go‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,44 @@
1717
package graphql
1818

1919
import (
20+
"encoding/json"
21+
"net/http"
22+
2023
"github.com/ethereum/go-ethereum/internal/ethapi"
2124
"github.com/ethereum/go-ethereum/node"
2225
"github.com/graph-gophers/graphql-go"
23-
"github.com/graph-gophers/graphql-go/relay"
2426
)
2527

28+
type handler struct {
29+
Schema *graphql.Schema
30+
}
31+
32+
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
33+
var params struct {
34+
Query string `json:"query"`
35+
OperationName string `json:"operationName"`
36+
Variables map[string]interface{} `json:"variables"`
37+
}
38+
if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
39+
http.Error(w, err.Error(), http.StatusBadRequest)
40+
return
41+
}
42+
43+
response := h.Schema.Exec(r.Context(), params.Query, params.OperationName, params.Variables)
44+
responseJSON, err := json.Marshal(response)
45+
if err != nil {
46+
http.Error(w, err.Error(), http.StatusInternalServerError)
47+
return
48+
}
49+
if len(response.Errors) > 0 {
50+
w.WriteHeader(http.StatusBadRequest)
51+
}
52+
53+
w.Header().Set("Content-Type", "application/json")
54+
w.Write(responseJSON)
55+
56+
}
57+
2658
// New constructs a new GraphQL service instance.
2759
func New(stack *node.Node, backend ethapi.Backend, cors, vhosts []string) error {
2860
if backend == nil {
@@ -41,7 +73,7 @@ func newHandler(stack *node.Node, backend ethapi.Backend, cors, vhosts []string)
4173
if err != nil {
4274
return err
4375
}
44-
h := &relay.Handler{Schema: s}
76+
h := handler{Schema: s}
4577
handler := node.NewHTTPHandlerStack(h, cors, vhosts)
4678

4779
stack.RegisterHandler("GraphQL UI", "/graphql/ui", GraphiQL{})

0 commit comments

Comments
 (0)