Files

502 lines
17 KiB
Python

import base64
import binascii
import hashlib
import json
import os
import secrets
import time
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
import psycopg
from psycopg.rows import dict_row
from fastapi import FastAPI, Query, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field, field_validator
from argon2 import PasswordHasher
from argon2.exceptions import VerificationError
APP_HOST = os.getenv("APP_HOST", "0.0.0.0")
APP_PORT = int(os.getenv("APP_PORT", "8080"))
DATABASE_URL = os.getenv("DATABASE_URL", "")
DATABASE_URL_FILE = os.getenv("DATABASE_URL_FILE", "")
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
MIGRATIONS_DIR = Path(__file__).parent / "migrations"
PASSWORD_HASHER = PasswordHasher()
class APIError(Exception):
def __init__(self, status_code: int, code: str, message: str):
self.status_code = status_code
self.code = code
self.message = message
class CreateUser(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", "password")
@classmethod
def validate_non_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("value must not be blank")
return value
class CreateChat(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)
@field_validator("title")
@classmethod
def validate_title(cls, value: str) -> str:
if not value.strip():
raise ValueError("title must not be blank")
return value
@field_validator("member_ids")
@classmethod
def validate_member_ids(cls, value: list[str]) -> list[str]:
if len(set(value)) != len(value):
raise ValueError("member_ids must be unique")
for member_id in value:
try:
uuid.UUID(member_id)
except ValueError as exc:
raise ValueError("member_ids must contain UUIDs") from exc
return value
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(..., min_length=1, max_length=4000)
@field_validator("text")
@classmethod
def validate_text(cls, value: str) -> str:
if not value.strip():
raise ValueError("text must not be blank")
return value
def utc_now() -> datetime:
return datetime.now(timezone.utc)
def iso(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace(
"+00:00", "Z"
)
def database_url() -> str:
if DATABASE_URL:
return DATABASE_URL
if DATABASE_URL_FILE:
try:
return Path(DATABASE_URL_FILE).read_text(encoding="utf-8").strip()
except OSError as exc:
raise RuntimeError("database URL file is not readable") from exc
raise RuntimeError("DATABASE_URL or DATABASE_URL_FILE is required")
def db():
return psycopg.connect(database_url(), row_factory=dict_row)
def apply_migrations() -> None:
with db() as conn:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT now()
)
"""
)
for path in sorted(MIGRATIONS_DIR.glob("*.sql")):
version = path.name.split("_", 1)[0]
applied = conn.execute(
"SELECT 1 FROM schema_migrations WHERE version = %s", (version,)
).fetchone()
if applied is None:
for statement in path.read_text(encoding="utf-8").split(";"):
if statement.strip():
conn.execute(statement)
conn.execute(
"INSERT INTO schema_migrations(version) VALUES (%s)", (version,)
)
def wait_for_database() -> None:
deadline = time.monotonic() + 60
last_error: Exception | None = None
while time.monotonic() < deadline:
try:
apply_migrations()
return
except (OSError, psycopg.Error) as exc:
last_error = exc
time.sleep(1)
raise RuntimeError("database did not become ready") from last_error
def error_response(request: Request, status_code: int, code: str, message: str):
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
headers = {"X-Request-Id": request_id}
if status_code == 401:
headers["WWW-Authenticate"] = (
'Bearer realm="messenger"'
if request.url.path != "/api/v1/auth/sessions"
else 'Basic realm="messenger", charset="UTF-8"'
)
return JSONResponse(
status_code=status_code,
content={"error": {"code": code, "message": message, "request_id": request_id}},
headers=headers,
)
def bearer_user(request: Request) -> dict[str, Any]:
header = request.headers.get("Authorization", "")
scheme, _, token = header.partition(" ")
if scheme.lower() != "bearer" or not token or " " in token:
raise APIError(401, "unauthorized", "valid bearer session required")
hashed_token = token_hash(token)
with db() as conn:
user = 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_hash = %s AND s.revoked_at IS NULL
AND s.expires_at > now()
""",
(hashed_token,),
).fetchone()
if user is None:
raise APIError(401, "unauthorized", "valid bearer session required")
return user
def basic_credentials(request: Request) -> tuple[str, str]:
header = request.headers.get("Authorization", "")
scheme, _, encoded = header.partition(" ")
if scheme.lower() != "basic" or not encoded:
raise APIError(401, "unauthorized", "basic credentials required")
try:
decoded = base64.b64decode(encoded, validate=True).decode("utf-8")
username, separator, password = decoded.partition(":")
except (binascii.Error, UnicodeDecodeError):
raise APIError(401, "unauthorized", "invalid credentials") from None
if not separator or not username or not password:
raise APIError(401, "unauthorized", "invalid credentials")
return username, password
def token_hash(token: str) -> str:
try:
return hashlib.sha256(token.encode("ascii", "strict")).hexdigest()
except UnicodeEncodeError:
raise APIError(401, "unauthorized", "valid bearer session required") from None
def encode_cursor(created_at: datetime, object_id: uuid.UUID) -> str:
payload = json.dumps(
{"created_at": iso(created_at), "id": str(object_id)},
separators=(",", ":"),
).encode()
return base64.urlsafe_b64encode(payload).decode().rstrip("=")
def decode_cursor(cursor: str) -> tuple[datetime, uuid.UUID]:
try:
padding = "=" * ((4 - len(cursor) % 4) % 4)
payload = json.loads(
base64.urlsafe_b64decode((cursor + padding).encode()).decode()
)
created_at = datetime.fromisoformat(payload["created_at"].replace("Z", "+00:00"))
return created_at, uuid.UUID(payload["id"])
except (KeyError, TypeError, ValueError, UnicodeDecodeError, binascii.Error, json.JSONDecodeError):
raise APIError(400, "invalid_request", "cursor is invalid") from None
app = FastAPI(title="MTUSI Messenger Lab2")
@app.on_event("startup")
def startup() -> None:
wait_for_database()
@app.middleware("http")
async def add_request_id(request: Request, call_next):
request_id = request.headers.get("X-Request-Id") or 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 api_error_handler(request: Request, exc: APIError):
return error_response(request, exc.status_code, exc.code, exc.message)
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
return error_response(request, 400, "invalid_request", "invalid request")
@app.exception_handler(Exception)
async def unexpected_error_handler(request: Request, exc: Exception):
return error_response(request, 500, "internal_error", "internal server error")
@app.get("/health/live")
def health_live():
return {"status": "ok"}
@app.get("/health/ready")
def health_ready():
try:
with db() as conn:
conn.execute("SELECT 1")
except (OSError, psycopg.Error):
raise APIError(503, "unavailable", "database unavailable")
return {"status": "ok"}
@app.post("/api/v1/users", status_code=201)
def create_user(payload: CreateUser):
user_id = uuid.uuid4()
password_hash = PASSWORD_HASHER.hash(payload.password)
try:
with db() as conn:
user = conn.execute(
"""
INSERT INTO users(id, username, display_name, password_hash)
VALUES (%s, %s, %s, %s)
RETURNING id, username, display_name, created_at
""",
(user_id, payload.username, payload.display_name, password_hash),
).fetchone()
except psycopg.errors.UniqueViolation:
raise APIError(409, "conflict", "user already exists") from None
return {**user, "id": str(user["id"]), "created_at": iso(user["created_at"])}
@app.post("/api/v1/auth/sessions", status_code=201)
def create_session(request: Request):
username, password = basic_credentials(request)
with db() as conn:
user = conn.execute(
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s",
(username,),
).fetchone()
if user is None:
raise APIError(401, "unauthorized", "invalid credentials")
try:
PASSWORD_HASHER.verify(user["password_hash"], password)
except VerificationError:
raise APIError(401, "unauthorized", "invalid credentials") from None
token = secrets.token_urlsafe(32)
expires_at = utc_now() + timedelta(seconds=SESSION_TTL_SECONDS)
with db() as conn:
conn.execute(
"INSERT INTO sessions(token_hash, user_id, expires_at) VALUES (%s, %s, %s)",
(token_hash(token), user["id"], expires_at),
)
public_user = {
"id": str(user["id"]),
"username": user["username"],
"display_name": user["display_name"],
"created_at": iso(user["created_at"]),
}
return {
"token": token,
"token_type": "Bearer",
"expires_at": iso(expires_at),
"user": public_user,
}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def revoke_session(request: Request):
bearer_user(request)
header = request.headers["Authorization"]
token = header.split(" ", 1)[1]
with db() as conn:
conn.execute(
"UPDATE sessions SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL",
(token_hash(token),),
)
return Response(status_code=204)
@app.get("/api/v1/users/me")
def current_user(request: Request):
user = bearer_user(request)
return {**user, "id": str(user["id"]), "created_at": iso(user["created_at"])}
@app.post("/api/v1/chats", status_code=201)
def create_chat(payload: CreateChat, request: Request):
actor = bearer_user(request)
member_ids = [uuid.UUID(member_id) for member_id in payload.member_ids]
if actor["id"] not in member_ids:
raise APIError(400, "invalid_request", "actor must be included in member_ids")
chat_id = uuid.uuid4()
with db() as conn:
existing = conn.execute(
"SELECT id FROM users WHERE id = ANY(%s)", (member_ids,)
).fetchall()
if len(existing) != len(member_ids):
raise APIError(400, "invalid_request", "member not found")
chat = conn.execute(
"INSERT INTO chats(id, title) VALUES (%s, %s) RETURNING id, title, created_at",
(chat_id, payload.title),
).fetchone()
with conn.cursor() as cur:
cur.executemany(
"INSERT INTO chat_members(chat_id, user_id) VALUES (%s, %s)",
[(chat_id, member_id) for member_id in member_ids],
)
return {
"id": str(chat["id"]),
"title": chat["title"],
"member_ids": sorted(str(member_id) for member_id in member_ids),
"created_at": iso(chat["created_at"]),
}
def chat_for_user(conn, chat_id: uuid.UUID, user_id: uuid.UUID):
return conn.execute(
"""
SELECT c.id, c.title, c.created_at
FROM chats c JOIN chat_members m ON m.chat_id = c.id
WHERE c.id = %s AND m.user_id = %s
""",
(chat_id, user_id),
).fetchone()
def public_chat(conn, chat: dict[str, Any]) -> dict[str, Any]:
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(row["user_id"]) for row in members],
"created_at": iso(chat["created_at"]),
}
@app.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: uuid.UUID, request: Request):
actor = bearer_user(request)
with db() as conn:
chat = chat_for_user(conn, chat_id, actor["id"])
if chat is None:
raise APIError(404, "not_found", "chat not found")
return public_chat(conn, chat)
@app.get("/api/v1/chats")
def list_chats(request: Request, limit: int = Query(50, ge=1, le=100), cursor: str | None = None):
actor = bearer_user(request)
after = decode_cursor(cursor) if cursor else None
with db() as conn:
rows = conn.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
AND (%s::timestamptz IS NULL OR (c.created_at, c.id) > (%s::timestamptz, %s::uuid))
ORDER BY c.created_at, c.id
LIMIT %s
""",
(actor["id"], after[0] if after else None, after[0] if after else None,
after[1] if after else None, limit + 1),
).fetchall()
items = [public_chat(conn, row) for row in rows[:limit]]
next_cursor = (
encode_cursor(rows[limit - 1]["created_at"], rows[limit - 1]["id"])
if len(rows) > limit
else None
)
return {"items": items, "next_cursor": next_cursor}
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def create_message(chat_id: uuid.UUID, payload: CreateMessage, request: Request):
actor = bearer_user(request)
message_id = uuid.uuid4()
with db() as conn:
if chat_for_user(conn, chat_id, actor["id"]) is None:
raise APIError(404, "not_found", "chat not accessible")
message = conn.execute(
"""
INSERT INTO messages(id, chat_id, sender_id, text)
VALUES (%s, %s, %s, %s)
RETURNING id, chat_id, sender_id, text, created_at
""",
(message_id, chat_id, actor["id"], payload.text),
).fetchone()
return {**message, "id": str(message["id"]), "chat_id": str(message["chat_id"]),
"sender_id": str(message["sender_id"]), "created_at": iso(message["created_at"])}
@app.get("/api/v1/chats/{chat_id}/messages")
def list_messages(
chat_id: uuid.UUID,
request: Request,
limit: int = Query(50, ge=1, le=100),
cursor: str | None = None,
):
actor = bearer_user(request)
after = decode_cursor(cursor) if cursor else None
with db() as conn:
if chat_for_user(conn, chat_id, actor["id"]) is None:
raise APIError(404, "not_found", "chat not accessible")
rows = conn.execute(
"""
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = %s
AND (%s::timestamptz IS NULL OR (created_at, id) > (%s::timestamptz, %s::uuid))
ORDER BY created_at, id
LIMIT %s
""",
(chat_id, after[0] if after else None, after[0] if after else None,
after[1] if after else None, limit + 1),
).fetchall()
items = [
{**row, "id": str(row["id"]), "chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]), "created_at": iso(row["created_at"])}
for row in rows[:limit]
]
next_cursor = (
encode_cursor(rows[limit - 1]["created_at"], rows[limit - 1]["id"])
if len(rows) > limit
else None
)
return {"items": items, "next_cursor": next_cursor}
if __name__ == "__main__":
import uvicorn
uvicorn.run("app:app", host=APP_HOST, port=APP_PORT, reload=False)