Files
mtusi2026lab7/src/app.py
T
Yuliiiaaaa c00d245263
Skeleton contracts / contracts (pull_request) Canceled after 0s
Complete lab 7 security infrastructure
2026-11-30 21:23:07 +03:00

711 lines
32 KiB
Python

#!/usr/bin/env python3
import base64
import datetime as dt
import hashlib
import hmac
import json
import os
import secrets
import uuid
import socket
import io
import asyncio
import logging
import time
from contextlib import asynccontextmanager
from typing import List, Optional
import redis.asyncio as redis
from fastapi import FastAPI, Request, Response, HTTPException, Header, Depends, Query
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from psycopg_pool import AsyncConnectionPool
from pydantic import BaseModel, Field, ConfigDict
from PIL import Image
from src.s3_client import upload_file, download_file, configure_client
from src.bao import read_secret
from argon2 import PasswordHasher, Type
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.instrumentation.psycopg import PsycopgInstrumentor
from opentelemetry.instrumentation.redis import RedisInstrumentor
from opentelemetry.instrumentation.botocore import BotocoreInstrumentor
from src.telemetry import get_logger, get_meter, log_event, setup_tracing, shutdown_telemetry
tracer = setup_tracing("messenger-api")
meter = get_meter("messenger.api")
api_logger = get_logger("api")
HTTP_REQUESTS = meter.create_counter(
"http_server_requests", unit="{request}", description="Completed HTTP requests"
)
HTTP_REQUEST_DURATION = meter.create_histogram(
"http_server_request_duration_seconds", unit="s", description="HTTP request duration"
)
PsycopgInstrumentor().instrument()
RedisInstrumentor().instrument()
BotocoreInstrumentor().instrument()
DATABASE_URL = ""
REDIS_URL = ""
BROKER_URL = ""
SESSION_TTL = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
S3_BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
MAX_FILE_SIZE = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
MAX_REQUEST_BYTES = int(os.environ.get("MAX_REQUEST_BYTES", str(11 * 1024 * 1024)))
pool: Optional[AsyncConnectionPool] = None
redis_client: Optional[redis.Redis] = None
broker_client: Optional[redis.Redis] = None
_ARGON2_MEMORY_KIB = max(19456, int(os.getenv("ARGON2_MEMORY_KIB", "19456")))
_ARGON2_ITERATIONS = max(2, int(os.getenv("ARGON2_ITERATIONS", "2")))
_ARGON2_PARALLELISM = max(1, int(os.getenv("ARGON2_PARALLELISM", "1")))
_password_hasher = PasswordHasher(
time_cost=_ARGON2_ITERATIONS,
memory_cost=_ARGON2_MEMORY_KIB,
parallelism=_ARGON2_PARALLELISM,
hash_len=32,
salt_len=16,
type=Type.ID,
)
class UserCreate(BaseModel):
model_config = ConfigDict(extra='forbid')
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 UserOut(BaseModel):
id: str
username: str
display_name: str
created_at: str
class ChatCreate(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 ChatOut(BaseModel):
id: str
title: str
member_ids: List[str]
created_at: str
class MessageCreate(BaseModel):
model_config = ConfigDict(extra='forbid')
text: str = Field(..., max_length=4000)
attachment_ids: List[str] = Field(default_factory=list, max_length=10)
class MessageOut(BaseModel):
id: str
chat_id: str
sender_id: str
text: str
created_at: str
attachment_ids: List[str] = []
class PageResponse(BaseModel):
items: List[dict]
next_cursor: Optional[str]
class SessionResponse(BaseModel):
token: str
token_type: str = "Bearer"
expires_at: str
user: UserOut
def hash_password(password: str) -> str:
"""Create an Argon2id hash with the lab's minimum work parameters."""
return _password_hasher.hash(password)
def verify_password(password: str, stored: str) -> bool:
"""Verify Argon2id hashes and legacy lab6 scrypt hashes during migration."""
try:
if stored.startswith("$argon2id$"):
return _password_hasher.verify(stored, password)
# Legacy lab6 format: salt_hex$scrypt_key_hex. Successful logins are rehashed.
salt_hex, key_hex = stored.split("$", 1)
salt = bytes.fromhex(salt_hex)
expected = bytes.fromhex(key_hex)
actual = hashlib.scrypt(password.encode("utf-8"), salt=salt, n=16384, r=8, p=1, dklen=64)
return hmac.compare_digest(actual, expected)
except (InvalidHashError, VerificationError, VerifyMismatchError, ValueError, TypeError):
return False
def password_needs_rehash(stored: str) -> bool:
if not stored.startswith("$argon2id$"):
return True
try:
return _password_hasher.check_needs_rehash(stored)
except (InvalidHashError, ValueError, TypeError):
return True
def generate_token() -> str:
return secrets.token_urlsafe(48)
def encode_cursor(scope: str, created_at: str) -> str:
payload = json.dumps({"s": scope, "t": created_at}, separators=(",", ":"))
return base64.urlsafe_b64encode(payload.encode("utf-8")).decode("ascii").rstrip("=")
def decode_cursor(cursor: str, expected_scope: str) -> Optional[str]:
try:
pad = "=" * (-len(cursor) % 4)
data = json.loads(base64.urlsafe_b64decode(cursor + pad))
if data.get("s") == expected_scope and isinstance(data.get("t"), str):
return data["t"]
except Exception:
pass
return None
def validate_image(data: bytes, content_type: str) -> str:
if len(data) > MAX_FILE_SIZE:
raise HTTPException(413, "File too large")
try:
img = Image.open(io.BytesIO(data))
img.verify()
except Exception:
raise HTTPException(415, "Invalid image file")
if img.format not in ("PNG", "JPEG"):
raise HTTPException(415, "Only PNG and JPEG are supported")
if img.width * img.height > MAX_PIXELS:
raise HTTPException(413, "Image has too many pixels")
return "image/png" if img.format == "PNG" else "image/jpeg"
@asynccontextmanager
async def lifespan(app: FastAPI):
global pool, redis_client, broker_client, DATABASE_URL, REDIS_URL, BROKER_URL, S3_BUCKET
service_secrets = read_secret(os.environ.get("BAO_SECRET_PATH", "messenger/api"))
DATABASE_URL = service_secrets["database_url"]
REDIS_URL = service_secrets["session_redis_url"]
BROKER_URL = service_secrets["broker_url"]
S3_BUCKET = service_secrets.get("s3_bucket", S3_BUCKET)
configure_client(
service_secrets["s3_endpoint"],
service_secrets["s3_access_key"],
service_secrets["s3_secret_key"],
os.environ.get("S3_CA_FILE", "/run/tls/service-ca.crt"),
service_secrets.get("s3_bucket", S3_BUCKET),
)
pool = AsyncConnectionPool(DATABASE_URL, min_size=2, max_size=20, open=False)
await pool.open()
redis_client = redis.from_url(REDIS_URL, decode_responses=True, socket_connect_timeout=5)
broker_client = redis.from_url(BROKER_URL, decode_responses=True, socket_connect_timeout=5)
async with pool.connection() as conn:
await conn.execute("SELECT 1")
await redis_client.ping()
await broker_client.ping()
try:
yield
finally:
await pool.close()
await redis_client.aclose()
await broker_client.aclose()
shutdown_telemetry()
app = FastAPI(lifespan=lifespan)
@app.middleware("http")
async def enforce_request_size(request: Request, call_next):
raw_length = request.headers.get("content-length")
if raw_length:
try:
if int(raw_length) > MAX_REQUEST_BYTES:
return JSONResponse(
status_code=413,
content={"error": {"code": "payload_too_large", "message": "Request body too large", "request_id": getattr(request.state, "request_id", "unknown")}},
)
except ValueError:
return JSONResponse(status_code=400, content={"error": {"code": "invalid_request", "message": "Invalid Content-Length", "request_id": getattr(request.state, "request_id", "unknown")}})
return await call_next(request)
@app.middleware("http")
async def add_instance_id(request: Request, call_next):
response = await call_next(request)
response.headers["X-Instance-Id"] = os.environ.get("INSTANCE_ID", os.environ.get("HOSTNAME", socket.gethostname()))
return response
@app.middleware("http")
async def add_request_id(request: Request, call_next):
request.state.request_id = uuid.uuid4().hex
response = await call_next(request)
response.headers["X-Request-Id"] = request.state.request_id
return response
@app.middleware("http")
async def collect_http_telemetry(request: Request, call_next):
started = time.perf_counter()
status_code = 500
try:
response = await call_next(request)
status_code = response.status_code
return response
except Exception:
status_code = 500
raise
finally:
elapsed = max(0.0, time.perf_counter() - started)
route = request.scope.get("route")
route_template = getattr(route, "path", None) or "unmatched"
status_class = f"{status_code // 100}xx"
attributes = {
"http_request_method": request.method,
"http_route": route_template,
"http_status_class": status_class,
}
HTTP_REQUESTS.add(1, attributes)
HTTP_REQUEST_DURATION.record(elapsed, attributes)
log_event(
api_logger,
logging.ERROR if status_code >= 500 else logging.INFO,
"http.request.completed",
request_id=getattr(request.state, "request_id", None),
method=request.method,
route=route_template,
status_code=status_code,
status_class=status_class,
duration_ms=round(elapsed * 1000, 3),
)
@app.exception_handler(HTTPException)
async def custom_http_exception_handler(request: Request, exc: HTTPException):
code_map = {
400: "invalid_request", 401: "unauthorized", 404: "not_found",
409: "conflict", 413: "payload_too_large", 415: "unsupported_media_type",
429: "rate_limited", 503: "unavailable", 500: "internal_error"
}
error_code = code_map.get(exc.status_code, "internal_error")
payload = {
"error": {
"code": error_code,
"message": str(exc.detail),
"request_id": getattr(request.state, "request_id", "unknown")
}
}
headers = dict(exc.headers or {})
if exc.status_code == 401:
if request.url.path == "/api/v1/auth/sessions":
headers["WWW-Authenticate"] = 'Basic realm="messenger", charset="UTF-8"'
else:
headers["WWW-Authenticate"] = 'Bearer realm="messenger"'
return JSONResponse(status_code=exc.status_code, content=payload, headers=headers)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
payload = {
"error": {
"code": "invalid_request",
"message": "Invalid request parameters",
"request_id": getattr(request.state, "request_id", "unknown")
}
}
return JSONResponse(status_code=400, content=payload)
# The instrumentation middleware wraps application middleware so request logs
# are emitted while the server span is still current.
FastAPIInstrumentor.instrument_app(app)
# --------------------------------------------------------------------------
# Dependencies
# --------------------------------------------------------------------------
async def get_current_user(request: Request, authorization: Optional[str] = Header(None)) -> dict:
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(401, "Missing or invalid Authorization header")
token = authorization[7:]
user_id = await redis_client.get(f"session:{token}")
if not user_id:
raise HTTPException(401, "Session expired or invalid")
async with pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT id::text, username, display_name, to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') FROM users WHERE id = %s",
(user_id,)
)
row = await cur.fetchone()
if not row:
raise HTTPException(401, "User no longer exists")
return {"id": row[0], "username": row[1], "display_name": row[2], "created_at": row[3]}
# --------------------------------------------------------------------------
# Health
# --------------------------------------------------------------------------
@app.get("/health/live")
async def health_live():
return {"status": "ok"}
@app.get("/health/ready")
async def health_ready():
try:
async with pool.connection() as conn:
await conn.execute("SELECT 1")
await redis_client.ping()
await broker_client.ping()
return {"status": "ok"}
except Exception:
raise HTTPException(503, "Dependencies unavailable")
async def enforce_login_rate_limit(request: Request) -> None:
"""Global per-IP and per-account throttles, shared by API replicas via Redis."""
forwarded = request.headers.get("x-real-ip") or request.headers.get("x-forwarded-for", "")
peer = forwarded.split(",", 1)[0].strip() if forwarded else (request.client.host if request.client else "unknown")
username_key = "unknown"
authorization = request.headers.get("authorization", "")
if authorization.startswith("Basic "):
try:
decoded = base64.b64decode(authorization[6:], validate=True).decode("utf-8")
username_key = decoded.split(":", 1)[0][:64].lower() or "unknown"
except Exception:
pass
# Limit by IP so rotating usernames cannot bypass the control, and by
# account so a distributed source cannot spray one account indefinitely.
ip_digest = hashlib.sha256(peer.encode("utf-8")).hexdigest()
user_digest = hashlib.sha256(username_key.encode("utf-8")).hexdigest()
keys = [f"ratelimit:login:ip:{ip_digest}", f"ratelimit:login:user:{user_digest}"]
request.state.login_rate_keys = keys
retry_after = 1
exceeded = False
for key in keys:
count = await redis_client.incr(key)
if count == 1:
await redis_client.expire(key, 60)
ttl = await redis_client.ttl(key)
if count > 10:
exceeded = True
retry_after = max(retry_after, ttl)
if exceeded:
raise HTTPException(429, "Too many login attempts", headers={"Retry-After": str(retry_after)})
# --------------------------------------------------------------------------
# Auth & Users
# --------------------------------------------------------------------------
@app.post("/api/v1/users", status_code=201, response_model=UserOut)
async def create_user(body: UserCreate):
pwd_hash = hash_password(body.password)
async with pool.connection() as conn:
try:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO users (username, display_name, password_hash) VALUES (%s, %s, %s) RETURNING id::text, username, display_name, to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"')",
(body.username, body.display_name, pwd_hash)
)
row = await cur.fetchone()
await conn.commit()
return {"id": row[0], "username": row[1], "display_name": row[2], "created_at": row[3]}
except Exception as e:
await conn.rollback()
if "unique" in str(e).lower():
raise HTTPException(409, "Username already taken")
raise HTTPException(400, "Invalid user data")
@app.post("/api/v1/auth/sessions", status_code=201, response_model=SessionResponse)
async def login(request: Request, authorization: Optional[str] = Header(None)):
await enforce_login_rate_limit(request)
if not authorization or not authorization.startswith("Basic "):
raise HTTPException(401, "Basic authentication required")
try:
creds = base64.b64decode(authorization[6:], validate=True).decode('utf-8').split(":", 1)
username, password = creds
except Exception:
raise HTTPException(401, "Invalid credentials")
async with pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT id::text, password_hash, username, display_name, to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') FROM users WHERE username = %s", (username,))
row = await cur.fetchone()
if not row or not verify_password(password, row[1]):
raise HTTPException(401, "Invalid credentials")
if password_needs_rehash(row[1]):
new_hash = hash_password(password)
async with pool.connection() as conn:
await conn.execute("UPDATE users SET password_hash = %s WHERE id = %s", (new_hash, row[0]))
await conn.commit()
# Successful authentication clears the two buckets for this request.
await redis_client.delete(*(getattr(request.state, "login_rate_keys", []) or []))
token = generate_token()
await redis_client.setex(f"session:{token}", SESSION_TTL, row[0])
expires = (dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=SESSION_TTL)).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
return {
"token": token, "token_type": "Bearer", "expires_at": expires,
"user": {"id": row[0], "username": row[2], "display_name": row[3], "created_at": row[4]}
}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def logout(authorization: Optional[str] = Header(None)):
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(401, "Missing Authorization header")
token = authorization[7:]
deleted = await redis_client.delete(f"session:{token}")
if not deleted:
raise HTTPException(401, "Session invalid or already logged out")
return Response(status_code=204)
@app.get("/api/v1/users/me", response_model=UserOut)
async def get_me(user: dict = Depends(get_current_user)):
return user
# --------------------------------------------------------------------------
# Chats
# --------------------------------------------------------------------------
@app.post("/api/v1/chats", status_code=201, response_model=ChatOut)
async def create_chat(body: ChatCreate, user: dict = Depends(get_current_user)):
if user["id"] not in body.member_ids:
raise HTTPException(400, "Caller must be a member of the chat")
unique_members = list(set(body.member_ids))
if len(unique_members) != len(body.member_ids):
raise HTTPException(400, "Duplicate member IDs")
async with pool.connection() as conn:
try:
async with conn.transaction():
async with conn.cursor() as cur:
await cur.execute("SELECT id::text FROM users WHERE id = ANY(%s::uuid[])", (unique_members,))
found_users = {r[0] for r in await cur.fetchall()}
if len(found_users) != len(unique_members):
raise HTTPException(400, "One or more members do not exist")
await cur.execute("INSERT INTO chats (title) VALUES (%s) RETURNING id::text, title, to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"')", (body.title,))
chat_row = await cur.fetchone()
chat_id = chat_row[0]
for uid in unique_members:
await cur.execute("INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)", (chat_id, uid))
return {"id": chat_id, "title": chat_row[1], "member_ids": unique_members, "created_at": chat_row[2]}
except HTTPException:
raise
except Exception:
raise HTTPException(500, "Failed to create chat")
@app.get("/api/v1/chats")
async def list_chats(limit: int = 50, cursor: Optional[str] = None, user: dict = Depends(get_current_user)):
if not (1 <= limit <= 100):
raise HTTPException(400, "Invalid limit")
cursor_ts = decode_cursor(cursor, "chats") if cursor else None
if cursor and not cursor_ts:
raise HTTPException(400, "Invalid cursor")
async with pool.connection() as conn:
async with conn.cursor() as cur:
if cursor_ts:
await cur.execute("SELECT c.id::text, c.title, to_char(c.created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') FROM chats c JOIN chat_members cm ON c.id = cm.chat_id WHERE cm.user_id = %s AND c.created_at > %s ORDER BY c.created_at ASC LIMIT %s", (user["id"], cursor_ts, limit + 1))
else:
await cur.execute("SELECT c.id::text, c.title, to_char(c.created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') FROM chats c JOIN chat_members cm ON c.id = cm.chat_id WHERE cm.user_id = %s ORDER BY c.created_at ASC LIMIT %s", (user["id"], limit + 1))
rows = await cur.fetchall()
chat_ids = [r[0] for r in rows[:limit]]
members_map = {}
if chat_ids:
await cur.execute("SELECT chat_id::text, user_id::text FROM chat_members WHERE chat_id = ANY(%s::uuid[])", (chat_ids,))
for cid, uid in await cur.fetchall():
members_map.setdefault(cid, []).append(uid)
items = [{"id": r[0], "title": r[1], "created_at": r[2], "member_ids": members_map.get(r[0], [])} for r in rows[:limit]]
next_cursor = encode_cursor("chats", items[-1]["created_at"]) if len(rows) > limit else None
return {"items": items, "next_cursor": next_cursor}
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(chat_id: str, user: dict = Depends(get_current_user)):
async with pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, user["id"]))
if not await cur.fetchone():
raise HTTPException(404, "Chat not found")
await cur.execute("SELECT id::text, title, to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') FROM chats WHERE id = %s", (chat_id,))
chat = await cur.fetchone()
await cur.execute("SELECT user_id::text FROM chat_members WHERE chat_id = %s", (chat_id,))
members = [r[0] for r in await cur.fetchall()]
return {"id": chat[0], "title": chat[1], "created_at": chat[2], "member_ids": members}
# --------------------------------------------------------------------------
# Attachments
# --------------------------------------------------------------------------
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
async def upload_attachment(
chat_id: str,
request: Request,
filename: str = Query(..., min_length=1, max_length=255),
user: dict = Depends(get_current_user)
):
async with pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, user["id"]))
if not await cur.fetchone():
raise HTTPException(404, "Chat not found")
data = await request.body()
if len(data) == 0:
raise HTTPException(400, "Empty file")
content_type_header = request.headers.get("content-type", "")
real_content_type = await asyncio.to_thread(validate_image, data, content_type_header)
sha256 = hashlib.sha256(data).hexdigest()
file_id = str(uuid.uuid4())
ext = "png" if real_content_type == "image/png" else "jpg"
s3_key = f"original/{chat_id}/{file_id}.{ext}"
await asyncio.to_thread(upload_file, s3_key, data, real_content_type)
async with pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, s3_key, status) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'queued') RETURNING id::text, filename, content_type, size_bytes, sha256, status, to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"'), to_char(updated_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"')",
(file_id, chat_id, user["id"], filename, real_content_type, len(data), sha256, s3_key)
)
row = await cur.fetchone()
await conn.commit()
if os.environ.get("SIMULATE_CRASH") == "api":
log_event(api_logger, logging.ERROR, "attachment.crash_simulated", stage="before_publish")
os._exit(1)
job = {"attachment_id": file_id, "s3_key": s3_key}
await broker_client.xadd("attachment_jobs", {"job": json.dumps(job)})
return {
"id": row[0], "chat_id": chat_id, "owner_id": user["id"], "filename": row[1],
"content_type": row[2], "size_bytes": row[3], "sha256": row[4],
"status": "queued", "created_at": row[6], "updated_at": row[7],
"error_code": None, "variants": []
}
@app.get("/api/v1/attachments/{attachment_id}")
async def get_attachment_meta(attachment_id: str, user: dict = Depends(get_current_user)):
async with pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT a.id::text, a.chat_id::text, a.owner_id::text, a.filename, a.content_type, a.size_bytes, a.sha256, a.status, to_char(a.created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"'), to_char(a.updated_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"'), a.error_code, a.variants "
"FROM attachments a JOIN chat_members cm ON a.chat_id = cm.chat_id "
"WHERE a.id = %s AND cm.user_id = %s",
(attachment_id, user["id"])
)
row = await cur.fetchone()
if not row:
raise HTTPException(404, "Attachment not found")
return {
"id": row[0], "chat_id": row[1], "owner_id": row[2], "filename": row[3],
"content_type": row[4], "size_bytes": row[5], "sha256": row[6],
"status": row[7], "created_at": row[8], "updated_at": row[9],
"error_code": row[10], "variants": row[11] or []
}
@app.get("/api/v1/attachments/{attachment_id}/content")
async def download_attachment(attachment_id: str, variant: str = "original", user: dict = Depends(get_current_user)):
async with pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT a.s3_key, a.content_type, a.filename, a.status FROM attachments a "
"JOIN chat_members cm ON a.chat_id = cm.chat_id "
"WHERE a.id = %s AND cm.user_id = %s",
(attachment_id, user["id"])
)
row = await cur.fetchone()
if not row:
raise HTTPException(404, "Attachment not found")
s3_key, orig_content_type, filename, status = row
if status != "ready":
raise HTTPException(409, "Attachment is not ready")
# Определяем правильный s3_key и content_type в зависимости от варианта
if variant == "original":
content_type = orig_content_type
elif variant in ("thumbnail", "crop"):
content_type = "image/jpeg"
s3_key = f"variants/{attachment_id}/{variant}.jpg"
elif variant == "optimized":
content_type = "image/webp"
s3_key = f"variants/{attachment_id}/optimized.webp"
else:
raise HTTPException(404, "Variant not found")
try:
data = await asyncio.to_thread(download_file, s3_key)
except Exception:
log_event(api_logger, logging.ERROR, "attachment.content_missing", variant=variant)
raise HTTPException(404, f"File content missing in S3 for variant {variant}")
return Response(
content=data,
media_type=content_type,
headers={"Content-Disposition": f'attachment; filename="{filename}"'}
)
# --------------------------------------------------------------------------
# Messages
# --------------------------------------------------------------------------
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201, response_model=MessageOut)
async def create_message(
chat_id: str,
body: MessageCreate,
user: dict = Depends(get_current_user),
idempotency_key: str = Header(None, alias="Idempotency-Key")
):
if not idempotency_key:
raise HTTPException(400, "Idempotency-Key is required")
if not body.text.strip() and not body.attachment_ids:
raise HTTPException(400, "Message must have either text or attachments")
req_hash = hashlib.sha256(body.text.encode('utf-8')).hexdigest()
new_msg_id = str(uuid.uuid4())
attachments = body.attachment_ids if hasattr(body, 'attachment_ids') and body.attachment_ids else []
async with pool.connection() as conn:
async with conn.transaction():
async with conn.cursor() as cur:
await cur.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, user["id"]))
if not await cur.fetchone():
raise HTTPException(404, "Chat not found")
await cur.execute(
"INSERT INTO idempotency_keys (key, user_id, request_hash, message_id) "
"VALUES (%s, %s, %s, %s) ON CONFLICT DO NOTHING",
(idempotency_key, user["id"], req_hash, new_msg_id)
)
if cur.rowcount == 1:
await cur.execute(
"INSERT INTO messages (id, chat_id, sender_id, text, attachment_ids) "
"VALUES (%s, %s, %s, %s, %s) "
"RETURNING id::text, chat_id::text, sender_id::text, text, attachment_ids::text[], to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"')",
(new_msg_id, chat_id, user["id"], body.text, attachments)
)
row = await cur.fetchone()
return {"id": row[0], "chat_id": row[1], "sender_id": row[2], "text": row[3], "attachment_ids": row[4] or [], "created_at": row[5]}
else:
await cur.execute(
"SELECT request_hash, message_id FROM idempotency_keys WHERE key = %s AND user_id = %s",
(idempotency_key, user["id"])
)
key_row = await cur.fetchone()
if key_row[0] != req_hash:
raise HTTPException(409, "Idempotency key reused with different body")
await cur.execute(
"SELECT id::text, chat_id::text, sender_id::text, text, attachment_ids::text[], to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') "
"FROM messages WHERE id = %s",
(key_row[1],)
)
row = await cur.fetchone()
return {"id": row[0], "chat_id": row[1], "sender_id": row[2], "text": row[3], "attachment_ids": row[4] or [], "created_at": row[5]}
@app.get("/api/v1/chats/{chat_id}/messages", response_model=PageResponse)
async def list_messages(chat_id: str, limit: int = 50, cursor: Optional[str] = None, user: dict = Depends(get_current_user)):
if not (1 <= limit <= 100):
raise HTTPException(400, "Invalid limit")
scope = f"chat:{chat_id}"
cursor_ts = decode_cursor(cursor, scope) if cursor else None
if cursor and not cursor_ts:
raise HTTPException(400, "Invalid cursor")
async with pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, user["id"]))
if not await cur.fetchone():
raise HTTPException(404, "Chat not found")
query = "SELECT id::text, chat_id::text, sender_id::text, text, attachment_ids::text[], to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') FROM messages WHERE chat_id = %s "
params = [chat_id]
if cursor_ts:
query += "AND created_at > %s "
params.append(cursor_ts)
query += "ORDER BY created_at ASC LIMIT %s"
params.append(limit + 1)
await cur.execute(query, tuple(params))
rows = await cur.fetchall()
items = []
for r in rows[:limit]:
items.append({
"id": r[0], "chat_id": r[1], "sender_id": r[2], "text": r[3],
"attachment_ids": r[4] or [],
"created_at": r[5]
})
next_cursor = encode_cursor(scope, items[-1]["created_at"]) if len(rows) > limit else None
return {"items": items, "next_cursor": next_cursor}