Debian Codegraph @

src/graphql/validation/rules/variables_in_allowed_position.py

raw
1 from typing import Any, Dict, Optional, cast
2
3 from ...error import GraphQLError
4 from ...language import (
5 NullValueNode,
6 OperationDefinitionNode,
7 ValueNode,
8 VariableDefinitionNode,
9 )
10 from ...pyutils import Undefined
11 from ...type import (
12 GraphQLInputObjectType,
13 GraphQLNonNull,
14 GraphQLSchema,
15 GraphQLType,
16 is_input_object_type,
17 is_non_null_type,
18 is_nullable_type,
19 )
20 from ...utilities import type_from_ast, is_type_sub_type_of
21 from . import ValidationContext, ValidationRule
22
23 __all__ = ["VariablesInAllowedPositionRule"]
24
25
26 class VariablesInAllowedPositionRule(ValidationRule):
27 """Variables in allowed position
28
29 Variable usages must be compatible with the arguments they are passed to.
30
31 See https://spec.graphql.org/draft/#sec-All-Variable-Usages-are-Allowed
32 """
33
34 def __init__(self, context: ValidationContext):
35 super().__init__(context)
36 self.var_def_map: Dict[str, Any] = {}
37
38 def enter_operation_definition(self, *_args: Any) -> None:
39 self.var_def_map.clear()
40
41 def leave_operation_definition(
42 self, operation: OperationDefinitionNode, *_args: Any
43 ) -> None:
44 var_def_map = self.var_def_map
45 usages = self.context.get_recursive_variable_usages(operation)
46
47 for usage in usages:
48 node, type_ = usage.node, usage.type
49 default_value = usage.default_value
50 parent_type = usage.parent_type
51 var_name = node.name.value
52 var_def = var_def_map.get(var_name)
53 if var_def and type_:
54 # A var type is allowed if it is the same or more strict (e.g. is a
55 # subtype of) than the expected type. It can be more strict if the
56 # variable type is non-null when the expected type is nullable. If both
57 # are list types, the variable item type can be more strict than the
58 # expected item type (contravariant).
59 schema = self.context.schema
60 var_type = type_from_ast(schema, var_def.type)
61 if var_type and not allowed_variable_usage(
62 schema, var_type, var_def.default_value, type_, default_value
63 ):
64 self.report_error(
65 GraphQLError(
66 f"Variable '${var_name}' of type '{var_type}' used"
67 f" in position expecting type '{type_}'.",
68 [var_def, node],
69 )
70 )
71
72 if (
73 is_input_object_type(parent_type)
74 and cast(GraphQLInputObjectType, parent_type).is_one_of
75 and is_nullable_type(var_type)
76 ):
77 self.report_error(
78 GraphQLError(
79 f"Variable '${var_name}' is of type '{var_type}'"
80 " but must be non-nullable to be used for OneOf"
81 f" Input Object '{parent_type}'.",
82 [var_def, node],
83 )
84 )
85
86 def enter_variable_definition(
87 self, node: VariableDefinitionNode, *_args: Any
88 ) -> None:
89 self.var_def_map[node.variable.name.value] = node
90
91
92 def allowed_variable_usage(
93 schema: GraphQLSchema,
94 var_type: GraphQLType,
95 var_default_value: Optional[ValueNode],
96 location_type: GraphQLType,
97 location_default_value: Any,
98 ) -> bool:
99 """Check for allowed variable usage.
100
101 Returns True if the variable is allowed in the location it was found, which includes
102 considering if default values exist for either the variable or the location at which
103 it is located.
104 """
105 if is_non_null_type(location_type) and not is_non_null_type(var_type):
106 has_non_null_variable_default_value = (
107 var_default_value is not None
108 and not isinstance(var_default_value, NullValueNode)
109 )
110 has_location_default_value = location_default_value is not Undefined
111 if not has_non_null_variable_default_value and not has_location_default_value:
112 return False
113 location_type = cast(GraphQLNonNull, location_type)
114 nullable_location_type = location_type.of_type
115 return is_type_sub_type_of(schema, var_type, nullable_location_type)
116 return is_type_sub_type_of(schema, var_type, location_type)