forked from mtusi2026/mtusi2026lab2
718 lines
19 KiB
Python
718 lines
19 KiB
Python
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import hashlib
|
|
import secrets
|
|
import uuid
|
|
import os
|
|
|
|
from datetime import datetime, timezone, timedelta
|
|
from typing import Any
|
|
|
|
import psycopg
|
|
from psycopg.rows import dict_row
|
|
from psycopg_pool import ConnectionPool
|
|
import redis
|
|
|
|
from argon2 import PasswordHasher
|
|
from argon2.exceptions import VerifyMismatchError, InvalidHashError
|
|
|
|
from fastapi import FastAPI, Request, Query
|
|
from fastapi.responses import JSONResponse
|
|
from fastapi.exceptions import RequestValidationError
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
|
|
|
|
DB_URL = os.getenv(
|
|
"DATABASE_URL",
|
|
"postgresql://messenger:messenger@localhost:5432/messenger"
|
|
)
|
|
|
|
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0")
|
|
TTL = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
|
|
|
pool = ConnectionPool(
|
|
DB_URL,
|
|
min_size=1,
|
|
max_size=10,
|
|
timeout=5,
|
|
kwargs={
|
|
"connect_timeout": 5,
|
|
"options": "-c statement_timeout=5000",
|
|
"row_factory": dict_row
|
|
},
|
|
open=False
|
|
)
|
|
|
|
cache = redis.Redis.from_url(
|
|
REDIS_URL,
|
|
socket_connect_timeout=2,
|
|
socket_timeout=2,
|
|
decode_responses=True
|
|
)
|
|
|
|
ph = PasswordHasher()
|
|
|
|
app = FastAPI(
|
|
title="MTUSI Messenger",
|
|
version="2.0.0",
|
|
docs_url=None,
|
|
redoc_url=None
|
|
)
|
|
|
|
|
|
class ApiError(Exception):
|
|
def __init__(self, status: int, code: str, message: str):
|
|
self.status, self.code, self.message = status, code, message
|
|
|
|
|
|
class UserOut(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
id: uuid.UUID
|
|
username: str
|
|
display_name: str
|
|
created_at: str
|
|
|
|
|
|
class UserIn(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)
|
|
|
|
@field_validator("display_name")
|
|
@classmethod
|
|
def not_blank(cls, v):
|
|
if not v.strip():
|
|
raise ValueError("blank")
|
|
return v
|
|
|
|
|
|
class ChatIn(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
title: str = Field(min_length=1, max_length=100)
|
|
member_ids: list[uuid.UUID] = Field(min_length=1, max_length=100)
|
|
|
|
@field_validator("title")
|
|
@classmethod
|
|
def nonblank(cls, v):
|
|
if not v.strip():
|
|
raise ValueError("blank")
|
|
return v
|
|
|
|
@field_validator("member_ids")
|
|
@classmethod
|
|
def unique(cls, v):
|
|
if len(v) != len(set(v)):
|
|
raise ValueError("duplicate")
|
|
return v
|
|
|
|
|
|
class MessageIn(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
text: str = Field(min_length=1, max_length=4000)
|
|
|
|
@field_validator("text")
|
|
@classmethod
|
|
def nonblank(cls, v):
|
|
if not v.strip():
|
|
raise ValueError("blank")
|
|
return v
|
|
|
|
|
|
def stamp(v):
|
|
return (
|
|
v.astimezone(timezone.utc)
|
|
.isoformat(timespec="microseconds")
|
|
.replace("+00:00", "Z")
|
|
if isinstance(v, datetime)
|
|
else str(v)
|
|
)
|
|
|
|
|
|
def out(row):
|
|
d = dict(row)
|
|
d["created_at"] = stamp(d["created_at"])
|
|
return d
|
|
|
|
|
|
def err(request, status, code, message):
|
|
rid = getattr(request.state, "rid", str(uuid.uuid4()))
|
|
headers = {"X-Request-Id": rid}
|
|
|
|
if status == 401:
|
|
headers["WWW-Authenticate"] = (
|
|
'Basic realm="messenger", charset="UTF-8"'
|
|
if request.url.path == "/api/v1/auth/sessions"
|
|
else 'Bearer realm="messenger"'
|
|
)
|
|
|
|
return JSONResponse(
|
|
status_code=status,
|
|
content={
|
|
"error": {
|
|
"code": code,
|
|
"message": message,
|
|
"request_id": rid
|
|
}
|
|
},
|
|
headers=headers
|
|
)
|
|
|
|
|
|
@app.middleware("http")
|
|
async def request_mw(req, call_next):
|
|
req.state.rid = req.headers.get("X-Request-Id") or str(uuid.uuid4())
|
|
response = await call_next(req)
|
|
response.headers["X-Request-Id"] = req.state.rid
|
|
return response
|
|
|
|
|
|
@app.exception_handler(ApiError)
|
|
async def apierr(req, e):
|
|
return err(req, e.status, e.code, e.message)
|
|
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def valerr(req, e):
|
|
return err(req, 400, "invalid_request", "Некорректный запрос")
|
|
|
|
|
|
@app.exception_handler(StarletteHTTPException)
|
|
async def httperr(req, e):
|
|
return err(
|
|
req,
|
|
e.status_code,
|
|
"not_found" if e.status_code == 404 else "invalid_request",
|
|
"Недоступный HTTP маршрут или метод"
|
|
)
|
|
|
|
|
|
@app.exception_handler(psycopg.Error)
|
|
async def dberr(req, e):
|
|
return err(req, 503, "unavailable", "База данных временно недоступна")
|
|
|
|
|
|
@app.exception_handler(Exception)
|
|
async def unexpected(req, e):
|
|
return err(req, 500, "internal_error", "Внутренняя ошибка")
|
|
|
|
|
|
@app.on_event("startup")
|
|
def startup():
|
|
pool.open(wait=True)
|
|
|
|
|
|
@app.on_event("shutdown")
|
|
def shutdown():
|
|
pool.close()
|
|
|
|
|
|
def current(req):
|
|
h = req.headers.get("Authorization", "")
|
|
parts = h.split(" ", 1)
|
|
|
|
if len(parts) != 2 or parts[0].lower() != "bearer" or not parts[1]:
|
|
raise ApiError(401, "unauthorized", "Требуется действительная сессия")
|
|
|
|
token = parts[1]
|
|
digest = hashlib.sha256(token.encode()).hexdigest()
|
|
|
|
try:
|
|
uid = cache.get("session:" + digest)
|
|
|
|
if uid is None:
|
|
with pool.connection() as c:
|
|
row = c.execute(
|
|
"SELECT user_id,expires_at FROM sessions WHERE token_hash=%s",
|
|
(digest,)
|
|
).fetchone()
|
|
|
|
if not row or row["expires_at"] <= datetime.now(timezone.utc):
|
|
raise ApiError(
|
|
401,
|
|
"unauthorized",
|
|
"Требуется действительная сессия"
|
|
)
|
|
|
|
uid = str(row["user_id"])
|
|
remain = max(
|
|
1,
|
|
int(
|
|
(
|
|
row["expires_at"] - datetime.now(timezone.utc)
|
|
).total_seconds()
|
|
)
|
|
)
|
|
|
|
cache.setex("session:" + digest, remain, uid)
|
|
|
|
except redis.RedisError as e:
|
|
raise ApiError(
|
|
503,
|
|
"unavailable",
|
|
"Сервис сессий временно недоступен"
|
|
) from e
|
|
|
|
try:
|
|
uid = uuid.UUID(uid)
|
|
except (ValueError, TypeError, AttributeError) as e:
|
|
raise ApiError(
|
|
401,
|
|
"unauthorized",
|
|
"Требуется действительная сессия"
|
|
) from e
|
|
|
|
with pool.connection() as c:
|
|
user = c.execute(
|
|
"SELECT id,username,display_name,created_at FROM users WHERE id=%s",
|
|
(uid,)
|
|
).fetchone()
|
|
|
|
if not user:
|
|
raise ApiError(401, "unauthorized", "Требуется действительная сессия")
|
|
|
|
return user, digest
|
|
|
|
|
|
def membership(cid, uid):
|
|
with pool.connection() as c:
|
|
row = c.execute(
|
|
"SELECT 1 FROM memberships WHERE chat_id=%s AND user_id=%s",
|
|
(cid, uid)
|
|
).fetchone()
|
|
|
|
if not row:
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
|
|
|
|
@app.get("/health/live")
|
|
def live():
|
|
return {"status": "ok"}
|
|
|
|
|
|
@app.get("/health/ready")
|
|
def ready():
|
|
try:
|
|
with pool.connection() as c:
|
|
c.execute("SELECT 1")
|
|
|
|
cache.ping()
|
|
return {"status": "ok"}
|
|
|
|
except Exception:
|
|
raise ApiError(503, "unavailable", "Зависимость временно недоступна")
|
|
|
|
|
|
@app.post("/api/v1/users", status_code=201)
|
|
def register(p: UserIn):
|
|
uid = uuid.uuid4()
|
|
|
|
try:
|
|
with pool.connection() as c:
|
|
with c.transaction():
|
|
r = c.execute(
|
|
"""
|
|
INSERT INTO users(id,username,display_name,password_hash)
|
|
VALUES(%s,%s,%s,%s)
|
|
RETURNING id,username,display_name,created_at
|
|
""",
|
|
(uid, p.username, p.display_name, ph.hash(p.password))
|
|
).fetchone()
|
|
|
|
return out(r)
|
|
|
|
except psycopg.errors.UniqueViolation as e:
|
|
raise ApiError(409, "conflict", "Username уже занят") from e
|
|
|
|
|
|
def basic_credentials(req):
|
|
h = req.headers.get("Authorization", "")
|
|
scheme, _, value = h.partition(" ")
|
|
|
|
try:
|
|
if scheme.lower() != "basic" or not value:
|
|
raise ValueError
|
|
|
|
decoded = base64.b64decode(value, validate=True).decode("utf-8")
|
|
username, password = decoded.split(":", 1)
|
|
|
|
if not username or not password:
|
|
raise ValueError
|
|
|
|
return username, password
|
|
|
|
except (ValueError, UnicodeError):
|
|
raise ApiError(401, "unauthorized", "Неверные учётные данные")
|
|
|
|
|
|
@app.post("/api/v1/auth/sessions", status_code=201)
|
|
def create_session(req: Request):
|
|
username, password = basic_credentials(req)
|
|
|
|
with pool.connection() as c:
|
|
user = c.execute(
|
|
"""
|
|
SELECT id,username,display_name,created_at,password_hash
|
|
FROM users WHERE username=%s
|
|
""",
|
|
(username,)
|
|
).fetchone()
|
|
|
|
good = False
|
|
|
|
if user:
|
|
try:
|
|
good = ph.verify(user["password_hash"], password)
|
|
except (VerifyMismatchError, InvalidHashError):
|
|
pass
|
|
|
|
if not good:
|
|
raise ApiError(401, "unauthorized", "Неверные учётные данные")
|
|
|
|
token = secrets.token_urlsafe(32)
|
|
digest = hashlib.sha256(token.encode()).hexdigest()
|
|
exp = datetime.now(timezone.utc) + timedelta(seconds=TTL)
|
|
|
|
try:
|
|
with pool.connection() as c:
|
|
c.execute(
|
|
"""
|
|
INSERT INTO sessions(token_hash,user_id,expires_at)
|
|
VALUES(%s,%s,%s)
|
|
""",
|
|
(digest, user["id"], exp)
|
|
)
|
|
|
|
cache.setex("session:" + digest, TTL, str(user["id"]))
|
|
|
|
except redis.RedisError as e:
|
|
with pool.connection() as c:
|
|
c.execute(
|
|
"DELETE FROM sessions WHERE token_hash=%s",
|
|
(digest,)
|
|
)
|
|
|
|
raise ApiError(
|
|
503,
|
|
"unavailable",
|
|
"Сервис сессий временно недоступен"
|
|
) from e
|
|
|
|
public_user = {
|
|
k: user[k]
|
|
for k in ("id", "username", "display_name", "created_at")
|
|
}
|
|
|
|
return {
|
|
"token": token,
|
|
"token_type": "Bearer",
|
|
"expires_at": stamp(exp),
|
|
"user": out(public_user)
|
|
}
|
|
|
|
|
|
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
|
def logout(req: Request):
|
|
user, digest = current(req)
|
|
|
|
try:
|
|
cache.delete("session:" + digest)
|
|
|
|
except redis.RedisError as e:
|
|
raise ApiError(
|
|
503,
|
|
"unavailable",
|
|
"Сервис сессий временно недоступен"
|
|
) from e
|
|
|
|
with pool.connection() as c:
|
|
c.execute(
|
|
"DELETE FROM sessions WHERE token_hash=%s",
|
|
(digest,)
|
|
)
|
|
|
|
return None
|
|
|
|
|
|
@app.get("/api/v1/users/me")
|
|
def me(req: Request):
|
|
return out(current(req)[0])
|
|
|
|
|
|
@app.post("/api/v1/chats", status_code=201)
|
|
def create_chat(req: Request, p: ChatIn):
|
|
user, _ = current(req)
|
|
cid = uuid.uuid4()
|
|
|
|
if user["id"] not in p.member_ids:
|
|
raise ApiError(400, "invalid_request", "Список участников некорректен")
|
|
|
|
try:
|
|
with pool.connection() as c:
|
|
with c.transaction():
|
|
c.execute(
|
|
"INSERT INTO chats(id,title) VALUES(%s,%s)",
|
|
(cid, p.title)
|
|
)
|
|
|
|
existing = c.execute(
|
|
"SELECT id FROM users WHERE id=ANY(%s)",
|
|
(p.member_ids,)
|
|
).fetchall()
|
|
|
|
if len(existing) != len(p.member_ids):
|
|
raise ApiError(
|
|
400,
|
|
"invalid_request",
|
|
"Список участников некорректен"
|
|
)
|
|
|
|
with c.cursor() as cur:
|
|
cur.executemany(
|
|
"INSERT INTO memberships(chat_id,user_id) VALUES(%s,%s)",
|
|
[(cid, x) for x in p.member_ids]
|
|
)
|
|
|
|
return {
|
|
"id": cid,
|
|
"title": p.title,
|
|
"member_ids": p.member_ids,
|
|
"created_at": stamp(
|
|
c.execute(
|
|
"SELECT created_at FROM chats WHERE id=%s",
|
|
(cid,)
|
|
).fetchone()["created_at"]
|
|
)
|
|
}
|
|
|
|
except psycopg.Error as e:
|
|
raise ApiError(
|
|
503,
|
|
"unavailable",
|
|
"База данных временно недоступна"
|
|
) from e
|
|
|
|
|
|
@app.get("/api/v1/chats")
|
|
def list_chats(
|
|
req: Request,
|
|
limit: int = Query(50, ge=1, le=100),
|
|
cursor: str | None = None
|
|
):
|
|
user, _ = current(req)
|
|
|
|
with pool.connection() as c:
|
|
query = (
|
|
"SELECT c.id,c.title,c.created_at,"
|
|
"array_agg(m.user_id ORDER BY m.user_id) member_ids "
|
|
"FROM chats c "
|
|
"JOIN memberships mine ON mine.chat_id=c.id "
|
|
"JOIN memberships m ON m.chat_id=c.id "
|
|
"WHERE mine.user_id=%s"
|
|
)
|
|
|
|
params = [user["id"]]
|
|
|
|
if cursor:
|
|
try:
|
|
import json
|
|
|
|
obj = json.loads(
|
|
base64.urlsafe_b64decode(
|
|
cursor + "=" * (-len(cursor) % 4)
|
|
).decode()
|
|
)
|
|
|
|
if obj["chat_id"] != str(uuid.UUID(int=0)):
|
|
raise ValueError
|
|
|
|
chat_marker = uuid.UUID(obj["id"])
|
|
datetime.fromisoformat(
|
|
obj["created_at"].replace("Z", "+00:00")
|
|
)
|
|
|
|
query += " AND (c.created_at,c.id)>(%s,%s)"
|
|
params.extend([obj["created_at"], chat_marker])
|
|
|
|
except Exception:
|
|
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
|
|
|
query += " GROUP BY c.id ORDER BY c.created_at,c.id LIMIT %s"
|
|
params.append(limit + 1)
|
|
|
|
rows = c.execute(query, params).fetchall()
|
|
|
|
more = len(rows) > limit
|
|
items = [
|
|
{**out(r), "member_ids": r["member_ids"]}
|
|
for r in rows[:limit]
|
|
]
|
|
next_cursor = None
|
|
|
|
if more and items:
|
|
import json
|
|
|
|
z = items[-1]
|
|
|
|
next_cursor = base64.urlsafe_b64encode(
|
|
json.dumps(
|
|
{
|
|
"chat_id": str(uuid.UUID(int=0)),
|
|
"created_at": z["created_at"],
|
|
"id": str(z["id"])
|
|
},
|
|
separators=(",", ":")
|
|
).encode()
|
|
).decode().rstrip("=")
|
|
|
|
return {"items": items, "next_cursor": next_cursor}
|
|
|
|
|
|
@app.get("/api/v1/chats/{chat_id}")
|
|
def get_chat(req: Request, chat_id: uuid.UUID):
|
|
user, _ = current(req)
|
|
membership(chat_id, user["id"])
|
|
|
|
with pool.connection() as c:
|
|
r = c.execute(
|
|
"""
|
|
SELECT c.id,c.title,c.created_at,
|
|
array_agg(m.user_id ORDER BY m.user_id) member_ids
|
|
FROM chats c
|
|
JOIN memberships m ON m.chat_id=c.id
|
|
WHERE c.id=%s GROUP BY c.id
|
|
""",
|
|
(chat_id,)
|
|
).fetchone()
|
|
|
|
return {**out(r), "member_ids": r["member_ids"]}
|
|
|
|
|
|
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
|
def create_message(req: Request, chat_id: uuid.UUID, p: MessageIn):
|
|
user, _ = current(req)
|
|
mid = uuid.uuid4()
|
|
|
|
try:
|
|
with pool.connection() as c:
|
|
with c.transaction():
|
|
if not c.execute(
|
|
"SELECT 1 FROM memberships WHERE chat_id=%s AND user_id=%s",
|
|
(chat_id, user["id"])
|
|
).fetchone():
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
|
|
r = c.execute(
|
|
"""
|
|
INSERT INTO messages(id,chat_id,sender_id,text)
|
|
VALUES(%s,%s,%s,%s)
|
|
RETURNING id,chat_id,sender_id,text,created_at
|
|
""",
|
|
(mid, chat_id, user["id"], p.text)
|
|
).fetchone()
|
|
|
|
return out(r)
|
|
|
|
except psycopg.Error as e:
|
|
raise ApiError(
|
|
503,
|
|
"unavailable",
|
|
"База данных временно недоступна"
|
|
) from e
|
|
|
|
|
|
@app.get("/api/v1/chats/{chat_id}/messages")
|
|
def list_messages(
|
|
req: Request,
|
|
chat_id: uuid.UUID,
|
|
limit: int = Query(50, ge=1, le=100),
|
|
cursor: str | None = None
|
|
):
|
|
user, _ = current(req)
|
|
membership(chat_id, user["id"])
|
|
|
|
try:
|
|
with pool.connection() as c:
|
|
if cursor:
|
|
try:
|
|
raw = base64.urlsafe_b64decode(
|
|
cursor + "=" * (-len(cursor) % 4)
|
|
).decode()
|
|
|
|
obj = __import__("json").loads(raw)
|
|
|
|
if obj["chat_id"] != str(chat_id):
|
|
raise ValueError
|
|
|
|
marker = (
|
|
obj["created_at"],
|
|
uuid.UUID(obj["id"])
|
|
)
|
|
|
|
except Exception:
|
|
raise ApiError(
|
|
400,
|
|
"invalid_request",
|
|
"Некорректный cursor"
|
|
)
|
|
|
|
rows = c.execute(
|
|
"""
|
|
SELECT id,chat_id,sender_id,text,created_at
|
|
FROM messages
|
|
WHERE chat_id=%s AND (created_at,id)>(%s,%s)
|
|
ORDER BY created_at,id
|
|
LIMIT %s
|
|
""",
|
|
(chat_id, marker[0], marker[1], limit + 1)
|
|
).fetchall()
|
|
|
|
else:
|
|
rows = c.execute(
|
|
"""
|
|
SELECT id,chat_id,sender_id,text,created_at
|
|
FROM messages
|
|
WHERE chat_id=%s
|
|
ORDER BY created_at,id
|
|
LIMIT %s
|
|
""",
|
|
(chat_id, limit + 1)
|
|
).fetchall()
|
|
|
|
more = len(rows) > limit
|
|
items = [out(x) for x in rows[:limit]]
|
|
next_cursor = None
|
|
|
|
if more and items:
|
|
import json
|
|
|
|
z = items[-1]
|
|
|
|
next_cursor = base64.urlsafe_b64encode(
|
|
json.dumps(
|
|
{
|
|
"chat_id": str(chat_id),
|
|
"created_at": z["created_at"],
|
|
"id": str(z["id"])
|
|
},
|
|
separators=(",", ":")
|
|
).encode()
|
|
).decode().rstrip("=")
|
|
|
|
return {"items": items, "next_cursor": next_cursor}
|
|
|
|
except psycopg.Error as e:
|
|
raise ApiError(
|
|
503,
|
|
"unavailable",
|
|
"База данных временно недоступна"
|
|
) from e
|