|
| 1 | +from typing import Any, Type |
| 2 | + |
| 3 | +from graphql import GraphQLError, ValidationRule |
| 4 | +from graphql.language.ast import DocumentNode, FieldNode, OperationDefinitionNode |
| 5 | +from graphql.validation import ValidationContext |
| 6 | + |
| 7 | + |
| 8 | +def create_max_depth_rule(max_depth: int) -> Type[ValidationRule]: |
| 9 | + class MaxDepthRule(ValidationRule): |
| 10 | + def __init__(self, context: ValidationContext) -> None: |
| 11 | + super().__init__(context) |
| 12 | + self.operation_depth: int = 1 |
| 13 | + self.max_depth_reached: bool = False |
| 14 | + self.max_depth: int = max_depth |
| 15 | + |
| 16 | + def enter_operation_definition( |
| 17 | + self, node: OperationDefinitionNode, *_args: Any |
| 18 | + ) -> None: |
| 19 | + self.operation_depth = 1 |
| 20 | + self.max_depth_reached = False |
| 21 | + |
| 22 | + def enter_field(self, node: FieldNode, *_args: Any) -> None: |
| 23 | + self.operation_depth += 1 |
| 24 | + |
| 25 | + if self.operation_depth > self.max_depth and not self.max_depth_reached: |
| 26 | + self.max_depth_reached = True |
| 27 | + self.report_error( |
| 28 | + GraphQLError( |
| 29 | + "Query depth exceeds the maximum allowed depth", |
| 30 | + node, |
| 31 | + ) |
| 32 | + ) |
| 33 | + |
| 34 | + def leave_field(self, node: FieldNode, *_args: Any) -> None: |
| 35 | + self.operation_depth -= 1 |
| 36 | + |
| 37 | + return MaxDepthRule |
| 38 | + |
| 39 | + |
| 40 | +def create_max_aliases_rule(max_aliases: int) -> Type[ValidationRule]: |
| 41 | + class MaxAliasesRule(ValidationRule): |
| 42 | + def __init__(self, context: ValidationContext) -> None: |
| 43 | + super().__init__(context) |
| 44 | + self.alias_count: int = 0 |
| 45 | + self.has_reported_error: bool = False |
| 46 | + self.max_aliases: int = max_aliases |
| 47 | + |
| 48 | + def enter_document(self, node: DocumentNode, *_args: Any) -> None: |
| 49 | + self.alias_count = 0 |
| 50 | + self.has_reported_error = False |
| 51 | + |
| 52 | + def enter_field(self, node: FieldNode, *_args: Any) -> None: |
| 53 | + if node.alias: |
| 54 | + self.alias_count += 1 |
| 55 | + |
| 56 | + if self.alias_count > self.max_aliases and not self.has_reported_error: |
| 57 | + self.has_reported_error = True |
| 58 | + self.report_error( |
| 59 | + GraphQLError( |
| 60 | + "Query uses too many aliases", |
| 61 | + node, |
| 62 | + ) |
| 63 | + ) |
| 64 | + |
| 65 | + return MaxAliasesRule |
0 commit comments