forked from mtusi2026/mtusi2026lab2
680 lines
18 KiB
Python
680 lines
18 KiB
Python
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import re
|
|
import secrets
|
|
import uuid
|
|
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
import psycopg
|
|
from psycopg.rows import dict_row
|
|
from psycopg.errors import UniqueViolation
|
|
|
|
from argon2 import PasswordHasher
|
|
from argon2.exceptions import (
|
|
VerifyMismatchError,
|
|
VerificationError,
|
|
InvalidHashError,
|
|
)
|
|
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.responses import JSONResponse, Response
|
|
from fastapi.exceptions import RequestValidationError
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
|
|
app = FastAPI(title="MTUSI Messenger Lab2")
|
|
|
|
DATABASE_URL = os.environ["DATABASE_URL"]
|
|
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
|
|
|
password_hasher = PasswordHasher()
|
|
|
|
|
|
# ---------- Helpers ----------
|
|
|
|
class ApiError(Exception):
|
|
def __init__(self, status, code, message, headers=None):
|
|
self.status = status
|
|
self.code = code
|
|
self.message = message
|
|
self.headers = headers or {}
|
|
|
|
|
|
def fail(status, code, message, headers=None):
|
|
raise ApiError(status, code, message, headers)
|
|
|
|
|
|
def db():
|
|
return psycopg.connect(DATABASE_URL, row_factory=dict_row)
|
|
|
|
|
|
def utc_string(value):
|
|
return value.astimezone(timezone.utc).isoformat(
|
|
timespec="microseconds"
|
|
).replace("+00:00", "Z")
|
|
|
|
|
|
def user_json(row):
|
|
return {
|
|
"id": str(row["id"]),
|
|
"username": row["username"],
|
|
"display_name": row["display_name"],
|
|
"created_at": utc_string(row["created_at"]),
|
|
}
|
|
|
|
|
|
def message_json(row):
|
|
return {
|
|
"id": str(row["id"]),
|
|
"chat_id": str(row["chat_id"]),
|
|
"sender_id": str(row["sender_id"]),
|
|
"text": row["text"],
|
|
"created_at": utc_string(row["created_at"]),
|
|
}
|
|
|
|
|
|
def chat_json(conn, row):
|
|
members = conn.execute(
|
|
"""
|
|
SELECT user_id FROM chat_members
|
|
WHERE chat_id = %s
|
|
ORDER BY position
|
|
""",
|
|
(row["id"],)
|
|
).fetchall()
|
|
|
|
return {
|
|
"id": str(row["id"]),
|
|
"title": row["title"],
|
|
"member_ids": [str(m["user_id"]) for m in members],
|
|
"created_at": utc_string(row["created_at"]),
|
|
}
|
|
|
|
|
|
def valid_uuid(value):
|
|
if not isinstance(value, str):
|
|
return False
|
|
try:
|
|
return str(uuid.UUID(value)) == value
|
|
except ValueError:
|
|
return False
|
|
|
|
|
|
def valid_text(value, maximum):
|
|
return (
|
|
isinstance(value, str)
|
|
and 1 <= len(value) <= maximum
|
|
and bool(value.strip())
|
|
)
|
|
|
|
|
|
def validate_limit(request):
|
|
value = request.query_params.get("limit", "50")
|
|
|
|
if not re.fullmatch(r"[0-9]+", value):
|
|
fail(400, "invalid_request", "Invalid limit")
|
|
|
|
number = int(value)
|
|
|
|
if not 1 <= number <= 100:
|
|
fail(400, "invalid_request", "Invalid limit")
|
|
|
|
return number
|
|
|
|
|
|
def make_cursor(resource, row):
|
|
payload = {
|
|
"resource": resource,
|
|
"created_at": utc_string(row["created_at"]),
|
|
"id": str(row["id"]),
|
|
}
|
|
|
|
raw = json.dumps(payload).encode("utf-8")
|
|
|
|
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
|
|
|
|
|
|
def read_cursor(cursor, resource):
|
|
if not isinstance(cursor, str) or not cursor:
|
|
fail(400, "invalid_request", "Invalid cursor")
|
|
|
|
try:
|
|
raw = base64.urlsafe_b64decode(
|
|
cursor + "=" * (-len(cursor) % 4)
|
|
)
|
|
value = json.loads(raw)
|
|
|
|
if value["resource"] != resource:
|
|
raise ValueError()
|
|
|
|
if not valid_uuid(value["id"]):
|
|
raise ValueError()
|
|
|
|
timestamp = datetime.fromisoformat(
|
|
value["created_at"].replace("Z", "+00:00")
|
|
)
|
|
|
|
if timestamp.tzinfo is None:
|
|
raise ValueError()
|
|
|
|
return timestamp, value["id"]
|
|
|
|
except (ValueError, KeyError, TypeError, UnicodeDecodeError):
|
|
fail(400, "invalid_request", "Invalid cursor")
|
|
|
|
|
|
async def json_body(request, required, allowed):
|
|
content_type = request.headers.get("content-type", "")
|
|
media_type = content_type.split(";")[0].strip().lower()
|
|
|
|
if media_type != "application/json":
|
|
fail(415, "unsupported_media_type", "Expected JSON")
|
|
|
|
try:
|
|
data = await request.json()
|
|
except Exception:
|
|
fail(400, "invalid_request", "Invalid JSON")
|
|
|
|
if not isinstance(data, dict):
|
|
fail(400, "invalid_request", "Expected JSON object")
|
|
|
|
if not set(required).issubset(data):
|
|
fail(400, "invalid_request", "Missing fields")
|
|
|
|
if not set(data).issubset(allowed):
|
|
fail(400, "invalid_request", "Unexpected fields")
|
|
|
|
return data
|
|
|
|
|
|
def unauthorized(kind="Bearer"):
|
|
if kind == "Basic":
|
|
header = 'Basic realm="messenger", charset="UTF-8"'
|
|
else:
|
|
header = 'Bearer realm="messenger"'
|
|
|
|
fail(
|
|
401,
|
|
"unauthorized",
|
|
"Authentication required",
|
|
{"WWW-Authenticate": header},
|
|
)
|
|
|
|
|
|
def current_user(request):
|
|
authorization = request.headers.get("Authorization", "")
|
|
|
|
if not authorization.startswith("Bearer "):
|
|
unauthorized()
|
|
|
|
token = authorization[7:]
|
|
|
|
if not token:
|
|
unauthorized()
|
|
|
|
token_hash = hashlib.sha256(token.encode()).hexdigest()
|
|
|
|
with db() as conn:
|
|
row = 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 = FALSE
|
|
AND s.expires_at > clock_timestamp()
|
|
""",
|
|
(token_hash,)
|
|
).fetchone()
|
|
|
|
if row is None:
|
|
unauthorized()
|
|
|
|
return row
|
|
|
|
|
|
def accessible_chat(conn, chat_id, user_id):
|
|
if not valid_uuid(chat_id):
|
|
fail(400, "invalid_request", "Invalid chat ID")
|
|
|
|
row = 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()
|
|
|
|
if row is None:
|
|
fail(404, "not_found", "Chat not found")
|
|
|
|
return row
|
|
|
|
|
|
# ---------- Request IDs and errors ----------
|
|
|
|
def error_response(request, status, code, message, headers=None):
|
|
request_id = request.state.request_id
|
|
|
|
response_headers = {
|
|
"X-Request-Id": request_id,
|
|
**(headers or {}),
|
|
}
|
|
|
|
return JSONResponse(
|
|
status_code=status,
|
|
content={
|
|
"error": {
|
|
"code": code,
|
|
"message": message,
|
|
"request_id": request_id,
|
|
}
|
|
},
|
|
headers=response_headers,
|
|
)
|
|
|
|
|
|
@app.middleware("http")
|
|
async def add_request_id(request, call_next):
|
|
request.state.request_id = str(uuid.uuid4())
|
|
|
|
try:
|
|
response = await call_next(request)
|
|
except psycopg.OperationalError:
|
|
response = error_response(
|
|
request, 503, "unavailable", "Database unavailable"
|
|
)
|
|
except Exception:
|
|
response = error_response(
|
|
request, 500, "internal_error", "Internal server error"
|
|
)
|
|
|
|
response.headers["X-Request-Id"] = request.state.request_id
|
|
return response
|
|
|
|
|
|
@app.exception_handler(ApiError)
|
|
async def api_error_handler(request, exc):
|
|
return error_response(
|
|
request, exc.status, exc.code, exc.message, exc.headers
|
|
)
|
|
|
|
|
|
@app.exception_handler(StarletteHTTPException)
|
|
async def http_error_handler(request, exc):
|
|
return error_response(
|
|
request, exc.status_code,
|
|
"not_found" if exc.status_code == 404 else "invalid_request",
|
|
"Resource not found" if exc.status_code == 404 else "Invalid request",
|
|
)
|
|
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_error_handler(request, exc):
|
|
return error_response(
|
|
request, 400, "invalid_request", "Invalid request"
|
|
)
|
|
|
|
|
|
# ---------- Health ----------
|
|
|
|
@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")
|
|
return {"status": "ok"}
|
|
except psycopg.Error:
|
|
fail(503, "unavailable", "Database unavailable")
|
|
|
|
|
|
# ---------- Users ----------
|
|
|
|
@app.post("/api/v1/users", status_code=201)
|
|
async def create_user(request: Request):
|
|
data = await json_body(
|
|
request,
|
|
required=["username", "display_name", "password"],
|
|
allowed=["username", "display_name", "password"],
|
|
)
|
|
|
|
username = data["username"]
|
|
display_name = data["display_name"]
|
|
password = data["password"]
|
|
|
|
if (
|
|
not isinstance(username, str)
|
|
or not re.fullmatch(r"[a-z0-9_]{3,32}", username)
|
|
or not valid_text(display_name, 100)
|
|
or not isinstance(password, str)
|
|
or not 12 <= len(password) <= 128
|
|
):
|
|
fail(400, "invalid_request", "Invalid user fields")
|
|
|
|
password_hash = password_hasher.hash(password)
|
|
user_id = str(uuid.uuid4())
|
|
|
|
try:
|
|
with db() as conn:
|
|
row = 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, username, display_name, password_hash)
|
|
).fetchone()
|
|
|
|
return user_json(row)
|
|
|
|
except UniqueViolation:
|
|
fail(409, "conflict", "Username already exists")
|
|
|
|
|
|
@app.get("/api/v1/users/me")
|
|
def get_me(request: Request):
|
|
return user_json(current_user(request))
|
|
|
|
|
|
# ---------- Sessions ----------
|
|
|
|
@app.post("/api/v1/auth/sessions", status_code=201)
|
|
async def create_session(request: Request):
|
|
authorization = request.headers.get("Authorization", "")
|
|
|
|
if not authorization.startswith("Basic "):
|
|
unauthorized("Basic")
|
|
|
|
try:
|
|
encoded = authorization[6:]
|
|
decoded = base64.b64decode(encoded, validate=True).decode("utf-8")
|
|
|
|
if ":" not in decoded:
|
|
raise ValueError()
|
|
|
|
username, password = decoded.split(":", 1)
|
|
|
|
except (ValueError, UnicodeDecodeError):
|
|
unauthorized("Basic")
|
|
|
|
if not re.fullmatch(r"[a-z0-9_]{3,32}", username):
|
|
unauthorized("Basic")
|
|
|
|
with db() as conn:
|
|
row = conn.execute(
|
|
"SELECT * FROM users WHERE username = %s",
|
|
(username,)
|
|
).fetchone()
|
|
|
|
if row is None:
|
|
unauthorized("Basic")
|
|
|
|
try:
|
|
password_hasher.verify(row["password_hash"], password)
|
|
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
|
unauthorized("Basic")
|
|
|
|
token = secrets.token_urlsafe(32)
|
|
token_hash = hashlib.sha256(token.encode()).hexdigest()
|
|
|
|
expires_at = datetime.now(timezone.utc) + 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, row["id"], expires_at)
|
|
)
|
|
|
|
return {
|
|
"token": token,
|
|
"token_type": "Bearer",
|
|
"expires_at": utc_string(expires_at),
|
|
"user": user_json(row),
|
|
}
|
|
|
|
|
|
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
|
def logout(request: Request):
|
|
current_user(request)
|
|
|
|
token = request.headers["Authorization"][7:]
|
|
token_hash = hashlib.sha256(token.encode()).hexdigest()
|
|
|
|
with db() as conn:
|
|
conn.execute(
|
|
"UPDATE sessions SET revoked = TRUE WHERE token_hash = %s",
|
|
(token_hash,)
|
|
)
|
|
|
|
return Response(status_code=204)
|
|
|
|
|
|
# ---------- Chats ----------
|
|
|
|
@app.post("/api/v1/chats", status_code=201)
|
|
async def create_chat(request: Request):
|
|
actor = current_user(request)
|
|
|
|
data = await json_body(
|
|
request,
|
|
required=["title", "member_ids"],
|
|
allowed=["title", "member_ids"],
|
|
)
|
|
|
|
title = data["title"]
|
|
member_ids = data["member_ids"]
|
|
|
|
if not valid_text(title, 100):
|
|
fail(400, "invalid_request", "Invalid title")
|
|
|
|
if (
|
|
not isinstance(member_ids, list)
|
|
or not 1 <= len(member_ids) <= 100
|
|
or not all(valid_uuid(x) for x in member_ids)
|
|
or len(member_ids) != len(set(member_ids))
|
|
or str(actor["id"]) not in member_ids
|
|
):
|
|
fail(400, "invalid_request", "Invalid members")
|
|
|
|
chat_id = str(uuid.uuid4())
|
|
|
|
with db() as conn:
|
|
# All operations use one transaction.
|
|
existing = conn.execute(
|
|
"""
|
|
SELECT id FROM users
|
|
WHERE id = ANY(%s::uuid[])
|
|
FOR KEY SHARE
|
|
""",
|
|
(member_ids,)
|
|
).fetchall()
|
|
|
|
if len(existing) != len(member_ids):
|
|
fail(400, "invalid_request", "Unknown member")
|
|
|
|
row = conn.execute(
|
|
"""
|
|
INSERT INTO chats (id, title)
|
|
VALUES (%s, %s)
|
|
RETURNING id, title, created_at
|
|
""",
|
|
(chat_id, title)
|
|
).fetchone()
|
|
|
|
for position, member_id in enumerate(member_ids):
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO chat_members (chat_id, user_id, position)
|
|
VALUES (%s, %s, %s)
|
|
""",
|
|
(chat_id, member_id, position)
|
|
)
|
|
|
|
result = chat_json(conn, row)
|
|
|
|
return result
|
|
|
|
|
|
@app.get("/api/v1/chats")
|
|
def list_chats(request: Request):
|
|
actor = current_user(request)
|
|
limit = validate_limit(request)
|
|
cursor = request.query_params.get("cursor")
|
|
|
|
resource = "chats:" + str(actor["id"])
|
|
|
|
with db() as conn:
|
|
if cursor is None:
|
|
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
|
|
ORDER BY c.created_at, c.id
|
|
LIMIT %s
|
|
""",
|
|
(actor["id"], limit + 1)
|
|
).fetchall()
|
|
else:
|
|
timestamp, last_id = read_cursor(cursor, resource)
|
|
|
|
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 (c.created_at, c.id) > (%s, %s)
|
|
ORDER BY c.created_at, c.id
|
|
LIMIT %s
|
|
""",
|
|
(actor["id"], timestamp, last_id, limit + 1)
|
|
).fetchall()
|
|
|
|
has_more = len(rows) > limit
|
|
page = rows[:limit]
|
|
|
|
items = [chat_json(conn, row) for row in page]
|
|
|
|
next_cursor = (
|
|
make_cursor(resource, page[-1])
|
|
if has_more else None
|
|
)
|
|
|
|
return {"items": items, "next_cursor": next_cursor}
|
|
|
|
|
|
@app.get("/api/v1/chats/{chat_id}")
|
|
def get_chat(chat_id: str, request: Request):
|
|
actor = current_user(request)
|
|
|
|
with db() as conn:
|
|
row = accessible_chat(conn, chat_id, actor["id"])
|
|
result = chat_json(conn, row)
|
|
|
|
return result
|
|
|
|
|
|
# ---------- Messages ----------
|
|
|
|
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
|
async def send_message(chat_id: str, request: Request):
|
|
actor = current_user(request)
|
|
|
|
data = await json_body(
|
|
request,
|
|
required=["text"],
|
|
allowed=["text"],
|
|
)
|
|
|
|
if not valid_text(data["text"], 4000):
|
|
fail(400, "invalid_request", "Invalid message text")
|
|
|
|
with db() as conn:
|
|
accessible_chat(conn, chat_id, actor["id"])
|
|
|
|
row = 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
|
|
""",
|
|
(
|
|
str(uuid.uuid4()),
|
|
chat_id,
|
|
actor["id"],
|
|
data["text"],
|
|
)
|
|
).fetchone()
|
|
|
|
return message_json(row)
|
|
|
|
|
|
@app.get("/api/v1/chats/{chat_id}/messages")
|
|
def list_messages(chat_id: str, request: Request):
|
|
actor = current_user(request)
|
|
limit = validate_limit(request)
|
|
cursor = request.query_params.get("cursor")
|
|
|
|
resource = "messages:" + chat_id
|
|
|
|
with db() as conn:
|
|
accessible_chat(conn, chat_id, actor["id"])
|
|
|
|
if cursor is None:
|
|
rows = conn.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()
|
|
else:
|
|
timestamp, last_id = read_cursor(cursor, resource)
|
|
|
|
rows = conn.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, timestamp, last_id, limit + 1)
|
|
).fetchall()
|
|
|
|
has_more = len(rows) > limit
|
|
page = rows[:limit]
|
|
|
|
next_cursor = (
|
|
make_cursor(resource, page[-1])
|
|
if has_more else None
|
|
)
|
|
|
|
items = [message_json(row) for row in page]
|
|
|
|
return {"items": items, "next_cursor": next_cursor}
|