Validation
Validation checks a document against the schema before it runs: that the fields
exist, that arguments have the right types, that fragments are used, and so on.
graphql.Do validates every request with the rules of the specification. This
page shows what those rules cover, how to validate a document yourself, and how
to write and add rules of your own; the complete program
adds a depth limit.
The specified rules
graphql.SpecifiedRules holds the 24 rules that graphql.Do applies. A
document that breaks one of them is not executed: the response has data: null
and an error for every problem found, with its location and, for misspelled
names, a suggestion:
{"message":"Cannot query field \"nme\" on type \"Author\". Did you mean \"name\"?","locations":[{"line":1,"column":12}]}Validation reports every problem it finds, without a limit, and suggestions name fields and types of the schema. A cap on the number of errors (#19) and an option to turn suggestions off (#74) are on the roadmap.
Three rules of the specification are not implemented yet, so documents that break them pass validation:
| Rule | Example | Issue |
|---|---|---|
| Executable definitions | type Foo { a: Int } { book { title } } passes, and fails later in execution. | #155 |
| Directives are unique per location | title @include(if: true) @include(if: false) | #24 |
| Single root field in subscriptions | subscription { a b } | #150 |
Validating a document
graphql.ValidateDocument validates a parsed document:
result := graphql.ValidateDocument(&schema, doc, nil)
if !result.IsValid {
// result.Errors holds the errors, as gqlerrors.FormattedError values.
}With nil rules, or an empty list, it uses graphql.SpecifiedRules; otherwise
it applies exactly the rules given, in a single walk of the document. Validate
documents yourself when you execute them with
graphql.Execute, which
does not validate, or to check documents ahead of time, for example when you
register the operations a client may send.
Writing a rule
A rule is a graphql.ValidationRuleFn: a function that receives a
*graphql.ValidationContext and returns the visitor that walks the document. It
is called for every validation, so state kept in its closure belongs to one
document. This rule rejects introspection:
func NoIntrospectionRule(ctx *graphql.ValidationContext) *graphql.ValidationRuleInstance {
return &graphql.ValidationRuleInstance{
VisitorOpts: &visitor.VisitorOptions{
KindFuncMap: map[string]visitor.NamedVisitFuncs{
kinds.Field: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
field := p.Node.(*ast.Field)
if field.Name.Value == "__schema" || field.Name.Value == "__type" {
ctx.ReportError(graphql.NewLocatedError(
"Introspection is disabled.", []ast.Node{field}))
}
return visitor.ActionNoChange, nil
},
},
},
},
}
}KindFuncMapmaps a node kind, from thelanguage/kindspackage, to the functions called when the walk enters (KindorEnter) and leaves (Leave) a node of that kind.ReportErrorrecords an error. Build it withgraphql.NewLocatedErrorand the offending nodes, so the error points at them.- The context also gives the schema (
Schema), a fragment by name (Fragment), the variables an operation uses (RecursiveVariableUsages) and, while walking, the type information of the current node:ParentType,FieldDef,Type,Argument. SeeValidationContext.
All rules walk the document together, so a rule cannot rely on another one
having passed. The depth rule in the complete program follows fragment spreads
through ctx.Fragment, and guards against two kinds of documents that reach it
like any other:
- Fragment cycles. It stops at a fragment it is already inside;
NoFragmentCyclesRulereports the cycle. - Fragments spread many times. A document where each fragment spreads the next one twice has as many paths as 2 to the power of its fragments. The rule computes each fragment’s depth once and reuses it, so its work grows with the size of the document, not with the number of paths.
Adding rules
To keep the specified rules and add your own, copy the list before appending, so
that graphql.SpecifiedRules itself never changes:
// rules are the specified rules plus a depth limit. The specified rules are
// copied so that appending never changes graphql.SpecifiedRules.
var rules = append(
append([]graphql.ValidationRuleFn{}, graphql.SpecifiedRules...),
MaxDepthRule(3),
)graphql.Do always uses the specified rules; passing your own is on the roadmap
(#17). Until then, run the three
steps yourself:
// do runs a request like graphql.Do, validating it with rules.
func do(schema graphql.Schema, request string) *graphql.Result {
doc, err := parser.Parse(parser.ParseParams{
Source: source.NewSource(&source.Source{Body: []byte(request), Name: "GraphQL request"}),
})
if err != nil {
return &graphql.Result{Errors: gqlerrors.FormatErrors(err)}
}
if v := graphql.ValidateDocument(&schema, doc, rules); !v.IsValid {
return &graphql.Result{Errors: v.Errors}
}
return graphql.Execute(graphql.ExecuteParams{Schema: schema, AST: doc})
}This keeps the same responses as graphql.Do for parse and validation errors.
It does not call the Init, parse and validation hooks of
extensions, so execution hooks do not
get the context that Init would have returned; graphql.Execute calls the
execution hooks as usual.
Ready-made rules for depth, aliases and introspection (#20) and query cost analysis (#21) are on the roadmap.
Cost
graphql.Do parses and validates every request, even when clients send the
same document again and again. Validating once, when a document is first seen
or registered, and executing the parsed document after that saves the work; a
document cache in graphql.Do is on the roadmap
(#33).
Complete program
main.go
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/gql-go/graphql"
"github.com/gql-go/graphql/gqlerrors"
"github.com/gql-go/graphql/language/ast"
"github.com/gql-go/graphql/language/kinds"
"github.com/gql-go/graphql/language/parser"
"github.com/gql-go/graphql/language/source"
"github.com/gql-go/graphql/language/visitor"
)
// MaxDepthRule returns a validation rule that rejects operations whose
// selections are nested more than max fields deep, fragments included.
func MaxDepthRule(max int) graphql.ValidationRuleFn {
return func(ctx *graphql.ValidationContext) *graphql.ValidationRuleInstance {
// Fragment depths are computed once per document, so that fragments
// spread many times do not multiply the work.
fragmentDepths := map[string]int{}
inProgress := map[string]bool{}
var depth func(set *ast.SelectionSet) int
fragmentDepth := func(name string) int {
if d, ok := fragmentDepths[name]; ok {
return d
}
frag := ctx.Fragment(name)
// NoFragmentCyclesRule reports cycles; stop here so that this
// rule does not loop on them.
if frag == nil || inProgress[name] {
return 0
}
inProgress[name] = true
d := depth(frag.SelectionSet)
delete(inProgress, name)
fragmentDepths[name] = d
return d
}
depth = func(set *ast.SelectionSet) int {
if set == nil {
return 0
}
deepest := 0
for _, sel := range set.Selections {
d := 0
switch sel := sel.(type) {
case *ast.Field:
if sel.SelectionSet != nil {
d = 1 + depth(sel.SelectionSet)
}
case *ast.InlineFragment:
d = depth(sel.SelectionSet)
case *ast.FragmentSpread:
d = fragmentDepth(sel.Name.Value)
}
if d > deepest {
deepest = d
}
}
return deepest
}
return &graphql.ValidationRuleInstance{
VisitorOpts: &visitor.VisitorOptions{
KindFuncMap: map[string]visitor.NamedVisitFuncs{
kinds.OperationDefinition: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
op := p.Node.(*ast.OperationDefinition)
if d := depth(op.SelectionSet); d > max {
ctx.ReportError(graphql.NewLocatedError(
fmt.Sprintf("Operation is %d levels deep; the maximum is %d.", d, max),
[]ast.Node{op},
))
}
return visitor.ActionNoChange, nil
},
},
},
},
}
}
}
// rules are the specified rules plus a depth limit. The specified rules are
// copied so that appending never changes graphql.SpecifiedRules.
var rules = append(
append([]graphql.ValidationRuleFn{}, graphql.SpecifiedRules...),
MaxDepthRule(3),
)
// do runs a request like graphql.Do, validating it with rules.
func do(schema graphql.Schema, request string) *graphql.Result {
doc, err := parser.Parse(parser.ParseParams{
Source: source.NewSource(&source.Source{Body: []byte(request), Name: "GraphQL request"}),
})
if err != nil {
return &graphql.Result{Errors: gqlerrors.FormatErrors(err)}
}
if v := graphql.ValidateDocument(&schema, doc, rules); !v.IsValid {
return &graphql.Result{Errors: v.Errors}
}
return graphql.Execute(graphql.ExecuteParams{Schema: schema, AST: doc})
}
type Author struct {
Name string `json:"name"`
Books []*Book `json:"books"`
}
type Book struct {
Title string `json:"title"`
Author *Author `json:"author"`
}
func main() {
leGuin := &Author{Name: "Ursula K. Le Guin"}
leGuin.Books = []*Book{{Title: "A Wizard of Earthsea", Author: leGuin}}
authorType := graphql.NewObject(graphql.ObjectConfig{
Name: "Author",
Fields: graphql.Fields{
"name": &graphql.Field{Type: graphql.String},
},
})
bookType := graphql.NewObject(graphql.ObjectConfig{
Name: "Book",
Fields: graphql.Fields{
"title": &graphql.Field{Type: graphql.String},
"author": &graphql.Field{Type: authorType},
},
})
authorType.AddFieldConfig("books", &graphql.Field{Type: graphql.NewList(bookType)})
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"author": &graphql.Field{
Type: authorType,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return leGuin, nil
},
},
},
}),
})
if err != nil {
log.Fatal(err)
}
for _, request := range []string{
`{ author { name books { title } } }`,
`{ author { books { author { books { title } } } } }`,
`{ ...Deep } fragment Deep on Query { author { ...Books } }
fragment Books on Author { books { author { books { title } } } }`,
`{ author { nme } }`,
} {
out, _ := json.Marshal(do(schema, request))
fmt.Println(string(out))
}
}The program runs four requests through do, with a depth limit of three: one
within the limit, one four levels deep, one four levels deep through fragments,
and one with a misspelled field, which the specified rules reject:
{"data":{"author":{"books":[{"title":"A Wizard of Earthsea"}],"name":"Ursula K. Le Guin"}}}
{"data":null,"errors":[{"message":"Operation is 4 levels deep; the maximum is 3.","locations":[{"line":1,"column":1}]}]}
{"data":null,"errors":[{"message":"Operation is 4 levels deep; the maximum is 3.","locations":[{"line":1,"column":1}]}]}
{"data":null,"errors":[{"message":"Cannot query field \"nme\" on type \"Author\". Did you mean \"name\"?","locations":[{"line":1,"column":12}]}]}