"""Local, non-web-served storage for published Agent release zips. Binaries never live in PostgreSQL — only their metadata (AgentRelease rows) do. The storage root is a plain directory outside `central/static`, so it is never directly reachable by a URL; every download goes through the authenticated or token-gated routes in agent_distribution.py. """ from pathlib import Path from . import config _SAFE_COMPONENT = __import__("re").compile(r"^[A-Za-z0-9._-]+$") def storage_root() -> Path: root = Path(config.settings.agent_release_storage_path) root.mkdir(parents=True, exist_ok=True) return root def release_filename(version: str, platform: str, architecture: str) -> str: return f"GTIFiscalAgent-{version}-{platform}-{architecture}.zip" def safe_path_for(storage_path: str) -> Path: """Resolve a release's storage_path against the root, refusing anything that could escape it (path traversal). storage_path is DB-controlled (never derived from an HTTP request), but this stays fail-closed anyway.""" if not storage_path or not _SAFE_COMPONENT.match(storage_path): raise ValueError(f"unsafe release storage_path: {storage_path!r}") root = storage_root().resolve() candidate = (root / storage_path).resolve() if candidate.parent != root: raise ValueError(f"release storage_path escapes storage root: {storage_path!r}") return candidate