Skip to content

Commit c88e806

Browse files
committed
add whitelisting feature for ratelimiting
1 parent ebb7104 commit c88e806

1 file changed

Lines changed: 32 additions & 2 deletions

File tree

api/middleware/rate_limit.py

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,42 @@
11
import logging
2+
import os
23
import time
34
from typing import Any, Callable, Optional, cast
45

6+
from django.conf import settings
57
from django.core.cache import cache
68
from django.http import HttpRequest, HttpResponse
79
from redis.exceptions import RedisError
810

911
logger = logging.getLogger(__name__)
1012

1113

14+
def get_whitelisted_ips() -> set[str]:
15+
"""Get the set of whitelisted IPs from settings or environment variable.
16+
17+
Can be configured via:
18+
- RATE_LIMIT_WHITELIST_IPS in Django settings (list)
19+
- RATE_LIMIT_WHITELIST_IPS environment variable (comma-separated string)
20+
"""
21+
# First check Django settings
22+
whitelist = getattr(settings, "RATE_LIMIT_WHITELIST_IPS", None)
23+
if whitelist:
24+
return set(whitelist)
25+
26+
# Fall back to environment variable
27+
env_whitelist = os.environ.get("RATE_LIMIT_WHITELIST_IPS", "")
28+
if env_whitelist:
29+
return {ip.strip() for ip in env_whitelist.split(",") if ip.strip()}
30+
31+
return set()
32+
33+
1234
class HttpResponseTooManyRequests(HttpResponse):
1335
status_code = 429
1436

1537

1638
def rate_limit_middleware(
17-
get_response: Callable[[HttpRequest], HttpResponse]
39+
get_response: Callable[[HttpRequest], HttpResponse],
1840
) -> Callable[[HttpRequest], HttpResponse]:
1941
"""Rate limiting middleware that uses a simple cache-based counter."""
2042

@@ -78,10 +100,18 @@ def check_rate_limit(request: HttpRequest) -> bool:
78100
return True # Allow request on unexpected error
79101

80102
def middleware(request: HttpRequest) -> HttpResponse:
103+
client_ip = get_client_ip(request)
104+
whitelisted_ips = get_whitelisted_ips()
105+
106+
# Skip rate limiting for whitelisted IPs
107+
if client_ip in whitelisted_ips:
108+
logger.debug(f"Skipping rate limit for whitelisted IP: {client_ip}")
109+
return get_response(request)
110+
81111
if not check_rate_limit(request):
82112
logger.warning(
83113
f"Rate limited - Method: {request.method}, "
84-
f"Path: {request.path}, IP: {get_client_ip(request)}"
114+
f"Path: {request.path}, IP: {client_ip}"
85115
)
86116
return HttpResponseTooManyRequests()
87117

0 commit comments

Comments
 (0)