HIGH cryptographic failuresfastapimongodb

Cryptographic Failures in Fastapi with Mongodb

Cryptographic Failures in Fastapi with Mongodb — how this specific combination creates or exposes the vulnerability

Cryptographic failures occur when an API does not adequately protect sensitive data at rest or in transit. The combination of FastAPI and MongoDB can inadvertently expose data when cryptographic controls are missing or misapplied. FastAPI does not enforce encryption or hashing by itself; it relies on the developer to implement secure handling of data before it reaches MongoDB. If fields such as passwords, API keys, or personal identifiers are stored in MongoDB without strong, modern hashing or encryption, they become vulnerable to extraction and offline attacks.

Transport layer protections are also at risk. FastAPI applications that do not enforce HTTPS can expose authentication tokens or session identifiers to interception. MongoDB connections that do not use TLS allow data in transit between the application and the database to be sniffed. Attackers can leverage weak or missing TLS configurations to conduct man-in-the-middle attacks. Even when TLS is used, if the application encrypts data with weak algorithms or hardcoded keys before sending it to MongoDB, the cryptographic protection is effectively bypassed.

Another common failure is improper key management. FastAPI applications may embed encryption keys in source code or configuration files that are checked into version control. If MongoDB stores encrypted fields but the encryption keys are compromised, the data is easily decrypted. Additionally, MongoDB’s flexible schema can lead to inconsistent application of encryption across documents, leaving some records protected while others remain plaintext. This inconsistency increases the attack surface and complicates compliance with frameworks such as OWASP API Security Top 10 and data protection regulations.

Real-world attack patterns highlight these risks. For example, an attacker who gains read access to a MongoDB collection due to weak access controls can immediately harvest plaintext credentials or tokens if passwords are not hashed with a strong, salted algorithm like bcrypt. Similarly, if API keys are encrypted with a weak cipher and the initialization vector is reused, cryptanalysis techniques can recover the original keys. Publicly documented CVEs in related libraries or misconfigured MongoDB deployments often serve as initial access vectors that lead to exfiltration of sensitive cryptographic material.

In FastAPI, developers must explicitly design cryptographic protections. The framework provides tools for request validation and dependency injection but does not automatically encrypt database payloads. Without deliberate implementation, MongoDB will store whatever data the application sends, including secrets transmitted over unencrypted channels or stored with insufficient integrity checks. Continuous scanning with a tool like middleBrick can detect missing transport encryption, weak hashing configurations, and inconsistent cryptographic practices across FastAPI endpoints that interact with MongoDB.

Mongodb-Specific Remediation in Fastapi — concrete code fixes

To mitigate cryptographic failures, FastAPI applications must enforce encryption in transit, use strong hashing for secrets, and manage cryptographic keys securely when storing data in MongoDB. Below are concrete code examples demonstrating secure practices.

1. Enforce HTTPS and secure MongoDB connections

Ensure FastAPI rejects HTTP requests and that the MongoDB driver uses TLS. Use environment variables for connection strings to avoid hardcoding sensitive parameters.

from fastapi import FastAPI, Request, HTTPException
from pymongo import MongoClient
import ssl
import os

app = FastAPI()

# Enforce HTTPS at the infrastructure level; reject insecure requests
@app.middleware("http")
async def enforce_https(request: Request, call_next):
    if request.url.scheme != "https":
        raise HTTPException(status_code=400, detail="HTTPS required")
    response = await call_next(request)
    return response

# MongoDB connection with TLS enabled
client = MongoClient(
    os.getenv("MONGODB_URI"),
    tls=True,
    tlsCAFile="/path/to/ca.pem"
)
db = client.get_database("secure_db")

2. Hash passwords with bcrypt before storing in MongoDB

Never store plaintext passwords. Use a strong adaptive hashing algorithm and store only the hash in MongoDB.

import bcrypt
from fastapi import Depends, FastAPI, HTTPException
from pymongo import MongoClient

app = FastAPI()
client = MongoClient(os.getenv("MONGODB_URI"), tls=True)
db = client["secure_db"]

def hash_password(plain: str) -> str:
    return bcrypt.hashpw(plain.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")

def verify_password(plain: str, hashed: str) -> bool:
    return bcrypt.checkpw(plain.encode("utf-8"), hashed.encode("utf-8"))

@app.post("/register")
def register(username: str, password: str):
    hashed = hash_password(password)
    db.users.insert_one({"username": username, "password_hash": hashed})
    return {"status": "ok"}

3. Use encrypted fields with proper key management

For sensitive fields beyond passwords, use encryption with keys managed outside the application code, such as environment-sealed secrets or key management services. Avoid hardcoded keys.

from cryptography.fernet import Fernet
from fastapi import Depends, FastAPI
from pymongo import MongoClient
import os

app = FastAPI()
client = MongoClient(os.getenv("MONGODB_URI"), tls=True)
db = client["secure_db"]

# Load key from a secure source at runtime; do not commit to version control
key = os.getenv("ENCRYPTION_KEY")
cipher = Fernet(key)

def encrypt_value(plain: str) -> str:
    return cipher.encrypt(plain.encode("utf-8")).decode("utf-8")

def decrypt_value(ciphertext: str) -> str:
    return cipher.decrypt(ciphertext.encode("utf-8")).decode("utf-8")

@app.post("/store-sensitive")
def store_data(ssn: str):
    encrypted = encrypt_value(ssn)
    db.secrets.insert_one({"ssn_encrypted": encrypted})
    return {"status": "stored"}

4. Validate and limit input to reduce injection risks

Combine input validation with cryptographic protections to prevent injection attacks that could compromise stored data.

from fastapi import FastAPI, Query
from pydantic import constr
from pymongo import MongoClient
import re

app = FastAPI()
client = MongoClient(os.getenv("MONGODB_URI"), tls=True)
db = client["secure_db"]

SafeString = constr(regex=r"^[a-zA-Z0-9 _-]{1,100}$")

@app.get("/search")
def search(query: SafeString = Query(...)):
    # Use parameterized queries to avoid injection
    result = db.items.find_one({"name": re.escape(query)})
    return {"result": result}

Frequently Asked Questions

How does middleBrick help detect cryptographic failures in FastAPI and MongoDB integrations?
middleBrick scans unauthenticated attack surfaces and runs 12 parallel security checks, including data exposure and input validation. It examines how FastAPI endpoints store and transmit data to MongoDB, flagging missing transport encryption, weak hashing, and inconsistent cryptographic practices with actionable remediation guidance.
Can middleBrick test LLM security when FastAPI exposes AI-related endpoints that interact with MongoDB?
Yes. middleBrick’s unique LLM/AI Security checks include system prompt leakage detection, active prompt injection testing, output scanning for PII or API keys, and detection of excessive agency patterns. These checks apply even when endpoints interact with MongoDB, helping identify risks specific to AI-assisted data handling.