HIGH nosql injectionfeathersjsapi keys

Nosql Injection in Feathersjs with Api Keys

Nosql Injection in Feathersjs with Api Keys — how this specific combination creates or exposes the vulnerability

FeathersJS is a JavaScript framework for real-time applications that often uses MongoDB or other NoSQL databases. When an API is protected only by an API key and the key is used to identify a tenant or scope without enforcing strict query constraints, the service can become susceptible to NoSQL injection. This occurs when attacker-controlled input is directly interpolated into NoSQL query objects, allowing an attacker to alter query logic.

Consider a Feathers service that retrieves user profiles. If the service trusts a query parameter such as userId and combines it with an API key–based tenant identifier to build a filter object, an attacker who knows or guesses a valid API key can inject into the query structure. For example, if the code builds a filter like { tenantId: apiKeyTenant, _id: req.query.userId }, a malicious userId value such as { "$ne": null } can change the meaning of the query, potentially returning records belonging to other tenants or users.

In a black-box scenario, an attacker without account access might probe endpoints using a stolen or leaked API key. Because the scan tests unauthenticated attack surfaces and maps findings to frameworks like OWASP API Top 10, a tool such as middleBrick can detect patterns consistent with NoSQL injection. The presence of API key authentication does not automatically validate input; if the API key controls tenant scoping but input parameters are concatenated into the query object, the service may inadvertently allow logical bypasses, privilege elevation across tenant boundaries, or data exposure across users.

Additionally, if the Feathers service uses a generic hook that forwards query parameters directly to the database layer, the risk increases. Attack patterns such as query manipulation can lead to information leakage or unauthorized access to other users’ data under the same tenant. This aligns with real-world injection behaviors observed in NoSQL stores, where operators like $or, $in, and $where can be abused when input is not strictly validated or serialized.

Api Keys-Specific Remediation in Feathersjs — concrete code fixes

To mitigate NoSQL injection while using API keys in FeathersJS, treat the API key as a tenant or scope identifier and enforce strict schema validation on all user-controlled inputs before they reach the database. Do not concatenate raw query parameters into NoSQL filter objects. Instead, use explicit allow-lists and parameterized access patterns.

Example: Unsafe pattern

An unsafe Feathers service might directly merge query parameters into the data access layer:

// Unsafe: directly using req.query values in the filter
app.service('profiles').hooks({
  before: {
    find: (context) => {
      const { userId } = context.params.query;
      // Vulnerable: userId is injected into a NoSQL filter
      context.params.query = {
        tenantId: context.params.apiKeyTenant,
        _id: userId
      };
      return context;
    }
  }
});

Example: Safe remediation with validation and parameterization

Validate and serialize inputs, and construct filters programmatically:

const { param } = require('express-validator');

app.service('profiles').hooks({
  before: {
    find: async (context) => {
      // Validate and sanitize userId strictly
      const userId = context.params.query.userId;
      if (!userId || typeof userId !== 'string') {
        throw new Error('Invalid user identifier');
      }
      // Ensure userId is a valid ObjectId format (for MongoDB)
      if (!/^[0-9a-fA-F]{24}$/.test(userId)) {
        throw new Error('Malformed user identifier');
      }

      // Build filter safely: do not allow user input to define operators
      context.params.query = {
        tenantId: context.params.apiKeyTenant,
        _id: userId // trusted after validation
      };
      return context;
    }
  }
});

Alternatively, use a validation layer that maps allowed fields and rejects operators:

const forbiddenOperators = ['$ne', '$in', '$or', '$where', '$regex'];
function sanitizeFilter(input) {
  if (typeof input !== 'object' || input === null) return input;
  const cleaned = {};
  for (const key of Object.keys(input)) {
    if (forbiddenOperators.some(op => key.startsWith(op))) {
      throw new Error('Invalid query operator');
    }
    // allow only safe scalar values or known field names
    cleaned[key] = input[key];
  }
  return cleaned;
}

app.service('profiles').hooks({
  before: {
    find: (context) => {
      const safeQuery = sanitizeFilter(context.params.query);
      context.params.query = {
        tenantId: context.params.apiKeyTenant,
        ...safeQuery
      };
      return context;
    }
  }
});

When using the middleBrick CLI (middlebrick scan <url>) or the GitHub Action to add API security checks to your CI/CD pipeline, such validation patterns reduce the likelihood of NoSQL injection findings. The dashboard can help track the security score over time, and the MCP Server enables scanning APIs directly from AI coding assistants to catch unsafe patterns early.

Additional measures include tightening CORS and rate limiting, using parameterized queries or an ORM that escapes inputs, and ensuring the API key scope is strictly enforced server-side. These steps align the implementation with secure coding practices and reduce the risk of unauthorized data access or manipulation.

Frequently Asked Questions

Can API keys alone prevent NoSQL injection in FeathersJS?
No. API keys provide tenant or scope identification but do not validate user input. If raw query parameters are merged into NoSQL filters, injection can occur regardless of the presence of API keys. Input validation and strict filter construction are required.
How can automated scanning help detect NoSQL injection in FeathersJS APIs?
Tools like middleBrick can identify patterns where user input is directly embedded in query objects, flagging potential NoSQL injection vectors. By scanning the unauthenticated attack surface and mapping findings to frameworks such as OWASP API Top 10, it highlights insecure coding practices and provides remediation guidance.