| 1 |
""" |
| 2 |
Tests for the throttling implementations in the permissions module. |
| 3 |
""" |
| 4 |
|
| 5 |
import pytest |
| 6 |
from django.contrib.auth.models import User |
| 7 |
from django.core.cache import cache |
| 8 |
from django.core.exceptions import ImproperlyConfigured |
| 9 |
from django.http import HttpRequest |
| 10 |
from django.test import TestCase |
| 11 |
|
| 12 |
from rest_framework.request import Request |
| 13 |
from rest_framework.response import Response |
| 14 |
from rest_framework.settings import api_settings |
| 15 |
from rest_framework.test import APIRequestFactory, force_authenticate |
| 16 |
from rest_framework.throttling import ( |
| 17 |
AnonRateThrottle, BaseThrottle, ScopedRateThrottle, SimpleRateThrottle, |
| 18 |
UserRateThrottle |
| 19 |
) |
| 20 |
from rest_framework.views import APIView |
| 21 |
|
| 22 |
|
| 23 |
class User3SecRateThrottle(UserRateThrottle): |
| 24 |
rate = '3/sec' |
| 25 |
scope = 'seconds' |
| 26 |
|
| 27 |
|
| 28 |
class User3MinRateThrottle(UserRateThrottle): |
| 29 |
rate = '3/min' |
| 30 |
scope = 'minutes' |
| 31 |
|
| 32 |
|
| 33 |
class User6MinRateThrottle(UserRateThrottle): |
| 34 |
rate = '6/min' |
| 35 |
scope = 'minutes' |
| 36 |
|
| 37 |
|
| 38 |
class NonTimeThrottle(BaseThrottle): |
| 39 |
def allow_request(self, request, view): |
| 40 |
if not hasattr(self.__class__, 'called'): |
| 41 |
self.__class__.called = True |
| 42 |
return True |
| 43 |
return False |
| 44 |
|
| 45 |
|
| 46 |
class MockView_DoubleThrottling(APIView): |
| 47 |
throttle_classes = (User3SecRateThrottle, User6MinRateThrottle,) |
| 48 |
|
| 49 |
def get(self, request): |
| 50 |
return Response('foo') |
| 51 |
|
| 52 |
|
| 53 |
class MockView(APIView): |
| 54 |
throttle_classes = (User3SecRateThrottle,) |
| 55 |
|
| 56 |
def get(self, request): |
| 57 |
return Response('foo') |
| 58 |
|
| 59 |
|
| 60 |
class MockView_MinuteThrottling(APIView): |
| 61 |
throttle_classes = (User3MinRateThrottle,) |
| 62 |
|
| 63 |
def get(self, request): |
| 64 |
return Response('foo') |
| 65 |
|
| 66 |
|
| 67 |
class MockView_NonTimeThrottling(APIView): |
| 68 |
throttle_classes = (NonTimeThrottle,) |
| 69 |
|
| 70 |
def get(self, request): |
| 71 |
return Response('foo') |
| 72 |
|
| 73 |
|
| 74 |
class ThrottlingTests(TestCase): |
| 75 |
def setUp(self): |
| 76 |
""" |
| 77 |
Reset the cache so that no throttles will be active |
| 78 |
""" |
| 79 |
cache.clear() |
| 80 |
self.factory = APIRequestFactory() |
| 81 |
|
| 82 |
def test_requests_are_throttled(self): |
| 83 |
""" |
| 84 |
Ensure request rate is limited |
| 85 |
""" |
| 86 |
request = self.factory.get('/') |
| 87 |
for dummy in range(4): |
| 88 |
response = MockView.as_view()(request) |
| 89 |
assert response.status_code == 429 |
| 90 |
|
| 91 |
def set_throttle_timer(self, view, value): |
| 92 |
""" |
| 93 |
Explicitly set the timer, overriding time.time() |
| 94 |
""" |
| 95 |
for cls in view.throttle_classes: |
| 96 |
cls.timer = lambda self: value |
| 97 |
|
| 98 |
def test_request_throttling_expires(self): |
| 99 |
""" |
| 100 |
Ensure request rate is limited for a limited duration only |
| 101 |
""" |
| 102 |
self.set_throttle_timer(MockView, 0) |
| 103 |
|
| 104 |
request = self.factory.get('/') |
| 105 |
for dummy in range(4): |
| 106 |
response = MockView.as_view()(request) |
| 107 |
assert response.status_code == 429 |
| 108 |
|
| 109 |
# Advance the timer by one second |
| 110 |
self.set_throttle_timer(MockView, 1) |
| 111 |
|
| 112 |
response = MockView.as_view()(request) |
| 113 |
assert response.status_code == 200 |
| 114 |
|
| 115 |
def ensure_is_throttled(self, view, expect): |
| 116 |
request = self.factory.get('/') |
| 117 |
request.user = User.objects.create(username='a') |
| 118 |
for dummy in range(3): |
| 119 |
view.as_view()(request) |
| 120 |
request.user = User.objects.create(username='b') |
| 121 |
response = view.as_view()(request) |
| 122 |
assert response.status_code == expect |
| 123 |
|
| 124 |
def test_request_throttling_is_per_user(self): |
| 125 |
""" |
| 126 |
Ensure request rate is only limited per user, not globally for |
| 127 |
PerUserThrottles |
| 128 |
""" |
| 129 |
self.ensure_is_throttled(MockView, 200) |
| 130 |
|
| 131 |
def test_request_throttling_multiple_throttles(self): |
| 132 |
""" |
| 133 |
Ensure all throttle classes see each request even when the request is |
| 134 |
already being throttled |
| 135 |
""" |
| 136 |
self.set_throttle_timer(MockView_DoubleThrottling, 0) |
| 137 |
request = self.factory.get('/') |
| 138 |
for dummy in range(4): |
| 139 |
response = MockView_DoubleThrottling.as_view()(request) |
| 140 |
assert response.status_code == 429 |
| 141 |
assert int(response['retry-after']) == 1 |
| 142 |
|
| 143 |
# At this point our client made 4 requests (one was throttled) in a |
| 144 |
# second. If we advance the timer by one additional second, the client |
| 145 |
# should be allowed to make 2 more before being throttled by the 2nd |
| 146 |
# throttle class, which has a limit of 6 per minute. |
| 147 |
self.set_throttle_timer(MockView_DoubleThrottling, 1) |
| 148 |
for dummy in range(2): |
| 149 |
response = MockView_DoubleThrottling.as_view()(request) |
| 150 |
assert response.status_code == 200 |
| 151 |
|
| 152 |
response = MockView_DoubleThrottling.as_view()(request) |
| 153 |
assert response.status_code == 429 |
| 154 |
assert int(response['retry-after']) == 59 |
| 155 |
|
| 156 |
# Just to make sure check again after two more seconds. |
| 157 |
self.set_throttle_timer(MockView_DoubleThrottling, 2) |
| 158 |
response = MockView_DoubleThrottling.as_view()(request) |
| 159 |
assert response.status_code == 429 |
| 160 |
assert int(response['retry-after']) == 58 |
| 161 |
|
| 162 |
def test_throttle_rate_change_negative(self): |
| 163 |
self.set_throttle_timer(MockView_DoubleThrottling, 0) |
| 164 |
request = self.factory.get('/') |
| 165 |
for dummy in range(24): |
| 166 |
response = MockView_DoubleThrottling.as_view()(request) |
| 167 |
assert response.status_code == 429 |
| 168 |
assert int(response['retry-after']) == 60 |
| 169 |
|
| 170 |
previous_rate = User3SecRateThrottle.rate |
| 171 |
try: |
| 172 |
User3SecRateThrottle.rate = '1/sec' |
| 173 |
|
| 174 |
for dummy in range(24): |
| 175 |
response = MockView_DoubleThrottling.as_view()(request) |
| 176 |
|
| 177 |
assert response.status_code == 429 |
| 178 |
assert int(response['retry-after']) == 60 |
| 179 |
finally: |
| 180 |
# reset |
| 181 |
User3SecRateThrottle.rate = previous_rate |
| 182 |
|
| 183 |
def ensure_response_header_contains_proper_throttle_field(self, view, expected_headers): |
| 184 |
""" |
| 185 |
Ensure the response returns an Retry-After field with status and next attributes |
| 186 |
set properly. |
| 187 |
""" |
| 188 |
request = self.factory.get('/') |
| 189 |
for timer, expect in expected_headers: |
| 190 |
self.set_throttle_timer(view, timer) |
| 191 |
response = view.as_view()(request) |
| 192 |
if expect is not None: |
| 193 |
assert response['Retry-After'] == expect |
| 194 |
else: |
| 195 |
assert 'Retry-After' not in response |
| 196 |
|
| 197 |
def test_seconds_fields(self): |
| 198 |
""" |
| 199 |
Ensure for second based throttles. |
| 200 |
""" |
| 201 |
self.ensure_response_header_contains_proper_throttle_field( |
| 202 |
MockView, ( |
| 203 |
(0, None), |
| 204 |
(0, None), |
| 205 |
(0, None), |
| 206 |
(0, '1') |
| 207 |
) |
| 208 |
) |
| 209 |
|
| 210 |
def test_minutes_fields(self): |
| 211 |
""" |
| 212 |
Ensure for minute based throttles. |
| 213 |
""" |
| 214 |
self.ensure_response_header_contains_proper_throttle_field( |
| 215 |
MockView_MinuteThrottling, ( |
| 216 |
(0, None), |
| 217 |
(0, None), |
| 218 |
(0, None), |
| 219 |
(0, '60') |
| 220 |
) |
| 221 |
) |
| 222 |
|
| 223 |
def test_next_rate_remains_constant_if_followed(self): |
| 224 |
""" |
| 225 |
If a client follows the recommended next request rate, |
| 226 |
the throttling rate should stay constant. |
| 227 |
""" |
| 228 |
self.ensure_response_header_contains_proper_throttle_field( |
| 229 |
MockView_MinuteThrottling, ( |
| 230 |
(0, None), |
| 231 |
(20, None), |
| 232 |
(40, None), |
| 233 |
(60, None), |
| 234 |
(80, None) |
| 235 |
) |
| 236 |
) |
| 237 |
|
| 238 |
def test_non_time_throttle(self): |
| 239 |
""" |
| 240 |
Ensure for second based throttles. |
| 241 |
""" |
| 242 |
request = self.factory.get('/') |
| 243 |
|
| 244 |
self.assertFalse(hasattr(MockView_NonTimeThrottling.throttle_classes[0], 'called')) |
| 245 |
|
| 246 |
response = MockView_NonTimeThrottling.as_view()(request) |
| 247 |
self.assertFalse('Retry-After' in response) |
| 248 |
|
| 249 |
self.assertTrue(MockView_NonTimeThrottling.throttle_classes[0].called) |
| 250 |
|
| 251 |
response = MockView_NonTimeThrottling.as_view()(request) |
| 252 |
self.assertFalse('Retry-After' in response) |
| 253 |
|
| 254 |
|
| 255 |
class ScopedRateThrottleTests(TestCase): |
| 256 |
""" |
| 257 |
Tests for ScopedRateThrottle. |
| 258 |
""" |
| 259 |
|
| 260 |
def setUp(self): |
| 261 |
self.throttle = ScopedRateThrottle() |
| 262 |
|
| 263 |
class XYScopedRateThrottle(ScopedRateThrottle): |
| 264 |
TIMER_SECONDS = 0 |
| 265 |
THROTTLE_RATES = {'x': '3/min', 'y': '1/min'} |
| 266 |
|
| 267 |
def timer(self): |
| 268 |
return self.TIMER_SECONDS |
| 269 |
|
| 270 |
class XView(APIView): |
| 271 |
throttle_classes = (XYScopedRateThrottle,) |
| 272 |
throttle_scope = 'x' |
| 273 |
|
| 274 |
def get(self, request): |
| 275 |
return Response('x') |
| 276 |
|
| 277 |
class YView(APIView): |
| 278 |
throttle_classes = (XYScopedRateThrottle,) |
| 279 |
throttle_scope = 'y' |
| 280 |
|
| 281 |
def get(self, request): |
| 282 |
return Response('y') |
| 283 |
|
| 284 |
class UnscopedView(APIView): |
| 285 |
throttle_classes = (XYScopedRateThrottle,) |
| 286 |
|
| 287 |
def get(self, request): |
| 288 |
return Response('y') |
| 289 |
|
| 290 |
self.throttle_class = XYScopedRateThrottle |
| 291 |
self.factory = APIRequestFactory() |
| 292 |
self.x_view = XView.as_view() |
| 293 |
self.y_view = YView.as_view() |
| 294 |
self.unscoped_view = UnscopedView.as_view() |
| 295 |
|
| 296 |
def increment_timer(self, seconds=1): |
| 297 |
self.throttle_class.TIMER_SECONDS += seconds |
| 298 |
|
| 299 |
def test_scoped_rate_throttle(self): |
| 300 |
request = self.factory.get('/') |
| 301 |
|
| 302 |
# Should be able to hit x view 3 times per minute. |
| 303 |
response = self.x_view(request) |
| 304 |
assert response.status_code == 200 |
| 305 |
|
| 306 |
self.increment_timer() |
| 307 |
response = self.x_view(request) |
| 308 |
assert response.status_code == 200 |
| 309 |
|
| 310 |
self.increment_timer() |
| 311 |
response = self.x_view(request) |
| 312 |
assert response.status_code == 200 |
| 313 |
self.increment_timer() |
| 314 |
response = self.x_view(request) |
| 315 |
assert response.status_code == 429 |
| 316 |
|
| 317 |
# Should be able to hit y view 1 time per minute. |
| 318 |
self.increment_timer() |
| 319 |
response = self.y_view(request) |
| 320 |
assert response.status_code == 200 |
| 321 |
|
| 322 |
self.increment_timer() |
| 323 |
response = self.y_view(request) |
| 324 |
assert response.status_code == 429 |
| 325 |
|
| 326 |
# Ensure throttles properly reset by advancing the rest of the minute |
| 327 |
self.increment_timer(55) |
| 328 |
|
| 329 |
# Should still be able to hit x view 3 times per minute. |
| 330 |
response = self.x_view(request) |
| 331 |
assert response.status_code == 200 |
| 332 |
|
| 333 |
self.increment_timer() |
| 334 |
response = self.x_view(request) |
| 335 |
assert response.status_code == 200 |
| 336 |
|
| 337 |
self.increment_timer() |
| 338 |
response = self.x_view(request) |
| 339 |
assert response.status_code == 200 |
| 340 |
|
| 341 |
self.increment_timer() |
| 342 |
response = self.x_view(request) |
| 343 |
assert response.status_code == 429 |
| 344 |
|
| 345 |
# Should still be able to hit y view 1 time per minute. |
| 346 |
self.increment_timer() |
| 347 |
response = self.y_view(request) |
| 348 |
assert response.status_code == 200 |
| 349 |
|
| 350 |
self.increment_timer() |
| 351 |
response = self.y_view(request) |
| 352 |
assert response.status_code == 429 |
| 353 |
|
| 354 |
def test_unscoped_view_not_throttled(self): |
| 355 |
request = self.factory.get('/') |
| 356 |
|
| 357 |
for idx in range(10): |
| 358 |
self.increment_timer() |
| 359 |
response = self.unscoped_view(request) |
| 360 |
assert response.status_code == 200 |
| 361 |
|
| 362 |
def test_get_cache_key_returns_correct_key_if_user_is_authenticated(self): |
| 363 |
class DummyView: |
| 364 |
throttle_scope = 'user' |
| 365 |
|
| 366 |
request = Request(HttpRequest()) |
| 367 |
user = User.objects.create(username='test') |
| 368 |
force_authenticate(request, user) |
| 369 |
request.user = user |
| 370 |
self.throttle.allow_request(request, DummyView()) |
| 371 |
cache_key = self.throttle.get_cache_key(request, view=DummyView()) |
| 372 |
assert cache_key == 'throttle_user_%s' % user.pk |
| 373 |
|
| 374 |
|
| 375 |
class XffTestingBase(TestCase): |
| 376 |
def setUp(self): |
| 377 |
|
| 378 |
class Throttle(ScopedRateThrottle): |
| 379 |
THROTTLE_RATES = {'test_limit': '1/day'} |
| 380 |
TIMER_SECONDS = 0 |
| 381 |
|
| 382 |
def timer(self): |
| 383 |
return self.TIMER_SECONDS |
| 384 |
|
| 385 |
class View(APIView): |
| 386 |
throttle_classes = (Throttle,) |
| 387 |
throttle_scope = 'test_limit' |
| 388 |
|
| 389 |
def get(self, request): |
| 390 |
return Response('test_limit') |
| 391 |
|
| 392 |
cache.clear() |
| 393 |
self.throttle = Throttle() |
| 394 |
self.view = View.as_view() |
| 395 |
self.request = self.build_request('0.0.0.0, 1.1.1.1, 2.2.2.2') |
| 396 |
|
| 397 |
def build_request(self, xff): |
| 398 |
# `HttpRequest.headers` is a cached_property, so a request has to be |
| 399 |
# rebuilt rather than have its META mutated to change a header. |
| 400 |
request = APIRequestFactory().get( |
| 401 |
'/some_uri', headers={'x-forwarded-for': xff} |
| 402 |
) |
| 403 |
request.META['REMOTE_ADDR'] = '3.3.3.3' |
| 404 |
return request |
| 405 |
|
| 406 |
def config_proxy(self, num_proxies): |
| 407 |
setattr(api_settings, 'NUM_PROXIES', num_proxies) |
| 408 |
|
| 409 |
|
| 410 |
class IdWithXffBasicTests(XffTestingBase): |
| 411 |
def test_accepts_request_under_limit(self): |
| 412 |
self.config_proxy(0) |
| 413 |
assert self.view(self.request).status_code == 200 |
| 414 |
|
| 415 |
def test_denies_request_over_limit(self): |
| 416 |
self.config_proxy(0) |
| 417 |
self.view(self.request) |
| 418 |
assert self.view(self.request).status_code == 429 |
| 419 |
|
| 420 |
|
| 421 |
class XffSpoofingTests(XffTestingBase): |
| 422 |
def test_xff_spoofing_doesnt_change_machine_id_with_one_app_proxy(self): |
| 423 |
self.config_proxy(1) |
| 424 |
self.view(self.request) |
| 425 |
spoofed = self.build_request('4.4.4.4, 5.5.5.5, 2.2.2.2') |
| 426 |
assert self.view(spoofed).status_code == 429 |
| 427 |
|
| 428 |
def test_xff_spoofing_doesnt_change_machine_id_with_two_app_proxies(self): |
| 429 |
self.config_proxy(2) |
| 430 |
self.view(self.request) |
| 431 |
spoofed = self.build_request('4.4.4.4, 1.1.1.1, 2.2.2.2') |
| 432 |
assert self.view(spoofed).status_code == 429 |
| 433 |
|
| 434 |
|
| 435 |
class XffUniqueMachinesTest(XffTestingBase): |
| 436 |
def test_unique_clients_are_counted_independently_with_one_proxy(self): |
| 437 |
self.config_proxy(1) |
| 438 |
self.view(self.request) |
| 439 |
other_client = self.build_request('0.0.0.0, 1.1.1.1, 7.7.7.7') |
| 440 |
assert self.view(other_client).status_code == 200 |
| 441 |
|
| 442 |
def test_unique_clients_are_counted_independently_with_two_proxies(self): |
| 443 |
self.config_proxy(2) |
| 444 |
self.view(self.request) |
| 445 |
other_client = self.build_request('0.0.0.0, 7.7.7.7, 2.2.2.2') |
| 446 |
assert self.view(other_client).status_code == 200 |
| 447 |
|
| 448 |
|
| 449 |
class BaseThrottleTests(TestCase): |
| 450 |
|
| 451 |
def test_allow_request_raises_not_implemented_error(self): |
| 452 |
with pytest.raises(NotImplementedError): |
| 453 |
BaseThrottle().allow_request(request={}, view={}) |
| 454 |
|
| 455 |
|
| 456 |
class SimpleRateThrottleTests(TestCase): |
| 457 |
|
| 458 |
def setUp(self): |
| 459 |
SimpleRateThrottle.scope = 'anon' |
| 460 |
|
| 461 |
def test_get_rate_raises_error_if_scope_is_missing(self): |
| 462 |
throttle = SimpleRateThrottle() |
| 463 |
with pytest.raises(ImproperlyConfigured): |
| 464 |
throttle.scope = None |
| 465 |
throttle.get_rate() |
| 466 |
|
| 467 |
def test_throttle_raises_error_if_rate_is_missing(self): |
| 468 |
SimpleRateThrottle.scope = 'invalid scope' |
| 469 |
with pytest.raises(ImproperlyConfigured): |
| 470 |
SimpleRateThrottle() |
| 471 |
|
| 472 |
def test_parse_rate_returns_tuple_with_none_if_rate_not_provided(self): |
| 473 |
rate = SimpleRateThrottle().parse_rate(None) |
| 474 |
assert rate == (None, None) |
| 475 |
|
| 476 |
def test_allow_request_returns_true_if_rate_is_none(self): |
| 477 |
assert SimpleRateThrottle().allow_request(request={}, view={}) is True |
| 478 |
|
| 479 |
def test_get_cache_key_raises_not_implemented_error(self): |
| 480 |
with pytest.raises(NotImplementedError): |
| 481 |
SimpleRateThrottle().get_cache_key({}, {}) |
| 482 |
|
| 483 |
def test_allow_request_returns_true_if_key_is_none(self): |
| 484 |
throttle = SimpleRateThrottle() |
| 485 |
throttle.rate = 'some rate' |
| 486 |
throttle.get_cache_key = lambda *args: None |
| 487 |
assert throttle.allow_request(request={}, view={}) is True |
| 488 |
|
| 489 |
def test_wait_returns_correct_waiting_time_without_history(self): |
| 490 |
throttle = SimpleRateThrottle() |
| 491 |
throttle.num_requests = 1 |
| 492 |
throttle.duration = 60 |
| 493 |
throttle.history = [] |
| 494 |
waiting_time = throttle.wait() |
| 495 |
assert isinstance(waiting_time, float) |
| 496 |
assert waiting_time == 30.0 |
| 497 |
|
| 498 |
def test_wait_returns_none_if_there_are_no_available_requests(self): |
| 499 |
throttle = SimpleRateThrottle() |
| 500 |
throttle.num_requests = 1 |
| 501 |
throttle.duration = 60 |
| 502 |
throttle.now = throttle.timer() |
| 503 |
throttle.history = [throttle.timer() for _ in range(3)] |
| 504 |
assert throttle.wait() is None |
| 505 |
|
| 506 |
|
| 507 |
class AnonRateThrottleTests(TestCase): |
| 508 |
|
| 509 |
def setUp(self): |
| 510 |
self.throttle = AnonRateThrottle() |
| 511 |
|
| 512 |
def test_authenticated_user_not_affected(self): |
| 513 |
request = Request(HttpRequest()) |
| 514 |
user = User.objects.create(username='test') |
| 515 |
force_authenticate(request, user) |
| 516 |
request.user = user |
| 517 |
assert self.throttle.get_cache_key(request, view={}) is None |
| 518 |
|
| 519 |
def test_get_cache_key_returns_correct_value(self): |
| 520 |
request = Request(HttpRequest()) |
| 521 |
cache_key = self.throttle.get_cache_key(request, view={}) |
| 522 |
assert cache_key == 'throttle_anon_None' |