Can code inside a `vm` sandbox access the filesystem? Explain why or why not, and how you might safely provide such functionality.
Node.js interview question for Advanced practice.
Answer
By default, code inside a vm sandbox created with vm.runInNewContext() cannot access the filesystem. This is because the sandbox has its own isolated global scope and does not have access to Node.js built-in modules like fs. However, it is a common but very dangerous pattern for developers to explicitly pass the fs module into the sandbox, which would grant full filesystem access to the untrusted code. To safely provide filesystem functionality, you should not pass the entire fs module. Instead, you should create wrapper functions that expose only the specific, limited functionality that is required. These wrappers must perform strict validation on all inputs. Example of providing safe file reading: javascript const vm = require('vm'); const fs = require('fs'); const path = require('path'); const untrustedCode = readFile('userdata.txt').then(logger);; const SANDBOXDIR = '/path/to/safe/user/files'; const sandbox = { Promise, logger: console.log, readFile: (filePath) = { // 1. Sanitize and validate the file path const resolvedPath = path.join(SANDBOXDIR, filePath); // 2. Security Check: Ensure the path is still within the intended directory if (!resolvedPath.startsWith(SANDBOXDIR)) { return Promise.reject(new Error('Access denied.')); } // 3. Perform the controlled action return fs.promises.readFile(resolvedPath, 'utf-8'); } } vm.runInNewContext(untrustedCode, sandbox); This approach ensures the untrusted code can only read files from a specific, safe directory and cannot use path traversal (../) to escape it.
Explanation
The principle of least privilege is a core security concept that applies directly to vm sandboxes: only grant the permissions and APIs that are absolutely necessary for the code to function.