GuardAPI Logo
GuardAPI

Fix NoSQL Injection in Grape

NoSQL Injection in Grape/Mongoid stacks occurs when untrusted input is passed directly to query operators. Attackers bypass authentication or leak data by injecting MongoDB operators like $gt, $ne, or $where via JSON payloads. If your API doesn't enforce strict typing on parameters, an attacker can swap a string for a hash containing malicious operators, hijacking the query logic.

The Vulnerable Pattern

params do
  requires :api_key
end
post '/auth' do
  # VULNERABLE: If api_key is passed as {"$ne": null}, authentication is bypassed.
  user = User.find_by(token: params[:api_key])
  present user
end

The Secure Implementation

To kill NoSQL injection in Grape, you must leverage the built-in parameter validation and the 'declared' helper. By defining 'type: String', Grape's middleware will automatically reject or stringify complex objects/hashes before they reach your business logic. Using 'declared(params)' is critical because it strips any undeclared parameters that an attacker might try to sneak into the query. This ensures that even if a library like Mongoid accepts hashes for complex queries, your API layer only ever passes sanitized, scalar values.

params do
  requires :api_key, type: String, desc: 'Strictly enforced string token'
end
post '/auth' do
  # SECURE: declared(params) ensures only validated keys are used.
  # type: String forces the input to be a scalar, neutralizing hash-based operator injection.
  safe_params = declared(params)
  user = User.find_by(token: safe_params[:api_key])
  present user
end
System Alert • ID: 3034
Target: Grape API
Potential Vulnerability

Your Grape API might be exposed to NoSQL Injection

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