Skip to content

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

Use separate scopes for tokens (#19430)

Mikailf2b628898f44
diff --git a/.semgrep/correctness/django/django-no-default-token-generator.yaml b/.semgrep/correctness/django/django-no-default-token-generator.yaml
index 3f432a10dc..494eab445c 100644
--- a/.semgrep/correctness/django/django-no-default-token-generator.yaml
+++ b/.semgrep/correctness/django/django-no-default-token-generator.yaml
@@ -3,18 +3,23 @@ rules:
# token generator classes (django.contrib.auth.tokens.*)
- id: django-no-default-token-generator
version: 1.0.0
- message: The default Django's token generator class shouldn't be used directly,
+ message: |
+ The default Django's token generator class shouldn't be used directly,
instead it should select it based on `settings.TOKEN_GENERATOR_CLASS`.
Replace `from django.contrib.auth.tokens import default_token_generator`
- by `from saleor.core.tokens import token_generator`
+ by `from saleor.core.tokens import XXX`
+
+ WARNING: make sure to create a new generator for your specific use-case.
+ The value for `key_salt` must not collide with another token
+ generator (e.g., a password reset token shouldn't be usable
+ to confirm an account).
metadata:
category: correctness
technology:
- - django
+ - django
languages:
- python
severity: ERROR
pattern: |
from django.contrib.auth.tokens import $X
- fix:
- from saleor.core.tokens import token_generator
+ fix: from saleor.core.tokens import XXX
diff --git a/saleor/account/notifications.py b/saleor/account/notifications.py
index f920428b7a..4de1094eb1 100644
--- a/saleor/account/notifications.py
+++ b/saleor/account/notifications.py
@@ -2,7 +2,11 @@ from urllib.parse import urlencode
from ..core.notification.utils import get_site_context
from ..core.notify import NotifyEventType, NotifyHandler
-from ..core.tokens import account_delete_token_generator, token_generator
+from ..core.tokens import (
+ account_confirm_token_generator,
+ account_delete_token_generator,
+ password_reset_token_generator,
+)
from ..core.utils.url import prepare_url
from ..graphql.core.utils import to_global_id_or_none
from .models import User
@@ -41,7 +45,7 @@ def send_password_reset_notification(
"""Trigger sending a password reset notification for the given customer/staff."""
def _generate_payload():
- token = token_generator.make_token(user)
+ token = password_reset_token_generator.make_token(user)
params = urlencode({"email": user.email, "token": token})
reset_url = prepare_url(params, redirect_url)
@@ -69,7 +73,7 @@ def send_account_confirmation(user, redirect_url, manager, channel_slug, token=N
def _generate_payload():
if not token:
- user_token = token_generator.make_token(user)
+ user_token = account_confirm_token_generator.make_token(user)
else:
user_token = token
@@ -179,12 +183,12 @@ def send_set_password_notification(
"""Trigger sending a set password notification for the given customer/staff."""
def _generate_payload():
- token = token_generator.make_token(user)
+ token = password_reset_token_generator.make_token(user)
params = urlencode({"email": user.email, "token": token})
password_set_url = prepare_url(params, redirect_url)
payload = {
"user": get_default_user_payload(user),
- "token": token_generator.make_token(user),
+ "token": password_reset_token_generator.make_token(user),
"recipient_email": user.email,
"password_set_url": password_set_url,
"channel_slug": channel_slug,
diff --git a/saleor/account/tasks.py b/saleor/account/tasks.py
index dc83060cbc..2f62fffe8b 100644
--- a/saleor/account/tasks.py
+++ b/saleor/account/tasks.py
@@ -6,7 +6,10 @@ from django.utils import timezone
from ..celeryconf import app
from ..core.db.connection import allow_writer
-from ..core.tokens import token_generator
+from ..core.tokens import (
+ account_confirm_token_generator,
+ password_reset_token_generator,
+)
from ..core.utils.events import call_event
from ..core.utils.url import prepare_url
from ..graphql.plugins.dataloaders import get_plugin_manager_promise
@@ -54,7 +57,7 @@ def trigger_send_password_reset_notification(
staff=user.is_staff,
)
- token = token_generator.make_token(user)
+ token = password_reset_token_generator.make_token(user)
redirect_params = _prepare_redirect_url(user, redirect_url, token)
if user.is_staff:
@@ -95,7 +98,7 @@ def finish_creating_user(user_pk, redirect_url, channel_slug, context_data):
if site.settings.enable_account_confirmation_by_email:
# Notifications will be deprecated in the future
- token = token_generator.make_token(user)
+ token = account_confirm_token_generator.make_token(user)
notifications.send_account_confirmation(
user=user,
redirect_url=redirect_url,
diff --git a/saleor/account/tests/test_notifications.py b/saleor/account/tests/test_notifications.py
index c1052439e5..c13b282bb0 100644
--- a/saleor/account/tests/test_notifications.py
+++ b/saleor/account/tests/test_notifications.py
@@ -104,7 +104,7 @@ def test_send_email_changed_notification(
@pytest.mark.parametrize("is_staff", [True, False])
[email protected]("saleor.account.notifications.token_generator.make_token")
[email protected]("saleor.account.notifications.password_reset_token_generator.make_token")
@mock.patch("saleor.plugins.manager.PluginsManager.notify")
def test_send_password_reset_notification(
mocked_notify, mocked_generator, is_staff, site_settings, customer_user, channel_PLN
diff --git a/saleor/core/tokens.py b/saleor/core/tokens.py
index e68c724290..8b65239104 100644
--- a/saleor/core/tokens.py
+++ b/saleor/core/tokens.py
@@ -1,10 +1,37 @@
from django.conf import settings
+
+# nosemgrep: django-no-default-token-generator # _DjangoGenerator is used safely
+from django.contrib.auth.tokens import PasswordResetTokenGenerator as _DjangoGenerator
from django.utils.module_loading import import_string
-token_generator_cls = import_string(settings.TOKEN_GENERATOR_CLASS)
+from saleor.account.models import User
+
+_base_token_generator_cls = import_string(settings.TOKEN_GENERATOR_CLASS)
+
+LEGACY_SALT = _base_token_generator_cls.key_salt
+
+
+class BaseTokenGenerator(_base_token_generator_cls): # type: ignore[valid-type,misc]
+ def __init__(self, *, key_salt: str):
+ """Initialize a token generator.
+
+ Args:
+ key_salt:
+ A custom salt to support.
+
+ This overrides Django's default salt [1] which allows us to create
+ different scopes for generated tokens (i.e., token from generator A
+ cannot be used in generator B).
+
+ [1]: https://github.com/django/django/blob/73dd0169a54f4bbcb41b29bf7d51a36f86c89afe/django/contrib/auth/tokens.py#L14
+ """
-class AccountDeleteTokenGenerator(token_generator_cls): # type: ignore[valid-type,misc]
+ self.key_salt = key_salt
+ super().__init__()
+
+
+class AccountDeleteTokenGenerator(BaseTokenGenerator):
def _make_hash_value(self, user, timestamp):
# Override this method to remove the user `last_login` value from the hash.
# As this token is used for deleting the user, so there is no worry
@@ -14,5 +41,44 @@ class AccountDeleteTokenGenerator(token_generator_cls): # type: ignore[valid-ty
return f"{user.pk}{user.password}{timestamp}{email}"
-account_delete_token_generator = AccountDeleteTokenGenerator()
-token_generator = token_generator_cls()
+def try_generators(
+ *,
+ current_generator: _DjangoGenerator,
+ fallback_generator: _DjangoGenerator,
+ user: User,
+ token: str,
+) -> bool:
+ """Try generators with different salts to ensure old tokens work.
+
+ Args:
+ current_generator: the generator with the current salt, will be tried first.
+ fallback_generator:
+ the legacy/old generator to try if `current_generator` rejects the token.
+ user: the user who is attempting to use the token.
+ token: the token to compare against.
+
+ """
+ if current_generator.check_token(user, token) is True:
+ return True
+ return fallback_generator.check_token(user, token)
+
+
+# Account delete
+account_delete_token_generator = AccountDeleteTokenGenerator(
+ key_salt=f"{__name__}.account_delete_token_generator"
+)
+legacy_account_delete_token_generator = AccountDeleteTokenGenerator(
+ key_salt=LEGACY_SALT
+)
+
+# Password reset
+password_reset_token_generator = BaseTokenGenerator(
+ key_salt=f"{__name__}.password_reset_token_generator"
+)
+legacy_password_reset_token_generator = BaseTokenGenerator(key_salt=LEGACY_SALT)
+
+# Account confirmation
+account_confirm_token_generator = BaseTokenGenerator(
+ key_salt=f"{__name__}.account_confirm_token_generator"
+)
+legacy_account_confirm_token_generator = BaseTokenGenerator(key_salt=LEGACY_SALT)
diff --git a/saleor/graphql/account/mutations/account/account_delete.py b/saleor/graphql/account/mutations/account/account_delete.py
index 7ccb772efc..bd332fc6b8 100644
--- a/saleor/graphql/account/mutations/account/account_delete.py
+++ b/saleor/graphql/account/mutations/account/account_delete.py
@@ -5,7 +5,11 @@ from django.core.exceptions import ValidationError
from .....account import models
from .....account.error_codes import AccountErrorCode
-from .....core.tokens import account_delete_token_generator
+from .....core.tokens import (
+ account_delete_token_generator,
+ legacy_account_delete_token_generator,
+ try_generators,
+)
from .....permission.auth_filters import AuthorizationFilters
from .....webhook.event_types import WebhookEventAsyncType
from ....core import ResolveInfo
@@ -60,7 +64,14 @@ class AccountDelete(ModelDeleteMutation):
user = cast(models.User, user)
cls.clean_instance(info, user)
- if not account_delete_token_generator.check_token(user, token):
+ valid_token = try_generators(
+ current_generator=account_delete_token_generator,
+ fallback_generator=legacy_account_delete_token_generator,
+ user=user,
+ token=token,
+ )
+
+ if not valid_token:
raise ValidationError(
{
"token": ValidationError(
diff --git a/saleor/graphql/account/mutations/account/confirm_account.py b/saleor/graphql/account/mutations/account/confirm_account.py
index 95cb19c22d..ac8af4969e 100644
--- a/saleor/graphql/account/mutations/account/confirm_account.py
+++ b/saleor/graphql/account/mutations/account/confirm_account.py
@@ -3,7 +3,11 @@ from django.core.exceptions import ObjectDoesNotExist, ValidationError
from .....account import models
from .....account.error_codes import AccountErrorCode
-from .....core.tokens import token_generator
+from .....core.tokens import (
+ account_confirm_token_generator,
+ legacy_account_confirm_token_generator,
+ try_generators,
+)
from .....giftcard.utils import assign_user_gift_cards
from .....order.utils import match_orders_with_new_user
from .....webhook.event_types import WebhookEventAsyncType
@@ -56,7 +60,12 @@ class ConfirmAccount(BaseMutation):
error = True
user = models.User()
- valid_token = token_generator.check_token(user, data["token"])
+ valid_token = try_generators(
+ current_generator=account_confirm_token_generator,
+ fallback_generator=legacy_account_confirm_token_generator,
+ user=user,
+ token=data["token"],
+ )
if not valid_token or error:
raise ValidationError(
{
diff --git a/saleor/graphql/account/mutations/account/send_confirmation_email.py b/saleor/graphql/account/mutations/account/send_confirmation_email.py
index 8eb20c05db..d38e829658 100644
--- a/saleor/graphql/account/mutations/account/send_confirmation_email.py
+++ b/saleor/graphql/account/mutations/account/send_confirmation_email.py
@@ -9,7 +9,7 @@ from django.utils import timezone
from .....account import models
from .....account.error_codes import SendConfirmationEmailErrorCode
from .....account.notifications import send_account_confirmation
-from .....core.tokens import token_generator
+from .....core.tokens import account_confirm_token_generator
from .....core.utils.url import prepare_url, validate_storefront_url
from .....permission.auth_filters import AuthorizationFilters
from .....webhook.event_types import WebhookEventAsyncType
@@ -100,7 +100,7 @@ class SendConfirmationEmail(BaseMutation):
allow_replica=False,
).slug
manager = get_plugin_manager_promise(info.context).get()
- token = token_generator.make_token(user)
+ token = account_confirm_token_generator.make_token(user)
send_account_confirmation(
user,
diff --git a/saleor/graphql/account/mutations/authentication/set_password.py b/saleor/graphql/account/mutations/authentication/set_password.py
index 4467fa9eb0..d07e496d68 100644
--- a/saleor/graphql/account/mutations/authentication/set_password.py
+++ b/saleor/graphql/account/mutations/authentication/set_password.py
@@ -6,7 +6,11 @@ from .....account import events as account_events
from .....account import models
from .....account.error_codes import AccountErrorCode
from .....core.db.connection import allow_writer
-from .....core.tokens import token_generator
+from .....core.tokens import (
+ legacy_password_reset_token_generator,
+ password_reset_token_generator,
+ try_generators,
+)
from .....order.utils import match_orders_with_new_user
from ....core import ResolveInfo
from ....core.context import disallow_replica_in_context
@@ -63,7 +67,12 @@ class SetPassword(CreateToken):
error = True
user = models.User()
- valid_token = token_generator.check_token(user, token)
+ valid_token = try_generators(
+ current_generator=password_reset_token_generator,
+ fallback_generator=legacy_password_reset_token_generator,
+ user=user,
+ token=token,
+ )
if not valid_token or error:
raise ValidationError(
{
diff --git a/saleor/graphql/account/mutations/staff/customer_create.py b/saleor/graphql/account/mutations/staff/customer_create.py
index cc83362d6c..db5c91fc29 100644
--- a/saleor/graphql/account/mutations/staff/customer_create.py
+++ b/saleor/graphql/account/mutations/staff/customer_create.py
@@ -7,7 +7,7 @@ from .....account import events as account_events
from .....account import models
from .....account.notifications import send_set_password_notification
from .....account.search import update_user_search_vector
-from .....core.tokens import token_generator
+from .....core.tokens import password_reset_token_generator
from .....core.tracing import traced_atomic_transaction
from .....core.utils.url import prepare_url
from .....permission.enums import AccountPermissions
@@ -162,7 +162,7 @@ class CustomerCreate(BaseCustomerCreate):
plugins_manager,
channel_slug,
)
- token = token_generator.make_token(instance)
+ token = password_reset_token_generator.make_token(instance)
params = urlencode({"email": instance.email, "token": token})
cls.call_event(
diff --git a/saleor/graphql/account/mutations/staff/staff_create.py b/saleor/graphql/account/mutations/staff/staff_create.py
index 9a8fc0bfcf..278d2cd821 100644
--- a/saleor/graphql/account/mutations/staff/staff_create.py
+++ b/saleor/graphql/account/mutations/staff/staff_create.py
@@ -10,7 +10,7 @@ from .....account.error_codes import AccountErrorCode
from .....account.notifications import send_set_password_notification
from .....account.search import USER_SEARCH_FIELDS, update_user_search_vector
from .....core.exceptions import PermissionDenied
-from .....core.tokens import token_generator
+from .....core.tokens import password_reset_token_generator
from .....core.tracing import traced_atomic_transaction
from .....core.utils.url import prepare_url, validate_storefront_url
from .....permission.enums import AccountPermissions
@@ -182,7 +182,7 @@ class StaffCreate(DeprecatedModelMutation):
channel_slug=None,
staff=True,
)
- token = token_generator.make_token(user)
+ token = password_reset_token_generator.make_token(user)
params = urlencode({"email": user.email, "token": token})
cls.call_event(
manager.staff_set_password_requested,
diff --git a/saleor/graphql/account/tests/mutations/account/test_account_delete.py b/saleor/graphql/account/tests/mutations/account/test_account_delete.py
index 9d591bb6f9..d4b43ee254 100644
--- a/saleor/graphql/account/tests/mutations/account/test_account_delete.py
+++ b/saleor/graphql/account/tests/mutations/account/test_account_delete.py
@@ -6,7 +6,11 @@ from django.utils import timezone
from freezegun import freeze_time
from ......account.models import User
-from ......core.tokens import account_delete_token_generator
+from ......core.tokens import (
+ account_delete_token_generator,
+ legacy_account_delete_token_generator,
+ password_reset_token_generator,
+)
from ......thumbnail.models import Thumbnail
from .....tests.utils import assert_no_permission, get_graphql_content
@@ -109,6 +113,58 @@ def test_account_delete_invalid_token(user_api_client):
assert User.objects.filter(pk=user.id).exists()
+def test_account_delete_rejects_token_for_other_mutation(user_api_client):
+ """When providing a token that's meant for another mutation, it should reject.
+
+ In this test, we pass a password reset token instead of an account deletion
+ token, and we test whether it rejects it properly.
+ """
+
+ user = user_api_client.user
+ invalid_token = password_reset_token_generator.make_token(user)
+ variables = {"token": invalid_token}
+
+ # Should reject the token
+ content = get_graphql_content(
+ user_api_client.post_graphql(ACCOUNT_DELETE_MUTATION, variables)
+ )
+ data = content["data"]["accountDelete"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "token"
+ assert data["errors"][0]["message"] == "Invalid or expired token."
+ assert User.objects.filter(pk=user.id).exists(), (
+ "shouldn't have deleted the account"
+ )
+
+ # Sanity check: should accept an account deletion token
+ valid_token = account_delete_token_generator.make_token(user)
+ variables["token"] = valid_token
+ content = get_graphql_content(
+ user_api_client.post_graphql(ACCOUNT_DELETE_MUTATION, variables)
+ )
+ data = content["data"]["accountDelete"]
+ assert not data["errors"]
+ assert not User.objects.filter(pk=user.id).exists()
+
+
+def test_account_delete_accepts_legacy_account_delete_token(user_api_client):
+ """Ensure old tokens before adding scopes still work properly."""
+
+ # given
+ user = user_api_client.user
+ token = legacy_account_delete_token_generator.make_token(user)
+ variables = {"token": token}
+
+ # when
+ response = user_api_client.post_graphql(ACCOUNT_DELETE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["accountDelete"]
+ assert not data["errors"]
+ assert not User.objects.filter(pk=user.id).exists()
+
+
def test_account_delete_anonymous_user(api_client):
variables = {"token": "invalid"}
diff --git a/saleor/graphql/account/tests/mutations/account/test_account_register.py b/saleor/graphql/account/tests/mutations/account/test_account_register.py
index b7914f31e2..1c6ffa8b87 100644
--- a/saleor/graphql/account/tests/mutations/account/test_account_register.py
+++ b/saleor/graphql/account/tests/mutations/account/test_account_register.py
@@ -12,7 +12,7 @@ from ......account.notifications import get_default_user_payload
from ......account.tasks import finish_creating_user
from ......core.notify import NotifyEventType
from ......core.tests.utils import get_site_context_payload
-from ......core.tokens import token_generator
+from ......core.tokens import account_confirm_token_generator
from ......core.utils.url import prepare_url
from ......settings import AUTH_PASSWORD_VALIDATORS
from ......tests import race_condition
@@ -100,7 +100,7 @@ mutation RegisterAccount($input: AccountRegisterInput!) {
@override_settings(
ENABLE_ACCOUNT_CONFIRMATION_BY_EMAIL=True, ALLOWED_CLIENT_HOSTS=["localhost"]
)
-@patch("saleor.account.notifications.token_generator.make_token")
+@patch("saleor.account.notifications.account_confirm_token_generator.make_token")
@patch("saleor.plugins.manager.PluginsManager.notify")
@patch(
"saleor.graphql.account.mutations.account.account_register.finish_creating_user",
@@ -178,7 +178,7 @@ def test_customer_register(
@override_settings(
ENABLE_ACCOUNT_CONFIRMATION_BY_EMAIL=True, ALLOWED_CLIENT_HOSTS=["localhost"]
)
-@patch("saleor.account.notifications.token_generator.make_token")
+@patch("saleor.account.notifications.account_confirm_token_generator.make_token")
@patch("saleor.plugins.manager.PluginsManager.notify")
@patch(
"saleor.graphql.account.mutations.account.account_register.finish_creating_user",
@@ -327,7 +327,7 @@ def test_customer_register_generates_valid_token(
assert called_kwargs["channel_slug"] == channel_PLN.slug
assert not data["errors"]
- assert token_generator.check_token(new_user, token)
+ assert account_confirm_token_generator.check_token(new_user, token)
@patch("saleor.plugins.manager.PluginsManager.notify")
@@ -480,7 +480,7 @@ def test_account_register_returns_empty_id(
@override_settings(
ENABLE_ACCOUNT_CONFIRMATION_BY_EMAIL=True, ALLOWED_CLIENT_HOSTS=["localhost"]
)
-@patch("saleor.account.notifications.token_generator.make_token")
+@patch("saleor.account.notifications.account_confirm_token_generator.make_token")
@patch("saleor.plugins.manager.PluginsManager.notify")
@patch(
"saleor.graphql.account.mutations.account.account_register.finish_creating_user",
diff --git a/saleor/graphql/account/tests/mutations/account/test_confirm_account.py b/saleor/graphql/account/tests/mutations/account/test_confirm_account.py
index f7d312fae5..bce4564a78 100644
--- a/saleor/graphql/account/tests/mutations/account/test_confirm_account.py
+++ b/saleor/graphql/account/tests/mutations/account/test_confirm_account.py
@@ -3,7 +3,11 @@ from unittest.mock import patch
from freezegun import freeze_time
from ......account.error_codes import AccountErrorCode
-from ......core.tokens import token_generator
+from ......core.tokens import (
+ account_confirm_token_generator,
+ legacy_account_confirm_token_generator,
+ password_reset_token_generator,
+)
from .....tests.utils import get_graphql_content
CONFIRM_ACCOUNT_MUTATION = """
@@ -43,7 +47,7 @@ def test_account_confirmation(
variables = {
"email": customer_user.email,
- "token": token_generator.make_token(customer_user),
+ "token": account_confirm_token_generator.make_token(customer_user),
"channel": channel_USD.slug,
}
response = api_client.post_graphql(CONFIRM_ACCOUNT_MUTATION, variables)
@@ -73,7 +77,7 @@ def test_account_confirmation_invalid_user(
):
variables = {
"email": "[email protected]",
- "token": token_generator.make_token(customer_user),
+ "token": account_confirm_token_generator.make_token(customer_user),
"channel": channel_USD.slug,
}
response = user_api_client.post_graphql(CONFIRM_ACCOUNT_MUTATION, variables)
@@ -114,3 +118,108 @@ def test_account_confirmation_invalid_token(
)
match_orders_with_new_user_mock.assert_not_called()
assign_gift_cards_mock.assert_not_called()
+
+
+@patch(
+ "saleor.graphql.account.mutations.account.confirm_account.assign_user_gift_cards"
+)
+@patch(
+ "saleor.graphql.account.mutations.account.confirm_account.match_orders_with_new_user"
+)
+@patch("saleor.plugins.manager.PluginsManager.account_confirmed")
+def test_account_confirmation_rejects_token_for_wrong_scope(
+ mocked_account_confirmed,
+ match_orders_with_new_user_mock,
+ assign_gift_cards_mock,
+ user_api_client,
+ customer_user,
+):
+ """When providing a token that's meant for another mutation, it should reject.
+
+ In this test, we pass a password reset token instead of an account confirmation
+ token, and we test whether it rejects it properly.
+ """
+
+ customer_user.is_confirmed = False
+ customer_user.save(update_fields=["is_confirmed"])
+
+ # Create token for the wrong mutation
+ invalid_token = password_reset_token_generator.make_token(customer_user)
+ variables = {
+ "email": customer_user.email,
+ "token": invalid_token,
+ }
+
+ # Should reject the token
+ content = get_graphql_content(
+ user_api_client.post_graphql(CONFIRM_ACCOUNT_MUTATION, variables)
+ )
+ data = content["data"]["confirmAccount"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "token"
+ assert data["errors"][0]["code"] == AccountErrorCode.INVALID.name
+
+ # Shouldn't have confirmed the account nor merged the account
+ customer_user.refresh_from_db(fields=("is_confirmed",))
+ assert customer_user.is_confirmed is False
+ match_orders_with_new_user_mock.assert_not_called()
+ assign_gift_cards_mock.assert_not_called()
+ mocked_account_confirmed.assert_not_called()
+
+ # Sanity check: a valid token should work properly
+ valid_token = account_confirm_token_generator.make_token(customer_user)
+ variables["token"] = valid_token
+ content = get_graphql_content(
+ user_api_client.post_graphql(CONFIRM_ACCOUNT_MUTATION, variables)
+ )
+ data = content["data"]["confirmAccount"]
+ assert not data["errors"]
+
+ # Should have merged the account & confirmed the account
+ customer_user.refresh_from_db(fields=("is_confirmed",))
+ assert customer_user.is_confirmed is True
+ match_orders_with_new_user_mock.assert_called_once_with(customer_user)
+ assign_gift_cards_mock.assert_called_once_with(customer_user)
+ mocked_account_confirmed.assert_called_once_with(customer_user)
+
+
+@patch(
+ "saleor.graphql.account.mutations.account.confirm_account.assign_user_gift_cards"
+)
+@patch(
+ "saleor.graphql.account.mutations.account.confirm_account.match_orders_with_new_user"
+)
+@patch("saleor.plugins.manager.PluginsManager.account_confirmed")
+def test_account_confirmation_accepts_legacy_account_confirm_token(
+ mocked_account_confirmed,
+ match_orders_with_new_user_mock,
+ assign_gift_cards_mock,
+ user_api_client,
+ customer_user,
+):
+ """Ensure old tokens before adding scopes still work properly."""
+
+ # given
+ customer_user.is_confirmed = False
+ customer_user.save(update_fields=["is_confirmed"])
+ token = legacy_account_confirm_token_generator.make_token(customer_user)
+ variables = {
+ "email": customer_user.email,
+ "token": token,
+ }
+
+ # when
+ response = user_api_client.post_graphql(CONFIRM_ACCOUNT_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["confirmAccount"]
+ assert not data["errors"]
+ assert data["user"]["email"] == customer_user.email
+ customer_user.refresh_from_db(fields=("is_confirmed",))
+
+ # Should have properly confirmed the account
+ assert customer_user.is_confirmed is True
+ match_orders_with_new_user_mock.assert_called_once_with(customer_user)
+ assign_gift_cards_mock.assert_called_once_with(customer_user)
+ mocked_account_confirmed.assert_called_once_with(customer_user)
diff --git a/saleor/graphql/account/tests/mutations/account/test_send_confirmation_email.py b/saleor/graphql/account/tests/mutations/account/test_send_confirmation_email.py
index 626e07f30b..2cfcb01f03 100644
--- a/saleor/graphql/account/tests/mutations/account/test_send_confirmation_email.py
+++ b/saleor/graphql/account/tests/mutations/account/test_send_confirmation_email.py
@@ -10,7 +10,7 @@ from ......account.error_codes import SendConfirmationEmailErrorCode
from ......account.notifications import get_default_user_payload
from ......core.notify import NotifyEventType
from ......core.tests.utils import get_site_context_payload
-from ......core.tokens import token_generator
+from ......core.tokens import account_confirm_token_generator
from ......core.utils.url import prepare_url
from .....tests.utils import get_graphql_content
@@ -55,7 +55,7 @@ def test_send_confirmation_email(
data = content["data"]["sendConfirmationEmail"]
assert not data["errors"]
- token = token_generator.make_token(user)
+ token = account_confirm_token_generator.make_token(user)
params = urlencode({"email": user.email, "token": token})
confirm_url = prepare_url(params, redirect_url)
expected_payload = {
@@ -226,4 +226,4 @@ def test_send_confirmation_email_generates_valid_token(
token = called_kwargs["payload_func"]()["token"]
user.refresh_from_db()
- assert token_generator.check_token(user, token)
+ assert account_confirm_token_generator.check_token(user, token)
diff --git a/saleor/graphql/account/tests/mutations/authentication/test_request_password_reset.py b/saleor/graphql/account/tests/mutations/authentication/test_request_password_reset.py
index d6c82cd78a..11de791ca5 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_request_password_reset.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_request_password_reset.py
@@ -10,7 +10,7 @@ from ......account.error_codes import AccountErrorCode
from ......account.notifications import get_default_user_payload
from ......core.notify import NotifyEventType
from ......core.tests.utils import get_site_context_payload
-from ......core.tokens import token_generator
+from ......core.tokens import password_reset_token_generator
from ......core.utils.url import prepare_url
from ......site import PasswordLoginMode
from .....tests.utils import get_graphql_content
@@ -57,7 +57,7 @@ def test_account_reset_password(
# then
data = content["data"]["requestPasswordReset"]
assert not data["errors"]
- token = token_generator.make_token(customer_user)
+ token = password_reset_token_generator.make_token(customer_user)
params = urlencode({"email": customer_user.email, "token": token})
reset_url = prepare_url(params, redirect_url)
expected_payload = {
@@ -162,7 +162,7 @@ def test_account_reset_password_with_upper_case_email(
# then
data = content["data"]["requestPasswordReset"]
assert not data["errors"]
- token = token_generator.make_token(customer_user)
+ token = password_reset_token_generator.make_token(customer_user)
params = urlencode({"email": customer_user.email, "token": token})
reset_url = prepare_url(params, redirect_url)
expected_payload = {
@@ -209,7 +209,7 @@ def test_request_password_reset_email_for_staff(
# then
data = content["data"]["requestPasswordReset"]
assert not data["errors"]
- token = token_generator.make_token(user)
+ token = password_reset_token_generator.make_token(user)
params = urlencode({"email": user.email, "token": token})
reset_url = prepare_url(params, redirect_url)
expected_payload = {
@@ -325,7 +325,7 @@ def test_account_reset_password_all_storefront_hosts_allowed(
data = content["data"]["requestPasswordReset"]
assert not data["errors"]
- token = token_generator.make_token(customer_user)
+ token = password_reset_token_generator.make_token(customer_user)
params = urlencode({"email": customer_user.email, "token": token})
reset_url = prepare_url(params, redirect_url)
expected_payload = {
@@ -368,7 +368,7 @@ def test_account_reset_password_subdomain(
data = content["data"]["requestPasswordReset"]
assert not data["errors"]
- token = token_generator.make_token(customer_user)
+ token = password_reset_token_generator.make_token(customer_user)
params = urlencode({"email": customer_user.email, "token": token})
reset_url = prepare_url(params, redirect_url)
expected_payload = {
@@ -446,7 +446,7 @@ def test_account_reset_password_for_not_confirmed_user(
content = get_graphql_content(response)
data = content["data"]["requestPasswordReset"]
assert not data["errors"]
- token = token_generator.make_token(customer_user)
+ token = password_reset_token_generator.make_token(customer_user)
params = urlencode({"email": customer_user.email, "token": token})
reset_url = prepare_url(params, redirect_url)
expected_payload = {
@@ -504,7 +504,7 @@ def test_account_reset_password_no_channel_provided_multiple_channels(
# then
data = content["data"]["requestPasswordReset"]
assert not data["errors"]
- token = token_generator.make_token(customer_user)
+ token = password_reset_token_generator.make_token(customer_user)
params = urlencode({"email": customer_user.email, "token": token})
reset_url = prepare_url(params, redirect_url)
expected_payload = {
@@ -568,7 +568,7 @@ def test_account_reset_password_no_channel_provided_one_channel(
# then
data = content["data"]["requestPasswordReset"]
assert not data["errors"]
- token = token_generator.make_token(customer_user)
+ token = password_reset_token_generator.make_token(customer_user)
params = urlencode({"email": customer_user.email, "token": token})
reset_url = prepare_url(params, redirect_url)
expected_payload = {
diff --git a/saleor/graphql/account/tests/mutations/authentication/test_set_password.py b/saleor/graphql/account/tests/mutations/authentication/test_set_password.py
index e89b0bf454..481c4f7212 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_set_password.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_set_password.py
@@ -5,7 +5,11 @@ from freezegun import freeze_time
from ......account import events as account_events
from ......account.error_codes import AccountErrorCode
from ......account.tests.fixtures.user import dangerously_create_test_user
-from ......core.tokens import token_generator
+from ......core.tokens import (
+ account_confirm_token_generator,
+ legacy_password_reset_token_generator,
+ password_reset_token_generator,
+)
from ......site import PasswordLoginMode
from .....core.utils import str_to_enum
from .....tests.utils import get_graphql_content
@@ -42,7 +46,7 @@ def test_set_password(mocked_cache, user_api_client, setup_mock_for_cache):
customer_user = dangerously_create_test_user(
email="[email protected]", password="old-password"
)
- token = token_generator.make_token(customer_user)
+ token = password_reset_token_generator.make_token(customer_user)
password = "spanish-inquisition"
variables = {"email": customer_user.email, "password": password, "token": token}
@@ -81,7 +85,7 @@ def test_set_password_confirm_user_and_match_orders(
is_confirmed=False,
)
- token = token_generator.make_token(customer_user)
+ token = password_reset_token_generator.make_token(customer_user)
password = "spanish-inquisition"
variables = {"email": customer_user.email, "password": password, "token": token}
@@ -126,6 +130,83 @@ def test_set_password_invalid_token(
assert account_errors[0]["code"] == AccountErrorCode.INVALID.name
+@patch("saleor.account.throttling.cache")
+def test_set_password_rejects_account_confirm_token(
+ mocked_cache, user_api_client, customer_user, setup_mock_for_cache
+):
+ """When providing a token that's meant for another mutation, it should reject.
+
+ In this test, we pass an account confirmation token instead of a password reset
+ token, and we test whether it rejects it properly.
+ """
+
+ setup_mock_for_cache({}, mocked_cache)
+
+ new_password = "new-password"
+ assert not customer_user.check_password(new_password)
+
+ variables = {
+ "email": customer_user.email,
+ "password": new_password,
+ }
+
+ # Should reject invalid token
+ invalid_token = account_confirm_token_generator.make_token(customer_user)
+ content = get_graphql_content(
+ user_api_client.post_graphql(
+ SET_PASSWORD_MUTATION, {**variables, "token": invalid_token}
+ )
+ )
+ data = content["data"]["setPassword"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["message"] == INVALID_TOKEN
+ assert data["errors"][0]["code"] == AccountErrorCode.INVALID.name
+ customer_user.refresh_from_db()
+ assert not customer_user.check_password(new_password)
+
+ # Sanity check: should accept valid tokens
+ valid_token = password_reset_token_generator.make_token(customer_user)
+ variables["token"] = valid_token
+ content = get_graphql_content(
+ user_api_client.post_graphql(
+ SET_PASSWORD_MUTATION, {**variables, "token": valid_token}
+ )
+ )
+ data = content["data"]["setPassword"]
+ assert not data["errors"]
+ customer_user.refresh_from_db()
+ assert customer_user.check_password(new_password)
+
+
+@patch("saleor.account.throttling.cache")
+def test_set_password_accepts_legacy_password_reset_token(
+ mocked_cache, user_api_client, customer_user, setup_mock_for_cache
+):
+ """Ensure old tokens before adding scopes still work properly."""
+
+ # given
+ setup_mock_for_cache({}, mocked_cache)
+ password = "new-password"
+ token = legacy_password_reset_token_generator.make_token(customer_user)
+ variables = {
+ "email": customer_user.email,
+ "password": password,
+ "token": token,
+ }
+
+ # when
+ response = user_api_client.post_graphql(SET_PASSWORD_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["setPassword"]
+ assert not data["errors"]
+ assert data["user"]["id"]
+ assert data["token"]
+ customer_user.refresh_from_db()
+ assert customer_user.check_password(password)
+
+
@patch("saleor.account.throttling.cache")
def test_set_password_invalid_email(
mocked_cache, user_api_client, setup_mock_for_cache
@@ -165,7 +246,7 @@ def test_set_password_invalid_password(
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]
- token = token_generator.make_token(customer_user)
+ token = password_reset_token_generator.make_token(customer_user)
variables = {"email": customer_user.email, "password": "1234", "token": token}
# when
@@ -195,7 +276,7 @@ def test_set_password_disabled_password_login(user_api_client, site_settings):
customer_user = dangerously_create_test_user(
email="[email protected]", password="old-password"
)
- token = token_generator.make_token(customer_user)
+ token = password_reset_token_generator.make_token(customer_user)
variables = {
"email": customer_user.email,
"password": "new-password",
diff --git a/saleor/graphql/account/tests/mutations/staff/test_customer_create.py b/saleor/graphql/account/tests/mutations/staff/test_customer_create.py
index cbfe9bf8f5..9007fc4dc0 100644
--- a/saleor/graphql/account/tests/mutations/staff/test_customer_create.py
+++ b/saleor/graphql/account/tests/mutations/staff/test_customer_create.py
@@ -81,7 +81,7 @@ CUSTOMER_CREATE_MUTATION = """
@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")
-@patch("saleor.account.notifications.token_generator.make_token")
+@patch("saleor.account.notifications.password_reset_token_generator.make_token")
@patch("saleor.plugins.manager.PluginsManager.notify")
@patch("saleor.plugins.manager.PluginsManager.account_set_password_requested")
def test_customer_create(
@@ -196,7 +196,7 @@ def test_customer_create(
@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")
-@patch("saleor.account.notifications.token_generator.make_token")
+@patch("saleor.account.notifications.password_reset_token_generator.make_token")
@patch("saleor.plugins.manager.PluginsManager.notify")
@patch("saleor.plugins.manager.PluginsManager.account_set_password_requested")
def test_customer_create_as_app(
@@ -315,7 +315,7 @@ def test_customer_create_as_app(
)
-@patch("saleor.account.notifications.token_generator.make_token")
+@patch("saleor.account.notifications.password_reset_token_generator.make_token")
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_customer_create_send_password_with_url(
mocked_notify,
@@ -503,7 +503,7 @@ def test_customer_create_with_non_unique_external_reference(
assert error["message"] == "User with this External reference already exists."
-@patch("saleor.account.notifications.token_generator.make_token")
+@patch("saleor.account.notifications.password_reset_token_generator.make_token")
@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
def test_customer_create_webhook_event_triggered(
mocked_trigger_webhooks_async,
diff --git a/saleor/graphql/account/tests/mutations/staff/test_staff_create.py b/saleor/graphql/account/tests/mutations/staff/test_staff_create.py
index 01e2412805..74fd0c8744 100644
--- a/saleor/graphql/account/tests/mutations/staff/test_staff_create.py
+++ b/saleor/graphql/account/tests/mutations/staff/test_staff_create.py
@@ -11,7 +11,7 @@ from ......account.models import Group, User
from ......account.notifications import get_default_user_payload
from ......core.notify import NotifyEventType
from ......core.tests.utils import get_site_context_payload
-from ......core.tokens import token_generator
+from ......core.tokens import password_reset_token_generator
from ......core.utils.json_serializer import CustomJsonEncoder
from ......core.utils.url import prepare_url
from ......webhook.event_types import WebhookEventAsyncType
@@ -121,7 +121,7 @@ def test_staff_create(
assert len(groups) == 1
assert {perm["code"].lower() for perm in groups[0]["permissions"]} == expected_perms
- token = token_generator.make_token(staff_user)
+ token = password_reset_token_generator.make_token(staff_user)
params = urlencode({"email": email, "token": token})
password_set_url = prepare_url(params, redirect_url)
expected_payload = {
@@ -375,7 +375,7 @@ def test_staff_create_out_of_scope_group(
assert len(groups) == 2
for group in expected_groups:
assert group in groups
- token = token_generator.make_token(staff_user)
+ token = password_reset_token_generator.make_token(staff_user)
params = urlencode({"email": email, "token": token})
password_set_url = prepare_url(params, redirect_url)
expected_payload = {
@@ -416,7 +416,7 @@ def test_staff_create_send_password_with_url(
staff_user = User.objects.get(email=email)
assert staff_user.is_staff
- token = token_generator.make_token(staff_user)
+ token = password_reset_token_generator.make_token(staff_user)
params = urlencode({"email": email, "token": token})
password_set_url = prepare_url(params, redirect_url)
expected_payload = {
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index 4d0273050a..782f87f686 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -28,7 +28,7 @@ from ....core import EventDeliveryStatus
from ....core.models import EventDelivery, EventDeliveryAttempt, EventPayload
from ....core.notification.utils import get_site_context
from ....core.notify import NotifyEventType
-from ....core.tokens import token_generator
+from ....core.tokens import account_confirm_token_generator
from ....core.utils.url import prepare_url
from ....discount import DiscountType, DiscountValueType, RewardType, RewardValueType
from ....discount.interface import VariantPromotionRuleInfo
@@ -1617,7 +1617,7 @@ def test_notify_user(
redirect_url = "http://redirect.com/"
send_account_confirmation(customer_user, redirect_url, manager, channel_USD.slug)
- token = token_generator.make_token(customer_user)
+ token = account_confirm_token_generator.make_token(customer_user)
params = urlencode({"email": customer_user.email, "token": token})
confirm_url = prepare_url(params, redirect_url)