MediumPro challengeJavaScriptTypeScript
Sanitize File Path
BackendSecurityFiles
The function below builds a file path by concatenating a base directory with user-supplied input.
The bug: an attacker can pass "../../../etc/passwd" as the filename and read any file on the server — a classic path traversal (directory traversal) attack.
Your task: fix solve(basePath, userInput) so that:
- Valid filenames within the base directory return the full path.
- Any input that would escape
basePathreturnsnull. - Use string operations only (no
require('path')available in this sandbox).
solve('/uploads', 'photo.jpg') // → '/uploads/photo.jpg'
solve('/uploads', 'sub/image.png') // → '/uploads/sub/image.png'
solve('/uploads', '../etc/passwd') // → null
solve('/uploads', '../../secret.key') // → nullSample tests
Test #1Subdirectory — allowed
Input: ["/uploads","sub/image.png"]
Output: "/uploads/sub/image.png"
Test #2Normal file — allowed
Input: ["/uploads","photo.jpg"]
Output: "/uploads/photo.jpg"
Test #3One level up — blocked
Input: ["/uploads","../etc/passwd"]
Output: null
Test #4Two levels up — blocked
Input: ["/uploads","../../secret.key"]
Output: null