HIGH formula injectionfeathersjsapi keys

Formula Injection in Feathersjs with Api Keys

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

Formula Injection occurs when an attacker can control part of a formula or expression that is later evaluated by a backend service, leading to unintended behavior or data access. In FeathersJS, this commonly arises when query parameters, headers, or payload fields are used to construct dynamic expressions or filter values without strict validation. When API keys are involved, the risk compounds because keys often grant elevated permissions or access to scoped data.

FeathersJS applications frequently use feathers-query-filters or custom hooks to transform REST query parameters into database queries. If an API key is passed in a header (e.g., x-api-key) and its value is directly interpolated into a query or used to influence record-level filtering, an attacker may supply a malicious formula such as 1=1 or a nested object like {"$or": [{"id": "0"}, {"id": "1"}]} to bypass intended access controls.

Consider a Feathers service that uses an API key to determine tenant scope:

// Before fix: vulnerable usage in a Feathers before hook
app.hooks('before').hooks.push((context) => {
  const apiKey = context.headers['x-api-key'];
  if (apiKey) {
    // Unsafe: directly using API key value to scope query
    context.params.query.tenantId = apiKey;
  }
  return context;
});

If the API key value is attacker-controlled (e.g., obtained via leakage or brute force), the query scope can be overridden, leading to OWASP API Security Top 10 violations such as Broken Object Level Authorization (BOLA). In this scenario, an attacker could enumerate valid API keys or reuse a key from a lower-privilege tenant to access another tenant’s data, effectively performing horizontal privilege escalation.

Formula Injection with API keys can also manifest in log aggregation or analytics pipelines where API key values are embedded into evaluative expressions. For example, if a key is used to dynamically generate a filter expression that is later eval’d or passed to a query builder without sanitization, arbitrary code execution or data leakage may occur. This aligns with OWASP A03: Injection and should be treated as a high-severity risk when sensitive data is involved.

The interaction between dynamic query building and static secrets like API keys creates a narrow attack surface that is difficult to secure without explicit allowlisting and strict schema validation. FeathersJS does not inherently sanitize these values, so developers must enforce input constraints and avoid using raw header or payload values in security-critical decisions.

Api Keys-Specific Remediation in Feathersjs — concrete code fixes

Remediation focuses on decoupling API key authentication from data access logic and enforcing strict schema validation. API keys should be used solely for authentication and rate limiting, not for building queries or scoping records directly.

1. Use an authentication hook to resolve identity, not query parameters

Instead of passing the API key into the query object, resolve the user or tenant in a dedicated hook and attach a normalized identity to context.params.

// Secure: resolve identity in a hook, do not inject into query
app.hooks('before').hooks.push(async (context) =>
{
  const apiKey = context.headers['x-api-key'];
  if (apiKey) {
    const tenant = await getTenantByKey(apiKey); // your validation logic
    if (!tenant) {
      throw new Error('Unauthorized');
    }
    // Attach resolved tenant ID, not the raw key
    context.params.tenantId = tenant.id;
    // Remove the key from params to prevent accidental exposure
    delete context.params.query['x-api-key'];
  }
  return context;
});

2. Validate and whitelist query inputs

Use a validation layer (e.g., feathers-hooks-common or a custom validator) to ensure only expected fields are allowed in queries.

const { iff, isProvider, preventChanges } = require('feathers-hooks-common');

app.service('records').hooks({
  before: {
    all: [
      // Prevent mutation of tenant scope by client
      preventChanges(['query.tenantId'], 'tenantId is managed by server'),
      // Ensure query fields conform to schema
      (context) => {
        const allowedKeys = ['$limit', '$skip', 'status'];
        const query = context.params.query || {};
        Object.keys(query).forEach(key => {
          if (!allowedKeys.includes(key)) {
            delete query[key];
          }
        });
        return context;
      }
    ]
  }
});

3. Avoid eval-like transformations of API key values

Never construct code or expressions using API key values. If dynamic filtering is required, use a predefined mapping rather than raw evaluation.

// Unsafe pattern to avoid
const filterExpr = buildExpression(context.params.query.formula); // hypothetical
const result = eval(filterExpr); // dangerous

// Safe alternative: use parameterized filters
const safeFilters = {
  status: context.params.query.status || 'active',
  limit: Number(context.params.query.limit) || 50
};
const records = await app.service('data').find({ query: safeFilters });

By treating API keys as opaque credentials and separating identity resolution from data access, you mitigate Formula Injection risks and align with OWASP API Security Top 10 controls.

Frequently Asked Questions

How does middleBrick detect Formula Injection risks related to API keys?
middleBrick runs parallel security checks including Input Validation and Property Authorization. It analyzes OpenAPI/Swagger specs and runtime behavior to detect whether API key values are used in query construction or expression evaluation, flagging potential BOLA or injection findings with remediation guidance.
Can the middleBrick CLI be used to scan FeathersJS APIs for API key related vulnerabilities?
Yes. Use the CLI to scan from terminal with middlebrick scan . The scan includes checks for authentication misuse, unsafe consumption patterns, and input validation issues relevant to API key handling in FeathersJS services.