GuardAPI Logo
GuardAPI

Fix NoSQL Injection in Hug

NoSQL Injection in Hug APIs occurs when untrusted input is merged directly into database query filters. In MongoDB environments, attackers can replace expected strings with dictionary objects containing operators like '$ne' (not equal) or '$gt' (greater than) to bypass logic or dump collections. To fix this, you must enforce strict typing and sanitize inputs before they hit the driver.

The Vulnerable Pattern

import hug
from pymongo import MongoClient

client = MongoClient(‘mongodb://localhost:27017/’) db = client.app_db

@hug.get(‘/profile’) def get_profile(user_id): # VULNERABLE: If user_id is {‘$ne’: None}, the query returns the first user in the DB. # Hug’s default behavior might allow complex objects via JSON bodies or certain query parsers. user = db.users.find_one({‘user_id’: user_id}) return user or {‘error’: ‘not_found’}

The Secure Implementation

The exploit leverages MongoDB's query syntax where keys can be operators. By passing a JSON object instead of a string, an attacker changes the query logic. The fix involves two layers of defense: 1. Hug Type Validation: Using 'hug.types.text' forces the framework to validate that the incoming parameter is a scalar string, rejecting dictionary-based payloads. 2. Explicit Casting: Forcing the variable to 'str()' before passing it to the PyMongo 'find_one' method ensures that even if validation is bypassed, the driver treats the input as a literal search term rather than a functional query operator.

import hug
from pymongo import MongoClient

client = MongoClient(‘mongodb://localhost:27017/’) db = client.app_db

@hug.get(‘/profile’) def get_profile(user_id: hug.types.text): # SECURE: hug.types.text enforces the input is a string. # We also explicitly cast to str to ensure the driver treats it as a literal value. sanitized_id = str(user_id) user = db.users.find_one({‘user_id’: sanitized_id}) return user or {‘error’: ‘not_found’}

System Alert • ID: 3515
Target: Hug API
Potential Vulnerability

Your Hug API might be exposed to NoSQL Injection

74% of Hug apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

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.