Skip to content

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

Add GraphQL query cost validation (#8526)

Rafał Pitońb25b8bf67286
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0ab87d7279..7818a4c86d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Batch loads in queries for Apollo Federation - #8273 by @rafalp
- Reserve stocks for checkouts - #7589 by @rafalp
- Add `variant_selection` to `ProductAttributeAssign` operations - #8235 by @kuchichan
+- Add query complexity limit to GraphQL API - #8526 by rafalp
# 3.0.0 [Unreleased]
diff --git a/saleor/graphql/core/tests/test_query_cost_validation.py b/saleor/graphql/core/tests/test_query_cost_validation.py
new file mode 100644
index 0000000000..55fbf53dc4
--- /dev/null
+++ b/saleor/graphql/core/tests/test_query_cost_validation.py
@@ -0,0 +1,133 @@
+import graphene
+from django.test import override_settings
+
+
+@override_settings(GRAPHQL_QUERY_MAX_COMPLEXITY=1)
+def test_query_exceeding_cost_limit_fails_validation(
+ api_client,
+ variant_with_many_stocks,
+ channel_USD,
+):
+ query_fields = "\n".join(
+ [
+ "p%s: productVariant(id: $id, channel: $channel) { id }" % i
+ for i in range(20)
+ ]
+ )
+ query = (
+ """
+ query variantAvailability($id: ID!, $channel: String) {
+ %s
+ }
+ """
+ % query_fields
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),
+ "channel": channel_USD.slug,
+ }
+
+ response = api_client.post_graphql(query, variables)
+ json_response = response.json()
+ assert "data" not in json_response
+ query_cost = json_response["extensions"]["cost"]["requestedQueryCost"]
+ assert query_cost > 1
+ assert len(json_response["errors"]) == 1
+ assert json_response["errors"][0]["message"] == (
+ f"The query exceeds the maximum cost of 1. Actual cost is {query_cost}"
+ )
+
+
+@override_settings(GRAPHQL_QUERY_MAX_COMPLEXITY=100000)
+def test_query_below_cost_limit_passes_validation(
+ api_client,
+ variant_with_many_stocks,
+ channel_USD,
+):
+ query_fields = "\n".join(
+ [
+ "p%s: productVariant(id: $id, channel: $channel) { id }" % i
+ for i in range(20)
+ ]
+ )
+ query = (
+ """
+ query variantQueryCost($id: ID!, $channel: String) {
+ %s
+ }
+ """
+ % query_fields
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),
+ "channel": channel_USD.slug,
+ }
+
+ response = api_client.post_graphql(query, variables)
+ json_response = response.json()
+ assert "errors" not in json_response
+ query_cost = json_response["extensions"]["cost"]["requestedQueryCost"]
+ assert query_cost == 20
+ assert len(json_response["data"]) == 20
+
+
+VARIANTS_QUERY = """
+ query variantsQueryCost($ids: [ID], $channel: String, $first: Int) {
+ productVariants(ids: $ids, channel: $channel, first: $first) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+@override_settings(GRAPHQL_QUERY_MAX_COMPLEXITY=10)
+def test_query_exceeding_cost_limit_due_to_multiplied_complexity_fails_validation(
+ api_client,
+ variant_with_many_stocks,
+ channel_USD,
+):
+ variables = {
+ "ids": [
+ graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk)
+ ],
+ "channel": channel_USD.slug,
+ "first": 100,
+ }
+
+ response = api_client.post_graphql(VARIANTS_QUERY, variables)
+ json_response = response.json()
+ assert "data" not in json_response
+ query_cost = json_response["extensions"]["cost"]["requestedQueryCost"]
+ assert query_cost > 10
+ assert len(json_response["errors"]) == 1
+ assert json_response["errors"][0]["message"] == (
+ f"The query exceeds the maximum cost of 10. Actual cost is {query_cost}"
+ )
+
+
+@override_settings(GRAPHQL_QUERY_MAX_COMPLEXITY=10)
+def test_query_below_cost_limit_with_multiplied_complexity_passes_validation(
+ api_client,
+ variant_with_many_stocks,
+ channel_USD,
+):
+ variables = {
+ "ids": [
+ graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk)
+ ],
+ "channel": channel_USD.slug,
+ "first": 5,
+ }
+
+ response = api_client.post_graphql(VARIANTS_QUERY, variables)
+ json_response = response.json()
+ assert "errors" not in json_response
+ query_cost = json_response["extensions"]["cost"]["requestedQueryCost"]
+ assert query_cost == 5
+ assert len(json_response["data"]) == 1
diff --git a/saleor/graphql/core/validators.py b/saleor/graphql/core/validators/__init__.py
similarity index 98%
rename from saleor/graphql/core/validators.py
rename to saleor/graphql/core/validators/__init__.py
index e031a94da8..562dd466ad 100644
--- a/saleor/graphql/core/validators.py
+++ b/saleor/graphql/core/validators/__init__.py
@@ -5,7 +5,7 @@ from django.core.exceptions import ValidationError
from django_prices.utils.formatting import get_currency_fraction
from graphql.error import GraphQLError
-from ...product.models import ProductVariantChannelListing
+from ....product.models import ProductVariantChannelListing
if TYPE_CHECKING:
from decimal import Decimal
diff --git a/saleor/graphql/core/validators/query_cost.py b/saleor/graphql/core/validators/query_cost.py
new file mode 100644
index 0000000000..687941eef7
--- /dev/null
+++ b/saleor/graphql/core/validators/query_cost.py
@@ -0,0 +1,304 @@
+from functools import reduce
+from operator import add, mul
+from typing import Any, Dict, List, Optional, Type, Union, cast
+
+from graphql import (
+ GraphQLError,
+ GraphQLInterfaceType,
+ GraphQLObjectType,
+ GraphQLSchema,
+ get_named_type,
+)
+from graphql.execution.values import get_argument_values
+from graphql.language.ast import (
+ Field,
+ FragmentDefinition,
+ FragmentSpread,
+ InlineFragment,
+ OperationDefinition,
+)
+from graphql.type import GraphQLField
+from graphql.validation import validate
+from graphql.validation.rules.base import ValidationRule
+from graphql.validation.validation import ValidationContext
+
+CostAwareNode = Union[
+ Field,
+ FragmentDefinition,
+ FragmentSpread,
+ InlineFragment,
+ OperationDefinition,
+]
+
+GraphQLFieldMap = Dict[str, GraphQLField]
+
+
+class CostValidator(ValidationRule):
+ maximum_cost: int
+ default_cost: int = 0
+ default_complexity: int = 1
+ variables: Optional[Dict] = None
+ cost_map: Optional[Dict[str, Dict[str, Any]]] = None
+
+ def __init__(
+ self,
+ maximum_cost: int,
+ *,
+ default_cost: int = 0,
+ default_complexity: int = 1,
+ variables: Optional[Dict] = None,
+ cost_map: Optional[Dict[str, Dict[str, Any]]] = None,
+ ): # pylint: disable=super-init-not-called
+ self.maximum_cost = maximum_cost
+ self.variables = variables
+ self.cost_map = cost_map
+ self.default_cost = default_cost
+ self.default_complexity = default_complexity
+ self.cost = 0
+ self.operation_multipliers: List[Any] = []
+
+ def __call__(self, context: ValidationContext):
+ self.context = context
+ return self
+
+ def compute_node_cost(self, node: CostAwareNode, type_def, parent_multipliers=None):
+ if parent_multipliers is None:
+ parent_multipliers = []
+ if isinstance(node, FragmentSpread) or not node.selection_set:
+ return 0
+ fields: GraphQLFieldMap = {}
+ if isinstance(type_def, (GraphQLObjectType, GraphQLInterfaceType)):
+ fields = type_def.fields
+ total = 0
+ for child_node in node.selection_set.selections:
+ self.operation_multipliers = parent_multipliers[:]
+ node_cost = self.default_cost
+ if isinstance(child_node, Field):
+ field = fields.get(child_node.name.value)
+ if not field:
+ continue
+ field_type = get_named_type(field.type)
+ try:
+ field_args: Dict[str, Any] = get_argument_values(
+ field.args,
+ child_node.arguments,
+ self.variables,
+ )
+ except Exception as e:
+ report_error(self.context, e)
+ field_args = {}
+
+ if not self.cost_map:
+ return 0
+
+ cost_map_args = (
+ self.get_args_from_cost_map(child_node, type_def.name, field_args)
+ if type_def and type_def.name
+ else None
+ )
+ if cost_map_args is not None:
+ try:
+ node_cost = self.compute_cost(**cost_map_args)
+ except (TypeError, ValueError) as e:
+ report_error(self.context, e)
+
+ child_cost = self.compute_node_cost(
+ child_node, field_type, self.operation_multipliers
+ )
+ node_cost += child_cost
+ if isinstance(child_node, FragmentSpread):
+ fragment = self.context.get_fragment(child_node.name.value)
+ if fragment:
+ fragment_type = self.context.get_schema().get_type(
+ fragment.type_condition.name.value
+ )
+ node_cost = self.compute_node_cost(fragment, fragment_type)
+ if isinstance(child_node, InlineFragment):
+ inline_fragment_type = type_def
+ if child_node.type_condition and child_node.type_condition.name:
+ inline_fragment_type = self.context.get_schema().get_type(
+ child_node.type_condition.name.value
+ )
+ node_cost = self.compute_node_cost(child_node, inline_fragment_type)
+ total += node_cost
+ return total
+
+ def enter_operation_definition(
+ self, node, key, parent, path, ancestors
+ ): # pylint: disable=unused-argument
+ if self.cost_map:
+ try:
+ validate_cost_map(self.cost_map, self.context.get_schema())
+ except GraphQLError as cost_map_error:
+ self.context.report_error(cost_map_error)
+ return
+
+ if node.operation == "query":
+ self.cost += self.compute_node_cost(
+ node, self.context.get_schema().get_query_type()
+ )
+ if node.operation == "mutation":
+ self.cost += self.compute_node_cost(
+ node, self.context.get_schema().get_mutation_type()
+ )
+ if node.operation == "subscription":
+ self.cost += self.compute_node_cost(
+ node, self.context.get_schema().get_subscription_type()
+ )
+
+ def leave_operation_definition(
+ self, node, key, parent, path, ancestors
+ ): # pylint: disable=unused-argument
+ if self.cost > self.maximum_cost:
+ self.context.report_error(self.get_cost_exceeded_error())
+
+ def compute_cost(self, multipliers=None, use_multipliers=True, complexity=None):
+ if complexity is None:
+ complexity = self.default_complexity
+ if use_multipliers:
+ if multipliers:
+ multiplier = reduce(add, multipliers, 0)
+ self.operation_multipliers = self.operation_multipliers + [multiplier]
+ return reduce(mul, self.operation_multipliers, complexity)
+ return complexity
+
+ def get_args_from_cost_map(self, node: Field, parent_type: str, field_args: Dict):
+ cost_args = None
+ cost_map = cast(Dict[Any, Dict], self.cost_map)
+ if parent_type in cost_map:
+ cost_args = cost_map[parent_type].get(node.name.value)
+ if not cost_args:
+ return None
+ cost_args = cost_args.copy()
+ if "multipliers" in cost_args:
+ cost_args["multipliers"] = self.get_multipliers_from_string(
+ cost_args["multipliers"], field_args
+ )
+ return cost_args
+
+ def get_multipliers_from_string(self, multipliers: List[str], field_args):
+ accessors = [s.split(".") for s in multipliers]
+ multipliers: Any = []
+ for accessor in accessors:
+ val = field_args
+ for key in accessor:
+ val = val.get(key)
+ try:
+ multipliers.append(int(val)) # type: ignore
+ except (ValueError, TypeError):
+ pass
+ multipliers = [
+ len(multiplier) if isinstance(multiplier, (list, tuple)) else multiplier
+ for multiplier in multipliers
+ ]
+ return [m for m in multipliers if m > 0]
+
+ def get_cost_exceeded_error(self) -> "QueryCostError":
+ return QueryCostError(
+ cost_analysis_message(self.maximum_cost, self.cost),
+ extensions={
+ "cost": {
+ "requestedQueryCost": self.cost,
+ "maximumAvailable": self.maximum_cost,
+ }
+ },
+ )
+
+ def enter(
+ self,
+ node: Any,
+ key: Optional[Union[int, str]],
+ parent: Any,
+ path: List[Union[int, str]],
+ ancestors: List[Any],
+ ):
+ if isinstance(node, OperationDefinition):
+ self.enter_operation_definition(node, key, parent, path, ancestors)
+
+ def leave(
+ self,
+ node: Any,
+ key: Optional[Union[int, str]],
+ parent: Any,
+ path: List[Union[int, str]],
+ ancestors: List[Any],
+ ):
+ if isinstance(node, OperationDefinition):
+ self.leave_operation_definition(node, key, parent, path, ancestors)
+
+
+def validate_cost_map(cost_map: Dict[str, Dict[str, Any]], schema: GraphQLSchema):
+ type_map = schema.get_type_map()
+ for type_name, type_fields in cost_map.items():
+ if type_name not in type_map:
+ raise GraphQLError(
+ "The query cost could not be calculated because cost map specifies "
+ f"a type {type_name} that is not defined by the schema."
+ )
+
+ if not isinstance(type_map[type_name], GraphQLObjectType):
+ raise GraphQLError(
+ "The query cost could not be calculated because cost map specifies "
+ f"a type {type_name} that is defined by the schema, but is not an "
+ "object type."
+ )
+
+ for field_name in type_fields:
+ graphql_type = cast(GraphQLObjectType, type_map[type_name])
+ if field_name not in graphql_type.fields:
+ raise GraphQLError(
+ "The query cost could not be calculated because cost map contains "
+ f"a field {field_name} not defined by the {type_name} type."
+ )
+
+
+def report_error(context: ValidationContext, error: Exception):
+ context.report_error(GraphQLError(str(error)))
+
+
+def cost_analysis_message(maximum_cost: int, cost: int) -> str:
+ return "The query exceeds the maximum cost of %d. Actual cost is %d" % (
+ maximum_cost,
+ cost,
+ )
+
+
+class QueryCostError(GraphQLError):
+ pass
+
+
+def cost_validator(
+ maximum_cost: int,
+ *,
+ default_cost: int = 0,
+ default_complexity: int = 1,
+ variables: Optional[Dict] = None,
+ cost_map: Optional[Dict[str, Dict[str, Any]]] = None,
+) -> Type[ValidationRule]:
+ validator = CostValidator(
+ maximum_cost=maximum_cost,
+ default_cost=default_cost,
+ default_complexity=default_complexity,
+ variables=variables,
+ cost_map=cost_map,
+ )
+
+ return cast(Type[ValidationRule], validator)
+
+
+def validate_query_cost(
+ schema,
+ query,
+ variables,
+ cost_map,
+ maximum_cost,
+):
+ validator = cost_validator(
+ maximum_cost,
+ variables=variables,
+ cost_map=cost_map,
+ )
+ error = validate(schema, query.document_ast, [validator])
+ if error:
+ return validator.cost, error
+ return validator.cost, None
diff --git a/saleor/graphql/menu/tests/test_menu.py b/saleor/graphql/menu/tests/test_menu.py
index f4c39f2a53..5ca56dfc97 100644
--- a/saleor/graphql/menu/tests/test_menu.py
+++ b/saleor/graphql/menu/tests/test_menu.py
@@ -1220,17 +1220,15 @@ def test_menu_cannot_get_menu_item_not_from_same_menu(
QUERY_REORDER_MENU, {"moves": moves, "menu": menu_id}, [permission_manage_menus]
)
- assert json.loads(response.content) == {
- "data": {
- "menuItemMove": {
- "errors": [
- {
- "field": "item",
- "message": f"Couldn't resolve to a node: {node_id}",
- }
- ],
- "menu": None,
- }
+ assert json.loads(response.content)["data"] == {
+ "menuItemMove": {
+ "errors": [
+ {
+ "field": "item",
+ "message": f"Couldn't resolve to a node: {node_id}",
+ }
+ ],
+ "menu": None,
}
}
@@ -1253,11 +1251,9 @@ def test_menu_cannot_pass_an_invalid_menu_item_node_type(
QUERY_REORDER_MENU, {"moves": moves, "menu": menu_id}, [permission_manage_menus]
)
- assert json.loads(response.content) == {
- "data": {
- "menuItemMove": {
- "errors": [{"field": "item", "message": "Must receive a MenuItem id."}],
- "menu": None,
- }
+ assert json.loads(response.content)["data"] == {
+ "menuItemMove": {
+ "errors": [{"field": "item", "message": "Must receive a MenuItem id."}],
+ "menu": None,
}
}
diff --git a/saleor/graphql/notifications/tests/test_external_notification_query.py b/saleor/graphql/notifications/tests/test_external_notification_query.py
index d6fe826101..b9cfc4c266 100644
--- a/saleor/graphql/notifications/tests/test_external_notification_query.py
+++ b/saleor/graphql/notifications/tests/test_external_notification_query.py
@@ -19,7 +19,8 @@ query_test_invalid_data = [
}
},
400,
- 'Variable "$channel" of required type "String!" was not provided.',
+ 'Argument "channel" of required type String!" provided the variable '
+ '"$channel" which was not provided',
),
(
{
diff --git a/saleor/graphql/query_cost_map.py b/saleor/graphql/query_cost_map.py
new file mode 100644
index 0000000000..1e2e9ccfcc
--- /dev/null
+++ b/saleor/graphql/query_cost_map.py
@@ -0,0 +1,130 @@
+"""Costs map used by query complexity validator.
+
+It's three levels deep dict of dicts:
+
+- Type
+- Fields
+- Complexity
+
+To set complexity cost for querying a field "likes" on type "User":
+
+{
+ "User": {
+ "likes": {"complexity": 2}
+ }
+}
+
+Querying above field will not increase query complexity by 1.
+
+If field's complexity should be multiplied by value of argument (or arguments),
+you can specify names of those arguments in "multipliers" list:
+
+{
+ "Query": {
+ "products": {"complexity": 1, "multipliers": ["first", "last"]}
+ }
+}
+
+This will result in following queries having cost of 100:
+
+{ products(first: 100) { edges: { id } } }
+
+{ products(last: 100) { edges: { id } } }
+
+{ products(first: 10, last: 10) { edges: { id } } }
+
+Notice that complexity is in last case is multiplied by all arguments.
+
+Complexity is also multiplied recursively:
+
+{
+ "Query": {
+ "products": {"complexity": 1, "multipliers": ["first", "last"]}
+ },
+ "Product": {
+ "shippings": {"complexity": 1},
+ }
+}
+
+This query will have cost of 200 (100 x 2 for each product):
+
+{ products(first: 100) { complexity } }
+"""
+
+COST_MAP = {
+ "Query": {
+ "webhook": {"complexity": 1},
+ "warehouse": {"complexity": 1},
+ "warehouses": {"complexity": 1},
+ "translations": {"complexity": 1},
+ "translation": {"complexity": 1},
+ "stock": {"complexity": 1},
+ "stocks": {"complexity": 1},
+ "shippingZone": {"complexity": 1},
+ "shippingZones": {"complexity": 1},
+ "digitalContent": {"complexity": 1},
+ "digitalContents": {"complexity": 1},
+ "categories": {"complexity": 1},
+ "category": {"complexity": 1},
+ "collection": {"complexity": 1},
+ "collections": {"complexity": 1},
+ "product": {"complexity": 1},
+ "products": {"complexity": 1, "multipliers": ["first", "last"]},
+ "productType": {"complexity": 1},
+ "productTypes": {"complexity": 1},
+ "productVariant": {"complexity": 1},
+ "productVariants": {"complexity": 1, "multipliers": ["first", "last"]},
+ "payment": {"complexity": 1},
+ "payments": {"complexity": 1},
+ "page": {"complexity": 1},
+ "pages": {"complexity": 1},
+ "pageType": {"complexity": 1},
+ "pageTypes": {"complexity": 1},
+ "homepageEvents": {"complexity": 1},
+ "order": {"complexity": 1},
+ "orders": {"complexity": 1},
+ "draftOrders": {"complexity": 1},
+ "ordersTotal": {"complexity": 1},
+ "orderByToken": {"complexity": 1},
+ "menu": {"complexity": 1},
+ "menus": {"complexity": 1},
+ "menuItem": {"complexity": 1},
+ "menuItems": {"complexity": 1},
+ "giftCard": {"complexity": 1},
+ "giftCards": {"complexity": 1},
+ "giftCardCurrencies": {"complexity": 1},
+ "plugin": {"complexity": 1},
+ "plugins": {"complexity": 1},
+ "sale": {"complexity": 1},
+ "sales": {"complexity": 1},
+ "voucher": {"complexity": 1},
+ "vouchers": {"complexity": 1},
+ "exportFile": {"complexity": 1},
+ "exportFiles": {"complexity": 1},
+ "taxTypes": {"complexity": 1},
+ "checkout": {"complexity": 1},
+ "checkouts": {"complexity": 1},
+ "checkoutLines": {"complexity": 1},
+ "channel": {"complexity": 1},
+ "channels": {"complexity": 1},
+ "attributes": {"complexity": 1},
+ "attribute": {"complexity": 1},
+ "appsInstallations": {"complexity": 1},
+ "apps": {"complexity": 1},
+ "app": {"complexity": 1},
+ "appExtensions": {"complexity": 1},
+ "appExtension": {"complexity": 1},
+ "addressValidationRules": {"complexity": 1},
+ "address": {"complexity": 1},
+ "customers": {"complexity": 1},
+ "permissionGroups": {"complexity": 1},
+ "permissionGroup": {"complexity": 1},
+ "me": {"complexity": 1},
+ "staffUsers": {"complexity": 1},
+ "user": {"complexity": 1},
+ },
+ "Product": {
+ "defaultVariant": {"complexity": 1},
+ "variants": {"complexity": 1},
+ },
+}
diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.py
index d7211e1607..78f6ae9199 100644
--- a/saleor/graphql/shop/tests/test_shop.py
+++ b/saleor/graphql/shop/tests/test_shop.py
@@ -1556,13 +1556,11 @@ def test_get_shop_limit_info_returns_null_by_default(staff_api_client):
query = LIMIT_INFO_QUERY
response = staff_api_client.post_graphql(query)
content = get_graphql_content(response)
- assert content == {
- "data": {
- "shop": {
- "limits": {
- "currentUsage": {"channels": None},
- "allowedUsage": {"channels": None},
- }
+ assert content["data"] == {
+ "shop": {
+ "limits": {
+ "currentUsage": {"channels": None},
+ "allowedUsage": {"channels": None},
}
}
}
diff --git a/saleor/graphql/views.py b/saleor/graphql/views.py
index 5b6b3f7338..0c1ed83f25 100644
--- a/saleor/graphql/views.py
+++ b/saleor/graphql/views.py
@@ -27,6 +27,9 @@ from jwt.exceptions import PyJWTError
from .. import __version__ as saleor_version
from ..core.exceptions import PermissionDenied, ReadOnlyException
from ..core.utils import is_valid_ipv4, is_valid_ipv6
+from .api import schema
+from .core.validators.query_cost import validate_query_cost
+from .query_cost_map import COST_MAP
from .utils import query_fingerprint
API_PATH = SimpleLazyObject(lambda: reverse("api"))
@@ -197,6 +200,8 @@ class GraphQLView(View):
status_code = 400
else:
response["data"] = execution_result.data
+ if execution_result.extensions:
+ response["extensions"] = execution_result.extensions
result: Optional[Dict[str, List[Any]]] = response
else:
result = None
@@ -256,6 +261,7 @@ class GraphQLView(View):
)
query, variables, operation_name = self.get_graphql_params(request, data)
+ query_cost = 0
document, error = self.parse_query(query)
if error:
@@ -272,6 +278,18 @@ class GraphQLView(View):
except GraphQLError as e:
return ExecutionResult(errors=[e], invalid=True)
+ if settings.GRAPHQL_QUERY_MAX_COMPLEXITY:
+ query_cost, cost_errors = validate_query_cost(
+ schema,
+ document,
+ variables,
+ COST_MAP,
+ settings.GRAPHQL_QUERY_MAX_COMPLEXITY,
+ )
+ if cost_errors:
+ result = ExecutionResult(errors=cost_errors, invalid=True)
+ return set_query_cost_on_result(result, query_cost)
+
extra_options: Dict[str, Optional[Any]] = {}
if self.executor:
@@ -299,7 +317,8 @@ class GraphQLView(View):
)
if should_use_cache_for_scheme:
cache.set(key, response)
- return response
+
+ return set_query_cost_on_result(response, query_cost)
except Exception as e:
span.set_tag(opentracing.tags.ERROR, True)
# In the graphql-core version that we are using,
@@ -348,6 +367,9 @@ class GraphQLView(View):
else:
result = {"message": str(error)}
+ if "extensions" not in result:
+ result["extensions"] = {}
+
exc = error
while isinstance(exc, GraphQLError) and hasattr(exc, "original_error"):
exc = exc.original_error
@@ -358,7 +380,7 @@ class GraphQLView(View):
else:
unhandled_errors_logger.error("A query failed unexpectedly", exc_info=exc)
- result["extensions"] = {"exception": {"code": type(exc).__name__}}
+ result["extensions"]["exception"] = {"code": type(exc).__name__}
if settings.DEBUG:
lines = []
@@ -419,3 +441,16 @@ def obj_set(obj, path, value, do_not_replace):
def generate_cache_key(raw_query: str) -> str:
hashed_query = hashlib.sha256(str(raw_query).encode("utf-8")).hexdigest()
return f"{saleor_version}-{hashed_query}"
+
+
+def set_query_cost_on_result(execution_result: ExecutionResult, query_cost):
+ if settings.GRAPHQL_QUERY_MAX_COMPLEXITY:
+ execution_result.extensions.update(
+ {
+ "cost": {
+ "requestedQueryCost": query_cost,
+ "maximumAvailable": settings.GRAPHQL_QUERY_MAX_COMPLEXITY,
+ }
+ }
+ )
+ return execution_result
diff --git a/saleor/settings.py b/saleor/settings.py
index 3696701159..9a3ae9aa66 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -532,6 +532,9 @@ GRAPHENE = {
],
}
+# Set GRAPHQL_QUERY_MAX_COMPLEXITY=0 in env to disable (not recommended)
+GRAPHQL_QUERY_MAX_COMPLEXITY = int(os.environ.get("GRAPHQL_QUERY_MAX_COMPLEXITY", 250))
+
# Max number entities that can be requested in single query by Apollo Federation
# Federation protocol implements no securities on its own part - malicious actor
# may build a query that requests for potentially few thousands of entities.