HIGH path traversaladonisjsdynamodb

Path Traversal in Adonisjs with Dynamodb

Path Traversal in Adonisjs with Dynamodb — how this specific combination creates or exposes the vulnerability

Path Traversal occurs when user-controlled input is used to construct file system paths without proper validation, allowing an attacker to access arbitrary files outside the intended directory. In AdonisJS, this typically arises when a route parameter or query string is directly concatenated into file operations such as fs.readFile or fs.stat. When AdonisJS applications integrate with AWS DynamoDB as a persistence layer, the risk shifts to how data stored in DynamoDB is later used to build file paths or references.

Consider an endpoint that retrieves an object from DynamoDB using a user-supplied identifier and then uses one of its attributes to build a local file path. If the attribute is attacker-controlled and not validated, an attacker can supply values like ../../../etc/passwd. Even though DynamoDB itself does not execute file operations, the application layer that reads from DynamoDB and interacts with the file system becomes the attack surface. The DynamoDB entry may have been created legitimately, but if the application trusts its contents, Path Traversal can be triggered downstream.

Additionally, if the application uses DynamoDB metadata (such as S3 object keys stored as attributes) to construct pre-signed URLs or local cache paths, and those keys include user-influenced components without normalization, the same class of vulnerability exists. For example, a key stored as user_uploads/../../etc/passwd in a DynamoDB attribute, when later used in path resolution, can escape the intended directory. The scan checks for these patterns by correlating DynamoDB attribute usage with runtime path-building logic, flagging instances where data from DynamoDB flows into file system operations without canonicalization or strict allowlisting.

In the context of middleBrick’s checks, the scanner tests unauthenticated endpoints that interact with DynamoDB-derived data and observes whether path traversal indicators appear in responses or side effects. It does not rely on internal architecture but on observable behavior, ensuring that the combination of AdonisJS route handling and DynamoDB data usage is assessed for insecure path construction patterns aligned with OWASP API Top 10 and related framework-specific risks.

Dynamodb-Specific Remediation in Adonisjs — concrete code fixes

To mitigate Path Traversal when using DynamoDB in AdonisJS, enforce strict input validation and canonicalize any file paths derived from DynamoDB attributes. Avoid concatenating user data or DynamoDB-stored values directly into file system paths. Instead, use a controlled mapping and validate against an allowlist of permitted values or patterns.

Secure DynamoDB attribute usage with path sanitization

When retrieving an item from DynamoDB, treat attributes that may influence file paths as untrusted. Use Node.js path utilities to normalize and validate paths, and ensure resolved paths remain within an allowed base directory.

import { join, normalize, resolve } from 'path';
import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3';
import { DynamoDBDocumentClient, GetCommand } from '@aws-sdk/lib-dynamodb';

const ddb = DynamoDBDocumentClient.from(new S3Client({}));
const allowedBase = resolve(process.cwd(), 'public/uploads');

async function getFileFromDynamo(userId, fileId) {
  const cmd = new GetCommand({
    TableName: 'UserFiles',
    Key: { userId, fileId },
  });
  const { Item } = await ddb.send(cmd);

  if (!Item || !Item.key) {
    throw new Error('File not found');
  }

  // Canonicalize and validate the key from DynamoDB before using it as a path
  const normalized = normalize(Item.key);
  const resolved = resolve(allowedBase, normalized);

  if (!resolved.startsWith(allowedBase)) {
    throw new Error('Invalid path traversal attempt');
  }

  // Use resolved path for safe file system operations
  return resolved;
}

In this example, Item.key originates from DynamoDB. The code normalizes path segments and ensures the resolved path does not escape allowedBase. This prevents sequences like ../../../etc/passwd from escaping the intended directory, even if the DynamoDB attribute contains malicious input.

Route parameter validation with allowlists

Validate route parameters before using them to query DynamoDB or derive file paths. Use AdonisJS schema validation to restrict characters and length, and avoid passing raw parameters to file operations.

import { schema } from '@ioc:Adonis/Core/Validator';
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';

const fileRouteSchema = schema.create({
  fileId: schema.string({ trim: true, escape: false }, [
    schema.regex('safeName', /^[a-zA-Z0-9_.-]+$/),
  ]),
});

export default class FilesController {
  public async show({ request, response }: HttpContextContract) {
    const payload = request.validate({ schema: fileRouteSchema });
    const safeFileId = payload.fileId;

    // Use safeFileId to query DynamoDB and derive paths securely
    const filePath = await getFileFromDynamo(request.$auth.user.id, safeFileId);
    return response.sendFile(filePath);
  }
}

The allowlist regex ensures fileId contains only safe characters, reducing the risk of path traversal before any DynamoDB lookup occurs. Combined with canonicalization on the retrieved attribute, this approach addresses Path Traversal across both application input and stored data.

Data stored in DynamoDB should avoid embedding path-like structures

Design DynamoDB items to store opaque identifiers or predefined keys rather than path fragments supplied by users. This reduces the attack surface by ensuring that even if an attribute is read from DynamoDB, it cannot directly influence file system paths without additional secure mapping.

Risk Area Insecure Pattern Secure Pattern
Path construction join(userSupplied, dbItem.key) resolve(allowedBase, sanitize(dbItem.key))
Route parameters query.fileId used directly Validated with allowlist before DynamoDB lookup

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

Can DynamoDB itself prevent Path Traversal?
DynamoDB does not handle file system paths; it stores and retrieves data. Path Traversal is an application-layer concern. Security depends on how AdonisJS uses data retrieved from DynamoDB, not on DynamoDB controls.
Does middleBrick fix Path Traversal in DynamoDB integrations?
middleBrick detects and reports Path Traversal findings and provides remediation guidance. It does not automatically patch code or modify DynamoDB data. Developers must apply the suggested fixes in their AdonisJS application.