Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Implement login throttling (#16219)
Piotr Zabieglikdcb74a612876
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 880b78e233..6e8c2da607 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -32,6 +32,7 @@ All notable, unreleased changes to this project will be documented in this file.- Fixed a rare crash in the introspection query detection code - #15966 by @patrys- Added HTTP compression telemetry - #16125 by @patrys- Rewrite `productVariants` resolvers to use JOINs instead of subqueries - #16262 by @maarcingebala+- Implement login throttling - #16219 by @zedzior# 3.19.0diff --git a/saleor/account/error_codes.py b/saleor/account/error_codes.pyindex 267f77008b..a66694988c 100644--- a/saleor/account/error_codes.py+++ b/saleor/account/error_codes.py@@ -36,6 +36,8 @@ class AccountErrorCode(Enum):CHANNEL_INACTIVE = "channel_inactive"MISSING_CHANNEL_SLUG = "missing_channel_slug"ACCOUNT_NOT_CONFIRMED = "account_not_confirmed"+ LOGIN_ATTEMPT_DELAYED = "login_attempt_delayed"+ UNKNOWN_IP_ADDRESS = "unknown_ip_address"class CustomerBulkUpdateErrorCode(Enum):diff --git a/saleor/account/tests/test_throttling.py b/saleor/account/tests/test_throttling.pynew file mode 100644index 0000000000..04a0d55eba--- /dev/null+++ b/saleor/account/tests/test_throttling.py@@ -0,0 +1,408 @@+import logging+from datetime import timedelta+from unittest.mock import patch++import before_after+import pytest+from django.core.exceptions import ValidationError+from django.utils import timezone+from freezegun import freeze_time++from ..error_codes import AccountErrorCode+from ..throttling import (+ MAX_DELAY,+ MIN_DELAY,+ authenticate_with_throttling,+ get_cache_key_blocked_ip,+ get_cache_key_failed_ip,+ get_cache_key_failed_ip_with_user,+ get_delay_time,+)++CORRECT_PASSWORD = "password"+INCORRECT_PASSWORD = "incorrect-password"+EXISTING_EMAIL = "[email protected]"+NON_EXISTING_EMAIL = "[email protected]"+++ ("ip_attempts_count", "ip_user_attempts_count", "expected_delay"),+ [+ (1, 0, 1),+ (0, 1, 1),+ (21, 1, 4),+ (21, 4, 8),+ (100, 1, MAX_DELAY),+ (1, 10, MAX_DELAY),+ (0, 0, 1),+ (-1, -17, 1),+ ],+)+def test_get_delay_time(ip_attempts_count, ip_user_attempts_count, expected_delay):+ # given & when+ delay = get_delay_time(ip_attempts_count, ip_user_attempts_count)++ # then+ assert delay == expected_delay+++@freeze_time("2024-05-31 12:00:01")+@patch("saleor.account.throttling.cache")+def test_authenticate_successful_first_attempt(+ mocked_cache, rf, customer_user, setup_mock_for_cache+):+ # given+ dummy_cache = {}+ setup_mock_for_cache(dummy_cache, mocked_cache)+ now = timezone.now()++ ip = "123.123.123.123"+ request = rf.request(HTTP_X_FORWARDED_FOR=ip)++ block_key = get_cache_key_blocked_ip(ip)+ ip_key = get_cache_key_failed_ip(ip)+ ip_user_key = get_cache_key_failed_ip_with_user(ip, customer_user.id)++ # when+ user = authenticate_with_throttling(request, EXISTING_EMAIL, CORRECT_PASSWORD)++ # then+ assert user++ assert mocked_cache.get(block_key) is None+ assert mocked_cache.get(ip_key) is None+ assert mocked_cache.get(ip_user_key) is None++ next_attempt = now + timedelta(seconds=MIN_DELAY)+ mocked_cache.add.assert_called_once_with(block_key, next_attempt, timeout=MIN_DELAY)+ mocked_cache.set.assert_not_called()+ mocked_cache.incr.assert_not_called()+ mock_delete_arg_set = {arg.args[0] for arg in mocked_cache.delete.call_args_list}+ assert {block_key, ip_key, ip_user_key} == mock_delete_arg_set+++@freeze_time("2024-05-31 12:00:01")+@patch("saleor.account.throttling.cache")+def test_authenticate_successful_subsequent_attempt(+ mocked_cache, rf, customer_user, setup_mock_for_cache+):+ """Make sure cache is cleared after successful login."""+ # given+ dummy_cache = {}+ setup_mock_for_cache(dummy_cache, mocked_cache)+ now = timezone.now()++ ip = "123.123.123.123"+ request = rf.request(HTTP_X_FORWARDED_FOR=ip)++ block_key = get_cache_key_blocked_ip(ip)+ ip_key = get_cache_key_failed_ip(ip)+ ip_user_key = get_cache_key_failed_ip_with_user(ip, customer_user.id)++ # imitate cache state after a couple of login attempts+ dummy_cache[ip_key] = {"value": 21, "ttl": 100}+ dummy_cache[ip_user_key] = {"value": 7, "ttl": 100}++ # when+ user = authenticate_with_throttling(request, EXISTING_EMAIL, CORRECT_PASSWORD)++ # then+ assert user++ assert mocked_cache.get(block_key) is None+ assert mocked_cache.get(ip_key) is None+ assert mocked_cache.get(ip_user_key) is None++ next_attempt = now + timedelta(seconds=MIN_DELAY)+ mocked_cache.add.assert_called_once_with(block_key, next_attempt, timeout=MIN_DELAY)+ mocked_cache.set.assert_not_called()+ mocked_cache.incr.assert_not_called()+ mock_delete_arg_set = {arg.args[0] for arg in mocked_cache.delete.call_args_list}+ assert {block_key, ip_key, ip_user_key} == mock_delete_arg_set+++@freeze_time("2024-05-31 12:00:01")+@patch("saleor.account.throttling.cache")+def test_authenticate_incorrect_password_non_existing_email_first_attempt(+ mocked_cache,+ rf,+ customer_user,+ setup_mock_for_cache,+):+ # given+ dummy_cache = {}+ setup_mock_for_cache(dummy_cache, mocked_cache)+ now = timezone.now()++ ip = "123.123.123.123"+ request = rf.request(HTTP_X_FORWARDED_FOR=ip)++ block_key = get_cache_key_blocked_ip(ip)+ ip_key = get_cache_key_failed_ip(ip)+ ip_user_key = get_cache_key_failed_ip_with_user(ip, customer_user.id)++ # when+ user = authenticate_with_throttling(request, NON_EXISTING_EMAIL, INCORRECT_PASSWORD)++ # then+ assert not user+ next_attempt = mocked_cache.get(block_key)+ ip_attempts_count = mocked_cache.get(ip_key)+ ip_user_attempts_count = mocked_cache.get(ip_user_key)++ assert next_attempt == now + timedelta(seconds=MIN_DELAY)+ assert ip_attempts_count == 1+ assert ip_user_attempts_count is None+ mock_incr_arg_set = {arg.args[0] for arg in mocked_cache.incr.call_args_list}+ assert ip_user_key not in mock_incr_arg_set+++@freeze_time("2024-05-31 12:00:01")+@patch("saleor.account.throttling.cache")+def test_authenticate_incorrect_password_non_existing_email_subsequent_attempt(+ mocked_cache,+ rf,+ customer_user,+ setup_mock_for_cache,+):+ # given+ dummy_cache = {}+ setup_mock_for_cache(dummy_cache, mocked_cache)+ now = timezone.now()++ ip = "123.123.123.123"+ request = rf.request(HTTP_X_FORWARDED_FOR=ip)++ block_key = get_cache_key_blocked_ip(ip)+ ip_key = get_cache_key_failed_ip(ip)+ ip_user_key = get_cache_key_failed_ip_with_user(ip, customer_user.id)++ # imitate cache state after a couple of login attempts+ ip_attempts_count = 21+ dummy_cache[ip_key] = {"value": ip_attempts_count, "ttl": 100}+ expected_delay = get_delay_time(ip_attempts_count + 1, 0)++ # when+ user = authenticate_with_throttling(request, NON_EXISTING_EMAIL, INCORRECT_PASSWORD)++ # then+ assert not user+ next_attempt = mocked_cache.get(block_key)+ updated_ip_attempts_count = mocked_cache.get(ip_key)+ ip_user_attempts_count = mocked_cache.get(ip_user_key)++ assert next_attempt == now + timedelta(seconds=expected_delay)+ assert updated_ip_attempts_count == ip_attempts_count + 1+ assert ip_user_attempts_count is None+ mock_incr_arg_set = {arg.args[0] for arg in mocked_cache.incr.call_args_list}+ assert ip_user_key not in mock_incr_arg_set+++@freeze_time("2024-05-31 12:00:01")+@patch("saleor.account.throttling.cache")+def test_authenticate_incorrect_password_existing_email_first_attempt(+ mocked_cache,+ rf,+ customer_user,+ setup_mock_for_cache,+):+ # given+ dummy_cache = {}+ setup_mock_for_cache(dummy_cache, mocked_cache)+ now = timezone.now()++ ip = "123.123.123.123"+ request = rf.request(HTTP_X_FORWARDED_FOR=ip)++ block_key = get_cache_key_blocked_ip(ip)+ ip_key = get_cache_key_failed_ip(ip)+ ip_user_key = get_cache_key_failed_ip_with_user(ip, customer_user.id)++ # when+ user = authenticate_with_throttling(request, EXISTING_EMAIL, INCORRECT_PASSWORD)++ # then+ assert not user+ next_attempt = mocked_cache.get(block_key)+ ip_attempts_count = mocked_cache.get(ip_key)+ ip_user_attempts_count = mocked_cache.get(ip_user_key)++ assert next_attempt == now + timedelta(seconds=MIN_DELAY)+ assert ip_attempts_count == 1+ assert ip_user_attempts_count == 1+++@freeze_time("2024-05-31 12:00:01")+@patch("saleor.account.throttling.cache")+def test_authenticate_incorrect_password_existing_email_subsequent_attempt(+ mocked_cache,+ rf,+ customer_user,+ setup_mock_for_cache,+):+ # given+ dummy_cache = {}+ setup_mock_for_cache(dummy_cache, mocked_cache)+ now = timezone.now()++ ip = "123.123.123.123"+ request = rf.request(HTTP_X_FORWARDED_FOR=ip)++ block_key = get_cache_key_blocked_ip(ip)+ ip_key = get_cache_key_failed_ip(ip)+ ip_user_key = get_cache_key_failed_ip_with_user(ip, customer_user.id)++ # imitate cache state after a couple of login attempts+ ip_attempts_count = 21+ ip_user_attempts_count = 5+ dummy_cache[ip_key] = {"value": ip_attempts_count, "ttl": 100}+ dummy_cache[ip_user_key] = {"value": ip_user_attempts_count, "ttl": 100}+ expected_delay = get_delay_time(ip_attempts_count + 1, ip_user_attempts_count + 1)++ # when+ user = authenticate_with_throttling(request, EXISTING_EMAIL, INCORRECT_PASSWORD)++ # then+ assert not user+ next_attempt = mocked_cache.get(block_key)+ updated_ip_attempts_count = mocked_cache.get(ip_key)+ updated_ip_user_attempts_count = mocked_cache.get(ip_user_key)++ assert next_attempt == now + timedelta(seconds=expected_delay)+ assert updated_ip_attempts_count == ip_attempts_count + 1+ assert updated_ip_user_attempts_count == ip_user_attempts_count + 1+++@freeze_time("2024-05-31 12:00:01")+def test_authenticate_unidentified_ip_address(rf, customer_user, caplog):+ # given+ request = rf.request(HTTP_X_FORWARDED_FOR="", REMOTE_ADDR="")+ caplog.set_level(logging.WARNING)++ # when & then+ with pytest.raises(ValidationError) as e:+ authenticate_with_throttling(request, EXISTING_EMAIL, CORRECT_PASSWORD)++ assert e.value.code == AccountErrorCode.UNKNOWN_IP_ADDRESS.value+ assert "Unknown request's IP address." in caplog.text+++@freeze_time("2024-05-31 12:00:01")+@patch("saleor.account.throttling.cache")+def test_authenticate_login_attempt_delayed(+ mocked_cache, rf, customer_user, setup_mock_for_cache+):+ # given+ dummy_cache = {}+ setup_mock_for_cache(dummy_cache, mocked_cache)+ now = timezone.now()++ ip = "123.123.123.123"+ request = rf.request(HTTP_X_FORWARDED_FOR=ip)++ block_key = get_cache_key_blocked_ip(ip)+ ip_key = get_cache_key_failed_ip(ip)+ ip_user_key = get_cache_key_failed_ip_with_user(ip, customer_user.id)++ # imitate cache state when login is temporarily blocked+ ip_attempts_count = 21+ ip_user_attempts_count = 5+ dummy_cache[ip_key] = {"value": ip_attempts_count, "ttl": 100}+ dummy_cache[ip_user_key] = {"value": ip_user_attempts_count, "ttl": 100}+ delay = get_delay_time(ip_attempts_count, ip_user_attempts_count)+ next_attempt = now + timedelta(seconds=delay)+ dummy_cache[block_key] = {"value": next_attempt, "ttl": delay}++ # when & then+ with pytest.raises(ValidationError) as e:+ authenticate_with_throttling(request, EXISTING_EMAIL, INCORRECT_PASSWORD)++ error = e.value+ assert error.code == AccountErrorCode.LOGIN_ATTEMPT_DELAYED.value+ assert str(next_attempt) in error.message++ assert mocked_cache.get(ip_key) == ip_attempts_count+ assert mocked_cache.get(ip_user_key) == ip_user_attempts_count+ assert mocked_cache.get(block_key) == next_attempt+++@freeze_time("2024-05-31 12:00:01")+@patch("saleor.account.throttling.cache")+def test_authenticate_race_condition(+ mocked_cache, rf, customer_user, setup_mock_for_cache+):+ # given+ dummy_cache = {}+ setup_mock_for_cache(dummy_cache, mocked_cache)+ now = timezone.now()++ ip = "123.123.123.123"+ request = rf.request(HTTP_X_FORWARDED_FOR=ip)++ block_key = get_cache_key_blocked_ip(ip)+ ip_key = get_cache_key_failed_ip(ip)+ ip_user_key = get_cache_key_failed_ip_with_user(ip, customer_user.id)++ next_attempt = now + timedelta(seconds=MIN_DELAY)++ # when+ def login_attempt(*args, **kwargs):+ authenticate_with_throttling(request, EXISTING_EMAIL, INCORRECT_PASSWORD)++ with before_after.before("saleor.account.throttling.add_block", login_attempt):+ with pytest.raises(ValidationError) as e:+ authenticate_with_throttling(request, EXISTING_EMAIL, INCORRECT_PASSWORD)++ # then+ error = e.value+ assert error.code == AccountErrorCode.LOGIN_ATTEMPT_DELAYED.value+ assert str(next_attempt) in error.message++ assert mocked_cache.get(ip_key) == 1+ assert mocked_cache.get(ip_user_key) == 1+ assert mocked_cache.get(block_key) == next_attempt+++@freeze_time("2024-05-31 12:00:01")+@patch("saleor.account.throttling.cache")+def test_authenticate_incorrect_credentials_max_attempts(+ mocked_cache,+ rf,+ customer_user,+ setup_mock_for_cache,+ caplog,+):+ # given+ dummy_cache = {}+ setup_mock_for_cache(dummy_cache, mocked_cache)+ now = timezone.now()+ caplog.set_level(logging.WARNING)++ ip = "123.123.123.123"+ request = rf.request(HTTP_X_FORWARDED_FOR=ip)++ block_key = get_cache_key_blocked_ip(ip)+ ip_key = get_cache_key_failed_ip(ip)+ ip_user_key = get_cache_key_failed_ip_with_user(ip, customer_user.id)++ # imitate cache state after a couple of login attempts+ ip_attempts_count = 100+ ip_user_attempts_count = 10+ dummy_cache[ip_key] = {"value": ip_attempts_count, "ttl": 100}+ dummy_cache[ip_user_key] = {"value": ip_user_attempts_count, "ttl": 100}+ expected_delay = get_delay_time(ip_attempts_count + 1, ip_user_attempts_count + 1)+ assert expected_delay == MAX_DELAY++ # when+ user = authenticate_with_throttling(request, EXISTING_EMAIL, INCORRECT_PASSWORD)++ # then+ assert not user+ next_attempt = mocked_cache.get(block_key)+ updated_ip_attempts_count = mocked_cache.get(ip_key)+ updated_ip_user_attempts_count = mocked_cache.get(ip_user_key)++ assert next_attempt == now + timedelta(seconds=expected_delay)+ assert updated_ip_attempts_count == ip_attempts_count + 1+ assert updated_ip_user_attempts_count == ip_user_attempts_count + 1+ assert "Unsuccessful logging attempts reached max value." in caplog.textdiff --git a/saleor/account/throttling.py b/saleor/account/throttling.pynew file mode 100644index 0000000000..1e6243017d--- /dev/null+++ b/saleor/account/throttling.py@@ -0,0 +1,137 @@+import logging+from datetime import timedelta+from math import ceil+from typing import Optional++from django.core.cache import cache+from django.core.exceptions import ValidationError+from django.utils import timezone++from ..core.utils import get_client_ip+from . import models+from .error_codes import AccountErrorCode+from .utils import retrieve_user_by_email++MIN_DELAY = 1+MAX_DELAY = 3600+ATTEMPT_COUNTER_EXPIRE_TIME = 7200++logger = logging.getLogger(__name__)+++def authenticate_with_throttling(request, email, password) -> Optional[models.User]:+ ip = get_client_ip(request)+ if not ip:+ logger.warning("Unknown request's IP address.")+ raise ValidationError(+ "Can't indentify requester IP address.",+ code=AccountErrorCode.UNKNOWN_IP_ADDRESS.value,+ )++ ip_key = get_cache_key_failed_ip(ip)+ block_key = get_cache_key_blocked_ip(ip)++ # block the IP address before the next attempt to prevent concurrent requests+ if add_block(block_key, MIN_DELAY) is False:+ next_attempt_time = cache.get(block_key) or timezone.now() + timedelta(+ seconds=MIN_DELAY+ )+ raise ValidationError(+ f"Logging has been suspended till {next_attempt_time} due to too many "+ f"logging attempts originating from the same IP address.",+ code=AccountErrorCode.LOGIN_ATTEMPT_DELAYED.value,+ )++ # retrieve user from credentials+ ip_user_attempts_count = 0+ if user := retrieve_user_by_email(email):+ ip_user_key = get_cache_key_failed_ip_with_user(ip, user.pk)+ if user.check_password(password):+ # clear cache entries when login successful+ clear_cache([ip_key, ip_user_key, block_key])+ return user++ else:+ # increment failed attempt for known user+ ip_user_attempts_count = increment_attempt(ip_user_key)++ # increment failed attempt for whatever user+ ip_attempts_count = increment_attempt(ip_key)++ # calculate next allowed login attempt time and block the IP till the time+ delay = get_delay_time(ip_attempts_count, ip_user_attempts_count)+ if delay == MAX_DELAY:+ logger.warning("Unsuccessful logging attempts reached max value.")+ override_block(block_key, delay)++ return None+++def get_cache_key_failed_ip(ip: str) -> str:+ return f"login:fail:ip:{ip}"+++def get_cache_key_failed_ip_with_user(ip: str, user_id) -> str:+ return f"login:fail:ip:{ip}:user:{user_id}"+++def get_cache_key_blocked_ip(ip: str) -> str:+ return f"login:block:ip:{ip}"+++def clear_cache(keys: list[str]):+ for key in keys:+ cache.delete(key)+++def get_delay_time(ip_attempts_count: int, ip_user_attempts_count: int) -> int:+ """Calculate next login attempt delay, based on number of attempts.++ Delay is incremented by the power of 2.++ We distinguish two cases:+ - Case "A": many failed logins for the same IP address, no matters the username+ provided, to prevent credential stuffing+ - Case "B": many failed logins for the same IP address and same existing username,+ to prevent brute-forcing++ For case "A" we increment delay time every 10 attempts. It means delay will be+ 1sec for attempts 1-10, 2sec for attempts 11-20, 4 sec for attempts 21-30 and so on.++ For case "B" we increment delay time every single attempt. It means delay will be+ 1sec after attempt 1, 2sec after attempt 2, 4sec after attempt 3 and so on.+ """+ ip_delay = 0+ if ip_attempts_count > 0:+ ip_delay = (+ 2 ** (ceil(ip_attempts_count / 10) - 1)+ if ip_attempts_count < 100+ else MAX_DELAY+ )++ ip_user_delay = 0+ if ip_user_attempts_count > 0:+ ip_user_delay = (+ 2 ** (ip_user_attempts_count - 1)+ if ip_user_attempts_count < 10+ else MAX_DELAY+ )++ return max(ip_delay, ip_user_delay, MIN_DELAY)+++def override_block(block_key: str, time_delta: int):+ next_attempt_time = timezone.now() + timedelta(seconds=time_delta)+ cache.set(block_key, next_attempt_time, timeout=time_delta)+++def add_block(block_key: str, time_delta: int) -> bool:+ next_attempt_time = timezone.now() + timedelta(seconds=time_delta)+ return cache.add(block_key, next_attempt_time, timeout=time_delta)+++def increment_attempt(key: str) -> int:+ # `cache.add` returns False and does nothing, when key already exists+ if not cache.add(key, 1, timeout=ATTEMPT_COUNTER_EXPIRE_TIME):+ return cache.incr(key, 1)+ return 1diff --git a/saleor/graphql/account/mutations/authentication/create_token.py b/saleor/graphql/account/mutations/authentication/create_token.pyindex 497c3a5d18..40a1132be5 100644--- a/saleor/graphql/account/mutations/authentication/create_token.py+++ b/saleor/graphql/account/mutations/authentication/create_token.py@@ -1,14 +1,12 @@from datetime import timedelta-from typing import Optionalimport graphenefrom django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom django.utils import timezone-from .....account import modelsfrom .....account.error_codes import AccountErrorCode-from .....account.utils import retrieve_user_by_email+from .....account.throttling import authenticate_with_throttlingfrom .....core.jwt import create_access_token, create_refresh_tokenfrom ....core import ResolveInfofrom ....core.descriptions import ADDED_IN_38@@ -49,18 +47,9 @@ class CreateToken(BaseMutation):)user = graphene.Field(User, description="A user instance.")- @classmethod- def _retrieve_user_from_credentials(cls, email, password) -> Optional[models.User]:- user = retrieve_user_by_email(email)-- if user and user.check_password(password):- return user- return None-@classmethoddef get_user(cls, info: ResolveInfo, email, password):- site_settings = get_site_promise(info.context).get().settings- user = cls._retrieve_user_from_credentials(email, password)+ user = authenticate_with_throttling(info.context, email, password)if not user:raise ValidationError({@@ -70,6 +59,8 @@ class CreateToken(BaseMutation):)})++ site_settings = get_site_promise(info.context).get().settingsif (not user.is_confirmedand not site_settings.allow_login_without_confirmationdiff --git a/saleor/graphql/account/tests/mutations/authentication/test_token_create.py b/saleor/graphql/account/tests/mutations/authentication/test_token_create.pyindex 3965da7244..4d73a676c6 100644--- a/saleor/graphql/account/tests/mutations/authentication/test_token_create.py+++ b/saleor/graphql/account/tests/mutations/authentication/test_token_create.py@@ -1,4 +1,5 @@from datetime import datetime, timedelta, timezone+from unittest.mock import patchimport grapheneimport pytz@@ -6,6 +7,12 @@ from django.urls import reversefrom freezegun import freeze_timefrom ......account.error_codes import AccountErrorCode+from ......account.throttling import (+ get_cache_key_blocked_ip,+ get_cache_key_failed_ip,+ get_cache_key_failed_ip_with_user,+ get_delay_time,+)from ......core.jwt import (JWT_ACCESS_TYPE,JWT_REFRESH_TYPE,@@ -40,11 +47,16 @@ MUTATION_CREATE_TOKEN = """@freeze_time("2020-03-18 12:00:00")-def test_create_token(api_client, customer_user, settings):+@patch("saleor.account.throttling.cache")+def test_create_token(_mocked_cache, api_client, customer_user, settings):+ # givenvariables = {"email": customer_user.email, "password": customer_user._password}++ # whenresponse = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)content = get_graphql_content(response)+ # thendata = content["data"]["tokenCreate"]user_email = data["user"]["email"]@@ -73,16 +85,21 @@ def test_create_token(api_client, customer_user, settings):@freeze_time("2020-03-18 12:00:00")-def test_create_token_with_audience(api_client, customer_user, settings):+@patch("saleor.account.throttling.cache")+def test_create_token_with_audience(_mocked_cache, api_client, customer_user, settings):+ # givenaudience = "dashboard"variables = {"email": customer_user.email,"password": customer_user._password,"audience": audience,}++ # whenresponse = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)content = get_graphql_content(response)+ # thendata = content["data"]["tokenCreate"]user_email = data["user"]["email"]@@ -112,15 +129,22 @@ def test_create_token_with_audience(api_client, customer_user, settings):@freeze_time("2020-03-18 12:00:00")-def test_create_token_sets_cookie(api_client, customer_user, settings, monkeypatch):+@patch("saleor.account.throttling.cache")+def test_create_token_sets_cookie(+ _mocked_cache, api_client, customer_user, settings, monkeypatch+):+ # givencsrf_token = _get_new_csrf_token()monkeypatch.setattr("saleor.graphql.account.mutations.authentication.create_token._get_new_csrf_token",lambda: csrf_token,)variables = {"email": customer_user.email, "password": customer_user._password}++ # whenresponse = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)+ # thenexpected_refresh_token = create_refresh_token(customer_user, {"csrfToken": csrf_token})@@ -134,27 +158,43 @@ def test_create_token_sets_cookie(api_client, customer_user, settings, monkeypatassert refresh_token["secure"]-def test_create_token_invalid_password(api_client, customer_user):+@freeze_time("2024-05-31 12:00:01")+@patch("saleor.account.throttling.cache")+def test_create_token_invalid_password(_mocked_cache, api_client, customer_user):+ # givenvariables = {"email": customer_user.email, "password": "wrongpassword"}expected_error_code = AccountErrorCode.INVALID_CREDENTIALS.value.upper()++ # whenresponse = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)content = get_graphql_content(response)++ # thenresponse_error = content["data"]["tokenCreate"]["errors"][0]assert response_error["code"] == expected_error_codeassert response_error["field"] == "email"-def test_create_token_invalid_email(api_client, customer_user):+@freeze_time("2024-05-31 12:00:01")+@patch("saleor.account.throttling.cache")+def test_create_token_invalid_email(_mocked_cache, api_client, customer_user):+ # givenvariables = {"email": "wrongemail", "password": "wrongpassword"}expected_error_code = AccountErrorCode.INVALID_CREDENTIALS.value.upper()++ # whenresponse = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)content = get_graphql_content(response)++ # thenresponse_error = content["data"]["tokenCreate"]["errors"][0]assert response_error["code"] == expected_error_codeassert response_error["field"] == "email"-def test_create_token_unconfirmed_email(api_client, customer_user):+@freeze_time("2024-05-31 12:00:01")+@patch("saleor.account.throttling.cache")+def test_create_token_unconfirmed_email(_mocked_cache, api_client, customer_user):# givenvariables = {"email": customer_user.email, "password": customer_user._password}customer_user.is_confirmed = False@@ -172,8 +212,9 @@ def test_create_token_unconfirmed_email(api_client, customer_user):@freeze_time("2020-03-18 12:00:00")+@patch("saleor.account.throttling.cache")def test_create_token_unconfirmed_user_unconfirmed_login_enabled(- api_client, customer_user, settings, site_settings+ _mocked_cache, api_client, customer_user, settings, site_settings):# givenvariables = {"email": customer_user.email, "password": customer_user._password}@@ -214,7 +255,9 @@ def test_create_token_unconfirmed_user_unconfirmed_login_enabled(assert payload["iss"] == build_absolute_uri(reverse("api"))-def test_create_token_deactivated_user(api_client, customer_user):+@freeze_time("2020-03-18 12:00:00")+@patch("saleor.account.throttling.cache")+def test_create_token_deactivated_user(_mocked_cache, api_client, customer_user):# givenvariables = {"email": customer_user.email, "password": customer_user._password}customer_user.is_active = False@@ -234,13 +277,20 @@ def test_create_token_deactivated_user(api_client, customer_user):@freeze_time("2020-03-18 12:00:00")-def test_create_token_active_user_logged_before(api_client, customer_user, settings):+@patch("saleor.account.throttling.cache")+def test_create_token_active_user_logged_before(+ _mocked_cache, api_client, customer_user, settings+):+ # givenvariables = {"email": customer_user.email, "password": customer_user._password}customer_user.last_login = datetime(2020, 3, 18, tzinfo=timezone.utc)customer_user.save()++ # whenresponse = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)content = get_graphql_content(response)+ # thendata = content["data"]["tokenCreate"]user_email = data["user"]["email"]@@ -269,7 +319,10 @@ def test_create_token_active_user_logged_before(api_client, customer_user, setti@freeze_time("2020-03-18 12:00:00")-def test_create_token_email_case_insensitive(api_client, customer_user, settings):+@patch("saleor.account.throttling.cache")+def test_create_token_email_case_insensitive(+ _mocked_cache, api_client, customer_user, settings+):# givenvariables = {"email": customer_user.email.upper(),@@ -340,3 +393,70 @@ def test_create_token_do_update_last_login_when_out_of_threshold(assert customer_user.last_login != previous_last_loginassert customer_user.updated_at == time_in_thresholdassert customer_user.last_login == time_in_threshold+++@freeze_time("2020-03-18 12:00:00")+@patch("saleor.account.throttling.get_client_ip")+@patch("saleor.account.throttling.cache")+def test_create_token_throttling_login_attempt_delay(+ mocked_cache, mocked_get_ip, api_client, customer_user, setup_mock_for_cache+):+ # given+ dummy_cache = {}+ setup_mock_for_cache(dummy_cache, mocked_cache)+ now = datetime.utcnow()++ variables = {"email": customer_user.email, "password": "incorrect-password"}++ ip = "123.123.123.123"+ mocked_get_ip.return_value = ip++ # imitate cache state after a couple of failed login attempts+ block_key = get_cache_key_blocked_ip(ip)+ ip_key = get_cache_key_failed_ip(ip)+ ip_user_key = get_cache_key_failed_ip_with_user(ip, customer_user.id)++ ip_attempts_count = 21+ ip_user_attempts_count = 5+ mocked_cache.set(ip_key, ip_attempts_count, timeout=100)+ mocked_cache.set(ip_user_key, ip_user_attempts_count, timeout=100)+ expected_delay = get_delay_time(ip_attempts_count + 1, ip_user_attempts_count + 1)+ next_attempt = now + timedelta(seconds=expected_delay)+ mocked_cache.set(block_key, next_attempt, timeout=100)++ # when+ response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)+ content = get_graphql_content(response)++ # then+ errors = content["data"]["tokenCreate"]["errors"]+ assert len(errors) == 1+ error = errors[0]+ assert error["code"] == AccountErrorCode.LOGIN_ATTEMPT_DELAYED.name+ assert error["field"] is None+ assert str(next_attempt) in error["message"]+++@freeze_time("2020-03-18 12:00:00")+@patch("saleor.account.throttling.get_client_ip")+@patch("saleor.account.throttling.cache")+def test_create_token_throttling_unidentified_ip_address(+ _mocked_cache, mock_get_ip, api_client, customer_user+):+ # given+ mock_get_ip.return_value = None+ variables = {+ "email": customer_user.email,+ "password": customer_user._password,+ }++ # when+ response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)+ content = get_graphql_content(response)++ # then+ errors = content["data"]["tokenCreate"]["errors"]+ assert len(errors) == 1+ error = errors[0]+ assert error["code"] == AccountErrorCode.UNKNOWN_IP_ADDRESS.name+ assert error["field"] is Nonediff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex b48efa6efc..1b676580e8 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -31237,6 +31237,8 @@ enum AccountErrorCode @doc(category: "Users") {CHANNEL_INACTIVEMISSING_CHANNEL_SLUGACCOUNT_NOT_CONFIRMED+ LOGIN_ATTEMPT_DELAYED+ UNKNOWN_IP_ADDRESS}"""diff --git a/saleor/tests/e2e/account/test_login_throttling.py b/saleor/tests/e2e/account/test_login_throttling.pynew file mode 100644index 0000000000..b153285d00--- /dev/null+++ b/saleor/tests/e2e/account/test_login_throttling.py@@ -0,0 +1,159 @@+from datetime import timedelta+from unittest.mock import patch++import graphene+import pytest+from django.utils import timezone+from freezegun import freeze_time++from ....account.error_codes import AccountErrorCode+from ....account.throttling import (+ get_cache_key_blocked_ip,+ get_cache_key_failed_ip,+ get_cache_key_failed_ip_with_user,+ get_delay_time,+)+from ..shop.utils import prepare_shop+from ..utils import assign_permissions+from .utils import account_register, raw_token_create+++@freeze_time("2020-03-18 12:00:00")+@patch("saleor.account.throttling.get_client_ip")+@patch("saleor.account.throttling.cache")+def test_customer_should_not_be_able_to_perform_credential_guessing_attacks_core_1519(+ mocked_cache,+ mocked_get_ip,+ e2e_not_logged_api_client,+ e2e_staff_api_client,+ permission_manage_product_types_and_attributes,+ shop_permissions,+ setup_mock_for_cache,+):+ # Before+ now = timezone.now()+ dummy_cache = {}+ setup_mock_for_cache(dummy_cache, mocked_cache)++ permissions = [+ permission_manage_product_types_and_attributes,+ *shop_permissions,+ ]+ assign_permissions(e2e_staff_api_client, permissions)++ shop_data, _tax_config = prepare_shop(+ e2e_staff_api_client,+ channels=[+ {+ "shipping_zones": [+ {+ "shipping_methods": [+ {},+ ],+ },+ ],+ "order_settings": {},+ }+ ],+ shop_settings={+ "enableAccountConfirmationByEmail": False,+ },+ )+ channel_slug = shop_data[0]["slug"]+ user_email = "[email protected]"+ user_password = "Test1234!"++ ip = "123.123.123.123"+ mocked_get_ip.return_value = ip++ # Step 1 - Create account for the new customer+ user_account = account_register(+ e2e_not_logged_api_client,+ user_email,+ user_password,+ channel_slug,+ )+ user_id = user_account["user"]["id"]+ assert user_id is not None+ _, user_db_id = graphene.Node.from_global_id(user_id)+ assert user_account["user"]["isActive"] is True++ # Step 2 - First attempt of logging with an invalid password+ invalid_password = "password"+ login_data = raw_token_create(+ e2e_not_logged_api_client, user_email, invalid_password+ )+ error = login_data["data"]["tokenCreate"]["errors"][0]+ assert error["code"] == AccountErrorCode.INVALID_CREDENTIALS.name++ block_key = get_cache_key_blocked_ip(ip)+ ip_key = get_cache_key_failed_ip(ip)+ ip_user_key = get_cache_key_failed_ip_with_user(ip, user_db_id)++ attempt_ip_counter = 1+ attempt_ip_user_counter = 1+ delay = get_delay_time(attempt_ip_counter, attempt_ip_user_counter)+ next_attempt = now + timedelta(seconds=delay)++ assert mocked_cache.get(block_key) == next_attempt+ assert mocked_cache.get(ip_key) == attempt_ip_counter+ assert mocked_cache.get(ip_user_key) == attempt_ip_counter++ # Step 3 - Second attempt of logging with an invalid password before it is allowed+ login_data = raw_token_create(+ e2e_not_logged_api_client, user_email, invalid_password+ )+ error = login_data["data"]["tokenCreate"]["errors"][0]+ assert error["code"] == AccountErrorCode.LOGIN_ATTEMPT_DELAYED.name++ # login attempt while logining is blocked should not result in increasing+ # logging attempt counter and next allowed attempt time+ assert mocked_cache.get(block_key) == next_attempt+ assert mocked_cache.get(ip_key) == attempt_ip_counter+ assert mocked_cache.get(ip_user_key) == attempt_ip_user_counter++ # Step 4 - Third attempt of logging with an invalid password when it is allowed+ mocked_cache.delete(block_key)+ login_data = raw_token_create(+ e2e_not_logged_api_client, user_email, invalid_password+ )+ error = login_data["data"]["tokenCreate"]["errors"][0]+ assert error["code"] == AccountErrorCode.INVALID_CREDENTIALS.name++ # login attempt when logging is allowed (not blocked), should increase login attempt+ # counter and next allowed attempt time+ attempt_ip_counter += 1+ attempt_ip_user_counter += 1+ new_delay = get_delay_time(attempt_ip_counter, attempt_ip_user_counter)+ assert new_delay != delay+ next_attempt = now + timedelta(seconds=new_delay)++ assert mocked_cache.get(block_key) == next_attempt+ assert mocked_cache.get(ip_key) == attempt_ip_counter+ assert mocked_cache.get(ip_user_key) == attempt_ip_counter++ # Step 5 - Fourth attempt of logging with non-existing email when it is allowed+ non_existing_email = "[email protected]"+ mocked_cache.delete(block_key)+ login_data = raw_token_create(+ e2e_not_logged_api_client, non_existing_email, invalid_password+ )+ error = login_data["data"]["tokenCreate"]["errors"][0]+ assert error["code"] == AccountErrorCode.INVALID_CREDENTIALS.name++ # when trying to log in with unknown email we should increase attempt for ip only+ # and not for ip+user+ assert mocked_cache.get(ip_key) == attempt_ip_counter + 1+ assert mocked_cache.get(ip_user_key) == attempt_ip_user_counter++ # Step 6 - Fifth attempt of logging with valid credentials when it is allowed+ mocked_cache.delete(block_key)+ login_data = raw_token_create(e2e_not_logged_api_client, user_email, user_password)+ assert not login_data["data"]["tokenCreate"]["errors"]+ assert login_data["data"]["tokenCreate"]["user"]["email"] == user_email++ # cache should be cleared after successful login attempt+ assert mocked_cache.get(block_key) is None+ assert mocked_cache.get(ip_key) is None+ assert mocked_cache.get(ip_user_key) is Nonediff --git a/saleor/tests/e2e/account/test_should_not_be_able_to_login_with_invalid_credentials.py b/saleor/tests/e2e/account/test_should_not_be_able_to_login_with_invalid_credentials.pyindex 53d863bfdd..5f8edb6ea4 100644--- a/saleor/tests/e2e/account/test_should_not_be_able_to_login_with_invalid_credentials.py+++ b/saleor/tests/e2e/account/test_should_not_be_able_to_login_with_invalid_credentials.py@@ -1,18 +1,30 @@+from unittest.mock import patch+import pytest+from saleor.account.throttling import get_cache_key_blocked_ip+from ..shop.utils import prepare_shopfrom ..utils import assign_permissionsfrom .utils import account_register, raw_token_create@pytest.mark.e2e+@patch("saleor.account.throttling.get_client_ip")+@patch("saleor.account.throttling.cache")def test_should_not_be_able_to_login_with_invalid_credentials_core_1506(+ mocked_cache,+ mocked_get_ip,e2e_not_logged_api_client,e2e_staff_api_client,permission_manage_product_types_and_attributes,shop_permissions,+ setup_mock_for_cache,):# Before+ dummy_cache = {}+ setup_mock_for_cache(dummy_cache, mocked_cache)+permissions = [permission_manage_product_types_and_attributes,*shop_permissions,@@ -41,6 +53,9 @@ def test_should_not_be_able_to_login_with_invalid_credentials_core_1506(user_email = "[email protected]"user_password = "Test1234!"+ ip = "123.123.123.123"+ mocked_get_ip.return_value = ip+# Step 1 - Create account for the new customeruser_account = account_register(e2e_not_logged_api_client,@@ -62,6 +77,11 @@ def test_should_not_be_able_to_login_with_invalid_credentials_core_1506(assert error["message"] == "Please, enter valid credentials"assert error["code"] == "INVALID_CREDENTIALS"+ # Due to throttling, login with invalid credentials leads to block next attempt,+ # by adding specific entry to cache. We should delete it here to unblock logining.+ block_key = get_cache_key_blocked_ip(ip)+ mocked_cache.delete(block_key)+# Step 3 - Login with invalid emailinvalid_email = "[email protected]"login_data = raw_token_create(diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 8a2be452a9..b60359e862 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -9343,3 +9343,66 @@ def lots_of_products_with_variants(product_type, channel_USD):ProductVariantChannelListing.objects.bulk_create(variant_listings)ProductChannelListing.objects.bulk_create(product_listings)return Product.objects.all()+++def setup_mock_for_cache():+ """Mock cache backend.++ To be used together with `cache_mock` and `dummy_cache`, where:+ - `dummy_cache` is a dict the mock is write to, instead of real cache db+ - `cache_mock` is a patch applied on real cache db++ It supports following functions: `get`, `set`, `delete`, `incr` and `add`. If other+ function is utilised in a tested codebase, this fixture should be extended.++ Stores `key`, `value` and `ttl` in following format:+ {key: {"value": value, "ttl": ttl}}+ """++ def _mocked_cache(dummy_cache, cache_mock):+ def cache_get(key):+ if data := dummy_cache.get(key):+ return data["value"]+ return None++ def cache_set(key, value, timeout):+ dummy_cache.update({key: {"value": value, "ttl": timeout}})++ def cache_add(key, value, timeout):+ if dummy_cache.get(key) is None:+ dummy_cache.update({key: {"value": value, "ttl": timeout}})+ return True+ return False++ def cache_delete(key):+ dummy_cache.pop(key, None)++ def cache_incr(key, delta):+ if current_data := dummy_cache.get(key):+ current_value = current_data["value"]+ new_value = current_value + delta+ dummy_cache.update(+ {key: {"value": new_value, "ttl": current_data["ttl"]}}+ )+ return new_value++ mocked_get_cache = MagicMock()+ mocked_set_cache = MagicMock()+ mocked_add_cache = MagicMock()+ mocked_incr_cache = MagicMock()+ mocked_delete_cache = MagicMock()++ mocked_get_cache.side_effect = cache_get+ mocked_set_cache.side_effect = cache_set+ mocked_add_cache.side_effect = cache_add+ mocked_incr_cache.side_effect = cache_incr+ mocked_delete_cache.side_effect = cache_delete++ cache_mock.get = mocked_get_cache+ cache_mock.set = mocked_set_cache+ cache_mock.add = mocked_add_cache+ cache_mock.incr = mocked_incr_cache+ cache_mock.delete = mocked_delete_cache++ return _mocked_cache