Brute Force Attack in Fastapi with Api Keys
Brute Force Attack in Fastapi with Api Keys — how this specific combination creates or exposes the vulnerability
A brute force attack against Fastapi endpoints protected only by API keys exploits the simplicity and predictability of key distribution and validation logic. When API keys are accepted via headers or query parameters without additional controls, an attacker can systematically iterate through valid key formats or test leaked keys at authentication boundaries. Because Fastapi routes often rely on a single key for authorization, repeated guesses may succeed if key entropy is low, keys are shared across environments, or keys are embedded in client-side code that can be extracted.
The attack surface is expanded when OpenAPI specs expose authentication requirements without clarifying rate limits or key rotation. MiddleBrick’s authentication and rate limiting checks highlight scenarios where an unauthenticated or low-friction endpoint allows rapid requests, making online brute force feasible. For example, an endpoint like /admin/export that only checks api_key in the header can be probed with thousands of candidate keys. If the application responds differently to valid versus invalid keys (timing differences, distinct HTTP status codes, or verbose errors), attackers can infer correctness and chain this with other vulnerabilities such as BOLA/IDOR to access other users’ data.
Fastapi’s dependency system can inadvertently simplify brute force: a global dependency that retrieves the key from headers and validates it against a database may short-circuit on match, reducing per-request overhead for attackers. Without per-client rate limiting or exponential backoff, a single compromised key can lead to widespread exposure. The API key model also complicates mitigation, because key rotation requires coordinated updates across clients. If the spec does not document key revocation or if old keys remain valid for long periods, attackers can leverage previously leaked keys. MiddleBrick’s input validation and rate limiting checks surface these weaknesses by correlating spec definitions with runtime behavior, showing whether protections like request caps and anomaly detection are enforced.
Api Keys-Specific Remediation in Fastapi — concrete code fixes
Remediation centers on making brute force impractical by combining strong key management with request-level controls. Use high-entropy keys, avoid exposing them in logs or error messages, and enforce strict rate limits per client. Below are concrete Fastapi examples that integrate these practices.
Secure API key validation with rate limiting
from fastapi import Fastapi, Depends, HTTPException, Request
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from slowapi import Limiter
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
import secrets
import time
app = Fastapi()
security = HTTPBearer()
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
# In-memory store for demonstration; use Redis in production
VALID_KEYS = {secrets.token_urlsafe(32) for _ in range(10)}
@app.post("/export")
@limiter.limit("5/minute")
async def export_data(
request: Request,
credentials: HTTPAuthorizationCredentials = Depends(security)
):
if credentials.credentials not in VALID_KEYS:
# Always respond with the same status and generic message
raise HTTPException(status_code=401, detail="Unauthorized")
# Proceed with operation
return {"status": "ok"}
Key rotation and environment-based validation
import os
from fastapi import Fastapi, Depends, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
app = Fastapi()
security = HTTPBearer()
# Load current keys from environment; rotate by updating env and restarting
CURRENT_KEY = os.getenv("API_KEY")
PREVIOUS_KEY = os.getenv("API_KEY_PREV") # for graceful transition
async def verify_key(credentials: HTTPAuthorizationCredentials = Depends(security)):
if credentials.credentials not in (CURRENT_KEY, PREVIOUS_KEY):
raise HTTPException(status_code=401, detail="Unauthorized")
return credentials.credentials
@app.get("/data")
async def get_data(token=Depends(verify_key)):
return {"data": "sensitive"}
OpenAPI spec discipline to reduce attack surface
Ensure your OpenAPI spec documents authentication clearly and avoids leaking key formats. Use securitySchemes consistently and avoid default/example keys in generated docs.
openapi: 3.0.3
info:
title: Secure API
version: 1.0.0
paths:
/export:
post:
summary: Export data
security:
- ApiKeyAuth: []
responses:
'200':
description: OK
components:
securitySchemes:
ApiKeyAuth:
type: apiKey
in: header
name: X-API-Key
By combining high-entropy keys, uniform error responses, per-route rate limiting, and disciplined spec maintenance, brute force attempts become slow and noisy, enabling detection and blocking at the network or gateway layer.