Api Rate Abuse in Fastapi with Basic Auth
Api Rate Abuse in Fastapi with Basic Auth — how this specific combination creates or exposes the vulnerability
Rate abuse occurs when an attacker sends a high volume of requests to an endpoint to exhaust server resources, degrade performance, or bypass usage limits. In Fastapi, combining public endpoints or weakly enforced authentication with Basic Auth can amplify risk because credentials are only base64-encoded, not encrypted. An attacker who intercepts or guesses a single valid credential pair can script repeated authentication requests, making each request appear legitimate to rate limiters that rely solely on IP or endpoint-level counting.
When Basic Auth is used without additional protections, attackers can enumerate valid usernames through timing differences or error messages, then focus brute-force or credential-stuffing campaigns against those accounts. Because Basic Auth transmits credentials with every request, intercepted tokens remain reusable until expiration or revocation, enabling sustained rate abuse even after initial detection. Without per-user rate limits, an attacker using a valid pair can saturate database connections or compute resources, affecting availability for legitimate users.
middleBrick scans such combinations by running 12 parallel checks, including Rate Limiting and Authentication, and flags scenarios where per-user throttling is absent or inconsistent. Findings map to OWASP API Top 10 categories such as Broken Object Level Authorization (BOLA) and Rate Limiting weaknesses, providing prioritized guidance and remediation steps instead of attempting to fix the issue automatically.
Basic Auth-Specific Remediation in Fastapi — concrete code fixes
To reduce rate abuse risk with Basic Auth in Fastapi, implement per-user or per-identity rate limits and avoid relying on IP-based limits alone. Use a fast in-memory store like Redis to track request counts keyed by a stable identifier derived from the decoded username, and enforce limits before routing to business logic.
Below is a complete, working example that combines HTTP Basic Auth with a Redis-backed rate limiter. It decodes credentials, validates them against a user store, and applies limits specific to each authenticated identity.
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from passlib.context import CryptContext
import aioredis
import os
app = FastAPI()
security = HTTPBasic()
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# Example user store; in production use a database
USERS = {
"alice": pwd_context.hash("s3cret1"),
"bob": pwd_context.hash("s3cret2")
}
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379")
async def get_redis():
redis = await aioredis.from_url(REDIS_URL, decode_responses=True)
return redis
def verify_user(credentials: HTTPBasicCredentials = Depends(security)):
hashed = USERS.get(credentials.username)
if not hashed or not pwd_context.verify(credentials.password, hashed):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
headers={"WWW-Authenticate": "Basic"}
)
return credentials.username
async def rate_limit_identity(identity: str, redis, limit: int = 5, window: int = 60):
key = f"rate:{identity}"
current = await redis.get(key)
if current is None:
await redis.set(key, 1, ex=window)
else:
if int(current) >= limit:
return False
await redis.incr(key)
return True
@app.get("/items")
async def read_items(username: str = Depends(verify_user), redis: aioredis.Redis = Depends(get_redis)):
allowed = await rate_limit_identity(username, redis, limit=10, window=60)
if not allowed:
raise HTTPException(status_code=429, detail="Rate limit exceeded")
return {"message": f"Hello {username}, here are your items"}
In this setup, each authenticated identity has its own counter, which mitigates distributed attackers using a single credential pair to flood the endpoint. For deployment, the Pro plan’s continuous monitoring can track rate limit effectiveness across endpoints and alert when abusive patterns are detected, while the CLI can integrate checks into scripts to validate configurations.
middleBrick’s scans verify whether per-identity throttling is present and highlight missing constraints, helping you align implementations with frameworks such as OWASP API Top 10 and PCI-DSS requirements. Note that middleBrick detects and reports these risks but does not modify code or block traffic; it provides prioritized findings with remediation guidance.