HIGH regex dosadonisjsapi keys

Regex Dos in Adonisjs with Api Keys

Regex Dos in Adonisjs with Api Keys — how this specific combination creates or exposes the vulnerability

AdonisJS applications that use API keys in route patterns or parameter extraction can be exposed to Regular Expression Denial of Service (ReDoS) when route definitions or validation logic rely on non‑deterministic or overly broad regular expressions. A Regex DoS occurs when a crafted input causes the regex engine to exhibit catastrophic backtracking, consuming excessive CPU time and blocking the event loop. This is especially risky when API keys are part of the matched pattern, for example when keys are embedded directly in route paths or when custom validation regexes are used to enforce key formats.

Consider an AdonisJS route that attempts to match an API key inline using a permissive character class and a quantifier that can expand exponentially:

Route.get('/api/resource/:key', async ({ params }) => {
  // Dangerous: the regex used by route matching can be abused if the key pattern is complex
  const keyPattern = /^[a-zA-Z0-9]*$/; // non‑deterministic when combined with long strings
  if (!keyPattern.test(params.key)) {
    throw new Error('Invalid key');
  }
  return { status: 'ok' };
});

If the route parameter :key is expected to be a fixed‑length, high‑entropy API key, an attacker can send a long string with many alphanumeric characters that causes the regex engine to explore many paths, especially if the pattern includes ambiguous quantifiers like * or + with optional groups. In AdonisJS, route‑level pattern matching (e.g., using route parameter constraints) may also apply implicit regexes; combining these with custom validation can compound the risk.

Another scenario involves parsing API keys from headers or query strings with regexes that are not anchored or are overly permissive. For example, extracting a key from a header value using a global search with repeated quantifiers can lead to long processing times on malicious input:

const extractKey = (header) => {
  const match = header.match(/^(?:.*?ApiKey\s*)*([a-f0-9]{32,128})$/i);
  return match ? match[1] : null;
};

The inner group (?:.*?ApiKey\s*)* is non‑deterministic because it allows many ways to match the same input, and the quantifier on the outer group enables exponential possibilities. When such patterns are evaluated for every request, an attacker can send a specially crafted header value that triggers severe backtracking, leading to elevated CPU usage and degraded service.

AdonisJS applications that rely on API keys for authentication should audit all route definitions, parameter constraints, and validation logic for regex patterns that include ambiguous quantifiers, nested quantifiers, or optional groups with overlapping matches. Even when API keys are handled via middleware or auth providers, any regex used to validate or parse them must be deterministic and bounded to avoid opening an indirect ReDoS vector.

Api Keys-Specific Remediation in Adonisjs — concrete code fixes

Mitigating Regex DoS in AdonisJS when API keys are involved centers on using deterministic patterns, avoiding unbounded repetition, and validating keys with fixed‑length or strictly bounded expressions. Prefer exact length checks or simple character class scans instead of complex regexes, and ensure that patterns are anchored and non‑recursive.

First, validate API keys using a fixed‑length hexadecimal check rather than open‑ended quantifiers. If your keys are 32‑character hex strings, use a precise pattern:

const isValidKey = (key) => /^[a-fA-F0-9]{32}$/.test(key);

// Example in an AdonisJS route handler
Route.get('/api/resource/:key', async ({ params }) => {
  if (!isValidKey(params.key)) {
    return Response.badRequest({ error: 'Invalid API key format' });
  }
  return { status: 'ok' };
});

This pattern is deterministic: it matches exactly 32 hex characters with no nested quantifiers or optional groups that could cause backtracking.

When API keys are passed in headers, avoid global scans with nested repetitions. Instead, use a simple prefix check followed by a bounded pattern:

const extractKeyFromHeader = (header) => {
  const prefix = 'ApiKey ';
  if (!header.startsWith(prefix)) return null;
  const key = header.slice(prefix.length);
  return /^[a-fA-F0-9]{32}$/.test(key) ? key : null;
};

// Usage in AdonisJS middleware
const ApiKeyValidator = async ({ request }, next) => {
  const key = extractKeyFromHeader(request.headers().get('authorization'));
  if (!key) {
    return response.unauthorized('Missing or malformed API key');
  }
  request.apiKey = key;
  await next();
};

This approach eliminates ambiguous repetitions by first checking a static prefix and then applying a fixed‑length regex, which is both safe and performant.

For applications using AdonisJS provider patterns or custom auth schemes, centralize key validation in a dedicated service with a strict schema. Avoid dynamically building regexes from user input or concatenating unbounded wildcards. If you integrate with tools like the middleBrick CLI (middlebrick scan <url>) or the GitHub Action to add API security checks to your CI/CD pipeline, include regex validation rules in your tests to ensure findings related to dangerous patterns are caught before deployment.

Finally, monitor for unexpected key formats in logs and use deterministic string operations (starts/ends with, length checks) where possible. Combining these practices reduces the attack surface for Regex DoS while keeping API key handling robust and efficient.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

Why are fixed-length regex patterns safer than open-ended ones for API key validation in AdonisJS?
Fixed-length patterns like /^[a-fA-F0-9]{32}$/ are deterministic and have constant runtime, whereas open-ended patterns with * or + can cause exponential backtracking on crafted inputs, leading to ReDoS.
Can middleBrick detect Regex DoS risks related to API key validation patterns?
middleBrick scans unauthenticated attack surfaces and includes checks such as Input Validation; findings may highlight suspicious regex usage. Use the CLI (middlebrick scan ) or the GitHub Action to include these scans in CI/CD pipelines.