"""Lab 4 REST API: shared messenger state and private S3 attachments.""" import base64 import binascii import hashlib import json import logging import re import uuid import time import os import hashlib import tempfile import re as regex import threading from collections import defaultdict, deque from datetime import timezone from fastapi import FastAPI, Request, Query from fastapi.responses import JSONResponse, StreamingResponse from starlette.concurrency import run_in_threadpool from PIL import Image, UnidentifiedImageError from botocore.exceptions import BotoCoreError, ClientError import redis from fastapi.exceptions import RequestValidationError from sqlalchemy import text from sqlalchemy.exc import SQLAlchemyError from .database import SessionLocal from .models import CreateUser, CreateChat, CreateMessage from .store import store, cursor_for_chat, cursor_for_message from . import session_cache from . import object_store from . import jobs from . import telemetry from opentelemetry import trace from opentelemetry.propagate import extract from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator class AppError(Exception): def __init__(self, status, code, message, headers=None): self.status, self.code, self.message, self.headers = status, code, message, headers or {} app = FastAPI(title="MTUSI Messenger", version="6.0.0") INSTANCE_ID = os.getenv("INSTANCE_ID") or str(uuid.uuid4()) _login_attempts = defaultdict(deque) _login_rate_lock = threading.Lock() def enforce_login_rate_limit(request): now = time.monotonic() forwarded = request.headers.get("X-Forwarded-For", "") peer = forwarded.rsplit(",", 1)[-1].strip() if forwarded else (request.client.host if request.client else "unknown") with _login_rate_lock: attempts = _login_attempts[peer] while attempts and now - attempts[0] >= 60: attempts.popleft() if len(attempts) >= 10: retry_after = max(1, 60 - int(now - attempts[0])) raise AppError(429, "rate_limited", "Too many login attempts", {"Retry-After": str(retry_after)}) attempts.append(now) @app.middleware("http") async def observe_request(request: Request, call_next): started = time.perf_counter() request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4()) request.state.request_id = request_id carrier = {key.lower(): value for key, value in request.headers.items() if key.lower() in ("traceparent", "tracestate")} parent = extract(carrier) with telemetry.tracer.start_as_current_span("http.request", context=parent, kind=trace.SpanKind.SERVER) as span: span.set_attribute("http.request.method", request.method) span.set_attribute("messenger.request_id", request_id) try: response = await call_next(request) except Exception: span.set_attribute("http.response.status_code", 500) span.record_exception(Exception("unhandled request failure")) route = request.scope.get("route") route_name = getattr(route, "path", "unmatched") attrs = {"http.request.method": request.method, "http.route": route_name, "http.response.status_class": "5xx"} elapsed = time.perf_counter() - started telemetry.http_requests.add(1, attrs) telemetry.http_duration.record(elapsed, attrs) logging.getLogger("messenger.api").error("http_request_failed", extra={"request_id": request_id, "http_route": route_name, "http_status": 500, "duration_seconds": round(elapsed, 6)}) raise route = request.scope.get("route") route_name = getattr(route, "path", "unmatched") response.headers["X-Request-Id"] = request_id response.headers["X-Instance-Id"] = INSTANCE_ID span.set_attribute("http.route", route_name) span.set_attribute("http.response.status_code", response.status_code) attrs = {"http.request.method": request.method, "http.route": route_name, "http.response.status_class": f"{response.status_code // 100}xx"} elapsed = time.perf_counter() - started telemetry.http_requests.add(1, attrs) telemetry.http_duration.record(elapsed, attrs) if response.status_code >= 500: span.set_status(trace.Status(trace.StatusCode.ERROR)) logging.getLogger("messenger.api").info("http_request_completed", extra={"request_id": request_id, "http_route": route_name, "http_status": response.status_code, "duration_seconds": round(elapsed, 6)}) return response @app.exception_handler(AppError) async def app_error_handler(request, exc): headers = {"X-Request-Id": request.state.request_id, **exc.headers} headers["X-Instance-Id"] = INSTANCE_ID return JSONResponse(status_code=exc.status, content={"error":{"code":exc.code,"message":exc.message,"request_id":request.state.request_id}}, headers=headers) @app.exception_handler(RequestValidationError) async def validation_handler(request, exc): return JSONResponse(status_code=400, content={"error":{"code":"invalid_request","message":"Invalid request","request_id":request.state.request_id}}, headers={"X-Request-Id":request.state.request_id,"X-Instance-Id":INSTANCE_ID}) @app.exception_handler(SQLAlchemyError) async def database_error_handler(request, exc): return JSONResponse(status_code=503, content={"error":{"code":"unavailable","message":"Database unavailable","request_id":request.state.request_id}}, headers={"X-Request-Id":request.state.request_id,"X-Instance-Id":INSTANCE_ID}) @app.exception_handler(Exception) async def internal_handler(request, exc): return JSONResponse(status_code=500, content={"error":{"code":"internal_error","message":"Internal server error","request_id":request.state.request_id}}, headers={"X-Request-Id":request.state.request_id,"X-Instance-Id":INSTANCE_ID}) def stamp(value): if value.tzinfo is None: value = value.replace(tzinfo=timezone.utc) return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") def user_json(user): return {"id":user.id,"username":user.username,"display_name":user.display_name,"created_at":stamp(user.created_at)} def auth_user(request): header = request.headers.get("Authorization", "") if not header.startswith("Bearer ") or not header[7:]: raise AppError(401,"unauthorized","Authentication required",{"WWW-Authenticate":'Bearer realm="messenger"'}) try: found = store.get_session_by_token(header[7:]) except session_cache.CacheUnavailable: raise AppError(503,"unavailable","Session cache unavailable") except SQLAlchemyError: raise AppError(503,"unavailable","Authentication store unavailable") if not found: raise AppError(401,"unauthorized","Invalid or expired session",{"WWW-Authenticate":'Bearer realm="messenger"'}) return found[0] def chat_json(chat): return {"id":chat.id,"title":chat.title,"member_ids":[m.user_id for m in chat.members],"created_at":stamp(chat.created_at)} def validate_uuid(value): try: uuid.UUID(value) except (ValueError, AttributeError): raise AppError(400,"invalid_request","Invalid UUID") @app.get("/health/live") async def live(): return {"status":"ok"} @app.get("/health/ready") async def ready(): try: with SessionLocal() as db: db.execute(text("SELECT 1")) session_cache.ping() object_store.s3.list_objects_v2(Bucket=object_store.S3_BUCKET, Prefix="original/", MaxKeys=1) await run_in_threadpool(jobs.ping) return {"status":"ok"} except session_cache.CacheUnavailable: raise AppError(503,"unavailable","Session cache unavailable") except SQLAlchemyError: raise AppError(503,"unavailable","Database unavailable") except (BotoCoreError, ClientError): raise AppError(503,"unavailable","Object storage unavailable") except (redis.exceptions.RedisError, OSError): raise AppError(503,"unavailable","Attachment queue unavailable") @app.post("/api/v1/users", status_code=201) async def register(data: CreateUser): if not data.display_name.strip() or not 12 <= len(data.password) <= 128: raise AppError(400,"invalid_request","Invalid user fields") try: return user_json(store.add_user(data.username,data.display_name,data.password)) except ValueError as exc: if str(exc) == "USERNAME_EXISTS": raise AppError(409,"conflict","Username already exists") raise AppError(400,"invalid_request","Invalid user fields") except SQLAlchemyError: raise AppError(503,"unavailable","Database unavailable") @app.post("/api/v1/auth/sessions", status_code=201) async def login(request: Request): enforce_login_rate_limit(request) header = request.headers.get("Authorization", "") challenge = {'WWW-Authenticate':'Basic realm="messenger", charset="UTF-8"'} if not header.startswith("Basic "): raise AppError(401,"unauthorized","Invalid credentials",challenge) try: decoded = base64.b64decode(header[6:], validate=True).decode("utf-8") username, password = decoded.split(":", 1) except (binascii.Error, UnicodeError, ValueError): raise AppError(401,"unauthorized","Invalid credentials",challenge) try: user = store.verify_user_password(username,password) if not user: raise AppError(401,"unauthorized","Invalid credentials",challenge) session = store.create_session(user.id) return {"token":session.token,"token_type":"Bearer","expires_at":stamp(session.expires_at),"user":user_json(user)} except session_cache.CacheUnavailable: raise AppError(503,"unavailable","Session cache unavailable") except SQLAlchemyError: raise AppError(503,"unavailable","Database unavailable") @app.delete("/api/v1/auth/sessions/current", status_code=204) async def logout(request: Request): auth_user(request) try: store.delete_session(request.headers["Authorization"][7:]) except session_cache.CacheUnavailable: raise AppError(503,"unavailable","Session cache unavailable") except SQLAlchemyError: raise AppError(503,"unavailable","Authentication store unavailable") return None @app.get("/api/v1/users/me") async def me(request: Request): user_id = auth_user(request) user = store.get_user_by_id(user_id) if not user: raise AppError(401,"unauthorized","Invalid session",{'WWW-Authenticate':'Bearer realm="messenger"'}) return user_json(user) @app.post("/api/v1/chats", status_code=201) async def create_chat(data: CreateChat, request: Request): user_id = auth_user(request) if not data.title.strip(): raise AppError(400,"invalid_request","Invalid title") try: return chat_json(store.create_chat(data.title,data.member_ids,user_id)) except ValueError as exc: if str(exc)=="USER_NOT_FOUND": raise AppError(400,"invalid_request","Unknown member") raise AppError(400,"invalid_request","Invalid members") except SQLAlchemyError: raise AppError(503,"unavailable","Database unavailable") @app.get("/api/v1/chats") async def list_chats(request: Request, limit: int = Query(50,ge=1,le=100), cursor: str|None=None): user_id=auth_user(request) try: rows=store.get_user_chats(user_id,cursor,limit+1) except ValueError: raise AppError(400,"invalid_request","Invalid cursor") more=len(rows)>limit rows=rows[:limit] return {"items":[chat_json(c) for c in rows],"next_cursor":cursor_for_chat(rows[-1]) if more else None} @app.get("/api/v1/chats/{chat_id}") async def get_chat(chat_id: str, request: Request): user_id=auth_user(request) validate_uuid(chat_id) if not store.is_chat_member(chat_id,user_id): raise AppError(404,"not_found","Chat not found") chat=store.get_chat(chat_id) if not chat: raise AppError(404,"not_found","Chat not found") return chat_json(chat) @app.post("/api/v1/chats/{chat_id}/messages", status_code=201) async def create_message(chat_id: str, data: CreateMessage, request: Request): user_id=auth_user(request) validate_uuid(chat_id) if data.text is None or len(data.text)>4000 or len(data.attachment_ids) != len(set(data.attachment_ids)): raise AppError(400,"invalid_request","Invalid message text") for attachment_id in data.attachment_ids: validate_uuid(attachment_id) if not data.text.strip() and not data.attachment_ids: raise AppError(400,"invalid_request","Message must contain text or attachments") key = request.headers.get("Idempotency-Key", "") if not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key, flags=re.ASCII): raise AppError(400,"invalid_request","A valid Idempotency-Key is required") canonical = json.dumps({"text":data.text,"attachment_ids":data.attachment_ids}, ensure_ascii=False, sort_keys=True, separators=(",", ":")) request_hash = hashlib.sha256(canonical.encode("utf-8")).hexdigest() try: msg=store.add_message_idempotent(chat_id,user_id,data.text,data.attachment_ids,key,request_hash) return {"id":msg.id,"chat_id":msg.chat_id,"sender_id":msg.sender_id,"text":msg.text,"created_at":stamp(msg.created_at),"attachment_ids":msg.attachment_ids} except ValueError as exc: if str(exc) == "IDEMPOTENCY_CONFLICT": raise AppError(409,"conflict","Idempotency key was used with a different request") if str(exc) == "EMPTY_MESSAGE": raise AppError(400,"invalid_request","Message must contain text or attachments") if str(exc) == "ATTACHMENT_FAILED": raise AppError(409,"conflict","Failed attachment cannot be added to a message") raise AppError(404,"not_found","Chat not found") except SQLAlchemyError: raise AppError(503,"unavailable","Database unavailable") @app.get("/api/v1/chats/{chat_id}/messages") async def list_messages(chat_id: str, request: Request, limit: int=Query(50,ge=1,le=100), cursor: str|None=None): user_id=auth_user(request) validate_uuid(chat_id) if not store.is_chat_member(chat_id,user_id): raise AppError(404,"not_found","Chat not found") try: rows=store.get_messages(chat_id,cursor,limit+1) except ValueError: raise AppError(400,"invalid_request","Invalid cursor") more=len(rows)>limit rows=rows[:limit] items=[{"id":m.id,"chat_id":m.chat_id,"sender_id":m.sender_id,"text":m.text,"created_at":stamp(m.created_at),"attachment_ids":m.attachment_ids or []} for m in rows] return {"items":items,"next_cursor":cursor_for_message(rows[-1]) if more else None} def attachment_json(row): return {"id":row.id,"chat_id":row.chat_id,"owner_id":row.owner_id,"filename":row.filename, "content_type":row.content_type,"size_bytes":row.size_bytes,"sha256":row.sha256, "status":row.status,"variants":row.variants or [],"error_code":row.error_code, "created_at":stamp(row.created_at),"updated_at":stamp(row.updated_at)} @app.post("/api/v1/chats/{chat_id}/attachments", status_code=202) async def upload_attachment(chat_id: str, request: Request, filename: str = Query(...)): user_id = auth_user(request) validate_uuid(chat_id) if not store.is_chat_member(chat_id, user_id): raise AppError(404, "not_found", "Chat not found") if not 1 <= len(filename) <= 255 or any(ch in filename for ch in "/\\\x00") or any(ord(ch) < 32 or 127 <= ord(ch) < 160 for ch in filename): raise AppError(400, "invalid_request", "Invalid filename") declared = request.headers.get("content-type", "").split(";", 1)[0].lower() if declared not in ("image/png", "image/jpeg"): raise AppError(415, "unsupported_media_type", "Only PNG and JPEG are accepted") max_bytes = 10 * 1024 * 1024 spool = tempfile.SpooledTemporaryFile(max_size=1024 * 1024, mode="w+b") digest = hashlib.sha256() size = 0 try: async for chunk in request.stream(): size += len(chunk) if size > max_bytes: raise AppError(413, "payload_too_large", "Image exceeds 10 MiB") digest.update(chunk) spool.write(chunk) if size == 0: raise AppError(415, "unsupported_media_type", "Empty image") spool.seek(0) try: image = Image.open(spool) fmt = image.format width, height = image.size if width * height > 40_000_000: raise AppError(413, "payload_too_large", "Image exceeds 40 million pixels") if (fmt, declared) not in (("PNG", "image/png"), ("JPEG", "image/jpeg")): raise AppError(415, "unsupported_media_type", "Image content does not match Content-Type") image.verify() except AppError: raise except (UnidentifiedImageError, OSError, Image.DecompressionBombError, Image.DecompressionBombWarning): raise AppError(415, "unsupported_media_type", "Invalid or unsupported image") object_id = str(uuid.uuid4()) object_key = f"original/{object_id}" staging_key = f"staging/{object_id}" job_id = str(uuid.uuid4()) spool.seek(0) await run_in_threadpool(object_store.s3.put_object, Bucket=object_store.S3_BUCKET, Key=staging_key, Body=spool, ContentLength=size, ContentType=declared) row = store.save_attachment(dict(id=object_id, chat_id=chat_id, owner_id=user_id, filename=filename, content_type=declared, size_bytes=size, sha256=digest.hexdigest(), object_key=object_key, staging_key=staging_key, status="queued", job_id=job_id, variants=[], error_code=None)) await run_in_threadpool(jobs.publish, object_id, job_id) return attachment_json(row) except AppError: raise except (BotoCoreError, ClientError): raise AppError(503, "unavailable", "Object storage unavailable") except (redis.exceptions.RedisError, OSError, RuntimeError): raise AppError(503, "unavailable", "Attachment queue unavailable") finally: spool.close() @app.get("/api/v1/attachments/{attachment_id}") async def get_attachment(attachment_id: str, request: Request): user_id = auth_user(request) validate_uuid(attachment_id) row = store.get_attachment(attachment_id, user_id) if not row: raise AppError(404, "not_found", "Attachment not found") return attachment_json(row) @app.get("/api/v1/attachments/{attachment_id}/content") async def download_attachment(attachment_id: str, request: Request, variant: str = "original"): user_id = auth_user(request) validate_uuid(attachment_id) row = store.get_attachment(attachment_id, user_id) if not row: raise AppError(404, "not_found", "Attachment not found") if row.status in ("queued", "processing", "failed"): raise AppError(409, "conflict", "Attachment content is not ready") if variant == "original": key, content_type, length = row.object_key, row.content_type, row.size_bytes elif variant in {item.get("name") for item in row.variants or []}: key = f"variants/{attachment_id}/{variant}" item = next(item for item in row.variants if item.get("name") == variant) content_type, length = item["content_type"], item["size_bytes"] else: raise AppError(404, "not_found", "Attachment variant not found") try: obj = await run_in_threadpool(object_store.s3.get_object, Bucket=object_store.S3_BUCKET, Key=key) except (BotoCoreError, ClientError): raise AppError(503, "unavailable", "Object storage unavailable") body = obj["Body"] def chunks(): try: while True: chunk = body.read(64 * 1024) if not chunk: break yield chunk finally: body.close() return StreamingResponse(chunks(), media_type=content_type, headers={"Content-Length": str(length)})