Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Merge commit from fork
Mikailf0371bdd4caf
diff --git a/saleor/core/jwt.py b/saleor/core/jwt.pyindex bd7f3fbc33..0060d17cec 100644--- a/saleor/core/jwt.py+++ b/saleor/core/jwt.py@@ -18,6 +18,7 @@ from .jwt_manager import get_jwt_managerJWT_ACCESS_TYPE = "access"JWT_REFRESH_TYPE = "refresh"+JWT_CONFIRM_CHANGE_EMAIL_TYPE = "confirm-email-change"JWT_THIRDPARTY_ACCESS_TYPE = "thirdparty"JWT_REFRESH_TOKEN_COOKIE_NAME = "refreshToken"@@ -82,8 +83,21 @@ def jwt_decode(token: str, verify_aud: bool = False) -> dict[str, Any]:return jwt_manager.decode(token, verify_aud=verify_aud)-def create_token(payload: dict[str, Any], exp_delta: datetime.timedelta) -> str:- payload.update(jwt_base_payload(exp_delta, token_owner=JWT_SALEOR_OWNER_NAME))+def create_token(+ payload: dict[str, Any],+ *,+ user: User,+ exp_delta: datetime.timedelta,+ token_type: str,+) -> str:+ payload.update(+ jwt_user_payload(+ token_owner=JWT_SALEOR_OWNER_NAME,+ user=user,+ exp_delta=exp_delta,+ token_type=token_type,+ )+ )return jwt_encode(payload)diff --git a/saleor/graphql/account/mutations/account/confirm_email_change.py b/saleor/graphql/account/mutations/account/confirm_email_change.pyindex b4c3ce2350..874b2f218b 100644--- a/saleor/graphql/account/mutations/account/confirm_email_change.py+++ b/saleor/graphql/account/mutations/account/confirm_email_change.py@@ -1,3 +1,4 @@+import loggingfrom typing import castimport graphene@@ -6,7 +7,7 @@ from django.core.exceptions import ValidationErrorfrom .....account import models, notifications, searchfrom .....account.error_codes import AccountErrorCode-from .....core.jwt import jwt_decode+from .....core.jwt import JWT_CONFIRM_CHANGE_EMAIL_TYPE, jwt_decodefrom .....giftcard.utils import assign_user_gift_cardsfrom .....order.utils import match_orders_with_new_userfrom .....permission.auth_filters import AuthorizationFilters@@ -20,6 +21,8 @@ from ....core.utils import WebhookEventInfofrom ....plugins.dataloaders import get_plugin_manager_promisefrom ...types import User+logger = logging.getLogger(__name__)+class ConfirmEmailChange(BaseMutation):user = graphene.Field(User, description="A user instance with a new email.")@@ -71,6 +74,16 @@ class ConfirmEmailChange(BaseMutation):) from ereturn payload+ @staticmethod+ def reject_token():+ raise ValidationError(+ {+ "token": ValidationError(+ "Invalid token.", code=AccountErrorCode.JWT_INVALID_TOKEN.value+ )+ }+ )+@classmethoddef perform_mutation( # type: ignore[override]cls, _root, info: ResolveInfo, /, *, channel=None, token@@ -79,12 +92,34 @@ class ConfirmEmailChange(BaseMutation):user = cast(models.User, user)payload = cls.get_token_payload(token)++ if (tok_type := payload.get("type")) != JWT_CONFIRM_CHANGE_EMAIL_TYPE:+ logger.info(+ "Received an invalid token type for email confirmation: %s", tok_type+ )+ return cls.reject_token()++ payload_user_pk = payload.get("user_id")+ if not payload_user_pk or payload_user_pk != graphene.Node.to_global_id(+ "User", user.id+ ):+ logger.info("The token user_id claim is mismatching (%s)", user.pk)+ return cls.reject_token()+new_email = payload["new_email"].lower()old_email = payload["old_email"]+ if user.email != old_email:+ logger.info("User's old email address is mismatching (%s)", user.pk)+ return cls.reject_token()+if models.User.objects.filter(email=new_email).exists():raise ValidationError({+ # Note: revealing the user's existence isn't an issue here as the+ # person who is calling this mutation already verified that+ # they are who they are claiming to be as they had to click+ # a unique link that was sent to 'new_email'"new_email": ValidationError("Email is used by other user.",code=AccountErrorCode.UNIQUE.value,diff --git a/saleor/graphql/account/mutations/account/request_email_change.py b/saleor/graphql/account/mutations/account/request_email_change.pyindex d84c5889a4..0c18b91181 100644--- a/saleor/graphql/account/mutations/account/request_email_change.py+++ b/saleor/graphql/account/mutations/account/request_email_change.py@@ -7,7 +7,7 @@ from django.core.exceptions import ValidationErrorfrom .....account import models, notificationsfrom .....account.error_codes import AccountErrorCode-from .....core.jwt import create_token+from .....core.jwt import JWT_CONFIRM_CHANGE_EMAIL_TYPE, create_tokenfrom .....core.utils.url import prepare_url, validate_storefront_urlfrom .....permission.auth_filters import AuthorizationFiltersfrom .....webhook.event_types import WebhookEventAsyncType@@ -83,15 +83,6 @@ class RequestEmailChange(BaseMutation):)})- if models.User.objects.filter(email=new_email).exists():- raise ValidationError(- {- "new_email": ValidationError(- "Email is used by other user.",- code=AccountErrorCode.UNIQUE.value,- )- }- )try:validate_storefront_url(redirect_url)except ValidationError as e:@@ -105,9 +96,13 @@ class RequestEmailChange(BaseMutation):token_payload = {"old_email": user.email,"new_email": new_email,- "user_pk": user.pk,}- token = create_token(token_payload, settings.JWT_TTL_REQUEST_EMAIL_CHANGE)+ token = create_token(+ token_payload,+ exp_delta=settings.JWT_TTL_REQUEST_EMAIL_CHANGE,+ user=user,+ token_type=JWT_CONFIRM_CHANGE_EMAIL_TYPE,+ )manager = get_plugin_manager_promise(info.context).get()params = urlencode({"token": token})@@ -121,6 +116,11 @@ class RequestEmailChange(BaseMutation):channel_slug=channel_slug,)+ # Note: we do not verify the user's existence in requestEmailChange()+ # as it would reveal the user's existence (both through error message+ # and through timings)+ # However, we still send the email as it's better than not sending any+ # as otherwise the user will think that the application isn't working.cls.call_event(manager.account_change_email_requested,user,diff --git a/saleor/graphql/account/tests/mutations/account/conftest.py b/saleor/graphql/account/tests/mutations/account/conftest.pynew file mode 100644index 0000000000..980d7f2a47--- /dev/null+++ b/saleor/graphql/account/tests/mutations/account/conftest.py@@ -0,0 +1,36 @@+REQUEST_EMAIL_CHANGE_QUERY = """+mutation requestEmailChange(+ $password: String!, $new_email: String!, $redirect_url: String!, $channel:String+) {+ requestEmailChange(+ password: $password,+ newEmail: $new_email,+ redirectUrl: $redirect_url,+ channel: $channel+ ) {+ user {+ }+ errors {+ code+ message+ field+ }+ }+}+"""++CONFIRM_EMAIL_UPDATE_QUERY = """+mutation emailUpdate($token: String!, $channel: String) {+ confirmEmailChange(token: $token, channel: $channel){+ user {+ }+ errors {+ code+ message+ field+ }+ }+}+"""diff --git a/saleor/graphql/account/tests/mutations/account/test_confirm_email_change.py b/saleor/graphql/account/tests/mutations/account/test_confirm_email_change.pyindex 6ea468871a..fa02d0a12f 100644--- a/saleor/graphql/account/tests/mutations/account/test_confirm_email_change.py+++ b/saleor/graphql/account/tests/mutations/account/test_confirm_email_change.py@@ -1,23 +1,48 @@-import datetime+from functools import partialfrom unittest.mock import patch-from ......core.jwt import create_token+from django.conf import settings++from ......account.models import User+from ......channel.models import Channel+from ......core.jwt import JWT_CONFIRM_CHANGE_EMAIL_TYPE, create_token, jwt_decode+from .....tests.fixtures import ApiClientfrom .....tests.utils import get_graphql_content+from .conftest import CONFIRM_EMAIL_UPDATE_QUERY, REQUEST_EMAIL_CHANGE_QUERY-EMAIL_UPDATE_QUERY = """-mutation emailUpdate($token: String!, $channel: String) {- confirmEmailChange(token: $token, channel: $channel){- user {- }- errors {- code- message- field- }- }-}-"""++def request_email_change(+ *, user: User, client: ApiClient, new_email: str, channel: Channel+) -> str:+ old_email = user.email++ # Request a new token+ with patch(+ "saleor.plugins.manager.PluginsManager.account_change_email_requested",+ ) as mocked_notify:+ resp = get_graphql_content(+ client.post_graphql(+ REQUEST_EMAIL_CHANGE_QUERY,+ {+ "new_email": new_email,+ "redirect_url": "https://www.example.com",+ "password": "password",+ "channel": channel.slug,+ },+ )+ )++ # Sanitity check: shouldn't have altered the user+ assert resp["data"]["requestEmailChange"]["errors"] == []+ user.refresh_from_db(fields=("email",))+ assert user.email == old_email++ # Retrive the token+ mocked_notify.assert_called_once()+ token: str = mocked_notify.call_args_list[0].args[2]+ assert isinstance(token, str)+ jwt_decode(token) # ensures it's a JWT+ return token@patch(@@ -43,9 +68,14 @@ def test_email_update(}user = user_api_client.user- token = create_token(payload, datetime.timedelta(hours=1))+ token = create_token(+ payload,+ exp_delta=settings.JWT_TTL_REQUEST_EMAIL_CHANGE,+ token_type=JWT_CONFIRM_CHANGE_EMAIL_TYPE,+ user=customer_user,+ )variables = {"token": token, "channel": channel_PLN.slug}- response = user_api_client.post_graphql(EMAIL_UPDATE_QUERY, variables)+ response = user_api_client.post_graphql(CONFIRM_EMAIL_UPDATE_QUERY, variables)content = get_graphql_content(response)data = content["data"]["confirmEmailChange"]assert data["user"]["email"] == new_email@@ -62,10 +92,15 @@ def test_email_update_to_existing_email(user_api_client, customer_user, staff_us"new_email": staff_user.email,"user_pk": customer_user.pk,}- token = create_token(payload, datetime.timedelta(hours=1))+ token = create_token(+ payload,+ exp_delta=settings.JWT_TTL_REQUEST_EMAIL_CHANGE,+ token_type=JWT_CONFIRM_CHANGE_EMAIL_TYPE,+ user=customer_user,+ )variables = {"token": token}- response = user_api_client.post_graphql(EMAIL_UPDATE_QUERY, variables)+ response = user_api_client.post_graphql(CONFIRM_EMAIL_UPDATE_QUERY, variables)content = get_graphql_content(response)data = content["data"]["confirmEmailChange"]assert not data["user"]@@ -98,14 +133,102 @@ def test_account_email_changed_webhook_event_triggered(}user = user_api_client.user- token = create_token(payload, datetime.timedelta(hours=1))+ token = create_token(+ payload,+ exp_delta=settings.JWT_TTL_REQUEST_EMAIL_CHANGE,+ token_type=JWT_CONFIRM_CHANGE_EMAIL_TYPE,+ user=customer_user,+ )variables = {"token": token, "channel": channel_PLN.slug}# when- user_api_client.post_graphql(EMAIL_UPDATE_QUERY, variables)+ user_api_client.post_graphql(CONFIRM_EMAIL_UPDATE_QUERY, variables)# thenuser.refresh_from_db()assert user.search_vectormocked_trigger_webhooks_async.assert_called()+++def test_confirm_email_change_other_user_token(+ user_api_client,+ user2_api_client,+ channel_USD,+ customer_user,+):+ old_email = customer_user.email+ new_email = "[email protected]"++ confirm_email_change_vars = {+ "token": request_email_change(+ user=customer_user,+ client=user_api_client,+ channel=channel_USD,+ new_email=new_email,+ ),+ "channel": channel_USD.slug,+ }++ # Ensure 'user2_api_client' cannot use token of 'user_api_client'+ resp = get_graphql_content(+ user2_api_client.post_graphql(+ CONFIRM_EMAIL_UPDATE_QUERY, confirm_email_change_vars+ )+ )+ assert resp["data"]["confirmEmailChange"]["errors"] == [+ {"message": "Invalid token.", "field": "token", "code": "JWT_INVALID_TOKEN"}+ ]++ # It shouldn't have altered the email+ customer_user.refresh_from_db(fields=("email",))+ assert customer_user.email == old_email++ # Sanity check: ensure 'user_api_client' can use the token generated by 'user_api_client'+ resp = get_graphql_content(+ user_api_client.post_graphql(+ CONFIRM_EMAIL_UPDATE_QUERY, confirm_email_change_vars+ )+ )+ assert resp["data"]["confirmEmailChange"]["errors"] == []+ customer_user.refresh_from_db(fields=("email",))+ assert customer_user.email == new_email+++def test_cannot_confirm_email_change_if_old_email_mismatches(+ user_api_client,+ channel_USD,+ customer_user,+):+ """Ensure when 'old_email' doesn't match user.email, then it aborts."""++ new_email = "[email protected]"++ confirm_email_change_vars = {+ "token": request_email_change(+ user=customer_user,+ client=user_api_client,+ channel=channel_USD,+ new_email=new_email,+ ),+ "channel": channel_USD.slug,+ }++ send_confirm_change = partial(+ user_api_client.post_graphql,+ CONFIRM_EMAIL_UPDATE_QUERY,+ confirm_email_change_vars,+ )++ # Should accept the token when using it for the first time+ resp = send_confirm_change().json()+ assert resp["data"]["confirmEmailChange"]["errors"] == [], resp+ customer_user.refresh_from_db(fields=("email",))+ assert customer_user.email == new_email++ resp = send_confirm_change().json()+ errors = resp["errors"]+ assert len(errors) == 1+ assert errors[0]["message"] == "Invalid token. User does not exist or is inactive."+ customer_user.refresh_from_db(fields=("email",))+ assert customer_user.email == new_emaildiff --git a/saleor/graphql/account/tests/mutations/account/test_request_email_change.py b/saleor/graphql/account/tests/mutations/account/test_request_email_change.pyindex 84129a5251..f28963648d 100644--- a/saleor/graphql/account/tests/mutations/account/test_request_email_change.py+++ b/saleor/graphql/account/tests/mutations/account/test_request_email_change.py@@ -1,38 +1,19 @@-from unittest.mock import patch+import time+from unittest.mock import ANY, patchfrom urllib.parse import urlencode+import graphenefrom django.conf import settingsfrom freezegun import freeze_timefrom ......account.error_codes import AccountErrorCodefrom ......account.notifications import get_default_user_payload-from ......core.jwt import create_token+from ......core.jwt import JWT_CONFIRM_CHANGE_EMAIL_TYPE, jwt_decodefrom ......core.notify import NotifyEventTypefrom ......core.tests.utils import get_site_context_payloadfrom ......core.utils.url import prepare_urlfrom .....tests.utils import get_graphql_content--REQUEST_EMAIL_CHANGE_QUERY = """-mutation requestEmailChange(- $password: String!, $new_email: String!, $redirect_url: String!, $channel:String-) {- requestEmailChange(- password: $password,- newEmail: $new_email,- redirectUrl: $redirect_url,- channel: $channel- ) {- user {- }- errors {- code- message- field- }- }-}-"""+from .conftest import CONFIRM_EMAIL_UPDATE_QUERY, REQUEST_EMAIL_CHANGE_QUERY@freeze_time("2018-05-31 12:00:01")@@ -53,12 +34,19 @@ def test_account_request_email_change_with_upper_case_email("password": "password","channel": channel_PLN.slug,}- token_payload = {+ expected_token_payload = {"old_email": customer_user.email,+ "email": customer_user.email,"new_email": new_email.lower(),- "user_pk": customer_user.pk,+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),+ "token": customer_user.jwt_token_key,+ "is_staff": False,+ "iat": time.time(),+ "exp": time.time() + settings.JWT_TTL_REQUEST_EMAIL_CHANGE.total_seconds(),+ "type": JWT_CONFIRM_CHANGE_EMAIL_TYPE,+ "owner": "saleor",+ "iss": "https://example.com/graphql/",}- token = create_token(token_payload, settings.JWT_TTL_REQUEST_EMAIL_CHANGE)# whenresponse = user_api_client.post_graphql(REQUEST_EMAIL_CHANGE_QUERY, variables)@@ -68,13 +56,11 @@ def test_account_request_email_change_with_upper_case_email(data = content["data"]["requestEmailChange"]assert not data["errors"]- params = urlencode({"token": token})- redirect_url = prepare_url(params, redirect_url)expected_payload = {"user": get_default_user_payload(customer_user),"recipient_email": new_email.lower(),- "token": token,- "redirect_url": redirect_url,+ "token": ANY,+ "redirect_url": ANY,"old_email": customer_user.email,"new_email": new_email.lower(),"channel_slug": channel_PLN.slug,@@ -87,9 +73,17 @@ def test_account_request_email_change_with_upper_case_email(called_kwargs = call_args.kwargsassert called_args[0] == NotifyEventType.ACCOUNT_CHANGE_EMAIL_REQUESTassert len(called_kwargs) == 2- assert called_kwargs["payload_func"]() == expected_payloadassert called_kwargs["channel_slug"] == channel_PLN.slug+ payload = called_kwargs["payload_func"]()+ assert payload == expected_payload+ assert jwt_decode(payload["token"]) == expected_token_payload++ expected_redirect_url = prepare_url(+ urlencode({"token": payload["token"]}), redirect_url+ )+ assert payload["redirect_url"] == expected_redirect_url+def test_request_email_change(user_api_client, customer_user, channel_PLN):variables = {@@ -106,25 +100,80 @@ def test_request_email_change(user_api_client, customer_user, channel_PLN):def test_request_email_change_to_existing_email(- user_api_client, customer_user, staff_user+ user_api_client,+ customer_user,+ staff_user,+ channel_PLN,):+ """Ensure that we do not reveal a user's existence when requesting email change.++ We expect the following flow:+ 1. Requesting changing the email to one that's already used, shouldn't error out+ (timing is also expected to be constant however this test doesn't verify it)+ 2. The confirmation token is sent to 'new_email' in order to verify whether the+ user has access to 'new_email'+ 3. Once the user clicks the link, they see 'Email is used by other user' error as+ they confirmed that they own or have access to 'new_email' thus it's safe to+ reveal that information+ """++ old_email = customer_user.email+ new_email = staff_user.email+ channel_slug = channel_PLN.slug+variables = {"password": "password",- "new_email": staff_user.email,+ "new_email": new_email,"redirect_url": "http://www.example.com",+ "channel": channel_slug,}- response = user_api_client.post_graphql(REQUEST_EMAIL_CHANGE_QUERY, variables)+ # When requesting email change and the new email address exists+ # it should NOT return an error (we do not want to reveal whether+ # the user exists)++ with patch(+ "saleor.plugins.manager.PluginsManager.account_change_email_requested",+ ) as mocked_notify:+ response = user_api_client.post_graphql(REQUEST_EMAIL_CHANGE_QUERY, variables)content = get_graphql_content(response)data = content["data"]["requestEmailChange"]- assert not data["user"]- assert data["errors"] == [- {- "code": "UNIQUE",- "message": "Email is used by other user.",- "field": "newEmail",- }- ]+ assert data["user"] == {"email": customer_user.email}+ assert not data["errors"]++ # Retrieve the email change confirmation token+ mocked_notify.assert_called_once_with(+ customer_user,+ channel_slug,+ ANY, # token+ ANY, # redirect url+ new_email,+ )+ token: str = mocked_notify.call_args_list[0].args[2]+ assert isinstance(token, str)+ jwt_decode(token) # ensure we grabbed a JWT and not something unrelated++ # When confirming the email change, it should error out when the user+ # already exists+ content = get_graphql_content(+ user_api_client.post_graphql(+ CONFIRM_EMAIL_UPDATE_QUERY, {"token": token, "channel": channel_slug}+ )+ )+ data = content["data"]["confirmEmailChange"]+ assert data == {+ "errors": [+ {+ "code": "UNIQUE",+ "field": "newEmail",+ "message": "Email is used by other user.",+ }+ ],+ "user": None,+ }++ customer_user.refresh_from_db(fields=("email",))+ assert customer_user.email == old_email, "Shouldn't have changed the email"def test_request_email_change_with_invalid_redirect_url(diff --git a/saleor/graphql/core/tests/test_view.py b/saleor/graphql/core/tests/test_view.pyindex 3c211c3180..7338259276 100644--- a/saleor/graphql/core/tests/test_view.py+++ b/saleor/graphql/core/tests/test_view.py@@ -17,7 +17,9 @@ from ...tests.utils import get_graphql_content, get_graphql_content_from_responsfrom ...views import GraphQLView, generate_cache_key-def test_batch_queries(category, product, api_client, channel_USD):+def test_batch_queries(category, product, api_client, channel_USD, settings):+ settings.GRAPHQL_BATCH_MAX_COUNT = 2+query_product = """query GetProduct($id: ID!, $channel: String) {product(id: $id, channel: $channel) {@@ -63,6 +65,41 @@ def test_batch_queries(category, product, api_client, channel_USD):assert data["category"]["name"] == category.name+def test_rejects_based_on_number_batch_queries(api_client, settings):+ """Verifies the behavior when sending multiple batch queries."""++ # By default, we expect Saleor to disallow batch queries+ assert settings.GRAPHQL_BATCH_MAX_COUNT == 1++ query = {"query": "{__typename}"}+ queries = [query]++ # When sending a batch with only 1 query, it should allow it+ resp = api_client.post(data=queries)+ resp_data = resp.json()+ assert isinstance(resp_data, list)+ assert len(resp_data) == 1+ resp_data[0].pop("extensions")+ assert resp_data[0] == {"data": {"__typename": "Query"}}++ # When sending more than 1 query, it should reject+ queries.append(query)+ resp = api_client.post(data=queries)+ assert resp.json() == {+ "errors": [+ {+ "extensions": {+ "exception": {+ "code": "GraphQLError",+ },+ },+ "message": "Number of batch queries exceeded.",+ },+ ]+ }+ assert resp.status_code == 400++def test_graphql_view_query_with_invalid_object_type(staff_api_client, product, permission_manage_orders, graphql_log_handler):diff --git a/saleor/graphql/core/validators/__init__.py b/saleor/graphql/core/validators/__init__.pyindex 6d752ca563..cd2ff8550e 100644--- a/saleor/graphql/core/validators/__init__.py+++ b/saleor/graphql/core/validators/__init__.py@@ -1,15 +1,21 @@-from typing import TYPE_CHECKING, Optional+from typing import TYPE_CHECKING, Any, Optionalfrom uuid import UUIDimport graphene+import graphql.validationfrom babel.numbers import get_currency_precisionfrom django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom graphene.utils.str_converters import to_camel_casefrom graphql.error import GraphQLError+from graphql.language.ast import Document+from graphql.type import GraphQLSchemafrom ....core.utils import generate_unique_slugfrom ....product.models import ProductVariantChannelListing+from .alias_count_limit_rule import AliasCountLimitRule+from .mutation_count_limit_rule import MutationCountLimitRule+from .query_cost import cost_validator as cost_validation_ruleif TYPE_CHECKING:from decimal import Decimal@@ -17,6 +23,32 @@ if TYPE_CHECKING:from django.db.models import Model+def validate_query(+ *,+ schema: GraphQLSchema,+ document_ast: Document,+ variables: dict[str, Any] | None,+ cost_map: dict[str, Any] | None,+):+ cost_validator = cost_validation_rule(+ maximum_cost=settings.GRAPHQL_QUERY_MAX_COMPLEXITY,+ variables=variables,+ cost_map=cost_map,+ )+ error = graphql.validation.validate(+ schema,+ document_ast,+ [+ cost_validator, # type: ignore[list-item] # cost validator is an instance that pretends to be a class # noqa: E501+ AliasCountLimitRule,+ MutationCountLimitRule,+ ],+ )+ if error:+ return cost_validator.cost, error+ return cost_validator.cost, None++def validate_one_of_args_is_in_mutation(*args, **kwargs):try:validate_one_of_args_is_in_query(*args, **kwargs)diff --git a/saleor/graphql/core/validators/alias_count_limit_rule.py b/saleor/graphql/core/validators/alias_count_limit_rule.pynew file mode 100644index 0000000000..c0ebe5b9ee--- /dev/null+++ b/saleor/graphql/core/validators/alias_count_limit_rule.py@@ -0,0 +1,26 @@+from typing import Any++from django.conf import settings+from graphql import GraphQLError+from graphql.language.ast import Field+from graphql.validation.rules.base import ValidationRule+from graphql.validation.validation import ValidationContext+++class AliasCountLimitRule(ValidationRule):+ """Limits the number of aliases that can be sent within a query."""++ def __init__(self, context: ValidationContext) -> None:+ super().__init__(context)+ self.limit: int = settings.GRAPHQL_ALIAS_COUNT_LIMIT+ self.alias_count_seen: int = 0++ def enter_Field(self, field: Field, *_args: Any) -> None:+ if field.alias is not None:+ self.alias_count_seen += 1++ def leave_Document(self, *_args: Any) -> None:+ if self.alias_count_seen > self.limit:+ self.context.report_error(+ GraphQLError(f"Number of aliases exceed the limit of {self.limit}")+ )diff --git a/saleor/graphql/core/validators/mutation_count_limit_rule.py b/saleor/graphql/core/validators/mutation_count_limit_rule.pynew file mode 100644index 0000000000..62e3c343c7--- /dev/null+++ b/saleor/graphql/core/validators/mutation_count_limit_rule.py@@ -0,0 +1,26 @@+from typing import Any++from django.conf import settings+from graphql import GraphQLError+from graphql.language.ast import OperationDefinition+from graphql.validation.rules.base import ValidationRule+from graphql.validation.validation import ValidationContext+++class MutationCountLimitRule(ValidationRule):+ """Limits the number of mutations within a single request."""++ def __init__(self, context: ValidationContext) -> None:+ super().__init__(context)+ self.limit: int = settings.GRAPHQL_MUTATION_COUNT_LIMIT+ self.seen_count: int = 0++ def enter_OperationDefinition(self, node: OperationDefinition, *_args: Any) -> None:+ if node.operation == "mutation" and node.selection_set:+ self.seen_count += len(node.selection_set.selections)++ def leave_Document(self, *_args: Any) -> None:+ if self.seen_count > self.limit:+ self.context.report_error(+ GraphQLError(f"Number of mutations exceed the limit of {self.limit}")+ )diff --git a/saleor/graphql/core/validators/tests/__init__.py b/saleor/graphql/core/validators/tests/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/graphql/core/validators/tests/test_alias_count_limit.py b/saleor/graphql/core/validators/tests/test_alias_count_limit.pynew file mode 100644index 0000000000..fad963f612--- /dev/null+++ b/saleor/graphql/core/validators/tests/test_alias_count_limit.py@@ -0,0 +1,82 @@+import pytest+++ ("_case", "is_valid", "query"),+ [+ ("Alias count lower than limit should be allowed", True, "{x:__typename}"),+ (+ "Too many aliases -> should reject",+ False,+ "{x1: __typename, x2: __typename, x3: __typename}",+ ),+ (+ "Aliases should be counted even if query is nested",+ False,+ """+ {+ alias1: products(first: 10) {+ alias2: edges {+ node {+ alias3: id+ }+ }+ }+ }+ """,+ ),+ (+ "Should count both mutations and response queries",+ False,+ """+ {+ mutation {+ alias1: tokenCreate(email:"x", password:"x"){ token }+ alias2: tokenCreate(email:"x", password:"x"){ token }+ tokenCreate(email:"x", password:"x"){ query: token }+ }+ }+ """,+ ),+ (+ "Should count even if using multiple operations",+ False,+ """+ query a {+ alias1: tokenCreate(email: "x", password: "x") { __typename }+ }+ query b {+ alias2: tokenCreate(email: "x", password: "x") { __typename }+ }+ query b {+ alias3: tokenCreate(email: "x", password: "x") { __typename }+ }+ """,+ ),+ ],+)+def test_limits_number_of_aliases(+ api_client, settings, _case: str, is_valid: bool, query: str+):+ # Prevent mutation limiter from triggering as we want to test alias validation+ settings.GRAPHQL_MUTATION_COUNT_LIMIT = 10+ settings.GRAPHQL_ALIAS_COUNT_LIMIT = 2++ # When sending a batch with only 1 query, it should allow it+ resp = api_client.post(data={"query": query})+ resp_data = resp.json()+ resp_data.pop("extensions")++ if is_valid:+ assert resp_data == {"data": {"x": "Query"}}+ assert resp.status_code == 200+ else:+ assert resp_data == {+ "errors": [+ {+ "extensions": {"exception": {"code": "GraphQLError"}},+ "message": "Number of aliases exceed the limit of 2",+ }+ ]+ }+ assert resp.status_code == 400diff --git a/saleor/graphql/core/validators/tests/test_mutation_count_limit.py b/saleor/graphql/core/validators/tests/test_mutation_count_limit.pynew file mode 100644index 0000000000..9f6c6e8343--- /dev/null+++ b/saleor/graphql/core/validators/tests/test_mutation_count_limit.py@@ -0,0 +1,79 @@+import pytest+++ ("_case", "is_valid", "query"),+ [+ (+ "Mutation count lower than the limit should be allowed",+ True,+ """+ mutation {+ tokenCreate(email: "x", password: "x") { __typename }+ }+ """,+ ),+ (+ "Too many mutations -> should reject",+ False,+ """+ mutation {+ tokenCreate(email: "x", password: "x") { __typename }+ tokenVerify(token: "x") { __typename }+ tokenRefresh(refreshToken: "x") { __typename }+ }+ """,+ ),+ (+ "Mutations should be counted even when using aliases",+ False,+ """+ mutation {+ tokenCreate(email: "x", password: "x") { __typename }+ alias: tokenCreate(email: "x", password: "x") { __typename }+ alias2: tokenCreate(email: "x", password: "x") { __typename }+ }+ """,+ ),+ (+ "Should count even if using multiple operations",+ False,+ """+ mutation {+ tokenCreate(email: "x", password: "x") { __typename }+ }+ mutation {+ tokenCreate(email: "x", password: "x") { __typename }+ }+ mutation {+ tokenCreate(email: "x", password: "x") { __typename }+ }+ """,+ ),+ ],+)+def test_limits_number_of_aliases(+ api_client, settings, _case: str, is_valid: bool, query: str+):+ # Prevent alias limiter from triggering as we want to test alias validation+ settings.GRAPHQL_ALIAS_COUNT_LIMIT = 10+ settings.GRAPHQL_MUTATION_COUNT_LIMIT = 2++ # When sending a batch with only 1 query, it should allow it+ resp = api_client.post(data={"query": query})+ resp_data = resp.json()+ resp_data.pop("extensions")++ if is_valid:+ assert "errors" not in resp_data+ assert resp.status_code == 200+ else:+ assert resp_data == {+ "errors": [+ {+ "extensions": {"exception": {"code": "GraphQLError"}},+ "message": "Number of mutations exceed the limit of 2",+ }+ ]+ }+ assert resp.status_code == 400diff --git a/saleor/graphql/views.py b/saleor/graphql/views.pyindex 327f5ae8d8..5637187953 100644--- a/saleor/graphql/views.py+++ b/saleor/graphql/views.py@@ -35,7 +35,7 @@ from ..webhook import observabilityfrom . import GraphQLOperationResultfrom .api import API_PATH, schemafrom .context import clear_context, get_context_value-from .core.validators.query_cost import validate_query_cost+from .core.validators import validate_queryfrom .error import clear_errorsfrom .metrics import (record_graphql_query_cost,@@ -181,6 +181,18 @@ class GraphQLView(View):result: GraphQLOperationResult | None | list[GraphQLOperationResult | None]if isinstance(data, list):+ if len(data) > settings.GRAPHQL_BATCH_MAX_COUNT:+ return JsonResponse(+ data={+ "errors": [+ self.format_error(+ GraphQLError("Number of batch queries exceeded.")+ )+ ]+ },+ status=400,+ )+responses = [self.get_response(request, entry) for entry in data]result = [response for response, code in responses]status_code = max((code for response, code in responses), default=200)@@ -383,12 +395,11 @@ class GraphQLView(View):saleor_attributes.SALEOR_SOURCE_SERVICE_NAME, source_service_name)- query_cost, cost_errors = validate_query_cost(- schema,- document,- variables,- COST_MAP,- settings.GRAPHQL_QUERY_MAX_COMPLEXITY,+ query_cost, cost_errors = validate_query(+ schema=schema,+ document_ast=document.document_ast,+ variables=variables,+ cost_map=COST_MAP,)span.set_attribute(saleor_attributes.GRAPHQL_OPERATION_COST, query_cost)diff --git a/saleor/settings.py b/saleor/settings.pyindex 7b81257b22..c059c19e98 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -871,6 +871,11 @@ def SENTRY_INIT(dsn: str, sentry_opts: dict):GRAPHQL_PAGINATION_LIMIT = 100GRAPHQL_MIDDLEWARE: list[str] = []+GRAPHQL_BATCH_MAX_COUNT: int = int(os.environ.get("GRAPHQL_BATCH_MAX_COUNT", 1))+GRAPHQL_ALIAS_COUNT_LIMIT: int = int(os.environ.get("GRAPHQL_ALIAS_COUNT_LIMIT", 100))+GRAPHQL_MUTATION_COUNT_LIMIT: int = int(+ os.environ.get("GRAPHQL_MUTATION_COUNT_LIMIT", 3)+)# Set GRAPHQL_QUERY_MAX_COMPLEXITY=0 in env to disable (not recommended)GRAPHQL_QUERY_MAX_COMPLEXITY = int(