| 1 |
import hashlib |
| 2 |
import time |
| 3 |
from typing import Dict, List, Optional, Tuple |
| 4 |
|
| 5 |
from django.core.cache import cache as default_cache |
| 6 |
from django.core.exceptions import ImproperlyConfigured |
| 7 |
from django.http import HttpRequest |
| 8 |
|
| 9 |
|
| 10 |
class BaseThrottle: |
| 11 |
""" |
| 12 |
Rate throttling of requests. |
| 13 |
""" |
| 14 |
|
| 15 |
def allow_request(self, request: HttpRequest) -> bool: |
| 16 |
""" |
| 17 |
Return `True` if the request should be allowed, `False` otherwise. |
| 18 |
""" |
| 19 |
raise NotImplementedError(".allow_request() must be overridden") |
| 20 |
|
| 21 |
def get_ident(self, request: HttpRequest) -> Optional[str]: |
| 22 |
""" |
| 23 |
Identify the machine making the request by parsing HTTP_X_FORWARDED_FOR |
| 24 |
if present and number of proxies is > 0. If not use all of |
| 25 |
HTTP_X_FORWARDED_FOR if it is available, if not use REMOTE_ADDR. |
| 26 |
""" |
| 27 |
from ninja.conf import settings |
| 28 |
|
| 29 |
xff = request.META.get("HTTP_X_FORWARDED_FOR") |
| 30 |
remote_addr = request.META.get("REMOTE_ADDR") |
| 31 |
num_proxies = settings.NUM_PROXIES |
| 32 |
|
| 33 |
if num_proxies is not None: |
| 34 |
if num_proxies == 0 or xff is None: |
| 35 |
return remote_addr |
| 36 |
addrs: List[str] = xff.split(",") |
| 37 |
client_addr = addrs[-min(num_proxies, len(addrs))] |
| 38 |
return client_addr.strip() |
| 39 |
|
| 40 |
return "".join(xff.split()) if xff else remote_addr |
| 41 |
|
| 42 |
def wait(self) -> Optional[float]: |
| 43 |
""" |
| 44 |
Optionally, return a recommended number of seconds to wait before |
| 45 |
the next request. |
| 46 |
""" |
| 47 |
return None |
| 48 |
|
| 49 |
|
| 50 |
class SimpleRateThrottle(BaseThrottle): |
| 51 |
""" |
| 52 |
A simple cache implementation, that only requires `.get_cache_key()` |
| 53 |
to be overridden. |
| 54 |
|
| 55 |
The rate (requests / seconds) is set by a `rate` attribute on the Throttle |
| 56 |
class. The attribute is a string of the form 'number_of_requests/period'. |
| 57 |
|
| 58 |
Period should be one of: ('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day') |
| 59 |
|
| 60 |
Previous request information used for throttling is stored in the cache. |
| 61 |
""" |
| 62 |
|
| 63 |
from ninja.conf import settings |
| 64 |
|
| 65 |
cache = default_cache |
| 66 |
timer = time.time |
| 67 |
cache_format = "throttle_%(scope)s_%(ident)s" |
| 68 |
scope: Optional[str] = None |
| 69 |
THROTTLE_RATES: Dict[str, Optional[str]] = settings.DEFAULT_THROTTLE_RATES |
| 70 |
_PERIODS = { |
| 71 |
"s": 1, |
| 72 |
"m": 60, |
| 73 |
"h": 60 * 60, |
| 74 |
"d": 60 * 60 * 24, |
| 75 |
"sec": 1, |
| 76 |
"min": 60, |
| 77 |
"hour": 60 * 60, |
| 78 |
"day": 60 * 60 * 24, |
| 79 |
} |
| 80 |
|
| 81 |
def __init__(self, rate: Optional[str] = None): |
| 82 |
self.rate: Optional[str] |
| 83 |
if rate: |
| 84 |
self.rate = rate |
| 85 |
else: |
| 86 |
self.rate = self.get_rate() |
| 87 |
self.num_requests, self.duration = self.parse_rate(self.rate) |
| 88 |
|
| 89 |
def get_cache_key(self, request: HttpRequest) -> Optional[str]: |
| 90 |
""" |
| 91 |
Should return a unique cache-key which can be used for throttling. |
| 92 |
Must be overridden. |
| 93 |
|
| 94 |
May return `None` if the request should not be throttled. |
| 95 |
""" |
| 96 |
raise NotImplementedError(".get_cache_key() must be overridden") |
| 97 |
|
| 98 |
def get_rate(self) -> Optional[str]: |
| 99 |
""" |
| 100 |
Determine the string representation of the allowed request rate. |
| 101 |
""" |
| 102 |
if not getattr(self, "scope", None): |
| 103 |
msg = f"You must set either `.scope` or `.rate` for '{self.__class__.__name__}' throttle" |
| 104 |
raise ImproperlyConfigured(msg) |
| 105 |
|
| 106 |
try: |
| 107 |
return self.THROTTLE_RATES[self.scope] |
| 108 |
except KeyError: |
| 109 |
msg = f"No default throttle rate set for '{self.scope}' scope" |
| 110 |
raise ImproperlyConfigured(msg) from None |
| 111 |
|
| 112 |
def parse_rate(self, rate: Optional[str]) -> Tuple[Optional[int], Optional[int]]: |
| 113 |
""" |
| 114 |
Given the request rate string, return a two tuple of: |
| 115 |
<allowed number of requests>, <period of time in seconds> |
| 116 |
""" |
| 117 |
if rate is None: |
| 118 |
return (None, None) |
| 119 |
|
| 120 |
try: |
| 121 |
count, rest = rate.split("/", 1) |
| 122 |
|
| 123 |
for unit in self._PERIODS: |
| 124 |
if rest.endswith(unit): |
| 125 |
multi = int(rest[: -len(unit)]) if rest[: -len(unit)] else 1 |
| 126 |
period = self._PERIODS[unit] |
| 127 |
break |
| 128 |
else: |
| 129 |
multi, period = int(rest), 1 |
| 130 |
|
| 131 |
return int(count), multi * period |
| 132 |
|
| 133 |
except (ValueError, IndexError): |
| 134 |
raise ValueError(f"Invalid rate format: {rate}") from None |
| 135 |
|
| 136 |
def allow_request(self, request: HttpRequest) -> bool: |
| 137 |
""" |
| 138 |
Implement the check to see if the request should be throttled. |
| 139 |
|
| 140 |
On success calls `throttle_success`. |
| 141 |
On failure calls `throttle_failure`. |
| 142 |
""" |
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
self.key = self.get_cache_key(request) |
| 147 |
if self.key is None: |
| 148 |
return True |
| 149 |
|
| 150 |
self.history = self.cache.get(self.key, []) |
| 151 |
self.now = self.timer() |
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
while self.history and self.history[-1] <= self.now - self.duration: |
| 156 |
self.history.pop() |
| 157 |
if len(self.history) >= self.num_requests: |
| 158 |
return self.throttle_failure() |
| 159 |
return self.throttle_success() |
| 160 |
|
| 161 |
def throttle_success(self) -> bool: |
| 162 |
""" |
| 163 |
Inserts the current request's timestamp along with the key |
| 164 |
into the cache. |
| 165 |
""" |
| 166 |
self.history.insert(0, self.now) |
| 167 |
self.cache.set(self.key, self.history, self.duration) |
| 168 |
return True |
| 169 |
|
| 170 |
def throttle_failure(self) -> bool: |
| 171 |
""" |
| 172 |
Called when a request to the API has failed due to throttling. |
| 173 |
""" |
| 174 |
return False |
| 175 |
|
| 176 |
def wait(self) -> Optional[float]: |
| 177 |
""" |
| 178 |
Returns the recommended next request time in seconds. |
| 179 |
""" |
| 180 |
if self.history: |
| 181 |
remaining_duration = self.duration - (self.now - self.history[-1]) |
| 182 |
else: |
| 183 |
remaining_duration = self.duration |
| 184 |
|
| 185 |
available_requests = self.num_requests - len(self.history) + 1 |
| 186 |
if available_requests <= 0: |
| 187 |
return None |
| 188 |
|
| 189 |
return remaining_duration / float(available_requests) |
| 190 |
|
| 191 |
|
| 192 |
class AnonRateThrottle(SimpleRateThrottle): |
| 193 |
""" |
| 194 |
Limits the rate of API calls that may be made by a anonymous users. |
| 195 |
|
| 196 |
The IP address of the request will be used as the unique cache key. |
| 197 |
""" |
| 198 |
|
| 199 |
scope = "anon" |
| 200 |
|
| 201 |
def get_cache_key(self, request: HttpRequest) -> Optional[str]: |
| 202 |
if getattr(request, "auth", None) is not None: |
| 203 |
return None |
| 204 |
|
| 205 |
return self.cache_format % { |
| 206 |
"scope": self.scope, |
| 207 |
"ident": self.get_ident(request), |
| 208 |
} |
| 209 |
|
| 210 |
|
| 211 |
class AuthRateThrottle(SimpleRateThrottle): |
| 212 |
""" |
| 213 |
Limits the rate of API calls that may be made by a given user. |
| 214 |
|
| 215 |
The string representation of request.auth object will be used as a unique cache key. |
| 216 |
If you use custom auth objects make sure to implement __str__ method. |
| 217 |
For anonymous requests, the IP address of the request will be used. |
| 218 |
""" |
| 219 |
|
| 220 |
scope = "auth" |
| 221 |
|
| 222 |
def get_cache_key(self, request: HttpRequest) -> str: |
| 223 |
if getattr(request, "auth", None) is not None: |
| 224 |
ident = hashlib.sha256(str(request.auth).encode()).hexdigest() |
| 225 |
|
| 226 |
else: |
| 227 |
ident = self.get_ident(request) |
| 228 |
|
| 229 |
return self.cache_format % {"scope": self.scope, "ident": ident} |
| 230 |
|
| 231 |
|
| 232 |
class UserRateThrottle(SimpleRateThrottle): |
| 233 |
""" |
| 234 |
Limits the rate of API calls that may be made by a given user. |
| 235 |
|
| 236 |
The user id will be used as a unique cache key if the user is |
| 237 |
authenticated. For anonymous requests, the IP address of the request will |
| 238 |
be used. |
| 239 |
""" |
| 240 |
|
| 241 |
scope = "user" |
| 242 |
|
| 243 |
def get_cache_key(self, request: HttpRequest) -> str: |
| 244 |
if request.user and request.user.is_authenticated: |
| 245 |
ident = request.user.pk |
| 246 |
else: |
| 247 |
ident = self.get_ident(request) |
| 248 |
|
| 249 |
return self.cache_format % {"scope": self.scope, "ident": ident} |