| 1 |
""" |
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
Rate limiting in this implementation relies on a cache and uses non-atomic |
| 5 |
operations, making it vulnerable to race conditions. As a result, users may |
| 6 |
occasionally bypass the intended rate limit due to concurrent access. However, |
| 7 |
such race conditions are rare in practice. For example, if the limit is set to |
| 8 |
10 requests per minute and a large number of parallel processes attempt to test |
| 9 |
that limit, you may occasionally observe slight overruns—such as 11 or 12 |
| 10 |
requests slipping through. Nevertheless, exceeding the limit by a large margin |
| 11 |
is highly unlikely due to the low probability of many processes entering the |
| 12 |
critical non-atomic code section simultaneously. |
| 13 |
""" |
| 14 |
|
| 15 |
import hashlib |
| 16 |
import ipaddress |
| 17 |
import time |
| 18 |
from collections import namedtuple |
| 19 |
from dataclasses import dataclass |
| 20 |
from http import HTTPStatus |
| 21 |
|
| 22 |
from django.core.cache import cache |
| 23 |
from django.core.exceptions import ImproperlyConfigured |
| 24 |
from django.http import HttpRequest, HttpResponse |
| 25 |
from django.shortcuts import render |
| 26 |
from django.template.exceptions import TemplateDoesNotExist |
| 27 |
|
| 28 |
from allauth.core.exceptions import RateLimited |
| 29 |
|
| 30 |
|
| 31 |
Rate = namedtuple("Rate", "amount duration per") |
| 32 |
|
| 33 |
|
| 34 |
@dataclass |
| 35 |
class SingleRateLimitUsage: |
| 36 |
cache_key: str |
| 37 |
cache_duration: float | int |
| 38 |
timestamp: float |
| 39 |
|
| 40 |
def rollback(self) -> None: |
| 41 |
history = cache.get(self.cache_key, []) |
| 42 |
history = [ts for ts in history if ts != self.timestamp] |
| 43 |
cache.set(self.cache_key, history, self.cache_duration) |
| 44 |
|
| 45 |
|
| 46 |
@dataclass |
| 47 |
class RateLimitUsage: |
| 48 |
usage: list[SingleRateLimitUsage] |
| 49 |
|
| 50 |
def rollback(self) -> None: |
| 51 |
for usage in self.usage: |
| 52 |
usage.rollback() |
| 53 |
|
| 54 |
|
| 55 |
def parse_duration(duration) -> int | float: |
| 56 |
if len(duration) == 0: |
| 57 |
raise ValueError(duration) |
| 58 |
unit = duration[-1] |
| 59 |
value = duration[0:-1] |
| 60 |
unit_map = {"s": 1, "m": 60, "h": 3600, "d": 86400} |
| 61 |
if unit not in unit_map: |
| 62 |
raise ValueError(f"Invalid duration unit: {unit}") |
| 63 |
if len(value) == 0: |
| 64 |
value = 1 |
| 65 |
else: |
| 66 |
value = float(value) |
| 67 |
return value * unit_map[unit] |
| 68 |
|
| 69 |
|
| 70 |
def parse_rate(rate: str) -> Rate: |
| 71 |
parts = rate.split("/") |
| 72 |
if len(parts) == 2: |
| 73 |
amount, duration = parts |
| 74 |
per = "ip" |
| 75 |
elif len(parts) == 3: |
| 76 |
amount, duration, per = parts |
| 77 |
else: |
| 78 |
raise ValueError(rate) |
| 79 |
amount_v = int(amount) |
| 80 |
duration_v = parse_duration(duration) |
| 81 |
return Rate(amount_v, duration_v, per) |
| 82 |
|
| 83 |
|
| 84 |
def parse_rates(rates: str | None) -> list[Rate]: |
| 85 |
ret = [] |
| 86 |
if rates: |
| 87 |
rates = rates.strip() |
| 88 |
if rates: |
| 89 |
parts = rates.split(",") |
| 90 |
for part in parts: |
| 91 |
ret.append(parse_rate(part.strip())) |
| 92 |
return ret |
| 93 |
|
| 94 |
|
| 95 |
def truncate_ip(ip: str) -> str: |
| 96 |
from allauth import app_settings as allauth_settings |
| 97 |
|
| 98 |
try: |
| 99 |
addr = ipaddress.ip_address(ip) |
| 100 |
except ValueError: |
| 101 |
return ip |
| 102 |
|
| 103 |
if isinstance(addr, ipaddress.IPv6Address): |
| 104 |
prefix = allauth_settings.RATE_LIMIT_IPV6_PREFIX |
| 105 |
network = ipaddress.IPv6Network(f"{addr}/{prefix}", strict=False) |
| 106 |
return str(network.network_address) |
| 107 |
return ip |
| 108 |
|
| 109 |
|
| 110 |
def get_ip(request: HttpRequest) -> str: |
| 111 |
from allauth.account.adapter import get_adapter |
| 112 |
|
| 113 |
ip = get_adapter().get_client_ip(request) |
| 114 |
return truncate_ip(ip) |
| 115 |
|
| 116 |
|
| 117 |
def get_cache_key( |
| 118 |
request: HttpRequest, *, action: str, rate: Rate, key=None, user=None |
| 119 |
) -> str: |
| 120 |
source: tuple[str, ...] |
| 121 |
if rate.per == "ip": |
| 122 |
source = ("ip", get_ip(request)) |
| 123 |
elif rate.per == "user": |
| 124 |
if user is None: |
| 125 |
if not request.user.is_authenticated: |
| 126 |
raise ImproperlyConfigured( |
| 127 |
"ratelimit configured per user but used anonymously" |
| 128 |
) |
| 129 |
user = request.user |
| 130 |
source = ("user", str(user.pk)) |
| 131 |
elif rate.per == "key": |
| 132 |
if key is None: |
| 133 |
raise ImproperlyConfigured( |
| 134 |
"ratelimit configured per key but no key specified" |
| 135 |
) |
| 136 |
key_hash = hashlib.sha256(key.encode("utf8")).hexdigest() |
| 137 |
source = (key_hash,) |
| 138 |
else: |
| 139 |
raise ValueError(rate.per) |
| 140 |
keys = ["allauth", "rl", action, *source] |
| 141 |
return ":".join(keys) |
| 142 |
|
| 143 |
|
| 144 |
def apply_rate( |
| 145 |
history: list[float], now: float, rate: Rate, *, dry_run: bool = False |
| 146 |
) -> tuple[bool, list[float]]: |
| 147 |
"""Apply ``rate`` to the hit timestamps at ``now``, returning |
| 148 |
``(allowed, history)``: expired timestamps are dropped and, unless |
| 149 |
``dry_run``, an allowed hit is recorded. I/O-free, so needs no cache. |
| 150 |
""" |
| 151 |
while history and history[-1] <= now - rate.duration: |
| 152 |
history.pop() |
| 153 |
allowed = len(history) < rate.amount |
| 154 |
if allowed and not dry_run: |
| 155 |
history.insert(0, now) |
| 156 |
return allowed, history |
| 157 |
|
| 158 |
|
| 159 |
def _consume_single_rate( |
| 160 |
request: HttpRequest, |
| 161 |
*, |
| 162 |
action: str, |
| 163 |
rate: Rate, |
| 164 |
key=None, |
| 165 |
user=None, |
| 166 |
dry_run: bool = False, |
| 167 |
raise_exception: bool = False, |
| 168 |
) -> SingleRateLimitUsage | None: |
| 169 |
cache_key = get_cache_key(request, action=action, rate=rate, key=key, user=user) |
| 170 |
history = cache.get(cache_key, []) |
| 171 |
now = time.time() |
| 172 |
allowed, history = apply_rate(history, now, rate, dry_run=dry_run) |
| 173 |
if allowed: |
| 174 |
usage = SingleRateLimitUsage( |
| 175 |
cache_key=cache_key, timestamp=now, cache_duration=rate.duration |
| 176 |
) |
| 177 |
if not dry_run: |
| 178 |
cache.set(cache_key, history, rate.duration) |
| 179 |
else: |
| 180 |
usage = None |
| 181 |
if raise_exception: |
| 182 |
raise RateLimited |
| 183 |
return usage |
| 184 |
|
| 185 |
|
| 186 |
def consume( |
| 187 |
request: HttpRequest, |
| 188 |
*, |
| 189 |
action: str, |
| 190 |
config: dict[str, str], |
| 191 |
key=None, |
| 192 |
user=None, |
| 193 |
dry_run: bool = False, |
| 194 |
limit_get: bool = False, |
| 195 |
raise_exception: bool = False, |
| 196 |
) -> RateLimitUsage | None: |
| 197 |
usage = RateLimitUsage(usage=[]) |
| 198 |
if (not limit_get) and request.method == "GET": |
| 199 |
return usage |
| 200 |
rates = parse_rates(config.get(action)) |
| 201 |
if not rates: |
| 202 |
return usage |
| 203 |
allowed = True |
| 204 |
for rate in rates: |
| 205 |
single_usage = _consume_single_rate( |
| 206 |
request, |
| 207 |
action=action, |
| 208 |
rate=rate, |
| 209 |
key=key, |
| 210 |
user=user, |
| 211 |
dry_run=dry_run, |
| 212 |
raise_exception=raise_exception, |
| 213 |
) |
| 214 |
if not single_usage: |
| 215 |
allowed = False |
| 216 |
break |
| 217 |
usage.usage.append(single_usage) |
| 218 |
return usage if allowed else None |
| 219 |
|
| 220 |
|
| 221 |
def handler429(request: HttpRequest) -> HttpResponse: |
| 222 |
from allauth.account import app_settings |
| 223 |
|
| 224 |
try: |
| 225 |
return render( |
| 226 |
request, |
| 227 |
f"429.{app_settings.TEMPLATE_EXTENSION}", |
| 228 |
status=HTTPStatus.TOO_MANY_REQUESTS, |
| 229 |
) |
| 230 |
except TemplateDoesNotExist: |
| 231 |
content = """<html> |
| 232 |
<head><title>Too Many Requests</title></head> |
| 233 |
<body> |
| 234 |
<h1>429 Too Many Requests</h1> |
| 235 |
<p>You have sent too many requests. Please try again later.</p> |
| 236 |
</body> |
| 237 |
</html>""" |
| 238 |
return HttpResponse( |
| 239 |
content=content, |
| 240 |
content_type="text/html", |
| 241 |
status=HTTPStatus.TOO_MANY_REQUESTS, |
| 242 |
) |
| 243 |
|
| 244 |
|
| 245 |
def clear( |
| 246 |
request: HttpRequest, *, config: dict, action: str, key=None, user=None |
| 247 |
) -> None: |
| 248 |
rates = parse_rates(config.get(action)) |
| 249 |
for rate in rates: |
| 250 |
cache_key = get_cache_key(request, action=action, rate=rate, key=key, user=user) |
| 251 |
cache.delete(cache_key) |