File size: 554 Bytes
a097d38
 
 
 
 
051911c
a097d38
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import re
from pathlib import Path

SAFE_FILENAME_REGEX = r"^[A-Za-z0-9_\-]+\.(pkl|json)$"

def safe_path(filename: str, base_dir: str = "models_info") -> str:
    if not re.match(SAFE_FILENAME_REGEX, filename):
        raise ValueError(f"Invalid file name: {filename}")

    base = Path(base_dir).resolve()
    full_path = (base / filename).resolve()

    # Prevent directory traversal (../../../ etc)
    if not str(full_path).startswith(str(base)):
        raise ValueError("Directory traversal detected!")

    return str(full_path)