Path Traversal in Adonisjs with Mongodb
Path Traversal in Adonisjs with Mongodb — how this specific combination creates or exposes the vulnerability
Path Traversal occurs when an attacker manipulates file or resource paths to access files outside the intended directory. In AdonisJS applications using MongoDB, this typically arises through user-supplied input used to construct filesystem paths or to query document locations without proper validation. While AdonisJS does not directly expose MongoDB as a filesystem, developers sometimes use file-system-like patterns with GridFS or store metadata (e.g., file paths or keys) in MongoDB documents. If an endpoint accepts a fileId or path parameter and uses it to locate a document in a MongoDB collection without restricting traversal sequences (e.g., ../), an attacker can reference parent directory paths to reach sensitive collections or metadata intended to be isolated.
For example, an endpoint designed to retrieve user profile pictures might accept a parameter like username and store associated images in a virtual path inside GridFS. If the application builds a GridFS bucket name or key using string concatenation such as ${username}/profile.jpg, an attacker providing ../../../etc/passwd as the username can escape the expected namespace. Even when using MongoDB as a store for access control lists or document references, unsanitized path inputs can lead to unauthorized reads across logical boundaries, effectively achieving a traversal effect within the data model.
AdonisJS relies on its routing and validation layer to sanitize inputs, but if developers bypass built-in validation rules or use raw user input directly in MongoDB queries that influence path-like behavior, the framework’s protections can be circumvented. The risk is compounded when the application uses dynamic database or collection names derived from user input, as MongoDB permits selecting databases and collections via strings. An attacker could attempt to inject database or collection names containing traversal-like patterns (e.g., users;../secrets), depending on how the application maps requests to MongoDB namespaces.
Because middleBrick tests unauthenticated attack surfaces and includes checks for Input Validation and Property Authorization, it can identify endpoints where path-like parameters are not constrained. The scanner does not assume internal architecture but flags findings that align with OWASP API Top 10 A01:2023 — Broken Object Level Authorization, which often overlaps with traversal risks when object references are not properly scoped.
Mongodb-Specific Remediation in Adonisjs — concrete code fixes
To mitigate Path Traversal in AdonisJS with MongoDB, enforce strict input validation and avoid constructing path-like strings directly from user input. Use AdonisJS validator schemas to constrain parameters to safe patterns and sanitize values before using them in MongoDB queries.
1. Validate and sanitize path-like parameters
Use the AdonisJS validator to reject inputs containing traversal sequences and limit characters to alphanumeric values and safe separators. For example, when accessing user-specific resources, validate the username parameter to ensure it does not contain . or path separators.
// start:validator/ProfileValidator.ts
import { schema } from '@ioc:Adonis/Core/Validator'
export default class ProfileValidator {
public schema = schema.create({
username: schema.string({}, [
(value, signature) => {
if (value.includes('..') || value.includes('/') || value.includes('\\')) {
throw new Error('Invalid username')
}
}
])
})
public messages = {
'username/function': 'The username is invalid'
}
}
2. Use parameterized GridFS or fixed bucket patterns
When storing files in GridFS, avoid dynamically constructing bucket names or keys from user input. Instead, use a fixed bucket name and store the user identifier as a metadata field. This prevents traversal-like behavior across logical storage boundaries.
// start:controllers/FilesController.ts
import { schema } from '@ioc:Adonis/Core/Validator'
import GridFsBucket from 'mongodb-gridfs-stream'
export default class FilesController {
public async show({ request, response, auth }: HttpContextContract) {
const username = request.validatedOrFail('username', ProfileValidator)
const userId = auth.user?.id
// Fixed bucket, user identified via metadata, not path
const bucket = new GridFsBucket(this.connection.db, {
bucketName: 'user_avatars'
})
const downloadStream = bucket.openDownloadStreamByFilename('profile.jpg', {
metadata: { ownerId: userId }
})
return response.header('Content-Type', 'image/jpeg').sendStream(downloadStream)
}
}
3. Avoid dynamic database/collection selection
Do not use user input to determine database or collection names. If necessary, map user identifiers to predefined collection names using a whitelist or hashing mechanism that does not involve string concatenation of raw input.
// start:controllers/UserController.ts
import { schema } from '@ioc:Adonis/Core/Validator'
export default class UserController {
public async index({ request, mongo }: HttpContextContract) {
const safeName = 'users_collection' // fixed name
const collection = mongo.db.collection(safeName)
const users = await collection.find({}).toArray()
return users
}
}
These measures ensure that MongoDB interactions remain scoped and that path traversal attempts cannot escape intended boundaries. middleBrick’s checks for Input Validation and Property Authorization help verify that such controls are in place during scans.
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 |