Coverage for rate_limiter.py: 79.25%
43 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:10 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:10 +0000
1"""
2Rate limiting for the authentication endpoints (SB-640) and live chat (SB-1309).
4This module holds **only limits that are actually enforced**. It used to
5carry a four-category policy — public, authenticated, admin, auth — none of
6which was in effect: the middleware and every decorator were commented out,
7so `RATE_LIMITS` read as a live policy while login and signup were
8unthrottled. Dead security config that reads as active is worse than none,
9because it invites the assumption that login is throttled when it is not.
11Two decisions worth keeping:
13**No global default limits, and no SlowAPIMiddleware.** `SlowAPIMiddleware`
14exists to apply `default_limits` to every request. The old defaults were 200
15per hour and 50 per minute, which the product itself would breach: the LIVE
16tab polls while a match is being scored, and ingest posts fixtures in bulk.
17Turning that on would have looked like an outage. Limits are applied per
18endpoint with `@rate_limit(...)` instead, which needs no middleware — so the
19"middleware order issue" the old code hedged about does not arise.
21**The key is the forwarded client IP, not the socket peer.** Behind the
22ingress every request arrives from one address, so keying on
23`slowapi.util.get_remote_address` would put every user in the world into a
24single bucket and five failed logins anywhere would lock out everyone. The
25app already resolves the real client for audit logging; this uses the same
26rule. `X-Forwarded-For` is spoofable by a direct caller, but the ingress
27rewrites it, and the alternative is a shared bucket that is trivially
28exhausted by accident.
29"""
31import logging
32import os
34import jwt
35import redis
36from fastapi import Request
37from slowapi import Limiter, _rate_limit_exceeded_handler
38from slowapi.errors import RateLimitExceeded
40logger = logging.getLogger(__name__)
42# Redis makes one limit hold across every backend pod. Without it each pod
43# counts on its own, so the effective limit is (pods x limit) — still a
44# limit, just a looser one. Prod sets REDIS_URL; local usually does not.
45REDIS_URL = os.getenv("REDIS_URL", "")
47# Limits for the credential endpoints, the public invite form, and posting
48# to live chat. These are the ones being enforced; anything added here must
49# also be applied to a route to be real.
50RATE_LIMITS = {
51 "login": "5 per minute",
52 "signup": "3 per hour",
53 "password_reset": "3 per hour",
54 # Public, unauthenticated, and writes a row per call (SB-1311). The
55 # honeypot only stops bots that fill every field; this caps the rest.
56 "invite_request": "5 per hour",
57 "chat_message": "10 per minute", # per user, see user_key
58}
61def client_key(request: Request) -> str:
62 """The bucket a request counts against: its originating client.
64 Mirrors `get_client_ip` in app.py rather than importing it, to keep this
65 module free of an app-level import cycle. Both must stay in step: if one
66 starts trusting a different header, a limit silently becomes global.
67 """
68 forwarded_for = request.headers.get("x-forwarded-for")
69 if forwarded_for:
70 return forwarded_for.split(",")[0].strip()
71 if request.client and request.client.host:
72 return request.client.host
73 return "unknown"
76def user_key(request: Request) -> str:
77 """The bucket for a signed-in endpoint: the user, not the address.
79 A stadium of parents on one guest Wi-Fi shares an IP; chat must not
80 throttle all of them as one. The token's signature is not checked here
81 because it already has been: FastAPI resolves the endpoint's auth
82 dependency before slowapi's wrapper counts the request, so an invalid
83 token is refused with a 401 before it reaches this function. Falls back
84 to the client address when there is no readable token.
85 """
86 auth = request.headers.get("authorization", "")
87 if auth.lower().startswith("bearer "):
88 try:
89 sub = jwt.decode(auth[7:].strip(), options={"verify_signature": False}).get("sub")
90 except jwt.PyJWTError:
91 sub = None
92 if sub: 92 ↛ 94line 92 didn't jump to line 94 because the condition on line 92 was always true
93 return f"user:{sub}"
94 return client_key(request)
97def _storage_uri() -> str | None:
98 """Redis when it answers, None (in-memory) when it does not.
100 Checked once at import: a limiter pointed at an unreachable Redis fails
101 every request it is asked to count, which would take down login rather
102 than protect it.
103 """
104 if not REDIS_URL: 104 ↛ 106line 104 didn't jump to line 106 because the condition on line 104 was always true
105 return None
106 try:
107 redis.from_url(REDIS_URL, socket_connect_timeout=2).ping()
108 except Exception as exc:
109 logger.warning("rate_limit_redis_unavailable falling back to in-memory: %s", exc)
110 return None
111 logger.info("rate_limit_storage_redis")
112 return REDIS_URL
115# headers_enabled is off deliberately. slowapi injects X-RateLimit-* by
116# writing to a `response: Response` parameter, which every decorated
117# endpoint would then have to declare — and an endpoint that forgets raises
118# at request time, turning a missing annotation into a broken login. The
119# 429 still carries Retry-After, which is the part a client acts on.
120limiter = Limiter(key_func=client_key, storage_uri=_storage_uri(), headers_enabled=False)
123def install_rate_limiting(app) -> Limiter:
124 """Attach the limiter to the app so `@rate_limit(...)` decorators work.
126 slowapi reads `app.state.limiter` when a decorated endpoint runs, and
127 needs a handler for RateLimitExceeded to turn it into a 429 instead of a
128 500. No middleware is added on purpose — see the module docstring.
129 """
130 app.state.limiter = limiter
131 app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
132 return limiter
135def rate_limit(limit: str, key_func=None):
136 """Apply a limit to one endpoint. The endpoint must take `request: Request`.
138 `key_func` overrides the default per-client-IP bucket (e.g. `user_key`).
139 """
140 return limiter.limit(limit, key_func=key_func)