Files
mtusi2026lab4/app/routers/attachments.py
T
2026-11-11 18:55:53 +03:00

167 lines
6.8 KiB
Python

"""Bounded image uploads, authorized streaming downloads and private object storage."""
import hashlib
import os
import tempfile
import unicodedata
from uuid import UUID, uuid4
from io import BytesIO
from fastapi import APIRouter, Depends, HTTPException, Request, Query
from fastapi.responses import StreamingResponse
from starlette.concurrency import run_in_threadpool
from PIL import Image, UnidentifiedImageError, ImageFile
from botocore.exceptions import BotoCoreError, ClientError
from app.dependencies import current_user
from app.routers.chats import get_chat_row
from app.storage import db
from app.s3 import s3_client, bucket
from app.models.time_format import utc_z
from pydantic import BaseModel, ConfigDict, field_serializer
from datetime import datetime
router=APIRouter()
MAX_BYTES=10*1024*1024
MAX_PIXELS=40_000_000
CHUNK=64*1024
Image.MAX_IMAGE_PIXELS=MAX_PIXELS
ImageFile.LOAD_TRUNCATED_IMAGES=False
class Attachment(BaseModel):
model_config=ConfigDict(extra='forbid')
id:UUID
chat_id:UUID
owner_id:UUID
filename:str
content_type:str
size_bytes:int
sha256:str
status:str
variants:list=[]
error_code:str|None=None
created_at:datetime
updated_at:datetime
@field_serializer('created_at','updated_at',when_used='json')
def as_utc(self,value:datetime)->str:
return utc_z(value)
def public(row):
return {k:row[k] for k in ('id','chat_id','owner_id','filename','content_type','size_bytes',
'sha256','status','created_at','updated_at')} | {'variants':[],'error_code':None}
def check_name(name):
if not 1<=len(name)<=255 or any(ch in '/\\' or ord(ch)<32 or 127<=ord(ch)<160 or unicodedata.category(ch)=='Cc' for ch in name):
raise HTTPException(400,'Invalid filename')
def inspect_image(file, declared):
file.seek(0)
try:
with Image.open(file) as img:
fmt=img.format
w,h=img.size
if w<=0 or h<=0 or w*h>MAX_PIXELS:
raise HTTPException(413,'Image pixel count exceeded')
expected={'PNG':'image/png','JPEG':'image/jpeg'}.get(fmt)
if not expected or expected!=declared:
raise HTTPException(415,'Image content type mismatch')
img.verify()
file.seek(0)
with Image.open(file) as img:
img.load() # reject truncated PNG/JPEG and decompression errors
except HTTPException:
raise
except (UnidentifiedImageError, ValueError, OSError, SyntaxError, Image.DecompressionBombError, Image.DecompressionBombWarning):
raise HTTPException(415,'Invalid image')
finally:
file.seek(0)
def put_original(file, key, content_type):
client=s3_client()
file.seek(0)
client.upload_fileobj(file,bucket(),key,ExtraArgs={'ContentType':content_type},
Config=__import__('boto3').s3.transfer.TransferConfig(
multipart_threshold=16*1024*1024,use_threads=False))
def delete_original(key):
s3_client().delete_object(Bucket=bucket(),Key=key)
@router.post('/api/v1/chats/{chat_id}/attachments',response_model=Attachment,status_code=201)
async def upload(chat_id:UUID,request:Request, filename:str=Query(...),user=Depends(current_user)):
check_name(filename)
declared=request.headers.get('content-type','').lower()
if declared not in ('image/png','image/jpeg'):
raise HTTPException(415,'Only PNG and JPEG are supported')
with db() as conn:
if get_chat_row(conn,chat_id,user['id']) is None:
raise HTTPException(404,'Chat not found')
length=request.headers.get('content-length')
if length is not None:
try:
if int(length)>MAX_BYTES:raise HTTPException(413,'Upload too large')
except ValueError:
raise HTTPException(400,'Invalid content length')
size=0
digest=hashlib.sha256()
# Disk-backed temporary spool; no API replica retains permanent content.
with tempfile.SpooledTemporaryFile(max_size=1024*1024,mode='w+b') as file:
async for part in request.stream():
size+=len(part)
if size>MAX_BYTES:
raise HTTPException(413,'Upload too large')
digest.update(part)
file.write(part)
if not size:raise HTTPException(415,'Empty image')
await run_in_threadpool(inspect_image,file,declared)
ident=uuid4()
key='originals/'+str(uuid4())
try:
await run_in_threadpool(put_original,file,key,declared)
except (ClientError,BotoCoreError,OSError):
# A partially written object is possible after a transport error.
try:await run_in_threadpool(delete_original,key)
except Exception:pass # periodic reconciler can remove an orphan after grace
raise HTTPException(503,'Storage unavailable')
try:
with db() as conn:
if get_chat_row(conn,chat_id,user['id']) is None:
raise HTTPException(404,'Chat not found')
row=conn.execute('''INSERT INTO attachments
(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *''',
(ident,chat_id,user['id'],filename,declared,size,digest.hexdigest(),key)).fetchone()
except Exception:
try:await run_in_threadpool(delete_original,key)
except Exception:pass
raise
return public(row)
def authorized(ident,user):
with db() as conn:
row=conn.execute('''SELECT a.* FROM attachments a
JOIN chat_members cm ON cm.chat_id=a.chat_id AND cm.user_id=%s
WHERE a.id=%s''',(user['id'],ident)).fetchone()
if row is None:raise HTTPException(404,'Attachment not found')
return row
@router.get('/api/v1/attachments/{attachment_id}',response_model=Attachment)
def get_attachment(attachment_id:UUID,user=Depends(current_user)):
return public(authorized(attachment_id,user))
@router.get('/api/v1/attachments/{attachment_id}/content')
def download(attachment_id:UUID,variant:str='original',user=Depends(current_user)):
row=authorized(attachment_id,user)
if variant!='original':raise HTTPException(404,'Variant not found')
try:
obj=s3_client().get_object(Bucket=bucket(),Key=row['object_key'])
except (ClientError,BotoCoreError,OSError):
raise HTTPException(503,'Storage unavailable')
body=obj['Body']
def chunks():
try:
for chunk in body.iter_chunks(chunk_size=CHUNK):
if chunk:yield chunk
finally:
body.close()
return StreamingResponse(chunks(),media_type=row['content_type'],headers={
'Content-Length':str(row['size_bytes']),
'Content-Disposition':'attachment',
'X-Content-Type-Options':'nosniff'})