Skip to content
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
34 changes: 34 additions & 0 deletions graphql/graphql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,40 @@ func TestWithdrawals(t *testing.T) {
}
}

// TestGraphQLMaxDepth ensures that queries exceeding the configured maximum depth
// are rejected to prevent resource exhaustion from deeply nested operations.
func TestGraphQLMaxDepth(t *testing.T) {
stack := createNode(t)
defer stack.Close()

h, err := newHandler(stack, nil, nil, []string{}, []string{})
if err != nil {
t.Fatalf("could not create graphql service: %v", err)
}

var b strings.Builder
for i := 0; i < maxQueryDepth+1; i++ {
b.WriteString("ommers{")
}
b.WriteString("number")
for i := 0; i < maxQueryDepth+1; i++ {
b.WriteString("}")
}
query := fmt.Sprintf("{block{%s}}", b.String())

res := h.Schema.Exec(context.Background(), query, "", nil)
var found bool
for _, err := range res.Errors {
if err.Rule == "MaxDepthExceeded" {
found = true
break
}
}
if !found {
t.Fatalf("expected max depth exceeded error, got %v", res.Errors)
}
}

func createNode(t *testing.T) *node.Node {
stack, err := node.New(&node.Config{
HTTPHost: "127.0.0.1",
Expand Down
5 changes: 4 additions & 1 deletion graphql/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ import (
gqlErrors "github.com/graph-gophers/graphql-go/errors"
)

// maxQueryDepth limits the maximum field nesting depth allowed in GraphQL queries.
const maxQueryDepth = 20

type handler struct {
Schema *graphql.Schema
}
Expand Down Expand Up @@ -116,7 +119,7 @@ func New(stack *node.Node, backend ethapi.Backend, filterSystem *filters.FilterS
func newHandler(stack *node.Node, backend ethapi.Backend, filterSystem *filters.FilterSystem, cors, vhosts []string) (*handler, error) {
q := Resolver{backend, filterSystem}

s, err := graphql.ParseSchema(schema, &q)
s, err := graphql.ParseSchema(schema, &q, graphql.MaxDepth(maxQueryDepth))
if err != nil {
return nil, err
}
Expand Down
Loading