GuardAPI Logo
GuardAPI

Fix NoSQL Injection in Polka

Polka is a minimalist Express alternative. Its lack of built-in input parsing means developers often pipe raw 'req.body' or 'req.query' objects directly into NoSQL drivers like MongoDB. This 'operator injection' allows attackers to use reserved keys like '$gt' or '$ne' to bypass authentication or exfiltrate data. If you aren't enforcing types, your queries are pwned.

The Vulnerable Pattern

const polka = require('polka');
const { MongoClient } = require('mongodb');

polka() .use(require(‘body-parser’).json()) .post(‘/api/user’, async (req, res) => { const client = await MongoClient.connect(‘mongodb://localhost:27017’); const db = client.db(‘apps’);

// VULNERABLE: Direct injection via object passing
// Attacker sends: { "username": "admin", "password": { "$ne": "" } }
const user = await db.collection('users').findOne({
  username: req.body.username,
  password: req.body.password
});

res.end(user ? 'Authenticated' : 'Failed');

}) .listen(3000);

The Secure Implementation

The exploit leverages JavaScript's dynamic typing. MongoDB drivers accept objects as query parameters to support operators ($gt, $regex, $ne). When an attacker sends a JSON body with an object instead of a string, the driver executes it as a logic command. By wrapping inputs in the 'String()' constructor or using a schema validator like Joi/Zod, you neutralize the attack by forcing the NoSQL engine to treat the input as a literal primitive rather than a query instruction.

const polka = require('polka');
const { MongoClient } = require('mongodb');

polka() .use(require(‘body-parser’).json()) .post(‘/api/user’, async (req, res) => { const client = await MongoClient.connect(‘mongodb://localhost:27017’); const db = client.db(‘apps’);

// SECURE: Explicit type casting to String
// This forces { "$ne": "" } to be treated as a literal string value
const username = String(req.body.username || '');
const password = String(req.body.password || '');

const user = await db.collection('users').findOne({
  username: username,
  password: password
});

res.end(user ? 'Authenticated' : 'Failed');

}) .listen(3000);

System Alert • ID: 3241
Target: Polka API
Potential Vulnerability

Your Polka API might be exposed to NoSQL Injection

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