"""Resumable file uploads via the tus 1.0.0 protocol (self-contained core). Streams chunks straight to disk (memory stays flat regardless of file size), survives interruption and resumes from the server-known offset, isolates each upload to its authenticated owner, and on completion moves the finished file into the user's work dir — the same place the legacy /api/upload writes — so the rest of the app keeps working unchanged. Wired up from main.py via register_tus(); kept dependency-free (deps are passed in) to avoid import cycles and stay unit-testable. """ import base64 import json import os import re import secrets import shutil import time from pathlib import Path from fastapi import HTTPException, Request, Response from starlette.requests import ClientDisconnect from archive_host import extract_archive_async, is_archive_file TUS_VERSION = "1.0.0" TUS_EXTENSIONS = "creation,termination" _ID_RE = re.compile(r"^[A-Za-z0-9_-]{8,64}$") _DISK_MARGIN = 1024 * 1024 * 1024 # refuse if it would leave < 1 GB free _STALE_AGE = 24 * 3600 # sweep abandoned partial uploads untouched for this long _PENDING_IDLE = 600 # upload untouched this long no longer counts toward a dialog's quota def _sweep_stale(staging: Path): """Drop partial uploads (data + sidecar) idle past _STALE_AGE. An in-flight upload keeps writing, so its mtime stays fresh and it is never swept.""" cutoff = time.time() - _STALE_AGE try: entries = list(staging.iterdir()) except OSError: return for p in entries: try: if p.stat().st_mtime < cutoff: p.unlink() except OSError: pass def _parse_metadata(header: str) -> dict: """tus Upload-Metadata: comma-separated `key ` pairs.""" out = {} for pair in (header or "").split(","): pair = pair.strip() if not pair: continue parts = pair.split(" ", 1) if len(parts) == 2: try: out[parts[0]] = base64.b64decode(parts[1]).decode("utf-8") except Exception: out[parts[0]] = "" else: out[parts[0]] = "" return out def _safe_tab(tab_id: str) -> str: """Block path traversal via attacker-controlled tab_id metadata.""" tab_id = (tab_id or "").strip() or "default" tab_id = re.sub(r"[^A-Za-z0-9_.-]", "_", tab_id) return tab_id if tab_id.strip(".") else "default" def register_tus(app, *, get_user, get_work_dir, is_allowed_file, log_action, save_message, max_size, staging_root, allowed_hint, check_upload=None): staging = Path(staging_root) staging.mkdir(parents=True, exist_ok=True) def _data(uid): return staging / uid def _meta(uid): return staging / f"{uid}.json" def _headers(extra=None): h = {"Tus-Resumable": TUS_VERSION} if extra: h.update(extra) return h def _load(uid: str, user: str) -> dict: # Unknown id, bad id, or someone else's upload all look the same: 404. if not _ID_RE.match(uid) or not _meta(uid).exists(): raise HTTPException(404, "Upload not found") meta = json.loads(_meta(uid).read_text("utf-8")) if meta.get("owner") != user: raise HTTPException(404, "Upload not found") return meta def _pending_split(user, tab): """(обычные, архивы) — заявленные размеры идущих загрузок человека в диалог. Брошенная лежит до уборки сутки — её не считаем: в идущую пишут непрерывно, её данные свежие.""" regular = archive = 0 fresh = time.time() - _PENDING_IDLE for mp in staging.glob("*.json"): try: if _data(mp.stem).stat().st_mtime < fresh: continue m = json.loads(mp.read_text("utf-8")) except (OSError, ValueError): continue if m.get("owner") == user and m.get("tab_id") == tab: if is_archive_file(m.get("filename") or ""): archive += int(m.get("length") or 0) else: regular += int(m.get("length") or 0) return regular, archive def _pending_count(user, tab): """Сколько загрузок человека в диалог ещё идёт — для предела «файлов за раз».""" n = 0 fresh = time.time() - _PENDING_IDLE for mp in staging.glob("*.json"): try: if _data(mp.stem).stat().st_mtime < fresh: continue m = json.loads(mp.read_text("utf-8")) except (OSError, ValueError): continue if m.get("owner") == user and m.get("tab_id") == tab: n += 1 return n async def options_collection(request: Request): return Response(status_code=204, headers=_headers({ "Tus-Version": TUS_VERSION, "Tus-Extension": TUS_EXTENSIONS, "Tus-Max-Size": str(max_size), })) async def create(request: Request): user = get_user(request) _sweep_stale(staging) raw_len = request.headers.get("upload-length") if raw_len is None or not raw_len.isdigit() or int(raw_len) <= 0: raise HTTPException(400, "Upload-Length required") length = int(raw_len) ip = request.client.host if request.client else None if length > max_size: # Логируем отказ: /api/tus в middleware не пишется (_SKIP_PREFIXES), # иначе оператор не узнает, ЧТО и почему юзер не смог загрузить. fn_hint = Path(_parse_metadata(request.headers.get("upload-metadata", "")).get("filename", "")).name log_action(user, "tus_reject", "POST", "/api/tus", f"{fn_hint or '?'}: too-large {length}B > {max_size}B", ip, 413) raise HTTPException(413, f"File too large (max {max_size // (1024 * 1024)}MB)") if check_upload is not None: # Пределы человека (файл, сумма в диалоге, «только просмотр») — до передачи байтов. _m = _parse_metadata(request.headers.get("upload-metadata", "")) _name = Path(_m.get("filename", "")).name or "?" try: _tab = _safe_tab(_m.get("tab_id")) _reg, _arc = _pending_split(user, _tab) check_upload(user, _tab, _name, length, pending_regular=_reg, pending_archive=_arc, pending_files=_pending_count(user, _tab)) except HTTPException as refusal: log_action(user, "tus_reject", "POST", "/api/tus", f"{_name}: {refusal.detail}", ip, refusal.status_code) raise if shutil.disk_usage(str(staging)).free < length + _DISK_MARGIN: raise HTTPException(507, "Insufficient storage on server") meta = _parse_metadata(request.headers.get("upload-metadata", "")) filename = Path(meta.get("filename", "")).name if not filename or filename.startswith("."): raise HTTPException(400, "Invalid or missing filename metadata") if not is_allowed_file(filename): log_action(user, "tus_reject", "POST", "/api/tus", f"{filename}: type not allowed", ip, 400) raise HTTPException(400, f"File type not allowed. Allowed: {allowed_hint}") uid = secrets.token_urlsafe(16) _data(uid).write_bytes(b"") _meta(uid).write_text(json.dumps({ "owner": user, "filename": filename, "tab_id": _safe_tab(meta.get("tab_id")), "length": length, }), "utf-8") return Response(status_code=201, headers=_headers({"Location": f"/api/tus/{uid}"})) async def head(request: Request, uid: str): user = get_user(request) meta = _load(uid, user) return Response(status_code=200, headers=_headers({ "Upload-Offset": str(_data(uid).stat().st_size), "Upload-Length": str(meta["length"]), "Cache-Control": "no-store", })) async def patch(request: Request, uid: str): user = get_user(request) meta = _load(uid, user) if request.headers.get("content-type") != "application/offset+octet-stream": raise HTTPException(415, "Content-Type must be application/offset+octet-stream") raw_off = request.headers.get("upload-offset") if raw_off is None or not raw_off.isdigit(): raise HTTPException(400, "Upload-Offset required") dp = _data(uid) offset = dp.stat().st_size if int(raw_off) != offset: raise HTTPException(409, "Offset conflict") length = meta["length"] try: with open(dp, "ab") as f: async for chunk in request.stream(): if not chunk: continue if offset + len(chunk) > length: raise HTTPException(400, "Upload exceeds declared length") f.write(chunk) offset += len(chunk) f.flush() os.fsync(f.fileno()) except ClientDisconnect: # Normal interruption: bytes flushed so far persist; next HEAD # reports the real on-disk offset and the client resumes from there. return Response(status_code=204, headers=_headers({ "Upload-Offset": str(dp.stat().st_size), })) if offset >= length: _finalize(uid, meta, request) return Response(status_code=204, headers=_headers({"Upload-Offset": str(offset)})) def _finalize(uid: str, meta: dict, request: Request): dest = Path(get_work_dir(meta["owner"], meta["tab_id"])) / meta["filename"] shutil.move(str(_data(uid)), str(dest)) _meta(uid).unlink(missing_ok=True) size = dest.stat().st_size try: # смета человека: сторож выгрузки её не запирает import gge_guard gge_guard.note_human_file(meta["owner"], meta["tab_id"], dest, "tus") except Exception: # noqa: BLE001 — отметка не может ломать загрузку pass save_message(meta["owner"], meta["tab_id"], "system", f"Загружен файл: {meta['filename']} ({size} байт)") # Архивы/тома многотомников распаковываем на хосте (unar) — у агента нет # питон-распаковщика rar, а тома многотомника поодиночке вообще не архивы. extract_archive_async(dest, dest.parent, meta["owner"], meta["tab_id"]) ip = request.client.host if request.client else None log_action(meta["owner"], "upload", "POST", "/api/tus", f"{meta['filename']} ({size}B) tab={meta['tab_id']}", ip, 200) async def terminate(request: Request, uid: str): user = get_user(request) _load(uid, user) # owner check _data(uid).unlink(missing_ok=True) _meta(uid).unlink(missing_ok=True) return Response(status_code=204, headers=_headers()) app.add_api_route("/api/tus", options_collection, methods=["OPTIONS"]) app.add_api_route("/api/tus", create, methods=["POST"]) app.add_api_route("/api/tus/{uid}", head, methods=["HEAD"]) app.add_api_route("/api/tus/{uid}", patch, methods=["PATCH"]) app.add_api_route("/api/tus/{uid}", terminate, methods=["DELETE"])