Skip to content

Commit 5e16071

Browse files
authored
Add maximum query length schema option (#494)
1 parent edea822 commit 5e16071

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

graphql.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ type Schema struct {
7474
schema *types.Schema
7575
res *resolvable.Schema
7676

77+
maxQueryLength int
7778
maxDepth int
7879
maxParallelism int
7980
tracer tracer.Tracer
@@ -123,6 +124,13 @@ func MaxParallelism(n int) SchemaOpt {
123124
}
124125
}
125126

127+
// MaxQueryLength specifies the maximum allowed query length in bytes. The default is 0 which disables max length checking.
128+
func MaxQueryLength(n int) SchemaOpt {
129+
return func(s *Schema) {
130+
s.maxQueryLength = n
131+
}
132+
}
133+
126134
// Tracer is used to trace queries and fields. It defaults to tracer.Noop.
127135
func Tracer(t tracer.Tracer) SchemaOpt {
128136
return func(s *Schema) {
@@ -204,6 +212,9 @@ func (s *Schema) Exec(ctx context.Context, queryString string, operationName str
204212
}
205213

206214
func (s *Schema) exec(ctx context.Context, queryString string, operationName string, variables map[string]interface{}, res *resolvable.Schema) *Response {
215+
if s.maxQueryLength > 0 && len(queryString) > s.maxQueryLength {
216+
return &Response{Errors: []*errors.QueryError{errors.Errorf("query length %d exceeds the maximum allowed query length of %d bytes", len(queryString), s.maxQueryLength)}}
217+
}
207218
doc, qErr := query.Parse(queryString)
208219
if qErr != nil {
209220
return &Response{Errors: []*errors.QueryError{qErr}}

graphql_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4518,6 +4518,37 @@ func TestCircularFragmentMaxDepth(t *testing.T) {
45184518
})
45194519
}
45204520

4521+
func TestMaxQueryLength(t *testing.T) {
4522+
withMaxQueryLen := graphql.MustParseSchema(starwars.Schema, &starwars.Resolver{}, graphql.MaxQueryLength(75))
4523+
gqltesting.RunTests(t, []*gqltesting.Test{
4524+
{
4525+
Schema: withMaxQueryLen,
4526+
// Query length is 69 bytes
4527+
Query: `
4528+
query {
4529+
hero(episode: EMPIRE) {
4530+
name
4531+
}
4532+
}
4533+
`,
4534+
ExpectedResult: `{"hero":{"name":"Luke Skywalker"}}`,
4535+
},
4536+
{
4537+
Schema: withMaxQueryLen,
4538+
Query: `
4539+
query HeroForEpisode {
4540+
hero(episode: WRATH_OF_KHAN) {
4541+
name
4542+
}
4543+
}
4544+
`,
4545+
ExpectedErrors: []*gqlerrors.QueryError{{
4546+
Message: `query length 91 exceeds the maximum allowed query length of 75 bytes`,
4547+
}},
4548+
},
4549+
})
4550+
}
4551+
45214552
func TestQueryService(t *testing.T) {
45224553
t.Parallel()
45234554

0 commit comments

Comments
 (0)