HIGH xpath injectionfeathersjsapi keys

Xpath Injection in Feathersjs with Api Keys

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

XPath Injection occurs when untrusted input is concatenated into an XPath expression without proper sanitization or parameterization. In FeathersJS, services often define custom find or get logic where developer-supplied query parameters are used directly inside XPath selectors. If the service also relies on API keys for routing, authorization, or versioning, keys may be reflected in logs, error messages, or used to select different XPath branches, increasing the attack surface.

Consider a Feathers service that resolves an XPath query against an XML document, selecting a namespace map based on an API key header value:

// Risky Feathers service hook: using API key to pick namespace context
app.service('data').hooks({
  before: {
    all: [ (context) => {
      const apiKey = context.params.headers['x-api-key'];
      const ns = apiKey == 'premium' ? 'ns1' : 'ns2';
      // Unsafe: user-controlled 'id' concatenated into XPath
      const xpath = `//${ns}:root/${ns}:item[@id='${context.id}']`;
      context.params.xpath = xpath;
      return context;
    } ]
  }
});

If context.id is user-controlled (e.g., from query or body), an attacker can break out of the intended node selection and alter document traversal. For example, with id=a' or '1'='1, the resulting XPath might become //ns1:root/ns1:item[@id='a' or '1'='1'], returning multiple nodes or bypassing intended filters. Additionally, if the API key influences which endpoint or mock data set is used (e.g., selecting a different XML file), an attacker may probe keys to enumerate internal document structures, leading to information disclosure.

In a black-box scan, middleBrick tests such patterns by injecting XPath meta-characters and boolean conditions while observing differences in response codes, timing, and data exposure. Findings may align with the OWASP API Top 10 category 'Broken Object Level Authorization' and related data exposure risks. The scanner also checks whether findings appear in spec-defined parameters (OpenAPI/Swagger 2.0/3.x) and maps them to compliance frameworks like PCI-DSS and SOC2.

Unlike traditional authenticated scans, this assessment is unauthenticated; the API key here is treated as part of the attack surface rather than a credential. middleBrick’s LLM/AI Security checks do not apply to this vector, but the tool does provide prioritized findings with remediation guidance and a per-category breakdown on the Dashboard or in exported reports.

Api Keys-Specific Remediation in Feathersjs — concrete code fixes

Secure FeathersJS services avoid concatenating untrusted input into XPath expressions. Instead, use parameterized XPath evaluation (where the runtime supports it) or strict allow-lists for namespace and element selection. API keys should never influence XPath construction; if keys are needed for routing, keep that logic outside XPath evaluation and validate inputs independently.

Remediation example: parameterize XPath and validate input against a strict pattern:

// Safer Feathers service hook: parameterize XPath, validate ID
const { xpathEval } = require('xpath-async'); // example library
app.service('data').hooks({
  before: {
    all: [ (context) => {
      const apiKey = context.params.headers['x-api-key'];
      // Use API key only for routing/auth decisions, not XPath building
      if (!['standard', 'premium'].includes(apiKey)) {
        throw new Error('Invalid API key');
      }
      const id = context.id;
      // Validate ID format strictly (alphanumeric, length)
      if (!/^[A-Za-z0-9_-]{1,64}$/.test(id)) {
        throw new Error('Invalid identifier');
      }
      // Parameterized XPath (pseudo API, depends on runtime support)
      context.params.xpath = {
        expression: '//root/item[@id=$id]',
        vars: { id }
      };
      return context;
    } ]
  }
});

If your XPath library does not support variables, sanitize input by allowing only known-safe values or by using a strict allow-list for element names and attributes. Avoid dynamic namespace selection driven by API keys; instead, fix namespaces in the service or configuration:

// Fixed namespace usage, API key used only for policy checks
const NAMESPACE = 'http://example.com/ns';
app.service('data').hooks({
  before: {
    all: [ (context) => {
      const apiKey = context.params.headers['x-api-key'];
      if (apiKey !== 'valid-key') {
        throw new Error('Forbidden');
      }
      // Safe: input is not concatenated into XPath
      const id = context.id.replace(/"/g, '"'); // basic escape if needed
      context.params.xpath = `//${NAMESPACE}:root/${NAMESPACE}:item[@id='${id}']`;
      return context;
    } ]
  }
});

Additionally, ensure API keys are handled via secure headers, never logged in full, and that error messages do not reflect user input. Use the middleBrick CLI to verify remediation:

$ middlebrick scan https://api.example.com/openapi.json

Review findings in the Web Dashboard or via the GitHub Action to fail builds if risk scores degrade. The Pro plan enables continuous monitoring and CI/CD integration for ongoing protection.

Frequently Asked Questions

Can middleBrick fix XPath Injection findings automatically?
middleBrick detects and reports XPath Injection with severity, impact, and remediation guidance. It does not automatically patch or block requests; developers must apply the suggested fixes in code and configuration.
How does using an API key in service hooks affect the scan?
If API keys influence XPath construction or data selection, they expand the attack surface. The scan treats the key as part of the surface, testing injection while the key influences branching. Do not rely on keys to select namespaces or documents; instead fix the logic and use keys for authentication/authorization only.