Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Fix introspection query detection code (#15966)

Patryk Zawadzki37ac69887f82
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 86ed388a1d..aa99cb3098 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Prevent name overwriting of Product Variants when Updating Product Types - #15670 by @teddyondieki
- Added support for the `BrokerProperties` custom header to webhooks to support Azure Service Bus - #15899 by @patrys
- Extend valid address values - #15877 by @zedzior
+- Fixed a rare crash in the introspection query detection code - #15966 by @patrys
# 3.19.0
diff --git a/saleor/graphql/tests/test_utils.py b/saleor/graphql/tests/test_utils.py
index a43effcc6f..03fb13517b 100644
--- a/saleor/graphql/tests/test_utils.py
+++ b/saleor/graphql/tests/test_utils.py
@@ -1,9 +1,13 @@
import re
+import pytest
from django.test import override_settings
+from graphql import GraphQLError
from graphql.utils import schema_printer
+from ..api import backend, schema
from ..utils import ALLOWED_ERRORS, INTERNAL_ERROR_MESSAGE, format_error
+from ..utils.validators import check_if_query_contains_only_schema
from .utils import get_graphql_content
@@ -49,3 +53,173 @@ def test_format_error_prints_internal_error_msg_in_debug_mode():
error = ValueError("Example error")
result = format_error(error, ())
assert result["message"] == str(error)
+
+
+def test_check_if_query_contains_only_schema_with_schema_query():
+ # given
+ query = """
+ query {
+ __schema {
+ __typename
+ }
+ }
+ """
+ document = backend.document_from_string(schema, query)
+
+ # when
+ result = check_if_query_contains_only_schema(document)
+
+ # then
+ assert result is True
+
+
+def test_check_if_query_contains_only_schema_with_mixed_query():
+ # given
+ query = """
+ query {
+ __schema {
+ __typename
+ }
+ shop {
+ name
+ }
+ }
+ """
+ document = backend.document_from_string(schema, query)
+
+ # then
+ with pytest.raises(GraphQLError):
+ check_if_query_contains_only_schema(document)
+
+
+def test_check_if_query_contains_only_schema_with_mixed_query_and_fragments():
+ # given
+ query = """
+ query {
+ ... {
+ __schema {
+ __typename
+ }
+ }
+ ... {
+ shop {
+ name
+ }
+ }
+ }
+ """
+ document = backend.document_from_string(schema, query)
+
+ # then
+ with pytest.raises(GraphQLError):
+ check_if_query_contains_only_schema(document)
+
+
+def test_check_if_query_contains_only_schema_with_fragments():
+ # given
+ query = """
+ fragment ShopFragment on Shop {
+ ... on Node {
+ __typename
+ }
+ }
+
+ query {
+ shop {
+ ...ShopFragment
+ }
+ }
+ """
+ document = backend.document_from_string(schema, query)
+
+ # when
+ result = check_if_query_contains_only_schema(document)
+
+ # then
+ assert result is False
+
+
+def test_check_if_query_contains_only_schema_with_schema_query_and_inline_fragment():
+ # given
+ query = """
+ query {
+ ... on Query {
+ __schema {
+ __typename
+ }
+ }
+ }
+ """
+ document = backend.document_from_string(schema, query)
+
+ # when
+ result = check_if_query_contains_only_schema(document)
+
+ # then
+ assert result is True
+
+
+def test_check_if_query_contains_only_schema_with_schema_query_and_unconditional_inline_fragment():
+ # given
+ query = """
+ query {
+ ... {
+ __schema {
+ __typename
+ }
+ }
+ }
+ """
+ document = backend.document_from_string(schema, query)
+
+ # when
+ result = check_if_query_contains_only_schema(document)
+
+ # then
+ assert result is True
+
+
+def test_check_if_query_contains_only_schema_with_schema_query_and_named_fragment():
+ # given
+ query = """
+ fragment SchemaFragment on Query {
+ __schema {
+ __typename
+ }
+ }
+
+ query {
+ ...SchemaFragment
+ }
+ """
+ document = backend.document_from_string(schema, query)
+
+ # when
+ result = check_if_query_contains_only_schema(document)
+
+ # then
+ assert result is True
+
+
+def test_check_if_query_contains_only_schema_with_schema_query_and_fragments():
+ # given
+ query = """
+ fragment SchemaFragment on Query {
+ ... {
+ __schema {
+ __typename
+ }
+ }
+ }
+
+ query {
+ ...SchemaFragment
+ }
+ """
+ document = backend.document_from_string(schema, query)
+
+ # when
+ result = check_if_query_contains_only_schema(document)
+
+ # then
+ assert result is True
diff --git a/saleor/graphql/utils/validators.py b/saleor/graphql/utils/validators.py
index 9efcfeea49..248797f49f 100644
--- a/saleor/graphql/utils/validators.py
+++ b/saleor/graphql/utils/validators.py
@@ -1,4 +1,12 @@
from django.core.exceptions import ValidationError
+from graphql import GraphQLDocument
+from graphql.error import GraphQLError
+from graphql.language.ast import (
+ Field,
+ FragmentDefinition,
+ InlineFragment,
+ OperationDefinition,
+)
from ..core.utils import get_duplicates_items
@@ -23,3 +31,78 @@ def check_for_duplicates(
error = ValidationError(message=error_msg, params=params)
return error
+
+
+def __queries_or_introspection_in_selections(selections: list, is_query: bool):
+ found_queries = False
+ found_introspection = False
+ for selection in selections:
+ if isinstance(selection, Field):
+ selection_name = str(selection.name.value)
+ if is_query and selection_name == "__schema":
+ found_introspection = True
+ else:
+ found_queries = True
+ if isinstance(selection, InlineFragment):
+ (
+ sub_queries,
+ sub_introspection,
+ ) = __queries_or_introspection_in_inline_fragment(
+ selection, is_query=is_query
+ )
+ found_queries = found_queries or sub_queries
+ found_introspection = found_introspection or sub_introspection
+ return found_queries, found_introspection
+
+
+def __queries_or_introspection_in_inline_fragment(
+ fragment: InlineFragment, is_query: bool
+):
+ if fragment.type_condition and fragment.type_condition.name.value == "__Schema":
+ return False, True
+ selections = fragment.selection_set.selections
+ if (fragment.type_condition and fragment.type_condition.name.value == "Query") or (
+ is_query and not fragment.type_condition
+ ):
+ return __queries_or_introspection_in_selections(selections, is_query=True)
+ else:
+ return __queries_or_introspection_in_selections(selections, is_query=False)
+
+
+def __queries_or_introspection_in_operation_definition(definition: OperationDefinition):
+ if definition.operation != "query":
+ return False, False
+ selections = definition.selection_set.selections
+ return __queries_or_introspection_in_selections(selections, is_query=True)
+
+
+def __queries_or_introspection_in_fragment_definition(definition: FragmentDefinition):
+ selections = definition.selection_set.selections
+ if definition.type_condition and definition.type_condition.name.value == "Query":
+ return __queries_or_introspection_in_selections(selections, is_query=True)
+ return __queries_or_introspection_in_selections(selections, is_query=False)
+
+
+def check_if_query_contains_only_schema(document: GraphQLDocument):
+ found_queries = False
+ found_introspection = False
+ for definition in document.document_ast.definitions:
+ if isinstance(definition, OperationDefinition):
+ (
+ sub_queries,
+ sub_introspection,
+ ) = __queries_or_introspection_in_operation_definition(definition)
+ found_queries = found_queries or sub_queries
+ found_introspection = found_introspection or sub_introspection
+ if isinstance(definition, FragmentDefinition):
+ (
+ sub_queries,
+ sub_introspection,
+ ) = __queries_or_introspection_in_fragment_definition(definition)
+ found_queries = found_queries or sub_queries
+ found_introspection = found_introspection or sub_introspection
+ if found_introspection and found_queries:
+ raise GraphQLError(
+ "Queries and introspection cannot be mixed in the same request."
+ )
+ return found_introspection
diff --git a/saleor/graphql/views.py b/saleor/graphql/views.py
index 24adc05c22..1d16b0941d 100644
--- a/saleor/graphql/views.py
+++ b/saleor/graphql/views.py
@@ -28,6 +28,7 @@ from .context import clear_context, get_context_value
from .core.validators.query_cost import validate_query_cost
from .query_cost_map import COST_MAP
from .utils import format_error, query_fingerprint, query_identifier
+from .utils.validators import check_if_query_contains_only_schema
INT_ERROR_MSG = "Int cannot represent non 32-bit signed integer value"
@@ -250,20 +251,6 @@ class GraphQLView(View):
except (ValueError, GraphQLSyntaxError) as e:
return None, ExecutionResult(errors=[e], invalid=True)
- def check_if_query_contains_only_schema(self, document: GraphQLDocument):
- query_with_schema = False
- for definition in document.document_ast.definitions:
- selections = definition.selection_set.selections
- selection_count = len(selections)
- for selection in selections:
- selection_name = str(selection.name.value)
- if selection_name == "__schema":
- query_with_schema = True
- if selection_count > 1:
- msg = "`__schema` must be fetched in separate query"
- raise GraphQLError(msg)
- return query_with_schema
-
def execute_graphql_request(self, request: HttpRequest, data: dict):
with opentracing.global_tracer().start_active_span("graphql_query") as scope:
span = scope.span
@@ -288,9 +275,7 @@ class GraphQLView(View):
span.set_tag("graphql.query_identifier", query_identifier(document))
span.set_tag("graphql.query_fingerprint", query_fingerprint(document))
try:
- query_contains_schema = self.check_if_query_contains_only_schema(
- document
- )
+ query_contains_schema = check_if_query_contains_only_schema(document)
except GraphQLError as e:
return ExecutionResult(errors=[e], invalid=True)