From 496a7139bdb2cdac7f516986b613715a693fff13 Mon Sep 17 00:00:00 2001 From: jcbl1 Date: Fri, 23 Oct 2026 09:18:26 +0000 Subject: [PATCH] perf(rate-limit): bound tracked IPs and use monotonic clock --- apps/base/dependencies.py | 76 +++++++++++++++++++++---------- tests/test_rate_limit_bounds.py | 81 +++++++++++++++++++++++++++++++++ 2 files changed, 132 insertions(+), 25 deletions(-) create mode 100644 tests/test_rate_limit_bounds.py diff --git a/apps/base/dependencies.py b/apps/base/dependencies.py index c774854..edf31b1 100644 --- a/apps/base/dependencies.py +++ b/apps/base/dependencies.py @@ -1,6 +1,7 @@ +import time +from collections import OrderedDict from ipaddress import ip_address, ip_network -from typing import Dict, Iterable, TypedDict -from datetime import datetime, timedelta +from typing import Iterable, TypedDict from fastapi import HTTPException, Request from core.settings import settings @@ -67,41 +68,66 @@ def get_client_ip(request: Request) -> str: class _IPRecord(TypedDict): count: int - time: datetime + last_seen: float + + +# Upper bound for tracked source IPs per limiter. Without it a scan using +# spoofed/rotating addresses grows the dict forever on a small VPS. +DEFAULT_MAX_TRACKED_IPS = 10_000 class IPRateLimit: - def __init__(self, count: int, minutes: int): - self.ips: Dict[str, _IPRecord] = {} + def __init__( + self, + count: int, + minutes: int, + max_ips: int = DEFAULT_MAX_TRACKED_IPS, + ): + # Ordered by last activity (oldest first) so capacity eviction and the + # periodic cleanup are both O(1)/O(expired) instead of a full rebuild. + self.ips: OrderedDict[str, _IPRecord] = OrderedDict() self.count = count self.minutes = minutes + self.max_ips = max(1, max_ips) + + def _window_seconds(self) -> float: + # minutes is mutable at runtime via apps.base.config._sync_ip_limits. + return float(self.minutes) * 60 def check_ip(self, ip: str) -> bool: - if ip in self.ips: - ip_info = self.ips[ip] - if ip_info["count"] >= self.count: - if ip_info["time"] + timedelta(minutes=self.minutes) > datetime.now(): - return False - self.ips.pop(ip) + record = self.ips.get(ip) + if record is None: + return True + if record["count"] >= self.count: + if record["last_seen"] + self._window_seconds() > time.monotonic(): + return False + self.ips.pop(ip, None) return True def add_ip(self, ip: str) -> int: - ip_info = self.ips.setdefault( - ip, {"count": 0, "time": datetime.now()} - ) - ip_info["count"] += 1 - ip_info["time"] = datetime.now() - self.ips[ip] = ip_info - return ip_info["count"] + now = time.monotonic() + record = self.ips.get(ip) + if record is None: + record = {"count": 0, "last_seen": now} + self.ips[ip] = record + else: + self.ips.move_to_end(ip) + record["count"] += 1 + record["last_seen"] = now + while len(self.ips) > self.max_ips: + # Evict the least recently active IP; fail-open for the evicted + # address is preferable to unbounded memory growth. + self.ips.popitem(last=False) + return record["count"] async def remove_expired_ip(self) -> None: - now = datetime.now() - expiration = timedelta(minutes=self.minutes) - self.ips = { - ip: info - for ip, info in self.ips.items() - if info["time"] + expiration >= now - } + now = time.monotonic() + window = self._window_seconds() + while self.ips: + _, record = next(iter(self.ips.items())) + if record["last_seen"] + window >= now: + break + self.ips.popitem(last=False) def __call__(self, request: Request) -> str: ip = get_client_ip(request) diff --git a/tests/test_rate_limit_bounds.py b/tests/test_rate_limit_bounds.py new file mode 100644 index 0000000..2984306 --- /dev/null +++ b/tests/test_rate_limit_bounds.py @@ -0,0 +1,81 @@ +"""IPRateLimit is bounded and uses a monotonic clock.""" +import unittest +from unittest import mock + +from apps.base.dependencies import IPRateLimit + + +class FakeClock: + def __init__(self, now: float = 1000.0): + self.now = now + + def __call__(self) -> float: + return self.now + + +class IPRateLimitBoundsTests(unittest.TestCase): + def test_first_add_returns_one(self): + limiter = IPRateLimit(count=3, minutes=1) + + self.assertEqual(limiter.add_ip("203.0.113.1"), 1) + self.assertEqual(limiter.add_ip("203.0.113.1"), 2) + + def test_capacity_evicts_least_recently_active_ip(self): + limiter = IPRateLimit(count=10, minutes=1, max_ips=3) + + for ip in ("a", "b", "c", "d"): + limiter.add_ip(ip) + + self.assertEqual(len(limiter.ips), 3) + self.assertEqual(list(limiter.ips), ["b", "c", "d"]) + + def test_activity_refreshes_recency(self): + limiter = IPRateLimit(count=10, minutes=1, max_ips=2) + + limiter.add_ip("a") + limiter.add_ip("b") + limiter.add_ip("a") + limiter.add_ip("c") + + self.assertEqual(list(limiter.ips), ["a", "c"]) + + def test_window_blocks_then_resets(self): + clock = FakeClock() + with mock.patch("time.monotonic", clock): + limiter = IPRateLimit(count=3, minutes=1) + for _ in range(3): + limiter.add_ip("198.51.100.9") + + self.assertFalse(limiter.check_ip("198.51.100.9")) + clock.now += 30 + self.assertFalse(limiter.check_ip("198.51.100.9")) + clock.now += 31 + self.assertTrue(limiter.check_ip("198.51.100.9")) + self.assertNotIn("198.51.100.9", limiter.ips) + + def test_remove_expired_compacts_old_entries_only(self): + clock = FakeClock() + with mock.patch("time.monotonic", clock): + limiter = IPRateLimit(count=10, minutes=1) + limiter.add_ip("old") + clock.now += 30 + limiter.add_ip("fresh") + clock.now += 31 + + import asyncio + + asyncio.run(limiter.remove_expired_ip()) + + self.assertEqual(list(limiter.ips), ["fresh"]) + + def test_record_count_is_bounded_under_ip_scan(self): + limiter = IPRateLimit(count=10, minutes=1, max_ips=10_000) + + for i in range(50_000): + limiter.add_ip(f"10.0.{i // 256}.{i % 256}") + + self.assertEqual(len(limiter.ips), 10_000) + + +if __name__ == "__main__": + unittest.main()