Path Traversal in Restify with Api Keys
Path Traversal in Restify with Api Keys — how this specific combination creates or exposes the vulnerability
Path Traversal occurs when an API endpoint uses user-supplied input to construct filesystem paths without adequate validation or sanitization. In Restify, this often manifests through endpoints that accept a filename or file path parameter and directly concatenate it with a base directory. When Api Keys are used for identification but not enforced for path resolution, the risk pattern changes: authentication is present, but authorization is weak or misapplied.
Consider a Restify handler that serves files from a configured directory. If the handler trusts a query parameter such as file and builds a path like path.join(UPLOAD_DIR, req.query.file), an attacker can provide ../../etc/passwd to traverse outside the intended directory. The presence of an Api Key in a header or query parameter does not prevent this traversal; it only identifies the caller. If the server does not validate that the resolved path remains within the allowed directory, the Api Key becomes an identifier for an unauthorized read, effectively exposing sensitive files while still appearing authenticated to the API.
In the context of middleBrick’s 12 checks, this scenario maps to BOLA/IDOR and Input Validation. The scanner tests unauthenticated and authenticated-style probes (where an Api Key is supplied but path constraints are ignored) to detect whether path traversal is possible. A vulnerable Restify endpoint may return files outside the intended scope, revealing configuration data, source code, or credentials. The detection does not require modifying the Api Key; it focuses on whether the server respects directory boundaries regardless of the provided key.
Real-world analogs include CVE scenarios where directory traversal leads to unauthorized file disclosure. The risk is particularly high when combined with overly permissive file-serving logic, missing path canonicalization, and insufficient boundary checks. middleBrick’s OpenAPI/Swagger analysis helps identify endpoints with file parameters and missing schema constraints, while runtime probing verifies whether supplied paths are confined to the declared safe directory.
Api Keys-Specific Remediation in Restify — concrete code fixes
Remediation centers on strict input validation, canonical path resolution, and ensuring authorization checks are tied to the resolved path, not merely the presence of an Api Key. Below are concrete code examples for a secure Restify setup.
1. Validate and sanitize the file parameter
Reject paths containing .. or absolute segments, and normalize the path to detect traversal attempts.
const restify = require('restify');
const path = require('path');
const server = restify.createServer();
server.use(restify.plugins.bodyParser());
server.get('/files/:filename', (req, res, next) => {
const baseDir = path.resolve('/srv/api-files');
// Allow only URL-safe filenames with a basic whitelist
if (!/^[a-zA-Z0-9._-]+$/.test(req.params.filename)) {
return next(new restify.ForbiddenError('Invalid filename'));
}
const requestedFile = path.normalize(req.params.filename).replace(/^(\.\.[\/\\])+/, '');
const filePath = path.join(baseDir, requestedFile);
// Ensure the resolved path is still inside the base directory
if (!filePath.startsWith(baseDir)) {
return next(new restify.ForbiddenError('Access denied'));
}
// Continue to serve the file securely
// ...
return next();
});
server.listen(8080, () => {
console.log('Server listening on port 8080');
});
2. Enforce Api Keys with role-based access control (RBAC) for file operations
Use the Api Key to determine permissions and ensure that even authenticated calls cannot escape the allowed directory.
const apiKeys = new Map([
['valid-key-123', { scopes: ['files:read'] }],
['admin-key-456', { scopes: ['files:read', 'files:write'] }]
]);
server.use((req, res, next) => {
const key = req.headers['x-api-key'];
if (!key || !apiKeys.has(key)) {
return next(new restify.UnauthorizedError('Invalid Api Key'));
}
req.context = { key, permissions: apiKeys.get(key) };
return next();
});
server.get('/files/:filename', (req, res, next) => {
if (!req.context.permissions.scopes.includes('files:read')) {
return next(new restify.ForbiddenError('Insufficient scope'));
}
const baseDir = path.resolve('/srv/api-files');
const filePath = path.resolve(baseDir, req.params.filename);
if (!filePath.startsWith(baseDir)) {
return next(new restify.ForbiddenError('Path traversal prevented'));
}
// Proceed with authorized, scoped file access
// ...
return next();
});
3. Use strict schema validation for query/path parameters
Define explicit constraints in your routes and validate before processing.
server.get({ path: '/download/*', schema: {
params: {
type: 'object',
properties: {
filename: { type: 'string', pattern: '^[a-zA-Z0-9._-]+$' }
},
required: ['filename'],
additionalProperties: false
}
}}, (req, res, next) => {
const baseDir = path.resolve('/srv/api-files');
const filePath = path.join(baseDir, req.params.filename);
if (!filePath.startsWith(baseDir)) {
return next(new restify.ForbiddenError('Invalid path'));
}
// Serve file logic
return next();
});
These examples emphasize canonicalization, scope-aware authorization, and rejecting unexpected path sequences. middleBrick’s CLI can be used to verify that such controls are effective by scanning the endpoint and confirming that path traversal attempts are detected and reported.
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
Does using an Api Key alone prevent path traversal in Restify?
How can I test my Restify endpoints for path traversal with Api Keys?
middlebrick scan https://api.example.com/files/:filename. The scanner submits crafted paths while Api Keys are supplied, checking whether traversal is possible and reporting findings with remediation guidance.