Fix NoSQL Injection in Axum
NoSQL injection in the Rust ecosystem typically occurs when Axum handlers accept loosely typed JSON (like `serde_json::Value`) and pass it directly into the `mongodb` crate's `doc!` macro. This allows attackers to substitute expected scalar values (e.g., a username string) with MongoDB query operators (e.g., `{"$gt": ""}`), potentially bypassing authentication or exfiltrating data.
The Vulnerable Pattern
use ax_um::{extract::Json, response::IntoResponse}; use mongodb::bson::doc; use serde_json::Value;// VULNERABLE: Accept arbitrary JSON and inject directly into filter async fn get_user(Json(payload): Json
) -> impl IntoResponse { let collection = get_db_collection(); // If payload is {"id": {"$ne": null}}, this returns the first user in the DB let filter = doc! { "user_id": &payload["id"] }; let result = collection.find_one(filter, None).await; // ... return response
}
The Secure Implementation
The fix leverages Rust's strong typing via Serde. By defining a struct with explicit types (e.g., `String`), the Axum `Json` extractor will automatically reject any input that contains nested objects or MongoDB operators like `$gt`, `$ne`, or `$or`. In the vulnerable example, `serde_json::Value` accepts any valid JSON, allowing an attacker to pass a dictionary that the `doc!` macro interprets as a query command rather than a literal value.
use axum::{extract::Json, response::IntoResponse}; use mongodb::bson::doc; use serde::Deserialize;#[derive(Deserialize)] struct UserRequest { // SECURE: Enforce String type to prevent operator injection id: String, }
async fn get_user(Json(payload): Json
) -> impl IntoResponse { let collection = get_db_collection(); // The payload.id is guaranteed to be a String; operators will fail deserialization let filter = doc! { "user_id": payload.id }; let result = collection.find_one(filter, None).await; // ... return response
}
Your Axum API
might be exposed to NoSQL Injection
74% of Axum 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.