NarratifAI / src /security.py
Consulawtech's picture
Accept resumable Companion uploads with atomic job deduplication
01864c7
Raw History Blame Contribute Delete
3.87 kB
"""Admission control before FastAPI parses multipart bodies."""
import asyncio
import json
import tempfile
import threading
from starlette.requests import Request
from starlette.responses import JSONResponse
class RequestAdmission:
def __init__(self, app, authorize, max_upload_bytes=256 * 1024 * 1024,
max_json_bytes=1024 * 1024, max_requests=8):
self.app = app
self.authorize = authorize
self.max_upload_bytes = max_upload_bytes
self.max_json_bytes = max_json_bytes
self.slots = threading.BoundedSemaphore(max_requests)
async def __call__(self, scope, receive, send):
if scope['type'] != 'http' or scope['method'] == 'OPTIONS':
return await self.app(scope, receive, send)
path = scope['path']
protected = (path in ('/transcribe', '/companion/transcribe', '/translate', '/minutes', '/minutes/docx', '/paystack/init', '/paystack/verify')
or any(path.startswith(p) for p in ('/result/', '/status/', '/progress/', '/cancel/')))
if protected:
try:
uid = await asyncio.to_thread(self.authorize, Request(scope))
scope.setdefault('state', {})['verified_uid'] = uid
except Exception as e:
status = getattr(e, 'status_code', 503)
detail = getattr(e, 'detail', 'Authentication unavailable')
return await JSONResponse({'detail': detail}, status_code=status)(scope, receive, send)
if scope['method'] not in ('POST', 'PUT', 'PATCH'):
return await self.app(scope, receive, send)
limit = self.max_upload_bytes if path == '/transcribe' else self.max_json_bytes
headers = dict(scope.get('headers', []))
try:
length = int(headers.get(b'content-length', b'0'))
if length < 0: raise ValueError()
except ValueError:
return await JSONResponse({'detail': 'Invalid Content-Length'}, status_code=400)(scope, receive, send)
if length > limit:
return await JSONResponse({'detail': 'Request too large'}, status_code=413)(scope, receive, send)
if not self.slots.acquire(blocking=False):
return await JSONResponse({'detail': 'Server busy. Retry later.'}, status_code=429,
headers={'Retry-After': '30'})(scope, receive, send)
try:
# Bound memory even for chunked bodies; check bytes before multipart parsing.
with tempfile.SpooledTemporaryFile(max_size=1024 * 1024) as body:
size = 0
async def consume():
nonlocal size
while True:
message = await receive()
if message['type'] == 'http.disconnect': return False
chunk = message.get('body', b'')
size += len(chunk)
if size > limit: return False
body.write(chunk)
if not message.get('more_body', False): return True
try:
ok = await asyncio.wait_for(consume(), timeout=600 if path == '/transcribe' else 30)
except asyncio.TimeoutError:
return await JSONResponse({'detail': 'Upload timed out'}, status_code=408)(scope, receive, send)
if not ok:
return await JSONResponse({'detail': 'Request too large or interrupted'}, status_code=413)(scope, receive, send)
body.seek(0)
async def replay():
chunk = body.read(65536)
return {'type': 'http.request', 'body': chunk, 'more_body': body.tell() < size}
await self.app(scope, replay, send)
finally:
self.slots.release()