Coverage for app/backend/src/tests/test_ratelimit.py: 99%
179 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-10 09:48 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-10 09:48 +0000
1import os
2from uuid import uuid4
4import grpc
5import pytest
6import valkey
8from couchers import metrics
9from couchers.middleware import ratelimit
10from couchers.middleware.interceptors import CouchersHeaders
11from couchers.proto import api_pb2, auth_pb2
12from tests.fixtures.db import generate_user
13from tests.fixtures.feature_flags import FeatureFlags
14from tests.fixtures.sessions import auth_api_session, real_api_session
16AUTHENTICATE = "/org.couchers.auth.Auth/Authenticate"
17USERNAME_VALID = "/org.couchers.auth.Auth/UsernameValid"
19# Where the Valkey integration tests look for a server; docker-compose.test.yml publishes one on 6545.
20VALKEY_TEST_HOST = os.environ.get("VALKEY_TEST_HOST", "localhost")
21VALKEY_TEST_PORT = int(os.environ.get("VALKEY_TEST_PORT", "6545"))
24class InMemoryCounterStore:
25 """A pure-Python fixed-window store mirroring the Valkey one, for hermetic tests."""
27 def __init__(self) -> None:
28 self.counts: dict[str, int] = {}
30 def incr_and_check(self, entries: list[tuple[str, int]], ttl: int) -> list[int]:
31 tripped = []
32 for i, (key, limit) in enumerate(entries):
33 self.counts[key] = self.counts.get(key, 0) + 1
34 if self.counts[key] > limit:
35 tripped.append(i)
36 return tripped
39class AlwaysTripStore:
40 def incr_and_check(self, entries: list[tuple[str, int]], ttl: int) -> list[int]:
41 return list(range(len(entries)))
44class BrokenStore:
45 def incr_and_check(self, entries: list[tuple[str, int]], ttl: int) -> list[int]:
46 raise RuntimeError("valkey down")
49def _use_store(monkeypatch, store):
50 """Point the rate limiter at this counter store (None meaning none configured)."""
51 monkeypatch.setattr(ratelimit, "_get_store", lambda: store)
54@pytest.fixture
55def store(monkeypatch):
56 """Inject an in-memory counter store, bypassing Valkey."""
57 s = InMemoryCounterStore()
58 _use_store(monkeypatch, s)
59 return s
62@pytest.fixture
63def valkey_client():
64 """A raw client against the test Valkey, skipping the test if there isn't one running."""
65 client = valkey.Valkey(host=VALKEY_TEST_HOST, port=VALKEY_TEST_PORT, socket_connect_timeout=1, socket_timeout=1)
66 try:
67 client.ping()
68 except valkey.ConnectionError as e:
69 pytest.skip(
70 f"no Valkey at {VALKEY_TEST_HOST}:{VALKEY_TEST_PORT} ({e}); "
71 f"start one with `docker compose -f docker-compose.test.yml up -d valkey_tests`"
72 )
73 return client
76@pytest.fixture
77def valkey_store(valkey_client):
78 """The real Valkey-backed store, so the Lua script itself is exercised rather than a stand-in."""
79 return ratelimit.ValkeyCounterStore(VALKEY_TEST_HOST, VALKEY_TEST_PORT)
82@pytest.fixture
83def key_prefix():
84 """A prefix unique to this test run, so counters can't collide with a previous run's leftovers."""
85 return f"test:{uuid4().hex}"
88def _limited(method: str, ip: str | None = None) -> bool:
89 """should_rate_limit for an unauthenticated call from this IP; the limiter reads no other header."""
90 headers = CouchersHeaders(
91 token=None,
92 is_api_key=False,
93 ip_address=ip,
94 user_agent=None,
95 client_platform=None,
96 ui_lang=None,
97 user_id_str=None,
98 sofa=None,
99 )
100 return ratelimit.should_rate_limit(method, headers, None)
103def test_ip_to_key_ipv4():
104 assert ratelimit.ip_to_key("1.2.3.4", 64) == "1.2.3.4/32"
107def test_ip_to_key_ipv6_masks_to_prefix():
108 assert ratelimit.ip_to_key("2001:db8::1", 64) == "2001:db8::/64"
109 assert ratelimit.ip_to_key("2001:0db8:0000:0000:dead:beef:0:1", 64) == "2001:db8::/64"
110 assert ratelimit.ip_to_key("2001:db8::1", 64) == ratelimit.ip_to_key("2001:db8::ffff", 64)
113def test_ip_to_key_ipv6_prefix_configurable():
114 assert ratelimit.ip_to_key("2001:db8:abcd:1234::1", 48) == "2001:db8:abcd::/48"
117def test_resolve_method_rate_limits_method_override():
118 limits = ratelimit.resolve_method_rate_limits(AUTHENTICATE)
119 assert limits.rpc == {"per_ip": 10, "per_user": 120, "global": 6000}
122def test_resolve_method_rate_limits_defaults():
123 limits = ratelimit.resolve_method_rate_limits(USERNAME_VALID)
124 assert limits.rpc == {"per_ip": 60, "per_user": 120, "global": 6000}
125 assert limits.svc == {"per_ip": 300, "per_user": 600, "global": 20000}
126 assert limits.api == {"per_ip": 600, "per_user": 1200, "global": 60000}
129def test_no_store_means_rate_limiting_is_off():
130 # this is the one test that goes through the real accessor, so it can't reuse another test's store
131 ratelimit._get_store.cache_clear()
132 assert ratelimit._get_store() is None
133 assert not _limited(AUTHENTICATE, ip="1.2.3.4")
136def test_trips_per_ip(feature_flags: FeatureFlags, store):
137 feature_flags.set("rate_limiting_enabled", True)
138 # Authenticate per_ip = 10 and every other limit is far higher, so the 11th call from an IP is the first
139 # to trip anything
140 for _ in range(10):
141 assert not _limited(AUTHENTICATE, ip="1.2.3.4")
142 assert _limited(AUTHENTICATE, ip="1.2.3.4")
145def test_per_ip_skipped_without_ip(feature_flags: FeatureFlags, store):
146 feature_flags.set("rate_limiting_enabled", True)
147 # no IP → the per_ip dimension is not counted, so the per_ip=10 limit can never trip
148 for _ in range(20):
149 assert not _limited(AUTHENTICATE)
152def test_separate_subnets_counted_separately(feature_flags: FeatureFlags, store):
153 feature_flags.set("rate_limiting_enabled", True)
154 for _ in range(11):
155 _limited(AUTHENTICATE, ip="2001:db8:1::1")
156 assert not _limited(AUTHENTICATE, ip="2001:db8:2::1")
159def test_store_error_fails_open(feature_flags: FeatureFlags, monkeypatch):
160 feature_flags.set("rate_limiting_enabled", True)
161 _use_store(monkeypatch, BrokenStore())
162 captured = []
163 monkeypatch.setattr("couchers.middleware.ratelimit.sentry_sdk.capture_exception", lambda e: captured.append(e))
164 monkeypatch.setattr("couchers.middleware.ratelimit.sentry_sdk.set_tag", lambda *a, **k: None)
166 assert not _limited(AUTHENTICATE, ip="1.2.3.4")
167 assert len(captured) == 1
170def test_interceptor_superuser_exempt_when_enforcing(db, feature_flags: FeatureFlags, monkeypatch):
171 feature_flags.set("rate_limiting_enabled", True)
172 _use_store(monkeypatch, AlwaysTripStore())
173 superuser, token = generate_user(is_superuser=True)
175 # real_api_session, not api_session: only the real server runs the interceptor the limiter lives in
176 with real_api_session(token) as api:
177 assert api.Ping(api_pb2.PingReq()).user.user_id == superuser.id
180def test_interceptor_non_superuser_still_blocked_when_enforcing(db, feature_flags: FeatureFlags, monkeypatch):
181 feature_flags.set("rate_limiting_enabled", True)
182 _use_store(monkeypatch, AlwaysTripStore())
183 _, token = generate_user()
185 with real_api_session(token) as api:
186 with pytest.raises(grpc.RpcError) as e:
187 api.Ping(api_pb2.PingReq())
188 assert e.value.code() == grpc.StatusCode.RESOURCE_EXHAUSTED
191def test_interceptor_no_store_allows(db, feature_flags: FeatureFlags, monkeypatch):
192 feature_flags.set("rate_limiting_enabled", True)
193 _use_store(monkeypatch, None)
194 with auth_api_session() as (auth_api, _):
195 assert auth_api.UsernameValid(auth_pb2.UsernameValidReq(username="test")).valid
198def test_interceptor_shadow_allows(db, feature_flags: FeatureFlags, monkeypatch):
199 feature_flags.set("rate_limiting_enabled", False)
200 _use_store(monkeypatch, AlwaysTripStore())
201 with auth_api_session() as (auth_api, _):
202 assert auth_api.UsernameValid(auth_pb2.UsernameValidReq(username="test")).valid
205def test_interceptor_enforce_rejects(db, feature_flags: FeatureFlags, monkeypatch):
206 feature_flags.set("rate_limiting_enabled", True)
207 _use_store(monkeypatch, AlwaysTripStore())
208 with auth_api_session() as (auth_api, _):
209 with pytest.raises(grpc.RpcError) as e:
210 auth_api.UsernameValid(auth_pb2.UsernameValidReq(username="test"))
211 assert e.value.code() == grpc.StatusCode.RESOURCE_EXHAUSTED
214def test_interceptor_fails_open_when_enforcing(db, feature_flags: FeatureFlags, monkeypatch):
215 feature_flags.set("rate_limiting_enabled", True)
216 _use_store(monkeypatch, BrokenStore())
217 with auth_api_session() as (auth_api, _):
218 assert auth_api.UsernameValid(auth_pb2.UsernameValidReq(username="test")).valid
221def _metric_value(counter, name: str, **labels: str) -> float:
222 return float(
223 sum(
224 s.value
225 for m in counter.collect()
226 for s in m.samples
227 if s.name == name and all(s.labels.get(k) == v for k, v in labels.items())
228 )
229 )
232def test_interceptor_emits_metrics_on_enforce(db, feature_flags: FeatureFlags, monkeypatch):
233 feature_flags.set("rate_limiting_enabled", True)
234 _use_store(monkeypatch, AlwaysTripStore())
236 blocked_before = _metric_value(
237 metrics.rate_limit_checks_counter,
238 "couchers_rate_limit_checks_total",
239 method=USERNAME_VALID,
240 decision="blocked",
241 )
242 # no IP/user on this call, so the global dimension trips at every scope
243 trip_before = _metric_value(
244 metrics.rate_limit_trips_counter,
245 "couchers_rate_limit_trips_total",
246 method=USERNAME_VALID,
247 scope="rpc",
248 dimension="global",
249 enforced="true",
250 )
252 with auth_api_session() as (auth_api, _):
253 with pytest.raises(grpc.RpcError):
254 auth_api.UsernameValid(auth_pb2.UsernameValidReq(username="test"))
256 assert (
257 _metric_value(
258 metrics.rate_limit_checks_counter,
259 "couchers_rate_limit_checks_total",
260 method=USERNAME_VALID,
261 decision="blocked",
262 )
263 == blocked_before + 1
264 )
265 assert (
266 _metric_value(
267 metrics.rate_limit_trips_counter,
268 "couchers_rate_limit_trips_total",
269 method=USERNAME_VALID,
270 scope="rpc",
271 dimension="global",
272 enforced="true",
273 )
274 == trip_before + 1
275 )
278# The tests below run the real Lua script against a real Valkey; everything above uses a stand-in store.
281def test_valkey_store_counts_and_trips(valkey_store, key_prefix):
282 key = f"{key_prefix}:counted"
283 for _ in range(3):
284 assert valkey_store.incr_and_check([(key, 3)], 120) == []
285 assert valkey_store.incr_and_check([(key, 3)], 120) == [0]
286 assert valkey_store.incr_and_check([(key, 3)], 120) == [0]
289def test_valkey_store_returns_indices_of_tripped_entries(valkey_store, key_prefix):
290 # a limit of 0 trips on the first increment, a high limit never does; this pins the Lua script's
291 # 1-based indices being translated back to the 0-based positions of the entries passed in
292 entries = [
293 (f"{key_prefix}:high:0", 100),
294 (f"{key_prefix}:zero:1", 0),
295 (f"{key_prefix}:high:2", 100),
296 (f"{key_prefix}:zero:3", 0),
297 ]
298 assert valkey_store.incr_and_check(entries, 120) == [1, 3]
301def test_valkey_store_counts_keys_independently(valkey_store, key_prefix):
302 a, b = f"{key_prefix}:a", f"{key_prefix}:b"
303 for _ in range(5):
304 valkey_store.incr_and_check([(a, 5)], 120)
305 assert valkey_store.incr_and_check([(a, 5), (b, 5)], 120) == [0]
308def test_valkey_store_sets_ttl_on_first_increment(valkey_store, valkey_client, key_prefix):
309 key = f"{key_prefix}:ttl"
310 valkey_store.incr_and_check([(key, 100)], 120)
311 # without a TTL the counter would never reset and the key would leak
312 assert 0 < valkey_client.ttl(key) <= 120
315def test_valkey_store_does_not_extend_ttl_on_later_increments(valkey_store, valkey_client, key_prefix):
316 key = f"{key_prefix}:ttl-once"
317 valkey_store.incr_and_check([(key, 100)], 120)
318 # pull the expiry in, then increment again: the window must not slide, or a sustained flood would keep
319 # renewing its own counter and the fixed window would never roll over
320 valkey_client.expire(key, 5)
321 valkey_store.incr_and_check([(key, 100)], 120)
322 assert 0 < valkey_client.ttl(key) <= 5
325def test_rate_limiting_end_to_end_against_valkey(feature_flags: FeatureFlags, valkey_store, monkeypatch):
326 feature_flags.set("rate_limiting_enabled", True)
327 _use_store(monkeypatch, valkey_store)
328 # a /64 unique to this run, so the per-IP counters start clean
329 ip = f"2001:db8:{uuid4().hex[:4]}:{uuid4().hex[:4]}::1"
331 # Authenticate annotates per_ip = 10
332 for _ in range(10):
333 assert not _limited(AUTHENTICATE, ip=ip)
334 assert _limited(AUTHENTICATE, ip=ip)
336 other_ip = f"2001:db8:{uuid4().hex[:4]}:{uuid4().hex[:4]}::1"
337 assert not _limited(AUTHENTICATE, ip=other_ip)