HIGH axumrustnosql injection

Nosql Injection in Axum (Rust)

Nosql Injection in Axum with Rust — how this specific combination creates or exposes the vulnerability

Axum is a popular web framework for building Rust APIs. When Axum endpoints accept user input and forward it to a NoSQL database without validation or encoding, they can be subject to NoSQL Injection. This occurs when attacker-controlled data is interpreted as part of the NoSQL query language or structure rather than purely as data values.

Consider a MongoDB-backed Axum service that builds queries by deserializing JSON directly into a BSON document. If an endpoint receives parameters such as filter or update and uses them to construct queries without strict schema enforcement, an attacker can inject operators like $ne, $gt, or $where to bypass authentication or extract data. For example, sending { "username": { "$ne": "" } } as a filter can match all users except an empty username, effectively returning all records.

In Rust, using a driver such as the official MongoDB Rust driver, developers may inadvertently construct queries from raw serde_json::Value objects. Since the driver trusts the structure provided, operators embedded by an attacker are executed. This mirrors classic injection patterns: the application loses the boundary between code and data. Common vulnerable patterns include concatenating JSON strings to build queries or using dynamic paths in aggregation pipelines without whitelisting field names.

NoSQL Injection in Axum with Rust is particularly risky when the API also exposes an OpenAPI spec that describes flexible object parameters. Attackers can leverage schema looseness to probe for operators, and because the scan runs black-box tests across 12 security checks, findings related to Input Validation and Property Authorization will highlight unsafe deserialization and missing operator filtering. The absence of server-side validation in the API layer means malicious payloads reach the database unchanged, enabling unauthorized reads or privilege escalation via BOLA/IDOR when object ownership is inferred from user-controlled filter content.

An example of a vulnerable Axum handler is one that directly passes a user-supplied JSON map into a MongoDB find operation. The handler trusts the map’s contents, allowing injection paths through operators such as $regex for denial-of-service or data extraction. Because Axum does not automatically sanitize inputs, the responsibility falls on developers to enforce strict schemas and reject unexpected operators.

Rust-Specific Remediation in Axum — concrete code fixes

To mitigate NoSQL Injection in Axum with Rust, enforce strict, typed input models and avoid constructing queries from raw user-controlled JSON. Prefer using strongly typed structs with serde and validate against a closed set of allowed fields. When dynamic queries are necessary, use builder patterns that permit only known operators and explicitly whitelist fields.

Below are concrete, safe patterns for Axum handlers using the MongoDB Rust driver.

// Safe: typed input with explicit filtering
use axum::{routing::post, Json, Router};
use serde::{Deserialize, Serialize};
use mongodb::{bson::doc, Client};

#[derive(Deserialize)]
struct UserFilter {
    username: String,
    // do not accept raw operator maps from the client
}

#[derive(Serialize)]
struct UserResponse {
    id: String,
    username: String,
}

async fn list_users(
    Json(payload): Json,
) -> Result>, (axum::http::StatusCode, String)> {
    let client = Client::with_uri_str("mongodb://localhost:27017").await.map_err(|e| (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    let db = client.database("mydb");
    let collection = db.collection::("users");

    // Build query using only known fields; no user-controlled operators
    let filter = doc! { "username": &payload.username };
    let cursor = collection.find(filter, None).await.map_err(|e| (axum::http::StatusCode::BAD_REQUEST, e.to_string()))?;
    let users: Vec = cursor.try_collect().await.map_err(|e| (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    Ok(Json(users))
}

pub fn app() -> Router {
    Router::new().route("/users", post(list_users))
}

For dynamic updates, validate operator usage on the server side rather than accepting raw JSON from the client.

// Safe: controlled update builder
use axum::{routing::patch, Json, Router};
use serde::{Deserialize, Serialize};
use mongodb::{bson::{doc, Document}, options::UpdateOptions};

#[derive(Deserialize)]
struct UpdateUser {
    username: String,
    email: String,
    // do not allow client to specify $set or other operators
}

async fn update_user(
    Json(payload): Json,
) -> Result<&'static str, (axum::http::StatusCode, String)> {
    let client = Client::with_uri_str("mongodb://localhost:27017").await.map_err(|e| (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    let db = client.database("mydb");
    let collection = db.collection("users");

    let filter = doc! { "username": &payload.username };
    let update = doc! { "$set": { "email": &payload.email } };
    collection.update_one(filter, update, None).await.map_err(|e| (axum::http::StatusCode::BAD_REQUEST, e.to_string()))?;
    Ok("updated")
}

Additionally, integrate middleBrick into your workflow to detect such issues before deployment. Use the CLI to scan endpoints from the terminal: middlebrick scan <url>, or add the GitHub Action to your CI/CD pipeline to fail builds if security scores drop below your chosen threshold. For continuous monitoring, the Pro plan supports configurable schedules and alerts, ensuring that regressions in input validation and property authorization are caught early.

Frequently Asked Questions

Can NoSQL Injection be detected by middleBrick when scanning an Axum API?
Yes. middleBrick runs Input Validation and Property Authorization checks against the unauthenticated attack surface. Findings will highlight unsafe deserialization and operator injection risks, with severity, remediation guidance, and mappings to frameworks such as OWASP API Top 10.
Does middleBrick provide automatic fixes for NoSQL Injection in Rust Axum services?
No. middleBrick detects and reports findings with remediation guidance, but it does not fix, patch, or block. Developers should apply typed schemas, reject unexpected operators, and use controlled update builders as shown in the remediation examples.