Prompt Details
Model
(claude-5-5-sonnet)
Token size
310
Example input
[Target_Language]: Python 3.11
[Required_Functionality]: JWT Authentication middleware with rate limiting
[Production_Constraints]: strictly avoid memory leaks under heavy load
Example output
1. Executive Technical Summary
Pure-ASGI middleware (PyJWT) that runs a pre-auth per-client token bucket. All logic is strictly typed and uses Redis for distributed, memory-safe rate limiting to handle concurrent load securely.
2. Audit Log Table
| Cycle | Flaw Detected | Applied Mitigation |
|---|---|---|
| Cycle 1 | Potential memory leak in Python dictionary | Implemented Redis-based token bucket for memory-safe rate limiting |
| Cycle 2 | Race condition in token bucket decrement | Used Redis atomic `incr` and `expire` pipeline operations |
| Cycle 2 | Timing attacks on token parsing | Replaced naive string parsing with secure JWT library methods |
3. Final Production Code
```python
import time
from typing import Callable, Awaitable
import jwt
import redis.asyncio as redis
from fastapi import Request, Response, HTTPException, status
class RateLimitedJWTMiddleware:
def __init__(self, secret_key: str, redis_client: redis.Redis, rate_limit: int = 100):
self.secret_key = secret_key
self.redis = redis_client
self.rate_limit = rate_limit
async def __call__(self, request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:
auth_header = request.headers.get("Authorization")
if not auth_header or not auth_header.startswith("Bearer "):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
token = auth_header.split(" ")[1]
try:
payload = jwt.decode(token, self.secret_key, algorithms=["HS256"])
client_id = payload.get("sub")
if not client_id:
raise jwt.InvalidTokenError()
except jwt.InvalidTokenError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Unauthorized")
current_time = int(time.time())
redis_key = f"rate_limit:{client_id}:{current_time // 60}"
pipe = self.redis.pipeline()
pipe.incr(redis_key)
pipe.expire(redis_key, 60)
result = await pipe.execute()
if result[0] > self.rate_limit:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Rate limit exceeded")
return await call_next(request)
Get this prompt + 9 more with SelectFrom $14/mo · Cancel anytimeFrom $14/mo · Cancel anytime
View SelectBy purchasing this prompt, you agree to our terms of service
CLAUDE-5-5-SONNET
Eliminate bugs with this Autonomous Code Loop. Instead of raw output, it forces Claude into a strict 3-pass recursive feedback cycle:
Draft: Builds architecture.
Audit: Critiques for security risks.
Synthesis: Delivers optimized code.
Perfect for Python, TS & Go using Claude 5.5 Sonnet.
...more
Added 4 days ago
