feat(lab4): private S3 attachments and safe storage reconciliation

This commit is contained in:
Quzzqq
2026-11-06 16:51:18 +03:00
parent ec540a1a72
commit 435a6465ec
61 changed files with 3106 additions and 33 deletions
View File
+476
View File
@@ -0,0 +1,476 @@
"""Synchronous lab4 contract. Binary reads are bounded, temporary spools are ephemeral."""
import asyncio
import base64
import datetime as dt
import hashlib
import json
import re
import secrets
import tempfile
import unicodedata
import uuid
import psycopg
from argon2 import PasswordHasher
from argon2.exceptions import VerificationError
from botocore.exceptions import BotoCoreError, ClientError
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, Response, StreamingResponse
from jsonschema import Draft202012Validator
from PIL import Image, UnidentifiedImageError
from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException
from starlette.requests import ClientDisconnect
from src.storage import BUCKET, PREFIX, LOCK, db, s3, setting
INSTANCE = setting('INSTANCE_ID', secrets.token_hex(8))
MAX_BYTES = min(int(setting('MAX_UPLOAD_BYTES', '10485760')), 10485760)
MAX_PIXELS = min(int(setting('MAX_IMAGE_PIXELS', '40000000')), 40000000)
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
PH = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
DUMMY = PH.hash(secrets.token_hex(16))
SCHEMAS = json.load(open('contracts/openapi.json', encoding='utf-8'))['components']['schemas']
UPLOAD_SLOTS = asyncio.Semaphore(2)
DECODE_SLOT = asyncio.Semaphore(1)
ERRORS = {400:'invalid_request',401:'unauthorized',404:'not_found',409:'conflict',
413:'payload_too_large',415:'unsupported_media_type',503:'unavailable',500:'internal_error'}
class Problem(Exception):
def __init__(self, status):
self.status = status
def fail(status):
raise Problem(status)
def encode(value):
if isinstance(value, (uuid.UUID,)):
return str(value)
if isinstance(value, dt.datetime):
return value.astimezone(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
raise TypeError()
def reply(value, status=200):
return Response(json.dumps(value, default=encode, ensure_ascii=False), status,
media_type='application/json')
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
@app.middleware('http')
async def envelope(request, call_next):
rid = uuid.uuid4().hex
try:
response = await call_next(request)
except Exception as exc:
status = exc.status if isinstance(exc, Problem) else (
503 if isinstance(exc, (psycopg.OperationalError, BotoCoreError, ClientError)) else 500)
# Never expose SQL, keys, tokens, tracebacks or request bodies.
response = JSONResponse({'error':{'code':ERRORS[status],
'message':ERRORS[status], 'request_id':rid}}, status_code=status)
if status == 401:
scheme = 'Basic' if request.url.path == '/api/v1/auth/sessions' else 'Bearer'
response.headers['WWW-Authenticate'] = scheme + ' realm="messenger"' + (
', charset="UTF-8"' if scheme == 'Basic' else '')
response.headers['X-Request-Id'] = rid
response.headers['X-Instance-Id'] = INSTANCE
return response
@app.exception_handler(HTTPException)
async def http_error(request, exc):
# Route misses travel through the same error envelope.
fail(404 if exc.status_code == 404 else 400)
def uid(value):
try:
return str(uuid.UUID(value))
except (ValueError, TypeError, AttributeError):
fail(400)
async def body(request, schema):
if request.headers.get('content-type', '').split(';')[0] != 'application/json':
fail(400)
data = bytearray()
async for chunk in request.stream():
if len(data) + len(chunk) > 65536:
fail(413)
data.extend(chunk)
try:
result = json.loads(data)
if not Draft202012Validator(SCHEMAS[schema]).is_valid(result):
fail(400)
for name in ('display_name', 'title'):
if name in result and not result[name].strip():
fail(400)
if schema == 'CreateUser' and not re.fullmatch('[a-z0-9_]{3,32}',result['username']):
fail(400)
# Reject unpaired JSON Unicode surrogates before database/UTF-8 encoding.
json.dumps(result,ensure_ascii=False).encode('utf-8')
return result
except (ValueError, UnicodeError):
fail(400)
def user_view(row):
return {k:row[k] for k in ('id','username','display_name','created_at')}
def actor(c, request):
auth = request.headers.get('authorization', '')
if not auth.startswith('Bearer ') or not auth[7:]:
fail(401)
row = c.execute('SELECT u.* FROM users u JOIN sessions s ON s.user_id=u.id '
'WHERE s.token_hash=%s AND s.expires_at>clock_timestamp()',
(hashlib.sha256(auth[7:].encode()).hexdigest(),)).fetchone()
if not row:
fail(401)
return row
def access(c, chat, user):
if not c.execute('SELECT 1 FROM members WHERE chat_id=%s AND user_id=%s',
(chat, user['id'])).fetchone():
fail(404)
def chat_view(c, row):
return {**row, 'member_ids':[r['user_id'] for r in c.execute(
'SELECT user_id FROM members WHERE chat_id=%s ORDER BY user_id', (row['id'],))]}
def message_view(c, row):
return {**row, 'attachment_ids':[r['attachment_id'] for r in c.execute(
'SELECT attachment_id FROM message_attachments WHERE message_id=%s ORDER BY position', (row['id'],))]}
def attachment_view(row):
if row['status'] != 'ready':
fail(409)
return {**{k:v for k,v in row.items() if k not in ('object_key','width','height')},
'variants':[]}
@app.get('/health/live')
def live():
return reply({'status':'ok'})
@app.get('/health/ready')
def ready():
with db() as c:
c.execute('SELECT 1')
s3().head_bucket(Bucket=BUCKET)
return reply({'status':'ok'})
@app.post('/api/v1/users')
async def register(request: Request):
data = await body(request, 'CreateUser')
def save():
with db() as c:
try:
row = c.execute('INSERT INTO users(id,username,display_name,password_hash) '
'VALUES (%s,%s,%s,%s) RETURNING *',
(uuid.uuid4(), data['username'],data['display_name'],PH.hash(data['password']))).fetchone()
except psycopg.errors.UniqueViolation:
fail(409)
return reply(user_view(row),201)
return await run_in_threadpool(save)
@app.post('/api/v1/auth/sessions')
async def login(request: Request):
async for chunk in request.stream():
if chunk:
fail(400)
try:
scheme, credential = request.headers.get('authorization','').split(' ',1)
if scheme != 'Basic':
fail(401)
name, password = base64.b64decode(credential,validate=True).decode('utf-8').split(':',1)
if not re.fullmatch('[a-z0-9_]{3,32}',name) or not 12 <= len(password) <= 128:
fail(401)
except (ValueError, UnicodeError):
fail(401)
def create():
with db() as c:
row = c.execute('SELECT * FROM users WHERE username=%s',(name,)).fetchone()
try:
PH.verify(row['password_hash'] if row else DUMMY,password)
except VerificationError:
fail(401)
if not row:
fail(401)
token = secrets.token_urlsafe(32)
expiry = c.execute('INSERT INTO sessions VALUES (%s,%s,clock_timestamp()+%s*interval \'1 second\') '
'RETURNING expires_at',(hashlib.sha256(token.encode()).hexdigest(),row['id'],
int(setting('SESSION_TTL_SECONDS','3600')))).fetchone()['expires_at']
return reply({'token':token,'token_type':'Bearer','expires_at':expiry,'user':user_view(row)},201)
return await run_in_threadpool(create)
@app.delete('/api/v1/auth/sessions/current')
def logout(request: Request):
with db() as c:
actor(c,request)
c.execute('DELETE FROM sessions WHERE token_hash=%s',
(hashlib.sha256(request.headers['authorization'][7:].encode()).hexdigest(),))
return Response(status_code=204)
@app.get('/api/v1/users/me')
def me(request: Request):
with db() as c:
return reply(user_view(actor(c,request)))
@app.post('/api/v1/chats')
async def create_chat(request: Request):
with db() as c:
user = actor(c,request)
data = await body(request,'CreateChat')
ids = [uid(i) for i in data['member_ids']]
if len(set(ids)) != len(ids) or str(user['id']) not in ids:
fail(400)
def save():
with db() as c:
if c.execute('SELECT count(*) n FROM users WHERE id=ANY(%s::uuid[])',(ids,)).fetchone()['n'] != len(ids):
fail(400)
row = c.execute('INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING *',
(uuid.uuid4(),data['title'])).fetchone()
for i in ids:
c.execute('INSERT INTO members VALUES (%s,%s)',(row['id'],i))
result = chat_view(c,row)
return reply(result,201)
return await run_in_threadpool(save)
def page_args(request, resource):
limit = request.query_params.get('limit','50')
if not re.fullmatch('[0-9]+',limit) or not 1 <= int(limit) <= 100:
fail(400)
cursor = request.query_params.get('cursor')
point = None
if cursor is not None:
try:
scope, stamp, ident = json.loads(base64.b64decode(cursor,altchars=b'-_',validate=True))
if scope != resource:
fail(400)
point = (dt.datetime.fromisoformat(stamp.replace('Z','+00:00')), uid(ident))
if point[0].tzinfo is None:
fail(400)
except (ValueError,TypeError,UnicodeError):
fail(400)
return int(limit), point
def page(rows, limit, resource, view):
more = len(rows)>limit
rows = rows[:limit]
cursor = base64.urlsafe_b64encode(json.dumps([resource,encode(rows[-1]['created_at']),
str(rows[-1]['id'])]).encode()).decode() if more else None
return reply({'items':[view(r) for r in rows],'next_cursor':cursor})
@app.get('/api/v1/chats')
def chats(request: Request):
with db() as c:
user = actor(c,request)
resource = 'chats:'+str(user['id'])
limit, point = page_args(request,resource)
rows = c.execute('SELECT ch.* FROM chats ch JOIN members m ON m.chat_id=ch.id '
'WHERE m.user_id=%s '+('AND (ch.created_at,ch.id)>(%s,%s::uuid) ' if point else '')+
'ORDER BY ch.created_at,ch.id LIMIT %s',(user['id'],*(point or ()),limit+1)).fetchall()
return page(rows,limit,resource,lambda row:chat_view(c,row))
@app.get('/api/v1/chats/{chat_id}')
def get_chat(chat_id: str, request: Request):
with db() as c:
user = actor(c,request)
chat = uid(chat_id)
access(c,chat,user)
return reply(chat_view(c,c.execute('SELECT * FROM chats WHERE id=%s',(chat,)).fetchone()))
@app.get('/api/v1/chats/{chat_id}/messages')
def history(chat_id: str, request: Request):
with db() as c:
user = actor(c,request)
chat = uid(chat_id)
access(c,chat,user)
limit, point = page_args(request,chat)
rows = c.execute('SELECT * FROM messages WHERE chat_id=%s '+
('AND (created_at,id)>(%s,%s::uuid) ' if point else '')+
'ORDER BY created_at,id LIMIT %s',(chat,*(point or ()),limit+1)).fetchall()
return page(rows,limit,chat,lambda row:message_view(c,row))
@app.post('/api/v1/chats/{chat_id}/messages')
async def send(chat_id: str, request: Request):
with db() as c:
user = actor(c,request)
chat = uid(chat_id)
access(c,chat,user)
data = await body(request,'CreateMessage')
ids = [uid(i) for i in data.get('attachment_ids',[])]
if not data['text'].strip() and not ids:
fail(400)
if len(set(ids)) != len(ids):
fail(400)
key = request.headers.get('idempotency-key','')
if not re.fullmatch('[A-Za-z0-9._:-]{1,128}',key):
fail(400)
digest = hashlib.sha256(json.dumps({'text':data['text'],'attachment_ids':ids},sort_keys=True).encode()).hexdigest()
def save():
with db() as c:
c.execute('SELECT pg_advisory_xact_lock_shared(%s)',(LOCK,))
# Serialize equal keys across all API processes before checking/creating.
c.execute('SELECT pg_advisory_xact_lock(hashtextextended(%s,0))',
(str(user['id'])+chat+':'+key,))
old = c.execute('SELECT * FROM idempotency WHERE user_id=%s AND chat_id=%s AND key=%s '
'AND expires_at>clock_timestamp()',(user['id'],chat,key)).fetchone()
if old:
if old['body_hash'] != digest:
fail(409)
return reply(message_view(c,c.execute('SELECT * FROM messages WHERE id=%s',
(old['message_id'],)).fetchone()),201)
for ident in ids:
att = c.execute('SELECT * FROM attachments WHERE id=%s AND chat_id=%s',(ident,chat)).fetchone()
if not att:
fail(404)
if att['status'] != 'ready':
fail(409)
row = c.execute('INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *',
(uuid.uuid4(),chat,user['id'],data['text'])).fetchone()
for n, ident in enumerate(ids):
c.execute('INSERT INTO message_attachments VALUES (%s,%s,%s)',(row['id'],ident,n))
c.execute('INSERT INTO idempotency VALUES (%s,%s,%s,%s,%s,clock_timestamp()+interval \'24 hours\') '
'ON CONFLICT(user_id,chat_id,key) DO UPDATE SET body_hash=excluded.body_hash, '
'message_id=excluded.message_id,expires_at=excluded.expires_at',
(user['id'],chat,key,digest,row['id']))
result = message_view(c,row)
return reply(result,201)
return await run_in_threadpool(save)
def validate_image(spool, mime):
try:
image = Image.open(spool)
width,height = image.size
if width*height > MAX_PIXELS:
fail(413)
actual = {'PNG':'image/png','JPEG':'image/jpeg'}.get(image.format)
if actual != mime:
fail(415)
image.verify()
spool.seek(0)
with Image.open(spool) as decoded:
decoded.load() # reject truncated JPEG/PNG, after dimension check
spool.seek(0)
return width,height
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
fail(413)
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
fail(415)
@app.post('/api/v1/chats/{chat_id}/attachments')
async def upload(chat_id: str, request: Request):
with db() as c:
user = actor(c,request)
chat = uid(chat_id)
access(c,chat,user)
filename = request.query_params.get('filename','')
if not 1 <= len(filename) <= 255 or any(x in '/\\' or unicodedata.category(x) in ('Cc','Cs') for x in filename):
fail(400)
mime = request.headers.get('content-type','')
if mime not in ('image/png','image/jpeg'):
fail(415)
length = request.headers.get('content-length')
if length and (not length.isdecimal() or int(length)>MAX_BYTES):
fail(413 if length.isdecimal() else 400)
try:
await asyncio.wait_for(UPLOAD_SLOTS.acquire(),timeout=15)
except asyncio.TimeoutError:
fail(503)
try:
with tempfile.SpooledTemporaryFile(max_size=262144) as spool:
size = 0
digest = hashlib.sha256()
try:
async with asyncio.timeout(20):
async for chunk in request.stream():
size += len(chunk)
if size>MAX_BYTES:
fail(413)
spool.write(chunk)
digest.update(chunk)
except (TimeoutError,ClientDisconnect):
fail(400)
async with DECODE_SLOT:
spool.seek(0)
width,height = await run_in_threadpool(validate_image,spool,mime)
def save():
ident = uuid.uuid4()
key = PREFIX+str(ident)
# Hold shared advisory lock until COMMIT. An uncertain COMMIT must
# never trigger immediate deletion: reconciler decides after grace.
with db() as c:
c.execute('SELECT pg_advisory_xact_lock_shared(%s)',(LOCK,))
s3().put_object(Bucket=BUCKET,Key=key,Body=spool,ContentLength=size,ContentType=mime)
row = c.execute('INSERT INTO attachments(id,chat_id,owner_id,object_key,filename,content_type,'
'size_bytes,sha256,width,height,status) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,\'ready\') RETURNING *',
(ident,chat,user['id'],key,filename,mime,size,digest.hexdigest(),width,height)).fetchone()
return reply(attachment_view(row),201)
return await run_in_threadpool(save)
finally:
UPLOAD_SLOTS.release()
def get_attachment(c, request, ident):
user = actor(c,request)
ident = uid(ident)
row = c.execute('SELECT * FROM attachments WHERE id=%s',(ident,)).fetchone()
if not row:
fail(404)
access(c,row['chat_id'],user)
return row
@app.get('/api/v1/attachments/{attachment_id}')
def attachment(attachment_id: str, request: Request):
with db() as c:
return reply(attachment_view(get_attachment(c,request,attachment_id)))
@app.get('/api/v1/attachments/{attachment_id}/content')
def content(attachment_id: str, request: Request):
with db() as c:
row = get_attachment(c,request,attachment_id)
if row['status'] != 'ready':
fail(409)
if request.query_params.get('variant','original') != 'original':
fail(404)
try:
stream = s3().get_object(Bucket=BUCKET,Key=row['object_key'])['Body']
except ClientError as exc:
if exc.response['Error']['Code'] in ('NoSuchKey','404'):
fail(503)
raise
def chunks():
try:
while block := stream.read(65536):
yield block
finally:
stream.close()
return StreamingResponse(chunks(),media_type=row['content_type'],
headers={'Content-Length':str(row['size_bytes']), 'X-Content-Type-Options':'nosniff'})
+94
View File
@@ -0,0 +1,94 @@
"""Operator-only, dry-run by default. Never infer missing from a failed LIST/HEAD."""
import argparse
import datetime as dt
import json
import time
from botocore.exceptions import ClientError
from src.storage import BUCKET, PREFIX, LOCK, db, s3
def reconcile(apply=False, grace=3600):
if grace < 60:
raise ValueError('Grace must be at least 60 seconds')
start = time.monotonic()
result = dict(mode='apply' if apply else 'dry-run', grace_seconds=grace,
scanned_objects=0, scanned_metadata=0, list_requests=0, head_requests=0,
orphan=[], missing=[], repaired=[], fresh_skipped=0)
client = s3()
with db() as c:
# Exclusive counterpart of upload/message shared locks: recheck and repair
# cannot race an in-flight PUT/COMMIT, even when the upload lasts past grace.
c.execute('SELECT pg_advisory_xact_lock(%s)',(LOCK,))
now = c.execute('SELECT clock_timestamp() t').fetchone()['t']
cutoff = now-dt.timedelta(seconds=grace)
rows = c.execute('SELECT * FROM attachments').fetchall()
by_key = {r['object_key']:r for r in rows}
result['scanned_metadata'] = len(rows)
# Complete list before any mutation. API-created names are unique, never reused.
objects = {}
for page in client.get_paginator('list_objects_v2').paginate(Bucket=BUCKET,Prefix=PREFIX):
result['list_requests'] += 1
for obj in page.get('Contents',[]):
objects[obj['Key']] = obj
result['scanned_objects'] = len(objects)
for key, obj in objects.items():
if key in by_key:
continue
if obj['LastModified'] >= cutoff:
result['fresh_skipped'] += 1
continue
# Re-read immediately before delete, under the exclusive DB lock.
result['head_requests'] += 1
current = client.head_object(Bucket=BUCKET,Key=key)
if current['LastModified'] >= cutoff or current['ETag'] != obj['ETag']:
continue
if c.execute('SELECT 1 FROM attachments WHERE object_key=%s',(key,)).fetchone():
continue
result['orphan'].append(key)
if apply:
client.delete_object(Bucket=BUCKET,Key=key)
for row in rows:
key = row['object_key']
if key in objects or row['created_at'] >= cutoff:
continue
result['head_requests'] += 1
try:
client.head_object(Bucket=BUCKET,Key=key)
except ClientError as exc:
if exc.response['Error']['Code'] not in ('404','NoSuchKey'):
raise
else:
# Restored objects can safely recover failed metadata.
continue
result['missing'].append(str(row['id']))
if apply and row['status'] != 'failed':
c.execute("UPDATE attachments SET status='failed',error_code='missing_object',updated_at=clock_timestamp() WHERE id=%s",(row['id'],))
for row in rows:
if row['status'] != 'failed' or row['error_code'] != 'missing_object' or row['object_key'] not in objects:
continue
# A restored backup must match the original bytes before publishing ready.
import hashlib
obj = client.get_object(Bucket=BUCKET,Key=row['object_key'])['Body']
digest = hashlib.sha256()
size = 0
try:
for chunk in obj.iter_chunks(65536):
size += len(chunk)
digest.update(chunk)
finally:
obj.close()
if size == row['size_bytes'] and digest.hexdigest() == row['sha256']:
result['repaired'].append(str(row['id']))
if apply:
c.execute("UPDATE attachments SET status='ready',error_code=NULL,updated_at=clock_timestamp() WHERE id=%s",(row['id'],))
result['elapsed_seconds'] = round(time.monotonic()-start,6)
return result
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--apply',action='store_true')
parser.add_argument('--grace-seconds',type=int,default=3600)
args = parser.parse_args()
print(json.dumps(reconcile(args.apply,args.grace_seconds),indent=2))
+42
View File
@@ -0,0 +1,42 @@
import os
from pathlib import Path
import boto3
import psycopg
from botocore.config import Config
from psycopg.rows import dict_row
def setting(name, default=None):
path = os.getenv(name + '_FILE')
return Path(path).read_text().strip() if path else os.getenv(name, default)
BUCKET = setting('S3_BUCKET', 'messenger-attachments')
PREFIX = 'originals/'
# Shared lock serializes reconciler with uploads/linking; downloads retain metadata.
LOCK = 4082301
def db():
return psycopg.connect(setting('DATABASE_URL'), row_factory=dict_row,
connect_timeout=3, options='-c statement_timeout=15000 -c lock_timeout=10000')
def s3():
return boto3.client('s3', endpoint_url=setting('S3_ENDPOINT', 'http://s3:9000'),
region_name=setting('S3_REGION', 'us-east-1'),
aws_access_key_id=setting('S3_ACCESS_KEY_ID'),
aws_secret_access_key=setting('S3_SECRET_ACCESS_KEY'),
config=Config(connect_timeout=2, read_timeout=5,
retries={'max_attempts': 0}, s3={'addressing_style': 'path'}))
def migrate():
with db() as c:
c.execute('SELECT pg_advisory_xact_lock(%s)', (LOCK,))
c.execute(Path('migrations/001_initial.sql').read_text())
if __name__ == '__main__':
migrate()