jira/apps/api/plane/authentication/rate_limit.py

110 lines
4.1 KiB
Python
Raw Permalink Normal View History

# Copyright (c) 2023-present Plane Software, Inc. and contributors
# SPDX-License-Identifier: AGPL-3.0-only
# See the LICENSE file for details.
fix(api): rate-limit magic-code verify, bound per-token attempts (GHSA-9pvm-fcf6-9234) (#9130) * fix(api): rate-limit magic-code verification and bound per-token attempts The magic-link sign-in / sign-up endpoints accept a 6-digit numeric code (900k-value space, 600s TTL) but never increment a failure counter on a wrong-code verify and extend django.views.View rather than DRF APIView, so DRF's AuthenticationThrottle never runs against them. The space-side generate endpoint also lacked throttle_classes. Combined, this allowed an unauthenticated attacker who knew a victim's email to brute-force the code within the TTL window and log in as the victim. - Add MAX_VERIFY_ATTEMPTS=5 in MagicCodeProvider.set_user_data: failed comparisons now persist verify_attempts in Redis under the remaining TTL and, on hitting the limit, delete the key and raise EMAIL_CODE_ATTEMPT_EXHAUSTED. This is the load-bearing fix - it caps total attempts per issued token regardless of request rate. - Add authentication_throttle_allows() so plain Django Views can apply AuthenticationThrottle without converting to APIView (would change CSRF + request-parsing semantics for the redirect-flow endpoints). - Apply the throttle to MagicSignIn/UpEndpoint and the space variants; add throttle_classes to MagicGenerateSpaceEndpoint to match its app sibling. Refs GHSA-9pvm-fcf6-9234. * fix(api): make verify-attempt increment atomic, expose throttle rate via env Address PR review feedback: - Replace the JSON read-modify-write of verify_attempts with a Lua EVAL script that INCRs a dedicated counter key and EXPIREs it only on the first increment. The previous round-trip was racy: parallel wrong-code requests could read the same value and both write the same incremented count, letting an attacker exceed MAX_VERIFY_ATTEMPTS under concurrency. Counter is now reset on each new token issuance and cleared on successful verify / exhaustion. - Make AuthenticationThrottle.rate configurable via the AUTHENTICATION_RATE_LIMIT env var (default 10/minute, down from 30 to tighten the budget on unauth auth-adjacent endpoints). Document it in deployments/aio and deployments/cli variables.env. * test(api): cover magic-code attempt cap, counter reset, and auth throttle Add the contract tests called out in the PR test plan: - TestMagicSignInVerifyAttempts: - test_exhausted_after_max_wrong_attempts: after MAX_VERIFY_ATTEMPTS wrong codes the next verify redirects with EMAIL_CODE_ATTEMPT_ EXHAUSTED_SIGN_IN and both Redis keys are deleted; a follow-up verify reports EXPIRED. - test_counter_increments_on_each_wrong_attempt: the dedicated verify_attempts counter advances by exactly one per wrong POST, matching the atomic Lua INCR. - test_counter_resets_on_token_regeneration: regenerating the magic-link clears the counter so the user isn't pre-locked-out by a prior session's wrong attempts. - TestMagicSignUpVerifyAttempts.test_signup_exhausted_after_max_wrong_attempts: the sign-up endpoint returns EMAIL_CODE_ATTEMPT_EXHAUSTED_SIGN_UP on the exhausting attempt. - TestAuthenticationThrottle: exercises authentication_throttle_allows on the plain-View redirect-flow endpoints by patching the rate down and asserting RATE_LIMIT_EXCEEDED is appended to the redirect URL once the per-IP budget is exceeded, for both magic-sign-in and magic-sign-up. Each new class clears Django cache (DRF throttle storage) and the per-email Redis keys around every test so runs are independent. * fix(api): clamp remaining_ttl to >=1 for verify-attempt counter EXPIRE ri.ttl() returns 0 when the token has less than one second remaining (Redis floors to whole seconds). The previous clamp only caught None and < 0, so a sub-second TTL would pass through and the Lua script's EXPIRE counter 0 would immediately delete the key — letting an attacker bypass MAX_VERIFY_ATTEMPTS during the final second of the token's life. Switch the comparison to <= 0. Narrow real-world impact (sub-second window, throttle still bounds the rate) but the cap should hold regardless of timing.
2026-06-01 13:14:57 +00:00
# Python imports
import os
[WEB-7946] fix: add rate limiting to email/password sign-in and sign-up endpoints (#9335) * fix: add rate limiting to email/password sign-in and sign-up endpoints All four password authentication views (app sign-in, app sign-up, space sign-in, space sign-up) extended django.views.View, so DRF's global AnonRateThrottle never ran and the endpoints accepted unlimited credential guesses with no friction (brute-force / credential stuffing, GHSA-349j). Add authentication_throttle_allows(request) at the top of each post() method — before any DB access — using the same AuthenticationThrottle already guarding the magic-code views. On rejection the view redirects with RATE_LIMIT_EXCEEDED, consistent with all other throttled auth endpoints. Default limit remains 10/minute, overridable via AUTHENTICATION_RATE_LIMIT. Co-authored-by: Plane AI <noreply@plane.so> * refactor: consolidate auth throttle into a decorator + add tests - Extract the repeated throttle-and-redirect block from the six redirect-flow auth views (email + magic, app + space) into a single throttle_auth_redirect decorator in rate_limit.py. Behaviour is unchanged: the throttle still runs before any DB access; brute-force traffic is rejected without a DB hit. - Add regression tests for the password sign-in/sign-up throttle on both app and space endpoints, mirroring the existing magic-code throttle tests. - Reset the shared AuthenticationThrottle bucket before every test in test_authentication.py. All auth endpoints share one per-IP throttle scope, so the newly-throttled password requests exhausted the budget mid-file and caused unrelated tests to trip RATE_LIMIT_EXCEEDED. --------- Co-authored-by: Plane AI <noreply@plane.so> Co-authored-by: sriramveeraghanta <veeraghanta.sriram@gmail.com>
2026-08-27 18:43:58 +00:00
from functools import wraps
fix(api): rate-limit magic-code verify, bound per-token attempts (GHSA-9pvm-fcf6-9234) (#9130) * fix(api): rate-limit magic-code verification and bound per-token attempts The magic-link sign-in / sign-up endpoints accept a 6-digit numeric code (900k-value space, 600s TTL) but never increment a failure counter on a wrong-code verify and extend django.views.View rather than DRF APIView, so DRF's AuthenticationThrottle never runs against them. The space-side generate endpoint also lacked throttle_classes. Combined, this allowed an unauthenticated attacker who knew a victim's email to brute-force the code within the TTL window and log in as the victim. - Add MAX_VERIFY_ATTEMPTS=5 in MagicCodeProvider.set_user_data: failed comparisons now persist verify_attempts in Redis under the remaining TTL and, on hitting the limit, delete the key and raise EMAIL_CODE_ATTEMPT_EXHAUSTED. This is the load-bearing fix - it caps total attempts per issued token regardless of request rate. - Add authentication_throttle_allows() so plain Django Views can apply AuthenticationThrottle without converting to APIView (would change CSRF + request-parsing semantics for the redirect-flow endpoints). - Apply the throttle to MagicSignIn/UpEndpoint and the space variants; add throttle_classes to MagicGenerateSpaceEndpoint to match its app sibling. Refs GHSA-9pvm-fcf6-9234. * fix(api): make verify-attempt increment atomic, expose throttle rate via env Address PR review feedback: - Replace the JSON read-modify-write of verify_attempts with a Lua EVAL script that INCRs a dedicated counter key and EXPIREs it only on the first increment. The previous round-trip was racy: parallel wrong-code requests could read the same value and both write the same incremented count, letting an attacker exceed MAX_VERIFY_ATTEMPTS under concurrency. Counter is now reset on each new token issuance and cleared on successful verify / exhaustion. - Make AuthenticationThrottle.rate configurable via the AUTHENTICATION_RATE_LIMIT env var (default 10/minute, down from 30 to tighten the budget on unauth auth-adjacent endpoints). Document it in deployments/aio and deployments/cli variables.env. * test(api): cover magic-code attempt cap, counter reset, and auth throttle Add the contract tests called out in the PR test plan: - TestMagicSignInVerifyAttempts: - test_exhausted_after_max_wrong_attempts: after MAX_VERIFY_ATTEMPTS wrong codes the next verify redirects with EMAIL_CODE_ATTEMPT_ EXHAUSTED_SIGN_IN and both Redis keys are deleted; a follow-up verify reports EXPIRED. - test_counter_increments_on_each_wrong_attempt: the dedicated verify_attempts counter advances by exactly one per wrong POST, matching the atomic Lua INCR. - test_counter_resets_on_token_regeneration: regenerating the magic-link clears the counter so the user isn't pre-locked-out by a prior session's wrong attempts. - TestMagicSignUpVerifyAttempts.test_signup_exhausted_after_max_wrong_attempts: the sign-up endpoint returns EMAIL_CODE_ATTEMPT_EXHAUSTED_SIGN_UP on the exhausting attempt. - TestAuthenticationThrottle: exercises authentication_throttle_allows on the plain-View redirect-flow endpoints by patching the rate down and asserting RATE_LIMIT_EXCEEDED is appended to the redirect URL once the per-IP budget is exceeded, for both magic-sign-in and magic-sign-up. Each new class clears Django cache (DRF throttle storage) and the per-email Redis keys around every test so runs are independent. * fix(api): clamp remaining_ttl to >=1 for verify-attempt counter EXPIRE ri.ttl() returns 0 when the token has less than one second remaining (Redis floors to whole seconds). The previous clamp only caught None and < 0, so a sub-second TTL would pass through and the Lua script's EXPIRE counter 0 would immediately delete the key — letting an attacker bypass MAX_VERIFY_ATTEMPTS during the final second of the token's life. Switch the comparison to <= 0. Narrow real-world impact (sub-second window, throttle still bounds the rate) but the cap should hold regardless of timing.
2026-06-01 13:14:57 +00:00
2024-05-21 09:33:01 +00:00
# Third party imports
from rest_framework.throttling import AnonRateThrottle, UserRateThrottle
2024-05-21 09:33:01 +00:00
from rest_framework import status
from rest_framework.response import Response
[WEB-7946] fix: add rate limiting to email/password sign-in and sign-up endpoints (#9335) * fix: add rate limiting to email/password sign-in and sign-up endpoints All four password authentication views (app sign-in, app sign-up, space sign-in, space sign-up) extended django.views.View, so DRF's global AnonRateThrottle never ran and the endpoints accepted unlimited credential guesses with no friction (brute-force / credential stuffing, GHSA-349j). Add authentication_throttle_allows(request) at the top of each post() method — before any DB access — using the same AuthenticationThrottle already guarding the magic-code views. On rejection the view redirects with RATE_LIMIT_EXCEEDED, consistent with all other throttled auth endpoints. Default limit remains 10/minute, overridable via AUTHENTICATION_RATE_LIMIT. Co-authored-by: Plane AI <noreply@plane.so> * refactor: consolidate auth throttle into a decorator + add tests - Extract the repeated throttle-and-redirect block from the six redirect-flow auth views (email + magic, app + space) into a single throttle_auth_redirect decorator in rate_limit.py. Behaviour is unchanged: the throttle still runs before any DB access; brute-force traffic is rejected without a DB hit. - Add regression tests for the password sign-in/sign-up throttle on both app and space endpoints, mirroring the existing magic-code throttle tests. - Reset the shared AuthenticationThrottle bucket before every test in test_authentication.py. All auth endpoints share one per-IP throttle scope, so the newly-throttled password requests exhausted the budget mid-file and caused unrelated tests to trip RATE_LIMIT_EXCEEDED. --------- Co-authored-by: Plane AI <noreply@plane.so> Co-authored-by: sriramveeraghanta <veeraghanta.sriram@gmail.com>
2026-08-27 18:43:58 +00:00
# Django imports
from django.http import HttpResponseRedirect
2024-05-21 09:33:01 +00:00
# Module imports
from plane.authentication.adapter.error import (
AuthenticationException,
AUTHENTICATION_ERROR_CODES,
)
[WEB-7946] fix: add rate limiting to email/password sign-in and sign-up endpoints (#9335) * fix: add rate limiting to email/password sign-in and sign-up endpoints All four password authentication views (app sign-in, app sign-up, space sign-in, space sign-up) extended django.views.View, so DRF's global AnonRateThrottle never ran and the endpoints accepted unlimited credential guesses with no friction (brute-force / credential stuffing, GHSA-349j). Add authentication_throttle_allows(request) at the top of each post() method — before any DB access — using the same AuthenticationThrottle already guarding the magic-code views. On rejection the view redirects with RATE_LIMIT_EXCEEDED, consistent with all other throttled auth endpoints. Default limit remains 10/minute, overridable via AUTHENTICATION_RATE_LIMIT. Co-authored-by: Plane AI <noreply@plane.so> * refactor: consolidate auth throttle into a decorator + add tests - Extract the repeated throttle-and-redirect block from the six redirect-flow auth views (email + magic, app + space) into a single throttle_auth_redirect decorator in rate_limit.py. Behaviour is unchanged: the throttle still runs before any DB access; brute-force traffic is rejected without a DB hit. - Add regression tests for the password sign-in/sign-up throttle on both app and space endpoints, mirroring the existing magic-code throttle tests. - Reset the shared AuthenticationThrottle bucket before every test in test_authentication.py. All auth endpoints share one per-IP throttle scope, so the newly-throttled password requests exhausted the budget mid-file and caused unrelated tests to trip RATE_LIMIT_EXCEEDED. --------- Co-authored-by: Plane AI <noreply@plane.so> Co-authored-by: sriramveeraghanta <veeraghanta.sriram@gmail.com>
2026-08-27 18:43:58 +00:00
from plane.authentication.utils.host import base_host
from plane.utils.path_validator import get_safe_redirect_url
2024-05-21 09:33:01 +00:00
class AuthenticationThrottle(AnonRateThrottle):
fix(api): rate-limit magic-code verify, bound per-token attempts (GHSA-9pvm-fcf6-9234) (#9130) * fix(api): rate-limit magic-code verification and bound per-token attempts The magic-link sign-in / sign-up endpoints accept a 6-digit numeric code (900k-value space, 600s TTL) but never increment a failure counter on a wrong-code verify and extend django.views.View rather than DRF APIView, so DRF's AuthenticationThrottle never runs against them. The space-side generate endpoint also lacked throttle_classes. Combined, this allowed an unauthenticated attacker who knew a victim's email to brute-force the code within the TTL window and log in as the victim. - Add MAX_VERIFY_ATTEMPTS=5 in MagicCodeProvider.set_user_data: failed comparisons now persist verify_attempts in Redis under the remaining TTL and, on hitting the limit, delete the key and raise EMAIL_CODE_ATTEMPT_EXHAUSTED. This is the load-bearing fix - it caps total attempts per issued token regardless of request rate. - Add authentication_throttle_allows() so plain Django Views can apply AuthenticationThrottle without converting to APIView (would change CSRF + request-parsing semantics for the redirect-flow endpoints). - Apply the throttle to MagicSignIn/UpEndpoint and the space variants; add throttle_classes to MagicGenerateSpaceEndpoint to match its app sibling. Refs GHSA-9pvm-fcf6-9234. * fix(api): make verify-attempt increment atomic, expose throttle rate via env Address PR review feedback: - Replace the JSON read-modify-write of verify_attempts with a Lua EVAL script that INCRs a dedicated counter key and EXPIREs it only on the first increment. The previous round-trip was racy: parallel wrong-code requests could read the same value and both write the same incremented count, letting an attacker exceed MAX_VERIFY_ATTEMPTS under concurrency. Counter is now reset on each new token issuance and cleared on successful verify / exhaustion. - Make AuthenticationThrottle.rate configurable via the AUTHENTICATION_RATE_LIMIT env var (default 10/minute, down from 30 to tighten the budget on unauth auth-adjacent endpoints). Document it in deployments/aio and deployments/cli variables.env. * test(api): cover magic-code attempt cap, counter reset, and auth throttle Add the contract tests called out in the PR test plan: - TestMagicSignInVerifyAttempts: - test_exhausted_after_max_wrong_attempts: after MAX_VERIFY_ATTEMPTS wrong codes the next verify redirects with EMAIL_CODE_ATTEMPT_ EXHAUSTED_SIGN_IN and both Redis keys are deleted; a follow-up verify reports EXPIRED. - test_counter_increments_on_each_wrong_attempt: the dedicated verify_attempts counter advances by exactly one per wrong POST, matching the atomic Lua INCR. - test_counter_resets_on_token_regeneration: regenerating the magic-link clears the counter so the user isn't pre-locked-out by a prior session's wrong attempts. - TestMagicSignUpVerifyAttempts.test_signup_exhausted_after_max_wrong_attempts: the sign-up endpoint returns EMAIL_CODE_ATTEMPT_EXHAUSTED_SIGN_UP on the exhausting attempt. - TestAuthenticationThrottle: exercises authentication_throttle_allows on the plain-View redirect-flow endpoints by patching the rate down and asserting RATE_LIMIT_EXCEEDED is appended to the redirect URL once the per-IP budget is exceeded, for both magic-sign-in and magic-sign-up. Each new class clears Django cache (DRF throttle storage) and the per-email Redis keys around every test so runs are independent. * fix(api): clamp remaining_ttl to >=1 for verify-attempt counter EXPIRE ri.ttl() returns 0 when the token has less than one second remaining (Redis floors to whole seconds). The previous clamp only caught None and < 0, so a sub-second TTL would pass through and the Lua script's EXPIRE counter 0 would immediately delete the key — letting an attacker bypass MAX_VERIFY_ATTEMPTS during the final second of the token's life. Switch the comparison to <= 0. Narrow real-world impact (sub-second window, throttle still bounds the rate) but the cap should hold regardless of timing.
2026-06-01 13:14:57 +00:00
# Rate is configurable per-deployment via the AUTHENTICATION_RATE_LIMIT
# env var (DRF format: "<num>/<period>" where period is second/minute/hour/day).
rate = os.environ.get("AUTHENTICATION_RATE_LIMIT", "10/minute")
2024-05-21 09:33:01 +00:00
scope = "authentication"
def throttle_failure_view(self, request, *args, **kwargs):
try:
raise AuthenticationException(
error_code=AUTHENTICATION_ERROR_CODES["RATE_LIMIT_EXCEEDED"],
error_message="RATE_LIMIT_EXCEEDED",
)
except AuthenticationException as e:
return Response(e.get_error_dict(), status=status.HTTP_429_TOO_MANY_REQUESTS)
fix(api): rate-limit magic-code verify, bound per-token attempts (GHSA-9pvm-fcf6-9234) (#9130) * fix(api): rate-limit magic-code verification and bound per-token attempts The magic-link sign-in / sign-up endpoints accept a 6-digit numeric code (900k-value space, 600s TTL) but never increment a failure counter on a wrong-code verify and extend django.views.View rather than DRF APIView, so DRF's AuthenticationThrottle never runs against them. The space-side generate endpoint also lacked throttle_classes. Combined, this allowed an unauthenticated attacker who knew a victim's email to brute-force the code within the TTL window and log in as the victim. - Add MAX_VERIFY_ATTEMPTS=5 in MagicCodeProvider.set_user_data: failed comparisons now persist verify_attempts in Redis under the remaining TTL and, on hitting the limit, delete the key and raise EMAIL_CODE_ATTEMPT_EXHAUSTED. This is the load-bearing fix - it caps total attempts per issued token regardless of request rate. - Add authentication_throttle_allows() so plain Django Views can apply AuthenticationThrottle without converting to APIView (would change CSRF + request-parsing semantics for the redirect-flow endpoints). - Apply the throttle to MagicSignIn/UpEndpoint and the space variants; add throttle_classes to MagicGenerateSpaceEndpoint to match its app sibling. Refs GHSA-9pvm-fcf6-9234. * fix(api): make verify-attempt increment atomic, expose throttle rate via env Address PR review feedback: - Replace the JSON read-modify-write of verify_attempts with a Lua EVAL script that INCRs a dedicated counter key and EXPIREs it only on the first increment. The previous round-trip was racy: parallel wrong-code requests could read the same value and both write the same incremented count, letting an attacker exceed MAX_VERIFY_ATTEMPTS under concurrency. Counter is now reset on each new token issuance and cleared on successful verify / exhaustion. - Make AuthenticationThrottle.rate configurable via the AUTHENTICATION_RATE_LIMIT env var (default 10/minute, down from 30 to tighten the budget on unauth auth-adjacent endpoints). Document it in deployments/aio and deployments/cli variables.env. * test(api): cover magic-code attempt cap, counter reset, and auth throttle Add the contract tests called out in the PR test plan: - TestMagicSignInVerifyAttempts: - test_exhausted_after_max_wrong_attempts: after MAX_VERIFY_ATTEMPTS wrong codes the next verify redirects with EMAIL_CODE_ATTEMPT_ EXHAUSTED_SIGN_IN and both Redis keys are deleted; a follow-up verify reports EXPIRED. - test_counter_increments_on_each_wrong_attempt: the dedicated verify_attempts counter advances by exactly one per wrong POST, matching the atomic Lua INCR. - test_counter_resets_on_token_regeneration: regenerating the magic-link clears the counter so the user isn't pre-locked-out by a prior session's wrong attempts. - TestMagicSignUpVerifyAttempts.test_signup_exhausted_after_max_wrong_attempts: the sign-up endpoint returns EMAIL_CODE_ATTEMPT_EXHAUSTED_SIGN_UP on the exhausting attempt. - TestAuthenticationThrottle: exercises authentication_throttle_allows on the plain-View redirect-flow endpoints by patching the rate down and asserting RATE_LIMIT_EXCEEDED is appended to the redirect URL once the per-IP budget is exceeded, for both magic-sign-in and magic-sign-up. Each new class clears Django cache (DRF throttle storage) and the per-email Redis keys around every test so runs are independent. * fix(api): clamp remaining_ttl to >=1 for verify-attempt counter EXPIRE ri.ttl() returns 0 when the token has less than one second remaining (Redis floors to whole seconds). The previous clamp only caught None and < 0, so a sub-second TTL would pass through and the Lua script's EXPIRE counter 0 would immediately delete the key — letting an attacker bypass MAX_VERIFY_ATTEMPTS during the final second of the token's life. Switch the comparison to <= 0. Narrow real-world impact (sub-second window, throttle still bounds the rate) but the cap should hold regardless of timing.
2026-06-01 13:14:57 +00:00
def authentication_throttle_allows(request):
"""
Apply AuthenticationThrottle to a plain django.views.View request.
DRF's throttle_classes only run inside APIView.initial(); the magic
sign-in / sign-up endpoints extend django.views.View to return
HttpResponseRedirect from a form POST flow, so they need a manual
throttle check. Returns True if the request is allowed through,
False if it should be rejected with a RATE_LIMIT_EXCEEDED error.
"""
throttle = AuthenticationThrottle()
# SimpleRateThrottle.allow_request only reads request.META and
# request.user, both available on a plain Django HttpRequest.
return throttle.allow_request(request, None)
[WEB-7946] fix: add rate limiting to email/password sign-in and sign-up endpoints (#9335) * fix: add rate limiting to email/password sign-in and sign-up endpoints All four password authentication views (app sign-in, app sign-up, space sign-in, space sign-up) extended django.views.View, so DRF's global AnonRateThrottle never ran and the endpoints accepted unlimited credential guesses with no friction (brute-force / credential stuffing, GHSA-349j). Add authentication_throttle_allows(request) at the top of each post() method — before any DB access — using the same AuthenticationThrottle already guarding the magic-code views. On rejection the view redirects with RATE_LIMIT_EXCEEDED, consistent with all other throttled auth endpoints. Default limit remains 10/minute, overridable via AUTHENTICATION_RATE_LIMIT. Co-authored-by: Plane AI <noreply@plane.so> * refactor: consolidate auth throttle into a decorator + add tests - Extract the repeated throttle-and-redirect block from the six redirect-flow auth views (email + magic, app + space) into a single throttle_auth_redirect decorator in rate_limit.py. Behaviour is unchanged: the throttle still runs before any DB access; brute-force traffic is rejected without a DB hit. - Add regression tests for the password sign-in/sign-up throttle on both app and space endpoints, mirroring the existing magic-code throttle tests. - Reset the shared AuthenticationThrottle bucket before every test in test_authentication.py. All auth endpoints share one per-IP throttle scope, so the newly-throttled password requests exhausted the budget mid-file and caused unrelated tests to trip RATE_LIMIT_EXCEEDED. --------- Co-authored-by: Plane AI <noreply@plane.so> Co-authored-by: sriramveeraghanta <veeraghanta.sriram@gmail.com>
2026-08-27 18:43:58 +00:00
def throttle_auth_redirect(*, is_app=False, is_space=False):
"""
Decorator for redirect-flow ``django.views.View`` POST handlers.
Applies AuthenticationThrottle before the wrapped handler runs; when the
per-IP budget is exceeded it short-circuits with a RATE_LIMIT_EXCEEDED
redirect to the auth error page (the same behaviour every throttled auth
endpoint uses). The throttle runs before any DB access in the handler, so
brute-force traffic is rejected without touching the database.
Pass ``is_app=True`` for /app auth views and ``is_space=True`` for /spaces
auth views so the redirect targets the correct base host.
"""
def decorator(post_method):
@wraps(post_method)
def wrapper(self, request, *args, **kwargs):
if not authentication_throttle_allows(request):
exc = AuthenticationException(
error_code=AUTHENTICATION_ERROR_CODES["RATE_LIMIT_EXCEEDED"],
error_message="RATE_LIMIT_EXCEEDED",
)
url = get_safe_redirect_url(
base_url=base_host(request=request, is_app=is_app, is_space=is_space),
next_path=request.POST.get("next_path"),
params=exc.get_error_dict(),
)
return HttpResponseRedirect(url)
return post_method(self, request, *args, **kwargs)
return wrapper
return decorator
class EmailVerificationThrottle(UserRateThrottle):
"""
Throttle for email verification code generation.
Limits to 3 requests per hour per user to prevent abuse.
"""
rate = "3/hour"
scope = "email_verification"
def throttle_failure_view(self, request, *args, **kwargs):
try:
raise AuthenticationException(
error_code=AUTHENTICATION_ERROR_CODES["RATE_LIMIT_EXCEEDED"],
error_message="RATE_LIMIT_EXCEEDED",
)
except AuthenticationException as e:
return Response(e.get_error_dict(), status=status.HTTP_429_TOO_MANY_REQUESTS)