Implement Lab 2 grade 4 messenger service
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
+456
@@ -0,0 +1,456 @@
|
||||
import base64
|
||||
import binascii
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import secrets
|
||||
import uuid
|
||||
|
||||
from argon2 import PasswordHasher, Type
|
||||
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from redis import Redis
|
||||
from redis.exceptions import RedisError
|
||||
from sqlalchemy import and_, func, or_, select, text, tuple_
|
||||
from sqlalchemy.exc import DBAPIError, OperationalError, TimeoutError as SQLAlchemyTimeoutError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from .db import SessionLocal, engine
|
||||
from .errors import ApiError, error_response
|
||||
from .models import Chat, ChatMember, Message, User
|
||||
from .schemas import (
|
||||
ChatOut,
|
||||
ChatPage,
|
||||
CreateChat,
|
||||
CreateMessage,
|
||||
CreateUser,
|
||||
Health,
|
||||
MessageOut,
|
||||
MessagePage,
|
||||
SessionOut,
|
||||
UserOut,
|
||||
)
|
||||
from .settings import load_settings
|
||||
|
||||
settings = load_settings()
|
||||
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
)
|
||||
logger = logging.getLogger("messenger.api")
|
||||
password_hasher = PasswordHasher(
|
||||
time_cost=2,
|
||||
memory_cost=19_456,
|
||||
parallelism=1,
|
||||
hash_len=32,
|
||||
salt_len=16,
|
||||
type=Type.ID,
|
||||
)
|
||||
DUMMY_PASSWORD_HASH = password_hasher.hash("dummy-password-for-timing-only")
|
||||
redis_client = Redis.from_url(
|
||||
settings.cache_url,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=2,
|
||||
socket_timeout=2,
|
||||
health_check_interval=30,
|
||||
)
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger — Lab 2", version="1.2.0")
|
||||
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
TOKEN_RE = re.compile(r"^[A-Za-z0-9_-]{43}$")
|
||||
|
||||
|
||||
def _iso(value: datetime) -> str:
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def _user_out(user: User) -> dict:
|
||||
return {
|
||||
"id": str(user.id),
|
||||
"username": user.username,
|
||||
"display_name": user.display_name,
|
||||
"created_at": _iso(user.created_at),
|
||||
}
|
||||
|
||||
|
||||
def _message_out(message: Message) -> dict:
|
||||
return {
|
||||
"id": str(message.id),
|
||||
"chat_id": str(message.chat_id),
|
||||
"sender_id": str(message.sender_id),
|
||||
"text": message.text,
|
||||
"created_at": _iso(message.created_at),
|
||||
}
|
||||
|
||||
|
||||
def _chat_out(session, chat: Chat) -> dict:
|
||||
members = session.scalars(
|
||||
select(ChatMember.user_id)
|
||||
.where(ChatMember.chat_id == chat.id)
|
||||
.order_by(ChatMember.user_id)
|
||||
).all()
|
||||
return {
|
||||
"id": str(chat.id),
|
||||
"title": chat.title,
|
||||
"member_ids": [str(member_id) for member_id in members],
|
||||
"created_at": _iso(chat.created_at),
|
||||
}
|
||||
|
||||
|
||||
def _api_error(code: str, message: str, status: int, challenge: str | None = None) -> ApiError:
|
||||
return ApiError(code, message, status, challenge)
|
||||
|
||||
|
||||
def _unauthorized(challenge: str = BEARER_CHALLENGE) -> ApiError:
|
||||
return _api_error("unauthorized", "Нет действительной идентификации", 401, challenge)
|
||||
|
||||
|
||||
def _encode_cursor(payload: dict) -> str:
|
||||
raw = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _decode_cursor(value: str) -> dict:
|
||||
try:
|
||||
padded = value + ("=" * ((4 - len(value) % 4) % 4))
|
||||
raw = base64.b64decode(padded.encode("ascii"), altchars=b"-_", validate=True)
|
||||
payload = json.loads(raw.decode("utf-8"))
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("cursor must be an object")
|
||||
return payload
|
||||
except (ValueError, UnicodeError, binascii.Error, json.JSONDecodeError) as exc:
|
||||
raise _api_error("invalid_request", "Неверный cursor", 400) from exc
|
||||
|
||||
|
||||
def _cursor_position(payload: dict) -> tuple[datetime, uuid.UUID]:
|
||||
try:
|
||||
created_at = datetime.fromisoformat(payload["t"].replace("Z", "+00:00"))
|
||||
if created_at.tzinfo is None:
|
||||
raise ValueError("cursor time must include timezone")
|
||||
item_id = uuid.UUID(payload["i"])
|
||||
return created_at.astimezone(timezone.utc), item_id
|
||||
except (KeyError, TypeError, ValueError, AttributeError) as exc:
|
||||
raise _api_error("invalid_request", "Неверный cursor", 400) from exc
|
||||
|
||||
|
||||
def _session_key(token: str) -> str:
|
||||
digest = hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||
return "session:v1:" + digest
|
||||
|
||||
|
||||
def _parse_bearer(request: Request) -> str:
|
||||
header = request.headers.get("authorization", "")
|
||||
scheme, separator, token = header.partition(" ")
|
||||
if scheme.lower() != "bearer" or not separator or not TOKEN_RE.fullmatch(token):
|
||||
raise _unauthorized()
|
||||
return token
|
||||
|
||||
|
||||
def _load_session(token: str) -> dict:
|
||||
value = redis_client.get(_session_key(token))
|
||||
if value is None:
|
||||
raise _unauthorized()
|
||||
try:
|
||||
session = json.loads(value)
|
||||
user_id = uuid.UUID(session["user_id"])
|
||||
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
|
||||
if expires_at.tzinfo is None or datetime.now(timezone.utc) >= expires_at:
|
||||
redis_client.delete(_session_key(token))
|
||||
raise _unauthorized()
|
||||
return {"user_id": user_id, "expires_at": expires_at}
|
||||
except ApiError:
|
||||
raise
|
||||
except (KeyError, TypeError, ValueError, AttributeError, json.JSONDecodeError):
|
||||
redis_client.delete(_session_key(token))
|
||||
raise _unauthorized() from None
|
||||
|
||||
|
||||
def _current_user(request: Request) -> tuple[User, str]:
|
||||
token = _parse_bearer(request)
|
||||
session_data = _load_session(token)
|
||||
with SessionLocal() as session:
|
||||
user = session.get(User, session_data["user_id"])
|
||||
if user is None:
|
||||
redis_client.delete(_session_key(token))
|
||||
raise _unauthorized()
|
||||
return user, token
|
||||
|
||||
|
||||
def _parse_basic(header: str) -> tuple[str, str]:
|
||||
scheme, separator, encoded = header.partition(" ")
|
||||
if scheme.lower() != "basic" or not separator or not encoded:
|
||||
raise _unauthorized(BASIC_CHALLENGE)
|
||||
try:
|
||||
decoded = base64.b64decode(encoded.encode("ascii"), validate=True).decode("utf-8")
|
||||
username, password = decoded.split(":", 1)
|
||||
except (UnicodeError, ValueError, binascii.Error):
|
||||
raise _unauthorized(BASIC_CHALLENGE) from None
|
||||
if not USERNAME_RE.fullmatch(username) or not password:
|
||||
raise _unauthorized(BASIC_CHALLENGE)
|
||||
return username, password
|
||||
|
||||
|
||||
def _password_matches(password_hash: str, password: str) -> bool:
|
||||
try:
|
||||
return password_hasher.verify(password_hash, password)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def _create_session(username: str, password: str) -> dict:
|
||||
with SessionLocal() as session:
|
||||
user = session.scalar(select(User).where(User.username == username))
|
||||
stored_hash = user.password_hash if user is not None else DUMMY_PASSWORD_HASH
|
||||
password_ok = _password_matches(stored_hash, password)
|
||||
if user is None or not password_ok:
|
||||
raise _unauthorized(BASIC_CHALLENGE)
|
||||
user_payload = _user_out(user)
|
||||
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(seconds=settings.session_ttl_seconds)
|
||||
for _ in range(3):
|
||||
token = secrets.token_urlsafe(32)
|
||||
stored_value = json.dumps(
|
||||
{"user_id": user_payload["id"], "expires_at": _iso(expires_at)},
|
||||
separators=(",", ":"),
|
||||
)
|
||||
if redis_client.set(_session_key(token), stored_value, ex=settings.session_ttl_seconds, nx=True):
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": _iso(expires_at),
|
||||
"user": user_payload,
|
||||
}
|
||||
logger.error("session_token_collision_limit_reached")
|
||||
raise _api_error("unavailable", "Сервис временно недоступен", 503)
|
||||
|
||||
|
||||
def _get_chat_for_member(session, chat_id: uuid.UUID, user_id: uuid.UUID) -> Chat | None:
|
||||
return session.scalar(
|
||||
select(Chat)
|
||||
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
||||
.where(Chat.id == chat_id, ChatMember.user_id == user_id)
|
||||
)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_id_middleware(request: Request, call_next):
|
||||
request_id = str(uuid.uuid4())
|
||||
request.state.request_id = request_id
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def handle_api_error(request: Request, exc: ApiError):
|
||||
return error_response(request, exc.code, exc.message, exc.status, exc.challenge)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def handle_validation_error(request: Request, _exc: RequestValidationError):
|
||||
return error_response(request, "invalid_request", "Неверный запрос", 400)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def handle_http_error(request: Request, exc: StarletteHTTPException):
|
||||
if exc.status_code == 404:
|
||||
return error_response(request, "not_found", "Объект не найден", 404)
|
||||
return error_response(request, "invalid_request", "Неверный запрос", 400)
|
||||
|
||||
|
||||
@app.exception_handler(OperationalError)
|
||||
@app.exception_handler(SQLAlchemyTimeoutError)
|
||||
async def handle_database_unavailable(request: Request, exc: Exception):
|
||||
logger.warning("database_unavailable request_id=%s type=%s", request.state.request_id, type(exc).__name__)
|
||||
return error_response(request, "unavailable", "Сервис временно недоступен", 503)
|
||||
|
||||
|
||||
@app.exception_handler(RedisError)
|
||||
async def handle_cache_unavailable(request: Request, exc: RedisError):
|
||||
logger.warning("session_store_unavailable request_id=%s type=%s", request.state.request_id, type(exc).__name__)
|
||||
return error_response(request, "unavailable", "Сервис временно недоступен", 503)
|
||||
|
||||
|
||||
@app.exception_handler(DBAPIError)
|
||||
async def handle_database_error(request: Request, exc: DBAPIError):
|
||||
if exc.connection_invalidated:
|
||||
logger.warning("database_connection_lost request_id=%s", request.state.request_id)
|
||||
return error_response(request, "unavailable", "Сервис временно недоступен", 503)
|
||||
logger.error("database_error request_id=%s type=%s", request.state.request_id, type(exc).__name__)
|
||||
return error_response(request, "internal_error", "Внутренняя ошибка", 500)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def handle_unexpected_error(request: Request, exc: Exception):
|
||||
logger.error("internal_error request_id=%s type=%s", request.state.request_id, type(exc).__name__)
|
||||
return error_response(request, "internal_error", "Внутренняя ошибка", 500)
|
||||
|
||||
|
||||
@app.get("/health/live", response_model=Health)
|
||||
def live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready", response_model=Health, responses={503: {"description": "Dependency unavailable"}})
|
||||
def ready():
|
||||
with SessionLocal() as session:
|
||||
session.execute(text("SELECT 1"))
|
||||
redis_client.ping()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.post("/api/v1/users", response_model=UserOut, status_code=201)
|
||||
def register_user(payload: CreateUser):
|
||||
password_hash = password_hasher.hash(payload.password)
|
||||
user = User(username=payload.username, display_name=payload.display_name, password_hash=password_hash)
|
||||
try:
|
||||
with SessionLocal.begin() as session:
|
||||
session.add(user)
|
||||
session.flush()
|
||||
except DBAPIError as exc:
|
||||
if getattr(getattr(exc, "orig", None), "sqlstate", None) == "23505":
|
||||
raise _api_error("conflict", "username занят", 409) from exc
|
||||
raise
|
||||
return _user_out(user)
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions", response_model=SessionOut, status_code=201)
|
||||
async def create_session(request: Request):
|
||||
if await request.body():
|
||||
raise _api_error("invalid_request", "Basic authentication must not include a body", 400)
|
||||
username, password = _parse_basic(request.headers.get("authorization", ""))
|
||||
return await run_in_threadpool(_create_session, username, password)
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def revoke_session(request: Request):
|
||||
_user, token = _current_user(request)
|
||||
redis_client.delete(_session_key(token))
|
||||
return None
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me", response_model=UserOut)
|
||||
def current_user(request: Request):
|
||||
user, _token = _current_user(request)
|
||||
return _user_out(user)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats", response_model=ChatOut, status_code=201)
|
||||
def create_chat(payload: CreateChat, request: Request):
|
||||
user, _token = _current_user(request)
|
||||
member_ids = [uuid.UUID(value) for value in payload.member_ids]
|
||||
if user.id not in member_ids:
|
||||
raise _api_error("invalid_request", "Вызывающий должен входить в member_ids", 400)
|
||||
|
||||
try:
|
||||
with SessionLocal.begin() as session:
|
||||
chat = Chat(title=payload.title)
|
||||
session.add(chat)
|
||||
session.flush()
|
||||
session.add_all(ChatMember(chat_id=chat.id, user_id=member_id) for member_id in member_ids)
|
||||
session.flush()
|
||||
result = _chat_out(session, chat)
|
||||
except DBAPIError as exc:
|
||||
if getattr(getattr(exc, "orig", None), "sqlstate", None) in {"23503", "23505"}:
|
||||
raise _api_error("invalid_request", "Неизвестный участник", 400) from exc
|
||||
raise
|
||||
return result
|
||||
|
||||
|
||||
@app.get("/api/v1/chats", response_model=ChatPage)
|
||||
def list_chats(request: Request, limit: int = 50, cursor: str | None = None):
|
||||
user, _token = _current_user(request)
|
||||
if limit < 1 or limit > 100:
|
||||
raise _api_error("invalid_request", "limit вне диапазона", 400)
|
||||
statement = (
|
||||
select(Chat)
|
||||
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
||||
.where(ChatMember.user_id == user.id)
|
||||
.order_by(Chat.created_at, Chat.id)
|
||||
)
|
||||
if cursor is not None:
|
||||
payload = _decode_cursor(cursor)
|
||||
if payload.get("u") != str(user.id):
|
||||
raise _api_error("invalid_request", "Неверный cursor", 400)
|
||||
created_at, chat_id = _cursor_position(payload)
|
||||
statement = statement.where(tuple_(Chat.created_at, Chat.id) > tuple_(created_at, chat_id))
|
||||
|
||||
with SessionLocal() as session:
|
||||
chats = session.scalars(statement.limit(limit + 1)).all()
|
||||
has_more = len(chats) > limit
|
||||
page = chats[:limit]
|
||||
items = [_chat_out(session, chat) for chat in page]
|
||||
next_cursor = None
|
||||
if has_more:
|
||||
last = page[-1]
|
||||
next_cursor = _encode_cursor({"u": str(user.id), "t": _iso(last.created_at), "i": str(last.id)})
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}", response_model=ChatOut)
|
||||
def get_chat(chat_id: uuid.UUID, request: Request):
|
||||
user, _token = _current_user(request)
|
||||
with SessionLocal() as session:
|
||||
chat = _get_chat_for_member(session, chat_id, user.id)
|
||||
if chat is None:
|
||||
raise _api_error("not_found", "Объект не найден", 404)
|
||||
return _chat_out(session, chat)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", response_model=MessageOut, status_code=201)
|
||||
def create_message(chat_id: uuid.UUID, payload: CreateMessage, request: Request):
|
||||
user, _token = _current_user(request)
|
||||
with SessionLocal.begin() as session:
|
||||
chat = _get_chat_for_member(session, chat_id, user.id)
|
||||
if chat is None:
|
||||
raise _api_error("not_found", "Объект не найден", 404)
|
||||
if not payload.text.strip():
|
||||
raise _api_error("invalid_request", "Сообщение не может состоять только из пробелов", 400)
|
||||
message = Message(chat_id=chat_id, sender_id=user.id, text=payload.text)
|
||||
session.add(message)
|
||||
session.flush()
|
||||
result = _message_out(message)
|
||||
return result
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
def list_messages(chat_id: uuid.UUID, request: Request, limit: int = 50, cursor: str | None = None):
|
||||
user, _token = _current_user(request)
|
||||
with SessionLocal() as session:
|
||||
chat = _get_chat_for_member(session, chat_id, user.id)
|
||||
if chat is None:
|
||||
raise _api_error("not_found", "Объект не найден", 404)
|
||||
if limit < 1 or limit > 100:
|
||||
raise _api_error("invalid_request", "limit вне диапазона", 400)
|
||||
after = None
|
||||
if cursor is not None:
|
||||
payload = _decode_cursor(cursor)
|
||||
if payload.get("c") != str(chat_id):
|
||||
raise _api_error("invalid_request", "cursor от другого чата", 400)
|
||||
after = _cursor_position(payload)
|
||||
statement = select(Message).where(Message.chat_id == chat_id)
|
||||
if after is not None:
|
||||
statement = statement.where(tuple_(Message.created_at, Message.id) > tuple_(*after))
|
||||
statement = statement.order_by(Message.created_at, Message.id).limit(limit + 1)
|
||||
rows = session.scalars(statement).all()
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
items = [_message_out(message) for message in page]
|
||||
|
||||
next_cursor = None
|
||||
if has_more:
|
||||
last = page[-1]
|
||||
next_cursor = _encode_cursor({"c": str(chat_id), "t": _iso(last.created_at), "i": str(last.id)})
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
Reference in New Issue
Block a user