|
| 1 | +import base64 |
| 2 | +import hashlib |
| 3 | +import json |
| 4 | + |
| 5 | +from django.conf import settings |
| 6 | +from django.http import JsonResponse |
| 7 | +from django_ratelimit.decorators import ratelimit |
| 8 | +from django_ratelimit.exceptions import Ratelimited |
| 9 | + |
| 10 | +DISABLED_RATE_VALUES = {"", "0", "off", "none", "false"} |
| 11 | + |
| 12 | + |
| 13 | +class PathoCoreRatelimitMiddleware: |
| 14 | + def __init__(self, get_response): |
| 15 | + self.get_response = get_response |
| 16 | + |
| 17 | + def __call__(self, request): |
| 18 | + return self.get_response(request) |
| 19 | + |
| 20 | + def process_exception(self, request, exception): |
| 21 | + if not isinstance(exception, Ratelimited): |
| 22 | + return None |
| 23 | + return JsonResponse( |
| 24 | + { |
| 25 | + "detail": "Rate limit exceeded.", |
| 26 | + "error": ( |
| 27 | + "Too many API requests. Wait before retrying or contact " |
| 28 | + "the PathoCore administrators if this limit is too strict." |
| 29 | + ), |
| 30 | + }, |
| 31 | + status=429, |
| 32 | + ) |
| 33 | + |
| 34 | + |
| 35 | +def apply_api_ratelimit(view, *, category): |
| 36 | + if not getattr(settings, "PATHOCORE_RATELIMIT_ENABLED", True): |
| 37 | + return view |
| 38 | + |
| 39 | + rate = _rate_for_category(category) |
| 40 | + if rate is None: |
| 41 | + return view |
| 42 | + |
| 43 | + return ratelimit( |
| 44 | + group=f"pathocore-api:{category}", |
| 45 | + key=ratelimit_identity_key, |
| 46 | + rate=rate, |
| 47 | + block=True, |
| 48 | + )(view) |
| 49 | + |
| 50 | + |
| 51 | +def ratelimit_identity_key(group, request): |
| 52 | + authorization = request.META.get("HTTP_AUTHORIZATION", "").strip() |
| 53 | + if authorization: |
| 54 | + return _authorization_key(authorization) |
| 55 | + return f"ip:{_client_ip(request)}" |
| 56 | + |
| 57 | + |
| 58 | +def _rate_for_category(category): |
| 59 | + rates = getattr(settings, "PATHOCORE_RATELIMIT_RATES", {}) |
| 60 | + rate = str(rates.get(category, "")).strip().lower() |
| 61 | + if rate in DISABLED_RATE_VALUES: |
| 62 | + return None |
| 63 | + return rate |
| 64 | + |
| 65 | + |
| 66 | +def _authorization_key(authorization): |
| 67 | + scheme, _, credentials = authorization.partition(" ") |
| 68 | + scheme = scheme.strip().lower() |
| 69 | + credentials = credentials.strip() |
| 70 | + |
| 71 | + if scheme == "bearer": |
| 72 | + subject = _jwt_subject(credentials) |
| 73 | + if subject: |
| 74 | + return f"bearer-sub:{subject}" |
| 75 | + |
| 76 | + if scheme == "basic": |
| 77 | + username = _basic_username(credentials) |
| 78 | + if username: |
| 79 | + return f"basic-user:{username}" |
| 80 | + |
| 81 | + digest = hashlib.sha256(authorization.encode("utf-8")).hexdigest() |
| 82 | + return f"auth-hash:{digest}" |
| 83 | + |
| 84 | + |
| 85 | +def _jwt_subject(token): |
| 86 | + parts = token.split(".") |
| 87 | + if len(parts) < 2: |
| 88 | + return "" |
| 89 | + payload = _urlsafe_b64decode(parts[1]) |
| 90 | + if payload is None: |
| 91 | + return "" |
| 92 | + try: |
| 93 | + data = json.loads(payload.decode("utf-8")) |
| 94 | + except (json.JSONDecodeError, UnicodeDecodeError): |
| 95 | + return "" |
| 96 | + return str(data.get("sub") or data.get("preferred_username") or "").strip() |
| 97 | + |
| 98 | + |
| 99 | +def _basic_username(credentials): |
| 100 | + decoded = _urlsafe_b64decode(credentials) |
| 101 | + if decoded is None: |
| 102 | + return "" |
| 103 | + try: |
| 104 | + raw_value = decoded.decode("utf-8") |
| 105 | + except UnicodeDecodeError: |
| 106 | + return "" |
| 107 | + username, _, _ = raw_value.partition(":") |
| 108 | + return username.strip() |
| 109 | + |
| 110 | + |
| 111 | +def _urlsafe_b64decode(value): |
| 112 | + padding = "=" * (-len(value) % 4) |
| 113 | + try: |
| 114 | + return base64.urlsafe_b64decode(value + padding) |
| 115 | + except (ValueError, TypeError): |
| 116 | + return None |
| 117 | + |
| 118 | + |
| 119 | +def _client_ip(request): |
| 120 | + meta_key = getattr(settings, "PATHOCORE_RATELIMIT_IP_META_KEY", "").strip() |
| 121 | + if meta_key: |
| 122 | + value = request.META.get(meta_key, "").strip() |
| 123 | + if value: |
| 124 | + return value.split(",", 1)[0].strip() |
| 125 | + return request.META.get("REMOTE_ADDR", "") |
0 commit comments