import hashlib import hmac import json import time from fastapi import HTTPException, Request from starlette.responses import JSONResponse def require_secret(actual, expected): if not actual or not hmac.compare_digest(actual, expected): raise HTTPException(401, "unauthorized") async def rate_limit(redis, bucket: str, limit=60, seconds=60): # Atomic counter + expiry: a crash cannot leave a permanent bucket. key = "hn:rate:" + hashlib.sha256(bucket.encode()).hexdigest() + ":" + str(int(time.time()) // seconds) pipe = redis.pipeline(transaction=True) pipe.incr(key) pipe.expire(key, seconds * 2) result = (await pipe.execute())[0] if int(result) > limit: raise HTTPException(429, "rate limited", headers={"Retry-After": str(seconds)}) class BodyLimitMiddleware: def __init__(self, app, max_body=262144): self.app, self.max_body = app, max_body async def __call__(self, scope, receive, send): if scope["type"] != "http": return await self.app(scope, receive, send) messages, size = [], 0 while True: message = await receive() if message["type"] == "http.disconnect": return size += len(message.get("body", b"")) if size > self.max_body: return await JSONResponse({"detail": "body too large"}, status_code=413)(scope, receive, send) messages.append(message) if not message.get("more_body", False): break async def buffered(): return messages.pop(0) if messages else await receive() await self.app(scope, buffered, send) def no_cache(response): response.headers["Cache-Control"] = "no-store" response.headers["X-Content-Type-Options"] = "nosniff" response.headers["Referrer-Policy"] = "no-referrer" return response async def json_pub(redis, channel, data): return await redis.publish(channel, json.dumps(data, separators=(",", ":"))) def peer(request: Request): # Do not trust arbitrary X-Forwarded-For; configure uvicorn trusted proxies explicitly. return request.client.host if request.client else "unknown"