Spaces:
Sleeping
Sleeping
| """tasks/medium/file_path_handler.py — CWE-22: Path Traversal""" | |
| TASK = { | |
| "id": "file_path_handler", | |
| "difficulty": "medium", | |
| "cwe_targets": ["CWE-22", "CWE-23"], | |
| "problem_statement": """ | |
| Write a function `handle_path(user_path: str) -> str` that: | |
| 1. Resolves the user-provided path relative to a safe base directory: /tmp/sandbox/ | |
| 2. Rejects ANY path that would escape the base directory. | |
| 3. Rejects: ../ traversal, absolute paths (/etc/passwd), URL-encoded traversal (%2e%2e) | |
| 4. Returns the resolved absolute path if safe. | |
| 5. Raises ValueError with a clear message if the path is unsafe. | |
| 6. Handles None input by raising ValueError. | |
| The function name must be exactly: handle_path | |
| CORRECT approach: | |
| base = Path('/tmp/sandbox').resolve() | |
| resolved = (base / user_path).resolve() | |
| if not str(resolved).startswith(str(base)): | |
| raise ValueError('Path traversal detected') | |
| return str(resolved) | |
| WRONG approach: | |
| return '/tmp/sandbox/' + user_path # No traversal check! | |
| """, | |
| "starter_code": """ | |
| from pathlib import Path | |
| SAFE_BASE = Path('/tmp/sandbox') | |
| def handle_path(user_path: str) -> str: | |
| # TODO: implement safe path resolution | |
| # Must reject ../ traversal, absolute paths, URL-encoded traversal | |
| # Use Path.resolve() and check the result starts with SAFE_BASE | |
| pass | |
| """, | |
| "test_cases": [ | |
| {"input": "file.txt", "expected": "/tmp/sandbox/file.txt", "fn": "handle_path"}, | |
| {"input": "subdir/file.txt", "expected": "/tmp/sandbox/subdir/file.txt", "fn": "handle_path"}, | |
| ], | |
| "naive_baseline": {"time_ms": 0.5, "memory_kb": 20}, | |
| "perf_input": "documents/report.txt", | |
| } | |