Fix NoSQL Injection in Sanic
NoSQL injection in Sanic applications occurs when untrusted JSON input is passed directly into database query filters (typically MongoDB/Motor). This allows attackers to inject operators like $ne (not equal), $gt (greater than), or $where to bypass authentication or exfiltrate data. To secure the app, you must enforce strict type checking and avoid passing raw request dictionaries into query methods.
The Vulnerable Pattern
from sanic import Sanic, response from motor.motor_asyncio import AsyncIOMotorClientapp = Sanic(“VulnApp”) client = AsyncIOMotorClient(“mongodb://localhost:27017”) db = client.test_db
@app.post(“/api/user”) async def get_user(request): # VULNERABLE: Directly passing request.json allows operator injection # Attacker sends: {“username”: {“$ne”: null}} user = await db.users.find_one(request.json) return response.json({“user”: str(user)})
The Secure Implementation
The vulnerability exists because MongoDB drivers interpret nested dictionaries in query filters as operators. If a user provides {'$ne': ''} instead of a string, the logic is subverted. The fix implements defensive programming by: 1. Extracting specific keys rather than the whole object. 2. Using isinstance() to ensure inputs are strings, not dictionaries. 3. Constructing a fresh query object that prevents the injection of top-level MongoDB operators.
from sanic import Sanic, response
from motor.motor_asyncio import AsyncIOMotorClient
app = Sanic(“SecureApp”)
client = AsyncIOMotorClient(“mongodb://localhost:27017”)
db = client.test_db
@app.post(“/api/user”)
async def get_user(request):
username = request.json.get(“username”)
# SECURE: Explicitly define the query structure and enforce types
if not isinstance(username, str):
return response.json({"error": "Invalid input"}, status=400)
# Use a literal dictionary with sanitized values
query = {"username": username}
user = await db.users.find_one(query)
return response.json({"user": str(user)})</code></pre>
Your Sanic API
might be exposed to NoSQL Injection
74% of Sanic apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.