Spaces:
Sleeping
Sleeping
fix: key rate-limit buckets on X-Forwarded-For behind Spaces ingress
Browse filesFiles changed (2)
48 unmodified lines4950515253541 unmodified line5657585960616248 unmodified linesfrom slowapi.errors import RateLimitExceededfrom slowapi.util import get_remote_address# One global per-IP budget, NOT per-route @limiter.limit decorators β# decorators would force the slowapi import whenever routes.py is# imported, which breaks the no-slowapi CI env. application_limits (scope1 unmodified line# endpoints doesn't multiply the budget by seven. 30/min covers real# interactive usage; /api/explain (~50 forward passes per call) is what# this protects.limiter = Limiter(key_func=get_remote_address, application_limits=["30/minute"])app.state.limiter = limiterapp.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)48 unmodified lines495051525354555657585960616263646566671 unmodified line6970717273747548 unmodified linesfrom slowapi.errors import RateLimitExceededfrom slowapi.util import get_remote_addressdef client_ip(request: Request) -> str:# Spaces terminates TLS at its ingress, so request.client.host is an# ingress hop, not the user β and the ingress is a fleet, so per-IP# buckets would fragment across hops (verified live: 36 rapid# requests, zero 429s). The real client is in X-Forwarded-For. Use# the RIGHTMOST entry: it's appended by the trusted ingress itself,# while leftmost entries arrive client-controlled β trusting those# would let an attacker mint fresh buckets with a spoofed header.xff = request.headers.get("x-forwarded-for")if xff:return xff.rsplit(",", 1)[-1].strip()return get_remote_address(request)# One global per-IP budget, NOT per-route @limiter.limit decorators β# decorators would force the slowapi import whenever routes.py is# imported, which breaks the no-slowapi CI env. application_limits (scope1 unmodified line# endpoints doesn't multiply the budget by seven. 30/min covers real# interactive usage; /api/explain (~50 forward passes per call) is what# this protects.limiter = Limiter(key_func=client_ip, application_limits=["30/minute"])app.state.limiter = limiterapp.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
62 unmodified lines63646566676862 unmodified lines_restore(["PUBLIC_DEPLOY"])def test_default_app_has_no_limiter_or_static_mount():"""Neither switch set (dev/CI default): no 429s ever, and GET / is a 404 βthe SPA is served by Vite (dev) or nginx (compose), not FastAPI."""62 unmodified lines6364656667686970717273747576777879808182838485868788899091929394959662 unmodified lines_restore(["PUBLIC_DEPLOY"])def test_rate_limit_buckets_key_on_rightmost_forwarded_for():"""Behind the Spaces ingress the client IP arrives in X-Forwarded-For.Buckets must key on the RIGHTMOST entry (appended by the trusted ingress);leftmost entries are client-controlled, so keying on them would let aspoofed header mint unlimited fresh buckets."""pytest.importorskip("slowapi")module = _reload_with({"PUBLIC_DEPLOY": "1"})try:with TestClient(module.app) as c:exhaust = {"X-Forwarded-For": "6.6.6.6, 9.9.9.9"}statuses = [c.get("/api/health", headers=exhaust).status_code for _ in range(31)]assert statuses[30] == 429# Same trusted (rightmost) hop, different spoofed leftmost entry:# still the SAME bucket β the spoof buys no fresh budget.spoof = {"X-Forwarded-For": "1.2.3.4, 9.9.9.9"}assert c.get("/api/health", headers=spoof).status_code == 429# A genuinely different client (different rightmost entry) is# unaffected by the exhausted bucket.other = {"X-Forwarded-For": "6.6.6.6, 7.7.7.7"}assert c.get("/api/health", headers=other).status_code == 200finally:_restore(["PUBLIC_DEPLOY"])def test_default_app_has_no_limiter_or_static_mount():"""Neither switch set (dev/CI default): no 429s ever, and GET / is a 404 βthe SPA is served by Vite (dev) or nginx (compose), not FastAPI."""
backend/app/main.py+14-1
backend/tests/test_public_deploy.py+28