HIGH nosql injectionaxumjwt tokens

Nosql Injection in Axum with Jwt Tokens

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

When an Axum service parses and validates JWT tokens and then uses data from those tokens in backend database queries, it can introduce NoSQL injection if the token payload is treated as untrusted user input. A JWT consists of a header, payload (claims), and signature; the payload is base64url-encoded but not encrypted by default (unless using JWE). If an API endpoint decodes a JWT, extracts claims such as sub, roles, or custom fields, and directly interpolates those values into a NoSQL query (for example, a MongoDB or DynamoDB query), an attacker who can influence the token payload may alter the query logic.

Consider an endpoint that identifies a user by a claim in the JWT and then retrieves user-specific data from a NoSQL store. If the JWT is accepted without strict validation of the issuer, audience, and expiration, and the application embeds the claim value into a query without parameterization, the attacker can modify the token payload to change the query behavior. For instance, a claim used in a filter like { "user_id": "{sub}" } can be manipulated to { "user_id": { "$ne": "" } } or { "$where": "return true" } depending on the NoSQL engine, leading to unauthorized data access or privilege escalation. This becomes a chained attack: an attacker who can influence the JWT (via weak signing keys, algorithm confusion, or stolen tokens) can manipulate the NoSQL query to bypass authorization checks, extract other users’ records, or probe the database structure.

Axum does not directly interact with JWTs or databases; it is a web framework. The risk arises in application code that combines JWT validation libraries (such as jsonwebtoken) with a NoSQL driver. If the handler retrieves a claim and uses it to construct a query map or a BSON document without strict allow-listing, the application performs unsafe string-to-query conversion. The scanner’s checks for Authentication, Property Authorization, and Input Validation will flag missing claim validation and unsafe consumption patterns, while the LLM/AI Security checks can detect prompt injection attempts that try to coax the API into leaking token contents or database structure through injected payloads.

In practice, this vulnerability often coexists with weak key management or missing token binding. For example, if the API accepts none algorithm tokens or does not verify the aud and iss claims, an attacker can craft a token with elevated roles and then use those roles to alter NoSQL filters. The scanner’s authentication and authorization checks, combined with its input validation and data exposure tests, help identify whether JWT-derived data reaches the query layer without sufficient sanitization or parameterization.

Jwt Tokens-Specific Remediation in Axum — concrete code fixes

Remediation focuses on strict JWT validation, claim allow-listing, and avoiding direct use of token payload fields in NoSQL queries. In Axum, you should validate the token early in the request lifecycle using a verified JSON Web Key Set (JWKS) or a trusted issuer, extract only the minimal required claims, and then use parameterized or schema-based structures when interacting with a NoSQL database.

Example: Validate JWT and extract only safe identifiers before building a query.

use axum::{routing::get, Router};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation, TokenData};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct Claims {
    sub: String,
    roles: Vec,
    exp: usize,
    iss: String,
    aud: String,
}

async fn validate_token(token: &str) -> TokenData<Claims> {
    let validation = Validation::new(Algorithm::RS256);
    let key = DecodingKey::from_rsa_pem(include_bytes!("public_key.pem")).expect("invalid key");
    decode::<Claims>(token, &key, &validation)
        .expect("invalid token")
}

async fn get_user_data(user_id: String) -> String {
    // Use user_id as a parameter, not by interpolating raw claims
    format!("SELECT * FROM users WHERE id = '{}'", user_id)
}

async fn handler(
    headers: axum::extract::Header<axum::http::header::AUTHORIZATION>
) -> String {
    let auth = headers.0.to_str().unwrap_or("");
    let token = auth.strip_prefix("Bearer ").unwrap_or(auth);
    let data = validate_token(token).claims;

    // Only use the subject claim as a parameterized identifier
    let query = get_user_data(data.sub).await;
    query
}

fn app() -> Router {
    Router::new().route("/me", get(handler))
}

In this example, the handler decodes the JWT with strict algorithm and key checks and then uses the sub claim strictly as a parameter to a query function. The query function should further ensure that the value is treated as a literal identifier (e.g., via prepared statements or a safe ORM layer) rather than being concatenated into a raw NoSQL string. This prevents attackers from injecting additional conditions or operators through the token payload.

Additionally, enforce claim validation for iss, aud, and expiration, and consider using short-lived tokens with refresh mechanisms. Avoid placing raw token payload fields directly into NoSQL filter documents; instead, map them to internal identifiers that are verified against access control rules. The scanner’s findings for Authentication, Property Authorization, and Input Validation will highlight missing checks, while the LLM/AI Security tests ensure that token-derived data cannot be abused to influence system prompts or extract sensitive outputs.

Frequently Asked Questions

Can an attacker modify a JWT to perform NoSQL injection if the token is signed with a weak secret?
Yes. If the signing key is weak or the algorithm is not enforced, an attacker can modify the JWT payload to inject malicious NoSQL operators. Always enforce strong algorithms (e.g., RS256), verify issuer and audience, and validate token expiration.
Does middleBrick detect NoSQL injection risks from JWT-derived data in Axum APIs?
Yes. middleBrick’s checks for Authentication, Property Authorization, Input Validation, and Unsafe Consumption can identify when JWT claims are used directly in database queries without proper sanitization or parameterization, and its LLM/AI Security tests verify that token data cannot be leveraged for prompt injection or data exfiltration.