Fix the path check in a file export endpoint
Your task
Your app has an endpoint that serves a user's exported report by file name. The first version joined the name straight onto the reports directory, so ../../etc/passwd served a system file. The fix has to turn the name into a path that stays inside the directory, or reject it.
An assistant wrote resolve_export_path(reports_dir, requested_name). It is in the editor. It has a bug. Find it and fix it.
Input and output:
reports_dir: the reports directory as an absolute path, such as/srv/app/reports. It may end with/and has no.or..parts.requested_name: the file name the user sent.- Return the resolved absolute path, or
""to reject the request.
Rules the tests check:
- Reject an empty name and a name that starts with
/. - Split both paths on
/. Empty parts and.parts are skipped. - Walk the name's parts from inside the reports directory. A normal part goes one level down.
..goes one level up. - Reject the request as soon as a
..would climb above the reports directory, even if later parts would come back inside it. - Reject a name that resolves to the reports directory itself.
- Otherwise return
/, then the directory's parts and the remaining name parts joined with/.
Examples
resolve_export_path(reports_dir: str, requested_name: str) -> strExample 1
Input
resolve_export_path("/srv/app/reports", "sales.csv")Output
"/srv/app/reports/sales.csv"Example 2
Input
resolve_export_path("/srv/app/reports", "../../etc/passwd")Output
""Example 3
Input
resolve_export_path("/srv/app/reports", "2026/q1/report.csv")Output
"/srv/app/reports/2026/q1/report.csv"