Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Merge pull request from GHSA-r8qr-wwg3-2r85
Marcin Gębala31bce881cccc
diff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.pyindex 919f3529fe..f2e9022a18 100644--- a/saleor/graphql/account/tests/test_account.py+++ b/saleor/graphql/account/tests/test_account.py@@ -5278,6 +5278,7 @@ REQUEST_PASSWORD_RESET_MUTATION = """errors {fieldmessage+ code}}}@@ -5516,12 +5517,10 @@ def test_account_reset_password_user_is_inactive("channel": channel_USD.slug,}response = user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)- results = response.json()- assert "errors" in results- assert (- results["errors"][0]["message"]- == "Invalid token. User does not exist or is inactive."- )+ content = get_graphql_content(response)+ data = content["data"]["requestPasswordReset"]+ assert len(data["errors"]) == 1+ assert data["errors"][0]["code"] == AccountErrorCode.JWT_INVALID_TOKEN.nameassert not mocked_notify.calleddiff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.pyindex 5d73aaefce..889c8736c8 100644--- a/saleor/graphql/core/mutations.py+++ b/saleor/graphql/core/mutations.py@@ -19,6 +19,7 @@ from typing import (from uuid import UUIDimport graphene+import jwtfrom django.core.exceptions import (NON_FIELD_ERRORS,ImproperlyConfigured,@@ -32,6 +33,7 @@ from graphene import ObjectTypefrom graphene.types.mutation import MutationOptionsfrom graphql.error import GraphQLError+from ...account.error_codes import AccountErrorCodefrom ...core.error_codes import MetadataErrorCodefrom ...core.exceptions import PermissionDeniedfrom ...core.utils.events import call_event@@ -502,7 +504,14 @@ class BaseMutation(graphene.Mutation):@classmethoddef mutate(cls, root, info: ResolveInfo, **data):disallow_replica_in_context(info.context)- setup_context_user(info.context)+ try:+ setup_context_user(info.context)+ except jwt.InvalidTokenError:+ return cls.handle_errors(+ ValidationError(+ "Invalid token", code=AccountErrorCode.JWT_INVALID_TOKEN.value+ )+ )if not cls.check_permissions(info.context, data=data):raise PermissionDenied(permissions=cls._meta.permissions)@@ -938,7 +947,14 @@ class BaseBulkMutation(BaseMutation):@classmethoddef mutate(cls, root, info: ResolveInfo, **data):disallow_replica_in_context(info.context)- setup_context_user(info.context)+ try:+ setup_context_user(info.context)+ except jwt.InvalidTokenError:+ return cls.handle_errors(+ ValidationError(+ "Invalid token", code=AccountErrorCode.JWT_INVALID_TOKEN.value+ )+ )if not cls.check_permissions(info.context):raise PermissionDenied(permissions=cls._meta.permissions)diff --git a/saleor/graphql/core/tests/test_view.py b/saleor/graphql/core/tests/test_view.pyindex 52735f32f4..6a72109983 100644--- a/saleor/graphql/core/tests/test_view.py+++ b/saleor/graphql/core/tests/test_view.py@@ -7,6 +7,7 @@ from graphql.execution.base import ExecutionResultfrom .... import __version__ as saleor_versionfrom ....demo.views import EXAMPLE_QUERY+from ....graphql.utils import INTERNAL_ERROR_MESSAGEfrom ...tests.fixtures import API_PATHfrom ...tests.utils import get_graphql_content, get_graphql_content_from_responsefrom ...views import generate_cache_key@@ -145,7 +146,7 @@ def test_graphql_execution_exception(monkeypatch, api_client):response = api_client.post_graphql("{ shop { name }}")assert response.status_code == 400content = get_graphql_content_from_response(response)- assert content["errors"][0]["message"] == "Spanish inquisition"+ assert content["errors"][0]["message"] == INTERNAL_ERROR_MESSAGEdef test_invalid_query_graphql_errors_are_logged_in_another_logger(diff --git a/saleor/graphql/tests/test_utils.py b/saleor/graphql/tests/test_utils.pyindex 50bdc9f24e..a43effcc6f 100644--- a/saleor/graphql/tests/test_utils.py+++ b/saleor/graphql/tests/test_utils.py@@ -1,7 +1,9 @@import re+from django.test import override_settingsfrom graphql.utils import schema_printer+from ..utils import ALLOWED_ERRORS, INTERNAL_ERROR_MESSAGE, format_errorfrom .utils import get_graphql_content@@ -25,3 +27,25 @@ def test_multiple_interface_separator_in_schema(api_client):def test_graphql_core_contains_patched_function():assert hasattr(schema_printer, "_print_object")+++@override_settings(DEBUG=False)+def test_format_error_hides_internal_error_msg_in_production_mode():+ error = ValueError("Example error")+ result = format_error(error, ())+ assert result["message"] == INTERNAL_ERROR_MESSAGE+++@override_settings(DEBUG=False)+def test_format_error_prints_allowed_errors():+ error_cls = ALLOWED_ERRORS[0]+ error = error_cls("Example error")+ result = format_error(error, ())+ assert result["message"] == str(error)+++@override_settings(DEBUG=True)+def test_format_error_prints_internal_error_msg_in_debug_mode():+ error = ValueError("Example error")+ result = format_error(error, ())+ assert result["message"] == str(error)diff --git a/saleor/graphql/utils/__init__.py b/saleor/graphql/utils/__init__.pyindex 5d93a39e84..a434a17299 100644--- a/saleor/graphql/utils/__init__.py+++ b/saleor/graphql/utils/__init__.py@@ -6,6 +6,7 @@ from uuid import UUIDimport graphenefrom django.conf import settings+from django.core.exceptions import ValidationErrorfrom django.db.models import Q, Valuefrom django.db.models.functions import Concatfrom graphql import GraphQLDocument@@ -14,9 +15,15 @@ from graphql.error import format_error as format_graphql_errorfrom ...account.models import Userfrom ...app.models import App+from ...core.exceptions import (+ CircularSubscriptionSyncEvent,+ PermissionDenied,+ ReadOnlyException,+)from ..core.enums import PermissionEnumfrom ..core.types import TYPES_WITH_DOUBLE_ID_AVAILABLE, Permissionfrom ..core.utils import from_global_id_or_error+from ..core.validators.query_cost import QueryCostErrorif TYPE_CHECKING:from ..core import SaleorContext@@ -33,6 +40,18 @@ REVERSED_DIRECTION = {"": "-",}+# List of error types of which messages can be returned in the GraphQL API.+ALLOWED_ERRORS = [+ CircularSubscriptionSyncEvent,+ GraphQLError,+ PermissionDenied,+ ReadOnlyException,+ ValidationError,+ QueryCostError,+]++INTERNAL_ERROR_MESSAGE = "Internal Server Error"+def resolve_global_ids_to_primary_keys(ids: Iterable[str], graphene_type=None, raise_error: bool = False@@ -268,6 +287,12 @@ def format_error(error, handled_exceptions):else:unhandled_errors_logger.error("A query failed unexpectedly", exc_info=exc)+ # If DEBUG mode is disabled we allow only certain error messages to be returned in+ # the API. This prevents from leaking internals that might be included in Python+ # exceptions' error messages.+ if type(exc) not in ALLOWED_ERRORS and not settings.DEBUG:+ result["message"] = INTERNAL_ERROR_MESSAGE+result["extensions"]["exception"] = {"code": type(exc).__name__}if settings.DEBUG:lines = []