Implement lab4 S3 attachments
This commit is contained in:
@@ -0,0 +1,166 @@
|
||||
"""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'})
|
||||
@@ -0,0 +1,52 @@
|
||||
from uuid import UUID, uuid4
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from app.dependencies import current_user
|
||||
from app.models.chats import Chat, ChatPage, CreateChat
|
||||
from app.storage import db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def get_chat_row(conn, chat_id, user_id):
|
||||
return conn.execute("""SELECT c.id,c.title,c.created_at FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id=c.id WHERE c.id=%s AND cm.user_id=%s""",
|
||||
(chat_id,user_id)).fetchone()
|
||||
|
||||
|
||||
def chat_output(conn,row):
|
||||
members=conn.execute('SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id',(row['id'],)).fetchall()
|
||||
return {**row, 'member_ids':[m['user_id'] for m in members]}
|
||||
|
||||
|
||||
@router.post('/api/v1/chats', response_model=Chat, status_code=201)
|
||||
def create_chat(payload:CreateChat,user=Depends(current_user)):
|
||||
if user['id'] not in payload.member_ids:
|
||||
raise HTTPException(status_code=400,detail='Creator must be a chat member')
|
||||
with db() as conn:
|
||||
rows=conn.execute('SELECT id FROM users WHERE id = ANY(%s)',(payload.member_ids,)).fetchall()
|
||||
if len(rows)!=len(payload.member_ids):
|
||||
raise HTTPException(status_code=400,detail='Unknown member')
|
||||
chat=conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING id,title,created_at',
|
||||
(uuid4(),payload.title)).fetchone()
|
||||
for member in payload.member_ids:
|
||||
conn.execute('INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)',(chat['id'],member))
|
||||
return chat_output(conn,chat)
|
||||
|
||||
|
||||
@router.get('/api/v1/chats',response_model=ChatPage)
|
||||
def list_chats(limit:int=Query(default=50,ge=1,le=100),user=Depends(current_user)):
|
||||
with db() as conn:
|
||||
rows=conn.execute("""SELECT c.id,c.title,c.created_at FROM chats c
|
||||
JOIN chat_members m ON m.chat_id=c.id WHERE m.user_id=%s
|
||||
ORDER BY c.created_at,c.id LIMIT %s""",(user['id'],limit+1)).fetchall()
|
||||
items=[chat_output(conn,row) for row in rows[:limit]]
|
||||
return {'items':items,'next_cursor':None}
|
||||
|
||||
|
||||
@router.get('/api/v1/chats/{chat_id}',response_model=Chat)
|
||||
def get_chat(chat_id:UUID,user=Depends(current_user)):
|
||||
with db() as conn:
|
||||
row=get_chat_row(conn,chat_id,user['id'])
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404,detail='Chat not found')
|
||||
return chat_output(conn,row)
|
||||
@@ -0,0 +1,113 @@
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
import hashlib
|
||||
import re
|
||||
from datetime import datetime
|
||||
from uuid import UUID,uuid4
|
||||
from fastapi import APIRouter,Depends,HTTPException,Query,Header
|
||||
from app.dependencies import current_user
|
||||
from app.models.messages import CreateMessage,Message,MessagePage
|
||||
from app.routers.chats import get_chat_row
|
||||
from app.storage import db
|
||||
|
||||
router=APIRouter()
|
||||
|
||||
MESSAGE_SELECT = """SELECT m.id,m.chat_id,m.sender_id,m.text,m.created_at,
|
||||
COALESCE((SELECT array_agg(ma.attachment_id ORDER BY ma.position)
|
||||
FROM message_attachments ma WHERE ma.message_id=m.id), ARRAY[]::uuid[]) AS attachment_ids
|
||||
FROM messages m"""
|
||||
|
||||
|
||||
|
||||
def encode_cursor(chat_id,row):
|
||||
raw=json.dumps({'chat_id':str(chat_id),'created_at':row['created_at'].isoformat(),'id':str(row['id'])}).encode()
|
||||
return base64.urlsafe_b64encode(raw).decode().rstrip('=')
|
||||
|
||||
|
||||
def decode_cursor(chat_id,cursor):
|
||||
try:
|
||||
raw=base64.b64decode(cursor+'='*(-len(cursor)%4),altchars=b'-_',validate=True)
|
||||
data=json.loads(raw)
|
||||
ts=datetime.fromisoformat(data['created_at'])
|
||||
ident=UUID(data['id'])
|
||||
if data['chat_id']!=str(chat_id) or ts.tzinfo is None:
|
||||
raise ValueError('Wrong cursor')
|
||||
return ts,ident
|
||||
except (ValueError,KeyError,TypeError,UnicodeDecodeError,binascii.Error):
|
||||
raise HTTPException(status_code=400,detail='Invalid cursor')
|
||||
|
||||
|
||||
IDEMPOTENCY_KEY_RE = re.compile(r'^[A-Za-z0-9._:-]{1,128}$', re.ASCII)
|
||||
|
||||
|
||||
def canonical_message_hash(payload):
|
||||
# Canonical semantics, not raw JSON bytes or field order.
|
||||
data = payload.model_dump(mode='json', exclude_none=True)
|
||||
data.setdefault('attachment_ids', [])
|
||||
return hashlib.sha256(json.dumps(data, sort_keys=True, separators=(',', ':'),
|
||||
ensure_ascii=False).encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def advisory_lock_id(user_id,chat_id,key):
|
||||
scope = f'{user_id}:{chat_id}:{key}'.encode('utf-8')
|
||||
return int.from_bytes(hashlib.sha256(scope).digest()[:8], 'big', signed=True)
|
||||
|
||||
|
||||
@router.post('/api/v1/chats/{chat_id}/messages',response_model=Message,status_code=201)
|
||||
def create_message(chat_id:UUID,payload:CreateMessage,user=Depends(current_user),
|
||||
idempotency_key:str|None=Header(default=None,alias='Idempotency-Key')):
|
||||
if idempotency_key is None or not IDEMPOTENCY_KEY_RE.fullmatch(idempotency_key):
|
||||
raise HTTPException(status_code=400,detail='Invalid or missing Idempotency-Key')
|
||||
request_hash=canonical_message_hash(payload)
|
||||
with db() as conn:
|
||||
# Explicit authorization is checked on EVERY replay, not just initial POST.
|
||||
if get_chat_row(conn,chat_id,user['id']) is None:
|
||||
raise HTTPException(status_code=404,detail='Chat not found')
|
||||
# Same key on different processes serializes in PostgreSQL. The message and
|
||||
# key record commit together, so a network timeout cannot create duplicates.
|
||||
conn.execute('SELECT pg_advisory_xact_lock(%s)',
|
||||
(advisory_lock_id(user['id'],chat_id,idempotency_key),))
|
||||
saved=conn.execute("""SELECT request_hash,message_id,created_at FROM message_idempotency
|
||||
WHERE user_id=%s AND chat_id=%s AND idem_key=%s FOR UPDATE""",
|
||||
(user['id'],chat_id,idempotency_key)).fetchone()
|
||||
if saved is not None:
|
||||
# Contract promises a replay window of at least 24 hours; retaining
|
||||
# keys longer is safe and prevents late duplicate deliveries.
|
||||
if saved['request_hash'] != request_hash:
|
||||
raise HTTPException(status_code=409,detail='Idempotency-Key used with another body')
|
||||
return conn.execute(MESSAGE_SELECT + """ WHERE m.id=%s""",(saved['message_id'],)).fetchone()
|
||||
if payload.attachment_ids:
|
||||
authorized=conn.execute("""SELECT id FROM attachments
|
||||
WHERE chat_id=%s AND id=ANY(%s) AND status='ready' FOR SHARE""",
|
||||
(chat_id,payload.attachment_ids)).fetchall()
|
||||
if len(authorized)!=len(payload.attachment_ids):
|
||||
raise HTTPException(status_code=404,detail='Attachment not found')
|
||||
row=conn.execute("""INSERT INTO messages(id,chat_id,sender_id,text)
|
||||
VALUES (%s,%s,%s,%s) RETURNING id,chat_id,sender_id,text,created_at""",
|
||||
(uuid4(),chat_id,user['id'],payload.text)).fetchone()
|
||||
for pos,attachment_id in enumerate(payload.attachment_ids):
|
||||
conn.execute("""INSERT INTO message_attachments(message_id,attachment_id,position)
|
||||
VALUES (%s,%s,%s)""",(row['id'],attachment_id,pos))
|
||||
row['attachment_ids']=payload.attachment_ids
|
||||
conn.execute("""INSERT INTO message_idempotency(user_id,chat_id,idem_key,request_hash,message_id)
|
||||
VALUES (%s,%s,%s,%s,%s)""",
|
||||
(user['id'],chat_id,idempotency_key,request_hash,row['id']))
|
||||
return row
|
||||
|
||||
|
||||
@router.get('/api/v1/chats/{chat_id}/messages',response_model=MessagePage)
|
||||
def list_messages(chat_id:UUID,limit:int=Query(default=50,ge=1,le=100),
|
||||
cursor:str|None=Query(default=None,min_length=1),user=Depends(current_user)):
|
||||
with db() as conn:
|
||||
if get_chat_row(conn,chat_id,user['id']) is None:
|
||||
raise HTTPException(status_code=404,detail='Chat not found')
|
||||
if cursor is not None:
|
||||
ts,ident=decode_cursor(chat_id,cursor)
|
||||
rows=conn.execute(MESSAGE_SELECT + """ WHERE m.chat_id=%s AND (m.created_at,m.id)>(%s,%s)
|
||||
ORDER BY m.created_at,m.id LIMIT %s""",(chat_id,ts,ident,limit+1)).fetchall()
|
||||
else:
|
||||
rows=conn.execute(MESSAGE_SELECT + """ WHERE m.chat_id=%s ORDER BY m.created_at,m.id LIMIT %s""",(chat_id,limit+1)).fetchall()
|
||||
items=rows[:limit]
|
||||
next_cursor=encode_cursor(chat_id,items[-1]) if len(rows)>limit else None
|
||||
return {'items':items,'next_cursor':next_cursor}
|
||||
@@ -0,0 +1,78 @@
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import uuid4
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Response
|
||||
from psycopg.errors import UniqueViolation
|
||||
from app.dependencies import current_user, unauthorized
|
||||
from app.models.users import CreateUser, User
|
||||
from app.models.time_format import utc_z
|
||||
from app.storage import db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def password_hash(password):
|
||||
salt = os.urandom(16)
|
||||
derived = hashlib.scrypt(password.encode('utf-8'), salt=salt, n=2**14, r=8, p=1, dklen=32)
|
||||
return 'scrypt$' + salt.hex() + '$' + derived.hex()
|
||||
|
||||
|
||||
def verify_password(password, encoded):
|
||||
try:
|
||||
_, salt_hex, expected_hex = encoded.split('$')
|
||||
actual = hashlib.scrypt(password.encode('utf-8'),salt=bytes.fromhex(salt_hex),n=2**14,r=8,p=1,dklen=32)
|
||||
return hmac.compare_digest(actual, bytes.fromhex(expected_hex))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
@router.post('/api/v1/users', response_model=User, status_code=201)
|
||||
def register_user(payload: CreateUser):
|
||||
with db() as conn:
|
||||
try:
|
||||
user = conn.execute("""INSERT INTO users(id,username,display_name,password_hash)
|
||||
VALUES (%s,%s,%s,%s) RETURNING id,username,display_name,created_at""",
|
||||
(uuid4(),payload.username,payload.display_name,password_hash(payload.password))).fetchone()
|
||||
except UniqueViolation:
|
||||
raise HTTPException(status_code=409,detail='Username already exists')
|
||||
return user
|
||||
|
||||
|
||||
@router.get('/api/v1/users/me', response_model=User)
|
||||
def get_current_user(user=Depends(current_user)):
|
||||
return user
|
||||
|
||||
|
||||
@router.post('/api/v1/auth/sessions', status_code=201)
|
||||
def create_session(authorization: str | None = Header(default=None)):
|
||||
if not authorization or not authorization.startswith('Basic '):
|
||||
unauthorized(basic=True)
|
||||
try:
|
||||
raw = base64.b64decode(authorization[6:],validate=True).decode('utf-8')
|
||||
username, password = raw.split(':',1)
|
||||
except (ValueError, UnicodeDecodeError, binascii.Error):
|
||||
unauthorized(basic=True)
|
||||
with db() as conn:
|
||||
row = conn.execute('SELECT * FROM users WHERE username=%s',(username,)).fetchone()
|
||||
if row is None or not verify_password(password,row['password_hash']):
|
||||
unauthorized(basic=True)
|
||||
token = secrets.token_urlsafe(48)
|
||||
ttl = int(os.getenv('SESSION_TTL_SECONDS','3600'))
|
||||
expires = datetime.now(timezone.utc)+timedelta(seconds=ttl)
|
||||
conn.execute('INSERT INTO sessions(token_hash,user_id,expires_at) VALUES (%s,%s,%s)',
|
||||
(hashlib.sha256(token.encode()).hexdigest(),row['id'],expires))
|
||||
return {'token':token,'token_type':'Bearer','expires_at':utc_z(expires),
|
||||
'user':User.model_validate({key:row[key] for key in ('id','username','display_name','created_at')})}
|
||||
|
||||
|
||||
@router.delete('/api/v1/auth/sessions/current',status_code=204)
|
||||
def logout(authorization: str | None = Header(default=None),user=Depends(current_user)):
|
||||
token=authorization[7:]
|
||||
with db() as conn:
|
||||
conn.execute('DELETE FROM sessions WHERE token_hash=%s',(hashlib.sha256(token.encode()).hexdigest(),))
|
||||
return Response(status_code=204)
|
||||
Reference in New Issue
Block a user