In this lesson, you will learn how to prevent "path traversal" attacks by enforcing a strict boundary around the files your application is allowed to access.
Understanding the Sandbox Boundary
When your application accepts file paths from external input (like a web request), a malicious user might try to access sensitive system files by passing paths like ../../etc/passwd. Even if you think your code is safe, failing to restrict the root directory allows an attacker to "break out" of your intended folder.
To secure your file access layer, you must treat your target directory as a sandboxed root. Before performing any read or write operation, you must verify that the requested path, when resolved to an absolute path, still begins with the path of your designated sandbox folder.
Implementing the Path Check
We use the path module to normalize inputs and resolve them into absolute paths. By comparing the resolved path against our "trusted root," we can reject any request that attempts to escape.
const path = require('path');
const fs = require('fs');
const SANDBOX_ROOT = path.resolve('./public_data');
function getSafeFilePath(userInput) {
// 1. Resolve the requested path relative to the sandbox
const requestedPath = path.resolve(SANDBOX_ROOT, userInput);
// 2. Ensure the resolved path starts with the SANDBOX_ROOT prefix
if (!requestedPath.startsWith(SANDBOX_ROOT)) {
throw new Error('Security Violation: Unauthorized access attempt.');
}
return requestedPath;
}
// Usage
const userRequested = 'user1/reports/summary.txt';
const safePath = getSafeFilePath(userRequested);
fs.readFile(safePath, 'utf8', (err, data) => { /* ... */ });
Why this works
By calling path.resolve(), we eliminate .. segments and symbolic links that attackers use to trick the file system. Once normalized, if the string doesn't start with your SANDBOX_ROOT, you know for certain that the file resides outside your permitted directory. This logic acts as a jail, ensuring your file operations stay confined to your intended data layer, regardless of what the user input provides.
Key Takeaway: Never trust user-provided paths; always resolve them to an absolute path and verify they start with your intended sandbox directory prefix before performing any file operations.