Files
smeta-web/tus_upload.py
T
anorandClaude Opus 4.8 704e6a31e7 fix: многотомные архивы (WinRAR/7-Zip split) — загрузка + сборка на хосте
Юзер грузил !_ТЗ ДЛЯ.z01..z06 + .zip (исходник >3 ГБ побит WinRAR на тома
700 МБ). Каждый том .z01… давал 400 «тип не поддерживается»: расширения томов
не было в allow-list, а по одному они и не архивы. Собрать набор было нечем.

- is_allowed_file принимает тома .z01…/.001…/.r00… (единый is_split_volume
  в archive_host — источник правды для allow-list и распаковки).
- archive_host: extract_archive_async наводит unar на entry-том (unar сам
  пересобирает набор из соседних томов — проверено на хосте: zip-split и
  7z-split). Триггер на КАЖДЫЙ финалайз, сборка ровно раз (done-маркер+lock),
  устойчиво к любому порядку прихода томов.
- tus create: отказы (413/400) теперь пишутся в audit_log с именем файла —
  /api/tus в middleware не логируется, оператор не видел, ЧТО отклонено.
- UI-подсказки при 400/413 упоминают многотомники; APP_VERSION 2026-07-16b.

Тесты: tests/test_split_archive.py (allow-list, выбор entry-тома, сборка
ровно один раз при любом порядке); реальная распаковка через unar проверена
на хосте end-to-end (sha совпал).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-16 17:28:32 +10:00

209 lines
8.8 KiB
Python

"""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
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
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 <base64value>` 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):
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
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 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
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"])