spaceforge / backend /app /security /zipsafe.py
2Btainment's picture
Upload folder using huggingface_hub
3806142 verified
Raw History Blame Contribute Delete
1.92 kB
"""Zip-slip protection and safe archive helpers."""
from __future__ import annotations
import zipfile
from pathlib import Path
def is_within_directory(directory: Path, target: Path) -> bool:
try:
directory = directory.resolve()
target = target.resolve()
return str(target).startswith(str(directory) + "/") or target == directory
except OSError:
return False
def safe_extract_zip(zf: zipfile.ZipFile, dest: Path) -> None:
dest = dest.resolve()
dest.mkdir(parents=True, exist_ok=True)
for member in zf.infolist():
name = member.filename
if name.startswith("/") or ".." in Path(name).parts:
raise ValueError(f"Unsafe zip path rejected: {name}")
target = (dest / name).resolve()
if not is_within_directory(dest, target):
raise ValueError(f"Zip-slip rejected: {name}")
if member.is_dir():
target.mkdir(parents=True, exist_ok=True)
else:
target.parent.mkdir(parents=True, exist_ok=True)
with zf.open(member) as src, open(target, "wb") as out:
out.write(src.read())
def safe_add_tree(zf: zipfile.ZipFile, root: Path, arc_prefix: str = "") -> None:
root = root.resolve()
for path in sorted(root.rglob("*")):
if path.is_file():
rel = path.relative_to(root)
arcname = f"{arc_prefix}/{rel}".lstrip("/") if arc_prefix else str(rel)
if ".." in Path(arcname).parts:
raise ValueError(f"Unsafe arcname: {arcname}")
zf.write(path, arcname.replace("\\", "/"))
def validate_output_path(base: Path, candidate: Path) -> Path:
base = base.resolve()
candidate = (base / candidate).resolve() if not candidate.is_absolute() else candidate.resolve()
if not is_within_directory(base, candidate):
raise ValueError("Path traversal blocked")
return candidate