forked from mtusi2026/mtusi2026lab5
897 lines
36 KiB
Python
897 lines
36 KiB
Python
from __future__ import annotations
|
|
|
|
import base64
|
|
import json
|
|
import os
|
|
import secrets
|
|
import socket
|
|
import re
|
|
import uuid
|
|
from datetime import datetime, timedelta, timezone
|
|
from pathlib import Path
|
|
from typing import Any, Dict, List, Optional, Tuple
|
|
|
|
import psycopg
|
|
from psycopg_pool import ConnectionPool
|
|
import redis
|
|
from argon2 import PasswordHasher
|
|
from fastapi import FastAPI, Header, HTTPException, Request
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse, Response, StreamingResponse
|
|
from starlette.concurrency import run_in_threadpool
|
|
from pydantic import BaseModel, ConfigDict, StringConstraints, ValidationError
|
|
from typing_extensions import Annotated
|
|
|
|
|
|
APP_HOST = os.getenv("APP_HOST", "0.0.0.0")
|
|
APP_PORT = int(os.getenv("APP_PORT", "8080"))
|
|
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
|
INSTANCE_ID = os.getenv("INSTANCE_ID", socket.gethostname())
|
|
|
|
USERNAME_RE = r"^[a-z0-9_]{3,32}$"
|
|
|
|
|
|
class ApiError(Exception):
|
|
def __init__(self, status_code: int, code: str, message: str, *, headers: Optional[Dict[str, str]] = None):
|
|
self.status_code = status_code
|
|
self.code = code
|
|
self.message = message
|
|
self.headers = headers or {}
|
|
|
|
|
|
class UserOut(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
id: str
|
|
username: str
|
|
display_name: str
|
|
created_at: str
|
|
|
|
|
|
class SessionOut(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
token: str
|
|
token_type: str
|
|
expires_at: str
|
|
user: UserOut
|
|
|
|
|
|
class ChatOut(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
id: str
|
|
title: str
|
|
member_ids: List[str]
|
|
created_at: str
|
|
|
|
|
|
class MessageOut(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
id: str
|
|
chat_id: str
|
|
sender_id: str
|
|
text: str
|
|
created_at: str
|
|
attachment_ids: List[str]
|
|
|
|
|
|
class CreateUserIn(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
username: Annotated[str, StringConstraints(pattern=USERNAME_RE, min_length=3, max_length=32)]
|
|
display_name: Annotated[str, StringConstraints(min_length=1, max_length=100)]
|
|
password: Annotated[str, StringConstraints(min_length=12, max_length=128)]
|
|
|
|
|
|
class CreateChatIn(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
title: Annotated[str, StringConstraints(min_length=1, max_length=100)]
|
|
member_ids: List[str]
|
|
|
|
|
|
class CreateMessageIn(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
attachment_ids: List[str] = []
|
|
text: Annotated[str, StringConstraints(max_length=4000)]
|
|
|
|
|
|
class Store:
|
|
def __init__(self) -> None:
|
|
self.connection_url = self._resolve_database_url()
|
|
self.cache_url = self._resolve_cache_url()
|
|
self.shared_cache = redis.Redis.from_url(self.cache_url, decode_responses=True, socket_connect_timeout=2, socket_timeout=2)
|
|
self.session_store = os.getenv("SESSION_STORE", "valkey")
|
|
self.password_hasher = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=2, hash_len=32, salt_len=16)
|
|
self.pool = ConnectionPool(
|
|
self.connection_url, min_size=1,
|
|
max_size=int(os.getenv("DB_POOL_MAX_SIZE", "10")),
|
|
timeout=5, max_waiting=20, open=False,
|
|
kwargs={"connect_timeout": 5, "autocommit": False,
|
|
"options": "-c statement_timeout=5000 -c lock_timeout=500"},
|
|
)
|
|
|
|
def _resolve_database_url(self) -> str:
|
|
value = os.getenv("DATABASE_URL")
|
|
if value:
|
|
return value
|
|
secret_path = os.getenv("DATABASE_URL_FILE")
|
|
if secret_path and os.path.exists(secret_path):
|
|
with open(secret_path, "r", encoding="utf-8") as handle:
|
|
return handle.read().strip()
|
|
return os.getenv("DEFAULT_DATABASE_URL", "postgresql://messenger:messenger@localhost:5432/messenger")
|
|
|
|
def _resolve_cache_url(self) -> str:
|
|
value = os.getenv("CACHE_URL")
|
|
if value:
|
|
return value
|
|
secret_path = os.getenv("CACHE_URL_FILE")
|
|
if secret_path and os.path.exists(secret_path):
|
|
with open(secret_path, "r", encoding="utf-8") as handle:
|
|
return handle.read().strip()
|
|
return os.getenv("DEFAULT_CACHE_URL", "redis://localhost:6379/0")
|
|
|
|
def connect(self):
|
|
return self.pool.connection()
|
|
|
|
def cache_client(self):
|
|
if os.getenv("CACHE_CLIENT_MODE", "shared") == "shared":
|
|
return self.shared_cache
|
|
return redis.Redis.from_url(self.cache_url, decode_responses=True, socket_connect_timeout=2, socket_timeout=2)
|
|
|
|
def cache_session(self, session: Dict[str, Any]) -> None:
|
|
if self.session_store != "valkey":
|
|
return
|
|
try:
|
|
client = self.cache_client()
|
|
ttl_seconds = max(1, int((self.parse_session_expiry(session["expires_at"]) - self.utc_now()).total_seconds()))
|
|
payload = json.dumps({
|
|
"token": session["token"],
|
|
"user_id": session["user_id"],
|
|
"expires_at": session["expires_at"],
|
|
"revoked_at": session.get("revoked_at"),
|
|
"user": session["user"],
|
|
}, separators=(",", ":"), ensure_ascii=False)
|
|
client.setex(f"session:{session['token']}", ttl_seconds, payload)
|
|
except redis.RedisError:
|
|
return
|
|
|
|
def get_cached_session(self, token: str, *, db_session) -> Optional[Dict[str, Any]]:
|
|
if self.session_store != "valkey":
|
|
return None
|
|
try:
|
|
client = self.cache_client()
|
|
payload = client.get(f"session:{token}")
|
|
if not payload:
|
|
return None
|
|
data = json.loads(payload)
|
|
session = {
|
|
"token": data["token"],
|
|
"user_id": data["user_id"],
|
|
"expires_at": data["expires_at"],
|
|
"revoked_at": data.get("revoked_at"),
|
|
"user": data["user"],
|
|
}
|
|
if not self.is_session_valid(session):
|
|
client.delete(f"session:{token}")
|
|
return None
|
|
if session != db_session:
|
|
client.delete(f"session:{token}")
|
|
return None
|
|
return db_session
|
|
except (redis.RedisError, KeyError, TypeError, ValueError):
|
|
return None
|
|
|
|
def delete_cached_session(self, token: str) -> None:
|
|
if self.session_store != "valkey":
|
|
return
|
|
try:
|
|
self.cache_client().delete(f"session:{token}")
|
|
except redis.RedisError:
|
|
return
|
|
|
|
@staticmethod
|
|
def parse_session_expiry(value: Any) -> datetime:
|
|
if isinstance(value, datetime):
|
|
return value.astimezone(timezone.utc)
|
|
if isinstance(value, str):
|
|
return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(timezone.utc)
|
|
raise ValueError("invalid session expiry")
|
|
|
|
def init(self) -> None:
|
|
migration_dir = Path(__file__).resolve().parent / "migrations"
|
|
with self.connect() as conn:
|
|
with conn.cursor() as cur:
|
|
cur.execute("SELECT pg_advisory_xact_lock(202603)")
|
|
cur.execute(
|
|
"""
|
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
version TEXT PRIMARY KEY,
|
|
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
);
|
|
"""
|
|
)
|
|
|
|
applied = set()
|
|
cur.execute("SELECT version FROM schema_migrations")
|
|
for (version,) in cur.fetchall():
|
|
applied.add(version)
|
|
|
|
for migration_path in sorted(migration_dir.glob("*.sql")):
|
|
version = migration_path.stem
|
|
if version in applied:
|
|
continue
|
|
sql = migration_path.read_text(encoding="utf-8")
|
|
cur.execute(sql)
|
|
cur.execute(
|
|
"INSERT INTO schema_migrations(version, applied_at) VALUES (%s, %s)",
|
|
(version, self.utc_now()),
|
|
)
|
|
conn.commit()
|
|
|
|
def utc_now(self) -> datetime:
|
|
return datetime.now(timezone.utc)
|
|
|
|
def isoformat_utc(self, value: datetime) -> str:
|
|
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
|
|
|
def hash_password(self, password: str) -> str:
|
|
return self.password_hasher.hash(password)
|
|
|
|
def verify_password(self, password_hash: str, password: str) -> bool:
|
|
try:
|
|
self.password_hasher.verify(password_hash, password)
|
|
return True
|
|
except Exception:
|
|
return False
|
|
|
|
def require_user_by_username(self, username: str, conn):
|
|
with conn.cursor() as cur:
|
|
cur.execute("SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s", (username,))
|
|
row = cur.fetchone()
|
|
if row is None:
|
|
return None
|
|
return {
|
|
"id": str(row[0]),
|
|
"username": row[1],
|
|
"display_name": row[2],
|
|
"created_at": self.isoformat_utc(row[3]),
|
|
"password_hash": row[4],
|
|
}
|
|
|
|
def fetch_user(self, user_id: str, conn):
|
|
with conn.cursor() as cur:
|
|
cur.execute("SELECT id, username, display_name, created_at FROM users WHERE id = %s", (user_id,))
|
|
row = cur.fetchone()
|
|
if row is None:
|
|
return None
|
|
return {
|
|
"id": str(row[0]),
|
|
"username": row[1],
|
|
"display_name": row[2],
|
|
"created_at": self.isoformat_utc(row[3]),
|
|
}
|
|
|
|
def fetch_session_by_token(self, token: str, conn):
|
|
with conn.cursor() as cur:
|
|
cur.execute(
|
|
"SELECT s.token, s.user_id, s.expires_at, s.revoked_at, 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",
|
|
(token,),
|
|
)
|
|
row = cur.fetchone()
|
|
if row is None:
|
|
return None
|
|
return {
|
|
"token": row[0],
|
|
"user_id": str(row[1]),
|
|
"expires_at": self.isoformat_utc(row[2]),
|
|
"revoked_at": row[3],
|
|
"user": {
|
|
"id": str(row[4]),
|
|
"username": row[5],
|
|
"display_name": row[6],
|
|
"created_at": self.isoformat_utc(row[7]),
|
|
},
|
|
}
|
|
|
|
def list_member_ids(self, chat_id: str, conn) -> List[str]:
|
|
with conn.cursor() as cur:
|
|
cur.execute("SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id", (chat_id,))
|
|
rows = cur.fetchall()
|
|
return [str(row[0]) for row in rows]
|
|
|
|
def fetch_chat(self, chat_id: str, conn):
|
|
with conn.cursor() as cur:
|
|
cur.execute("SELECT id, title, created_at FROM chats WHERE id = %s", (chat_id,))
|
|
row = cur.fetchone()
|
|
if row is None:
|
|
return None
|
|
return {
|
|
"id": str(row[0]),
|
|
"title": row[1],
|
|
"created_at": self.isoformat_utc(row[2]),
|
|
"member_ids": self.list_member_ids(str(row[0]), conn),
|
|
}
|
|
|
|
def fetch_message(self, message_id: str, conn):
|
|
with conn.cursor() as cur:
|
|
cur.execute("SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE id = %s", (message_id,))
|
|
row = cur.fetchone()
|
|
if row is None:
|
|
return None
|
|
return {
|
|
"id": str(row[0]),
|
|
"chat_id": str(row[1]),
|
|
"sender_id": str(row[2]),
|
|
"text": row[3],
|
|
"created_at": self.isoformat_utc(row[4]),
|
|
"attachment_ids": self.message_attachment_ids(str(row[0]), conn),
|
|
}
|
|
|
|
def fetch_chat_membership(self, chat_id: str, user_id: str, conn) -> 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
|
|
|
|
def insert_user(self, username: str, display_name: str, password: str):
|
|
now = self.utc_now()
|
|
user_id = uuid.uuid4()
|
|
password_hash = self.hash_password(password)
|
|
with self.connect() as conn:
|
|
with conn.cursor() as cur:
|
|
cur.execute(
|
|
"INSERT INTO users(id, username, display_name, password_hash, created_at) VALUES (%s,%s,%s,%s,%s)",
|
|
(user_id, username, display_name, password_hash, now),
|
|
)
|
|
conn.commit()
|
|
return {
|
|
"id": str(user_id),
|
|
"username": username,
|
|
"display_name": display_name,
|
|
"created_at": self.isoformat_utc(now),
|
|
}
|
|
|
|
def insert_chat(self, title: str, member_ids: List[str], actor_id: str):
|
|
now = self.utc_now()
|
|
chat_id = uuid.uuid4()
|
|
with self.connect() as conn:
|
|
with conn.cursor() as cur:
|
|
cur.execute("INSERT INTO chats(id,title,created_at) VALUES (%s,%s,%s)", (chat_id, title, now))
|
|
for member_id in sorted(set(member_ids)):
|
|
cur.execute("INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)", (chat_id, member_id))
|
|
conn.commit()
|
|
return {
|
|
"id": str(chat_id),
|
|
"title": title,
|
|
"member_ids": sorted(set(member_ids)),
|
|
"created_at": self.isoformat_utc(now),
|
|
}
|
|
|
|
def insert_message(self, chat_id: str, sender_id: str, text: str, key: str, attachment_ids: List[str]):
|
|
# Transaction-level lock serializes the same scope across all replicas.
|
|
scope = json.dumps([sender_id, "POST", chat_id, key])
|
|
request_body = {"text": text, "attachment_ids": attachment_ids}
|
|
with self.connect() as conn:
|
|
with conn.cursor() as cur:
|
|
cur.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (scope,))
|
|
cur.execute("DELETE FROM message_requests WHERE sender_id=%s AND chat_id=%s AND key=%s AND expires_at <= NOW()", (sender_id, chat_id, key))
|
|
cur.execute("SELECT body, response FROM message_requests WHERE sender_id=%s AND chat_id=%s AND key=%s", (sender_id, chat_id, key))
|
|
previous = cur.fetchone()
|
|
if previous:
|
|
if previous[0] != request_body:
|
|
raise ApiError(409, "conflict", "idempotency key reused with different body")
|
|
return previous[1]
|
|
for aid in attachment_ids:
|
|
cur.execute("SELECT state FROM attachments WHERE id=%s AND chat_id=%s FOR SHARE", (aid, chat_id))
|
|
att = cur.fetchone()
|
|
if att is None:
|
|
raise ApiError(404, "not_found", "attachment not found")
|
|
if att[0] == "failed":
|
|
raise ApiError(409, "conflict", "attachment unavailable")
|
|
now = self.utc_now()
|
|
message_id = str(uuid.uuid4())
|
|
message = {"id": message_id, "chat_id": chat_id, "sender_id": sender_id,
|
|
"text": text, "created_at": self.isoformat_utc(now), "attachment_ids": attachment_ids}
|
|
cur.execute("INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES (%s,%s,%s,%s,%s)",
|
|
(message_id, chat_id, sender_id, text, now))
|
|
for position, aid in enumerate(attachment_ids):
|
|
cur.execute("INSERT INTO message_attachments(message_id,attachment_id,position) VALUES (%s,%s,%s)", (message_id, aid, position))
|
|
cur.execute("INSERT INTO message_requests(sender_id,chat_id,key,body,response,expires_at) VALUES (%s,%s,%s,%s::jsonb,%s::jsonb,%s)",
|
|
(sender_id, chat_id, key, json.dumps(request_body), json.dumps(message), now + timedelta(hours=24)))
|
|
conn.commit()
|
|
return message
|
|
|
|
def message_attachment_ids(self, message_id, conn):
|
|
return [str(row[0]) for row in conn.execute("SELECT attachment_id FROM message_attachments WHERE message_id=%s ORDER BY position", (message_id,)).fetchall()]
|
|
|
|
@staticmethod
|
|
def cursor_uuid_key(value: str) -> int:
|
|
try:
|
|
return uuid.UUID(value).int
|
|
except (ValueError, TypeError):
|
|
return 0
|
|
|
|
def list_chats_for_user(self, user_id: str, limit: int, cursor: Optional[str]):
|
|
with self.connect() as conn:
|
|
with conn.cursor() as cur:
|
|
query = """
|
|
SELECT c.id, c.title, c.created_at
|
|
FROM chats c
|
|
JOIN chat_members cm ON cm.chat_id = c.id
|
|
WHERE cm.user_id = %s
|
|
"""
|
|
params: List[Any] = [user_id]
|
|
if cursor:
|
|
prefix = f"user:{user_id}|"
|
|
if not cursor.startswith(prefix):
|
|
raise ApiError(400, "invalid_request", "cursor does not match user chat list")
|
|
remainder = cursor[len(prefix):]
|
|
if not remainder:
|
|
raise ApiError(400, "invalid_request", "invalid cursor")
|
|
try:
|
|
cursor_ts_raw, cursor_id = remainder.split("|", 1)
|
|
cursor_dt = datetime.fromisoformat(cursor_ts_raw.replace("Z", "+00:00")).astimezone(timezone.utc)
|
|
except ValueError as exc:
|
|
raise ApiError(400, "invalid_request", "invalid cursor") from exc
|
|
query += " AND (c.created_at > %s OR (c.created_at = %s AND c.id > %s::uuid))"
|
|
params.extend([cursor_dt, cursor_dt, cursor_id])
|
|
query += " ORDER BY c.created_at ASC, c.id ASC LIMIT %s"
|
|
params.append(limit + 1)
|
|
cur.execute(query, tuple(params))
|
|
rows = cur.fetchall()
|
|
items = [
|
|
{
|
|
"id": str(row[0]),
|
|
"title": row[1],
|
|
"created_at": self.isoformat_utc(row[2]),
|
|
"member_ids": self.list_member_ids(str(row[0]), conn),
|
|
}
|
|
for row in rows
|
|
]
|
|
|
|
next_cursor = None
|
|
if len(items) > limit:
|
|
last_item = items[limit - 1]
|
|
next_cursor = f"user:{user_id}|{last_item['created_at']}|{last_item['id']}"
|
|
items = items[:limit]
|
|
|
|
return {"items": items, "next_cursor": next_cursor}
|
|
|
|
def list_messages_for_chat(self, chat_id: str, limit: int, cursor: Optional[str]):
|
|
with self.connect() as conn:
|
|
with conn.cursor() as cur:
|
|
query = "SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = %s"
|
|
params: List[Any] = [chat_id]
|
|
if cursor:
|
|
prefix = f"chat:{chat_id}|"
|
|
if not cursor.startswith(prefix):
|
|
raise ApiError(400, "invalid_request", "cursor does not match chat")
|
|
remainder = cursor[len(prefix):]
|
|
if not remainder:
|
|
raise ApiError(400, "invalid_request", "invalid cursor")
|
|
try:
|
|
cursor_ts_raw, cursor_id = remainder.split("|", 1)
|
|
cursor_dt = datetime.fromisoformat(cursor_ts_raw.replace("Z", "+00:00")).astimezone(timezone.utc)
|
|
except ValueError as exc:
|
|
raise ApiError(400, "invalid_request", "invalid cursor") from exc
|
|
query += " AND (created_at, id) > (%s, %s::uuid)"
|
|
params.extend([cursor_dt, cursor_id])
|
|
query += " ORDER BY created_at ASC, id ASC LIMIT %s"
|
|
params.append(limit + 1)
|
|
cur.execute(query, tuple(params))
|
|
rows = cur.fetchall()
|
|
links = {}
|
|
if rows:
|
|
cur.execute("SELECT message_id, attachment_id FROM message_attachments WHERE message_id=ANY(%s::uuid[]) ORDER BY message_id, position", ([str(row[0]) for row in rows],))
|
|
for mid, aid in cur.fetchall():
|
|
links.setdefault(str(mid), []).append(str(aid))
|
|
|
|
items = [{
|
|
"id": str(row[0]),
|
|
"chat_id": str(row[1]),
|
|
"sender_id": str(row[2]),
|
|
"text": row[3],
|
|
"created_at": self.isoformat_utc(row[4]),
|
|
"attachment_ids": links.get(str(row[0]), []),
|
|
} for row in rows]
|
|
|
|
next_cursor = None
|
|
if len(items) > limit:
|
|
last_item = items[limit - 1]
|
|
next_cursor = f"chat:{chat_id}|{last_item['created_at']}|{last_item['id']}"
|
|
items = items[:limit]
|
|
|
|
return {"items": items, "next_cursor": next_cursor}
|
|
|
|
def create_session(self, user_id: str, username: str):
|
|
token = secrets.token_urlsafe(32)
|
|
expires_at = self.utc_now() + timedelta(seconds=SESSION_TTL_SECONDS)
|
|
with self.connect() as conn:
|
|
with conn.cursor() as cur:
|
|
cur.execute(
|
|
"INSERT INTO sessions(id, token, user_id, expires_at, created_at) VALUES (%s,%s,%s,%s,%s)",
|
|
(uuid.uuid4(), token, user_id, expires_at, self.utc_now()),
|
|
)
|
|
conn.commit()
|
|
with self.connect() as conn:
|
|
user = self.fetch_user(user_id, conn)
|
|
if user is None:
|
|
raise ApiError(500, "internal_error", "session user missing")
|
|
session = {
|
|
"token": token,
|
|
"user_id": user_id,
|
|
"expires_at": self.isoformat_utc(expires_at),
|
|
"revoked_at": None,
|
|
"user": user,
|
|
}
|
|
self.cache_session(session)
|
|
return {
|
|
"token": token,
|
|
"token_type": "Bearer",
|
|
"expires_at": self.isoformat_utc(expires_at),
|
|
"user": user,
|
|
}
|
|
|
|
def get_session_by_token(self, token: str, conn=None):
|
|
if conn is None:
|
|
with self.connect() as db_conn:
|
|
return self.get_session_by_token(token, db_conn)
|
|
db_session = self.fetch_session_by_token(token, conn)
|
|
if db_session is None or not self.is_session_valid(db_session):
|
|
self.delete_cached_session(token)
|
|
return None
|
|
cached = self.get_cached_session(token, db_session=db_session)
|
|
if cached is None:
|
|
self.cache_session(db_session)
|
|
return db_session
|
|
|
|
def revoke_current_session(self, token: str):
|
|
with self.connect() as conn:
|
|
with conn.cursor() as cur:
|
|
cur.execute("UPDATE sessions SET revoked_at = %s WHERE token = %s AND revoked_at IS NULL", (self.utc_now(), token))
|
|
conn.commit()
|
|
self.delete_cached_session(token)
|
|
|
|
def is_session_valid(self, session) -> bool:
|
|
if session is None:
|
|
return False
|
|
if session.get("revoked_at") is not None:
|
|
return False
|
|
try:
|
|
expiry = self.parse_session_expiry(session["expires_at"])
|
|
except ValueError:
|
|
return False
|
|
if expiry <= self.utc_now():
|
|
return False
|
|
return True
|
|
|
|
|
|
store = Store()
|
|
from attachments import ObjectStore
|
|
object_store = ObjectStore(store, ApiError)
|
|
app = FastAPI(title="MTUSI Messenger")
|
|
|
|
|
|
@app.on_event("startup")
|
|
def startup_event() -> None:
|
|
store.pool.open(wait=True, timeout=10)
|
|
|
|
|
|
|
|
@app.on_event("shutdown")
|
|
def shutdown_event() -> None:
|
|
store.pool.close()
|
|
store.shared_cache.close()
|
|
object_store.close()
|
|
|
|
|
|
@app.exception_handler(psycopg.OperationalError)
|
|
async def database_error_handler(request: Request, exc):
|
|
return await api_error_handler(request, ApiError(503, "unavailable", "database unavailable"))
|
|
|
|
|
|
@app.middleware("http")
|
|
async def request_id_middleware(request: Request, call_next):
|
|
request_id = uuid.uuid4().hex
|
|
request.state.request_id = request_id
|
|
response = await call_next(request)
|
|
response.headers["X-Request-Id"] = request_id
|
|
response.headers["X-Instance-Id"] = INSTANCE_ID
|
|
response.headers["X-App-Revision"] = os.getenv("APP_REVISION", "lab4-v1")
|
|
return response
|
|
|
|
|
|
@app.exception_handler(ApiError)
|
|
async def api_error_handler(request: Request, exc: ApiError):
|
|
body = {"error": {"code": exc.code, "message": exc.message, "request_id": getattr(request.state, "request_id", "")}}
|
|
return JSONResponse(status_code=exc.status_code, headers={**exc.headers, "X-Request-Id": getattr(request.state, "request_id", ""), "X-Instance-Id": INSTANCE_ID}, content=body)
|
|
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_error_handler(request: Request, exc: RequestValidationError):
|
|
request_id = getattr(request.state, "request_id", "")
|
|
return JSONResponse(
|
|
status_code=400,
|
|
headers={"X-Request-Id": request_id, "X-Instance-Id": INSTANCE_ID},
|
|
content={"error": {"code": "invalid_request", "message": "invalid request", "request_id": request_id}},
|
|
)
|
|
|
|
|
|
@app.exception_handler(Exception)
|
|
async def generic_error_handler(request: Request, exc: Exception):
|
|
request_id = getattr(request.state, "request_id", "")
|
|
return JSONResponse(
|
|
status_code=500,
|
|
headers={"X-Request-Id": request_id, "X-Instance-Id": INSTANCE_ID},
|
|
content={"error": {"code": "internal_error", "message": "internal error", "request_id": request_id}},
|
|
)
|
|
|
|
|
|
def get_auth_header(request: Request):
|
|
auth = request.headers.get("Authorization")
|
|
if not auth:
|
|
raise ApiError(401, "unauthorized", "missing authorization", headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
|
|
scheme, _, token = auth.partition(" ")
|
|
if scheme.lower() != "bearer" or not token:
|
|
raise ApiError(401, "unauthorized", "invalid bearer token", headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
|
|
return token.strip()
|
|
|
|
|
|
def require_bearer_session(request: Request):
|
|
token = get_auth_header(request)
|
|
with store.connect() as conn:
|
|
session = store.get_session_by_token(token, conn)
|
|
if session is None or not store.is_session_valid(session):
|
|
raise ApiError(401, "unauthorized", "invalid or expired session", headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
|
|
return session
|
|
|
|
|
|
async def parse_json_body(request: Request) -> Dict[str, Any]:
|
|
try:
|
|
raw = await request.body()
|
|
if not raw:
|
|
return {}
|
|
return __import__("json").loads(raw)
|
|
except Exception as exc:
|
|
raise ApiError(400, "invalid_request", "malformed JSON") from exc
|
|
|
|
|
|
@app.get("/health/live")
|
|
def health_live():
|
|
return {"status": "ok"}
|
|
|
|
|
|
@app.get("/health/ready")
|
|
def health_ready():
|
|
try:
|
|
with store.connect() as conn:
|
|
with conn.cursor() as cur:
|
|
cur.execute("SELECT 1")
|
|
object_store.ready()
|
|
return {"status": "ok"}
|
|
except Exception as exc:
|
|
raise ApiError(503, "unavailable", "required storage unavailable") from exc
|
|
|
|
|
|
@app.post("/api/v1/users", status_code=201)
|
|
async def create_user_endpoint(request: Request):
|
|
try:
|
|
body = await request.json()
|
|
except Exception as exc:
|
|
raise ApiError(400, "invalid_request", "malformed JSON") from exc
|
|
if not isinstance(body, dict):
|
|
raise ApiError(400, "invalid_request", "invalid user payload")
|
|
try:
|
|
payload = CreateUserIn.model_validate(body)
|
|
except ValidationError as exc:
|
|
raise ApiError(400, "invalid_request", "invalid user payload") from exc
|
|
if not payload.username or not payload.display_name.strip():
|
|
raise ApiError(400, "invalid_request", "invalid request")
|
|
payload.display_name = payload.display_name.strip()
|
|
try:
|
|
user = store.insert_user(payload.username, payload.display_name, payload.password)
|
|
return UserOut.model_validate(user)
|
|
except Exception as exc:
|
|
if "duplicate key" in str(exc).lower() or "unique" in str(exc).lower():
|
|
raise ApiError(409, "conflict", "username already exists") from exc
|
|
raise ApiError(503, "unavailable", "required storage unavailable") from exc
|
|
|
|
|
|
@app.get("/api/v1/users/me")
|
|
def current_user(request: Request):
|
|
session = require_bearer_session(request)
|
|
user = session["user"]
|
|
return UserOut.model_validate(user)
|
|
|
|
|
|
@app.post("/api/v1/auth/sessions", status_code=201)
|
|
def create_session(request: Request):
|
|
auth = request.headers.get("Authorization", "")
|
|
if not auth.lower().startswith("basic "):
|
|
raise ApiError(401, "unauthorized", "invalid credentials", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
|
|
encoded = auth.split(" ", 1)[1].strip()
|
|
try:
|
|
decoded = base64.b64decode(encoded.encode("ascii"), validate=True)
|
|
raw = decoded.decode("utf-8")
|
|
except Exception:
|
|
raise ApiError(401, "unauthorized", "invalid credentials", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
|
|
if ":" not in raw:
|
|
raise ApiError(401, "unauthorized", "invalid credentials", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
|
|
username, password = raw.split(":", 1)
|
|
if not re_match(username):
|
|
raise ApiError(401, "unauthorized", "invalid credentials", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
|
|
if not (12 <= len(password) <= 128):
|
|
raise ApiError(401, "unauthorized", "invalid credentials", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
|
|
try:
|
|
with store.connect() as conn:
|
|
user = store.require_user_by_username(username, conn)
|
|
if user is None or not store.verify_password(user["password_hash"], password):
|
|
raise ApiError(401, "unauthorized", "invalid credentials", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
|
|
session = store.create_session(user["id"], username)
|
|
return SessionOut.model_validate(session)
|
|
except ApiError:
|
|
raise
|
|
except Exception as exc:
|
|
raise ApiError(503, "unavailable", "required storage unavailable") from exc
|
|
|
|
|
|
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
|
def revoke_session(request: Request):
|
|
session = require_bearer_session(request)
|
|
token = session["token"]
|
|
store.revoke_current_session(token)
|
|
return Response(status_code=204)
|
|
|
|
|
|
@app.post("/api/v1/chats", status_code=201)
|
|
async def create_chat_endpoint(request: Request):
|
|
session = require_bearer_session(request)
|
|
try:
|
|
body = await request.json()
|
|
except Exception as exc:
|
|
raise ApiError(400, "invalid_request", "malformed JSON") from exc
|
|
if not isinstance(body, dict):
|
|
raise ApiError(400, "invalid_request", "invalid chat payload")
|
|
try:
|
|
payload = CreateChatIn.model_validate(body)
|
|
except ValidationError as exc:
|
|
raise ApiError(400, "invalid_request", "invalid chat payload") from exc
|
|
if len(payload.member_ids) < 1 or len(payload.member_ids) > 100:
|
|
raise ApiError(400, "invalid_request", "invalid member_ids")
|
|
title = payload.title.strip()
|
|
if not title:
|
|
raise ApiError(400, "invalid_request", "invalid title")
|
|
normalized = []
|
|
seen = set()
|
|
for member_id in payload.member_ids:
|
|
try:
|
|
member_id = str(uuid.UUID(member_id))
|
|
except ValueError as exc:
|
|
raise ApiError(400, "invalid_request", "invalid member_ids") from exc
|
|
if member_id in seen:
|
|
raise ApiError(400, "invalid_request", "duplicate member_ids")
|
|
seen.add(member_id)
|
|
normalized.append(member_id)
|
|
if session["user_id"] not in normalized:
|
|
raise ApiError(400, "invalid_request", "current user must be a member")
|
|
try:
|
|
with store.connect() as conn:
|
|
for member_id in normalized:
|
|
with conn.cursor() as cur:
|
|
cur.execute("SELECT id FROM users WHERE id = %s", (member_id,))
|
|
if cur.fetchone() is None:
|
|
raise ApiError(400, "invalid_request", "unknown member")
|
|
chat = store.insert_chat(title, normalized, session["user_id"])
|
|
return ChatOut.model_validate(chat)
|
|
except ApiError:
|
|
raise
|
|
except Exception as exc:
|
|
raise ApiError(503, "unavailable", "required storage unavailable") from exc
|
|
|
|
|
|
@app.get("/api/v1/chats")
|
|
def list_chats(request: Request):
|
|
session = require_bearer_session(request)
|
|
limit = request.query_params.get("limit", "50")
|
|
cursor = request.query_params.get("cursor")
|
|
try:
|
|
limit_int = int(limit)
|
|
except ValueError as exc:
|
|
raise ApiError(400, "invalid_request", "invalid limit") from exc
|
|
if not (1 <= limit_int <= 100):
|
|
raise ApiError(400, "invalid_request", "invalid limit")
|
|
result = store.list_chats_for_user(session["user_id"], limit_int, cursor)
|
|
return {"items": [ChatOut.model_validate(item) for item in result["items"]], "next_cursor": result["next_cursor"]}
|
|
|
|
|
|
@app.get("/api/v1/chats/{chat_id}")
|
|
def get_chat(request: Request, chat_id: str):
|
|
session = require_bearer_session(request)
|
|
try:
|
|
uuid.UUID(chat_id)
|
|
except ValueError as exc:
|
|
raise ApiError(400, "invalid_request", "invalid chat_id") from exc
|
|
with store.connect() as conn:
|
|
chat = store.fetch_chat(chat_id, conn)
|
|
if chat is None or not store.fetch_chat_membership(chat_id, session["user_id"], conn):
|
|
raise ApiError(404, "not_found", "chat not found")
|
|
return ChatOut.model_validate(chat)
|
|
|
|
|
|
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
|
async def create_message(request: Request, chat_id: str):
|
|
session = require_bearer_session(request)
|
|
try:
|
|
uuid.UUID(chat_id)
|
|
except ValueError as exc:
|
|
raise ApiError(400, "invalid_request", "invalid chat_id") from exc
|
|
try:
|
|
body = await request.json()
|
|
except Exception as exc:
|
|
raise ApiError(400, "invalid_request", "malformed JSON") from exc
|
|
if not isinstance(body, dict):
|
|
raise ApiError(400, "invalid_request", "invalid message payload")
|
|
try:
|
|
payload = CreateMessageIn.model_validate(body)
|
|
except ValidationError as exc:
|
|
raise ApiError(400, "invalid_request", "invalid message payload") from exc
|
|
if len(payload.attachment_ids) > 10:
|
|
raise ApiError(400, "invalid_request", "too many attachments")
|
|
try:
|
|
payload.attachment_ids = [str(uuid.UUID(aid)) for aid in payload.attachment_ids]
|
|
except (ValueError, TypeError) as exc:
|
|
raise ApiError(400, "invalid_request", "invalid attachment id") from exc
|
|
if len(set(payload.attachment_ids)) != len(payload.attachment_ids):
|
|
raise ApiError(400, "invalid_request", "duplicate attachment ids")
|
|
if not payload.text.strip() and not payload.attachment_ids:
|
|
raise ApiError(400, "invalid_request", "invalid text")
|
|
key = request.headers.get("Idempotency-Key", "")
|
|
if not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key):
|
|
raise ApiError(400, "invalid_request", "invalid Idempotency-Key")
|
|
with store.connect() as conn:
|
|
chat = store.fetch_chat(chat_id, conn)
|
|
if chat is None or not store.fetch_chat_membership(chat_id, session["user_id"], conn):
|
|
raise ApiError(404, "not_found", "chat not found")
|
|
message = store.insert_message(str(uuid.UUID(chat_id)), session["user_id"], payload.text, key, payload.attachment_ids)
|
|
return MessageOut.model_validate(message)
|
|
|
|
|
|
@app.get("/api/v1/chats/{chat_id}/messages")
|
|
def list_messages(request: Request, chat_id: str):
|
|
session = require_bearer_session(request)
|
|
try:
|
|
uuid.UUID(chat_id)
|
|
except ValueError as exc:
|
|
raise ApiError(400, "invalid_request", "invalid chat_id") from exc
|
|
limit = request.query_params.get("limit", "50")
|
|
cursor = request.query_params.get("cursor")
|
|
try:
|
|
limit_int = int(limit)
|
|
except ValueError as exc:
|
|
raise ApiError(400, "invalid_request", "invalid limit") from exc
|
|
if not (1 <= limit_int <= 100):
|
|
raise ApiError(400, "invalid_request", "invalid limit")
|
|
with store.connect() as conn:
|
|
if not store.fetch_chat_membership(chat_id, session["user_id"], conn):
|
|
raise ApiError(404, "not_found", "chat not found")
|
|
result = store.list_messages_for_chat(chat_id, limit_int, cursor)
|
|
return {"items": [MessageOut.model_validate(item) for item in result["items"]], "next_cursor": result["next_cursor"]}
|
|
|
|
|
|
def re_match(value: str) -> bool:
|
|
import re
|
|
|
|
return bool(re.fullmatch(USERNAME_RE, value))
|
|
|
|
|
|
from attachments import register_routes
|
|
register_routes(app, object_store, require_bearer_session)
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
|
|
uvicorn.run("app:app", host=APP_HOST, port=APP_PORT, reload=False)
|