ЛР 2 - БПИ2304 - Лесковский- на 3 #188

Closed
Leskovskiy wants to merge 1 commits from Leskovskiy/mtusi2026lab2-Leskovskiy:lab2-final into master
11 changed files with 556 additions and 0 deletions
+11
View File
@@ -0,0 +1,11 @@
FROM python:3.12-slim AS runtime
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY migrations ./migrations
COPY src ./src
RUN useradd -m app && chown -R app /app
USER app
EXPOSE 8080
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8080"]
+41
View File
@@ -0,0 +1,41 @@
services:
postgres:
image: postgres:16.4
environment:
POSTGRES_USER: messenger
POSTGRES_PASSWORD_FILE: /run/secrets/pg_password
POSTGRES_DB: messenger
secrets: [pg_password]
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
interval: 3s
timeout: 3s
retries: 20
api:
build: .
depends_on:
postgres:
condition: service_healthy
environment:
SESSION_TTL_SECONDS: "3600"
DATABASE_URL_FILE: /run/secrets/database_url
secrets: [database_url]
ports:
- "8080:8080"
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request;urllib.request.urlopen('http://localhost:8080/health/ready',timeout=2)"]
interval: 3s
timeout: 3s
retries: 30
secrets:
pg_password:
file: ./secrets/pg_password.txt
database_url:
file: ./secrets/database_url.txt
volumes:
pgdata:
+40
View File
@@ -0,0 +1,40 @@
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE IF NOT EXISTS users (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS chats (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS chat_members (
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
PRIMARY KEY (chat_id, user_id)
);
CREATE TABLE IF NOT EXISTS messages (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users(id),
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS messages_chat_created_idx ON messages (chat_id, created_at, id);
CREATE TABLE IF NOT EXISTS sessions (
token_hash text PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at timestamptz NOT NULL
);
CREATE INDEX IF NOT EXISTS sessions_user_idx ON sessions (user_id);
CREATE INDEX IF NOT EXISTS sessions_expires_idx ON sessions (expires_at);
+5
View File
@@ -0,0 +1,5 @@
fastapi==0.115.0
uvicorn[standard]==0.30.6
psycopg[binary,pool]==3.2.3
argon2-cffi==23.1.0
pydantic==2.9.2
+9
View File
@@ -0,0 +1,9 @@
@echo off
docker compose restart api postgres
:wait
docker compose exec -T api python -c "import urllib.request;urllib.request.urlopen('http://localhost:8080/health/ready',timeout=2)" >nul 2>&1
if %errorlevel% neq 0 (
timeout /t 1 /nobreak >nul
goto wait
)
echo restart OK
Executable → Regular
View File
View File
+71
View File
@@ -0,0 +1,71 @@
import hashlib
import os
import secrets
from datetime import datetime, timedelta, timezone
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
from .db import pool
TTL = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
hasher = PasswordHasher()
def hash_password(pw: str) -> str:
return hasher.hash(pw)
def verify_password(hash_: str, pw: str) -> bool:
try:
return hasher.verify(hash_, pw)
except VerifyMismatchError:
return False
def _hash_token(token: str) -> str:
return hashlib.sha256(token.encode()).hexdigest()
def create_session(user_id: str):
token = secrets.token_urlsafe(32)
expires = datetime.now(timezone.utc) + timedelta(seconds=TTL)
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute(
"INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (%s,%s,%s)",
(_hash_token(token), user_id, expires),
)
conn.commit()
return token, expires
def resolve_session(token: str):
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT user_id, expires_at FROM sessions WHERE token_hash=%s",
(_hash_token(token),),
)
row = cur.fetchone()
if not row:
return None
user_id, expires = row
if expires <= datetime.now(timezone.utc):
revoke_session(token)
return None
return user_id
def revoke_session(token: str) -> None:
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("DELETE FROM sessions WHERE token_hash=%s", (_hash_token(token),))
conn.commit()
def purge_expired() -> None:
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("DELETE FROM sessions WHERE expires_at < now()")
conn.commit()
+35
View File
@@ -0,0 +1,35 @@
import os
from contextlib import contextmanager
from pathlib import Path
from psycopg_pool import ConnectionPool
def _read_secret(env_var: str, file_env_var: str) -> str:
if os.environ.get(env_var):
return os.environ[env_var]
path = os.environ.get(file_env_var)
if path and Path(path).is_file():
# Используем utf-8-sig, чтобы игнорировать BOM (невидимый маркер),
# который Windows иногда добавляет в начало файла.
return Path(path).read_text(encoding="utf-8-sig").strip()
raise RuntimeError(f"Neither {env_var} nor {file_env_var} is set")
DATABASE_URL = _read_secret("DATABASE_URL", "DATABASE_URL_FILE")
pool = ConnectionPool(conninfo=DATABASE_URL, min_size=1, max_size=10, open=True)
def run_migrations() -> None:
sql = Path("migrations/001_init.sql").read_text(encoding="utf-8-sig")
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute(sql)
conn.commit()
@contextmanager
def tx():
with pool.connection() as conn:
with conn.transaction():
yield conn
+40
View File
@@ -0,0 +1,40 @@
import uuid
from fastapi import Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
class ApiError(Exception):
def __init__(self, status: int, code: str, message: str, headers=None):
self.status = status
self.code = code
self.message = message
self.headers = headers or {}
def request_id_of(request: Request) -> str:
# Берем ID из состояния запроса, если он там есть
if hasattr(request.state, "request_id"):
return request.state.request_id
# Иначе смотрим в заголовках или генерируем новый
return request.headers.get("X-Request-Id") or uuid.uuid4().hex
async def api_error_handler(request: Request, exc: ApiError):
rid = request_id_of(request)
body = {"error": {"code": exc.code, "message": exc.message, "request_id": rid}}
headers = {"X-Request-Id": rid, **exc.headers}
return JSONResponse(body, status_code=exc.status, headers=headers)
async def unhandled_handler(request: Request, exc: Exception):
rid = request_id_of(request)
body = {"error": {"code": "internal_error", "message": "internal error", "request_id": rid}}
return JSONResponse(body, status_code=500, headers={"X-Request-Id": rid})
async def validation_exception_handler(request: Request, exc: RequestValidationError):
rid = request_id_of(request)
body = {"error": {"code": "invalid_request", "message": "Ошибка валидации данных", "request_id": rid}}
return JSONResponse(body, status_code=400, headers={"X-Request-Id": rid})
+304
View File
@@ -0,0 +1,304 @@
import base64
import uuid
from contextlib import asynccontextmanager
from datetime import timezone
from typing import Optional
from fastapi import FastAPI, Header, Request, Response
from fastapi.exceptions import RequestValidationError
from pydantic import BaseModel, Field, field_validator
from .auth import (create_session, hash_password, purge_expired,
resolve_session, revoke_session, verify_password)
from .db import pool, run_migrations, tx
from .errors import (ApiError, api_error_handler, request_id_of,
unhandled_handler, validation_exception_handler)
@asynccontextmanager
async def lifespan(app: FastAPI):
run_migrations()
purge_expired()
yield
app = FastAPI(lifespan=lifespan)
app.add_exception_handler(ApiError, api_error_handler)
app.add_exception_handler(RequestValidationError, validation_exception_handler)
app.add_exception_handler(Exception, unhandled_handler)
@app.middleware("http")
async def _rid_middleware(request: Request, call_next):
rid = request_id_of(request)
request.state.request_id = rid
response = await call_next(request)
response.headers["X-Request-Id"] = rid
return response
USERNAME_RE = r"^[a-z0-9_]{3,32}$"
class CreateUser(BaseModel):
username: str = Field(pattern=USERNAME_RE)
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
class CreateChat(BaseModel):
title: str = Field(min_length=1, max_length=100)
member_ids: list[uuid.UUID] = Field(min_length=1, max_length=100)
@field_validator("member_ids")
@classmethod
def unique_members(cls, v):
if len(set(v)) != len(v):
raise ValueError("duplicate member_ids")
return v
class CreateMessage(BaseModel):
text: str = Field(min_length=1, max_length=4000)
def _iso(dt) -> str:
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
def _row_to_user(row) -> dict:
return {"id": str(row[0]), "username": row[1],
"display_name": row[2], "created_at": _iso(row[3])}
def _require_bearer(authorization: Optional[str]) -> str:
if not authorization or not authorization.startswith("Bearer "):
raise ApiError(401, "unauthorized", "Требуется Bearer-токен",
{"WWW-Authenticate": 'Bearer realm="messenger"'})
token = authorization[len("Bearer "):]
user_id = resolve_session(token)
if not user_id:
raise ApiError(401, "unauthorized", "Сессия недействительна",
{"WWW-Authenticate": 'Bearer realm="messenger"'})
return str(user_id)
def _is_member(conn, chat_id: str, user_id: str) -> bool:
with conn.cursor() as cur:
cur.execute("SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s",
(chat_id, user_id))
return cur.fetchone() is not None
@app.get("/health/live")
def live():
return {"status": "ok"}
@app.get("/health/ready")
def ready():
try:
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT 1")
return {"status": "ok"}
except Exception:
raise ApiError(503, "unavailable", "База недоступна")
@app.post("/api/v1/users", status_code=201)
def register(body: CreateUser):
with tx() as conn:
with conn.cursor() as cur:
cur.execute("SELECT 1 FROM users WHERE username=%s", (body.username,))
if cur.fetchone():
raise ApiError(409, "conflict", "Username занят")
cur.execute(
"INSERT INTO users (username, display_name, password_hash) "
"VALUES (%s,%s,%s) RETURNING id, username, display_name, created_at",
(body.username, body.display_name, hash_password(body.password)),
)
row = cur.fetchone()
return _row_to_user(row)
@app.get("/api/v1/users/me")
def me(authorization: Optional[str] = Header(default=None)):
uid = _require_bearer(authorization)
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT id, username, display_name, created_at FROM users WHERE id=%s",
(uid,))
row = cur.fetchone()
if not row:
raise ApiError(401, "unauthorized", "Пользователь не найден",
{"WWW-Authenticate": 'Bearer realm="messenger"'})
return _row_to_user(row)
@app.post("/api/v1/auth/sessions", status_code=201)
def login(authorization: Optional[str] = Header(default=None)):
if not authorization or not authorization.startswith("Basic "):
raise ApiError(401, "unauthorized", "Требуется Basic",
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
try:
raw = base64.b64decode(authorization[len("Basic "):], validate=True).decode("utf-8")
username, password = raw.split(":", 1)
except Exception:
raise ApiError(400, "invalid_request", "Некорректный Basic")
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT id, password_hash FROM users WHERE username=%s", (username,))
row = cur.fetchone()
if not row or not verify_password(row[1], password):
raise ApiError(401, "unauthorized", "Неверные учётные данные",
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
token, expires = create_session(str(row[0]))
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT id, username, display_name, created_at FROM users WHERE id=%s",
(row[0],))
u = cur.fetchone()
return {"token": token, "token_type": "Bearer",
"expires_at": _iso(expires), "user": _row_to_user(u)}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def logout(authorization: Optional[str] = Header(default=None)):
if not authorization or not authorization.startswith("Bearer "):
raise ApiError(401, "unauthorized", "Требуется Bearer",
{"WWW-Authenticate": 'Bearer realm="messenger"'})
token = authorization[len("Bearer "):]
if not resolve_session(token):
raise ApiError(401, "unauthorized", "Сессия недействительна",
{"WWW-Authenticate": 'Bearer realm="messenger"'})
revoke_session(token)
return Response(status_code=204)
def _row_to_chat(row, members) -> dict:
return {"id": str(row[0]), "title": row[1],
"member_ids": [str(m) for m in members], "created_at": _iso(row[2])}
@app.post("/api/v1/chats", status_code=201)
def create_chat(body: CreateChat, authorization: Optional[str] = Header(default=None)):
uid = _require_bearer(authorization)
if uuid.UUID(uid) not in body.member_ids:
raise ApiError(400, "invalid_request", "Вызывающий должен быть в member_ids")
with tx() as conn:
with conn.cursor() as cur:
cur.execute("SELECT id FROM users WHERE id = ANY(%s)",
([str(m) for m in body.member_ids],))
found = {str(r[0]) for r in cur.fetchall()}
if found != {str(m) for m in body.member_ids}:
raise ApiError(400, "invalid_request", "Неизвестный участник")
cur.execute("INSERT INTO chats (title) VALUES (%s) "
"RETURNING id, title, created_at", (body.title,))
row = cur.fetchone()
chat_id = row[0]
cur.executemany("INSERT INTO chat_members (chat_id, user_id) VALUES (%s,%s)",
[(chat_id, str(m)) for m in body.member_ids])
return _row_to_chat(row, body.member_ids)
@app.get("/api/v1/chats")
def list_chats(limit: int = 50, cursor: Optional[str] = None,
authorization: Optional[str] = Header(default=None)):
uid = _require_bearer(authorization)
if not (1 <= limit <= 100):
raise ApiError(400, "invalid_request", "limit 1..100")
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT c.id, c.title, c.created_at 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",
(uid, limit),
)
rows = cur.fetchall()
items = []
for r in rows:
cur.execute("SELECT user_id FROM chat_members WHERE chat_id=%s", (r[0],))
members = [x[0] for x in cur.fetchall()]
items.append(_row_to_chat(r, members))
return {"items": items, "next_cursor": None}
@app.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: uuid.UUID, authorization: Optional[str] = Header(default=None)):
uid = _require_bearer(authorization)
with pool.connection() as conn:
if not _is_member(conn, str(chat_id), uid):
raise ApiError(404, "not_found", "Чат не найден")
with conn.cursor() as cur:
cur.execute("SELECT id, title, created_at FROM chats WHERE id=%s", (str(chat_id),))
row = cur.fetchone()
cur.execute("SELECT user_id FROM chat_members WHERE chat_id=%s", (str(chat_id),))
members = [x[0] for x in cur.fetchall()]
return _row_to_chat(row, members)
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def send_message(chat_id: uuid.UUID, body: CreateMessage,
authorization: Optional[str] = Header(default=None)):
uid = _require_bearer(authorization)
if not body.text.strip():
raise ApiError(400, "invalid_request", "Пустой текст")
with tx() as conn:
if not _is_member(conn, str(chat_id), uid):
raise ApiError(404, "not_found", "Чат не найден")
with conn.cursor() as cur:
cur.execute(
"INSERT INTO messages (chat_id, sender_id, text) VALUES (%s,%s,%s) "
"RETURNING id, chat_id, sender_id, text, created_at",
(str(chat_id), uid, body.text),
)
row = cur.fetchone()
return {"id": str(row[0]), "chat_id": str(row[1]), "sender_id": str(row[2]),
"text": row[3], "created_at": _iso(row[4])}
@app.get("/api/v1/chats/{chat_id}/messages")
def list_messages(chat_id: uuid.UUID, limit: int = 50, cursor: Optional[str] = None,
authorization: Optional[str] = Header(default=None)):
uid = _require_bearer(authorization)
if not (1 <= limit <= 100):
raise ApiError(400, "invalid_request", "limit 1..100")
with pool.connection() as conn:
if not _is_member(conn, str(chat_id), uid):
raise ApiError(404, "not_found", "Чат не найден")
params = [str(chat_id)]
where = "chat_id=%s"
if cursor:
try:
ts, mid = cursor.split("|")
params += [ts, mid]
where += " AND (created_at, id) > (%s::timestamptz, %s::uuid)"
except Exception:
raise ApiError(400, "invalid_request", "Неверный cursor")
params.append(limit + 1)
with conn.cursor() as cur:
cur.execute(
f"SELECT id, chat_id, sender_id, text, created_at FROM messages "
f"WHERE {where} ORDER BY created_at, id LIMIT %s", params)
rows = cur.fetchall()
has_more = len(rows) > limit
if has_more:
rows = rows[:limit]
items = [{"id": str(r[0]), "chat_id": str(r[1]), "sender_id": str(r[2]),
"text": r[3], "created_at": _iso(r[4])} for r in rows]
next_cursor = None
if has_more and rows:
last = rows[-1]
next_cursor = f"{last[4].isoformat()}|{last[0]}"
return {"items": items, "next_cursor": next_cursor}