Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

rate_limiter: Update Redis rate limiter to use in-server GCRA.

Alex Vandiverfc9b09a9e78a
diff --git a/zerver/lib/rate_limiter.lua b/zerver/lib/rate_limiter.lua
new file mode 100644
index 00000000000..9019658b404
--- /dev/null
+++ b/zerver/lib/rate_limiter.lua
@@ -0,0 +1,100 @@
+-- GCRA (Generic Cell Rate Algorithm) rate limiter.
+-- Atomically checks all rules and updates TATs in a single round trip.
+--
+-- KEYS[1] = block_key, KEYS[2] = gcra_key
+-- ARGV[1] = num_rules, ARGV[2..2*num_rules+1] = w1, l1, w2, l2, ...
+-- ARGV[2*num_rules+2] (optional) = override timestamp for tests only
+--
+-- Returns a 4-element list of strings:
+-- [ratelimited, secs_to_freedom, calls_remaining, secs_to_reset]
+
+local block_key = KEYS[1]
+local gcra_key = KEYS[2]
+local num_rules = tonumber(ARGV[1])
+
+-- Use Redis server time so that all app servers see a consistent
+-- clock, avoiding false positives from inter-machine clock drift.
+-- Tests may pass an explicit timestamp as the last argument to get
+-- deterministic behavior without wall-clock sleeps.
+local now
+local test_time_arg = ARGV[2 * num_rules + 2]
+if test_time_arg then
+ now = tonumber(test_time_arg)
+else
+ local time_result = redis.call('TIME')
+ now = tonumber(time_result[1]) + tonumber(time_result[2]) / 1000000
+end
+
+-- Check for manual block (set by block_access).
+if redis.call('EXISTS', block_key) == 1 then
+ local ttl = redis.call('PTTL', block_key)
+ if ttl < 0 then ttl = 1000 end
+ return {'1', string.format('%.17g', ttl / 1000.0), '0', '0'}
+end
+
+-- For each rule, compute the new TAT (Theoretical Arrival Time)
+-- without writing anything yet. If any rule would be violated,
+-- we reject the request and leave all TATs unchanged.
+local fields = {}
+local new_tats = {}
+local max_ttl = 0
+local limited = false
+local secs_to_freedom = 0
+
+for i = 1, num_rules do
+ local window = tonumber(ARGV[1 + (i - 1) * 2 + 1])
+ local limit = tonumber(ARGV[1 + (i - 1) * 2 + 2])
+ local field = window .. ':' .. limit
+ -- Time between ideally-spaced requests.
+ local emission_interval = window / limit
+
+ local stored = redis.call('HGET', gcra_key, field)
+ -- If the stored TAT is in the past, treat it as now (the
+ -- bucket has fully drained).
+ local tat = math.max(stored and tonumber(stored) or now, now)
+ local new_tat = tat + emission_interval
+
+ -- The bucket overflows when new_tat exceeds the window
+ -- horizon: the request arrived faster than the drain rate
+ -- can sustain.
+ if new_tat > now + window then
+ limited = true
+ local freedom = new_tat - window - now
+ if freedom > secs_to_freedom then
+ secs_to_freedom = freedom
+ end
+ end
+
+ fields[i] = field
+ new_tats[i] = new_tat
+ local remaining = new_tat - now
+ if remaining > max_ttl then
+ max_ttl = remaining
+ end
+end
+
+-- All-or-nothing: if any rule triggered, reject without updating.
+if limited then
+ return {'1', string.format('%.17g', secs_to_freedom), '0', '0'}
+end
+
+-- Request allowed — persist all new TATs atomically.
+for i = 1, num_rules do
+ redis.call('HSET', gcra_key, fields[i], string.format('%.17g', new_tats[i]))
+end
+local ttl_seconds = math.ceil(max_ttl)
+if ttl_seconds > 0 then
+ redis.call('EXPIRE', gcra_key, ttl_seconds)
+end
+
+-- Compute remaining quota for the max (outermost) rule, used for
+-- the X-RateLimit-Remaining response header.
+local max_window = tonumber(ARGV[1 + (num_rules - 1) * 2 + 1])
+local max_limit = tonumber(ARGV[1 + (num_rules - 1) * 2 + 2])
+local max_tat = new_tats[num_rules]
+local calls_remaining = math.max(0, math.floor(
+ (now + max_window - max_tat) * max_limit / max_window
+))
+local secs_to_reset = max_tat - now
+
+return {'0', '0', tostring(calls_remaining), string.format('%.17g', secs_to_reset)}
diff --git a/zerver/lib/rate_limiter.py b/zerver/lib/rate_limiter.py
index 4dc1a982401..fc569f70a7c 100644
--- a/zerver/lib/rate_limiter.py
+++ b/zerver/lib/rate_limiter.py
@@ -3,10 +3,11 @@ import time
from abc import ABC, abstractmethod
from datetime import timedelta
from ipaddress import IPv6Network, ip_network
-from typing import Optional, cast
+from pathlib import Path
+from typing import Optional
import orjson
-import redis
+import redis.commands.core
from circuitbreaker import CircuitBreakerError, circuit
from django.conf import settings
from django.http import HttpRequest
@@ -21,18 +22,14 @@ from zerver.lib.exceptions import RateLimitedError
from zerver.lib.redis_utils import get_redis_client
from zerver.models import UserProfile
-# Implement a rate-limiting scheme inspired by the one described here, but heavily modified
-# https://www.domaintools.com/resources/blog/rate-limiting-with-redis
+# Rate limiting using the GCRA (Generic Cell Rate Algorithm), a leaky-bucket
+# variant that stores one TAT (Theoretical Arrival Time) per rule in Redis.
client = get_redis_client()
logger = logging.getLogger(__name__)
-class RateLimiterLockingError(Exception):
- pass
-
-
class RateLimitedObject(ABC):
def __init__(self, backend: Optional["type[RateLimiterBackend]"] = None) -> None:
if backend is not None:
@@ -349,18 +346,30 @@ class TornadoInMemoryRateLimiterBackend(RateLimiterBackend):
class RedisRateLimiterBackend(RateLimiterBackend):
+ _script: redis.commands.core.Script | None = None
+
+ # When True, pass time.time() to the Lua script instead of using
+ # Redis TIME. This lets tests control the rate-limiting clock via
+ # mock.patch("time.time") or time_machine without wall-clock sleeps.
+ _testing_clock: bool = settings.TEST_SUITE
+
@classmethod
- def get_keys(cls, entity_key: str) -> list[str]:
- return [
- f"{redis_utils.REDIS_KEY_PREFIX}ratelimit:{entity_key}:{keytype}"
- for keytype in ["list", "zset", "block"]
- ]
+ def get_keys(cls, entity_key: str) -> tuple[str, str]:
+ prefix = f"{redis_utils.REDIS_KEY_PREFIX}ratelimit:{entity_key}"
+ return f"{prefix}:gcra", f"{prefix}:block"
+
+ @classmethod
+ def _get_script(cls) -> redis.commands.core.Script:
+ if cls._script is None:
+ script_text = Path(__file__).with_suffix(".lua").read_text()
+ cls._script = client.register_script(script_text)
+ return cls._script
@classmethod
@override
def block_access(cls, entity_key: str, seconds: int) -> None:
"""Manually blocks an entity for the desired number of seconds"""
- _, _, blocking_key = cls.get_keys(entity_key)
+ _, blocking_key = cls.get_keys(entity_key)
with client.pipeline() as pipe:
pipe.set(blocking_key, 1)
pipe.expire(blocking_key, seconds)
@@ -369,7 +378,7 @@ class RedisRateLimiterBackend(RateLimiterBackend):
@classmethod
@override
def unblock_access(cls, entity_key: str) -> None:
- _, _, blocking_key = cls.get_keys(entity_key)
+ _, blocking_key = cls.get_keys(entity_key)
client.delete(blocking_key)
@classmethod
@@ -383,155 +392,48 @@ class RedisRateLimiterBackend(RateLimiterBackend):
def get_api_calls_left(
cls, entity_key: str, range_seconds: int, max_calls: int
) -> tuple[int, float]:
- list_key, set_key, _ = cls.get_keys(entity_key)
- # Count the number of values in our sorted set
- # that are between now and the cutoff
- now = time.time()
- boundary = now - range_seconds
-
- with client.pipeline() as pipe:
- # Count how many API calls in our range have already been made
- pipe.zcount(set_key, boundary, now)
- # Get the newest call so we can calculate when the ratelimit
- # will reset to 0
- pipe.lindex(list_key, 0)
-
- results = pipe.execute()
-
- count: int = results[0]
- newest_call: bytes | None = results[1]
-
- calls_left = max_calls - count
- if newest_call is not None:
- time_reset = now + (range_seconds - (now - float(newest_call)))
- else:
- time_reset = now
-
- return calls_left, time_reset - now
-
- @classmethod
- def is_ratelimited(cls, entity_key: str, rules: list[tuple[int, int]]) -> tuple[bool, float]:
- """Returns a tuple of (rate_limited, time_till_free)"""
- assert rules
- list_key, _set_key, blocking_key = cls.get_keys(entity_key)
-
- # Go through the rules from shortest to longest,
- # seeing if this user has violated any of them. First
- # get the timestamps for each nth items
- with client.pipeline() as pipe:
- for _, request_count in rules:
- pipe.lindex(list_key, request_count - 1) # 0-indexed list
-
- # Get blocking info
- pipe.get(blocking_key)
- pipe.ttl(blocking_key)
-
- rule_timestamps: list[bytes | None] = pipe.execute()
-
- # Check if there is a manual block on this API key
- blocking_ttl_b = rule_timestamps.pop()
- key_blocked = rule_timestamps.pop()
-
- if key_blocked is not None:
- # We are manually blocked. Report for how much longer we will be
- if blocking_ttl_b is None: # nocoverage # defensive code, this should never happen
- blocking_ttl = 0.5
- else:
- blocking_ttl = int(blocking_ttl_b)
- return True, blocking_ttl
-
- now = time.time()
- for timestamp, (range_seconds, num_requests) in zip(rule_timestamps, rules, strict=False):
- # Check if the nth timestamp is newer than the associated rule. If so,
- # it means we've hit our limit for this rule
- if timestamp is None:
- continue
-
- boundary = float(timestamp) + range_seconds
- if boundary >= now:
- free = boundary - now
- return True, free
-
- return False, 0.0
-
- @classmethod
- def incr_ratelimit(cls, entity_key: str, max_api_calls: int, max_api_window: int) -> None:
- """Increases the rate-limit for the specified entity"""
- list_key, set_key, _ = cls.get_keys(entity_key)
- now = time.time()
+ gcra_key, _ = cls.get_keys(entity_key)
+ if cls._testing_clock:
+ now = time.time()
+ else: # nocoverage
+ redis_time = client.time()
+ now = redis_time[0] + redis_time[1] / 1_000_000
+ field = f"{range_seconds}:{max_calls}"
+ stored_tat = client.hget(gcra_key, field)
+ if stored_tat is None:
+ return max_calls, 0
- # Start Redis transaction
- with client.pipeline() as pipe:
- count = 0
- while True:
- try:
- # To avoid a race condition between getting the element we might trim from our list
- # and removing it from our associated set, we abort this whole transaction if
- # another agent manages to change our list out from under us
- # When watching a value, the pipeline is set to Immediate mode
- pipe.watch(list_key)
-
- # Get the last elem that we'll trim (so we can remove it from our sorted set)
- last_val = cast( # mypy doesn’t know the pipe is in immediate mode
- bytes | None, pipe.lindex(list_key, max_api_calls - 1)
- )
-
- # Restart buffered execution
- pipe.multi()
-
- # Add this timestamp to our list
- pipe.lpush(list_key, now)
-
- # Trim our list to the oldest rule we have
- pipe.ltrim(list_key, 0, max_api_calls - 1)
-
- # Add our new value to the sorted set that we keep
- # We need to put the score and val both as timestamp,
- # as we sort by score but remove by value
- pipe.zadd(set_key, {str(now): now})
-
- # Remove the trimmed value from our sorted set, if there was one
- if last_val is not None:
- pipe.zrem(set_key, last_val)
-
- # Set the TTL for our keys as well
- api_window = max_api_window
- pipe.expire(list_key, api_window)
- pipe.expire(set_key, api_window)
-
- pipe.execute()
-
- # If no exception was raised in the execution, there were no transaction conflicts
- break
- except redis.WatchError: # nocoverage # Ideally we'd have a test for this.
- if count > 10:
- raise RateLimiterLockingError
- count += 1
-
- continue
+ tat = float(stored_tat)
+ calls_remaining = max(0, int((now + range_seconds - tat) * max_calls // range_seconds))
+ secs_to_reset = tat - now
+ return calls_remaining, secs_to_reset
@classmethod
@override
def rate_limit_entity(
cls, entity_key: str, rules: list[tuple[int, int]], max_api_calls: int, max_api_window: int
) -> tuple[bool, float, int, float]:
- ratelimited, time = cls.is_ratelimited(entity_key, rules)
-
- if not ratelimited:
- try:
- cls.incr_ratelimit(entity_key, max_api_calls, max_api_window)
- except RateLimiterLockingError:
- logger.warning("Deadlock trying to incr_ratelimit for %s", entity_key)
- # rate-limit users who are hitting the API so hard we can't update our stats.
- ratelimited = True
-
- if ratelimited:
- return True, time, 0, 0.0
-
- calls_remaining, secs_to_reset = cls.get_api_calls_left(
- entity_key, max_api_window, max_api_calls
- )
- return False, 0.0, calls_remaining, secs_to_reset
+ assert rules
+ gcra_key, block_key = cls.get_keys(entity_key)
+
+ # Build args: num_rules, w1, l1, w2, l2, ...[, now]
+ # The Lua script uses Redis TIME internally for clock
+ # consistency; tests may pass a trailing timestamp override.
+ args: list[float | int] = [len(rules)]
+ for window, limit in rules:
+ args.append(window)
+ args.append(limit)
+ if cls._testing_clock:
+ args.append(time.time())
+
+ result = cls._get_script()(keys=[block_key, gcra_key], args=args)
+
+ ratelimited = result[0] == b"1"
+ secs_to_freedom = float(result[1])
+ calls_remaining = int(result[2])
+ secs_to_reset = float(result[3])
+
+ return ratelimited, secs_to_freedom, calls_remaining, secs_to_reset
class RateLimitResult:
diff --git a/zerver/tests/test_external.py b/zerver/tests/test_external.py
index 75cb9c6ce19..dcc787b9652 100644
--- a/zerver/tests/test_external.py
+++ b/zerver/tests/test_external.py
@@ -6,6 +6,7 @@ from typing import IO, TYPE_CHECKING, Any
from unittest import mock, skipUnless
import orjson
+import time_machine
from circuitbreaker import CircuitBreakerMonitor
from django.conf import settings
from django.test import override_settings
@@ -13,12 +14,7 @@ from django.utils.timezone import now as timezone_now
from typing_extensions import override
from zerver.lib.cache import cache_delete
-from zerver.lib.rate_limiter import (
- RateLimitedIPAddr,
- RateLimitedUser,
- RateLimiterLockingError,
- get_tor_ips,
-)
+from zerver.lib.rate_limiter import RateLimitedIPAddr, RateLimitedUser, get_tor_ips
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import ratelimit_rule
from zerver.models import PushDeviceToken, UserProfile
@@ -52,7 +48,6 @@ class RateLimitTests(ZulipTestCase):
@override
def tearDown(self) -> None:
settings.RATE_LIMITING = False
-
super().tearDown()
def send_api_message(self, user: UserProfile, content: str) -> "TestHttpResponse":
@@ -86,13 +81,18 @@ class RateLimitTests(ZulipTestCase):
self.assertTrue("X-RateLimit-Limit" in result.headers)
self.assertTrue("X-RateLimit-Reset" in result.headers)
+ @ratelimit_rule(60, 200, domain="api_by_user")
def test_ratelimit_decrease(self) -> None:
user = self.example_user("hamlet")
RateLimitedUser(user).clear_history()
- result = self.send_api_message(user, "some stuff")
+ start_time = time.time()
+
+ with time_machine.travel(start_time, tick=False):
+ result = self.send_api_message(user, "some stuff")
limit = int(result["X-RateLimit-Remaining"])
- result = self.send_api_message(user, "some stuff 2")
+ with time_machine.travel(start_time + 0.001, tick=False):
+ result = self.send_api_message(user, "some stuff 2")
newlimit = int(result["X-RateLimit-Remaining"])
self.assertEqual(limit, newlimit + 1)
@@ -107,9 +107,9 @@ class RateLimitTests(ZulipTestCase):
json = result.json()
self.assertEqual(json.get("result"), "error")
self.assertIn("API usage exceeded rate limit", json.get("msg"))
- self.assertEqual(json.get("retry-after"), 0.5)
+ self.assertAlmostEqual(json.get("retry-after"), 0.195, places=2)
self.assertTrue("Retry-After" in result.headers)
- self.assertEqual(result["Retry-After"], "0.5")
+ self.assertAlmostEqual(float(result["Retry-After"]), 0.195, places=2)
def user_facing_assert_func(result: "TestHttpResponse") -> None:
self.assertEqual(result.status_code, 429)
@@ -123,7 +123,7 @@ class RateLimitTests(ZulipTestCase):
start_time = time.time()
for i in range(6):
- with mock.patch("time.time", return_value=start_time + i * 0.1):
+ with time_machine.travel(start_time + i * 0.001, tick=False):
result = request_func()
if i < 5:
self.assertNotEqual(result.status_code, 429)
@@ -133,7 +133,7 @@ class RateLimitTests(ZulipTestCase):
# We simulate waiting a second here, rather than force-clearing our history,
# to make sure the rate-limiting code automatically forgives a user
# after some time has passed.
- with mock.patch("time.time", return_value=start_time + 1.01):
+ with time_machine.travel(start_time + 1.01, tick=False):
result = request_func()
self.assertNotEqual(result.status_code, 429)
@@ -394,23 +394,3 @@ class RateLimitTests(ZulipTestCase):
)
finally:
self.DEFAULT_SUBDOMAIN = original_default_subdomain
-
- def test_hit_ratelimiterlockingexception(self) -> None:
- user = self.example_user("cordelia")
- RateLimitedUser(user).clear_history()
-
- with mock.patch(
- "zerver.lib.rate_limiter.RedisRateLimiterBackend.incr_ratelimit",
- side_effect=RateLimiterLockingError,
- ):
- with self.assertLogs("zerver.lib.rate_limiter", level="WARNING") as m:
- result = self.send_api_message(user, "some stuff")
- self.assertEqual(result.status_code, 429)
- self.assertEqual(
- m.output,
- [
- "WARNING:zerver.lib.rate_limiter:Deadlock trying to incr_ratelimit for {}".format(
- f"RateLimitedUser:{user.id}:api_by_user"
- )
- ],
- )
diff --git a/zerver/tests/test_rate_limiter.py b/zerver/tests/test_rate_limiter.py
index b775bf4bd5c..b08fbc0f54d 100644
--- a/zerver/tests/test_rate_limiter.py
+++ b/zerver/tests/test_rate_limiter.py
@@ -165,11 +165,14 @@ class RedisRateLimiterBackendTest(RateLimiterBackendBase):
def api_calls_left_from_history(
self, history: list[float], max_window: int, max_calls: int, now: float
) -> tuple[int, float]:
- latest_timestamp = history[-1]
- relevant_requests = [t for t in history if t >= now - max_window]
- relevant_requests_amount = len(relevant_requests)
+ reset_time = 0.0
+ for timestamp in history:
+ reset_time = max(reset_time, timestamp) + (max_window / max_calls)
- return max_calls - relevant_requests_amount, latest_timestamp + max_window - now
+ calls_left = (now + max_window - reset_time) * max_calls // max_window
+ calls_left = int(calls_left)
+
+ return calls_left, reset_time - now
def test_block_access(self) -> None:
"""
diff --git a/zerver/tests/test_settings.py b/zerver/tests/test_settings.py
index 8a19d61a5a6..f68baa0de1f 100644
--- a/zerver/tests/test_settings.py
+++ b/zerver/tests/test_settings.py
@@ -272,7 +272,7 @@ class ChangeSettingsTest(ZulipTestCase):
),
)
self.assert_json_error(
- result, "You're making too many attempts! Try again in 10 seconds."
+ result, "You're making too many attempts! Try again in 5 seconds."
)
# After time passes, we should be able to succeed if we give the correct password.
diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.py
index 89848ae6a7e..edd06441763 100644
--- a/zerver/tests/test_signup.py
+++ b/zerver/tests/test_signup.py
@@ -987,7 +987,7 @@ class LoginTest(ZulipTestCase):
# We're over the allowed limit, so the next attempt, even with the correct
# password, will get blocked.
result = self.login_with_return(email)
- self.assert_in_success_response(["Try again in 10 seconds"], result)
+ self.assert_in_success_response(["Try again in 5 seconds"], result)
# After time passes, we should be able to log in.
with patch("time.time", return_value=start_time + 11):