Vulnerable Components in Fastapi with Mongodb
Vulnerable Components in Fastapi with Mongodb — how this specific combination creates or exposes the vulnerability
FastAPI with MongoDB is a common backend stack that can introduce several API-specific risks when security controls are incomplete. Because FastAPI encourages rapid route definition and automatic OpenAPI generation, developers may unintentionally expose endpoints that interact with MongoDB in ways that leak data or enable unsafe operations.
One vulnerability pattern arises when route parameters are directly mapped to MongoDB queries without type validation or query normalization. For example, accepting an item_id from the path and using it directly in a find_one call can lead to Insecure Direct Object References (IDOR) or Broken Object Level Authorization (BOLA) when access checks are missing or applied inconsistently. An attacker could enumerate IDs and access other users’ data if authorization is not enforced per request.
Input validation gaps compound these issues. If Pydantic models validate structure but do not restrict operators, a client may supply query keys that include MongoDB update operators such as {"$ne": ""} or {"$in": [...]}. Without strict allow-listing, this can enable data exfiltration or unintended mutation behavior. The OpenAPI spec may describe expected fields but not restrict operator injection, so runtime behavior diverges from intended access boundaries.
Another risk specific to FastAPI with MongoDB is improper handling of sensitive fields in responses. FastAPI’s response models may omit fields for documentation purposes, but if the MongoDB projection is misconfigured, the database can return credentials, tokens, or internal flags. Data Exposure findings often occur when projections are omitted in find calls, returning entire documents including password hashes or API keys.
SSRF is also possible if user-supplied hostnames or IPs are used to build MongoDB connection strings or are passed to aggregation stages that perform external HTTP calls. Although MongoDB’s direct HTTP usage is limited, aggregation pipelines can include stages that trigger external requests when combined with custom code or connectors. The unauthenticated attack surface of FastAPI endpoints that build MongoDB operations from raw input increases the likelihood of such scenarios.
Finally, rate limiting and enumeration protections may be inconsistently applied. Without per-endpoint rate limits, attackers can perform brute-force enumeration of valid resource identifiers or inject malformed queries to probe schema behavior. middleBrick’s checks for Rate Limiting and Input Validation highlight these gaps when scans detect endpoints that allow excessive requests or permit operator injection in MongoDB queries.
Mongodb-Specific Remediation in Fastapi — concrete code fixes
Remediation focuses on strict input validation, explicit projections, and consistent authorization. Use Pydantic models to define acceptable ID formats and reject operators by validating field values with regex patterns or custom validators. Enforce object-level checks in every database call, and ensure MongoDB projections limit returned fields.
Example of a vulnerable route that directly uses user input:
from fastapi import FastAPI, Depends, HTTPException
from pymongo import MongoClient
from bson.objectid import ObjectId
app = FastAPI()
client = MongoClient("mongodb://localhost:27017")
db = client["mydb"]["items"]
@app.get("/items/{item_id}")
def read_item(item_id: str):
# Unsafe: directly using user input in query
doc = db.find_one({"_id": ObjectId(item_id)})
return doc
Fixed version with validation, projection, and authorization checks:
from fastapi import FastAPI, Depends, HTTPException, status
from pymongo import MongoClient
from bson.objectid import ObjectId
from pydantic import BaseModel, Field
import re
app = FastAPI()
client = MongoClient("mongodb://localhost:27017")
db = client["mydb"]["items"]
class ItemResponse(BaseModel):
id: str
name: str
description: str
def valid_objectid(value: str) -> bool:
return re.match(r"^[0-9a-f]{24}$", value) is not None
@app.get("/items/{item_id}", response_model=ItemResponse)
def read_item(item_id: str, user=Depends(get_current_user)):
if not valid_objectid(item_id):
raise HTTPException(status_code=400, detail="Invalid item ID")
# Enforce authorization: ensure item belongs to user
doc = db.find_one(
{"_id": ObjectId(item_id), "owner_id": user.id},
{"name": 1, "description": 1} # explicit projection to avoid data exposure
)
if doc is None:
raise HTTPException(status_code=404, detail="Item not found or unauthorized")
return ItemResponse(id=str(doc["_id"]), name=doc["name"], description=doc["description"])
Additional measures include using a dependency injection layer for authorization, applying default field filters in response models, and monitoring logs for unexpected query patterns. middleBrick’s scans can verify that endpoints implement these controls by checking for missing projections, unvalidated ID formats, and inconsistent authorization rules.
Frequently Asked Questions
Can middleBrick detect IDOR risks when using FastAPI with MongoDB?
Does middleBrick test for operator injection in MongoDB queries during scans?
$ne, $in, and other operators that may lead to data exposure or logic bypass when not properly restricted.