HIGH nosql injectionfeathersjs

Nosql Injection in Feathersjs

How Nosql Injection Manifests in Feathersjs

Nosql Injection in Feathersjs occurs when user-supplied input is directly incorporated into MongoDB queries without proper sanitization. Unlike SQL injection, NoSQL injection exploits the query language's flexibility to manipulate database operations through crafted input.

In Feathersjs, the most common attack vectors appear in service methods that accept query parameters. Consider this vulnerable pattern:

const usersService = app.service('users');

// Vulnerable: Direct query parameter injection
app.get('/api/users', async (req, res) => {
const query = {
$where: req.query.filter
};
const users = await usersService.find({ query });
res.json(users);
});

An attacker could send: /api/users?filter=this.constructor.constructor('return process.mainModule.require(%22os%22).homedir()')() to execute arbitrary code on the server.

Another common pattern involves $regex injection:

// Vulnerable: Regex injection
app.get('/api/search', async (req, res) => {
const query = {
email: { $regex: req.query.pattern }
};
const results = await usersService.find({ query });
res.json(results);
});

Feathersjs's service layer makes these attacks particularly dangerous because it automatically converts query parameters into MongoDB operators. An attacker can manipulate operators like $ne, $gt, $lt, or even inject $where clauses that execute JavaScript.

Object injection is another critical vulnerability:

// Vulnerable: Object injection via query params
app.get('/api/items', async (req, res) => {
const query = JSON.parse(req.query.q);
const items = await itemsService.find({ query });
res.json(items);
});

If an attacker sends ?q={%22$ne%22:{%22%24where%22:%22return%20this.constructor.constructor('return%20process.env')()%22}}, they can potentially access environment variables.

Feathersjs's authentication hooks don't automatically protect against these injection patterns, making it crucial to validate and sanitize all user input before it reaches the database layer.

Feathersjs-Specific Detection

Detecting Nosql Injection in Feathersjs applications requires both static analysis and runtime scanning. middleBrick's black-box scanning approach is particularly effective for Feathersjs APIs because it tests the actual attack surface without requiring source code access.

middleBrick scans Feathersjs endpoints by submitting crafted payloads to test for NoSQL injection vulnerabilities. The scanner automatically tests for:

  • $where clause injection with JavaScript execution
  • $regex pattern injection
  • Object injection via query parameters
  • Operator manipulation ($ne, $gt, $lt, etc.)
  • Array and object injection patterns

For a Feathersjs application running at https://api.example.com, you can scan it directly:

npm install -g middlebrick
middlebrick scan https://api.example.com/users

The CLI will test common injection patterns and report findings with severity levels. For CI/CD integration, add this to your GitHub workflow:

- name: Scan API Security
uses: middlebrick/middlebrick-action@v1
with:
url: ${{ secrets.API_URL }}
fail-on-severity: high
token: ${{ secrets.MIDDLEBRICK_TOKEN }}

middleBrick's LLM/AI security checks are particularly relevant for Feathersjs applications using AI features. The scanner tests for system prompt leakage and prompt injection vulnerabilities that could be exploited alongside NoSQL injection.

Manual detection techniques for Feathersjs include:

// Test for $where injection
app.get('/test-injection', async (req, res) => {
try {
const query = { $where: req.query.test };
const result = await usersService.find({ query });
res.json({ success: true, count: result.length });
} catch (error) {
res.json({ error: error.message });
}

Run this endpoint through middleBrick to verify it's properly protected. The scanner will attempt various injection payloads and report if any succeed.

Feathersjs-Specific Remediation

Remediating NoSQL injection in Feathersjs requires input validation, parameterized queries, and proper use of Feathersjs's built-in features. Here are Feathersjs-specific solutions:

1. Input Validation with Feathers Hooks

const { hooks } = require('@feathersjs/commons');

// Custom validation hook
const validateQuery = hook => {
const allowedOperators = ['$eq', '$gt', '$lt', '$gte', '$lte', '$in'];
const query = hook.params.query || {};

const sanitize = obj => {
if (typeof obj !== 'object' || obj === null) return obj;

for (const [key, value] of Object.entries(obj)) {
if (key.startsWith('$') && !allowedOperators.includes(key)) {
delete obj[key];
} else if (typeof value === 'object') {
sanitize(value);
}
}
return obj;
};

hook.params.query = sanitize(query);
return hook;
};

Apply this hook to services:

app.service('users').hooks({
before: {
find: [validateQuery, sanitizeInput]
}
});

2. Using Feathers Query Sanitization

const { disallow, discard } = require('@feathersjs/commons');

app.service('users').hooks({
before: {
find: [discard('$where'), disallow('$regex')],
update: [disallow('$where')],
patch: [disallow('$where')]
}
});

3. Parameterized Query Pattern

// Safe pattern using whitelist approach
const allowedFields = ['name', 'email', 'age'];

app.get('/api/users', async (req, res) => {
const query = { $limit: 10 };
for (const [key, value] of Object.entries(req.query)) {
if (allowedFields.includes(key)) {
query[key] = value;
}
}

const users = await usersService.find({ query });
res.json(users);
});

4. Using Feathers Common Sanitization

const { discard, disallow } = require('@feathersjs/commons');

const sanitizeQuery = hook => {
const query = hook.params.query || {};

// Remove dangerous operators
discard(['$where', '$regex'])(hook);

// Validate field names
const allowedFields = new Set(['name', 'email', 'age']);

for (const [key, value] of Object.entries(query)) {
if (allowedFields.has(key)) {
sanitized[key] = value;
}
}

hook.params.query = sanitized;
};

5. Testing with middleBrick

After implementing these fixes, verify them with middleBrick:

middlebrick scan https://your-feathers-app.com/api/users

The scanner will attempt injection attacks and confirm whether your protections are effective. middleBrick provides specific remediation guidance for any vulnerabilities found, mapping them to OWASP API Security Top 10 standards.

Frequently Asked Questions

How is NoSQL injection different in Feathersjs compared to other Node.js frameworks?
Feathersjs's service layer automatically converts query parameters into MongoDB operators, making injection more straightforward for attackers. The framework's convention-over-configuration approach means developers might not realize how query parameters are being processed. middleBrick specifically tests Feathersjs patterns like $where injection and operator manipulation that are unique to this framework's query handling.
Can middleBrick detect NoSQL injection in my Feathersjs API without access to the source code?
Yes, middleBrick performs black-box scanning that tests the actual API endpoints. It sends crafted payloads to detect injection vulnerabilities without needing your source code. For Feathersjs applications, middleBrick tests common injection patterns like $where clauses, $regex injection, and object manipulation. The scanner runs in 5-15 seconds and provides specific findings with severity levels and remediation guidance.