HIGH regex dosadonisjsdynamodb

Regex Dos in Adonisjs with Dynamodb

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

AdonisJS applications that use regular expressions to validate or parse user input can be vulnerable to Regular Expression Denial of Service (ReDoS) when those patterns are applied to data retrieved from or stored in Amazon DynamoDB. The risk arises because DynamoDB stores string attributes that may include user-controlled content such as email addresses, URLs, or free-form text. If an AdonisJS route validates these attributes using naive or overly complex regex patterns, an attacker can supply crafted input that causes catastrophic backtracking, consuming excessive CPU time and leading to resource exhaustion or timeouts.

Specifically, this combination becomes dangerous when developers use patterns like (a+)+, .*.*, or overly permissive email regexes against DynamoDB string fields without pre-validating length or structure. For example, an attacker might store a large, specially crafted string in a DynamoDB attribute (e.g., a user profile bio or a query parameter stored as a DynamoDB item) that is later matched by an AdonisJS route using an inefficient pattern. Because DynamoDB does not perform regex evaluation, the burden shifts entirely to the application layer, where AdonisJS performs the match. This can result in long-running JavaScript event-loop blocking, increased latency, and potential denial of service for other requests.

Common real-world scenarios include using route parameter validation with regex patterns against DynamoDB primary key attributes, or sanitizing string fields retrieved from DynamoDB before rendering responses. If the regex is not carefully bounded (e.g., using possessive quantifiers, atomic groups, or explicit length limits), patterns intended to enforce format constraints can become severe bottlenecks. The impact is amplified when multiple requests target the same inefficient pattern, as each request independently triggers the costly backtracking on the server-side Node.js process.

Dynamodb-Specific Remediation in Adonisjs — concrete code fixes

To mitigate Regex Dos in AdonisJS when working with DynamoDB, adopt a defense-in-depth approach: constrain input lengths at the application level, use safe regex patterns, and validate data before it reaches DynamoDB or before it is matched in route handlers.

1. Use bounded, safe regex patterns

Replace open-ended quantifiers with explicit limits. For example, when validating an email retrieved from a DynamoDB item, use a pattern that limits the local part and domain length:

const emailPattern = /^[-!#$%&'*+/=?^_`{|}~0-9a-zA-Z]+(?:\.[-!#$%&'*+/=?^_`{|}~0-9a-zA-Z]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
const email = item.email; // item from DynamoDB
if (!emailPattern.test(email)) {
  throw new Error('Invalid email format');
}

2. Validate length and structure before regex matching

Ensure that string attributes from DynamoDB are within reasonable bounds before applying regex. For example, limit a username retrieved from DynamoDB to a safe length:

const username = item.username; // item from DynamoDB
if (username.length > 128) {
  throw new Error('Username too long');
}
const safeUsernamePattern = /^[a-zA-Z0-9_]{3,30}$/;
if (!safeUsernamePattern.test(username)) {
  throw new Error('Invalid username format');
}

3. Use non-backtracking regex features where supported

When your runtime environment supports it, prefer atomic groups or possessive quantifiers to prevent catastrophic backtracking. For a simple tag list stored in DynamoDB, you can split instead of using a complex single regex:

const tagsString = item.tags; // e.g., "node,api,security"
const tags = tagsString.split(',').map(t => t.trim()).filter(Boolean);
if (tags.length > 10) {
  throw new Error('Too many tags');
}
for (const tag of tags) {
  if (!/^[a-zA-Z0-9-]{1,30}$/.test(tag)) {
    throw new Error('Invalid tag format');
  }
}

4. Offload validation to DynamoDB condition expressions when possible

For simple format checks, use DynamoDB Condition Expressions with built-in functions to reduce application-side regex usage. For example, enforce a basic alphanumeric pattern on a partition key attribute during retrieval:

const AWS = require('aws-sdk');
const dynamo = new AWS.DynamoDB.DocumentClient();
const params = {
  TableName: 'Users',
  Key: { id: userId },
  ConditionExpression: 'attribute_exists(id) AND size(username) <= 128',
};
try {
  const data = await dynamo.get(params).promise();
  // further safe processing
} catch (err) {
  if (err.code === 'ConditionalCheckFailedException') {
    throw new Error('Validation failed');
  }
  throw err;
}

5. Leverage AdonisJS sanitizers and middleware

Use AdonisJS built-in sanitizers and validation rules to normalize input before it is used in regex checks or sent to DynamoDB. For route parameters, define a schema that constrains length and character set:

const { schema } = use('Validator');
const userSchema = schema.create({
  username: schema.string({ trim: true, escape: true }, [
    rules.minLength(3),
    rules.maxLength(30),
    rules.regex(/^[a-zA-Z0-9_]+$/),
  ]),
});

const { username } = await validate(request.all(), userSchema);
const params = {
  TableName: 'Users',
  Item: { id: userId, username },
};
await dynamo.put(params).promise();

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 regex patterns on DynamoDB string fields a risk in AdonisJS?
DynamoDB stores string attributes that may contain attacker-controlled content. If AdonisJS applies unbound or complex regex patterns to these values, it can trigger catastrophic backtracking, leading to high CPU usage and denial of service. Because regex evaluation happens in the application layer, there is no built-in protection in DynamoDB to prevent inefficient patterns.
How does middleBrick help identify Regex Dos risks with DynamoDB-backed APIs?
middleBrick scans API endpoints and returns a security risk score with findings such as inefficient regex usage against string fields. It includes contextual remediation guidance and maps findings to frameworks like OWASP API Top 10, helping you detect and prioritize Regex Dos risks before they impact production.