Merge gap-b-per-ip-limit: per-IP WS rate limiting via CF-Connecting-IP

This commit is contained in:
Indiana
2026-07-23 00:33:28 +00:00
4 changed files with 163 additions and 6 deletions

View File

@@ -1,6 +1,6 @@
from unittest.mock import patch
from app.rate_limit import RateLimiter
from app.rate_limit import RateLimiter, resolve_client_ip
def test_allows_up_to_limit_then_blocks():
@@ -29,3 +29,20 @@ def test_hits_expire_after_window_elapses():
with patch("app.rate_limit.time.monotonic", return_value=111.0):
# 11 seconds later, both prior hits (at t=100) are older than window_start (111 - 10 = 101)
assert limiter.allow("user-1") is True
def test_resolve_client_ip_prefers_cf_connecting_ip_over_socket_peer():
# The App CT sits behind a Cloudflare Tunnel on a separate machine — the
# raw socket peer is always the tunnel, never the visitor, for every
# internet-facing request.
headers = {"cf-connecting-ip": "203.0.113.7"}
assert resolve_client_ip(headers, "10.30.20.1") == "203.0.113.7"
def test_resolve_client_ip_falls_back_to_socket_peer_without_header():
# Direct LAN/local access (no Cloudflare in front) has no such header.
assert resolve_client_ip({}, "10.30.20.1") == "10.30.20.1"
def test_resolve_client_ip_falls_back_to_unknown_with_no_peer_or_header():
assert resolve_client_ip({}, None) == "unknown"

View File

@@ -7,6 +7,7 @@ import app.ws
from app.entities import fallback_profile
from app.models.contact_session import ContactSession
from app.models.event import Event
from app.rate_limit import RateLimiter
class FakeSpiritService:
@@ -175,3 +176,92 @@ async def test_same_signature_recontacts_same_entity(sync_client):
assert second_frame["entity"]["name"] == first
assert second_frame["is_new"] is False
assert second_frame["entity"]["contact_count"] == 2
@pytest.mark.asyncio
async def test_summon_rate_limited_per_account(sync_client, monkeypatch):
# Swap in a tight, test-scoped limiter so this doesn't depend on (or
# pollute) the shared module-level budget other tests draw from.
monkeypatch.setattr(
app.ws, "summon_limiter", RateLimiter(max_requests=2, window_seconds=60)
)
_login(sync_client, "account-limited")
with _ws_connect(sync_client, sync_client.cookies.get("qm_session")) as ws:
_read_until(ws, "session")
for _ in range(2):
ws.send_json({"type": "summon"})
_read_until(ws, "entity")
_read_until(ws, "utterance", kind="greeting")
ws.send_json({"type": "summon"})
rejection = _read_until(ws, "error")
assert rejection["code"] == "rate_limited"
assert rejection["message"] == (
"The veil is crowded. The spirits need a moment before another summoning."
)
@pytest.mark.asyncio
async def test_summon_rate_limited_per_ip_even_with_fresh_account(
sync_client, monkeypatch
):
# Starve only the IP bucket; the per-account limiter stays at its
# production default so each account below has plenty of its own budget
# left. This proves the IP limiter alone can reject a request — the
# gap the per-account-only limiters left open.
monkeypatch.setattr(
app.ws, "summon_ip_limiter", RateLimiter(max_requests=1, window_seconds=60)
)
_login(sync_client, "ip-limited-a")
with _ws_connect(sync_client, sync_client.cookies.get("qm_session")) as ws:
_read_until(ws, "session")
ws.send_json({"type": "summon"})
_read_until(ws, "entity") # spends the single per-IP slot
# A different account — its own per-account budget is untouched — but
# every connection in this test shares the same (simulated) source IP,
# which is already spent.
_login(sync_client, "ip-limited-b")
with _ws_connect(sync_client, sync_client.cookies.get("qm_session")) as ws:
_read_until(ws, "session")
ws.send_json({"type": "summon"})
rejection = _read_until(ws, "error")
assert rejection["code"] == "rate_limited"
assert rejection["message"] == (
"The veil is crowded. The spirits need a moment before another summoning."
)
@pytest.mark.asyncio
async def test_summon_per_ip_bucket_follows_cf_connecting_ip_not_socket_peer(
sync_client, monkeypatch
):
# Every connection in this test suite shares the same simulated socket
# peer (TestClient has no real network). Without preferring
# CF-Connecting-IP, distinct visitors behind the Cloudflare Tunnel would
# collapse into one shared per-IP bucket — this proves they don't.
monkeypatch.setattr(
app.ws, "summon_ip_limiter", RateLimiter(max_requests=1, window_seconds=60)
)
token_a = _login(sync_client, "cf-ip-a")
with sync_client.websocket_connect(
"/ws/session",
headers={"cookie": f"qm_session={token_a}", "cf-connecting-ip": "203.0.113.1"},
) as ws:
_read_until(ws, "session")
ws.send_json({"type": "summon"})
_read_until(ws, "entity") # spends visitor A's per-IP slot only
token_b = _login(sync_client, "cf-ip-b")
with sync_client.websocket_connect(
"/ws/session",
headers={"cookie": f"qm_session={token_b}", "cf-connecting-ip": "203.0.113.2"},
) as ws:
_read_until(ws, "session")
ws.send_json({"type": "summon"})
# A different visitor IP behind the same tunnel — must not be
# rejected by visitor A's already-spent bucket.
_read_until(ws, "entity")