Path Traversal in Restify with Cockroachdb
Path Traversal in Restify with Cockroachdb — how this specific combination creates or exposes the vulnerability
Path Traversal occurs when an API endpoint uses user-supplied input to construct file system paths or database references without proper validation, allowing an attacker to escape the intended directory or namespace. In a Restify service that uses CockroachDB, this typically manifests through endpoints that accept identifiers (e.g., fileId or tenantId) and directly interpolate them into SQL queries or filesystem paths. Because CockroachDB is a distributed SQL database, path-like inputs can inadvertently affect schema or table resolution when dynamic identifiers are concatenated into queries. If input validation is weak, an attacker can supply sequences such as ../../../etc/passwd or SQL-encoded traversal patterns to access unauthorized data or force the database to resolve unexpected object names.
Restify does not inherently guard against logical path traversal; it relies on the application to validate and sanitize inputs before using them in database operations. When combined with CockroachDB, a common vulnerable pattern is building SQL strings via concatenation, for example: SELECT * FROM files WHERE id = '${userInput}'. An input like 1; DROP TABLE users -- or 1' OR '1'='1 can lead to injection, while path-like inputs may exploit schema or namespace traversal if the application uses constructs like SHOW TABLES or dynamic database/table names. Even without direct filesystem access, a compromised query can expose rows across tenants or tables, effectively a logical path traversal in the data plane.
The LLM/AI Security checks included in middleBrick are designed to detect system prompt leakage and active prompt injection, which are conceptually similar to traversal attacks in that they attempt to escape intended boundaries. Although middleBrick does not fix vulnerabilities, its findings include prioritized remediation guidance mapped to frameworks such as OWASP API Top 10, helping you understand how Path Traversal fits into broader API risk. With the free tier, you can run up to 3 scans per month to identify such issues early, while the Pro plan provides continuous monitoring to detect regressions that could reintroduce traversal risks in Restify endpoints backed by CockroachDB.
When scanning a Restify API that uses CockroachDB, middleBrick performs OpenAPI/Swagger spec analysis (supporting 2.0, 3.0, and 3.1) with full $ref resolution, cross-referencing spec definitions with runtime findings. This helps identify endpoints that accept path-like parameters without sufficient constraints. The scanner runs 12 security checks in parallel, including Input Validation and Property Authorization, to highlight whether user-controlled data reaches database queries unchecked. Results appear in the Web Dashboard, where you can track scores over time, and in reports generated via the CLI tool middlebrick scan <url>, which outputs JSON or text for integration into scripts.
Cockroachdb-Specific Remediation in Restify — concrete code fixes
To remediate Path Traversal in Restify when interacting with CockroachDB, enforce strict input validation, use parameterized queries, and avoid dynamic SQL construction. The goal is to ensure that user-supplied identifiers cannot alter the intended structure of SQL statements or escape logical boundaries. Below are concrete examples demonstrating secure patterns.
1. Use parameterized queries with placeholders
Never concatenate user input into SQL strings. Instead, use prepared statements with placeholders. This prevents both SQL injection and unintended logical traversal across schemas or tables.
const express = require('express');
const { Pool } = require('cockroachdb');
const app = express();
const pool = new Pool({
connectionString: 'postgresql://user:password@host:26257/dbname?sslmode=require'
});
app.get('/files/:fileId', async (req, res) => {
const fileId = req.params.fileId;
// Validate fileId format (e.g., UUID or integer)
if (!/^[0-9a-fA-F-]{36}$/.test(fileId)) {
return res.status(400).send({ error: 'Invalid file ID format' });
}
try {
const result = await pool.query('SELECT name, content FROM files WHERE id = $1', [fileId]);
if (result.rows.length === 0) {
return res.status(404).send({ error: 'File not found' });
}
res.send(result.rows[0]);
} catch (err) {
res.status(500).send({ error: 'Database error' });
}
});
app.listen(3000, () => console.log('Server running on port 3000'));
2. Restrict schema object names with allowlists
If your application dynamically references schemas or tables, validate identifiers against a strict allowlist rather than a blocklist. This approach mitigates traversal attempts that exploit reserved names or multi-tenant patterns.
const validTables = ['users', 'files', 'logs'];
async function getTableData(tableName, id) {
if (!validTables.includes(tableName)) {
throw new Error('Invalid table name');
}
const result = await pool.query(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
return result.rows;
}
3. Enforce tenant isolation using parameterized schema or row-level security
In multi-tenant setups using CockroachDB, ensure that queries incorporate tenant identifiers as parameters and not as string fragments. Combine this with Row-Level Security (RLS) where possible to enforce isolation at the database level.
app.get('/tenant/:tenantId/records/:recordId', async (req, res) => {
const tenantId = req.params.tenantId;
const recordId = req.params.recordId;
if (!/^[0-9]+$/.test(tenantId) || !/^[0-9]+$/.test(recordId)) {
return res.status(400).send({ error: 'Invalid parameter format' });
}
const result = await pool.query(
'SELECT data FROM records WHERE tenant_id = $1 AND id = $2',
[tenantId, recordId]
);
if (result.rows.length === 0) {
return res.status(404).send({ error: 'Record not found' });
}
res.send(result.rows[0]);
});
Integrate these practices into your CI/CD pipeline by adding the middleBrick GitHub Action to fail builds if security scores drop below your threshold. This ensures that regressions introducing Path Traversal risks in Restify endpoints are caught before deployment. For ongoing protection, the Pro plan provides continuous monitoring and alerts, while the MCP Server lets you scan APIs directly from your AI coding assistant within the development environment.
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 |
Frequently Asked Questions
How can I test if my Restify endpoint with CockroachDB is vulnerable to Path Traversal?
middlebrick scan <your-api-url> from the terminal. The CLI outputs a JSON report highlighting input validation and authorization findings, including whether user input reaches database queries unchecked.