"""Authenticate and bound uploads before multipart parsing creates spool files.""" import asyncio import tempfile from fastapi import HTTPException from starlette.requests import Request from starlette.responses import JSONResponse from app.api.dependencies import current_actor, csrf_actor from app.services.quotas import check_storage_budget class UploadGuard: def __init__(self, app): self.app = app self.slots = asyncio.Semaphore(2) self.lock = asyncio.Lock() self.reserved = {} self.global_reserved = 0 async def __call__(self, scope, receive, send): if ( scope["type"] != "http" or scope["method"] != "POST" or scope["path"].rstrip("/") != "/api/assets" ): return await self.app(scope, receive, send) request = Request(scope) settings = request.app.state.settings async def reject(status, code, message): await JSONResponse({"detail": {"code": code, "message": message}}, status_code=status)( scope, receive, send ) try: actor = await current_actor(request) await csrf_actor(request, actor) except HTTPException as exc: return await JSONResponse({"detail": exc.detail}, status_code=exc.status_code)( scope, receive, send ) limit = settings.max_upload_bytes + 1024 * 1024 # bounded multipart overhead length = request.headers.get("content-length") try: expected = int(length) if length is not None else limit if expected < 0: raise ValueError() except ValueError: return await reject(400, "invalid_content_length", "上传长度无效") if expected > limit: return await reject(413, "upload_too_large", "上传超过文件大小限制") if self.slots.locked(): return await reject(429, "upload_busy", "同时上传数量已满,请稍后重试") await self.slots.acquire() reservation = expected * 2 # raw body plus multipart spool during parsing reserved = False try: async with self.lock: async with request.app.state.db.session() as session: await check_storage_budget( session, settings, actor.id, incoming_bytes=self.reserved.get(actor.id, 0) + expected, global_incoming_bytes=self.global_reserved + reservation, ) self.reserved[actor.id] = self.reserved.get(actor.id, 0) + expected self.global_reserved += reservation reserved = True temporary = (settings.asset_root.parent / "tmp").resolve() if not temporary.is_relative_to(settings.workspace_root): return await reject(503, "upload_storage_unavailable", "上传暂存目录不可用") temporary.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryFile(dir=temporary) as body: total = 0 while True: message = await receive() if message["type"] == "http.disconnect": return await reject(499, "upload_disconnected", "上传连接已断开") if message["type"] != "http.request": continue chunk = message.get("body", b"") total += len(chunk) if total > limit or (length is not None and total > expected): return await reject(413, "upload_too_large", "上传超过文件大小限制") await asyncio.to_thread(body.write, chunk) if not message.get("more_body", False): break if length is not None and total != expected: return await reject(400, "invalid_content_length", "上传数据长度不匹配") await asyncio.to_thread(body.seek, 0) remaining = total completed = False async def replay(): nonlocal remaining, completed if completed: return await receive() chunk = await asyncio.to_thread(body.read, min(1024 * 1024, remaining)) remaining -= len(chunk) completed = remaining == 0 return {"type": "http.request", "body": chunk, "more_body": not completed} await self.app(scope, replay, send) except HTTPException as exc: await JSONResponse({"detail": exc.detail}, status_code=exc.status_code)( scope, receive, send ) finally: if reserved: async with self.lock: self.reserved[actor.id] -= expected self.global_reserved -= reservation if self.reserved[actor.id] == 0: self.reserved.pop(actor.id) self.slots.release()