Выполнение 4 лабораторной на оценку 3
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""MTUSI Messenger service package."""
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
"""scrypt password KDF and opaque, cryptographically random bearer tokens."""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import secrets
|
||||
|
||||
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
salt = secrets.token_bytes(16)
|
||||
digest = hashlib.scrypt(password.encode("utf-8"), salt=salt, n=2**14, r=8, p=1, dklen=32)
|
||||
return "scrypt$16384$8$1$" + base64.urlsafe_b64encode(salt + digest).decode("ascii")
|
||||
|
||||
|
||||
def verify_password(password: str, encoded: str) -> bool:
|
||||
try:
|
||||
scheme, n, r, p, raw = encoded.split("$", 4)
|
||||
if scheme != "scrypt":
|
||||
return False
|
||||
data = base64.urlsafe_b64decode(raw.encode("ascii"))
|
||||
salt, expected = data[:16], data[16:]
|
||||
actual = hashlib.scrypt(password.encode("utf-8"), salt=salt, n=int(n), r=int(r), p=int(p), dklen=len(expected))
|
||||
return hmac.compare_digest(actual, expected)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def new_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
@@ -0,0 +1,97 @@
|
||||
"""PostgreSQL schema and bounded connection pool."""
|
||||
import os
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import (Column, DateTime, ForeignKey, Index, String, Text, Integer, JSON,
|
||||
UniqueConstraint, create_engine)
|
||||
from sqlalchemy.orm import declarative_base, relationship, sessionmaker
|
||||
|
||||
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://postgres:postgres@db:5432/messenger")
|
||||
engine = create_engine(DATABASE_URL, pool_size=5, max_overflow=5, pool_timeout=5,
|
||||
pool_pre_ping=True, connect_args={"connect_timeout": 5,
|
||||
"options": "-c statement_timeout=5000"})
|
||||
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
|
||||
Base = declarative_base()
|
||||
now = lambda: datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||
username = Column(String(32), nullable=False)
|
||||
display_name = Column(String(100), nullable=False)
|
||||
password_hash = Column(String(255), nullable=False)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=now)
|
||||
__table_args__ = (Index("ix_users_username", "username", unique=True),)
|
||||
|
||||
|
||||
class Session(Base):
|
||||
__tablename__ = "sessions"
|
||||
id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||
token = Column(String(255), nullable=False)
|
||||
user_id = Column(String, ForeignKey("users.id"), nullable=False)
|
||||
expires_at = Column(DateTime(timezone=True), nullable=False)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=now)
|
||||
user = relationship("User")
|
||||
__table_args__ = (Index("ix_sessions_token", "token", unique=True),)
|
||||
|
||||
|
||||
class Chat(Base):
|
||||
__tablename__ = "chats"
|
||||
id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||
title = Column(String(100), nullable=False)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=now)
|
||||
members = relationship("ChatMember", back_populates="chat", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class ChatMember(Base):
|
||||
__tablename__ = "chat_members"
|
||||
id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||
chat_id = Column(String, ForeignKey("chats.id"), nullable=False)
|
||||
user_id = Column(String, ForeignKey("users.id"), nullable=False)
|
||||
chat = relationship("Chat", back_populates="members")
|
||||
user = relationship("User")
|
||||
__table_args__ = (UniqueConstraint("chat_id", "user_id", name="uq_chat_member"),
|
||||
Index("ix_chat_members_user_chat", "user_id", "chat_id"))
|
||||
|
||||
|
||||
class Message(Base):
|
||||
__tablename__ = "messages"
|
||||
id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||
chat_id = Column(String, ForeignKey("chats.id"), nullable=False)
|
||||
sender_id = Column(String, ForeignKey("users.id"), nullable=False)
|
||||
text = Column(Text, nullable=False)
|
||||
attachment_ids = Column(JSON, nullable=False, default=list)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=now)
|
||||
chat = relationship("Chat")
|
||||
sender = relationship("User")
|
||||
__table_args__ = (Index("ix_messages_chat_created_id", "chat_id", "created_at", "id"),)
|
||||
|
||||
|
||||
class Attachment(Base):
|
||||
__tablename__ = "attachments"
|
||||
id = Column(String, primary_key=True)
|
||||
chat_id = Column(String, ForeignKey("chats.id"), nullable=False, index=True)
|
||||
owner_id = Column(String, ForeignKey("users.id"), nullable=False)
|
||||
filename = Column(String(255), nullable=False)
|
||||
content_type = Column(String(32), nullable=False)
|
||||
size_bytes = Column(Integer, nullable=False)
|
||||
sha256 = Column(String(64), nullable=False)
|
||||
object_key = Column(String(128), nullable=False, unique=True)
|
||||
status = Column(String(16), nullable=False, default="ready")
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=now)
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False, default=now)
|
||||
|
||||
|
||||
class MessageIdempotency(Base):
|
||||
__tablename__ = "message_idempotency"
|
||||
id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||
user_id = Column(String, ForeignKey("users.id"), nullable=False)
|
||||
method = Column(String(8), nullable=False)
|
||||
chat_path = Column(String(80), nullable=False)
|
||||
key = Column(String(128), nullable=False)
|
||||
request_hash = Column(String(64), nullable=False)
|
||||
message_id = Column(String, ForeignKey("messages.id"), nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=now)
|
||||
__table_args__ = (UniqueConstraint("user_id", "method", "chat_path", "key",
|
||||
name="uq_idempotency_scope"),)
|
||||
+361
@@ -0,0 +1,361 @@
|
||||
"""Lab 4 REST API: shared messenger state and private S3 attachments."""
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
import hashlib
|
||||
import tempfile
|
||||
import re as regex
|
||||
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
|
||||
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
|
||||
|
||||
|
||||
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="4.0.0")
|
||||
INSTANCE_ID = str(uuid.uuid4())
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_headers(request: Request, call_next):
|
||||
request.state.request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request.state.request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
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)
|
||||
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")
|
||||
|
||||
|
||||
@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):
|
||||
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")
|
||||
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":"ready","variants":[],"error_code":None,
|
||||
"created_at":stamp(row.created_at),"updated_at":stamp(row.updated_at)}
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=201)
|
||||
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}"
|
||||
spool.seek(0)
|
||||
await run_in_threadpool(object_store.s3.put_object, Bucket=object_store.S3_BUCKET,
|
||||
Key=object_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, status="ready"))
|
||||
return attachment_json(row)
|
||||
except AppError:
|
||||
raise
|
||||
except (BotoCoreError, ClientError):
|
||||
raise AppError(503, "unavailable", "Object storage 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 variant != "original":
|
||||
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=row.object_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=row.content_type, headers={"Content-Length": str(row.size_bytes)})
|
||||
@@ -0,0 +1,28 @@
|
||||
from pydantic import BaseModel, Field, ConfigDict
|
||||
from typing import List
|
||||
|
||||
|
||||
# ==================== REQUEST MODELS ====================
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=False)
|
||||
username: str = Field(..., pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(..., min_length=1, max_length=100)
|
||||
password: str = Field(..., min_length=12, max_length=128)
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str = Field(..., min_length=1, max_length=100)
|
||||
member_ids: List[str] = Field(..., min_length=1, max_length=100)
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
text: str = Field(..., max_length=4000)
|
||||
attachment_ids: List[str] = Field(default_factory=list, max_length=10)
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Private S3-compatible object storage client."""
|
||||
import os
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
|
||||
S3_BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
s3 = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=os.environ.get("S3_ENDPOINT", "http://minio:9000"),
|
||||
aws_access_key_id=os.environ["S3_ACCESS_KEY"],
|
||||
aws_secret_access_key=os.environ["S3_SECRET_KEY"],
|
||||
region_name=os.environ.get("S3_REGION", "us-east-1"),
|
||||
config=Config(connect_timeout=3, read_timeout=10, retries={"max_attempts": 2}),
|
||||
)
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Redis TTL cache for active sessions; PostgreSQL remains authoritative."""
|
||||
import os
|
||||
import socket
|
||||
from urllib.parse import urlparse
|
||||
from redis import Redis
|
||||
from redis.backoff import NoBackoff
|
||||
from redis.exceptions import RedisError
|
||||
from redis.retry import Retry
|
||||
|
||||
CACHE_URL = os.getenv("CACHE_URL", "redis://redis:6379/0")
|
||||
_cache_address = urlparse(CACHE_URL)
|
||||
_cache_host = _cache_address.hostname or "redis"
|
||||
_cache_port = _cache_address.port or (6380 if _cache_address.scheme == "rediss" else 6379)
|
||||
try:
|
||||
_cache_ips = tuple(dict.fromkeys(item[4][0] for item in socket.getaddrinfo(
|
||||
_cache_host, _cache_port, type=socket.SOCK_STREAM)))
|
||||
except OSError:
|
||||
_cache_ips = (_cache_host,)
|
||||
client = Redis.from_url(CACHE_URL, decode_responses=True,
|
||||
socket_connect_timeout=0.2, socket_timeout=0.2,
|
||||
health_check_interval=15, retry=Retry(NoBackoff(), 0))
|
||||
|
||||
|
||||
class CacheUnavailable(Exception):
|
||||
"""The required session cache cannot be reached within its short timeout."""
|
||||
|
||||
|
||||
def _check_port():
|
||||
# Fail fast when the Redis container is stopped. redis-py may otherwise
|
||||
# spend several seconds cycling through connection retries on Docker DNS.
|
||||
try:
|
||||
for address in _cache_ips:
|
||||
try:
|
||||
with socket.create_connection((address, _cache_port), timeout=0.2):
|
||||
return
|
||||
except OSError:
|
||||
continue
|
||||
raise OSError("Redis is not accepting connections")
|
||||
except OSError as exc:
|
||||
raise CacheUnavailable from exc
|
||||
|
||||
|
||||
def get(token: str):
|
||||
try:
|
||||
_check_port()
|
||||
return client.get("session:" + token)
|
||||
except RedisError as exc:
|
||||
raise CacheUnavailable from exc
|
||||
|
||||
|
||||
def put(token: str, user_id: str, ttl_seconds: int):
|
||||
try:
|
||||
_check_port()
|
||||
client.set("session:" + token, user_id, ex=max(1, ttl_seconds))
|
||||
except RedisError as exc:
|
||||
raise CacheUnavailable from exc
|
||||
|
||||
|
||||
def delete(token: str):
|
||||
try:
|
||||
_check_port()
|
||||
client.delete("session:" + token)
|
||||
except RedisError as exc:
|
||||
raise CacheUnavailable from exc
|
||||
|
||||
|
||||
def ping():
|
||||
try:
|
||||
_check_port()
|
||||
return bool(client.ping())
|
||||
except RedisError as exc:
|
||||
raise CacheUnavailable from exc
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
"""Small repository layer; each operation owns and closes its DB transaction."""
|
||||
import base64
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timezone, timedelta
|
||||
import math
|
||||
from sqlalchemy import and_, or_, select, update
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.orm import selectinload
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from .database import User, Session as SessionRow, Chat, ChatMember, Message, MessageIdempotency, Attachment, SessionLocal
|
||||
from .auth import hash_password, verify_password, new_token, SESSION_TTL_SECONDS
|
||||
from . import session_cache
|
||||
|
||||
|
||||
class Store:
|
||||
def add_user(self, username, display_name, password):
|
||||
with SessionLocal() as db:
|
||||
user = User(username=username, display_name=display_name, password_hash=hash_password(password))
|
||||
db.add(user)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise ValueError("USERNAME_EXISTS")
|
||||
db.refresh(user)
|
||||
return user
|
||||
|
||||
def get_user_by_id(self, user_id):
|
||||
with SessionLocal() as db:
|
||||
return db.query(User).filter(User.id == user_id).first()
|
||||
|
||||
def verify_user_password(self, username, password):
|
||||
with SessionLocal() as db:
|
||||
user = db.query(User).filter(User.username == username).first()
|
||||
# A fixed dummy hash is avoided here; the public contract only requires
|
||||
# identical response status and challenge for unknown users/bad passwords.
|
||||
if not user or not verify_password(password, user.password_hash):
|
||||
return None
|
||||
return user
|
||||
|
||||
def create_session(self, user_id):
|
||||
with SessionLocal() as db:
|
||||
row = SessionRow(token=new_token(), user_id=user_id,
|
||||
expires_at=datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS))
|
||||
db.add(row)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
try:
|
||||
session_cache.put(row.token, row.user_id, SESSION_TTL_SECONDS)
|
||||
except session_cache.CacheUnavailable:
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
raise
|
||||
return row
|
||||
|
||||
def get_session_by_token(self, token):
|
||||
cached_user_id = session_cache.get(token)
|
||||
if cached_user_id:
|
||||
return (cached_user_id, None)
|
||||
with SessionLocal() as db:
|
||||
row = db.query(SessionRow).filter(SessionRow.token == token,
|
||||
SessionRow.expires_at > datetime.now(timezone.utc)).first()
|
||||
if not row:
|
||||
return None
|
||||
remaining = math.ceil((row.expires_at - datetime.now(timezone.utc)).total_seconds())
|
||||
session_cache.put(row.token, row.user_id, remaining)
|
||||
return (row.user_id, row.expires_at)
|
||||
|
||||
def delete_session(self, token):
|
||||
# Require successful cache invalidation before reporting a completed logout.
|
||||
session_cache.delete(token)
|
||||
with SessionLocal() as db:
|
||||
row = db.query(SessionRow).filter(SessionRow.token == token).first()
|
||||
if row:
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
return True
|
||||
return False
|
||||
|
||||
def create_chat(self, title, member_ids, creator_id):
|
||||
if creator_id not in member_ids:
|
||||
raise ValueError("CREATOR_NOT_MEMBER")
|
||||
if len(member_ids) != len(set(member_ids)):
|
||||
raise ValueError("DUPLICATE_MEMBER")
|
||||
with SessionLocal() as db:
|
||||
users = db.query(User.id).filter(User.id.in_(member_ids)).all()
|
||||
if len(users) != len(member_ids):
|
||||
raise ValueError("USER_NOT_FOUND")
|
||||
chat = Chat(title=title)
|
||||
chat.members = [ChatMember(user_id=mid) for mid in member_ids]
|
||||
db.add(chat)
|
||||
db.commit()
|
||||
db.refresh(chat)
|
||||
list(chat.members)
|
||||
return chat
|
||||
|
||||
def get_chat(self, chat_id):
|
||||
with SessionLocal() as db:
|
||||
return db.query(Chat).options(selectinload(Chat.members)).filter(Chat.id == chat_id).first()
|
||||
|
||||
def get_user_chats(self, user_id, cursor=None, limit=50):
|
||||
with SessionLocal() as db:
|
||||
query = db.query(Chat).options(selectinload(Chat.members)).join(ChatMember).filter(ChatMember.user_id == user_id)
|
||||
if cursor:
|
||||
decoded = decode_cursor(cursor, "chats")
|
||||
query = query.filter(or_(Chat.created_at > decoded[0], and_(Chat.created_at == decoded[0], Chat.id > decoded[1])))
|
||||
rows = query.order_by(Chat.created_at, Chat.id).limit(limit).all()
|
||||
for row in rows:
|
||||
list(row.members)
|
||||
return rows
|
||||
|
||||
def is_chat_member(self, chat_id, user_id):
|
||||
with SessionLocal() as db:
|
||||
return db.query(ChatMember.id).filter(ChatMember.chat_id == chat_id, ChatMember.user_id == user_id).first() is not None
|
||||
|
||||
def add_message(self, chat_id, sender_id, text):
|
||||
with SessionLocal() as db:
|
||||
if not db.query(Chat.id).filter(Chat.id == chat_id).first():
|
||||
raise ValueError("CHAT_NOT_FOUND")
|
||||
if not db.query(ChatMember.id).filter(ChatMember.chat_id == chat_id, ChatMember.user_id == sender_id).first():
|
||||
raise ValueError("NOT_MEMBER")
|
||||
msg = Message(chat_id=chat_id, sender_id=sender_id, text=text)
|
||||
db.add(msg)
|
||||
db.commit()
|
||||
db.refresh(msg)
|
||||
return msg
|
||||
|
||||
def add_message_idempotent(self, chat_id, sender_id, text, attachment_ids, key, request_hash):
|
||||
"""Claim a scoped key and create its message in the same DB transaction."""
|
||||
with SessionLocal() as db:
|
||||
if not db.query(ChatMember.id).filter(ChatMember.chat_id == chat_id,
|
||||
ChatMember.user_id == sender_id).first():
|
||||
raise ValueError("CHAT_NOT_FOUND")
|
||||
if not text.strip() and not attachment_ids:
|
||||
raise ValueError("EMPTY_MESSAGE")
|
||||
if attachment_ids:
|
||||
rows = db.query(Attachment).filter(Attachment.id.in_(attachment_ids),
|
||||
Attachment.chat_id == chat_id).all()
|
||||
if len(rows) != len(attachment_ids):
|
||||
raise ValueError("ATTACHMENT_NOT_FOUND")
|
||||
scope = dict(user_id=sender_id, method="POST", chat_path=f"/api/v1/chats/{chat_id}/messages", key=key)
|
||||
claim = insert(MessageIdempotency).values(**scope, request_hash=request_hash,
|
||||
message_id=None).on_conflict_do_nothing(
|
||||
constraint="uq_idempotency_scope").returning(MessageIdempotency.id)
|
||||
claimed = db.execute(claim).scalar_one_or_none()
|
||||
if claimed is None:
|
||||
record = db.execute(select(MessageIdempotency).filter_by(**scope)).scalar_one()
|
||||
if record.request_hash != request_hash:
|
||||
raise ValueError("IDEMPOTENCY_CONFLICT")
|
||||
msg = db.get(Message, record.message_id)
|
||||
if msg is None:
|
||||
raise RuntimeError("Idempotency record has no message")
|
||||
return msg
|
||||
msg = Message(chat_id=chat_id, sender_id=sender_id, text=text, attachment_ids=attachment_ids)
|
||||
db.add(msg)
|
||||
db.flush()
|
||||
db.execute(update(MessageIdempotency).where(MessageIdempotency.id == claimed).values(message_id=msg.id))
|
||||
db.commit()
|
||||
db.refresh(msg)
|
||||
return msg
|
||||
|
||||
def get_messages(self, chat_id, cursor=None, limit=50):
|
||||
with SessionLocal() as db:
|
||||
query = db.query(Message).filter(Message.chat_id == chat_id)
|
||||
if cursor:
|
||||
created, message_id = decode_cursor(cursor, chat_id)
|
||||
query = query.filter(or_(Message.created_at > created,
|
||||
and_(Message.created_at == created, Message.id > message_id)))
|
||||
return query.order_by(Message.created_at, Message.id).limit(limit).all()
|
||||
|
||||
def save_attachment(self, attachment):
|
||||
with SessionLocal() as db:
|
||||
row = Attachment(**attachment)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return row
|
||||
|
||||
def get_attachment(self, attachment_id, user_id):
|
||||
with SessionLocal() as db:
|
||||
return db.query(Attachment).join(ChatMember, ChatMember.chat_id == Attachment.chat_id).filter(
|
||||
Attachment.id == attachment_id, ChatMember.user_id == user_id).first()
|
||||
|
||||
|
||||
def encode_cursor(resource, created_at, item_id):
|
||||
raw = json.dumps([resource, created_at.isoformat(), item_id], separators=(",", ":")).encode()
|
||||
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(cursor, resource):
|
||||
try:
|
||||
data = json.loads(base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)))
|
||||
if data[0] != resource:
|
||||
raise ValueError
|
||||
return datetime.fromisoformat(data[1]), data[2]
|
||||
except Exception:
|
||||
raise ValueError("INVALID_CURSOR")
|
||||
|
||||
|
||||
def cursor_for_chat(chat):
|
||||
return encode_cursor("chats", chat.created_at, chat.id)
|
||||
|
||||
|
||||
def cursor_for_message(message):
|
||||
return encode_cursor(message.chat_id, message.created_at, message.id)
|
||||
|
||||
|
||||
store = Store()
|
||||
Reference in New Issue
Block a user