GuardAPI Logo
GuardAPI

Fix NoSQL Injection in Micronaut

NoSQL injection in Micronaut environments typically targets MongoDB integrations where developers bypass Micronaut Data's abstraction layer. The vulnerability manifests when raw BSON documents are constructed using untrusted Map objects or string concatenation, allowing attackers to inject operators like $gt, $ne, or $regex to bypass authentication or exfiltrate data. To secure the stack, you must enforce type-safe queries and leverage the Micronaut Data repository pattern which handles parameterization natively.

The Vulnerable Pattern

@Controller("/users")
public class UserController {
    @Inject MongoClient mongoClient;
@Post("/lookup")
public List<Document> lookup(@Body Map<String, Object> userInput) {
    // CRITICAL VULNERABILITY: Raw map from request body passed directly to find()
    // Attacker payload: {"username": {"$ne": null}, "password": {"$gt": ""}}
    MongoCollection<Document> collection = mongoClient.getDatabase("app").getCollection("users");
    return collection.find(new Document(userInput)).into(new ArrayList<>());
}

}

The Secure Implementation

The vulnerable code allows the attacker to control the structure of the MongoDB query by injecting nested maps containing MongoDB operators. The fix involves two primary layers of defense: 1. Using Micronaut Data Repositories, which abstracts the query logic and ensures that user input is treated as data rather than part of the query command. 2. Strict type binding in the controller, which prevents the application from accepting complex objects where simple scalars (like Strings) are expected. If raw driver access is absolutely necessary, use the 'Filters' API (e.g., Filters.eq('username', username)) which correctly escapes values.

@Repository
public interface UserRepository extends CrudRepository {
    // SECURE: Micronaut Data generates a compile-time query that treats input as a literal value
    List findByUsername(String username);
}

@Controller(“/users”) public class UserController { @Inject UserRepository userRepository;

@Post("/lookup")
public List<User> lookup(@QueryValue String username) {
    // Input is now bound to a String and handled by the repository abstraction
    return userRepository.findByUsername(username);
}

}

System Alert • ID: 1116
Target: Micronaut API
Potential Vulnerability

Your Micronaut API might be exposed to NoSQL Injection

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