Path Traversal in Adonisjs with Cockroachdb
Path Traversal in Adonisjs with Cockroachdb — how this specific combination creates or exposes the vulnerability
Path Traversal occurs when an attacker manipulates file paths to access or affect files outside the intended directory. In Adonisjs, this risk is amplified when user-controlled input is directly used to construct filesystem paths or to query a database such as Cockroachdb without proper validation or sanitization. Cockroachdb, as a distributed SQL database, does not inherently prevent unsafe path usage in application code; it faithfully executes queries constructed by the application. If Adonisjs constructs dynamic file paths or SQL identifiers using unsanitized parameters — for example, a file name or a table name derived from user input — an attacker may use sequences like ../../../etc/passwd or encoded variants to traverse directories.
Consider an Adonisjs controller that serves documents stored in a Cockroachdb-managed metadata table and uses a user-supplied document identifier to locate a file path. If the identifier is concatenated into a filesystem path without normalization and validation, the request /documents?file=../../../config may resolve outside the document root. Even when Cockroachdb stores file metadata or permissions, the application layer must enforce strict path controls. Attackers may also exploit path traversal to influence SQL object names if dynamic identifiers are improperly interpolated, potentially leading to unauthorized data access or injection-assisted operations. Since Cockroachdb supports standard SQL string patterns, crafted inputs could attempt to break escaping logic if the application does not treat paths as opaque values.
Moreover, the combination of Adonisjs routing and Cockroachdb queries can expose indirect traversal risks: an API endpoint might accept a folder identifier, query Cockroachdb for associated resources, and then use the returned path to serve files. If the database value is trusted without revalidation, an attacker who can manipulate database entries (e.g., via other vulnerabilities) may indirectly force path traversal when the application later concatenates that value with a base directory. This highlights the need to treat both the web framework layer and the database layer as part of a single defense-in-depth strategy against path traversal.
Cockroachdb-Specific Remediation in Adonisjs — concrete code fixes
Remediation focuses on strict input validation, canonical path resolution, and avoiding direct concatenation of user input into filesystem or SQL object paths. In Adonisjs, use framework utilities for path manipulation and ensure that any value retrieved from Cockroachdb is verified before use. Below are concrete, safe patterns with Cockroachdb code examples tailored for Adonisjs.
1. Validated file access with resolved absolute paths
Always resolve user input against a strict base directory and ensure the resulting path remains within that boundary. Use Node.js built-in modules alongside Adonisjs request handling.
import { join, resolve, normalize } from 'path';
import { ensureDir, pathExists } from 'fs-extra';
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
export default class DocumentsController {
public async serveDocument({ request, response }: HttpContextContract) {
const requested = request.qs().file as string;
const baseDir = resolve('/app/public/documents');
// Normalize and resolve; this removes '..' sequences
const normalized = normalize(requested);
const resolved = resolve(baseDir, normalized);
if (!resolved.startsWith(baseDir)) {
return response.badRequest({ error: 'Invalid path' });
}
const exists = await pathExists(resolved);
if (!exists) {
return response.notFound({ error: 'File not found' });
}
return response.sendFile(resolved);
}
}
2. Parameterized queries with Cockroachdb to avoid injection-assisted traversal
When retrieving file metadata from Cockroachdb, use parameterized statements. This prevents attackers from altering query structure to expose or manipulate paths.
import { Database } from '@ioc:Adonis/Addons/Lucid';
export default class DocumentService {
constructor(private db: Database) {}
public async getDocumentMetadata(documentId: string) {
// Use parameterized query; do not interpolate identifiers
const row = await this.db
.from('documents')
.where('id', documentId)
.select('storage_path', 'owner_id')
.limit(1)
.first();
return row;
}
}
3. Avoid dynamic SQL identifiers; use schema-controlled mappings
If you must reference tables or columns dynamically, map user input to a predefined set of values rather than concatenating directly. Cockroachdb identifiers should be validated against an allowlist.
const allowedTableMap: Record = {
reports2023: 'reports_2023',
auditlog: 'audit_log',
};
export default class QueryService {
constructor(private db: Database) {}
public async queryAllowedTable(tableKey: string, documentId: string) {
const tableName = allowedTableMap[tableKey];
if (!tableName) {
throw new Error('Invalid table reference');
}
// Use raw query with identifier quoting via bindings where supported
const results = await this.db
.raw(`SELECT * FROM ?? WHERE id = ?`, [tableName, documentId]);
return results.rows;
}
}
4. Sanitize values retrieved from Cockroachdb before filesystem use
Never trust values stored in the database as safe paths. Re-validate and resolve them before any filesystem operation.
import { resolve, normalize } from 'path';
export async function safeServeFromDb(dbRow: any, baseDir: string) {
const storedPath = dbRow.file_path; // from Cockroachdb
const normalized = normalize(storedPath);
const resolved = resolve(baseDir, normalized);
if (!resolved.startsWith(baseDir)) {
throw new Error('Database path traversal attempt detected');
}
// proceed with file access
}
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 |