"""Client L1 Earth hot-update manifest and bundle hosting endpoints.""" from __future__ import annotations import hashlib import hmac import io import json import os import re import tarfile from datetime import UTC, datetime from pathlib import Path from typing import Any from uuid import uuid4 from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile, status from fastapi.responses import FileResponse, JSONResponse from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from sqlalchemy.ext.asyncio import AsyncSession from app.core.config import settings from app.core.logging import get_logger from app.core.security import get_current_user from app.db.session import get_db router = APIRouter() logger = get_logger(__name__, service="api") bearer_optional = HTTPBearer(auto_error=False) DEFAULT_CLIENT_UPDATES_DIR = Path(__file__).resolve().parents[3] / "data" / "client-updates" MAX_HOTFIX_BUNDLE_BYTES = 32 * 1024 * 1024 MAX_HOTFIX_FILES = 2000 MAX_HOTFIX_UNCOMPRESSED_BYTES = 64 * 1024 * 1024 SEMVER_PATTERN = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$") SAFE_BUNDLE_FILENAME_PATTERN = re.compile(r"^planet-earth-bundle-[0-9A-Za-z._-]+\.tar\.gz$") def get_client_updates_dir() -> Path: configured = str(settings.CLIENT_UPDATES_DIR or "").strip() if configured: return Path(configured) return DEFAULT_CLIENT_UPDATES_DIR def _manifest_path(updates_dir: Path) -> Path: return updates_dir / "manifest.json" def _atomic_write_bytes(target: Path, content: bytes) -> None: target.parent.mkdir(parents=True, exist_ok=True) tmp_path = target.with_name(f".{target.name}.{os.getpid()}.{uuid4().hex}.tmp") try: tmp_path.write_bytes(content) os.replace(tmp_path, target) except Exception: tmp_path.unlink(missing_ok=True) raise def _validate_hotfix_tar_gz(content: bytes) -> dict[str, int]: if not content: raise HTTPException(status_code=400, detail="Hotfix bundle archive is empty") file_count = 0 total_size = 0 has_index_html = False try: with tarfile.open(fileobj=io.BytesIO(content), mode="r:gz") as archive: for member in archive.getmembers(): raw_name = member.name or "" if "\\" in raw_name or "\0" in raw_name: raise HTTPException(status_code=400, detail=f"Unsafe archive entry path: {raw_name!r}") if member.issym() or member.islnk() or member.isdev() or member.ischr() or member.isblk() or member.isfifo(): raise HTTPException(status_code=400, detail=f"Unsupported special archive entry: {raw_name!r}") stripped = raw_name.lstrip("./") if raw_name.startswith("./") else raw_name while stripped.startswith("./"): stripped = stripped[2:] stripped = stripped.rstrip("/") if raw_name.startswith("/"): raise HTTPException(status_code=400, detail=f"Absolute archive entry path is forbidden: {raw_name!r}") if stripped in ("", "."): if member.isdir(): continue raise HTTPException(status_code=400, detail="Empty archive file path") segments = stripped.split("/") if any(seg in ("", ".", "..") for seg in segments): raise HTTPException(status_code=400, detail=f"Path traversal forbidden in archive: {raw_name!r}") if member.isdir(): continue if not member.isreg(): raise HTTPException(status_code=400, detail=f"Unsupported archive entry type: {raw_name!r}") file_count += 1 if file_count > MAX_HOTFIX_FILES: raise HTTPException(status_code=400, detail="Archive exceeds maximum allowed file count") total_size += max(0, int(member.size)) if total_size > MAX_HOTFIX_UNCOMPRESSED_BYTES: raise HTTPException(status_code=400, detail="Archive exceeds maximum uncompressed size limit") if stripped == "index.html": has_index_html = True except HTTPException: raise except (tarfile.TarError, EOFError, OSError, ValueError) as exc: raise HTTPException(status_code=400, detail=f"Invalid gzip tar archive: {exc}") from exc if not has_index_html: raise HTTPException(status_code=400, detail="Hotfix bundle must include index.html at root") return {"filesCount": file_count, "uncompressedBytes": total_size} def _default_manifest() -> dict[str, Any]: return { "shell": { "version": settings.VERSION, "minRequired": settings.CLIENT_MIN_SHELL_VERSION, "downloadUrl": settings.CLIENT_RELEASE_PAGE_URL, "releaseNotes": "", }, "bundle": None, } def _read_manifest(updates_dir: Path) -> dict[str, Any]: manifest_file = _manifest_path(updates_dir) if not manifest_file.is_file(): return _default_manifest() try: payload = json.loads(manifest_file.read_text(encoding="utf-8")) if not isinstance(payload, dict): return _default_manifest() return payload except (OSError, json.JSONDecodeError): return _default_manifest() async def _require_update_publisher( request: Request, credentials: HTTPAuthorizationCredentials | None = Depends(bearer_optional), db: AsyncSession = Depends(get_db), ) -> str: publish_token = request.headers.get("X-Client-Update-Token") if publish_token is not None: expected = str(settings.CLIENT_UPDATE_PUBLISH_TOKEN or "").strip() if not expected or not hmac.compare_digest(publish_token.strip(), expected): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid client update publish token", ) return "ci-token" if credentials is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated", ) user = await get_current_user(credentials=credentials, db=db) if getattr(user, "role", None) != "admin": raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Admin privileges required", ) return f"admin:{user.username}" def _validate_semver(value: str, field_name: str) -> str: cleaned = str(value or "").strip().lstrip("vV") if not SEMVER_PATTERN.match(cleaned): raise HTTPException( status_code=400, detail=f"Invalid semantic version for {field_name}: {value!r}", ) return cleaned @router.get("/update-manifest") async def get_client_update_manifest( platform: str = "", arch: str = "", shell: str = "", bundle: str = "", ): updates_dir = get_client_updates_dir() manifest = _read_manifest(updates_dir) bundle_info = manifest.get("bundle") if isinstance(bundle_info, dict): filename = Path(str(bundle_info.get("url") or "")).name if not SAFE_BUNDLE_FILENAME_PATTERN.match(filename) or not (updates_dir / filename).is_file(): manifest = {**manifest, "bundle": None} logger.debug_event( "Served client update manifest", event="client_updates.manifest.read", context={ "platform": platform or None, "arch": arch or None, "shell": shell or None, "bundle": bundle or None, "has_bundle": bool(manifest.get("bundle")), }, ) return JSONResponse(content=manifest, headers={"Cache-Control": "no-store"}) @router.get("/updates/files/{filename}") async def download_client_hotfix_bundle(filename: str): if not SAFE_BUNDLE_FILENAME_PATTERN.match(filename): raise HTTPException(status_code=400, detail="Invalid client hotfix bundle filename") updates_dir = get_client_updates_dir().resolve() target = (updates_dir / filename).resolve() if target.parent != updates_dir or not target.is_file(): raise HTTPException(status_code=404, detail="Client hotfix bundle not found") return FileResponse( path=target, media_type="application/gzip", filename=filename, headers={"Cache-Control": "public, max-age=31536000, immutable"}, ) @router.post("/updates/bundle") async def publish_client_hotfix_bundle( file: UploadFile = File(...), version: str = Form(...), min_shell_version: str = Form(""), release_notes: str = Form(""), shell_version: str = Form(""), shell_min_required: str = Form(""), shell_download_url: str = Form(""), publisher: str = Depends(_require_update_publisher), ): normalized_version = _validate_semver(version, "version") normalized_min_shell = _validate_semver( min_shell_version or settings.CLIENT_MIN_SHELL_VERSION or normalized_version, "min_shell_version", ) content = await file.read(MAX_HOTFIX_BUNDLE_BYTES + 1) if len(content) > MAX_HOTFIX_BUNDLE_BYTES: raise HTTPException(status_code=400, detail="Hotfix bundle exceeds 32 MiB limit") archive_meta = _validate_hotfix_tar_gz(content) sha256_hex = hashlib.sha256(content).hexdigest() bundle_filename = f"planet-earth-bundle-{normalized_version}.tar.gz" updates_dir = get_client_updates_dir() _atomic_write_bytes(updates_dir / bundle_filename, content) existing_manifest = _read_manifest(updates_dir) existing_shell = existing_manifest.get("shell") if isinstance(existing_manifest.get("shell"), dict) else {} resolved_shell_version = ( _validate_semver(shell_version, "shell_version") if str(shell_version or "").strip() else str(existing_shell.get("version") or settings.VERSION) ) resolved_shell_min = ( _validate_semver(shell_min_required, "shell_min_required") if str(shell_min_required or "").strip() else str(existing_shell.get("minRequired") or settings.CLIENT_MIN_SHELL_VERSION) ) resolved_shell_url = str(shell_download_url or "").strip() or str( existing_shell.get("downloadUrl") or settings.CLIENT_RELEASE_PAGE_URL ) if not resolved_shell_url.startswith(("https://", "http://")): raise HTTPException(status_code=400, detail="shell_download_url must start with http:// or https://") cleaned_notes = str(release_notes or "").strip()[:4000] manifest: dict[str, Any] = { "shell": { "version": resolved_shell_version, "minRequired": resolved_shell_min, "downloadUrl": resolved_shell_url, "releaseNotes": cleaned_notes or str(existing_shell.get("releaseNotes") or ""), }, "bundle": { "version": normalized_version, "minShellVersion": normalized_min_shell, "url": f"/api/v1/client/updates/files/{bundle_filename}", "sha256": sha256_hex, "size": len(content), "releaseNotes": cleaned_notes, "publishedAt": datetime.now(UTC).isoformat(), **archive_meta, }, } _atomic_write_bytes( _manifest_path(updates_dir), (json.dumps(manifest, ensure_ascii=False, indent=2) + "\n").encode("utf-8"), ) logger.info_event( "Published client L1 hotfix bundle", event="client_updates.bundle_published", context={ "publisher": publisher, "version": normalized_version, "min_shell_version": normalized_min_shell, "bytes": len(content), "sha256": sha256_hex, "files_count": archive_meta["filesCount"], }, ) return {"status": "published", "manifest": manifest}