Skip to content

Commit 2a38a95

Browse files
pavelnikolovKNiepok
authored andcommitted
Add maximum query length schema option (graph-gophers#494)
1 parent f67a266 commit 2a38a95

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

graphql.go

+11
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ type Schema struct {
7979
schema *types.Schema
8080
res *resolvable.Schema
8181

82+
maxQueryLength int
8283
maxDepth int
8384
maxParallelism int
8485
rateLimiter ratelimit.RateLimiter
@@ -137,6 +138,13 @@ func RateLimiter(r ratelimit.RateLimiter) SchemaOpt {
137138
}
138139
}
139140

141+
// MaxQueryLength specifies the maximum allowed query length in bytes. The default is 0 which disables max length checking.
142+
func MaxQueryLength(n int) SchemaOpt {
143+
return func(s *Schema) {
144+
s.maxQueryLength = n
145+
}
146+
}
147+
140148
// Tracer is used to trace queries and fields. It defaults to tracer.Noop.
141149
func Tracer(t tracer.Tracer) SchemaOpt {
142150
return func(s *Schema) {
@@ -234,6 +242,9 @@ func (s *Schema) Exec(ctx context.Context, queryString string, operationName str
234242
}
235243

236244
func (s *Schema) exec(ctx context.Context, queryString string, operationName string, variables map[string]interface{}, res *resolvable.Schema) *Response {
245+
if s.maxQueryLength > 0 && len(queryString) > s.maxQueryLength {
246+
return &Response{Errors: []*errors.QueryError{errors.Errorf("query length %d exceeds the maximum allowed query length of %d bytes", len(queryString), s.maxQueryLength)}}
247+
}
237248
doc, qErr := query.Parse(queryString)
238249
if qErr != nil {
239250
return &Response{Errors: []*errors.QueryError{qErr}}

graphql_test.go

+31
Original file line numberDiff line numberDiff line change
@@ -4565,6 +4565,37 @@ func TestCircularFragmentMaxDepth(t *testing.T) {
45654565
})
45664566
}
45674567

4568+
func TestMaxQueryLength(t *testing.T) {
4569+
withMaxQueryLen := graphql.MustParseSchema(starwars.Schema, &starwars.Resolver{}, graphql.MaxQueryLength(75))
4570+
gqltesting.RunTests(t, []*gqltesting.Test{
4571+
{
4572+
Schema: withMaxQueryLen,
4573+
// Query length is 69 bytes
4574+
Query: `
4575+
query {
4576+
hero(episode: EMPIRE) {
4577+
name
4578+
}
4579+
}
4580+
`,
4581+
ExpectedResult: `{"hero":{"name":"Luke Skywalker"}}`,
4582+
},
4583+
{
4584+
Schema: withMaxQueryLen,
4585+
Query: `
4586+
query HeroForEpisode {
4587+
hero(episode: WRATH_OF_KHAN) {
4588+
name
4589+
}
4590+
}
4591+
`,
4592+
ExpectedErrors: []*gqlerrors.QueryError{{
4593+
Message: `query length 91 exceeds the maximum allowed query length of 75 bytes`,
4594+
}},
4595+
},
4596+
})
4597+
}
4598+
45684599
func TestQueryService(t *testing.T) {
45694600
t.Parallel()
45704601

0 commit comments

Comments
 (0)