Implement lab4 private S3 attachments and reconciliation track

This commit is contained in:
ferraronp
2026-11-12 18:15:42 +03:00
parent ec540a1a72
commit 87ce432b81
56 changed files with 2465 additions and 41 deletions
+1
View File
@@ -0,0 +1 @@
"""Lab 3 messenger API."""
+4
View File
@@ -0,0 +1,4 @@
import os
import uvicorn
if __name__ == "__main__":
uvicorn.run("app.main:app", host="0.0.0.0", port=int(os.getenv("APP_PORT", "8080")), workers=1, timeout_graceful_shutdown=8)
+191
View File
@@ -0,0 +1,191 @@
"""Messenger HTTP handlers; state lives only in PostgreSQL/Redis."""
import hashlib
import json
import re
import uuid
import psycopg
from argon2 import PasswordHasher
from fastapi import APIRouter, Request
from .auth import current_user, hasher, login, logout, public_user
from .core import APIError, invalid, iso, make_cursor, parse_limit, parse_uuid, read_cursor
from .models import CreateChat, CreateMessage, CreateUser
from .storage import db
router = APIRouter()
KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$", re.ASCII)
def actor(req: Request) -> dict:
return getattr(req.state, "actor", None) or current_user(req)
def chat_detail(conn, chat: dict) -> dict:
members = conn.execute("SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY position", (chat["id"],)).fetchall()
return {"id": str(chat["id"]), "title": bytes(chat["title"]).decode("utf-8"), "created_at": iso(chat["created_at"]), "member_ids": [str(x["user_id"]) for x in members]}
def message_detail(conn, row: dict) -> dict:
linked = conn.execute("SELECT attachment_id FROM message_attachments WHERE message_id=%s ORDER BY position", (row["id"],)).fetchall()
return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), "text": bytes(row["text"]).decode("utf-8"), "created_at": iso(row["created_at"]), "attachment_ids": [str(x["attachment_id"]) for x in linked]}
def require_chat(conn, chat_id: str, actor_id: str) -> dict:
row = conn.execute("SELECT c.* FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE c.id=%s AND cm.user_id=%s", (chat_id, actor_id)).fetchone()
if row is None:
raise APIError(404, "not_found", "Object not found")
return row
@router.get("/health/live")
def live():
return {"status": "ok"}
@router.get("/health/ready")
def ready():
from .storage import ready as storage_ready
if not storage_ready():
raise APIError(503, "unavailable", "Service not ready")
return {"status": "ok"}
@router.post("/api/v1/users", status_code=201)
def register(body: CreateUser):
hashed = hasher.hash(body.password)
ident = 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 *", (ident, body.username, body.display_name.encode("utf-8"), hashed)).fetchone()
return public_user(row)
except psycopg.errors.UniqueViolation:
raise APIError(409, "conflict", "Username already exists") from None
@router.post("/api/v1/auth/sessions", status_code=201)
def sessions(req: Request):
return login(req)
@router.delete("/api/v1/auth/sessions/current", status_code=204)
def sessions_delete(req: Request):
logout(req)
return None
@router.get("/api/v1/users/me")
def users_me(req: Request):
return actor(req)
@router.post("/api/v1/chats", status_code=201)
def chats_create(req: Request, body: CreateChat):
ident = actor(req)["id"]
if ident not in body.member_ids:
raise invalid("Current user must belong to the chat")
chat_id = str(uuid.uuid4())
try:
with db() as conn:
with conn.transaction():
# Validate all members; FK constraints are the final authority for races.
found = conn.execute("SELECT id FROM users WHERE id = ANY(%s::uuid[])", (body.member_ids,)).fetchall()
if len(found) != len(body.member_ids):
raise invalid("Unknown member")
row = conn.execute("INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING *", (chat_id, body.title.encode("utf-8"))).fetchone()
for pos, member in enumerate(body.member_ids):
conn.execute("INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,%s)", (chat_id, member, pos))
result = chat_detail(conn, row)
return result
except psycopg.errors.ForeignKeyViolation:
raise invalid("Unknown member") from None
@router.get("/api/v1/chats")
def chats_list(req: Request, limit: str | None = None, cursor: str | None = None):
who = actor(req)["id"]
n = parse_limit(limit)
mark = read_cursor(cursor, "chats", who)
with db() as conn:
if mark:
existing = conn.execute("SELECT 1 FROM chats c JOIN chat_members cm ON c.id=cm.chat_id WHERE c.id=%s AND c.created_at=%s AND cm.user_id=%s", (mark[1], mark[0], who)).fetchone()
if not existing:
raise invalid("Invalid cursor")
rows = conn.execute("""
SELECT c.* FROM chats c JOIN chat_members cm ON cm.chat_id=c.id
WHERE cm.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
""", (who, mark[0] if mark else None, mark[0] if mark else None, mark[1] if mark else None, n+1)).fetchall()
items = [chat_detail(conn, row) for row in rows[:n]]
more = len(rows) > n
last = rows[n-1] if more else None
return {"items": items, "next_cursor": make_cursor("chats", who, last["created_at"], str(last["id"])) if last else None}
@router.get("/api/v1/chats/{chat_id}")
def chats_get(req: Request, chat_id: str):
who = actor(req)["id"]
ident = parse_uuid(chat_id)
with db() as conn:
row = require_chat(conn, ident, who)
return chat_detail(conn, row)
@router.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def messages_create(req: Request, chat_id: str, body: CreateMessage):
who = actor(req)["id"]
ident = parse_uuid(chat_id)
key = req.headers.get("Idempotency-Key")
if not key or not KEY_RE.fullmatch(key):
raise invalid("Invalid Idempotency-Key")
# Lab3 has only text; canonical JSON avoids unstable formatting/field ordering.
fingerprint = hashlib.sha256(json.dumps({"text": body.text, "attachment_ids": body.attachment_ids}, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
lock_scope = f"{who}:POST:/api/v1/chats/{ident}/messages:{key}"
with db() as conn:
with conn.transaction():
require_chat(conn, ident, who)
# Transaction-scoped advisory lock is GLOBAL across API replicas.
conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (lock_scope,))
previous = conn.execute("""
SELECT idem.body_sha256, m.* FROM message_idempotency idem
JOIN messages m ON m.id=idem.message_id
WHERE idem.actor_id=%s AND idem.chat_id=%s AND idem.method='POST' AND idem.idem_key=%s
""", (who, ident, key)).fetchone()
if previous:
if previous["body_sha256"] != fingerprint:
raise APIError(409, "conflict", "Idempotency key used with another body")
return message_detail(conn, previous)
# 404 for foreign/nonexistent IDs; check BEFORE any message insert.
if body.attachment_ids:
owned = conn.execute("SELECT id FROM attachments WHERE chat_id=%s AND id=ANY(%s::uuid[])", (ident, body.attachment_ids)).fetchall()
if len(owned) != len(body.attachment_ids):
raise APIError(404, "not_found", "Attachment not found")
message_id = str(uuid.uuid4())
row = conn.execute("INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *", (message_id, ident, who, body.text.encode("utf-8"))).fetchone()
for pos, attachment_id in enumerate(body.attachment_ids):
conn.execute("INSERT INTO message_attachments(message_id,attachment_id,position) VALUES (%s,%s,%s)", (message_id, attachment_id, pos))
conn.execute("INSERT INTO message_idempotency(actor_id,chat_id,method,idem_key,body_sha256,message_id) VALUES (%s,%s,'POST',%s,%s,%s)", (who, ident, key, fingerprint, message_id))
return message_detail(conn, row)
@router.get("/api/v1/chats/{chat_id}/messages")
def messages_list(req: Request, chat_id: str, limit: str | None = None, cursor: str | None = None):
who = actor(req)["id"]
ident = parse_uuid(chat_id)
n = parse_limit(limit)
mark = read_cursor(cursor, "messages", ident)
with db() as conn:
require_chat(conn, ident, who)
if mark:
existing = conn.execute("SELECT 1 FROM messages WHERE id=%s AND chat_id=%s AND created_at=%s", (mark[1], ident, mark[0])).fetchone()
if not existing:
raise invalid("Invalid cursor")
rows = conn.execute("""
SELECT * 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
""", (ident, mark[0] if mark else None, mark[0] if mark else None, mark[1] if mark else None, n+1)).fetchall()
with db() as conn:
items = [message_detail(conn, row) for row in rows[:n]]
last = rows[n-1] if len(rows)>n else None
return {"items": items, "next_cursor": make_cursor("messages", ident, last["created_at"], str(last["id"])) if last else None}
+241
View File
@@ -0,0 +1,241 @@
"""Lab4 synchronous attachment API: streamed ingress, S3 storage and per-chat ACL.
The spool is temporary request workspace, not an authoritative file store. No
original survives a completed request on either API replica's local disk.
"""
import hashlib
import io
import os
import tempfile
import threading
import uuid
from contextlib import closing
import boto3
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError, EndpointConnectionError
from fastapi import APIRouter, Query, Request
from fastapi.responses import StreamingResponse
from PIL import Image, ImageFile, UnidentifiedImageError
from starlette.concurrency import run_in_threadpool
from .auth import current_user
from .core import APIError, invalid, iso, parse_uuid
from .storage import db
router = APIRouter()
BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
SPOOL_MEMORY_BYTES = 1024 * 1024
S3_BUFFER_BYTES = 256 * 1024
DECODE_LIMIT = threading.BoundedSemaphore(1) # bound expensive Pillow decoding per replica
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
ImageFile.LOAD_TRUNCATED_IMAGES = False
def s3_client():
return boto3.client(
"s3", endpoint_url=os.environ["S3_ENDPOINT"],
aws_access_key_id=os.environ["S3_ACCESS_KEY"],
aws_secret_access_key=os.environ["S3_SECRET_KEY"],
region_name="us-east-1", use_ssl=False,
config=Config(s3={"addressing_style": "path"},
connect_timeout=3, read_timeout=10, retries={"max_attempts": 1}),
)
def s3_error(exc):
return APIError(503, "unavailable", "Object storage unavailable")
def format_attachment(row):
return {
"id": str(row["id"]), "chat_id": str(row["chat_id"]),
"owner_id": str(row["owner_id"]), "filename": row["filename"],
"content_type": row["content_type"], "size_bytes": row["size_bytes"],
"sha256": row["sha256"], "status": "ready", "variants": [],
"error_code": None, "created_at": iso(row["created_at"]),
"updated_at": iso(row["updated_at"]),
}
def require_member(conn, chat_id, user_id):
row = conn.execute(
"SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s", (chat_id, user_id)
).fetchone()
if not row:
raise APIError(404, "not_found", "Object not found")
def attachment_row(conn, attachment_id, user_id):
row = conn.execute("""
SELECT a.* FROM attachments a
JOIN chat_members cm ON cm.chat_id=a.chat_id
WHERE a.id=%s AND cm.user_id=%s
""", (attachment_id, user_id)).fetchone()
if not row:
raise APIError(404, "not_found", "Object not found")
return row
def validate_filename(filename: str):
if not (1 <= len(filename) <= 255) or any(
c in "/\\" or ord(c) < 32 or ord(c) == 127 for c in filename
):
raise invalid("Invalid filename")
def validate_image(fileobj, mime: str):
"""Check full decode, dimensions, magic and MIME before writing to S3."""
try:
fileobj.seek(0)
with Image.open(fileobj) as im:
fmt = im.format
if fmt not in ("PNG", "JPEG"):
raise APIError(415, "unsupported_media_type", "Unsupported image encoding")
actual_mime = "image/png" if fmt == "PNG" else "image/jpeg"
if actual_mime != mime:
raise APIError(415, "unsupported_media_type", "Content-Type does not match image")
if im.width * im.height > MAX_PIXELS:
raise APIError(413, "payload_too_large", "Image dimensions too large")
im.verify()
fileobj.seek(0)
with DECODE_LIMIT:
with Image.open(fileobj) as im:
im.load() # reject corrupt/truncated pixel data, not just headers
except APIError:
raise
except Image.DecompressionBombError:
raise APIError(413, "payload_too_large", "Image dimensions too large") from None
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
raise APIError(415, "unsupported_media_type", "Invalid image") from None
except Image.DecompressionBombWarning:
raise APIError(413, "payload_too_large", "Image dimensions too large") from None
finally:
fileobj.seek(0)
def _upload_checked(spool, *, attachment_id, chat_id, user_id, filename, mime, size, digest):
"""Blocking S3 and DB steps run outside the event loop."""
key = f"attachments/{attachment_id}/original"
backup = f"recovery/{attachment_id}/original"
client = s3_client()
wrote_original = False
wrote_backup = False
committed = False
try:
# A recovery copy enables non-destructive repair if the primary key is lost.
spool.seek(0)
client.upload_fileobj(spool, BUCKET, key, ExtraArgs={"ContentType": mime},
Config=__import__('boto3.s3.transfer', fromlist=['TransferConfig']).TransferConfig(
use_threads=False, multipart_threshold=16*1024*1024,
io_chunksize=S3_BUFFER_BYTES))
wrote_original = True
client.copy_object(Bucket=BUCKET, Key=backup,
CopySource={"Bucket": BUCKET, "Key": key}, ContentType=mime,
MetadataDirective="REPLACE")
wrote_backup = True
with db() as conn:
with conn.transaction():
require_member(conn, chat_id, user_id)
row = conn.execute("""
INSERT INTO attachments(id,chat_id,owner_id,object_key,backup_key,filename,
content_type,size_bytes,sha256)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *
""", (attachment_id, chat_id, user_id, key, backup, filename, mime, size, digest)).fetchone()
committed = True
return format_attachment(row)
except (BotoCoreError, ClientError, EndpointConnectionError) as exc:
raise s3_error(exc) from exc
finally:
# Never delete after an ambiguous COMMIT unless a fresh read proves
# metadata is absent. A lost COMMIT acknowledgement can still mean
# PostgreSQL committed successfully. Reconciler handles uncertainty.
if not committed:
confirmed_absent = False
try:
with db() as conn:
confirmed_absent = conn.execute(
"SELECT 1 FROM attachments WHERE id=%s", (attachment_id,)
).fetchone() is None
except Exception:
pass
if confirmed_absent:
for written, object_key in ((wrote_backup, backup), (wrote_original, key)):
if written:
try:
client.delete_object(Bucket=BUCKET, Key=object_key)
except (BotoCoreError, ClientError, EndpointConnectionError):
pass
@router.post("/api/v1/chats/{chat_id}/attachments", status_code=201)
async def upload_attachment(req: Request, chat_id: str, filename: str = Query(...)):
from .api import actor, require_chat
who = actor(req)["id"]
chat_id = parse_uuid(chat_id)
validate_filename(filename)
mime = req.headers.get("content-type", "").split(";", 1)[0].strip().lower()
if mime not in ("image/png", "image/jpeg"):
raise APIError(415, "unsupported_media_type", "Only PNG and JPEG are supported")
with db() as conn:
require_chat(conn, chat_id, who)
announced_size = req.headers.get("content-length")
if announced_size:
try:
if int(announced_size) > MAX_BYTES:
raise APIError(413, "payload_too_large", "Image too large")
except ValueError:
raise invalid("Invalid Content-Length") from None
size = 0
digest = hashlib.sha256()
with tempfile.SpooledTemporaryFile(max_size=SPOOL_MEMORY_BYTES, mode="w+b") as spool:
async for chunk in req.stream():
size += len(chunk)
if size > MAX_BYTES:
raise APIError(413, "payload_too_large", "Image too large")
digest.update(chunk)
spool.write(chunk)
if size == 0:
raise APIError(415, "unsupported_media_type", "Empty image")
await run_in_threadpool(validate_image, spool, mime)
return await run_in_threadpool(_upload_checked, spool,
attachment_id=str(uuid.uuid4()), chat_id=chat_id, user_id=who,
filename=filename, mime=mime, size=size, digest=digest.hexdigest())
@router.get("/api/v1/attachments/{attachment_id}")
def get_attachment(req: Request, attachment_id: str):
who = getattr(req.state, "actor", None) or current_user(req)
with db() as conn:
return format_attachment(attachment_row(conn, parse_uuid(attachment_id), who["id"]))
@router.get("/api/v1/attachments/{attachment_id}/content")
def download_attachment(req: Request, attachment_id: str, variant: str = "original"):
who = getattr(req.state, "actor", None) or current_user(req)
with db() as conn:
row = attachment_row(conn, parse_uuid(attachment_id), who["id"])
if variant != "original":
raise APIError(404, "not_found", "Object not found")
client = s3_client()
try:
response = client.get_object(Bucket=BUCKET, Key=row["object_key"])
except ClientError as exc:
if exc.response.get("Error", {}).get("Code") in ("NoSuchKey", "404", "NotFound"):
raise APIError(503, "unavailable", "Stored object missing") from exc
raise s3_error(exc) from exc
except BotoCoreError as exc:
raise s3_error(exc) from exc
def iterator():
with closing(response["Body"]) as body:
while True:
chunk = body.read(S3_BUFFER_BYTES)
if not chunk:
break
yield chunk
return StreamingResponse(iterator(), media_type=row["content_type"],
headers={"Content-Length": str(row["size_bytes"])})
+104
View File
@@ -0,0 +1,104 @@
"""HTTP Basic only on login; bearer sessions shared by all API replicas."""
import base64
import binascii
import hashlib
import re
import secrets
import uuid
from datetime import datetime, timedelta, timezone
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError, VerificationError
from fastapi import Request
from redis.exceptions import RedisError
from .core import APIError, SESSION_TTL, iso
from .storage import cache, db
hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
PASSWORD_RE = re.compile(r"^[a-z0-9_]{3,32}$")
def public_user(row: dict):
return {"id": str(row["id"]), "username": row["username"], "display_name": bytes(row["display_name"]).decode("utf-8"), "created_at": iso(row["created_at"])}
def unauthorized() -> APIError:
return APIError(401, "unauthorized", "Unauthorized")
def challenge(req: Request) -> str:
return 'Basic realm="messenger", charset="UTF-8"' if req.url.path == "/api/v1/auth/sessions" else 'Bearer realm="messenger"'
def bearer_token(req: Request) -> str:
value = req.headers.get("Authorization", "")
if not value.startswith("Bearer ") or len(value) <= 7 or " " in value[7:] or len(value) > 512:
raise unauthorized()
try:
value[7:].encode("ascii")
except UnicodeEncodeError:
raise unauthorized() from None
return value[7:]
def session_key(token: str) -> str:
return "session:" + hashlib.sha256(token.encode("ascii")).hexdigest()
def current_user(req: Request) -> dict:
token = bearer_token(req)
try:
raw = cache().get(session_key(token))
except (RedisError, UnicodeError) as exc:
raise APIError(503, "unavailable", "Session store unavailable") from exc
if not raw:
raise unauthorized()
try:
ident = str(uuid.UUID(raw))
except (ValueError, TypeError):
try:
cache().delete(session_key(token))
except RedisError as exc:
raise APIError(503, "unavailable", "Session store unavailable") from exc
raise unauthorized() from None
with db() as conn:
row = conn.execute("SELECT * FROM users WHERE id = %s", (ident,)).fetchone()
if row is None:
raise unauthorized()
return public_user(row)
def login(req: Request):
auth = req.headers.get("Authorization", "")
if not auth.startswith("Basic "):
raise unauthorized()
try:
decoded = base64.b64decode(auth[6:].encode("ascii"), validate=True).decode("utf-8")
username, password = decoded.split(":", 1)
if not PASSWORD_RE.fullmatch(username):
raise ValueError()
except (ValueError, UnicodeError, binascii.Error):
raise unauthorized() from None
with db() as conn:
row = conn.execute("SELECT * FROM users WHERE username=%s", (username,)).fetchone()
if not row:
raise unauthorized()
try:
hasher.verify(row["password_hash"], password)
except (VerifyMismatchError, VerificationError):
raise unauthorized() from None
token = secrets.token_urlsafe(32)
try:
cache().set(session_key(token), str(row["id"]), ex=SESSION_TTL)
except RedisError as exc:
raise APIError(503, "unavailable", "Session store unavailable") from exc
return {"token": token, "token_type": "Bearer", "expires_at": iso(datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL)), "user": public_user(row)}
def logout(req: Request):
current_user(req)
try:
cache().delete(session_key(bearer_token(req)))
except RedisError as exc:
raise APIError(503, "unavailable", "Session store unavailable") from exc
+79
View File
@@ -0,0 +1,79 @@
"""Configuration, HTTP errors and shared representation helpers."""
import base64
import json
import os
import uuid
from datetime import datetime, timezone
from fastapi import Request
INSTANCE_ID = os.getenv("API_INSTANCE_ID", uuid.uuid4().hex[:12])
SESSION_TTL = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
IDEMPOTENCY_TTL = max(86400, int(os.getenv("IDEMPOTENCY_TTL_SECONDS", "86400")))
class APIError(Exception):
def __init__(self, status: int, code: str, message: str):
super().__init__(message)
self.status = status
self.code = code
self.message = message
def iso(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
def invalid(message: str = "Invalid request") -> APIError:
return APIError(400, "invalid_request", message)
def parse_uuid(value: str) -> str:
try:
return str(uuid.UUID(value))
except (ValueError, TypeError, AttributeError):
raise invalid("Invalid UUID") from None
def parse_limit(raw: str | None) -> int:
if raw is None:
return 50
try:
if not raw.isascii() or not raw.isdecimal():
raise ValueError()
value = int(raw)
except (ValueError, AttributeError):
raise invalid("Invalid limit") from None
if not 1 <= value <= 100:
raise invalid("Invalid limit")
return value
def make_cursor(kind: str, scope: str, created: datetime, ident: str) -> str:
b = json.dumps({"kind": kind, "scope": scope, "created_at": iso(created), "id": ident}, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(b).decode().rstrip("=")
def read_cursor(raw: str | None, kind: str, scope: str):
if raw is None:
return None
try:
if not raw or len(raw) > 2048 or any(ch not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" for ch in raw):
raise ValueError()
data = json.loads(base64.b64decode(raw + "=" * (-len(raw) % 4), altchars=b"-_", validate=True))
if not isinstance(data, dict) or data.get("kind") != kind or data.get("scope") != scope:
raise ValueError()
created = datetime.fromisoformat(data["created_at"].replace("Z", "+00:00"))
if created.tzinfo is None:
raise ValueError()
ident = str(uuid.UUID(data["id"]))
return created, ident
except (ValueError, TypeError, KeyError, UnicodeError, json.JSONDecodeError):
raise invalid("Invalid cursor") from None
def request_id(req: Request) -> str:
return getattr(req.state, "request_id", uuid.uuid4().hex)
def error_body(req: Request, code: str, message: str):
return {"error": {"code": code, "message": message, "request_id": request_id(req)}}
+84
View File
@@ -0,0 +1,84 @@
"""FastAPI process: one stateless replica. No auto-migration on startup."""
import logging
import uuid
from contextlib import asynccontextmanager
import psycopg
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.concurrency import run_in_threadpool
from redis.exceptions import RedisError
from .api import router
from .attachments import router as attachment_router
from .auth import challenge, current_user
from .core import APIError, INSTANCE_ID, error_body, invalid, request_id
from .storage import start, stop
logging.basicConfig(level="INFO")
logger = logging.getLogger("lab3")
@asynccontextmanager
async def lifespan(app: FastAPI):
start()
try:
yield
finally:
stop()
app = FastAPI(title="MTUCI Messenger Lab 4", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
app.include_router(router)
app.include_router(attachment_router)
PROTECTED = ("/api/v1/chats", "/api/v1/attachments", "/api/v1/users/me", "/api/v1/auth/sessions/current")
JSON_POST = ("/api/v1/users", "/api/v1/chats")
@app.middleware("http")
async def request_context(req: Request, call_next):
req.state.request_id = uuid.uuid4().hex
try:
path = req.url.path
# Authenticate before parsing the request body or resource-specific fields.
if any(path == p or path.startswith(p + "/") for p in PROTECTED):
req.state.actor = await run_in_threadpool(current_user, req)
if req.method == "POST" and (path in JSON_POST or (path.startswith("/api/v1/chats/") and path.endswith("/messages"))):
if req.headers.get("content-type", "").split(";", 1)[0].strip().lower() != "application/json":
raise APIError(415, "unsupported_media_type", "Content-Type must be application/json")
if req.method == "POST" and path == "/api/v1/auth/sessions" and await req.body():
raise invalid("Login body is not allowed")
response = await call_next(req)
except APIError as exc:
response = api_error(req, exc)
except (RedisError, psycopg.OperationalError, psycopg.InterfaceError):
response = api_error(req, APIError(503, "unavailable", "Dependency unavailable"))
except Exception:
logger.exception("unexpected request failure id=%s", request_id(req))
response = api_error(req, APIError(500, "internal_error", "Internal server error"))
response.headers["X-Request-Id"] = request_id(req)
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
def api_error(req: Request, exc: APIError) -> JSONResponse:
headers = {"WWW-Authenticate": challenge(req)} if exc.status == 401 else {}
return JSONResponse(status_code=exc.status, content=error_body(req, exc.code, exc.message), headers=headers)
@app.exception_handler(APIError)
async def api_error_handler(req: Request, exc: APIError):
return api_error(req, exc)
@app.exception_handler(RequestValidationError)
async def validation_error_handler(req: Request, exc: RequestValidationError):
return api_error(req, invalid())
@app.exception_handler(Exception)
async def unexpected_error_handler(req: Request, exc: Exception):
logger.exception("handler failure id=%s", request_id(req))
if isinstance(exc, (psycopg.OperationalError, psycopg.InterfaceError, RedisError)):
return api_error(req, APIError(503, "unavailable", "Dependency unavailable"))
return api_error(req, APIError(500, "internal_error", "Internal server error"))
+23
View File
@@ -0,0 +1,23 @@
"""Run once before API instances; transactional and advisory-lock coordinated migrations."""
import os
from pathlib import Path
import psycopg
MIGRATIONS = Path(__file__).resolve().parents[1] / "db" / "migrations"
def main():
with psycopg.connect(os.environ["DATABASE_URL"], autocommit=False) as conn:
with conn.transaction():
conn.execute("SELECT pg_advisory_xact_lock(62132103)")
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.glob("[0-9]*.sql")):
applied = conn.execute("SELECT 1 FROM schema_migrations WHERE version=%s", (path.name,)).fetchone()
if applied:
continue
conn.execute(path.read_text(encoding="utf-8"))
conn.execute("INSERT INTO schema_migrations(version) VALUES (%s)", (path.name,))
print("Applied", path.name, flush=True)
print("Migrations up to date", flush=True)
if __name__ == "__main__":
main()
+77
View File
@@ -0,0 +1,77 @@
"""HTTP request models; all strings use Unicode code point limits."""
import re
import uuid
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
class StrictModel(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
class CreateUser(StrictModel):
username: str
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
@field_validator("username")
@classmethod
def username_valid(cls, value: str) -> str:
if not USERNAME_RE.fullmatch(value):
raise ValueError("Invalid username")
return value
@field_validator("display_name", "password")
@classmethod
def non_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("Blank value")
value.encode("utf-8", errors="strict")
return value
class CreateChat(StrictModel):
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 non_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("Blank title")
value.encode("utf-8", errors="strict")
return value
@field_validator("member_ids")
@classmethod
def uuid_members(cls, value: list[str]) -> list[str]:
for member in value:
if not isinstance(member, str) or str(uuid.UUID(member)) != member:
raise ValueError("Invalid member UUID")
if len(value) != len(set(value)):
raise ValueError("Duplicate member")
return value
class CreateMessage(StrictModel):
text: str = Field(min_length=0, max_length=4000)
attachment_ids: list[str] = Field(default_factory=list, max_length=10)
@field_validator("text")
@classmethod
def non_blank(cls, value: str) -> str:
value.encode("utf-8", errors="strict")
return value
@field_validator("attachment_ids")
@classmethod
def valid_attachments(cls, value: list[str]) -> list[str]:
if len(value) != len(set(value)):
raise ValueError("Duplicate attachment IDs")
for item in value:
if not isinstance(item, str) or str(uuid.UUID(item)) != item:
raise ValueError("Invalid attachment UUID")
return value
@model_validator(mode="after")
def nonempty_message(self):
if not self.text.strip() and not self.attachment_ids:
raise ValueError("Empty message")
return self
+130
View File
@@ -0,0 +1,130 @@
"""Lab4 grade-5 track 2: repeatable DB/S3 reconciliation.
Dry-run is default. Apply never drops metadata when BOTH object copies are gone:
without a trustworthy copy or external backup, deletion would destroy evidence.
"""
import argparse
import json
import sys
import time
from datetime import datetime, timezone
import psycopg
from psycopg.rows import dict_row
from botocore.exceptions import BotoCoreError, ClientError
from .attachments import BUCKET, s3_client
def inventory(client):
result = {}
for page in client.get_paginator("list_objects_v2").paginate(Bucket=BUCKET):
for obj in page.get("Contents", []):
# Only reconciliation-owned prefixes; never mutate arbitrary S3 keys.
key = obj["Key"]
if key.startswith(("attachments/", "recovery/")):
result[key] = obj["LastModified"]
return result
def get_db_rows(conn):
return conn.execute("SELECT id, object_key, backup_key FROM attachments").fetchall()
def current_reference(conn, key):
return conn.execute(
"SELECT 1 FROM attachments WHERE object_key=%s OR backup_key=%s", (key, key)
).fetchone() is not None
def reconcile(*, apply=False, grace_seconds=300, now=None, client=None, connect=None):
if grace_seconds < 300 and apply:
raise ValueError("Apply requires >=300 s grace period to protect in-flight uploads")
started = time.monotonic()
now = now or datetime.now(timezone.utc)
client = client or s3_client()
connect = connect or (lambda: psycopg.connect(__import__('os').environ['DATABASE_URL'], row_factory=dict_row))
objects = inventory(client)
stats = {
"mode": "apply" if apply else "dry-run", "grace_seconds": grace_seconds,
"s3_keys_scanned": len(objects), "db_rows_scanned": 0,
"orphan_keys": [], "orphan_keys_young": [],
"missing_primary_repairable": [], "missing_backup_repairable": [],
"missing_both_unrecoverable": [], "actions": [], "errors": [],
}
with connect() as conn:
rows = get_db_rows(conn)
stats["db_rows_scanned"] = len(rows)
references = {key for row in rows for key in (row["object_key"], row["backup_key"])}
for row in rows:
primary, backup = row["object_key"], row["backup_key"]
have_primary, have_backup = primary in objects, backup in objects
rid = str(row["id"])
if have_primary and have_backup:
continue
if not have_primary and not have_backup:
stats["missing_both_unrecoverable"].append(rid)
continue
dest, source, typ = (primary, backup, "missing_primary_repairable") if not have_primary else (backup, primary, "missing_backup_repairable")
stats[typ].append(rid)
if apply:
# Defensive recheck. Object may have reappeared after inventory.
try:
client.head_object(Bucket=BUCKET, Key=dest)
stats["actions"].append({"action": "already-restored", "key": dest})
continue
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code")
if code not in ("404", "NotFound", "NoSuchKey"):
raise
try:
client.copy_object(Bucket=BUCKET, Key=dest,
CopySource={"Bucket": BUCKET, "Key": source})
stats["actions"].append({"action": "restore", "key": dest, "from": source})
except (BotoCoreError, ClientError) as exc:
stats["errors"].append({"action": "restore", "key": dest, "error_type": type(exc).__name__})
for key, modified in objects.items():
if key in references:
continue
age = (now - modified).total_seconds()
if age < grace_seconds:
stats["orphan_keys_young"].append(key)
continue
stats["orphan_keys"].append(key)
if apply:
# Query again immediately before destructive action; never delete
# an object now referenced by a committed metadata row.
if current_reference(conn, key):
stats["actions"].append({"action": "skip-now-referenced", "key": key})
continue
try:
client.delete_object(Bucket=BUCKET, Key=key)
stats["actions"].append({"action": "delete-old-orphan", "key": key})
except (BotoCoreError, ClientError) as exc:
stats["errors"].append({"action": "delete-old-orphan", "key": key, "error_type": type(exc).__name__})
stats["scan_elapsed_seconds"] = round(time.monotonic() - started, 3)
return stats
def main():
parser = argparse.ArgumentParser(description="Reconcile S3 attachments vs PostgreSQL (dry-run default)")
parser.add_argument("--apply", action="store_true", help="Make safe changes; orphans older than 300 seconds only")
parser.add_argument("--grace-seconds", type=int, default=300)
parser.add_argument("--output", help="Write JSON summary (no credentials)")
args = parser.parse_args()
try:
result = reconcile(apply=args.apply, grace_seconds=args.grace_seconds)
except Exception as exc:
# No exception string: botocore errors may contain signed credentials/URLs.
print(json.dumps({"status":"failed", "error_type":type(exc).__name__}), file=sys.stderr)
raise SystemExit(2) from None
rendered = json.dumps(result, ensure_ascii=False, indent=2)
print(rendered)
if args.output:
with open(args.output, "w", encoding="utf-8") as fh:
fh.write(rendered + "\n")
if result["errors"] or result["missing_both_unrecoverable"]:
raise SystemExit(1)
if __name__ == "__main__":
main()
+36
View File
@@ -0,0 +1,36 @@
"""Operator-only fault injection in a LOCAL TEST stack; never exposed as HTTP."""
import argparse
import json
import os
import uuid
import psycopg
from psycopg.rows import dict_row
from .attachments import BUCKET, s3_client
def main():
p = argparse.ArgumentParser()
p.add_argument("action", choices=["delete-primary", "delete-backup", "create-orphan"])
p.add_argument("--id", help="Attachment UUID for the delete actions")
args = p.parse_args()
if os.environ.get("LAB4_ALLOW_FAULT_INJECTION") != "yes":
raise SystemExit("Fault injection disabled; use LAB4_ALLOW_FAULT_INJECTION=yes in isolated test")
client = s3_client()
if args.action == "create-orphan":
key = f"attachments/{uuid.uuid4()}/original"
client.put_object(Bucket=BUCKET, Key=key, Body=b"synthetic orphan")
print(json.dumps({"fault":"orphan-created", "object_key":key}))
return
if not args.id:
raise SystemExit("--id is required")
ident = str(uuid.UUID(args.id))
with psycopg.connect(os.environ["DATABASE_URL"], row_factory=dict_row) as conn:
row = conn.execute("SELECT object_key,backup_key FROM attachments WHERE id=%s", (ident,)).fetchone()
if not row:
raise SystemExit("Attachment does not exist")
key = row["object_key"] if args.action == "delete-primary" else row["backup_key"]
client.delete_object(Bucket=BUCKET, Key=key)
print(json.dumps({"fault":args.action, "object_key":key}))
if __name__ == "__main__":
main()
+61
View File
@@ -0,0 +1,61 @@
"""Fast isolated tests for reconciliation safety; run in application image."""
import uuid
from datetime import datetime, timezone, timedelta
from .reconcile import reconcile
from .attachments import BUCKET
NOW = datetime.now(timezone.utc)
class FakeConn:
def __init__(self, rows): self.rows=rows
def __enter__(self): return self
def __exit__(self,*a): return False
def execute(self, sql, args=None):
self.sql=sql
self.args=args
return self
def fetchall(self): return self.rows
def fetchone(self):
key=self.args[0]
return {'id': 1} if any(key in (row['object_key'],row['backup_key']) for row in self.rows) else None
class FakeS3:
def __init__(self,objects): self.objects=objects
def get_paginator(self,op): return self
def paginate(self,**kwargs):
yield {'Contents':[{'Key':k,'LastModified':t} for k,t in self.objects.items()]}
def head_object(self,**kw):
if kw['Key'] not in self.objects:
from botocore.exceptions import ClientError
raise ClientError({'Error':{'Code':'404'}},'HeadObject')
def copy_object(self,**kw):
assert kw['CopySource']['Key'] in self.objects
self.objects[kw['Key']]=NOW
def delete_object(self,**kw):
self.objects.pop(kw['Key'],None)
def test():
i=str(uuid.uuid4())
primary=f'attachments/{i}/original';backup=f'recovery/{i}/original'
young=f'attachments/{uuid.uuid4()}/original'
old=f'attachments/{uuid.uuid4()}/original'
rows=[{'id':i,'object_key':primary,'backup_key':backup}]
fake=FakeS3({backup: NOW-timedelta(days=1),young:NOW-timedelta(seconds=10),old:NOW-timedelta(days=1)})
kwargs={'now':NOW,'client':fake,'connect':lambda:FakeConn(rows)}
first=reconcile(apply=False,**kwargs)
assert first['missing_primary_repairable']==[i]
assert old in first['orphan_keys'] and young in first['orphan_keys_young']
assert primary not in fake.objects and old in fake.objects, 'Dry run mutated objects'
second=reconcile(apply=True,**kwargs)
assert primary in fake.objects and old not in fake.objects and young in fake.objects
assert any(x['action']=='restore' for x in second['actions'])
third=reconcile(apply=True,**kwargs)
assert not third['actions'], 'Re-run unexpectedly mutated objects'
assert rows[0]['object_key']==primary, 'Metadata destroyed'
try: reconcile(apply=True, grace_seconds=0, **kwargs)
except ValueError: pass
else: raise AssertionError('Unsafe zero-grace apply accepted')
print('PASS: dry-run, orphan grace, recover primary from backup, apply idempotence')
if __name__ == '__main__': test()
+35
View File
@@ -0,0 +1,35 @@
"""Idempotently create the private S3 bucket with bootstrap-only credentials."""
import os
import time
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError, BotoCoreError
def main():
bucket = os.environ["S3_BUCKET"]
client = boto3.client("s3", endpoint_url=os.environ["S3_ENDPOINT"],
aws_access_key_id=os.environ["S3_ADMIN_ACCESS_KEY"],
aws_secret_access_key=os.environ["S3_ADMIN_SECRET_KEY"],
region_name="us-east-1",
config=Config(s3={"addressing_style": "path"},
connect_timeout=2, read_timeout=4, retries={"max_attempts": 1}))
for attempt in range(70):
try:
try:
client.head_bucket(Bucket=bucket)
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code", "")
if code not in ("404", "NoSuchBucket", "NotFound"):
raise
client.create_bucket(Bucket=bucket)
# PRIVATE: no public bucket policy, ACL or anonymous identity.
print(f"Private bucket {bucket} ready", flush=True)
return
except (ClientError, BotoCoreError, OSError) as exc:
if attempt == 69:
raise RuntimeError("S3 bootstrap failed; inspect S3 container") from exc
time.sleep(1)
if __name__ == "__main__":
main()
+32
View File
@@ -0,0 +1,32 @@
"""One-off creation of private SeaweedFS S3 identities; secrets stay in Docker volume."""
import json
import os
from pathlib import Path
def main():
bucket = os.environ["S3_BUCKET"]
identities = [
{"name": "bucket-bootstrap", "credentials": [{"accessKey": os.environ["S3_ADMIN_ACCESS_KEY"],
"secretKey": os.environ["S3_ADMIN_SECRET_KEY"]}],
"actions": ["Admin", "Read", "Write", "List"]},
{"name": "messenger-api", "credentials": [{"accessKey": os.environ["S3_ACCESS_KEY"],
"secretKey": os.environ["S3_SECRET_KEY"]}],
"actions": [f"Read:{bucket}", f"Write:{bucket}", f"List:{bucket}"]},
]
if len({entry["credentials"][0]["accessKey"] for entry in identities}) != 2:
raise ValueError("Admin and API credentials must differ")
path = Path("/s3-config/config.json")
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".tmp")
old_umask = os.umask(0o077)
try:
tmp.write_text(json.dumps({"identities": identities}, separators=(",", ":")), encoding="utf-8")
os.chmod(tmp, 0o644) # readable by the SeaweedFS runtime UID; Docker volume stays private
os.replace(tmp, path)
finally:
os.umask(old_umask)
print("S3 identities configured (no secrets printed)", flush=True)
if __name__ == "__main__":
main()
+40
View File
@@ -0,0 +1,40 @@
"""Verify bucket is private at S3 boundary (not merely hidden behind HTTP API)."""
import json
import os
import boto3
from botocore import UNSIGNED
from botocore.config import Config
from botocore.exceptions import ClientError
from .attachments import BUCKET, s3_client
def main():
client = s3_client()
client.head_bucket(Bucket=BUCKET) # restricted app identity works
unauth = boto3.client("s3", endpoint_url=os.environ["S3_ENDPOINT"],
region_name="us-east-1", config=Config(signature_version=UNSIGNED,
s3={"addressing_style":"path"}))
try:
unauth.list_objects_v2(Bucket=BUCKET, MaxKeys=1)
except ClientError as exc:
status = exc.response.get("ResponseMetadata", {}).get("HTTPStatusCode")
if status not in (401,403):
raise RuntimeError("Unexpected anonymous S3 response") from None
else:
raise RuntimeError("Private bucket leaked object list to anonymous caller")
listing = client.list_objects_v2(Bucket=BUCKET, MaxKeys=1)
keys = [entry["Key"] for entry in listing.get("Contents", [])]
if keys:
try:
unauth.get_object(Bucket=BUCKET, Key=keys[0])
except ClientError as exc:
status = exc.response.get("ResponseMetadata", {}).get("HTTPStatusCode")
if status not in (401, 403):
raise RuntimeError("Unexpected anonymous object GET response") from None
else:
raise RuntimeError("Private S3 object downloadable anonymously")
print(json.dumps({"private_bucket": True, "anonymous_listing": "denied",
"anonymous_object_get": "denied" if keys else "not_tested_empty_bucket"}))
if __name__ == "__main__":
main()
+64
View File
@@ -0,0 +1,64 @@
"""Shared external state: psycopg connection pool and Redis session store."""
import os
from contextlib import contextmanager
import psycopg
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool, PoolTimeout
from redis import Redis
from redis.exceptions import RedisError
from .core import APIError
pool: ConnectionPool | None = None
redis_client: Redis | None = None
def start() -> None:
global pool, redis_client
url = os.environ["DATABASE_URL"]
size = int(os.getenv("DB_POOL_MAX", "8"))
pool = ConnectionPool(conninfo=url, min_size=1, max_size=size, timeout=3, kwargs={"row_factory": dict_row, "connect_timeout": 5, "options": "-c statement_timeout=5000"}, open=False)
pool.open(wait=True, timeout=30)
redis_client = Redis.from_url(os.environ.get("REDIS_URL", "redis://redis:6379/0"), socket_connect_timeout=2, socket_timeout=2, decode_responses=True)
redis_client.ping()
def stop() -> None:
global pool, redis_client
if pool is not None:
pool.close()
pool = None
if redis_client is not None:
redis_client.close()
redis_client = None
@contextmanager
def db():
if pool is None:
raise APIError(503, "unavailable", "Database unavailable")
try:
with pool.connection() as conn:
yield conn
except (psycopg.OperationalError, psycopg.InterfaceError, PoolTimeout) as exc:
raise APIError(503, "unavailable", "Database unavailable") from exc
def cache() -> Redis:
if redis_client is None:
raise APIError(503, "unavailable", "Session store unavailable")
return redis_client
def ready() -> bool:
try:
with db() as conn:
conn.execute("SELECT 1").fetchone()
cache().ping()
# S3 is needed for the mandatory synchronous upload/download path.
from .attachments import s3_client, BUCKET
s3_client().head_bucket(Bucket=BUCKET)
return True
except Exception:
return False