367 lines
16 KiB
Python
367 lines
16 KiB
Python
import base64
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import re
|
|
import io
|
|
import warnings
|
|
from datetime import datetime, timezone
|
|
from uuid import UUID, uuid4
|
|
from urllib.parse import unquote
|
|
|
|
from fastapi import FastAPI, Request, HTTPException, Query
|
|
from fastapi.responses import JSONResponse, Response, StreamingResponse
|
|
from fastapi.exceptions import RequestValidationError
|
|
from typing import Optional
|
|
from PIL import Image, UnidentifiedImageError, ImageFile, ImageFilter
|
|
|
|
from .models import (
|
|
CreateUserRequest, CreateChatRequest, CreateMessageRequest,
|
|
UserResponse, ChatResponse, MessageResponse, ChatPage, MessagePage,
|
|
SessionResponse, HealthResponse, AttachmentResponse
|
|
)
|
|
from .database import store, init_db, get_db_connection
|
|
from .auth import hash_password, verify_password, create_session, get_session, delete_session
|
|
from . import s3
|
|
|
|
INSTANCE_ID = os.getenv("INSTANCE_ID") or str(uuid4())
|
|
MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024
|
|
MAX_PIXELS = 40_000_000
|
|
ALLOWED_CONTENT_TYPES = {"image/png": "PNG", "image/jpeg": "JPEG"}
|
|
|
|
app = FastAPI()
|
|
|
|
|
|
@app.on_event("startup")
|
|
async def startup_event():
|
|
init_db()
|
|
s3.ensure_bucket()
|
|
print(f"[startup] INSTANCE_ID={INSTANCE_ID}")
|
|
|
|
|
|
@app.middleware("http")
|
|
async def add_headers(request: Request, call_next):
|
|
request_id = str(uuid4())
|
|
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
|
|
return response
|
|
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
|
request_id = getattr(request.state, "request_id", str(uuid4()))
|
|
return JSONResponse(status_code=400, content={"error": {
|
|
"code": "invalid_request",
|
|
"message": "Неверный формат запроса, неверные типы данных или лишние поля",
|
|
"request_id": request_id,
|
|
}})
|
|
|
|
|
|
@app.exception_handler(HTTPException)
|
|
async def http_exception_handler(request: Request, exc: HTTPException):
|
|
request_id = getattr(request.state, "request_id", str(uuid4()))
|
|
headers = dict(exc.headers) if exc.headers else {}
|
|
if exc.status_code == 401 and "WWW-Authenticate" not in headers:
|
|
if "/auth/sessions" in str(request.url.path):
|
|
headers["WWW-Authenticate"] = 'Basic realm="messenger", charset="UTF-8"'
|
|
else:
|
|
headers["WWW-Authenticate"] = 'Bearer realm="messenger"'
|
|
if isinstance(exc.detail, dict) and "error" in exc.detail:
|
|
content = exc.detail
|
|
content["error"]["request_id"] = request_id
|
|
else:
|
|
code_map = {400: "invalid_request", 401: "unauthorized", 404: "not_found",
|
|
409: "conflict", 413: "payload_too_large", 415: "unsupported_media_type",
|
|
429: "rate_limited", 500: "internal_error", 503: "unavailable"}
|
|
content = {"error": {"code": code_map.get(exc.status_code, "invalid_request"),
|
|
"message": str(exc.detail), "request_id": request_id}}
|
|
return JSONResponse(status_code=exc.status_code, content=content, headers=headers)
|
|
|
|
|
|
async def get_current_user_from_request(request: Request) -> dict:
|
|
auth_header = request.headers.get("Authorization")
|
|
if not auth_header or not auth_header.startswith("Bearer "):
|
|
raise HTTPException(401, detail="Missing or invalid Authorization header",
|
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
|
|
token = auth_header[7:]
|
|
conn = get_db_connection()
|
|
try:
|
|
session = get_session(conn, token)
|
|
if not session:
|
|
raise HTTPException(401, detail="Invalid or expired session",
|
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
|
|
user = store.get_user(session["user_id"])
|
|
if not user:
|
|
raise HTTPException(401, detail="User not found",
|
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
|
|
return user
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
@app.get("/health/live", response_model=HealthResponse)
|
|
async def health_live():
|
|
return {"status": "ok"}
|
|
|
|
|
|
@app.get("/health/ready", response_model=HealthResponse)
|
|
async def health_ready():
|
|
try:
|
|
conn = get_db_connection()
|
|
conn.close()
|
|
if not s3.check_available():
|
|
raise RuntimeError("S3 unavailable")
|
|
return {"status": "ok"}
|
|
except Exception:
|
|
raise HTTPException(503, detail="Required storage unavailable")
|
|
|
|
|
|
@app.post("/api/v1/auth/sessions", response_model=SessionResponse, status_code=201)
|
|
async def create_session_endpoint(request: Request):
|
|
auth_header = request.headers.get("Authorization")
|
|
if not auth_header or not auth_header.startswith("Basic "):
|
|
raise HTTPException(401, detail="Missing Basic authentication",
|
|
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
|
|
try:
|
|
decoded = base64.b64decode(auth_header[6:]).decode('utf-8')
|
|
username, password = decoded.split(":", 1)
|
|
except Exception:
|
|
raise HTTPException(400, detail="Invalid Basic authentication format")
|
|
if not re.match(r'^[a-z0-9_]{3,32}$', username):
|
|
raise HTTPException(400, detail="Invalid username format")
|
|
if len(password) < 12 or len(password) > 128:
|
|
raise HTTPException(400, detail="Password must be 12-128 characters")
|
|
user = store.get_user_by_username(username)
|
|
if not user or not verify_password(password, user["password_hash"]):
|
|
raise HTTPException(401, detail="Invalid credentials")
|
|
conn = get_db_connection()
|
|
try:
|
|
session_data = create_session(conn, user["id"])
|
|
return {"token": session_data["token"], "token_type": "Bearer", "expires_at": session_data["expires_at"],
|
|
"user": {"id": user["id"], "username": user["username"], "display_name": user["display_name"], "created_at": user["created_at"]}}
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
|
async def revoke_session(request: Request):
|
|
await get_current_user_from_request(request)
|
|
token = request.headers["Authorization"][7:]
|
|
conn = get_db_connection()
|
|
try:
|
|
delete_session(conn, token)
|
|
finally:
|
|
conn.close()
|
|
return Response(status_code=204)
|
|
|
|
|
|
@app.post("/api/v1/users", response_model=UserResponse, status_code=201)
|
|
async def create_user(body: CreateUserRequest):
|
|
try:
|
|
return store.create_user(body.username, body.display_name, hash_password(body.password))
|
|
except ValueError as e:
|
|
if str(e) == "username_already_exists":
|
|
raise HTTPException(409, detail="Username already exists")
|
|
raise HTTPException(400, detail=str(e))
|
|
|
|
|
|
@app.get("/api/v1/users/me", response_model=UserResponse)
|
|
async def get_current_user(request: Request):
|
|
return await get_current_user_from_request(request)
|
|
|
|
|
|
@app.post("/api/v1/chats", response_model=ChatResponse, status_code=201)
|
|
async def create_chat(body: CreateChatRequest, request: Request):
|
|
user = await get_current_user_from_request(request)
|
|
try:
|
|
return store.create_chat(body.title, body.member_ids, user["id"])
|
|
except ValueError as e:
|
|
mapping = {"user_not_found": "One or more members not found", "creator_not_in_members": "Creator must be in member list", "duplicate_members": "Duplicate member IDs"}
|
|
raise HTTPException(400, detail=mapping.get(str(e), str(e)))
|
|
|
|
|
|
@app.get("/api/v1/chats", response_model=ChatPage)
|
|
async def list_chats(request: Request, limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None, min_length=1)):
|
|
user = await get_current_user_from_request(request)
|
|
chats, next_cursor = store.list_chats(user["id"], limit, cursor)
|
|
return {"items": chats, "next_cursor": next_cursor}
|
|
|
|
|
|
@app.get("/api/v1/chats/{chat_id}", response_model=ChatResponse)
|
|
async def get_chat(chat_id: str, request: Request):
|
|
user = await get_current_user_from_request(request)
|
|
chat = store.get_chat(chat_id, user["id"])
|
|
if not chat:
|
|
raise HTTPException(404, detail="Chat not found")
|
|
return chat
|
|
|
|
|
|
@app.post("/api/v1/chats/{chat_id}/messages", response_model=MessageResponse, status_code=201)
|
|
async def create_message(chat_id: str, body: CreateMessageRequest, request: Request):
|
|
try:
|
|
UUID(chat_id)
|
|
except ValueError:
|
|
raise HTTPException(400, detail="Invalid chat_id")
|
|
user = await get_current_user_from_request(request)
|
|
idem_key = request.headers.get("Idempotency-Key")
|
|
if not idem_key or len(idem_key) > 128 or not re.match(r'^[A-Za-z0-9._:-]{1,128}$', idem_key):
|
|
raise HTTPException(400, detail="Idempotency-Key must match ^[A-Za-z0-9._:-]{1,128}$")
|
|
path = f"/api/v1/chats/{chat_id}/messages"
|
|
request_hash = hashlib.sha256(json.dumps({"chat_id": chat_id, "text": body.text, "attachment_ids": body.attachment_ids}, sort_keys=True).encode()).hexdigest()
|
|
try:
|
|
return store.create_message_idempotent(chat_id, user["id"], body.text, body.attachment_ids, idem_key, path, request_hash)
|
|
except ValueError as e:
|
|
mapping = {"idempotency_conflict": (409, "Idempotency-Key reused with different payload"),
|
|
"chat_not_found": (404, "Chat not found"), "sender_not_in_chat": (404, "User not in chat"),
|
|
"attachment_not_found": (404, "Attachment not found"), "attachment_not_ready": (409, "Attachment is not ready"),
|
|
"message_empty": (400, "Message text or attachment is required"), "invalid_attachment_ids": (400, "Invalid attachment_ids")}
|
|
code, message = mapping.get(str(e), (400, str(e)))
|
|
raise HTTPException(code, detail=message)
|
|
|
|
|
|
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
|
async def list_messages(chat_id: str, request: Request, limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None, min_length=1)):
|
|
user = await get_current_user_from_request(request)
|
|
try:
|
|
messages, next_cursor = store.list_messages(chat_id, user["id"], limit, cursor)
|
|
return {"items": messages, "next_cursor": next_cursor}
|
|
except ValueError as e:
|
|
if str(e) == "chat_not_found":
|
|
raise HTTPException(404, detail="Chat not found")
|
|
if str(e) == "user_not_in_chat":
|
|
raise HTTPException(404, detail="User not in chat")
|
|
raise HTTPException(400, detail=str(e))
|
|
|
|
|
|
def _validate_filename(filename: str) -> str:
|
|
filename = unquote(filename)
|
|
if not filename or len(filename) > 255:
|
|
raise HTTPException(400, detail="Invalid filename")
|
|
if any(ord(ch) == 0 or ch in '/\\' or ord(ch) < 32 or ord(ch) == 127 for ch in filename):
|
|
raise HTTPException(400, detail="Invalid filename")
|
|
return filename
|
|
|
|
|
|
async def _read_limited_body(request: Request) -> bytes:
|
|
content_length = request.headers.get("content-length")
|
|
if content_length:
|
|
try:
|
|
if int(content_length) > MAX_ATTACHMENT_BYTES:
|
|
raise HTTPException(413, detail="Attachment is too large")
|
|
except ValueError:
|
|
raise HTTPException(400, detail="Invalid Content-Length")
|
|
buf = io.BytesIO()
|
|
total = 0
|
|
async for chunk in request.stream():
|
|
total += len(chunk)
|
|
if total > MAX_ATTACHMENT_BYTES:
|
|
raise HTTPException(413, detail="Attachment is too large")
|
|
buf.write(chunk)
|
|
if total == 0:
|
|
raise HTTPException(400, detail="Empty attachment")
|
|
return buf.getvalue()
|
|
|
|
|
|
def _validate_image(data: bytes, declared_type: str):
|
|
if declared_type not in ALLOWED_CONTENT_TYPES:
|
|
raise HTTPException(415, detail="Only image/png and image/jpeg are supported")
|
|
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
|
ImageFile.LOAD_TRUNCATED_IMAGES = False
|
|
try:
|
|
with warnings.catch_warnings():
|
|
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
|
img = Image.open(io.BytesIO(data))
|
|
actual = img.format
|
|
if actual not in ALLOWED_CONTENT_TYPES.values() or ALLOWED_CONTENT_TYPES[declared_type] != actual:
|
|
raise HTTPException(415, detail="Content-Type does not match image content")
|
|
width, height = img.size
|
|
if width * height > MAX_PIXELS:
|
|
raise HTTPException(413, detail="Image has too many pixels")
|
|
img.verify()
|
|
return actual, width, height
|
|
except HTTPException:
|
|
raise
|
|
except (UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombError, Image.DecompressionBombWarning):
|
|
raise HTTPException(415, detail="Invalid or corrupted image")
|
|
|
|
|
|
@app.post("/api/v1/chats/{chat_id}/attachments", response_model=AttachmentResponse, status_code=201)
|
|
async def upload_attachment(chat_id: str, request: Request, filename: str = Query(..., min_length=1, max_length=255)):
|
|
try:
|
|
UUID(chat_id)
|
|
except ValueError:
|
|
raise HTTPException(400, detail="Invalid chat_id")
|
|
user = await get_current_user_from_request(request)
|
|
filename = _validate_filename(filename)
|
|
content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
|
if content_type not in ALLOWED_CONTENT_TYPES:
|
|
raise HTTPException(415, detail="Only image/png and image/jpeg are supported")
|
|
data = await _read_limited_body(request)
|
|
actual, width, height = _validate_image(data, content_type)
|
|
if len(data) > MAX_ATTACHMENT_BYTES or width * height > MAX_PIXELS:
|
|
raise HTTPException(413, detail="Attachment exceeds limits")
|
|
|
|
attachment_id = str(uuid4())
|
|
object_key = f"attachments/{attachment_id}/original"
|
|
sha256 = hashlib.sha256(data).hexdigest()
|
|
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
|
attachment = {"id": attachment_id, "chat_id": chat_id, "owner_id": user["id"], "filename": filename,
|
|
"content_type": content_type, "size_bytes": len(data), "sha256": sha256,
|
|
"object_key": object_key, "created_at": now, "updated_at": now}
|
|
try:
|
|
s3.put_bytes(object_key, io.BytesIO(data), len(data), content_type)
|
|
except Exception:
|
|
raise HTTPException(503, detail="Object storage unavailable")
|
|
try:
|
|
return store.create_attachment(attachment)
|
|
except ValueError as e:
|
|
try:
|
|
s3.delete_object(object_key)
|
|
except Exception:
|
|
pass
|
|
if str(e) == "chat_not_found":
|
|
raise HTTPException(404, detail="Chat not found")
|
|
if str(e) == "owner_not_in_chat":
|
|
raise HTTPException(404, detail="Chat not found")
|
|
raise HTTPException(400, detail=str(e))
|
|
except Exception:
|
|
try:
|
|
s3.delete_object(object_key)
|
|
except Exception:
|
|
pass
|
|
raise HTTPException(500, detail="Attachment metadata could not be saved")
|
|
|
|
|
|
@app.get("/api/v1/attachments/{attachment_id}", response_model=AttachmentResponse)
|
|
async def get_attachment(attachment_id: str, request: Request):
|
|
try:
|
|
UUID(attachment_id)
|
|
except ValueError:
|
|
raise HTTPException(400, detail="Invalid attachment_id")
|
|
user = await get_current_user_from_request(request)
|
|
attachment = store.get_attachment(attachment_id, user["id"])
|
|
if not attachment:
|
|
raise HTTPException(404, detail="Attachment not found")
|
|
return attachment
|
|
|
|
|
|
@app.get("/api/v1/attachments/{attachment_id}/content")
|
|
async def download_attachment(attachment_id: str, request: Request, variant: str = Query(default="original")):
|
|
try:
|
|
UUID(attachment_id)
|
|
except ValueError:
|
|
raise HTTPException(400, detail="Invalid attachment_id")
|
|
user = await get_current_user_from_request(request)
|
|
if variant != "original":
|
|
raise HTTPException(404, detail="Attachment variant not found")
|
|
object_key = store.get_attachment_object_key(attachment_id, user["id"])
|
|
if not object_key:
|
|
raise HTTPException(404, detail="Attachment not found")
|
|
try:
|
|
obj = s3.get_object(object_key)
|
|
except Exception:
|
|
raise HTTPException(503, detail="Object storage unavailable")
|
|
return StreamingResponse(obj["Body"], media_type=obj.get("ContentType", "application/octet-stream"), headers={"Content-Length": str(obj.get("ContentLength", ""))})
|