GuardAPI Logo
GuardAPI

Fix NoSQL Injection in Javalin

NoSQL Injection in Javalin applications typically occurs when untrusted user input is concatenated into raw BSON strings or used to build dynamic queries without using type-safe query builders. Attackers can inject operators like $gt, $ne, or $where to bypass authentication, leak sensitive data, or cause Denial of Service by forcing inefficient full-table scans.

The Vulnerable Pattern

app.post("/login", ctx -> {
    String username = ctx.formParam("username");
    String password = ctx.formParam("password");
// VULNERABLE: Using Document.parse with raw string concatenation
// An attacker can send username: admin' , 'password': { '$ne': 'foo' }
String rawQuery = "{ 'username': '" + username + "', 'password': '" + password + "' }";
Document user = collection.find(Document.parse(rawQuery)).first();

if (user != null) {
    ctx.result("Logged in as: " + user.getString("username"));
} else {
    ctx.status(401);
}

});

The Secure Implementation

The fix involves replacing raw JSON string parsing with the MongoDB Java Driver's 'Filters' class. The vulnerable code allows an attacker to break out of the string literal and inject MongoDB operators (e.g., {$ne: ''}) to return the first user in the database without knowing the password. By using Filters.eq(), the driver ensures the input is treated strictly as a value, not as part of the query syntax. Additionally, always validate that input types match expected schemas and avoid using the $where operator which allows arbitrary JavaScript execution.

import static com.mongodb.client.model.Filters.*;

app.post(“/login”, ctx -> { String username = ctx.formParam(“username”); String password = ctx.formParam(“password”);

// SECURE: Use the MongoDB Filters builder (Query Parameterization)
// This treats input as literals, neutralizing operator injection.
Bson filter = and(eq("username", username), eq("password", password));
Document user = collection.find(filter).first();

if (user != null) {
    ctx.result("Logged in as: " + user.getString("username"));
} else {
    ctx.status(401);
}

});

System Alert • ID: 7028
Target: Javalin API
Potential Vulnerability

Your Javalin API might be exposed to NoSQL Injection

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