Compare Vulnerable vs Secure Path Construction
mainWhen handling file system access, avoid direct concatenation or simple joining of user input with a base directory. Use the 'Resolve + Prefix Check' pattern instead.
Vulnerable Pattern (Do Not Use):
Using path.join() with user input allows attackers to use ../ sequences to escape the intended directory.
Secure Pattern:
- Resolve the
safeRootto an absolute path. - Resolve the
targetPathusing thesafeRootanduserInput. - Use
.startsWith()to ensuretargetPathis contained withinsafeRoot(including the path separator).
### Vulnerable (Do Not Use)
```typescript
// VULNERABLE: Direct concatenation allows inputs like "../../etc/passwd"
const targetPath = path.join('/var/www/uploads', userInput);
return fs.readFile(targetPath, 'utf-8');Secure
// SECURE: Resolve + Prefix Check
const safeRoot = path.resolve('/var/www/uploads');
const targetPath = path.resolve(safeRoot, userInput);
if (!targetPath.startsWith(safeRoot + path.sep)) {
throw new Error('Path traversal detected');
}
return fs.readFile(targetPath, 'utf-8');