MediumPro challengePython

Sanitize File Path

PythonSecurityFiles

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 attack.

Your task: fix solve(base_path, user_input) so that:

  • Valid filenames within the base directory return the full, normalized path.
  • Any input that would resolve outside base_path returns None.
solve('/uploads', 'photo.jpg')         # → '/uploads/photo.jpg'
solve('/uploads', 'sub/image.png')     # → '/uploads/sub/image.png'
solve('/uploads', '../etc/passwd')     # → None
solve('/uploads', '../../secret.key')  # → None

Sample tests

Test #1Normal file — allowed
Input: ["/uploads","photo.jpg"]
Output: "/uploads/photo.jpg"
Test #2One level up — blocked
Input: ["/uploads","../etc/passwd"]
Output: null
Test #3Two levels up — blocked
Input: ["/uploads","../../secret.key"]
Output: null
Test #4Subdirectory — allowed
Input: ["/uploads","sub/image.png"]
Output: "/uploads/sub/image.png"