Out Of Bounds Read in Fastapi with Api Keys
Out Of Bounds Read in Fastapi with Api Keys — how this specific combination creates or exposes the vulnerability
An Out Of Bounds Read occurs when an API accesses memory beyond the intended allocation, potentially exposing adjacent data. In Fastapi, combining this vulnerability with Api Keys can amplify risk if key validation logic relies on unchecked indexing into arrays, buffers, or structured data such as JSON or headers. For example, if a developer uses an Api Key to look up tenant or plan information by index in a list, and the index is derived from user input without proper bounds checking, an attacker can supply an out-of-range index to read memory contents that may contain sensitive information or trigger instability.
Consider a Fastapi endpoint that retrieves feature flags based on a user's subscription plan stored in a list. The Api Key is used to identify the plan, but the mapping uses a numeric offset derived from the key or a decoded payload without verifying it against the list length. An attacker sending a crafted key can cause the application to read beyond the list boundary, potentially exposing other keys, configuration values, or internal structures that were not intended to be accessible.
Another scenario involves parsing request headers where the Api Key is one of multiple values stored in a fixed-size buffer. If the code iterates over headers using an integer index derived from the key's position or a parsed numeric component, an invalid index can lead to reading uninitialized memory or adjacent objects. This can result in information disclosure, such as seeing unrelated key-value pairs or internal pointers, which may aid further attacks. Because the scan category of Property Authorization in middleBrick checks for BOLA/IDOR and BFLA/Privilege Escalation, such indexing issues can be surfaced as findings when runtime behavior deviates from expected access patterns.
With middleBrick's OpenAPI/Swagger spec analysis, definitions and $ref resolution are cross-referenced against runtime behavior, so if your spec describes an Api Key header but the implementation uses it as an index or lookup key without validation, the mismatch can highlight risky data flows. The tool's checks for Input Validation and Data Exposure help identify cases where keys are used in ways that may lead to out-of-bounds conditions, supporting compliance mapping to OWASP API Top 10 and SOC2. Note that middleBrick detects and reports these patterns but does not modify code or block execution; it provides prioritized findings with severity and remediation guidance.
Api Keys-Specific Remediation in Fastapi — concrete code fixes
To remediate Out Of Bounds Read risks when using Api Keys in Fastapi, ensure all key-based lookups are bounds-checked and avoid using raw key values or derived numbers as array indices. Use dictionaries or mappings with explicit existence checks instead of positional indexing, and validate any numeric claims in tokens or payloads against allowed ranges before use.
Below are two concrete Fastapi examples. The first demonstrates a vulnerable pattern where an Api Key is decoded and used as an index into a list, risking an out-of-bounds read.
from fastapi import FastAPI, Header, HTTPException
app = FastAPI()
# Vulnerable: using decoded key index directly
PLANS = ["free", "pro", "enterprise"]
@app.get("/plan")
async def get_plan(x_api_key: str = Header(...)):
try:
# Simulate decoding key to an index (e.g., via JWT or custom encoding)
index = int(x_api_key[-1]) # last character as digit
return {"plan": PLANS[index]}
except (ValueError, IndexError):
raise HTTPException(status_code=400, detail="Invalid key")
An attacker can supply a key ending in 9, causing PLANS[9] to read beyond the list. The fix is to validate the index against the list length and use a safe mapping.
from fastapi import FastAPI, Header, HTTPException
app = FastAPI()
# Secure: map keys to plans explicitly
PLAN_MAP = {
"key_free": "free",
"key_pro": "pro",
"key_enterprise": "enterprise",
}
@app.get("/plan")
async def get_plan(x_api_key: str = Header(...)):
plan = PLAN_MAP.get(x_api_key)
if plan is None:
raise HTTPException(status_code=403, detail="Forbidden")
return {"plan": plan}
This approach eliminates index-based reading entirely and ensures only known keys are accepted. For numeric identifiers, always check bounds before accessing collections:
from fastapi import FastAPI, Header, HTTPException
app = FastAPI()
USERS = ["alice", "bob", "charlie"]
@app.get("/user")
async def get_user(uid: int = Header(...), x_api_key: str = Header(...)):
if uid < 0 or uid >= len(USERS):
raise HTTPException(status_code=400, detail="Invalid user id")
# safe access
return {"user": USERS[uid]}
Use middleware or dependency injection to validate Api Keys centrally, and ensure any derived numeric values are checked against collection sizes. middleBrick's checks for Authentication, Input Validation, and Property Authorization can highlight areas where keys are used in risky contexts, though the tool only reports findings and provides remediation guidance.