Api Rate Abuse in Fastapi with Api Keys
Api Rate Abuse in Fastapi with Api Keys — how this specific combination creates or exposes the vulnerability
Rate abuse in FastAPI when using API keys typically involves scenarios where a client with a valid key exceeds intended request volume, leading to denial of service for others or inflated costs. FastAPI does not enforce rate limits by default, so developers often add key validation without corresponding throttling. If API keys are issued broadly (for example, per user or per client application) and stored in headers or query parameters, an attacker who obtains a key can make rapid, repeated calls until the backend resource is exhausted. This is common with keys embedded in client-side code or logs that are inadvertently exposed.
The vulnerability is not in the API key mechanism itself, but in the absence of coordinated rate limiting. Without per-key tracking, a single key can be used to bypass intended usage caps. For instance, an endpoint that returns user data may be called thousands of times per second using a leaked key, consuming database connections and increasing latency for legitimate users. In a black-box scan, middleBrick tests unauthenticated endpoints and can detect missing rate controls; when API keys are present but rate limits are absent or misconfigured, the tool may flag the API under BFLA/Privilege Escalation and Rate Limiting checks.
Attack patterns include rapid-fire requests using a single key, key sharing among many clients, or parameter pollution to evade simplistic counters. Because FastAPI applications often sit behind load balancers or reverse proxies, rate limiting might be partially implemented at the infrastructure layer, but if key-level granularity is missing, the protection is incomplete. middleBrick’s 12 security checks run in parallel and can surface these gaps by correlating authentication findings with rate limiting behavior, highlighting where key usage does not map to request throttling.
Api Keys-Specific Remediation in Fastapi — concrete code fixes
To remediate rate abuse with API keys in FastAPI, implement per-key rate limiting using a shared storage backend such as Redis. This ensures that each key is subject to a defined request rate regardless of how the key is propagated. Combine this with dependency injection in FastAPI to validate keys and enforce limits before reaching business logic.
Example: a FastAPI app using Redis to track key usage with a sliding window.
import time
from fastapi import FastAPI, Depends, HTTPException, Header
import aioredis
app = FastAPI()
async def get_redis():
redis = await aioredis.from_url("redis://localhost")
try:
return redis
except Exception:
raise
async def rate_limit_key(api_key: str = Header(...), redis=Depends(get_redis)):
# key format: "rate_limit:{api_key}"
limit = 100 # max requests
window = 60 # per 60 seconds
now = time.time()
pipe = redis.pipeline()
# Remove outdated entries
pipe.zremrangebyscore(f"rate:{api_key}", 0, now - window)
# Count current requests
pipe.zcard(f"rate:{api_key}")
# Add current request timestamp
pipe.zadd(f"rate:{api_key}", {str(now): now})
pipe.expire(f"rate:{api_key}", window)
results = await pipe.execute()
count = results[1]
if count > limit:
raise HTTPException(status_code=429, detail="Rate limit exceeded for this API key")
return api_key
@app.get("/data")
async def read_data(key: str = Depends(ratelimit_key)):
return {"message": "success"}In this pattern, each API key is tracked independently in a sorted set with timestamps. The check runs as an async dependency, ensuring that requests beyond the configured threshold are rejected with HTTP 429. For production, ensure Redis is secured and connection handling is robust. middleBrick’s CLI can be used to validate that such controls are present by scanning the endpoint and checking whether rate limiting findings appear under Rate Limiting and Authentication categories.
Additional practices include rotating keys, avoiding long-lived keys, and monitoring request patterns. If using the middleBrick GitHub Action, you can fail CI/CD builds when a key-protected endpoint lacks detectable rate limiting, helping prevent regressions as code evolves.