Files
mtusi2026lab5/src/app.py
T

260 lines
12 KiB
Python

import asyncio
import base64
from contextlib import asynccontextmanager
from dataclasses import dataclass
import os
import re
import secrets
import tempfile
import unicodedata
from argon2 import PasswordHasher
from argon2.exceptions import VerificationError, InvalidHashError
from fastapi import FastAPI, Request, Response
import psycopg
from psycopg_pool import PoolTimeout, TooManyRequests
from starlette.exceptions import HTTPException
from starlette.responses import StreamingResponse
from botocore.exceptions import BotoCoreError, ClientError
from .common import ApiError, invalid, json_body, object_fields, pagination, string, uuid_value
from .http import Boundaries, error_response
from .store import Store, clean
from .storage import Storage, MAX_BYTES, validate_image
from .offload import complete_thread
@dataclass
class Settings:
database_url: str
redis_url: str
cursor_secret: str
session_ttl_seconds: int = 3600
db_pool_size: int = 5
max_body_bytes: int = 32768
max_inflight: int = 32
request_timeout: int = 30
write_rps: int = 100
write_burst: int = 100
@classmethod
def environment(cls):
result=cls(database_url=os.environ['DATABASE_URL'],redis_url=os.environ['REDIS_URL'],cursor_secret=os.environ['CURSOR_SECRET'],
**{name:int(os.environ.get(name.upper(),field.default)) for name,field in cls.__dataclass_fields__.items() if field.type is int})
if len(result.cursor_secret)<32 or any(getattr(result,name)<=0 for name,field in cls.__dataclass_fields__.items() if field.type is int):
raise ValueError('Invalid configuration')
return result
def create_app(settings=None):
cfg=settings or Settings.environment()
store=Store(cfg)
storage=Storage()
uploads=asyncio.Semaphore(2)
decoders=asyncio.Semaphore(1)
downloads=asyncio.Semaphore(4)
hasher=PasswordHasher(time_cost=2,memory_cost=32768,parallelism=1)
dummy_hash=hasher.hash(secrets.token_urlsafe(32))
kdf_slots=asyncio.Semaphore(4)
@asynccontextmanager
async def lifespan(api):
await store.open()
try: yield
finally:
await store.close()
storage.client.close()
api=FastAPI(lifespan=lifespan,openapi_url=None,docs_url=None,redoc_url=None)
api.state.store=store
@api.exception_handler(ApiError)
async def api_error(request,exc): return error_response(exc,request.state.request_id)
@api.exception_handler(HTTPException)
async def http_error(request,exc):
return error_response(ApiError(404,'not_found','Route not found'),request.state.request_id)
async def database_error(request,exc):
return error_response(ApiError(503,'unavailable','Database unavailable',{'Retry-After':'1'}),request.state.request_id)
for exception in (psycopg.Error,PoolTimeout,TooManyRequests): api.add_exception_handler(exception,database_error)
async def storage_error(request,exc):
return error_response(ApiError(503,'unavailable','Object storage unavailable',{'Retry-After':'1'}),request.state.request_id)
for exception in (BotoCoreError,ClientError): api.add_exception_handler(exception,storage_error)
@api.exception_handler(psycopg.DataError)
async def data_error(request,exc):
return error_response(ApiError(400,'invalid_request','Unsupported field value'),request.state.request_id)
def unauthorized(basic=False):
scheme='Basic realm="messenger", charset="UTF-8"' if basic else 'Bearer realm="messenger"'
return ApiError(401,'unauthorized','Invalid credentials',{'WWW-Authenticate':scheme})
def bearer(request):
value=request.headers.get('authorization','')
parts=value.split()
if len(parts)!=2 or parts[0].lower()!='bearer' or not re.fullmatch(r'[A-Za-z0-9_-]{43}',parts[1]):
raise unauthorized()
return parts[1]
async def actor(request): return await store.authenticate(bearer(request))
@api.get('/health/live')
async def live(): return {'status':'ok'}
@api.get('/health/ready')
async def ready():
await store.ready()
await asyncio.to_thread(storage.ready)
return {'status':'ok'}
@api.post('/api/v1/users',status_code=201)
async def register(request:Request):
body=object_fields(await json_body(request),('username','display_name','password'))
username=string(body['username'],32)
if not re.fullmatch(r'[a-z0-9_]{3,32}',username): invalid('Invalid username')
name=string(body['display_name'],100)
password=string(body['password'],128)
if len(password)<12: invalid('Password must contain 12..128 code points')
async with kdf_slots: hashed=await asyncio.to_thread(hasher.hash,password)
return await store.register(username,name,hashed)
@api.post('/api/v1/auth/sessions',status_code=201)
async def login(request:Request):
try:
scheme,encoded=request.headers.get('authorization','').split(' ',1)
if scheme.lower()!='basic': raise ValueError()
username,password=base64.b64decode(encoded,validate=True).decode('utf-8').split(':',1)
if not re.fullmatch(r'[a-z0-9_]{3,32}',username) or not 12<=len(password)<=128: raise ValueError()
except (ValueError,UnicodeError): raise unauthorized(True) from None
if await request.body(): invalid('Session login does not accept a body')
row=await store.credentials(username)
try:
async with kdf_slots: await asyncio.to_thread(hasher.verify,row['password_hash'] if row else dummy_hash,password)
except (VerificationError,InvalidHashError): raise unauthorized(True) from None
if not row: raise unauthorized(True)
token=secrets.token_urlsafe(32)
expires=await store.create_session(row['id'],token)
return {'token':token,'token_type':'Bearer','expires_at':expires,
'user':clean({k:v for k,v in row.items() if k!='password_hash'})}
@api.delete('/api/v1/auth/sessions/current',status_code=204)
async def logout(request:Request):
await actor(request)
await store.logout(bearer(request))
return Response(status_code=204)
@api.get('/api/v1/users/me')
async def me(request:Request): return await actor(request)
@api.post('/api/v1/chats',status_code=201)
async def create_chat(request:Request):
user=await actor(request)
body=object_fields(await json_body(request),('title','member_ids'))
title=string(body['title'],100)
if not isinstance(body['member_ids'],list) or not 1<=len(body['member_ids'])<=100: invalid('Invalid members')
members=[uuid_value(v) for v in body['member_ids']]
if len(set(members))!=len(members): invalid('Duplicate member')
return await store.create_chat(user['id'],title,members)
@api.get('/api/v1/chats')
async def list_chats(request:Request):
user=await actor(request)
limit,cursor=pagination(request,'chats:'+user['id'],store.secret)
return await store.page(user['id'],None,limit,cursor)
@api.get('/api/v1/chats/{chat_id}')
async def get_chat(chat_id:str,request:Request):
user=await actor(request)
return await store.chat(user['id'],uuid_value(chat_id))
@api.get('/api/v1/chats/{chat_id}/messages')
async def list_messages(chat_id:str,request:Request):
user=await actor(request); chat_id=uuid_value(chat_id)
await store.chat(user['id'],chat_id)
limit,cursor=pagination(request,'messages:'+chat_id,store.secret)
return await store.page(user['id'],chat_id,limit,cursor)
@api.post('/api/v1/chats/{chat_id}/messages',status_code=201)
async def create_message(chat_id:str,request:Request):
user=await actor(request); chat_id=uuid_value(chat_id)
await store.chat(user['id'],chat_id)
body=object_fields(await json_body(request),('text',),('attachment_ids',))
key=request.headers.get('idempotency-key','')
if not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}',key): invalid('Invalid Idempotency-Key')
ids=body.get('attachment_ids',[])
if not isinstance(ids,list) or len(ids)>10: invalid('Invalid attachments')
ids=[uuid_value(v) for v in ids]
if len(ids)!=len(set(ids)): invalid('Duplicate attachment')
text=string(body['text'],4000,blank=True)
if not text.strip() and not ids: invalid('Message must have content')
return await store.create_message(user['id'],chat_id,text,key,ids)
def metadata(row):
fields=('id','chat_id','owner_id','filename','content_type','size_bytes','sha256','created_at','updated_at','status','error_code')
result={k:row[k] for k in fields}
result['variants']=[{k:v for k,v in variant.items() if k!='object_key'} for variant in row['variants']] if row['status']=='ready' else []
return result
@api.post('/api/v1/chats/{chat_id}/attachments',status_code=202)
async def upload(chat_id:str,request:Request):
user=await actor(request); chat_id=uuid_value(chat_id)
await store.chat(user['id'],chat_id)
if set(request.query_params)!={'filename'} or len(request.query_params.getlist('filename'))!=1:
invalid('Expected one filename')
filename=string(request.query_params['filename'],255)
if any(c in '/\\' or unicodedata.category(c)=='Cc' for c in filename): invalid('Invalid filename')
mime=request.headers.get('content-type','').strip().lower()
if mime not in ('image/png','image/jpeg'): raise ApiError(415,'unsupported_media_type','Expected PNG/JPEG')
if uploads.locked(): raise ApiError(503,'unavailable','Upload slots busy',{'Retry-After':'1'})
async with uploads:
with tempfile.TemporaryFile() as file:
size=0
async for chunk in request.stream():
size+=len(chunk)
if size>MAX_BYTES: raise ApiError(413,'payload_too_large','Upload exceeds 10 MiB')
file.write(chunk)
async with decoders:
digest=await complete_thread(validate_image,file,mime)
row=await store.save_attachment(user['id'],chat_id,filename,mime,size,digest,file,storage)
return metadata(row)
@api.get('/api/v1/attachments/{attachment_id}')
async def attachment(attachment_id:str,request:Request):
user=await actor(request)
return metadata(await store.attachment(user['id'],uuid_value(attachment_id)))
@api.get('/api/v1/attachments/{attachment_id}/content')
async def content(attachment_id:str,request:Request):
user=await actor(request)
row=await store.attachment(user['id'],uuid_value(attachment_id))
if row['status']!='ready': raise ApiError(409,'conflict','Attachment is not ready')
if set(request.query_params)-{'variant'} or len(request.query_params.getlist('variant'))>1: invalid('Invalid query')
variant=request.query_params.get('variant','original')
target=row if variant=='original' else next((v for v in row['variants'] if v['name']==variant),None)
if target is None: raise ApiError(404,'not_found','Variant not found')
if downloads.locked(): raise ApiError(503,'unavailable','Download slots busy')
await downloads.acquire()
try:
obj=await asyncio.to_thread(storage.get,target['object_key'])
except BaseException:
downloads.release()
raise
async def chunks():
try:
while data:=await asyncio.to_thread(obj['Body'].read,65536):
yield data
finally:
obj['Body'].close()
downloads.release()
return StreamingResponse(chunks(),media_type=target['content_type'],headers={
'Content-Length':str(target['size_bytes']),'X-Content-Type-Options':'nosniff',
'Content-Disposition':'attachment'})
api.add_middleware(Boundaries,settings=cfg)
return api
app=create_app()