Files
smeta-web/tus_upload.py
T
anorandClaude Opus 4.8 7074f0f5dc feat: распаковка .rar/.7z на хосте (unar) при загрузке
Инцидент 2026-07-15: юзер залил 09.0200.rar, экстрактор умел только zip → «покажи
содержимое» не срабатывало. Для rar питон-распаковщика нет (проприетарный формат),
поэтому: unar на хосте + archive_host.py распаковывает rar/7z в work_dir/<stem>_extracted/
фоном при загрузке (оба пути: /api/upload и tus), по готовности — system-сообщение,
чтобы агент видел обычные файлы. .zip не трогаем (работает через parse_gge_archive).
Юнит (mutation-safe) + серверный real-тест на реальном 09.0200.rar → 39 файлов.
APP_VERSION → 2026-07-15b.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 20:06:51 +10:00

201 lines
8.1 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_rarlike_async, RARLIKE_EXT
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)
if length > max_size:
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):
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} байт)")
# .rar/.7z распаковываем на хосте (unar) — у агента нет питон-распаковщика rar.
if dest.suffix.lower() in RARLIKE_EXT:
extract_rarlike_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"])