| 1 |
from itertools import chain |
| 2 |
from typing import Any, Dict, List, Optional, Tuple, Union, cast |
| 3 |
|
| 4 |
from ...error import GraphQLError |
| 5 |
from ...language import ( |
| 6 |
DirectiveNode, |
| 7 |
FieldNode, |
| 8 |
FragmentDefinitionNode, |
| 9 |
FragmentSpreadNode, |
| 10 |
InlineFragmentNode, |
| 11 |
SelectionSetNode, |
| 12 |
ValueNode, |
| 13 |
print_ast, |
| 14 |
) |
| 15 |
from ...type import ( |
| 16 |
GraphQLCompositeType, |
| 17 |
GraphQLField, |
| 18 |
GraphQLList, |
| 19 |
GraphQLNamedType, |
| 20 |
GraphQLNonNull, |
| 21 |
GraphQLOutputType, |
| 22 |
get_named_type, |
| 23 |
is_interface_type, |
| 24 |
is_leaf_type, |
| 25 |
is_list_type, |
| 26 |
is_non_null_type, |
| 27 |
is_object_type, |
| 28 |
) |
| 29 |
from ...utilities import type_from_ast |
| 30 |
from ...utilities.sort_value_node import sort_value_node |
| 31 |
from . import ValidationContext, ValidationRule |
| 32 |
|
| 33 |
MYPY = False |
| 34 |
|
| 35 |
__all__ = ["MAX_FIELD_COMPARISONS", "OverlappingFieldsCanBeMergedRule"] |
| 36 |
|
| 37 |
# The maximum number of pairwise field comparisons performed while validating a |
| 38 |
# single document with the OverlappingFieldsCanBeMerged rule. The rule compares |
| 39 |
# every pair of fields that share a response name and recurses into their |
| 40 |
# sub-selections, which is O(n^2) in the number of such fields (and worse when |
| 41 |
# inline fragments repeat the same response name at multiple nesting levels). A |
| 42 |
# crafted query can therefore drive validation into minutes of CPU on a single |
| 43 |
# request. Once this many comparisons have been made, validation is aborted with a |
| 44 |
# GraphQLError instead of running to completion. The default is high enough that any |
| 45 |
# realistic query stays far below it; it can be raised or lowered by assigning to |
| 46 |
# ``graphql.validation.rules.overlapping_fields_can_be_merged.MAX_FIELD_COMPARISONS``. |
| 47 |
MAX_FIELD_COMPARISONS = 250_000 |
| 48 |
|
| 49 |
|
| 50 |
class ComparisonBudgetExceededError(Exception): |
| 51 |
"""Internal signal that the field-comparison budget has been exhausted. |
| 52 |
|
| 53 |
Raised deep inside the recursive conflict search and caught by the rule to abort |
| 54 |
validation. Never surfaces to callers of ``validate``. |
| 55 |
""" |
| 56 |
|
| 57 |
|
| 58 |
def reason_message(reason: "ConflictReasonMessage") -> str: |
| 59 |
if isinstance(reason, list): |
| 60 |
return " and ".join( |
| 61 |
f"subfields '{response_name}' conflict" |
| 62 |
f" because {reason_message(sub_reason)}" |
| 63 |
for response_name, sub_reason in reason |
| 64 |
) |
| 65 |
return reason |
| 66 |
|
| 67 |
|
| 68 |
class OverlappingFieldsCanBeMergedRule(ValidationRule): |
| 69 |
"""Overlapping fields can be merged |
| 70 |
|
| 71 |
A selection set is only valid if all fields (including spreading any fragments) |
| 72 |
either correspond to distinct response names or can be merged without ambiguity. |
| 73 |
|
| 74 |
See https://spec.graphql.org/draft/#sec-Field-Selection-Merging |
| 75 |
""" |
| 76 |
|
| 77 |
def __init__(self, context: ValidationContext): |
| 78 |
super().__init__(context) |
| 79 |
# A memoization for when fields and a fragment or two fragments are compared |
| 80 |
# "between" each other for conflicts. Comparisons may be made many times, so |
| 81 |
# memoizing this can dramatically improve the performance of this validator. |
| 82 |
self.compared_fields_and_fragment_pairs = OrderedPairSet() |
| 83 |
self.compared_fragment_pairs = PairSet() |
| 84 |
|
| 85 |
# A cache for the "field map" and list of fragment names found in any given |
| 86 |
# selection set. Selection sets may be asked for this information multiple |
| 87 |
# times, so this improves the performance of this validator. |
| 88 |
self.cached_fields_and_fragment_names: Dict = {} |
| 89 |
|
| 90 |
# Set once the comparison budget is exhausted. Further selection sets are then |
| 91 |
# skipped, since validation has already been aborted with an error. |
| 92 |
self._budget_exceeded = False |
| 93 |
|
| 94 |
def enter_selection_set(self, selection_set: SelectionSetNode, *_args: Any) -> None: |
| 95 |
if self._budget_exceeded: |
| 96 |
return |
| 97 |
try: |
| 98 |
conflicts = find_conflicts_within_selection_set( |
| 99 |
self.context, |
| 100 |
self.cached_fields_and_fragment_names, |
| 101 |
self.compared_fields_and_fragment_pairs, |
| 102 |
self.compared_fragment_pairs, |
| 103 |
self.context.get_parent_type(), |
| 104 |
selection_set, |
| 105 |
) |
| 106 |
except ComparisonBudgetExceededError: |
| 107 |
self._budget_exceeded = True |
| 108 |
self.report_error( |
| 109 |
GraphQLError( |
| 110 |
"Query is too complex to validate for overlapping fields:" |
| 111 |
f" exceeded {MAX_FIELD_COMPARISONS} field comparisons." |
| 112 |
" Validation was aborted.", |
| 113 |
selection_set, |
| 114 |
) |
| 115 |
) |
| 116 |
return |
| 117 |
for (reason_name, reason), fields1, fields2 in conflicts: |
| 118 |
reason_msg = reason_message(reason) |
| 119 |
self.report_error( |
| 120 |
GraphQLError( |
| 121 |
f"Fields '{reason_name}' conflict because {reason_msg}." |
| 122 |
" Use different aliases on the fields to fetch both" |
| 123 |
" if this was intentional.", |
| 124 |
fields1 + fields2, |
| 125 |
) |
| 126 |
) |
| 127 |
|
| 128 |
|
| 129 |
Conflict = Tuple["ConflictReason", List[FieldNode], List[FieldNode]] |
| 130 |
# Field name and reason. |
| 131 |
ConflictReason = Tuple[str, "ConflictReasonMessage"] |
| 132 |
# Reason is a string, or a nested list of conflicts. |
| 133 |
if MYPY: # recursive types not fully supported yet (/python/mypy/issues/731) |
| 134 |
ConflictReasonMessage = Union[str, List] |
| 135 |
else: |
| 136 |
ConflictReasonMessage = Union[str, List[ConflictReason]] |
| 137 |
# Tuple defining a field node in a context. |
| 138 |
NodeAndDef = Tuple[GraphQLCompositeType, FieldNode, Optional[GraphQLField]] |
| 139 |
# Dictionary of lists of those. |
| 140 |
NodeAndDefCollection = Dict[str, List[NodeAndDef]] |
| 141 |
|
| 142 |
|
| 143 |
# Algorithm: |
| 144 |
# |
| 145 |
# Conflicts occur when two fields exist in a query which will produce the same |
| 146 |
# response name, but represent differing values, thus creating a conflict. |
| 147 |
# The algorithm below finds all conflicts via making a series of comparisons |
| 148 |
# between fields. In order to compare as few fields as possible, this makes |
| 149 |
# a series of comparisons "within" sets of fields and "between" sets of fields. |
| 150 |
# |
| 151 |
# Given any selection set, a collection produces both a set of fields by |
| 152 |
# also including all inline fragments, as well as a list of fragments |
| 153 |
# referenced by fragment spreads. |
| 154 |
# |
| 155 |
# A) Each selection set represented in the document first compares "within" its |
| 156 |
# collected set of fields, finding any conflicts between every pair of |
| 157 |
# overlapping fields. |
| 158 |
# Note: This is the#only time* that a the fields "within" a set are compared |
| 159 |
# to each other. After this only fields "between" sets are compared. |
| 160 |
# |
| 161 |
# B) Also, if any fragment is referenced in a selection set, then a |
| 162 |
# comparison is made "between" the original set of fields and the |
| 163 |
# referenced fragment. |
| 164 |
# |
| 165 |
# C) Also, if multiple fragments are referenced, then comparisons |
| 166 |
# are made "between" each referenced fragment. |
| 167 |
# |
| 168 |
# D) When comparing "between" a set of fields and a referenced fragment, first |
| 169 |
# a comparison is made between each field in the original set of fields and |
| 170 |
# each field in the the referenced set of fields. |
| 171 |
# |
| 172 |
# E) Also, if any fragment is referenced in the referenced selection set, |
| 173 |
# then a comparison is made "between" the original set of fields and the |
| 174 |
# referenced fragment (recursively referring to step D). |
| 175 |
# |
| 176 |
# F) When comparing "between" two fragments, first a comparison is made between |
| 177 |
# each field in the first referenced set of fields and each field in the the |
| 178 |
# second referenced set of fields. |
| 179 |
# |
| 180 |
# G) Also, any fragments referenced by the first must be compared to the |
| 181 |
# second, and any fragments referenced by the second must be compared to the |
| 182 |
# first (recursively referring to step F). |
| 183 |
# |
| 184 |
# H) When comparing two fields, if both have selection sets, then a comparison |
| 185 |
# is made "between" both selection sets, first comparing the set of fields in |
| 186 |
# the first selection set with the set of fields in the second. |
| 187 |
# |
| 188 |
# I) Also, if any fragment is referenced in either selection set, then a |
| 189 |
# comparison is made "between" the other set of fields and the |
| 190 |
# referenced fragment. |
| 191 |
# |
| 192 |
# J) Also, if two fragments are referenced in both selection sets, then a |
| 193 |
# comparison is made "between" the two fragments. |
| 194 |
|
| 195 |
|
| 196 |
def find_conflicts_within_selection_set( |
| 197 |
context: ValidationContext, |
| 198 |
cached_fields_and_fragment_names: Dict, |
| 199 |
compared_fields_and_fragment_pairs: "OrderedPairSet", |
| 200 |
compared_fragment_pairs: "PairSet", |
| 201 |
parent_type: Optional[GraphQLNamedType], |
| 202 |
selection_set: SelectionSetNode, |
| 203 |
) -> List[Conflict]: |
| 204 |
"""Find conflicts within selection set. |
| 205 |
|
| 206 |
Find all conflicts found "within" a selection set, including those found via |
| 207 |
spreading in fragments. |
| 208 |
|
| 209 |
Called when visiting each SelectionSet in the GraphQL Document. |
| 210 |
""" |
| 211 |
conflicts: List[Conflict] = [] |
| 212 |
|
| 213 |
field_map, fragment_names = get_fields_and_fragment_names( |
| 214 |
context, cached_fields_and_fragment_names, parent_type, selection_set |
| 215 |
) |
| 216 |
|
| 217 |
# (A) Find all conflicts "within" the fields of this selection set. |
| 218 |
# Note: this is the *only place* `collect_conflicts_within` is called. |
| 219 |
collect_conflicts_within( |
| 220 |
context, |
| 221 |
conflicts, |
| 222 |
cached_fields_and_fragment_names, |
| 223 |
compared_fields_and_fragment_pairs, |
| 224 |
compared_fragment_pairs, |
| 225 |
field_map, |
| 226 |
) |
| 227 |
|
| 228 |
if fragment_names: |
| 229 |
# (B) Then collect conflicts between these fields and those represented by each |
| 230 |
# spread fragment name found. |
| 231 |
for i, fragment_name in enumerate(fragment_names): |
| 232 |
collect_conflicts_between_fields_and_fragment( |
| 233 |
context, |
| 234 |
conflicts, |
| 235 |
cached_fields_and_fragment_names, |
| 236 |
compared_fields_and_fragment_pairs, |
| 237 |
compared_fragment_pairs, |
| 238 |
False, |
| 239 |
field_map, |
| 240 |
fragment_name, |
| 241 |
) |
| 242 |
# (C) Then compare this fragment with all other fragments found in this |
| 243 |
# selection set to collect conflicts within fragments spread together. |
| 244 |
# This compares each item in the list of fragment names to every other |
| 245 |
# item in that same list (except for itself). |
| 246 |
for other_fragment_name in fragment_names[i + 1 :]: |
| 247 |
collect_conflicts_between_fragments( |
| 248 |
context, |
| 249 |
conflicts, |
| 250 |
cached_fields_and_fragment_names, |
| 251 |
compared_fields_and_fragment_pairs, |
| 252 |
compared_fragment_pairs, |
| 253 |
False, |
| 254 |
fragment_name, |
| 255 |
other_fragment_name, |
| 256 |
) |
| 257 |
|
| 258 |
return conflicts |
| 259 |
|
| 260 |
|
| 261 |
def collect_conflicts_between_fields_and_fragment( |
| 262 |
context: ValidationContext, |
| 263 |
conflicts: List[Conflict], |
| 264 |
cached_fields_and_fragment_names: Dict, |
| 265 |
compared_fields_and_fragment_pairs: "OrderedPairSet", |
| 266 |
compared_fragment_pairs: "PairSet", |
| 267 |
are_mutually_exclusive: bool, |
| 268 |
field_map: NodeAndDefCollection, |
| 269 |
fragment_name: str, |
| 270 |
) -> None: |
| 271 |
"""Collect conflicts between fields and fragment. |
| 272 |
|
| 273 |
Collect all conflicts found between a set of fields and a fragment reference |
| 274 |
including via spreading in any nested fragments. |
| 275 |
""" |
| 276 |
# Memoize so the fields and fragments are not compared for conflicts more |
| 277 |
# than once. |
| 278 |
if compared_fields_and_fragment_pairs.has( |
| 279 |
field_map, fragment_name, are_mutually_exclusive |
| 280 |
): |
| 281 |
return |
| 282 |
compared_fields_and_fragment_pairs.add( |
| 283 |
field_map, fragment_name, are_mutually_exclusive |
| 284 |
) |
| 285 |
|
| 286 |
fragment = context.get_fragment(fragment_name) |
| 287 |
if not fragment: |
| 288 |
return None |
| 289 |
|
| 290 |
field_map2, referenced_fragment_names = get_referenced_fields_and_fragment_names( |
| 291 |
context, cached_fields_and_fragment_names, fragment |
| 292 |
) |
| 293 |
|
| 294 |
# Do not compare a fragment's fieldMap to itself. |
| 295 |
if field_map is field_map2: |
| 296 |
return |
| 297 |
|
| 298 |
# (D) First collect any conflicts between the provided collection of fields and the |
| 299 |
# collection of fields represented by the given fragment. |
| 300 |
collect_conflicts_between( |
| 301 |
context, |
| 302 |
conflicts, |
| 303 |
cached_fields_and_fragment_names, |
| 304 |
compared_fields_and_fragment_pairs, |
| 305 |
compared_fragment_pairs, |
| 306 |
are_mutually_exclusive, |
| 307 |
field_map, |
| 308 |
field_map2, |
| 309 |
) |
| 310 |
|
| 311 |
# (E) Then collect any conflicts between the provided collection of fields and any |
| 312 |
# fragment names found in the given fragment. |
| 313 |
for referenced_fragment_name in referenced_fragment_names: |
| 314 |
collect_conflicts_between_fields_and_fragment( |
| 315 |
context, |
| 316 |
conflicts, |
| 317 |
cached_fields_and_fragment_names, |
| 318 |
compared_fields_and_fragment_pairs, |
| 319 |
compared_fragment_pairs, |
| 320 |
are_mutually_exclusive, |
| 321 |
field_map, |
| 322 |
referenced_fragment_name, |
| 323 |
) |
| 324 |
|
| 325 |
|
| 326 |
def collect_conflicts_between_fragments( |
| 327 |
context: ValidationContext, |
| 328 |
conflicts: List[Conflict], |
| 329 |
cached_fields_and_fragment_names: Dict, |
| 330 |
compared_fields_and_fragment_pairs: "OrderedPairSet", |
| 331 |
compared_fragment_pairs: "PairSet", |
| 332 |
are_mutually_exclusive: bool, |
| 333 |
fragment_name1: str, |
| 334 |
fragment_name2: str, |
| 335 |
) -> None: |
| 336 |
"""Collect conflicts between fragments. |
| 337 |
|
| 338 |
Collect all conflicts found between two fragments, including via spreading in any |
| 339 |
nested fragments. |
| 340 |
""" |
| 341 |
# No need to compare a fragment to itself. |
| 342 |
if fragment_name1 == fragment_name2: |
| 343 |
return |
| 344 |
|
| 345 |
# Memoize so two fragments are not compared for conflicts more than once. |
| 346 |
if compared_fragment_pairs.has( |
| 347 |
fragment_name1, fragment_name2, are_mutually_exclusive |
| 348 |
): |
| 349 |
return |
| 350 |
compared_fragment_pairs.add(fragment_name1, fragment_name2, are_mutually_exclusive) |
| 351 |
|
| 352 |
fragment1 = context.get_fragment(fragment_name1) |
| 353 |
fragment2 = context.get_fragment(fragment_name2) |
| 354 |
if not fragment1 or not fragment2: |
| 355 |
return None |
| 356 |
|
| 357 |
field_map1, referenced_fragment_names1 = get_referenced_fields_and_fragment_names( |
| 358 |
context, cached_fields_and_fragment_names, fragment1 |
| 359 |
) |
| 360 |
|
| 361 |
field_map2, referenced_fragment_names2 = get_referenced_fields_and_fragment_names( |
| 362 |
context, cached_fields_and_fragment_names, fragment2 |
| 363 |
) |
| 364 |
|
| 365 |
# (F) First, collect all conflicts between these two collections of fields |
| 366 |
# (not including any nested fragments) |
| 367 |
collect_conflicts_between( |
| 368 |
context, |
| 369 |
conflicts, |
| 370 |
cached_fields_and_fragment_names, |
| 371 |
compared_fields_and_fragment_pairs, |
| 372 |
compared_fragment_pairs, |
| 373 |
are_mutually_exclusive, |
| 374 |
field_map1, |
| 375 |
field_map2, |
| 376 |
) |
| 377 |
|
| 378 |
# (G) Then collect conflicts between the first fragment and any nested fragments |
| 379 |
# spread in the second fragment. |
| 380 |
for referenced_fragment_name2 in referenced_fragment_names2: |
| 381 |
collect_conflicts_between_fragments( |
| 382 |
context, |
| 383 |
conflicts, |
| 384 |
cached_fields_and_fragment_names, |
| 385 |
compared_fields_and_fragment_pairs, |
| 386 |
compared_fragment_pairs, |
| 387 |
are_mutually_exclusive, |
| 388 |
fragment_name1, |
| 389 |
referenced_fragment_name2, |
| 390 |
) |
| 391 |
|
| 392 |
# (G) Then collect conflicts between the second fragment and any nested fragments |
| 393 |
# spread in the first fragment. |
| 394 |
for referenced_fragment_name1 in referenced_fragment_names1: |
| 395 |
collect_conflicts_between_fragments( |
| 396 |
context, |
| 397 |
conflicts, |
| 398 |
cached_fields_and_fragment_names, |
| 399 |
compared_fields_and_fragment_pairs, |
| 400 |
compared_fragment_pairs, |
| 401 |
are_mutually_exclusive, |
| 402 |
referenced_fragment_name1, |
| 403 |
fragment_name2, |
| 404 |
) |
| 405 |
|
| 406 |
|
| 407 |
def find_conflicts_between_sub_selection_sets( |
| 408 |
context: ValidationContext, |
| 409 |
cached_fields_and_fragment_names: Dict, |
| 410 |
compared_fields_and_fragment_pairs: "OrderedPairSet", |
| 411 |
compared_fragment_pairs: "PairSet", |
| 412 |
are_mutually_exclusive: bool, |
| 413 |
parent_type1: Optional[GraphQLNamedType], |
| 414 |
selection_set1: SelectionSetNode, |
| 415 |
parent_type2: Optional[GraphQLNamedType], |
| 416 |
selection_set2: SelectionSetNode, |
| 417 |
) -> List[Conflict]: |
| 418 |
"""Find conflicts between sub selection sets. |
| 419 |
|
| 420 |
Find all conflicts found between two selection sets, including those found via |
| 421 |
spreading in fragments. Called when determining if conflicts exist between the |
| 422 |
sub-fields of two overlapping fields. |
| 423 |
""" |
| 424 |
conflicts: List[Conflict] = [] |
| 425 |
|
| 426 |
field_map1, fragment_names1 = get_fields_and_fragment_names( |
| 427 |
context, cached_fields_and_fragment_names, parent_type1, selection_set1 |
| 428 |
) |
| 429 |
field_map2, fragment_names2 = get_fields_and_fragment_names( |
| 430 |
context, cached_fields_and_fragment_names, parent_type2, selection_set2 |
| 431 |
) |
| 432 |
|
| 433 |
# (H) First, collect all conflicts between these two collections of field. |
| 434 |
collect_conflicts_between( |
| 435 |
context, |
| 436 |
conflicts, |
| 437 |
cached_fields_and_fragment_names, |
| 438 |
compared_fields_and_fragment_pairs, |
| 439 |
compared_fragment_pairs, |
| 440 |
are_mutually_exclusive, |
| 441 |
field_map1, |
| 442 |
field_map2, |
| 443 |
) |
| 444 |
|
| 445 |
# (I) Then collect conflicts between the first collection of fields and those |
| 446 |
# referenced by each fragment name associated with the second. |
| 447 |
if fragment_names2: |
| 448 |
for fragment_name2 in fragment_names2: |
| 449 |
collect_conflicts_between_fields_and_fragment( |
| 450 |
context, |
| 451 |
conflicts, |
| 452 |
cached_fields_and_fragment_names, |
| 453 |
compared_fields_and_fragment_pairs, |
| 454 |
compared_fragment_pairs, |
| 455 |
are_mutually_exclusive, |
| 456 |
field_map1, |
| 457 |
fragment_name2, |
| 458 |
) |
| 459 |
|
| 460 |
# (I) Then collect conflicts between the second collection of fields and those |
| 461 |
# referenced by each fragment name associated with the first. |
| 462 |
if fragment_names1: |
| 463 |
for fragment_name1 in fragment_names1: |
| 464 |
collect_conflicts_between_fields_and_fragment( |
| 465 |
context, |
| 466 |
conflicts, |
| 467 |
cached_fields_and_fragment_names, |
| 468 |
compared_fields_and_fragment_pairs, |
| 469 |
compared_fragment_pairs, |
| 470 |
are_mutually_exclusive, |
| 471 |
field_map2, |
| 472 |
fragment_name1, |
| 473 |
) |
| 474 |
|
| 475 |
# (J) Also collect conflicts between any fragment names by the first and fragment |
| 476 |
# names by the second. This compares each item in the first set of names to each |
| 477 |
# item in the second set of names. |
| 478 |
for fragment_name1 in fragment_names1: |
| 479 |
for fragment_name2 in fragment_names2: |
| 480 |
collect_conflicts_between_fragments( |
| 481 |
context, |
| 482 |
conflicts, |
| 483 |
cached_fields_and_fragment_names, |
| 484 |
compared_fields_and_fragment_pairs, |
| 485 |
compared_fragment_pairs, |
| 486 |
are_mutually_exclusive, |
| 487 |
fragment_name1, |
| 488 |
fragment_name2, |
| 489 |
) |
| 490 |
|
| 491 |
return conflicts |
| 492 |
|
| 493 |
|
| 494 |
def collect_conflicts_within( |
| 495 |
context: ValidationContext, |
| 496 |
conflicts: List[Conflict], |
| 497 |
cached_fields_and_fragment_names: Dict, |
| 498 |
compared_fields_and_fragment_pairs: "OrderedPairSet", |
| 499 |
compared_fragment_pairs: "PairSet", |
| 500 |
field_map: NodeAndDefCollection, |
| 501 |
) -> None: |
| 502 |
"""Collect all Conflicts "within" one collection of fields.""" |
| 503 |
# A field map is a keyed collection, where each key represents a response name and |
| 504 |
# the value at that key is a list of all fields which provide that response name. |
| 505 |
# For every response name, if there are multiple fields, they must be compared to |
| 506 |
# find a potential conflict. |
| 507 |
for response_name, fields in field_map.items(): |
| 508 |
# This compares every field in the list to every other field in this list |
| 509 |
# (except to itself). If the list only has one item, nothing needs to be |
| 510 |
# compared. |
| 511 |
if len(fields) > 1: |
| 512 |
for i, field in enumerate(fields): |
| 513 |
for other_field in fields[i + 1 :]: |
| 514 |
conflict = find_conflict( |
| 515 |
context, |
| 516 |
cached_fields_and_fragment_names, |
| 517 |
compared_fields_and_fragment_pairs, |
| 518 |
compared_fragment_pairs, |
| 519 |
# within one collection is never mutually exclusive |
| 520 |
False, |
| 521 |
response_name, |
| 522 |
field, |
| 523 |
other_field, |
| 524 |
) |
| 525 |
if conflict: |
| 526 |
conflicts.append(conflict) |
| 527 |
|
| 528 |
|
| 529 |
def collect_conflicts_between( |
| 530 |
context: ValidationContext, |
| 531 |
conflicts: List[Conflict], |
| 532 |
cached_fields_and_fragment_names: Dict, |
| 533 |
compared_fields_and_fragment_pairs: "OrderedPairSet", |
| 534 |
compared_fragment_pairs: "PairSet", |
| 535 |
parent_fields_are_mutually_exclusive: bool, |
| 536 |
field_map1: NodeAndDefCollection, |
| 537 |
field_map2: NodeAndDefCollection, |
| 538 |
) -> None: |
| 539 |
"""Collect all Conflicts between two collections of fields. |
| 540 |
|
| 541 |
This is similar to, but different from the :func:`~.collect_conflicts_within` |
| 542 |
function above. This check assumes that :func:`~.collect_conflicts_within` has |
| 543 |
already been called on each provided collection of fields. This is true because |
| 544 |
this validator traverses each individual selection set. |
| 545 |
""" |
| 546 |
# A field map is a keyed collection, where each key represents a response name and |
| 547 |
# the value at that key is a list of all fields which provide that response name. |
| 548 |
# For any response name which appears in both provided field maps, each field from |
| 549 |
# the first field map must be compared to every field in the second field map to |
| 550 |
# find potential conflicts. |
| 551 |
for response_name, fields1 in field_map1.items(): |
| 552 |
fields2 = field_map2.get(response_name) |
| 553 |
if fields2: |
| 554 |
for field1 in fields1: |
| 555 |
for field2 in fields2: |
| 556 |
conflict = find_conflict( |
| 557 |
context, |
| 558 |
cached_fields_and_fragment_names, |
| 559 |
compared_fields_and_fragment_pairs, |
| 560 |
compared_fragment_pairs, |
| 561 |
parent_fields_are_mutually_exclusive, |
| 562 |
response_name, |
| 563 |
field1, |
| 564 |
field2, |
| 565 |
) |
| 566 |
if conflict: |
| 567 |
conflicts.append(conflict) |
| 568 |
|
| 569 |
|
| 570 |
def find_conflict( |
| 571 |
context: ValidationContext, |
| 572 |
cached_fields_and_fragment_names: Dict, |
| 573 |
compared_fields_and_fragment_pairs: "OrderedPairSet", |
| 574 |
compared_fragment_pairs: "PairSet", |
| 575 |
parent_fields_are_mutually_exclusive: bool, |
| 576 |
response_name: str, |
| 577 |
field1: NodeAndDef, |
| 578 |
field2: NodeAndDef, |
| 579 |
) -> Optional[Conflict]: |
| 580 |
"""Find conflict. |
| 581 |
|
| 582 |
Determines if there is a conflict between two particular fields, including comparing |
| 583 |
their sub-fields. |
| 584 |
""" |
| 585 |
# Charge this comparison against the document-wide budget and abort validation once |
| 586 |
# it is exhausted, guarding against quadratic-blowup denial of service. |
| 587 |
compared_fields_and_fragment_pairs.comparisons += 1 |
| 588 |
if compared_fields_and_fragment_pairs.comparisons > MAX_FIELD_COMPARISONS: |
| 589 |
raise ComparisonBudgetExceededError |
| 590 |
|
| 591 |
parent_type1, node1, def1 = field1 |
| 592 |
parent_type2, node2, def2 = field2 |
| 593 |
|
| 594 |
# If it is known that two fields could not possibly apply at the same time, due to |
| 595 |
# the parent types, then it is safe to permit them to diverge in aliased field or |
| 596 |
# arguments used as they will not present any ambiguity by differing. It is known |
| 597 |
# that two parent types could never overlap if they are different Object types. |
| 598 |
# Interface or Union types might overlap - if not in the current state of the |
| 599 |
# schema, then perhaps in some future version, thus may not safely diverge. |
| 600 |
are_mutually_exclusive = parent_fields_are_mutually_exclusive or ( |
| 601 |
parent_type1 != parent_type2 |
| 602 |
and is_object_type(parent_type1) |
| 603 |
and is_object_type(parent_type2) |
| 604 |
) |
| 605 |
|
| 606 |
# The return type for each field. |
| 607 |
type1 = cast(Optional[GraphQLOutputType], def1 and def1.type) |
| 608 |
type2 = cast(Optional[GraphQLOutputType], def2 and def2.type) |
| 609 |
|
| 610 |
if not are_mutually_exclusive: |
| 611 |
# Two aliases must refer to the same field. |
| 612 |
name1 = node1.name.value |
| 613 |
name2 = node2.name.value |
| 614 |
if name1 != name2: |
| 615 |
return ( |
| 616 |
(response_name, f"'{name1}' and '{name2}' are different fields"), |
| 617 |
[node1], |
| 618 |
[node2], |
| 619 |
) |
| 620 |
|
| 621 |
# Two field calls must have the same arguments. |
| 622 |
if not same_arguments(node1, node2): |
| 623 |
return (response_name, "they have differing arguments"), [node1], [node2] |
| 624 |
|
| 625 |
if type1 and type2 and do_types_conflict(type1, type2): |
| 626 |
return ( |
| 627 |
(response_name, f"they return conflicting types '{type1}' and '{type2}'"), |
| 628 |
[node1], |
| 629 |
[node2], |
| 630 |
) |
| 631 |
|
| 632 |
# Collect and compare sub-fields. Use the same "visited fragment names" list for |
| 633 |
# both collections so fields in a fragment reference are never compared to |
| 634 |
# themselves. |
| 635 |
selection_set1 = node1.selection_set |
| 636 |
selection_set2 = node2.selection_set |
| 637 |
if selection_set1 and selection_set2: |
| 638 |
conflicts = find_conflicts_between_sub_selection_sets( |
| 639 |
context, |
| 640 |
cached_fields_and_fragment_names, |
| 641 |
compared_fields_and_fragment_pairs, |
| 642 |
compared_fragment_pairs, |
| 643 |
are_mutually_exclusive, |
| 644 |
get_named_type(type1), |
| 645 |
selection_set1, |
| 646 |
get_named_type(type2), |
| 647 |
selection_set2, |
| 648 |
) |
| 649 |
return subfield_conflicts(conflicts, response_name, node1, node2) |
| 650 |
|
| 651 |
return None # no conflict |
| 652 |
|
| 653 |
|
| 654 |
def same_arguments( |
| 655 |
node1: Union[FieldNode, DirectiveNode], node2: Union[FieldNode, DirectiveNode] |
| 656 |
) -> bool: |
| 657 |
args1 = node1.arguments |
| 658 |
args2 = node2.arguments |
| 659 |
|
| 660 |
if not args1: |
| 661 |
return not args2 |
| 662 |
|
| 663 |
if not args2: |
| 664 |
return False |
| 665 |
|
| 666 |
if len(args1) != len(args2): |
| 667 |
return False # pragma: no cover |
| 668 |
|
| 669 |
values2 = {arg.name.value: arg.value for arg in args2} |
| 670 |
|
| 671 |
for arg1 in args1: |
| 672 |
value1 = arg1.value |
| 673 |
value2 = values2.get(arg1.name.value) |
| 674 |
if value2 is None or stringify_value(value1) != stringify_value(value2): |
| 675 |
return False |
| 676 |
|
| 677 |
return True |
| 678 |
|
| 679 |
|
| 680 |
def stringify_value(value: ValueNode) -> str: |
| 681 |
return print_ast(sort_value_node(value)) |
| 682 |
|
| 683 |
|
| 684 |
def do_types_conflict(type1: GraphQLOutputType, type2: GraphQLOutputType) -> bool: |
| 685 |
"""Check whether two types conflict |
| 686 |
|
| 687 |
Two types conflict if both types could not apply to a value simultaneously. |
| 688 |
Composite types are ignored as their individual field types will be compared later |
| 689 |
recursively. However List and Non-Null types must match. |
| 690 |
""" |
| 691 |
if is_list_type(type1): |
| 692 |
return ( |
| 693 |
do_types_conflict( |
| 694 |
cast(GraphQLList, type1).of_type, cast(GraphQLList, type2).of_type |
| 695 |
) |
| 696 |
if is_list_type(type2) |
| 697 |
else True |
| 698 |
) |
| 699 |
if is_list_type(type2): |
| 700 |
return True |
| 701 |
if is_non_null_type(type1): |
| 702 |
return ( |
| 703 |
do_types_conflict( |
| 704 |
cast(GraphQLNonNull, type1).of_type, cast(GraphQLNonNull, type2).of_type |
| 705 |
) |
| 706 |
if is_non_null_type(type2) |
| 707 |
else True |
| 708 |
) |
| 709 |
if is_non_null_type(type2): |
| 710 |
return True |
| 711 |
if is_leaf_type(type1) or is_leaf_type(type2): |
| 712 |
return type1 is not type2 |
| 713 |
return False |
| 714 |
|
| 715 |
|
| 716 |
def get_fields_and_fragment_names( |
| 717 |
context: ValidationContext, |
| 718 |
cached_fields_and_fragment_names: Dict, |
| 719 |
parent_type: Optional[GraphQLNamedType], |
| 720 |
selection_set: SelectionSetNode, |
| 721 |
) -> Tuple[NodeAndDefCollection, List[str]]: |
| 722 |
"""Get fields and referenced fragment names |
| 723 |
|
| 724 |
Given a selection set, return the collection of fields (a mapping of response name |
| 725 |
to field nodes and definitions) as well as a list of fragment names referenced via |
| 726 |
fragment spreads. |
| 727 |
""" |
| 728 |
cached = cached_fields_and_fragment_names.get(selection_set) |
| 729 |
if not cached: |
| 730 |
node_and_defs: NodeAndDefCollection = {} |
| 731 |
fragment_names: Dict[str, bool] = {} |
| 732 |
collect_fields_and_fragment_names( |
| 733 |
context, parent_type, selection_set, node_and_defs, fragment_names |
| 734 |
) |
| 735 |
cached = (node_and_defs, list(fragment_names)) |
| 736 |
cached_fields_and_fragment_names[selection_set] = cached |
| 737 |
return cached |
| 738 |
|
| 739 |
|
| 740 |
def get_referenced_fields_and_fragment_names( |
| 741 |
context: ValidationContext, |
| 742 |
cached_fields_and_fragment_names: Dict, |
| 743 |
fragment: FragmentDefinitionNode, |
| 744 |
) -> Tuple[NodeAndDefCollection, List[str]]: |
| 745 |
"""Get referenced fields and nested fragment names |
| 746 |
|
| 747 |
Given a reference to a fragment, return the represented collection of fields as well |
| 748 |
as a list of nested fragment names referenced via fragment spreads. |
| 749 |
""" |
| 750 |
# Short-circuit building a type from the node if possible. |
| 751 |
cached = cached_fields_and_fragment_names.get(fragment.selection_set) |
| 752 |
if cached: |
| 753 |
return cached |
| 754 |
|
| 755 |
fragment_type = type_from_ast(context.schema, fragment.type_condition) |
| 756 |
return get_fields_and_fragment_names( |
| 757 |
context, cached_fields_and_fragment_names, fragment_type, fragment.selection_set |
| 758 |
) |
| 759 |
|
| 760 |
|
| 761 |
def collect_fields_and_fragment_names( |
| 762 |
context: ValidationContext, |
| 763 |
parent_type: Optional[GraphQLNamedType], |
| 764 |
selection_set: SelectionSetNode, |
| 765 |
node_and_defs: NodeAndDefCollection, |
| 766 |
fragment_names: Dict[str, bool], |
| 767 |
) -> None: |
| 768 |
for selection in selection_set.selections: |
| 769 |
if isinstance(selection, FieldNode): |
| 770 |
field_name = selection.name.value |
| 771 |
field_def = ( |
| 772 |
parent_type.fields.get(field_name) # type: ignore |
| 773 |
if is_object_type(parent_type) or is_interface_type(parent_type) |
| 774 |
else None |
| 775 |
) |
| 776 |
response_name = selection.alias.value if selection.alias else field_name |
| 777 |
if not node_and_defs.get(response_name): |
| 778 |
node_and_defs[response_name] = [] |
| 779 |
node_and_defs[response_name].append( |
| 780 |
cast(NodeAndDef, (parent_type, selection, field_def)) |
| 781 |
) |
| 782 |
elif isinstance(selection, FragmentSpreadNode): |
| 783 |
fragment_names[selection.name.value] = True |
| 784 |
elif isinstance(selection, InlineFragmentNode): # pragma: no cover else |
| 785 |
type_condition = selection.type_condition |
| 786 |
inline_fragment_type = ( |
| 787 |
type_from_ast(context.schema, type_condition) |
| 788 |
if type_condition |
| 789 |
else parent_type |
| 790 |
) |
| 791 |
collect_fields_and_fragment_names( |
| 792 |
context, |
| 793 |
inline_fragment_type, |
| 794 |
selection.selection_set, |
| 795 |
node_and_defs, |
| 796 |
fragment_names, |
| 797 |
) |
| 798 |
|
| 799 |
|
| 800 |
def subfield_conflicts( |
| 801 |
conflicts: List[Conflict], response_name: str, node1: FieldNode, node2: FieldNode |
| 802 |
) -> Optional[Conflict]: |
| 803 |
"""Check whether there are conflicts between sub-fields. |
| 804 |
|
| 805 |
Given a series of Conflicts which occurred between two sub-fields, generate a single |
| 806 |
Conflict. |
| 807 |
""" |
| 808 |
if conflicts: |
| 809 |
return ( |
| 810 |
(response_name, [conflict[0] for conflict in conflicts]), |
| 811 |
list(chain([node1], *[conflict[1] for conflict in conflicts])), |
| 812 |
list(chain([node2], *[conflict[2] for conflict in conflicts])), |
| 813 |
) |
| 814 |
return None # no conflict |
| 815 |
|
| 816 |
|
| 817 |
class OrderedPairSet: |
| 818 |
"""Ordered pair set |
| 819 |
|
| 820 |
A way to keep track of pairs of things where the ordering of the pair matters. |
| 821 |
|
| 822 |
Provides a third argument for has/add to allow flagging the pair as weakly or |
| 823 |
strongly present within the collection. |
| 824 |
|
| 825 |
The first element is matched by object identity (its ``id``), since field maps |
| 826 |
are unhashable mappings that are kept alive for the duration of the validation. |
| 827 |
|
| 828 |
Also carries a running count of the pairwise field comparisons performed with |
| 829 |
this set, used to enforce the OverlappingFieldsCanBeMerged comparison budget. |
| 830 |
""" |
| 831 |
|
| 832 |
__slots__ = ("_data", "comparisons") |
| 833 |
|
| 834 |
_data: Dict[int, Dict[str, bool]] |
| 835 |
comparisons: int |
| 836 |
|
| 837 |
def __init__(self) -> None: |
| 838 |
self._data = {} |
| 839 |
self.comparisons = 0 |
| 840 |
|
| 841 |
def has(self, a: NodeAndDefCollection, b: str, weakly_present: bool) -> bool: |
| 842 |
map_ = self._data.get(id(a)) |
| 843 |
if map_ is None: |
| 844 |
return False |
| 845 |
result = map_.get(b) |
| 846 |
if result is None: |
| 847 |
return False |
| 848 |
|
| 849 |
return True if weakly_present else weakly_present == result |
| 850 |
|
| 851 |
def add(self, a: NodeAndDefCollection, b: str, weakly_present: bool) -> None: |
| 852 |
map_ = self._data.get(id(a)) |
| 853 |
if map_ is None: |
| 854 |
self._data[id(a)] = {b: weakly_present} |
| 855 |
else: |
| 856 |
map_[b] = weakly_present |
| 857 |
|
| 858 |
|
| 859 |
class PairSet: |
| 860 |
"""Pair set |
| 861 |
|
| 862 |
A way to keep track of pairs of things when the ordering of the pair doesn't matter. |
| 863 |
""" |
| 864 |
|
| 865 |
__slots__ = ("_data",) |
| 866 |
|
| 867 |
_data: Dict[str, Dict[str, bool]] |
| 868 |
|
| 869 |
def __init__(self) -> None: |
| 870 |
self._data = {} |
| 871 |
|
| 872 |
def has(self, a: str, b: str, are_mutually_exclusive: bool) -> bool: |
| 873 |
key1, key2 = (a, b) if a < b else (b, a) |
| 874 |
|
| 875 |
map_ = self._data.get(key1) |
| 876 |
if map_ is None: |
| 877 |
return False |
| 878 |
result = map_.get(key2) |
| 879 |
if result is None: |
| 880 |
return False |
| 881 |
|
| 882 |
# are_mutually_exclusive being False is a superset of being True, |
| 883 |
# hence if we want to know if this PairSet "has" these two with no exclusivity, |
| 884 |
# we have to ensure it was added as such. |
| 885 |
return True if are_mutually_exclusive else are_mutually_exclusive == result |
| 886 |
|
| 887 |
def add(self, a: str, b: str, are_mutually_exclusive: bool) -> None: |
| 888 |
key1, key2 = (a, b) if a < b else (b, a) |
| 889 |
|
| 890 |
map_ = self._data.get(key1) |
| 891 |
if map_ is None: |
| 892 |
self._data[key1] = {key2: are_mutually_exclusive} |
| 893 |
else: |
| 894 |
map_[key2] = are_mutually_exclusive |