GuardAPI Logo
GuardAPI

Fix NoSQL Injection in Rocket

NoSQL injection in Rocket/Rust typically occurs when developers use `serde_json::Value` to accept arbitrary JSON input and pass it directly into a MongoDB filter. This allows attackers to inject operators like `$ne`, `$gt`, or `$where`, bypassing authentication or exfiltrating data. To secure your app, you must enforce strict schema validation using Serde structs.

The Vulnerable Pattern

#[post("/user/lookup", data = "")]
async fn lookup(payload: Json, db: &State) -> Result, Status> {
    let collection = db.collection::("users");
    // VULNERABLE: If payload is {"username": {"$ne": null}}, the filter matches the first user in the DB.
    let filter = doc! { "username": payload["username"].clone() };
    collection.find_one(filter, None).await.map(|u| Json(u.unwrap()))
}

The Secure Implementation

The vulnerability lies in the dynamic nature of the `serde_json::Value` type. When `doc! { "key": value }` is called with a `Value` that contains a nested object (e.g., `{"$gt": ""}`), the MongoDB driver interprets this as a query operator rather than a literal string. By replacing `Value` with a strongly-typed struct, Serde's deserializer will fail if the attacker tries to pass an object where a string is expected. This effectively sanitizes the input by leveraging Rust's type system to enforce data boundaries.

#[derive(Deserialize)]
struct LookupRequest {
    username: String, // Enforces that input must be a primitive string, not an object
}

#[post(“/user/lookup”, data = "")] async fn lookup(payload: Json, db: &State) -> Result<Json, Status> { let collection = db.collection::(“users”); // SECURE: The type system ensures ‘username’ is a String. // BSON conversion will treat it as a literal value, neutralizing operators. let filter = doc! { “username”: &payload.username }; collection.find_one(filter, None).await.map(|u| Json(u.unwrap())) }

System Alert • ID: 5005
Target: Rocket API
Potential Vulnerability

Your Rocket API might be exposed to NoSQL Injection

74% of Rocket 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.