HIGH nosql injectionadonisjsfirestore

Nosql Injection in Adonisjs with Firestore

Nosql Injection in Adonisjs with Firestore — how this specific combination creates or exposes the vulnerability

AdonisJS is a Node.js web framework that encourages structured request handling, yet when developers compose Firestore queries using unsanitized request data, they can inadvertently create NoSQL injection conditions. Firestore’s query and document-path construction rely on string-based selectors and field lookups, which can be manipulated if user input is concatenated into query constraints or document references without validation or escaping.

Consider a typical route that retrieves a user profile by ID:

// Risky route: directly using request input in a Firestore path
const { id } = request.params
const docRef = db.collection('users').doc(id)
const snapshot = await docRef.get()

If id is attacker-controlled (e.g., ../../../roles/admin or a crafted string that traverses collections), the effective path may escape the intended collection, exposing or modifying data in other collections. Even when using query filters like where, unsanitized input can shift query semantics:

// Unsafe where clause built from user input
const query = request.input('filter') // e.g., "1==1;__proto__=deleteUserData"
const q = db.collection('posts').where(query)

AdonisJS middleware may normalize or trim input, but does not inherently neutralize path traversal or injection patterns in Firestore document references or query constraints. Attack patterns such as prototype pollution or field key manipulation can be chained to affect authorization checks, leading to BOLA/IDOR outcomes. For example, an attacker may supply { "$ne": null } as a filter to extract more records than intended, effectively bypassing intended scoping when combined with weak ownership checks.

In a microservice architecture where AdonisJS acts as an API gateway to Firestore, unsanitized parameters may also facilitate server-side request forgery (SSRF) against internal Firestore endpoints if the client-supplied data influences backend routing or retry logic. Because Firestore rules are evaluated in the context of the provided query, maliciously shaped inputs can exploit rule misconfigurations to read or write across security boundaries.

Because middleBrick tests unauthenticated attack surfaces and includes NoSQL injection checks among its 12 parallel security validations, such weaknesses would be flagged with remediation guidance tied to the specific Firestore patterns observed, helping teams correlate runtime behavior with spec-defined OpenAPI contracts.

Firestore-Specific Remediation in Adonisjs — concrete code fixes

Remediation centers on strict input validation, canonical path construction, and avoiding direct concatenation of user input into Firestore paths or query constraints. Use parameterized approaches and enforce allowlists for identifiers.

1. Safe document path construction

Validate and sanitize IDs before building document references. Use a regular expression to allow only safe characters and reject path traversal sequences.

const { id } = request.params
// Allow only alphanumeric, underscore, dash, and dot (for subcollection-like IDs you control)
if (!/^[a-zA-Z0-9_.-]+$/.test(id)) {
  throw new Error('Invalid document ID')
}
const docRef = db.collection('users').doc(id)
const snapshot = await docRef.get()

2. Parameterized queries with allowlists

Do not directly embed user input into where clauses. Map user-friendly filter keys to known, safe field names and operators.

const ALLOWED_FILTERS = ['status', 'created_at']
const { field, value, operator = '==' } = request.all()

if (!ALLOWED_FILTERS.includes(field)) {
  throw new Error('Unsupported filter field')
}

// Map operator input to Firestore operator safely
const operators = {
  'eq': '==',
  'gt': '>',
  'gte': '>=',
  'lt': '<',
  'lte': '<='
}
if (!(operator in operators)) {
  throw new Error('Unsupported operator')
}

const q = db.collection('posts').where(field, operators[operator], value)
const snapshot = await q.get()

3. Avoid dynamic collection names

If you must use dynamic collection names, validate them against an allowlist rather than trusting client input.

const ALLOWED_COLLECTIONS = ['users', 'posts', 'comments']
const collectionName = request.input('collection')
if (!ALLOWED_COLLECTIONS.includes(collectionName)) {
  throw new Error('Invalid collection')
}
const docs = await db.collection(collectionName).limit(10).get()

4. Middleware normalization and schema validation

Use AdonisJS schema validation to enforce types and patterns early in the request lifecycle.

// In a validator file
import { schema } from '@ioc:Adonis/Core/Validator'

export const postFilterSchema = schema.create({
  field: schema.enum(['status', 'created_at']),
  value: schema.string({}, [rules.escape()]),
  operator: schema.optional(schema.enum(['eq', 'gt', 'gte', 'lt', 'lte']))
})

// In the route handler
const payload = await request.validate({ schema: postFilterSchema })
const q = db.collection('posts').where(payload.field, payload.operator || '==', payload.value)

These measures reduce the attack surface for NoSQL injection by ensuring that Firestore interactions are driven by controlled, validated inputs rather than raw request data. When combined with middleBrick’s continuous monitoring and compliance mapping (e.g., to OWASP API Top 10 and SOC2), teams can detect deviations and maintain a strong security posture across AdonisJS services integrated with Firestore.

Products like the middleBrick CLI (middlebrick scan <url>) can be integrated into development workflows to surface such issues early, while the GitHub Action helps enforce security gates in CI/CD pipelines, and the MCP Server enables rapid scanning from AI-assisted coding environments.

Frequently Asked Questions

How can I test my AdonisJS + Firestore endpoints for NoSQL injection?
Use the middleBrick CLI to scan your API endpoints: middlebrick scan <your-api-url>. It runs unauthenticated checks, including NoSQL injection patterns, and returns a security risk score with prioritized findings and remediation guidance.
Does middleBrick fix the vulnerabilities it detects?
middleBrick detects and reports findings with remediation guidance; it does not fix, patch, block, or remediate. Implement the suggested input validation and query parameterization patterns in your AdonisJS code to address NoSQL injection risks.