HIGH denial of servicefastapiapi keys

Denial Of Service in Fastapi with Api Keys

Denial Of Service in Fastapi with Api Keys — how this specific combination creates or exposes the vulnerability

Denial of Service (DoS) in FastAPI when API keys are used for authentication can arise from a mix of resource-intensive request handling and weak key validation logic. FastAPI, built on Starlette, processes each request in an asynchronous context; if API key validation is performed inefficiently—such as making a synchronous database or external service call for every request—concurrency can be blocked, tying up worker cycles and limiting the number of requests the application can serve concurrently.

When API keys are accepted via headers (e.g., X-API-Key) but not validated with care, attackers can send many requests with invalid or missing keys, triggering expensive operations like regex checks, cryptographic verification, or repeated lookups. If these checks are not short-circuited early, they consume CPU and memory, increasing latency for legitimate users. In high-concurrency deployments, this can manifest as a bottleneck at the application layer rather than the network layer, effectively causing a DoS for valid clients.

Another vector specific to the combination of FastAPI and API keys is missing or misconfigured rate limiting. Without explicit limits tied to the key identity, a single compromised or malicious key can generate a high volume of traffic. Because FastAPI does not enforce throttling by default, an unthrottled endpoint that performs non-trivial work (e.g., querying a database or calling an external API) can be overwhelmed. This is especially risky when OpenAPI/Swagger specs describe endpoints as key-protected but do not reflect operational rate constraints, creating a mismatch between documented and actual resilience.

Furthermore, if API key validation logic is intertwined with business logic in path operations, an attacker can craft requests that force the server to perform complex computations or large data transformations before rejecting the key. For example, deserializing large JSON payloads or processing nested data structures prior to authorization can amplify resource usage. In such cases, the server may appear responsive but is internally saturated, leading to slow response times or timeouts for benign requests, a classic application-layer DoS scenario aligned with common OWASP API Top 10 risks around excessive resource consumption.

middleBrick scans such configurations and flags DoS-related findings across the 12 security checks, including Authentication, Rate Limiting, and Input Validation. By correlating OpenAPI spec definitions with runtime behavior, it highlights mismatches where authentication and throttling are under-specified or under-tested, helping teams understand how API key handling can contribute to availability risks.

Api Keys-Specific Remediation in Fastapi — concrete code fixes

To mitigate DoS risks when using API keys in FastAPI, implement early validation, efficient lookups, and explicit rate controls. Ensure that key verification is performed before any heavy processing, and that invalid keys fail quickly to avoid unnecessary resource consumption.

from fastapi import FastAPI, Depends, HTTPException, Header, status
from fastapi.security import APIKeyHeader
from typing import Dict
import time

app = FastAPI()

# In-memory key store (use a fast cache like Redis in production)
API_KEYS: Dict[str, str] = {
    "abc123": "service-a",
    "def456": "service-b",
}

# Define header-based key authentication
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)

def get_key(api_key: str = Depends(api_key_header)):
    if not api_key:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="API key missing",
        )
    # Fast fail: constant-time lookup to avoid timing-based side channels
    if api_key not in API_KEYS:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Invalid API key",
        )
    return api_key

# Apply dependency to routes that require key protection
@app.get("/secure-data")
def read_secure_data(x_api_key: str = Depends(get_key)):
    # Key is validated; proceed with lightweight business logic
    return {"message": "Authorized access", "service": API_KEYS[x_api_key]}

For production, replace the in-memory dictionary with a high-performance store such as Redis to keep lookup times predictable and reduce latency. Also enforce rate limits per key using a sliding window or token bucket algorithm; the following example demonstrates a simple in-memory rate limiter that can be expanded with a distributed cache:

from fastapi import FastAPI, Depends, HTTPException, Header, status
from collections import defaultdict
import time

app = FastAPI()

API_KEYS = {"abc123": "service-a"}
RATE_LIMIT = 100  # requests
WINDOW = 60       # seconds

# Track request timestamps per key
request_log: Dict[str, list] = defaultdict(list)

def rate_limited(key: str) -> bool:
    now = time.time()
    # Clean old entries
    request_log[key] = [t for t in request_log[key] if now - t < WINDOW]
    if len(request_log[key]) >= RATE_LIMIT:
        return True
    request_log[key].append(now)
    return False

def get_key_and_check_rate(api_key: str = Depends(api_key_header)):
    if not api_key or api_key not in API_KEYS:
        raise HTTPException(status_code=403, detail="Invalid key")
    if rate_limited(api_key):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")
    return api_key

@app.get("/limited")
def limited_endpoint(x_api_key: str = Depends(get_key_and_check_rate)):
    return {"ok": True}

In CI/CD workflows, the middleBrick GitHub Action can be added to validate that rate limiting and key validation are reflected in your OpenAPI spec and that scans do not detect missing controls. This helps ensure that remediation code aligns with declared security posture. For ongoing assurance, the middleBrick Pro plan provides continuous monitoring and alerts when availability-related findings reappear, while the CLI allows quick checks from the terminal with middlebrick scan <url>.

Related CWEs: resourceConsumption

CWE IDNameSeverity
CWE-400Uncontrolled Resource Consumption HIGH
CWE-770Allocation of Resources Without Limits MEDIUM
CWE-799Improper Control of Interaction Frequency MEDIUM
CWE-835Infinite Loop HIGH
CWE-1050Excessive Platform Resource Consumption MEDIUM

Frequently Asked Questions

Can API keys alone prevent DoS attacks in FastAPI?
No. API keys provide authentication but do not inherently limit traffic volume or protect against resource exhaustion. Without explicit rate limiting and efficient validation, an API key can be used to amplify DoS attacks by allowing unthrottled requests.
How does middleBrick help with DoS risks related to API keys?
middleBrick checks Authentication and Rate Limiting configurations, correlates them with OpenAPI definitions, and flags missing or inconsistent controls that can lead to availability issues. It does not fix the code but provides prioritized findings and remediation guidance.