Files
mtusi2026lab4/app.py
2026-11-22 17:26:57 +03:00

542 lines
25 KiB
Python

import base64
import hashlib
import io
import os
import secrets
import time
import uuid
from datetime import datetime, timedelta, timezone
from urllib.parse import parse_qs
import bcrypt
import boto3
import psycopg
from botocore.config import Config
from fastapi import FastAPI, Request, Response
from fastapi.responses import JSONResponse, StreamingResponse
from PIL import Image, ImageFile
from psycopg.rows import dict_row
APP_INSTANCE = os.environ.get("INSTANCE_ID", secrets.token_hex(8))
DB_URL = os.environ.get("DATABASE_URL", "postgresql://messenger:messenger@postgres:5432/messenger")
SESSION_TTL = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
MAX_UPLOAD = int(os.environ.get("MAX_UPLOAD_BYTES", str(10 * 1024 * 1024)))
MAX_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
S3_ENDPOINT = os.environ.get("S3_ENDPOINT", "http://s3:9000")
S3_BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
s3 = boto3.client(
"s3",
endpoint_url=S3_ENDPOINT,
region_name=os.environ.get("S3_REGION", "us-east-1"),
aws_access_key_id=os.environ["S3_ACCESS_KEY_ID"],
aws_secret_access_key=os.environ["S3_SECRET_ACCESS_KEY"],
config=Config(s3={"addressing_style": "path"}, retries={"max_attempts": 3}),
)
app = FastAPI(docs_url=None, redoc_url=None)
def utcnow():
return datetime.now(timezone.utc)
def iso(dt):
return dt.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
def db():
return psycopg.connect(DB_URL, row_factory=dict_row)
def ensure_error(request_id, code, message, status):
return JSONResponse(
{"error": {"code": code, "message": message, "request_id": request_id}},
status_code=status,
headers={"X-Request-Id": request_id, "X-Instance-Id": APP_INSTANCE},
)
def request_id(request):
return request.headers.get("X-Request-Id") or str(uuid.uuid4())
def bearer_user(request):
auth = request.headers.get("Authorization", "")
if not auth.startswith("Bearer ") or not auth[7:].strip():
return None
token = auth[7:].strip()
with db() as conn:
row = conn.execute(
"""SELECT u.id,u.username,u.display_name,u.created_at
FROM sessions s JOIN users u ON u.id=s.user_id
WHERE s.token=%s AND s.expires_at>%s""",
(token, utcnow()),
).fetchone()
return row
def require_user(request):
rid = request_id(request)
user = bearer_user(request)
if not user:
response = ensure_error(rid, "unauthorized", "Требуется действительная сессия", 401)
response.headers["WWW-Authenticate"] = 'Bearer realm="messenger"'
return rid, None, response
return rid, user, None
def public_user(row):
return {"id": str(row["id"]), "username": row["username"], "display_name": row["display_name"], "created_at": iso(row["created_at"])}
def is_member(conn, chat_id, user_id):
return conn.execute("SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s", (chat_id, user_id)).fetchone() is not None
@app.middleware("http")
async def response_headers(request, call_next):
rid = request.headers.get("X-Request-Id") or str(uuid.uuid4())
response = await call_next(request)
response.headers["X-Request-Id"] = rid
response.headers.setdefault("X-Instance-Id", APP_INSTANCE)
return response
@app.get("/health/live")
async def live():
return {"status": "ok"}
@app.get("/health/ready")
async def ready():
rid = str(uuid.uuid4())
try:
with db() as conn:
conn.execute("SELECT 1").fetchone()
s3.head_bucket(Bucket=S3_BUCKET)
return {"status": "ok"}
except Exception:
return ensure_error(rid, "unavailable", "Зависимость недоступна", 503)
@app.post("/api/v1/users")
async def create_user(request: Request):
rid = request_id(request)
try:
body = await request.json()
except Exception:
return ensure_error(rid, "invalid_request", "Некорректный JSON", 400)
if not isinstance(body, dict) or set(body) != {"username", "display_name", "password"}:
return ensure_error(rid, "invalid_request", "Неверные поля запроса", 400)
username, display, password = body["username"], body["display_name"], body["password"]
if not isinstance(username, str) or not isinstance(display, str) or not isinstance(password, str):
return ensure_error(rid, "invalid_request", "Неверные типы полей", 400)
import re
if not re.fullmatch(r"[a-z0-9_]{3,32}", username):
return ensure_error(rid, "invalid_request", "Некорректное имя пользователя", 400)
if not display or len(display) > 100 or display.strip() == "":
return ensure_error(rid, "invalid_request", "Некорректное отображаемое имя", 400)
if not 12 <= len(password) <= 128:
return ensure_error(rid, "invalid_request", "Некорректная длина пароля", 400)
try:
password_hash = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt(rounds=12)).decode("ascii")
uid = str(uuid.uuid4())
now = utcnow()
with db() as conn:
conn.execute(
"INSERT INTO users(id,username,display_name,password_hash,created_at) VALUES(%s,%s,%s,%s,%s)",
(uid, username, display, password_hash, now),
)
conn.commit()
with db() as conn:
row = conn.execute("SELECT * FROM users WHERE id=%s", (uid,)).fetchone()
return JSONResponse(public_user(row), status_code=201, headers={"X-Request-Id": rid, "X-Instance-Id": APP_INSTANCE})
except psycopg.IntegrityError:
return ensure_error(rid, "conflict", "Имя пользователя занято", 409)
except Exception:
return ensure_error(rid, "internal_error", "Внутренняя ошибка", 500)
@app.post("/api/v1/auth/sessions")
async def login(request: Request):
rid = request_id(request)
auth = request.headers.get("Authorization", "")
if not auth.lower().startswith("basic "):
response = ensure_error(rid, "unauthorized", "Неверные учетные данные", 401)
response.headers["WWW-Authenticate"] = 'Basic realm="messenger", charset="UTF-8"'
return response
try:
decoded = base64.b64decode(auth.split(None, 1)[1], validate=True).decode("utf-8")
username, password = decoded.split(":", 1)
except Exception:
response = ensure_error(rid, "unauthorized", "Неверные учетные данные", 401)
response.headers["WWW-Authenticate"] = 'Basic realm="messenger", charset="UTF-8"'
return response
with db() as conn:
row = conn.execute("SELECT * FROM users WHERE username=%s", (username,)).fetchone()
if not row or not bcrypt.checkpw(password.encode("utf-8"), row["password_hash"].encode("ascii")):
response = ensure_error(rid, "unauthorized", "Неверные учетные данные", 401)
response.headers["WWW-Authenticate"] = 'Basic realm="messenger", charset="UTF-8"'
return response
token = base64.urlsafe_b64encode(secrets.token_bytes(32)).decode("ascii").rstrip("=")
expires = utcnow() + timedelta(seconds=SESSION_TTL)
with db() as conn:
conn.execute("INSERT INTO sessions(token,user_id,expires_at) VALUES(%s,%s,%s)", (token, row["id"], expires))
conn.commit()
return JSONResponse(
{"token": token, "token_type": "Bearer", "expires_at": iso(expires), "user": public_user(row)},
status_code=201,
headers={"X-Request-Id": rid, "X-Instance-Id": APP_INSTANCE},
)
@app.delete("/api/v1/auth/sessions/current")
async def logout(request: Request):
rid, user, error = require_user(request)
if error:
return error
token = request.headers["Authorization"][7:].strip()
with db() as conn:
conn.execute("DELETE FROM sessions WHERE token=%s", (token,))
conn.commit()
return Response(status_code=204, headers={"X-Request-Id": rid, "X-Instance-Id": APP_INSTANCE})
@app.get("/api/v1/users/me")
async def users_me(request: Request):
rid, user, error = require_user(request)
if error:
return error
return public_user(user)
@app.post("/api/v1/chats")
async def create_chat(request: Request):
rid, user, error = require_user(request)
if error:
return error
try:
body = await request.json()
except Exception:
return ensure_error(rid, "invalid_request", "Некорректный JSON", 400)
if not isinstance(body, dict) or set(body) != {"title", "member_ids"}:
return ensure_error(rid, "invalid_request", "Неверные поля запроса", 400)
title, member_ids = body["title"], body["member_ids"]
if not isinstance(title, str) or not title.strip() or len(title) > 255:
return ensure_error(rid, "invalid_request", "Некорректный title", 400)
if not isinstance(member_ids, list) or not all(isinstance(x, str) for x in member_ids):
return ensure_error(rid, "invalid_request", "Некорректный member_ids", 400)
if str(user["id"]) not in member_ids or len(set(member_ids)) != len(member_ids):
return ensure_error(rid, "invalid_request", "Участники некорректны", 400)
cid, now = str(uuid.uuid4()), utcnow()
try:
with db() as conn:
existing = conn.execute("SELECT id FROM users WHERE id=ANY(%s)", (member_ids,)).fetchall()
if len(existing) != len(set(member_ids)):
return ensure_error(rid, "invalid_request", "Неизвестный участник", 400)
conn.execute("INSERT INTO chats(id,title,created_at) VALUES(%s,%s,%s)", (cid, title, now))
for member_id in member_ids:
conn.execute("INSERT INTO chat_members(chat_id,user_id) VALUES(%s,%s)", (cid, member_id))
conn.commit()
return JSONResponse({"id": cid, "title": title, "member_ids": member_ids, "created_at": iso(now)}, status_code=201, headers={"X-Request-Id": rid, "X-Instance-Id": APP_INSTANCE})
except psycopg.Error:
return ensure_error(rid, "internal_error", "Внутренняя ошибка", 500)
@app.get("/api/v1/chats")
async def list_chats(request: Request):
rid, user, error = require_user(request)
if error:
return error
limit = request.query_params.get("limit", "50")
try:
limit = int(limit)
except ValueError:
return ensure_error(rid, "invalid_request", "Некорректный limit", 400)
if not 1 <= limit <= 100:
return ensure_error(rid, "invalid_request", "Некорректный limit", 400)
with db() as conn:
rows = conn.execute(
"""SELECT c.* FROM chats c JOIN chat_members m ON m.chat_id=c.id
WHERE m.user_id=%s ORDER BY c.created_at,c.id LIMIT %s""",
(user["id"], limit),
).fetchall()
items = []
for row in rows:
members = conn.execute("SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id", (row["id"],)).fetchall()
items.append({"id": str(row["id"]), "title": row["title"], "member_ids": [str(x["user_id"]) for x in members], "created_at": iso(row["created_at"])})
return {"items": items, "next_cursor": None}
def chat_for_member(conn, chat_id, user_id):
chat = conn.execute("SELECT * FROM chats WHERE id=%s", (chat_id,)).fetchone()
if not chat or not is_member(conn, chat_id, user_id):
return None
return chat
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(chat_id: str, request: Request):
rid, user, error = require_user(request)
if error:
return error
with db() as conn:
chat = chat_for_member(conn, chat_id, user["id"])
if not chat:
return ensure_error(rid, "not_found", "Объект не найден", 404)
members = conn.execute(
"SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id",
(chat_id,),
).fetchall()
return {
"id": str(chat["id"]),
"title": chat["title"],
"member_ids": [str(x["user_id"]) for x in members],
"created_at": iso(chat["created_at"]),
}
@app.post("/api/v1/chats/{chat_id}/messages")
async def create_message(chat_id: str, request: Request):
rid, user, error = require_user(request)
if error:
return error
try:
body = await request.json()
except Exception:
return ensure_error(rid, "invalid_request", "Некорректный JSON", 400)
if not isinstance(body, dict) or set(body) - {"text", "attachment_ids"}:
return ensure_error(rid, "invalid_request", "Неверные поля запроса", 400)
text = body.get("text", "")
attachments = body.get("attachment_ids", [])
if not isinstance(text, str) or not isinstance(attachments, list):
return ensure_error(rid, "invalid_request", "Неверные типы полей", 400)
if len(text) > 4000 or len(attachments) > 10 or len(set(attachments)) != len(attachments):
return ensure_error(rid, "invalid_request", "Неверный текст или вложения", 400)
if not text.strip() and not attachments:
return ensure_error(rid, "invalid_request", "Пустое текстовое сообщение", 400)
key = request.headers.get("Idempotency-Key")
import re
if not key or not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key):
return ensure_error(rid, "invalid_request", "Некорректный Idempotency-Key", 400)
normalized = {"text": text, "attachment_ids": attachments}
body_hash = hashlib.sha256(__import__("json").dumps(normalized, ensure_ascii=False, sort_keys=True).encode()).hexdigest()
with db() as conn:
conn.execute(
"SELECT pg_advisory_xact_lock(hashtextextended(%s,0))",
(str(user["id"]) + "|" + f"/api/v1/chats/{chat_id}/messages" + "|" + key,),
)
chat = chat_for_member(conn, chat_id, user["id"])
if not chat:
return ensure_error(rid, "not_found", "Объект не найден", 404)
for aid in attachments:
att = conn.execute("SELECT chat_id,status FROM attachments WHERE id=%s", (aid,)).fetchone()
if not att or str(att["chat_id"]) != str(chat_id):
return ensure_error(rid, "not_found", "Вложение не найдено", 404)
if att["status"] == "failed":
return ensure_error(rid, "conflict", "Вложение недоступно", 409)
replay = conn.execute(
"SELECT body_hash,response_code,response_body FROM idempotency WHERE user_id=%s AND method='POST' AND path=%s AND key=%s",
(user["id"], f"/api/v1/chats/{chat_id}/messages", key),
).fetchone()
if replay:
if replay["body_hash"] != body_hash:
return ensure_error(rid, "conflict", "Ключ уже использован с другим содержимым", 409)
import json
return JSONResponse(json.loads(replay["response_body"]), status_code=replay["response_code"], headers={"X-Request-Id": rid, "X-Instance-Id": APP_INSTANCE})
existing = conn.execute(
"SELECT body_hash FROM idempotency WHERE user_id=%s AND method='POST' AND path=%s AND key=%s",
(user["id"], f"/api/v1/chats/{chat_id}/messages", key),
).fetchone()
if existing and existing["body_hash"] != body_hash:
return ensure_error(rid, "conflict", "Ключ уже использован с другим содержимым", 409)
mid, now = str(uuid.uuid4()), utcnow()
conn.execute(
"INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES(%s,%s,%s,%s,%s)",
(mid, chat_id, user["id"], text, now),
)
for aid in attachments:
conn.execute("INSERT INTO message_attachments(message_id,attachment_id) VALUES(%s,%s)", (mid, aid))
result = {"id": mid, "chat_id": str(chat_id), "sender_id": str(user["id"]), "text": text, "created_at": iso(now), "attachment_ids": attachments}
import json
conn.execute(
"INSERT INTO idempotency(user_id,method,path,key,body_hash,response_code,response_body,created_at) VALUES(%s,'POST',%s,%s,%s,201,%s,%s)",
(user["id"], f"/api/v1/chats/{chat_id}/messages", key, body_hash, json.dumps(result, ensure_ascii=False), now),
)
conn.commit()
return JSONResponse(result, status_code=201, headers={"X-Request-Id": rid, "X-Instance-Id": APP_INSTANCE})
@app.get("/api/v1/chats/{chat_id}/messages")
async def message_history(chat_id: str, request: Request):
rid, user, error = require_user(request)
if error:
return error
limit = request.query_params.get("limit", "50")
cursor = request.query_params.get("cursor")
try:
limit = int(limit)
except ValueError:
return ensure_error(rid, "invalid_request", "Некорректный limit", 400)
if not 1 <= limit <= 100:
return ensure_error(rid, "invalid_request", "Некорректный limit", 400)
with db() as conn:
chat = chat_for_member(conn, chat_id, user["id"])
if not chat:
return ensure_error(rid, "not_found", "Объект не найден", 404)
after = None
if cursor:
try:
padded = cursor + "=" * (-len(cursor) % 4)
raw = base64.urlsafe_b64decode(padded.encode()).decode()
saved_chat, at, mid = raw.rsplit("|", 2)
if saved_chat != chat_id:
raise ValueError()
after = (datetime.fromisoformat(at.replace("Z", "+00:00")), mid)
except Exception:
return ensure_error(rid, "invalid_request", "Некорректный cursor", 400)
if after:
rows = conn.execute(
"""SELECT * FROM messages WHERE chat_id=%s AND (created_at,id) > (%s::timestamptz,%s::uuid)
ORDER BY created_at,id LIMIT %s""",
(chat_id, after[0], after[1], limit + 1),
).fetchall()
else:
rows = conn.execute(
"SELECT * FROM messages WHERE chat_id=%s ORDER BY created_at,id LIMIT %s",
(chat_id, limit + 1),
).fetchall()
has_next = len(rows) > limit
rows = rows[:limit]
items = []
for row in rows:
aids = conn.execute(
"SELECT attachment_id FROM message_attachments WHERE message_id=%s ORDER BY attachment_id",
(row["id"],),
).fetchall()
items.append({
"id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]),
"text": row["text"], "created_at": iso(row["created_at"]),
"attachment_ids": [str(x["attachment_id"]) for x in aids],
})
next_cursor = None
if has_next:
last = rows[-1]
raw = f"{chat_id}|{iso(last['created_at'])}|{last['id']}"
next_cursor = base64.urlsafe_b64encode(raw.encode()).decode().rstrip("=")
return {"items": items, "next_cursor": next_cursor}
async def read_limited(request):
chunks = []
total = 0
async for chunk in request.stream():
total += len(chunk)
if total > MAX_UPLOAD:
return None, "payload_too_large"
chunks.append(chunk)
return b"".join(chunks), None
def attachment_public(row):
return {
"id": str(row["id"]), "chat_id": str(row["chat_id"]), "owner_id": str(row["owner_id"]),
"filename": row["filename"], "size_bytes": row["size_bytes"], "sha256": row["sha256"],
"content_type": row["content_type"], "status": row["status"], "variants": [],
"error_code": row["error_code"],
"created_at": iso(row["created_at"]), "updated_at": iso(row["created_at"]),
}
@app.post("/api/v1/chats/{chat_id}/attachments")
async def upload_attachment(chat_id: str, request: Request):
rid, user, error = require_user(request)
if error:
return error
filename = request.query_params.get("filename")
if not filename or len(filename) > 255 or filename.strip() == "":
return ensure_error(rid, "invalid_request", "Некорректное filename", 400)
if "/" in filename or "\\" in filename or "\x00" in filename or any(ord(c) < 32 for c in filename):
return ensure_error(rid, "invalid_request", "Опасное filename", 400)
with db() as conn:
chat = chat_for_member(conn, chat_id, user["id"])
if not chat:
return ensure_error(rid, "not_found", "Объект не найден", 404)
data, size_error = await read_limited(request)
if size_error:
return ensure_error(rid, "payload_too_large", "Файл превышает допустимый размер", 413)
if not data:
return ensure_error(rid, "unsupported_media_type", "Файл не является изображением", 415)
declared = request.headers.get("Content-Type", "").lower().split(";")[0].strip()
try:
with Image.open(io.BytesIO(data)) as image:
image.verify()
with Image.open(io.BytesIO(data)) as verified:
width, height = verified.size
actual_format = verified.format
except Exception:
return ensure_error(rid, "unsupported_media_type", "Поврежденное изображение", 415)
actual_type = "image/png" if actual_format == "PNG" else "image/jpeg" if actual_format == "JPEG" else None
if not actual_type or declared not in ("image/png", "image/jpeg") or declared != actual_type:
return ensure_error(rid, "unsupported_media_type", "Тип файла не соответствует содержимому", 415)
if width * height > MAX_PIXELS:
return ensure_error(rid, "payload_too_large", "Изображение содержит слишком много пикселей", 413)
aid, key = str(uuid.uuid4()), f"attachments/{uuid.uuid4()}/{uuid.uuid4()}"
digest = hashlib.sha256(data).hexdigest()
now = utcnow()
try:
s3.put_object(Bucket=S3_BUCKET, Key=key, Body=data, ContentType=actual_type)
except Exception:
return ensure_error(rid, "unavailable", "Хранилище недоступно", 503)
try:
with db() as conn:
conn.execute(
"""INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,size_bytes,sha256,content_type,status,error_code,created_at)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,'ready',NULL,%s)""",
(aid, chat_id, user["id"], filename, key, len(data), digest, actual_type, now),
)
conn.commit()
row = conn.execute("SELECT * FROM attachments WHERE id=%s", (aid,)).fetchone()
except Exception:
try:
s3.delete_object(Bucket=S3_BUCKET, Key=key)
except Exception:
pass
return ensure_error(rid, "internal_error", "Внутренняя ошибка", 500)
return JSONResponse(attachment_public(row), status_code=201, headers={"X-Request-Id": rid, "X-Instance-Id": APP_INSTANCE})
@app.get("/api/v1/attachments/{attachment_id}")
async def attachment_metadata(attachment_id: str, request: Request):
rid, user, error = require_user(request)
if error:
return error
with db() as conn:
row = conn.execute("SELECT * FROM attachments WHERE id=%s", (attachment_id,)).fetchone()
if not row or not is_member(conn, row["chat_id"], user["id"]):
return ensure_error(rid, "not_found", "Объект не найден", 404)
return attachment_public(row)
@app.get("/api/v1/attachments/{attachment_id}/content")
async def attachment_content(attachment_id: str, request: Request):
rid, user, error = require_user(request)
if error:
return error
variant = request.query_params.get("variant", "original")
if variant != "original":
return ensure_error(rid, "not_found", "Вариант не найден", 404)
with db() as conn:
row = conn.execute("SELECT * FROM attachments WHERE id=%s", (attachment_id,)).fetchone()
if not row or not is_member(conn, row["chat_id"], user["id"]):
return ensure_error(rid, "not_found", "Объект не найден", 404)
if row["status"] != "ready":
return ensure_error(rid, "conflict", "Вложение не готово", 409)
try:
obj = s3.get_object(Bucket=S3_BUCKET, Key=row["object_key"])
body = obj["Body"]
except Exception:
return ensure_error(rid, "unavailable", "Файл недоступен", 503)
return StreamingResponse(body, media_type=row["content_type"], headers={"X-Request-Id": rid, "X-Instance-Id": APP_INSTANCE})