Path Traversal in Restify with Dynamodb
Path Traversal in Restify with Dynamodb — how this specific combination creates or exposes the vulnerability
Path Traversal in a Restify service that uses DynamoDB as a backend often arises from unsafe construction of DynamoDB key expressions using user-controlled path parameters. Because DynamoDB access patterns are driven by keys, an attacker can manipulate string concatenation or template literals to traverse logical paths and reference unintended items or attributes.
Consider a Restify endpoint designed to fetch user data by ID, where the ID is appended to a DynamoDB key prefix. If the endpoint does not validate or sanitize the ID, a crafted path such as ../../../admin/000 can be appended to the prefix, causing the constructed key to resolve outside the intended logical partition. This does not exploit a filesystem path traversal but a logical key traversal that exposes or overwrites data belonging to other users or administrative records.
In DynamoDB, operations like GetItem or Query rely on exact key matches. If the application builds the key using string interpolation, an attacker-supplied path segment can shift the effective partition key or sort key, leading to unauthorized reads. For example, given a table with partition key PK and sort key SK, a naive implementation might do pk = `USER#${req.params.id}`. With id set to ../../../admin, the resulting PK no longer scoped to the target user, potentially matching administrative items if prefix patterns overlap.
Another common pattern is using DynamoDB Document Paths in expression attribute names to navigate nested structures. If user input is used directly in expression attribute names without validation, an attacker can inject path segments to reach sensitive attributes. For example, an expression like #map.#user.#data can be altered to #map.#user.#data../../../secrets, attempting to traverse logical map keys to reach unintended data. This is especially risky when combined with overly permissive IAM policies, where the same credentials used for legitimate queries also allow broader item access.
middleBrick detects these patterns during black-box scanning by testing endpoints with path traversal payloads and observing whether DynamoDB responses differ unexpectedly, indicating that logical key boundaries are not enforced. Findings are mapped to the Authentication and BOLA/IDOR checks, as improper scoping often leads to unauthorized access across user boundaries. The LLM/AI Security checks do not apply here, but the scanner validates that responses remain constrained to the intended tenant or resource scope.
Because DynamoDB does not provide native filesystem-style path resolution, the risk manifests as data exposure or incorrect authorization rather than arbitrary file access. The impact depends on what data lies at the traversed logical location: administrative configurations, PII, or cross-user records. Remediation focuses on strict input validation, canonicalization of keys, and scoping queries with explicit partition key values.
Dynamodb-Specific Remediation in Restify — concrete code fixes
To prevent Path Traversal in Restify with DynamoDB, enforce strict validation and canonicalization of identifiers before constructing keys. Use allowlists for acceptable characters (e.g., alphanumeric and a limited safe set), and reject any input containing path-like sequences such as .. or directory separators. Avoid building keys via string concatenation with user input; instead, use structured identifiers and bind them explicitly to known partition and sort key values.
Example: Safe DynamoDB GetItem with Restify
Below is a secure Restify handler that retrieves a user item using a validated user ID. The ID is checked against a regex allowlist before constructing the DynamoDB key. The partition key is explicitly set, preventing key traversal.
const restify = require('restify');
const { DynamoDBClient, GetItemCommand } = require('@aws-sdk/client-dynamodb');
const client = new DynamoDBClient({ region: 'us-east-1' });
const server = restify.createServer();
server.get('/users/:id', async (req, res, next) => {
const { id } = req.params;
// Strict allowlist: alphanumeric and underscores, 1..64 chars
if (!/^[A-Za-z0-9_]{1,64}$/.test(id)) {
return next(new restify.InvalidArgumentError('Invalid user identifier'));
}
const params = {
TableName: process.env.USERS_TABLE,
Key: {
PK: { S: `USER#${id}` },
SK: { S: `PROFILE` }
}
};
try {
const command = new GetItemCommand(params);
const data = await client.send(command);
if (!data.Item) {
return next(new restify.NotFoundError('User not found'));
}
res.send(200, {
id,
name: data.Item.name?.S,
email: data.Item.email?.S
});
} catch (err) {
return next(new restify.InternalServerError('Failed to fetch user'));
}
});
server.listen(8080, () => {
console.log('Service running on port 8080');
});
Example: Query with explicit partition key and safe sort key filtering
When using Query, provide the partition key directly and avoid injecting user input into the key expression. Use filter expressions for attribute-level constraints instead.
const params = {
TableName: 'ACTIVITY_LOG',
KeyConditionExpression: 'PK = :pk AND begins_with(SK, :skPrefix)',
ExpressionAttributeValues: {
':pk': { S: `USER#${validatedUserId}` },
':skPrefix': { S: 'EVENT#' }
},
FilterExpression: 'timestamp BETWEEN :start AND :end',
ExpressionAttributeValues: {
':start': { N: String(startTimestamp) },
':end': { N: String(endTimestamp) }
}
};
General defensive practices
- Do not construct DynamoDB keys by interpolating path segments from URLs.
- Use middleware to normalize and validate identifiers early in the request lifecycle.
- Apply least-privilege IAM policies so that each operation only accesses the specific table and key patterns required.
- Log rejected inputs for audit purposes without exposing sensitive data in responses.
middleBrick’s CLI can be used to verify that endpoints handling DynamoDB-backed resources do not exhibit path traversal by running middlebrick scan <url>. The dashboard and GitHub Action integrations help track findings over time and prevent regressions in CI/CD pipelines.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |