Path Traversal in Restify with Mongodb
Path Traversal in Restify with Mongodb — how this specific combination creates or exposes the vulnerability
Path Traversal in a Restify service that uses MongoDB typically occurs when user-controlled path segments are used to build filesystem paths or to construct query filters that traverse logical boundaries. In a Restify context, endpoints that expose file-like resources or dynamic database lookups can become vectors if input is not strictly constrained. For example, an endpoint such as /files/:filename might concatenate req.params.filename into a filesystem location or use it to query a MongoDB collection where the field reflects a path or key. If the parameter is not validated, sequences like ../../ can move outside the intended directory scope when paths are resolved, or they can manipulate document references in MongoDB queries, leading to unauthorized data access.
When MongoDB is used, path traversal can also manifest through query injection that leverages dot notation or nested field traversal. An attacker might supply a parameter like user.$where[0].profile or a deeply nested path that maps to sensitive collections or fields, especially if the application dynamically builds query objects using string concatenation or unchecked user input. In a Restify handler, failing to sanitize and strictly type-check parameters before using them in MongoDB operations can expose document structures that should remain isolated. This becomes critical when the API serves multiple tenants or users and relies on path-derived identifiers to scope queries.
middleBrick can detect such issues by correlating OpenAPI specifications with runtime behavior. For example, if the spec defines a path parameter that is later used in a MongoDB filter without clear constraints, middleBrick’s checks for Input Validation and Property Authorization can highlight missing validation and potential traversal or privilege escalation paths. The scanner does not make assumptions about internal architecture but does flag high-risk patterns such as unvalidated path parameters in endpoints backed by MongoDB, supporting compliance mapping to OWASP API Top 10 and other standards.
Mongodb-Specific Remediation in Restify — concrete code fixes
To remediate Path Traversal in a Restify service using MongoDB, enforce strict input validation and avoid building filesystem paths or MongoDB queries directly from user input. Use parameterized approaches and schema validation to ensure that only expected values are accepted.
1. Validate and sanitize path parameters
Use a validation library to constrain allowed characters and block traversal sequences. For example, using an explicit allowlist for filenames prevents unexpected directory navigation.
const validate = require('express-validator'); // or similar validation middleware compatible with Restify
const sanitizedFilename = validate
.param('filename')
.isString()
.trim()
.escape()
.matches(/^[a-zA-Z0-9._-]+$/)
.withMessage('Invalid filename');
2. Use MongoDB’s native operators safely
Do not construct query objects by directly interpolating user input. Instead, use MongoDB operators explicitly and validate field paths to prevent unintended traversal via dot notation.
const { MongoClient } = require('mongodb');
async function getUserProfileSafe(db, tenantId, userIdentifier) {
// Validate tenantId and userIdentifier before use
const tenantRegex = /^[a-zA-Z0-9_-]+$/;
const userRegex = /^[a-zA-Z0-9_-]+$/;
if (!tenantRegex.test(tenantId) || !userRegex.test(userIdentifier)) {
throw new Error('Invalid identifier');
}
const collection = db.collection('profiles');
const user = await collection.findOne({
tenantId: tenantId,
'user.id': userIdentifier,
});
return user;
}
3. Scope queries with tenant isolation
Always include tenant or scope fields in queries to ensure users cannot traverse across logical boundaries. Avoid using path-derived values as part of the query key without mapping them to a controlled reference.
async function getFileMetadata(db, tenantId, logicalFileKey) {
const files = db.collection('files');
const metadata = await files.findOne({
tenantId: tenantId,
logicalId: logicalFileKey,
});
return metadata;
}
4. Avoid dynamic path concatenation for filesystem access
If your Restify endpoint interacts with the filesystem, resolve paths against a controlled base directory and use realpath to ensure the resolved path remains within the allowed scope.
const path = require('path');
const fs = require('fs').promises;
async function safeReadFile(baseDir, requestedName) {
const cleanName = path.basename(requestedName); // strips directory segments
const resolved = path.resolve(baseDir, cleanName);
if (!resolved.startsWith(path.resolve(baseDir))) {
throw new Error('Path traversal attempt');
}
return fs.readFile(resolved, 'utf8');
}
By combining strict validation, tenant-aware queries, and controlled filesystem resolution, you reduce the risk of Path Traversal in Restify applications using MongoDB. middleBrick’s scans can help verify that such controls are reflected in both your OpenAPI definitions and runtime behavior, mapping findings to relevant security checks and compliance guidance.
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 |