Debian Codegraph @

src/graphql/validation/validate.py

raw
1 from typing import Collection, Dict, List, Optional, Tuple, Type
2
3 from ..error import GraphQLError
4 from ..language import DocumentNode, ParallelVisitor, visit
5 from ..language.ast import QUERY_DOCUMENT_KEYS
6 from ..pyutils import inspect, is_collection
7 from ..type import GraphQLSchema, assert_valid_schema
8 from ..utilities import TypeInfo, TypeInfoVisitor
9 from .rules import ASTValidationRule
10 from .specified_rules import specified_rules, specified_sdl_rules
11 from .validation_context import SDLValidationContext, ValidationContext
12
13 __all__ = ["assert_valid_sdl", "assert_valid_sdl_extension", "validate", "validate_sdl"]
14
15
16 class ValidationAbortedError(RuntimeError):
17 """Error when a validation has been aborted (error limit reached)."""
18
19
20 # Per the specification, descriptions must not affect validation.
21 # See https://spec.graphql.org/draft/#sec-Descriptions
22 query_document_keys_to_validate: Dict[str, Tuple[str, ...]] = {
23 kind: tuple(key for key in keys if key != "description")
24 for kind, keys in QUERY_DOCUMENT_KEYS.items()
25 }
26
27
28 def validate(
29 schema: GraphQLSchema,
30 document_ast: DocumentNode,
31 rules: Optional[Collection[Type[ASTValidationRule]]] = None,
32 max_errors: Optional[int] = None,
33 type_info: Optional[TypeInfo] = None,
34 ) -> List[GraphQLError]:
35 """Implements the "Validation" section of the spec.
36
37 Validation runs synchronously, returning a list of encountered errors, or an empty
38 list if no errors were encountered and the document is valid.
39
40 A list of specific validation rules may be provided. If not provided, the default
41 list of rules defined by the GraphQL specification will be used.
42
43 Each validation rule is a ValidationRule object which is a visitor object that holds
44 a ValidationContext (see the language/visitor API). Visitor methods are expected to
45 return GraphQLErrors, or lists of GraphQLErrors when invalid.
46
47 Validate will stop validation after a ``max_errors`` limit has been reached.
48 Attackers can send pathologically invalid queries to induce a DoS attack,
49 so by default ``max_errors`` set to 100 errors.
50
51 Providing a custom TypeInfo instance is deprecated; omit the ``type_info``
52 argument so that validate creates the TypeInfo instance. It will be removed in v3.3.
53 """
54 if not document_ast or not isinstance(document_ast, DocumentNode):
55 raise TypeError("Must provide document.")
56 # If the schema used for validation is invalid, throw an error.
57 assert_valid_schema(schema)
58 if max_errors is None:
59 max_errors = 100
60 elif not isinstance(max_errors, int):
61 raise TypeError("The maximum number of errors must be passed as an int.")
62 if type_info is None:
63 type_info = TypeInfo(schema)
64 elif not isinstance(type_info, TypeInfo):
65 raise TypeError(f"Not a TypeInfo object: {inspect(type_info)}.")
66 if rules is None:
67 rules = specified_rules
68 elif not is_collection(rules) or not all(
69 isinstance(rule, type) and issubclass(rule, ASTValidationRule) for rule in rules
70 ):
71 raise TypeError(
72 "Rules must be specified as a collection of ASTValidationRule subclasses."
73 )
74
75 errors: List[GraphQLError] = []
76
77 def on_error(error: GraphQLError) -> None:
78 if len(errors) >= max_errors:
79 errors.append(
80 GraphQLError(
81 "Too many validation errors, error limit reached."
82 " Validation aborted."
83 )
84 )
85 raise ValidationAbortedError
86 errors.append(error)
87
88 context = ValidationContext(schema, document_ast, type_info, on_error)
89
90 # This uses a specialized visitor which runs multiple visitors in parallel,
91 # while maintaining the visitor skip and break API.
92 visitors = [rule(context) for rule in rules]
93
94 # Visit the whole document with each instance of all provided rules.
95 try:
96 visit(
97 document_ast,
98 TypeInfoVisitor(type_info, ParallelVisitor(visitors)),
99 query_document_keys_to_validate,
100 )
101 except ValidationAbortedError:
102 pass
103 return errors
104
105
106 def validate_sdl(
107 document_ast: DocumentNode,
108 schema_to_extend: Optional[GraphQLSchema] = None,
109 rules: Optional[Collection[Type[ASTValidationRule]]] = None,
110 ) -> List[GraphQLError]:
111 """Validate an SDL document.
112
113 For internal use only.
114 """
115 errors: List[GraphQLError] = []
116 context = SDLValidationContext(document_ast, schema_to_extend, errors.append)
117 if rules is None:
118 rules = specified_sdl_rules
119 visitors = [rule(context) for rule in rules]
120 visit(document_ast, ParallelVisitor(visitors))
121 return errors
122
123
124 def assert_valid_sdl(document_ast: DocumentNode) -> None:
125 """Assert document is valid SDL.
126
127 Utility function which asserts a SDL document is valid by throwing an error if it
128 is invalid.
129 """
130
131 errors = validate_sdl(document_ast)
132 if errors:
133 raise TypeError("\n\n".join(error.message for error in errors))
134
135
136 def assert_valid_sdl_extension(
137 document_ast: DocumentNode, schema: GraphQLSchema
138 ) -> None:
139 """Assert document is a valid SDL extension.
140
141 Utility function which asserts a SDL document is valid by throwing an error if it
142 is invalid.
143 """
144
145 errors = validate_sdl(document_ast, schema)
146 if errors:
147 raise TypeError("\n\n".join(error.message for error in errors))