diff --git a/generator/src/api.py b/generator/src/api.py index 34c0e03..3837c85 100644 --- a/generator/src/api.py +++ b/generator/src/api.py @@ -84,6 +84,7 @@ _RATE_LIMITS = { } _rate_lock = Lock() _rate_hits: dict[tuple[str, str], deque] = defaultdict(deque) +_rate_hits_per_login: dict[tuple[str, str], deque] = defaultdict(deque) def _client_ip() -> str: @@ -111,12 +112,39 @@ def _rate_limit(bucket: str) -> bool: return True +def _rate_limit_per_login(bucket: str, login: str) -> bool: + """Per-login rate limit layered on top of per-IP limit. + + Returns True if allowed; False if the login has exceeded the limit. + If no login (unauthenticated), returns True (per-IP already covers it). + """ + if not login: + return True # per-IP already covers the unauth path + if bucket == "mutate": + limit, window = config.RATE_LIMIT_MUTATE_PER_LOGIN_MAX, config.RATE_LIMIT_MUTATE_PER_LOGIN_WINDOW + else: + return True + now = time.time() + cutoff = now - window + key = (bucket, login) + with _rate_lock: + q = _rate_hits_per_login[key] + while q and q[0] < cutoff: + q.popleft() + if len(q) >= limit: + return False + q.append(now) + return True + + def rate_limited(bucket: str): def deco(fn): @wraps(fn) def wrapper(*args, **kwargs): if not _rate_limit(bucket): return jsonify({"error": "rate_limited"}), 429 + if not _rate_limit_per_login(bucket, auth.current_login() or ""): + return jsonify({"error": "rate_limited"}), 429 return fn(*args, **kwargs) return wrapper return deco diff --git a/generator/tests/test_api.py b/generator/tests/test_api.py index d31618a..94da851 100644 --- a/generator/tests/test_api.py +++ b/generator/tests/test_api.py @@ -21,6 +21,9 @@ def client(monkeypatch): app.config["SESSION_COOKIE_SECURE"] = False with app.test_client() as c: yield c + # Clear rate limit state after each test to prevent pollution. + apimod._rate_hits.clear() + apimod._rate_hits_per_login.clear() def test_health(client): @@ -244,3 +247,22 @@ def test_enroll_endpoint_is_gone(client): r = client.post("/api/enroll", json={"username": "alice"}, headers={"Origin": "https://gh-stats.com"}) assert r.status_code == 405 + + +def test_per_login_mutate_rate_limit(client, monkeypatch): + """Per-login rate limit on mutate routes allows up to MAX requests, + then rejects with 429.""" + monkeypatch.setattr(cfg, "RATE_LIMIT_MUTATE_PER_LOGIN_MAX", 2) + monkeypatch.setattr(cfg, "RATE_LIMIT_MUTATE_PER_LOGIN_WINDOW", 60) + dbmod.enroll("alice", {"theme": "dark"}) + with client.session_transaction() as s: + s["gh_login"] = "alice" + h = {"Origin": "https://gh-stats.com"} + # First two requests should succeed. + r1 = client.patch("/api/alice/settings", json={}, headers=h) + assert r1.status_code == 200 + r2 = client.patch("/api/alice/settings", json={}, headers=h) + assert r2.status_code == 200 + # Third request should be rate-limited. + r3 = client.patch("/api/alice/settings", json={}, headers=h) + assert r3.status_code == 429