[+] add project
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-12-05 22:05:31 +03:00
parent 20afc2c790
commit 1d146756d7
63 changed files with 3501 additions and 149 deletions
+1
View File
@@ -0,0 +1 @@
"""Messenger lab7 application package."""
+808
View File
@@ -0,0 +1,808 @@
import asyncio
import base64
import hashlib
import json
import logging
import re
import secrets
import ssl
import time
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import PurePosixPath
import asyncpg
import boto3
import pika
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, Response
from PIL import Image
from .config import load_settings, env
from .db import migrate, pg_ssl
from .vault import login
from .telemetry import configure
settings = load_settings("api")
tracer = configure("messenger-api", settings.instance_id,
settings.otlp_endpoint, settings.otlp_verify)
vault = None
try:
vault = login(settings, "api")
vault_secrets = vault["secrets"]
settings = settings.__class__(
**{**settings.__dict__,
"database_url": vault_secrets["database_url"],
"broker_url": vault_secrets["broker_url"],
"s3_access_key": vault_secrets["s3_access_key"],
"s3_secret_key": vault_secrets["s3_secret_key"]}
)
except Exception as exc:
if env("APP_ENV") == "lab" and env("ALLOW_INSECURE_LOCAL_DEV") == "1":
raise
raise
ph = PasswordHasher(
memory_cost=settings.argon_memory,
time_cost=settings.argon_iterations,
parallelism=settings.argon_parallelism,
)
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
pool = None
instances = {}
rate_state = {}
logger = logging.getLogger("messenger-api")
@app.middleware("http")
async def rate_limit_middleware(req: Request, call_next):
if req.url.path.startswith("/health/"):
return await call_next(req)
now = time.monotonic()
key = req.client.host if req.client else "unknown"
bucket = rate_state.setdefault(key, [])
bucket[:] = [stamp for stamp in bucket if now - stamp < 60]
if len(bucket) >= 120:
rid = request_id(req)
return JSONResponse(
{"error": {"code": "rate_limited", "message": "Слишком много запросов", "request_id": rid}},
status_code=429,
headers={"Retry-After": "60", "X-Request-Id": rid, "X-Instance-Id": settings.instance_id},
)
bucket.append(now)
return await call_next(req)
def utcnow():
return datetime.now(timezone.utc)
def rfc3339(value):
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
def error(code, message, status, request_id, headers=None):
h = {"X-Request-Id": request_id}
if headers:
h.update(headers)
return JSONResponse({"error": {"code": code, "message": message, "request_id": request_id}},
status_code=status, headers=h)
def request_id(req):
return (
getattr(req.state, "request_id", None)
or req.headers.get("X-Request-Id")
or uuid.uuid4().hex
)
@app.middleware("http")
async def request_middleware(req: Request, call_next):
rid = request_id(req)
req.state.request_id = rid
start = time.monotonic()
try:
response = await call_next(req)
except Exception as exc:
route_template = req.url.path
route_template = re.sub(
r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-"
r"[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}",
"{id}", route_template,
)
logger.error("request_failed_safe", extra={
"event": "request_failed",
"request_id": rid,
"method": req.method,
"route_template": route_template,
"error_type": type(exc).__name__,
})
response = error("internal_error", "Внутренняя ошибка сервера", 500, rid)
response.headers["X-Request-Id"] = rid
response.headers["X-Instance-Id"] = settings.instance_id
return response
def bearer(req):
auth = req.headers.get("Authorization", "")
if not auth.lower().startswith("bearer ") or len(auth.strip()) <= 7:
return None
return auth.split(None, 1)[1].strip()
async def auth_user(req):
token = bearer(req)
if not token:
return None
async with pool.acquire() as con:
row = await con.fetchrow(
"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=$1 AND s.expires_at>$2",
token, utcnow(),
)
if not row:
return None
return row
async def auth_or_error(req):
user = await auth_user(req)
rid = request_id(req)
if not user:
return None, error("unauthorized", "Требуется действительная сессия", 401, rid,
{"WWW-Authenticate": 'Bearer realm="messenger"'})
return user, None
def user_json(row):
return {"id": str(row["id"]), "username": row["username"], "display_name": row["display_name"],
"created_at": rfc3339(row["created_at"])}
def chat_json(row, member_ids):
return {"id": str(row["id"]), "title": row["title"], "member_ids": [str(x) for x in member_ids],
"created_at": rfc3339(row["created_at"])}
def is_blank(value):
return not isinstance(value, str) or not value.strip()
def valid_uuid(value):
try:
return str(uuid.UUID(value))
except (ValueError, AttributeError, TypeError):
return None
@app.on_event("startup")
async def startup():
global pool
ca = env("PG_CACERT", env("TLS_CA_FILE"))
ssl_context = pg_ssl(settings.database_url, ca)
pool = await asyncpg.create_pool(settings.database_url, ssl=ssl_context, min_size=1, max_size=10)
await migrate(pool)
@app.on_event("shutdown")
async def shutdown():
if pool:
await pool.close()
@app.get("/health/live")
async def live(request: Request):
return {"status": "ok"}
@app.get("/health/ready")
async def ready(request: Request):
rid = request_id(request)
try:
async with pool.acquire() as con:
await con.fetchval("SELECT 1")
await asyncio.to_thread(s3_client().head_bucket, Bucket=settings.s3_bucket)
await asyncio.to_thread(check_broker)
return {"status": "ok"}
except Exception:
return error("unavailable", "Сервис временно недоступен", 503, rid)
@app.post("/api/v1/users")
async def create_user(request: Request):
rid = request_id(request)
try:
body = await request.json()
except Exception:
return error("invalid_request", "Некорректный JSON", 400, rid)
if not isinstance(body, dict) or set(body) != {"username", "display_name", "password"}:
return error("invalid_request", "Неверные поля запроса", 400, rid)
username = body["username"]
display = body["display_name"]
password = body["password"]
if not isinstance(username, str) or not re.fullmatch(r"[a-z0-9_]{3,32}", username):
return error("invalid_request", "Неверное имя пользователя", 400, rid)
if not isinstance(display, str) or is_blank(display) or len(display) > 100:
return error("invalid_request", "Неверное отображаемое имя", 400, rid)
if not isinstance(password, str) or not 12 <= len(password) <= 128:
return error("invalid_request", "Неверный пароль", 400, rid)
password_hash = ph.hash(password)
uid = uuid.uuid4()
now = utcnow()
try:
async with pool.acquire() as con:
row = await con.fetchrow(
"INSERT INTO users(id,username,display_name,password_hash,created_at) "
"VALUES($1,$2,$3,$4,$5) RETURNING id,username,display_name,created_at",
uid, username, display, password_hash, now,
)
except asyncpg.UniqueViolationError:
return error("conflict", "Имя пользователя уже занято", 409, rid)
return JSONResponse(user_json(row), status_code=201)
@app.post("/api/v1/auth/sessions")
async def login_session(request: Request):
rid = request_id(request)
if await request.body():
return error("invalid_request", "Basic аутентификация не принимает JSON body", 400, rid)
auth = request.headers.get("Authorization", "")
if not auth.startswith("Basic ") or len(auth) == 6:
return error("unauthorized", "Неверные учетные данные", 401, rid,
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
try:
raw = base64.b64decode(auth[6:].strip(), validate=True).decode("utf-8")
username, password = raw.split(":", 1)
except Exception:
return error("unauthorized", "Неверные учетные данные", 401, rid,
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
if not re.fullmatch(r"[a-z0-9_]{3,32}", username) or not 12 <= len(password) <= 128:
return error("unauthorized", "Неверные учетные данные", 401, rid,
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
async with pool.acquire() as con:
row = await con.fetchrow("SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=$1", username)
if not row:
return error("unauthorized", "Неверные учетные данные", 401, rid,
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
try:
ph.verify(row["password_hash"], password)
except VerifyMismatchError:
return error("unauthorized", "Неверные учетные данные", 401, rid,
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
token = secrets.token_urlsafe(32)
expires = utcnow() + timedelta(seconds=settings.session_ttl)
async with pool.acquire() as con:
await con.execute("INSERT INTO sessions(token,user_id,expires_at) VALUES($1,$2,$3)",
token, row["id"], expires)
return JSONResponse({"token": token, "token_type": "Bearer", "expires_at": rfc3339(expires),
"user": user_json(row)}, status_code=201)
@app.delete("/api/v1/auth/sessions/current")
async def logout(request: Request):
rid = request_id(request)
user, denied = await auth_or_error(request)
if denied:
return denied
token = bearer(request)
async with pool.acquire() as con:
deleted = await con.fetchval("DELETE FROM sessions WHERE token=$1 AND expires_at>$2 RETURNING token",
token, utcnow())
if not deleted:
return error("unauthorized", "Сессия недействительна", 401, rid,
{"WWW-Authenticate": 'Bearer realm="messenger"'})
return Response(status_code=204)
@app.get("/api/v1/users/me")
async def users_me(request: Request):
rid = request_id(request)
user, denied = await auth_or_error(request)
if denied:
return denied
return user_json(user)
async def member_check(con, chat_id, user_id):
return await con.fetchval(
"SELECT 1 FROM chat_members WHERE chat_id=$1 AND user_id=$2",
chat_id, user_id,
)
@app.post("/api/v1/chats")
async def create_chat(request: Request):
rid = request_id(request)
user, denied = await auth_or_error(request)
if denied:
return denied
try:
body = await request.json()
except Exception:
return error("invalid_request", "Некорректный JSON", 400, rid)
if not isinstance(body, dict) or set(body) != {"title", "member_ids"}:
return error("invalid_request", "Неверные поля запроса", 400, rid)
title = body["title"]
ids = body["member_ids"]
if not isinstance(title, str) or is_blank(title) or len(title) > 100:
return error("invalid_request", "Неверный title", 400, rid)
if not isinstance(ids, list) or not 1 <= len(ids) <= 100:
return error("invalid_request", "Неверный member_ids", 400, rid)
normalized = []
for value in ids:
uid = valid_uuid(value) if isinstance(value, str) else None
if not uid:
return error("invalid_request", "Неверный UUID участника", 400, rid)
normalized.append(uuid.UUID(uid))
if len(set(normalized)) != len(normalized):
return error("invalid_request", "Дубликаты участников", 400, rid)
if user["id"] not in normalized:
return error("invalid_request", "Создатель должен быть участником", 400, rid)
cid = uuid.uuid4()
now = utcnow()
async with pool.acquire() as con:
async with con.transaction():
found = await con.fetchval("SELECT COUNT(*) FROM users WHERE id=ANY($1::uuid[])", normalized)
if found != len(normalized):
return error("invalid_request", "Неизвестный участник", 400, rid)
row = await con.fetchrow(
"INSERT INTO chats(id,title,created_at) VALUES($1,$2,$3) "
"RETURNING id,title,created_at", cid, title, now,
)
await con.executemany(
"INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)",
[(cid, uid) for uid in normalized],
)
return JSONResponse(chat_json(row, normalized), status_code=201)
@app.get("/api/v1/chats")
async def list_chats(request: Request):
rid = request_id(request)
user, denied = await auth_or_error(request)
if denied:
return denied
try:
limit = int(request.query_params.get("limit", "50"))
except (ValueError, TypeError):
return error("invalid_request", "Неверный limit", 400, rid)
if not 1 <= limit <= 100:
return error("invalid_request", "Неверный limit", 400, rid)
async with pool.acquire() as con:
rows = await con.fetch(
"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=$1 "
"ORDER BY c.created_at,c.id LIMIT $2",
user["id"], limit,
)
items = []
for row in rows:
member_rows = await con.fetch("SELECT user_id FROM chat_members WHERE chat_id=$1 ORDER BY user_id", row["id"])
items.append(chat_json(row, [x["user_id"] for x in member_rows]))
return {"items": items, "next_cursor": None}
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(chat_id: str, request: Request):
rid = request_id(request)
user, denied = await auth_or_error(request)
if denied:
return denied
cid = valid_uuid(chat_id)
if not cid:
return error("invalid_request", "Неверный UUID чата", 400, rid)
async with pool.acquire() as con:
if not await member_check(con, uuid.UUID(cid), user["id"]):
return error("not_found", "Объект не найден", 404, rid)
row = await con.fetchrow("SELECT id,title,created_at FROM chats WHERE id=$1", uuid.UUID(cid))
member_rows = await con.fetch("SELECT user_id FROM chat_members WHERE chat_id=$1 ORDER BY user_id", uuid.UUID(cid))
return chat_json(row, [x["user_id"] for x in member_rows])
def encode_cursor(chat_id, created, message_id):
timestamp = (
created.astimezone(timezone.utc)
.isoformat(timespec="microseconds")
.replace("+00:00", "Z")
)
payload = json.dumps(
{"chat": chat_id, "t": timestamp, "id": message_id},
separators=(",", ":"),
).encode()
return base64.urlsafe_b64encode(payload).decode().rstrip("=")
def decode_cursor(cursor, chat_id):
try:
padding = "=" * (-len(cursor) % 4)
payload = json.loads(base64.urlsafe_b64decode(cursor + padding))
if payload.get("chat") != chat_id or set(payload) != {"chat", "t", "id"}:
return None
timestamp = datetime.fromisoformat(payload["t"].replace("Z", "+00:00"))
mid = valid_uuid(payload["id"])
if not mid:
return None
return timestamp, uuid.UUID(mid)
except Exception:
return None
@app.get("/api/v1/chats/{chat_id}/messages")
async def history(chat_id: str, request: Request):
rid = request_id(request)
user, denied = await auth_or_error(request)
if denied:
return denied
cid = valid_uuid(chat_id)
if not cid:
return error("invalid_request", "Неверный UUID чата", 400, rid)
try:
limit = int(request.query_params.get("limit", "50"))
except (ValueError, TypeError):
return error("invalid_request", "Неверный limit", 400, rid)
if not 1 <= limit <= 100:
return error("invalid_request", "Неверный limit", 400, rid)
cursor = request.query_params.get("cursor")
after = decode_cursor(cursor, cid) if cursor else None
if cursor and after is None:
return error("invalid_request", "Неверный cursor", 400, rid)
async with pool.acquire() as con:
if not await member_check(con, uuid.UUID(cid), user["id"]):
return error("not_found", "Объект не найден", 404, rid)
if after:
rows = await con.fetch(
"SELECT * FROM messages WHERE chat_id=$1 "
"AND (created_at,id) > ($2,$3) "
"ORDER BY created_at,id LIMIT $4",
uuid.UUID(cid), after[0], after[1], limit + 1,
)
else:
rows = await con.fetch(
"SELECT * FROM messages WHERE chat_id=$1 "
"ORDER BY created_at,id LIMIT $2",
uuid.UUID(cid), limit + 1,
)
items = []
for row in rows[:limit]:
aids = await con.fetch(
"SELECT attachment_id FROM message_attachments WHERE message_id=$1 ORDER BY attachment_id",
row["id"],
)
items.append({
"id": str(row["id"]), "chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]), "text": row["text"],
"created_at": rfc3339(row["created_at"]),
"attachment_ids": [str(x["attachment_id"]) for x in aids],
})
next_cursor = None
if len(rows) > limit:
last = rows[limit - 1]
next_cursor = encode_cursor(cid, last["created_at"], str(last["id"]))
return {"items": items, "next_cursor": next_cursor}
def canonical_body(body):
text = body.get("text")
attachments = body.get("attachment_ids", [])
return {"text": text, "attachment_ids": sorted(attachments)}
def s3_client():
return boto3.client(
"s3",
endpoint_url=settings.s3_endpoint,
region_name=settings.s3_region,
aws_access_key_id=settings.s3_access_key,
aws_secret_access_key=settings.s3_secret_key,
verify=settings.s3_verify,
)
def check_broker():
params = pika.URLParameters(settings.broker_url)
if settings.broker_url.startswith("amqps://"):
ssl_context = ssl.create_default_context(cafile=settings.broker_verify)
ssl_context.check_hostname = True
ssl_context.verify_mode = ssl.CERT_REQUIRED
params.ssl_options = pika.SSLOptions(ssl_context)
connection = pika.BlockingConnection(params)
connection.close()
def publish_job(payload):
params = pika.URLParameters(settings.broker_url)
if settings.broker_url.startswith("amqps://"):
ssl_context = ssl.create_default_context(cafile=settings.broker_verify)
ssl_context.check_hostname = True
ssl_context.verify_mode = ssl.CERT_REQUIRED
params.ssl_options = pika.SSLOptions(ssl_context)
connection = pika.BlockingConnection(params)
channel = connection.channel()
channel.queue_declare(queue="attachment.jobs", durable=True)
channel.confirm_delivery()
channel.basic_publish(
exchange="", routing_key="attachment.jobs",
body=json.dumps(payload, separators=(",", ":")).encode("utf-8"),
properties=pika.BasicProperties(delivery_mode=2),
mandatory=True,
)
connection.close()
@app.post("/api/v1/chats/{chat_id}/messages")
async def create_message(chat_id: str, request: Request):
rid = request_id(request)
user, denied = await auth_or_error(request)
if denied:
return denied
cid = valid_uuid(chat_id)
if not cid:
return error("invalid_request", "Неверный UUID чата", 400, rid)
key = request.headers.get("Idempotency-Key")
if not key or not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key):
return error("invalid_request", "Неверный Idempotency-Key", 400, rid)
try:
body = await request.json()
except Exception:
return error("invalid_request", "Некорректный JSON", 400, rid)
if not isinstance(body, dict) or set(body) - {"text", "attachment_ids"}:
return error("invalid_request", "Неверные поля запроса", 400, rid)
if set(body) == set() or "text" not in body or not isinstance(body["text"], str):
return error("invalid_request", "Неверный текст сообщения", 400, rid)
text = body["text"]
aids = body.get("attachment_ids", [])
if not isinstance(aids, list) or len(aids) > 10 or len(set(aids)) != len(aids):
return error("invalid_request", "Неверный attachment_ids", 400, rid)
normalized_aids = []
for value in aids:
aid = valid_uuid(value) if isinstance(value, str) else None
if not aid:
return error("invalid_request", "Неверный UUID вложения", 400, rid)
normalized_aids.append(uuid.UUID(aid))
if len(text) > 4000:
return error("invalid_request", "Текст сообщения слишком длинный", 400, rid)
if is_blank(text) and not normalized_aids:
return error("invalid_request", "Пустое сообщение", 400, rid)
canonical = canonical_body({"text": text, "attachment_ids": [str(x) for x in normalized_aids]})
body_hash = hashlib.sha256(json.dumps(canonical, ensure_ascii=False, sort_keys=True).encode()).hexdigest()
path = "/api/v1/chats/" + cid + "/messages"
async with pool.acquire() as con:
if not await member_check(con, uuid.UUID(cid), user["id"]):
return error("not_found", "Объект не найден", 404, rid)
async with con.transaction():
await con.fetchval(
"SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))",
str(user["id"]), cid + ":" + key,
)
prior = await con.fetchrow(
"SELECT body_hash,response_json FROM idempotency "
"WHERE user_id=$1 AND method='POST' AND path=$2 AND key=$3 "
"AND created_at>$4",
user["id"], path, key, utcnow() - timedelta(hours=24),
)
if prior:
if prior["body_hash"] != body_hash:
return error("conflict", "Ключ используется для другого сообщения", 409, rid)
return JSONResponse(
json.loads(prior["response_json"]),
status_code=201,
)
for aid in normalized_aids:
att = await con.fetchrow(
"SELECT chat_id,status FROM attachments WHERE id=$1", aid,
)
if not att or att["chat_id"] != uuid.UUID(cid):
return error("not_found", "Вложение не найдено", 404, rid)
if att["status"] == "failed":
return error("conflict", "Вложение ещё или не готово", 409, rid)
mid = uuid.uuid4()
now = utcnow()
now = now.replace(microsecond=(now.microsecond // 1000) * 1000)
row = await con.fetchrow(
"INSERT INTO messages(id,chat_id,sender_id,text,created_at) "
"VALUES($1,$2,$3,$4,$5) RETURNING id,chat_id,sender_id,text,created_at",
mid, uuid.UUID(cid), user["id"], text, now,
)
await con.executemany(
"INSERT INTO message_attachments(message_id,attachment_id) VALUES($1,$2)",
[(mid, aid) for aid in normalized_aids],
)
response_data = {
"id": str(row["id"]), "chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]), "text": row["text"],
"created_at": rfc3339(row["created_at"]),
"attachment_ids": [str(x) for x in normalized_aids],
}
inserted = await con.fetchval(
"INSERT INTO idempotency(user_id,method,path,key,body_hash,status,response_json,created_at) "
"VALUES($1,'POST',$2,$3,$4,201,$5,$6) "
"ON CONFLICT(user_id,method,path,key) DO NOTHING RETURNING key",
user["id"], path, key, body_hash, json.dumps(response_data), now,
)
if not inserted:
prior = await con.fetchrow(
"SELECT body_hash,response_json FROM idempotency "
"WHERE user_id=$1 AND method='POST' AND path=$2 AND key=$3",
user["id"], path, key,
)
if prior and prior["body_hash"] == body_hash:
return JSONResponse(prior["response_json"], status_code=201)
message = {
"id": str(row["id"]), "chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]), "text": row["text"],
"created_at": rfc3339(row["created_at"]),
"attachment_ids": [str(x) for x in normalized_aids],
}
return JSONResponse(message, status_code=201)
@app.post("/api/v1/chats/{chat_id}/attachments")
async def upload_attachment(chat_id: str, request: Request):
rid = request_id(request)
user, denied = await auth_or_error(request)
if denied:
return denied
cid = valid_uuid(chat_id)
if not cid:
return error("invalid_request", "Неверный UUID чата", 400, rid)
filename = request.query_params.get("filename")
if not filename or len(filename) > 255 or is_blank(filename):
return error("invalid_request", "Неверное имя файла", 400, rid)
if any(ch in filename for ch in ('/', '\\', '\x00')) or any(ord(ch) < 32 for ch in filename):
return error("invalid_request", "Недопустимое имя файла", 400, rid)
media_type = request.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
if media_type not in ("image/png", "image/jpeg"):
return error("unsupported_media_type", "Допустимые форматы — PNG или JPEG", 415, rid)
data = await request.body()
if len(data) > settings.max_upload:
return error("payload_too_large", "Файл превышает допустимый размер", 413, rid)
if len(data) == 0:
return error("unsupported_media_type", "Повреждённое изображение", 415, rid)
try:
from io import BytesIO
with Image.open(BytesIO(data)) as image:
image.verify()
with Image.open(BytesIO(data)) as image:
image_format = image.format
width, height = image.size
if width * height > settings.max_pixels:
return error("payload_too_large", "Изображение содержит слишком много пикселей", 413, rid)
except Exception:
return error("unsupported_media_type", "Повреждённое или неподдерживаемое изображение", 415, rid)
detected = "image/png" if image_format == "PNG" else "image/jpeg" if image_format == "JPEG" else None
if detected != media_type:
return error("unsupported_media_type", "Содержимое не соответствует MIME типу", 415, rid)
async with pool.acquire() as con:
if not await member_check(con, uuid.UUID(cid), user["id"]):
return error("not_found", "Объект не найден", 404, rid)
aid = uuid.uuid4()
sha = hashlib.sha256(data).hexdigest()
staging_key = f"staging/{aid}/{sha}"
now = utcnow()
try:
await asyncio.to_thread(
s3_client().put_object,
Bucket=settings.s3_bucket,
Key=staging_key,
Body=data,
ContentType=detected,
)
async with pool.acquire() as con:
await con.execute(
"INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,"
"sha256,staging_key,status,created_at,updated_at) "
"VALUES($1,$2,$3,$4,$5,$6,$7,$8,'queued',$9,$9)",
aid, uuid.UUID(cid), user["id"], filename, detected, len(data),
sha, staging_key, now,
)
job = {
"schema_version": 1,
"job_id": str(uuid.uuid4()),
"type": "attachment.process.v1",
"attachment_id": str(aid),
"pipeline_version": 1,
"attempt": 1,
"created_at": rfc3339(now),
}
await asyncio.to_thread(publish_job, job)
except Exception:
return error("unavailable", "Хранилище временно недоступно", 503, rid)
return JSONResponse({
"id": str(aid), "chat_id": cid, "owner_id": str(user["id"]),
"filename": filename, "content_type": detected, "size_bytes": len(data),
"sha256": sha, "status": "queued", "variants": [], "error_code": None,
"created_at": rfc3339(now), "updated_at": rfc3339(now),
}, status_code=202)
async def attachment_row(req, aid):
user, denied = await auth_or_error(req)
if denied:
return None, denied
rid = request_id(req)
async with pool.acquire() as con:
row = await con.fetchrow("SELECT * FROM attachments WHERE id=$1", aid)
if not row:
return None, error("not_found", "Объект не найден", 404, rid)
if not await member_check(con, row["chat_id"], user["id"]):
return None, error("not_found", "Объект не найден", 404, rid)
return row, None
def attachment_json(row, variants):
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": row["status"], "variants": variants, "error_code": row["error_code"],
"created_at": rfc3339(row["created_at"]), "updated_at": rfc3339(row["updated_at"]),
}
@app.get("/api/v1/attachments/{attachment_id}")
async def get_attachment(attachment_id: str, request: Request):
rid = request_id(request)
aid = valid_uuid(attachment_id)
if not aid:
return error("invalid_request", "Неверный UUID вложения", 400, rid)
row, denied = await attachment_row(request, uuid.UUID(aid))
if denied:
return denied
async with pool.acquire() as con:
variant_rows = await con.fetch(
"SELECT name,content_type,size_bytes,width,height,sha256 "
"FROM attachment_variants WHERE attachment_id=$1 ORDER BY name", row["id"],
)
variants = [dict(v) for v in variant_rows]
return attachment_json(row, variants)
@app.get("/api/v1/attachments/{attachment_id}/content")
async def attachment_content(attachment_id: str, request: Request):
rid = request_id(request)
aid = valid_uuid(attachment_id)
if not aid:
return error("invalid_request", "Неверный UUID вложения", 400, rid)
row, denied = await attachment_row(request, uuid.UUID(aid))
if denied:
return denied
variant = request.query_params.get("variant", "original")
if row["status"] in ("queued", "processing"):
return error("conflict", "Вложение ещё не готово", 409, rid)
if row["status"] == "failed":
return error("conflict", "Вложение обработано с ошибкой", 409, rid)
try:
if variant == "original":
key = row["final_key"] or row["staging_key"]
content_type = row["content_type"]
else:
if variant != "thumbnail":
return error("not_found", "Вариант не найден", 404, rid)
async with pool.acquire() as con:
v = await con.fetchrow(
"SELECT object_key,content_type FROM attachment_variants "
"WHERE attachment_id=$1 AND name='thumbnail'", row["id"],
)
if not v:
return error("not_found", "Вариант не найден", 404, rid)
key = v["object_key"]
content_type = v["content_type"]
obj = await asyncio.to_thread(s3_client().get_object, Bucket=settings.s3_bucket, Key=key)
data = await asyncio.to_thread(obj["Body"].read)
except Exception:
return error("unavailable", "Хранилище временно недоступно", 503, rid)
return Response(content=data, media_type=content_type,
headers={"Content-Length": str(len(data))})
+134
View File
@@ -0,0 +1,134 @@
import os
import secrets
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
def env(name: str, default: Optional[str] = None, required: bool = False) -> Optional[str]:
value = os.getenv(name, default)
if required and not value:
raise RuntimeError(f"required environment variable {name} is not set")
return value
def secret_file(name: str) -> str:
path = env(name, required=True)
try:
return Path(path).read_text(encoding="utf-8").strip()
except OSError as exc:
raise RuntimeError(f"unable to read secret file {name}") from exc
@dataclass(frozen=True)
class Settings:
database_url: str
session_ttl: int
idempotency_ttl: int
s3_endpoint: str
s3_region: str
s3_bucket: str
s3_access_key: str
s3_secret_key: str
s3_verify: str
broker_url: str
broker_verify: str
bao_addr: str
bao_cacert: str
bao_role_id: str
bao_secret_id: str
bao_api_secret_path: str
bao_worker_secret_path: str
tls_cert: str
tls_key: str
tls_ca: str
tls_client_sans: tuple[str, ...]
argon_memory: int
argon_iterations: int
argon_parallelism: int
otlp_endpoint: Optional[str]
otlp_verify: Optional[str]
max_upload: int
max_pixels: int
job_attempts: int
job_timeout: int
instance_id: str
def load_settings(role: str) -> Settings:
if role not in ("api", "worker"):
raise RuntimeError("role must be api or worker")
argon_memory = int(env("ARGON2_MEMORY_KIB", "19456"))
argon_iterations = int(env("ARGON2_ITERATIONS", "2"))
argon_parallelism = int(env("ARGON2_PARALLELISM", "1"))
if argon_memory < 19456 or argon_iterations < 2 or argon_parallelism < 1:
raise RuntimeError("Argon2id parameters are below the mandatory minimum")
database_url = env("DATABASE_URL")
if not database_url and env("DATABASE_URL_FILE"):
database_url = secret_file("DATABASE_URL_FILE")
broker_url = env("BROKER_URL")
if not broker_url and env("BROKER_URL_FILE"):
broker_url = secret_file("BROKER_URL_FILE")
s3_access = env("S3_ACCESS_KEY_ID")
if not s3_access and env("S3_ACCESS_KEY_ID_FILE"):
s3_access = secret_file("S3_ACCESS_KEY_ID_FILE")
s3_secret = env("S3_SECRET_ACCESS_KEY")
if not s3_secret and env("S3_SECRET_ACCESS_KEY_FILE"):
s3_secret = secret_file("S3_SECRET_ACCESS_KEY_FILE")
if role == "api":
bao_role = env("BAO_API_ROLE_ID") or (
secret_file("BAO_API_ROLE_ID_FILE") if env("BAO_API_ROLE_ID_FILE") else ""
)
bao_secret = env("BAO_API_SECRET_ID") or (
secret_file("BAO_API_SECRET_ID_FILE") if env("BAO_API_SECRET_ID_FILE") else ""
)
else:
bao_role = env("BAO_WORKER_ROLE_ID") or (
secret_file("BAO_WORKER_ROLE_ID_FILE") if env("BAO_WORKER_ROLE_ID_FILE") else ""
)
bao_secret = env("BAO_WORKER_SECRET_ID") or (
secret_file("BAO_WORKER_SECRET_ID_FILE") if env("BAO_WORKER_SECRET_ID_FILE") else ""
)
return Settings(
database_url=database_url,
session_ttl=int(env("SESSION_TTL_SECONDS", "3600")),
idempotency_ttl=int(env("IDEMPOTENCY_TTL_SECONDS", "86400")),
s3_endpoint=env("S3_ENDPOINT", "https://s3:9000"),
s3_region=env("S3_REGION", "us-east-1"),
s3_bucket=env("S3_BUCKET", "messenger-attachments"),
s3_access_key=s3_access or "",
s3_secret_key=s3_secret or "",
s3_verify=env("S3_CACERT", env("TLS_CA_FILE", "/run/secrets/ca.crt")),
broker_url=broker_url or "",
broker_verify=env("RABBITMQ_CACERT", env("TLS_CA_FILE", "/run/secrets/ca.crt")),
bao_addr=env("BAO_ADDR", ""),
bao_cacert=env("BAO_CACERT", ""),
bao_role_id=bao_role or "",
bao_secret_id=bao_secret or "",
bao_api_secret_path=env("BAO_API_SECRET_PATH", env("API_BAO_SECRET_PATH", "secret/data/messenger/api")),
bao_worker_secret_path=env("BAO_WORKER_SECRET_PATH", env("WORKER_BAO_SECRET_PATH", "secret/data/messenger/worker")),
tls_cert=env("TLS_CERT_FILE", ""),
tls_key=env("TLS_KEY_FILE", ""),
tls_ca=env("TLS_CA_FILE", ""),
tls_client_sans=tuple(
x.strip() for x in env(
"TLS_ALLOWED_CLIENT_SANS",
"URI:spiffe://lab7/role/load-balancer",
).split(",") if x.strip()
),
argon_memory=argon_memory,
argon_iterations=argon_iterations,
argon_parallelism=argon_parallelism,
otlp_endpoint=env("OTEL_EXPORTER_OTLP_ENDPOINT"),
otlp_verify=env("OTEL_EXPORTER_TLS_CA", env("TLS_CA_FILE")),
max_upload=int(env("MAX_UPLOAD_BYTES", "10485760")),
max_pixels=int(env("MAX_IMAGE_PIXELS", "40000000")),
job_attempts=int(env("JOB_MAX_ATTEMPTS", "5")),
job_timeout=int(env("JOB_TIMEOUT_SECONDS", "60")),
instance_id=env("INSTANCE_ID", secrets.token_urlsafe(12)),
)
+82
View File
@@ -0,0 +1,82 @@
import ssl
from urllib.parse import urlparse
import asyncpg
SCHEMA = """
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY, username TEXT UNIQUE NOT NULL, display_name TEXT NOT NULL,
password_hash TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY, user_id UUID NOT NULL REFERENCES users(id),
expires_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE IF NOT EXISTS chats (
id UUID PRIMARY KEY, title TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE IF NOT EXISTS chat_members (
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id UUID NOT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
PRIMARY KEY(chat_id,user_id)
);
CREATE TABLE IF NOT EXISTS messages (
id UUID PRIMARY KEY, chat_id UUID NOT NULL REFERENCES chats(id),
sender_id UUID NOT NULL REFERENCES users(id), text TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE IF NOT EXISTS message_attachments (
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
attachment_id UUID NOT NULL, PRIMARY KEY(message_id,attachment_id)
);
CREATE TABLE IF NOT EXISTS attachments (
id UUID PRIMARY KEY, chat_id UUID NOT NULL REFERENCES chats(id),
owner_id UUID NOT NULL REFERENCES users(id), filename TEXT NOT NULL,
content_type TEXT NOT NULL, size_bytes INTEGER NOT NULL, sha256 TEXT NOT NULL,
staging_key TEXT NOT NULL, final_key TEXT,
status TEXT NOT NULL, error_code TEXT, created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE IF NOT EXISTS attachment_variants (
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
name TEXT NOT NULL, content_type TEXT NOT NULL, size_bytes INTEGER NOT NULL,
width INTEGER NOT NULL, height INTEGER NOT NULL, sha256 TEXT NOT NULL,
object_key TEXT NOT NULL, PRIMARY KEY(attachment_id,name)
);
CREATE TABLE IF NOT EXISTS idempotency (
user_id UUID NOT NULL, method TEXT NOT NULL, path TEXT NOT NULL, key TEXT NOT NULL,
body_hash TEXT NOT NULL, status INTEGER NOT NULL, response_json JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY(user_id,method,path,key)
);
CREATE INDEX IF NOT EXISTS idx_sessions_expiry ON sessions(expires_at);
CREATE INDEX IF NOT EXISTS idx_messages_chat_time ON messages(chat_id,created_at,id);
CREATE INDEX IF NOT EXISTS idx_chats_time ON chats(created_at,id);
CREATE INDEX IF NOT EXISTS idx_attachments_status ON attachments(status);
"""
SCHEMA = SCHEMA.replace("user_id UUID NOT NOT NULL", "user_id UUID NOT NULL")
def pg_ssl(database_url: str, ca_path: str) -> ssl.SSLContext:
context = ssl.create_default_context(cafile=ca_path)
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
return context
async def connect(database_url: str, ca_path: str):
return await asyncpg.connect(database_url, ssl=pg_ssl(database_url, ca_path))
async def migrate(pool):
async with pool.acquire() as con:
async with con.transaction():
await con.execute("SELECT pg_advisory_xact_lock($1)", 721548103)
await con.execute(SCHEMA)
await con.execute(
"GRANT SELECT, UPDATE ON attachments TO messenger_worker"
)
await con.execute(
"GRANT SELECT, INSERT, UPDATE ON attachment_variants TO messenger_worker"
)
+147
View File
@@ -0,0 +1,147 @@
"""HTTPS/mTLS entrypoint for the API process."""
import asyncio
import ssl
from urllib.parse import unquote
import h11
import uvicorn
from uvicorn.protocols.http.h11_impl import H11Protocol, RequestResponseCycle
from uvicorn.protocols.http.flow_control import HIGH_WATER_LIMIT
from cryptography import x509
from cryptography.x509.oid import ExtensionOID
from .api import app
from .config import load_settings
from .tls import normalize_allowed_sans, peer_uri_identites
from .tls import API_SERVER_DNS_SAN, LB_URI_SAN
def make_server_context(settings) -> ssl.SSLContext:
if not settings.tls_cert or not settings.tls_key or not settings.tls_ca:
raise RuntimeError("TLS_CERT_FILE, TLS_KEY_FILE and TLS_CA_FILE are required for lab7")
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.minimum_version = ssl.TLSVersion.TLSv1_2
context.load_cert_chain(settings.tls_cert, settings.tls_key)
try:
cert = x509.load_pem_x509_certificate(open(settings.tls_cert, "rb").read())
san = cert.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME).value
if API_SERVER_DNS_SAN not in san.get_values_for_type(x509.DNSName):
raise RuntimeError("API server certificate must contain DNS SAN api")
except (OSError, x509.ExtensionNotFound) as exc:
raise RuntimeError("valid API TLS certificate/SAN is required") from exc
context.load_verify_locations(cafile=settings.tls_ca)
context.verify_mode = ssl.CERT_REQUIRED
return context
async def identity_rejected_app(scope, receive, send):
body = b'{"error":{"code":"unauthorized","message":"TLS client identity rejected","request_id":"tls-identity"}}'
await send({"type": "http.response.start", "status": 401,
"headers": [(b"content-type", b"application/json"),
(b"content-length", str(len(body)).encode("ascii"))]})
await send({"type": "http.response.body", "body": body})
class AllowlistH11Protocol(H11Protocol):
allowed_uri_identity = LB_URI_SAN
def handle_events(self) -> None:
while True:
try:
event = self.conn.next_event()
except h11.RemoteProtocolError:
self.logger.warning("Invalid HTTP request received")
self.send_400_response("Invalid HTTP request received.")
return
if event is h11.NEED_DATA:
break
if event is h11.PAUSED:
self.flow.pause_reading()
break
if isinstance(event, h11.Request):
self.headers = [(key.lower(), value) for key, value in event.headers]
raw_path, _, query_string = event.target.partition(b"?")
ssl_object = self.transport.get_extra_info("ssl_object")
peer = peer_uri_identites(ssl_object)
allowed_from_env = getattr(self.config, "_tls_allowed_client_sans", ())
allowed = normalize_allowed_sans(allowed_from_env) or {self.allowed_uri_identity}
identity_allowed = bool(peer & allowed)
self.scope = {
"type": "http",
"asgi": {"version": self.config.asgi_version, "spec_version": "2.3"},
"http_version": event.http_version.decode("ascii"),
"server": self.server,
"client": self.client,
"scheme": self.scheme,
"method": event.method.decode("ascii"),
"root_path": self.root_path,
"path": unquote(raw_path.decode("ascii")),
"raw_path": raw_path,
"query_string": query_string,
"headers": self.headers,
"state": self.app_state.copy(),
"transport": self.transport,
}
app = identity_rejected_app if not identity_allowed else self.app
if self.limit_concurrency is not None and len(self.connections) >= self.limit_concurrency:
app = __import__("uvicorn.protocols.http.h11_impl", fromlist=["service_unavailable"]).service_unavailable
self.cycle = RequestResponseCycle(
scope=self.scope,
conn=self.conn,
transport=self.transport,
flow=self.flow,
logger=self.logger,
access_logger=self.access_logger,
access_log=self.access_log,
default_headers=self.server_state.default_headers,
message_event=asyncio.Event(),
on_response=self.on_response_complete,
)
task = self.loop.create_task(self.cycle.run_asgi(app))
task.add_done_callback(self.tasks.discard)
self.tasks.add(task)
elif isinstance(event, h11.Data):
if self.conn.our_state is h11.DONE:
continue
self.cycle.body += event.data
if len(self.cycle.body) > HIGH_WATER_LIMIT:
self.flow.pause_reading()
self.cycle.message_event.set()
elif isinstance(event, h11.EndOfMessage):
if self.conn.our_state is h11.DONE:
self.transport.resume_reading()
self.conn.start_next_cycle()
continue
self.cycle.more_body = False
self.cycle.message_event.set()
def main():
settings = load_settings("api")
context = make_server_context(settings)
from os import environ
config = uvicorn.Config(
app,
host=environ.get("APP_HOST", "0.0.0.0"),
port=int(environ.get("APP_PORT", "8443")),
log_level=environ.get("UVICORN_LOG_LEVEL", "info"),
http="h11",
ssl_keyfile=settings.tls_key,
ssl_certfile=settings.tls_cert,
ssl_ca_certs=settings.tls_ca,
ssl_cert_reqs=ssl.CERT_REQUIRED,
)
config.load()
config.ssl = context
config.http_protocol_class = AllowlistH11Protocol
config._tls_allowed_client_sans = settings.tls_client_sans
server = uvicorn.Server(config)
asyncio.run(server.serve())
if __name__ == "__main__":
main()
+35
View File
@@ -0,0 +1,35 @@
import os
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
def configure(service_name: str, instance_id: str, endpoint: str | None, ca_file: str | None):
if not endpoint:
return None
resource = Resource.create({
"service.name": service_name,
"service.version": "1.7.0",
"service.instance.id": instance_id,
"deployment.environment.name": "lab",
})
exporter_headers = None
kwargs = {"certificate_file": ca_file} if ca_file and os.path.isfile(ca_file) else {}
tracer_provider = TracerProvider(resource=resource)
tracer_provider.add_span_processor(
BatchSpanProcessor(OTLPSpanExporter(endpoint=endpoint.rstrip("/") + "/v1/traces",
headers=exporter_headers, **kwargs))
)
metric_reader = PeriodicExportingMetricReader(
OTLPMetricExporter(endpoint=endpoint.rstrip("/") + "/v1/metrics",
headers=exporter_headers, **kwargs)
)
meter_provider = MeterProvider(resource=resource, metric_readers=[metric_reader])
from opentelemetry import trace, metrics
trace.set_tracer_provider(tracer_provider)
metrics.set_meter_provider(meter_provider)
return trace.get_tracer(service_name)
+71
View File
@@ -0,0 +1,71 @@
import unittest
import os
import tempfile
from app.tls import (
API_SERVER_DNS_SAN,
LB_URI_SAN,
normalize_allowed_sans,
peer_uri_identites,
)
from app.config import load_settings
class FakeSslObject:
def getpeercert(self, binary_form=False):
return {"subjectAltName": (
("URI", "spiffe://lab7/role/load-balancer"),
("DNS", "not-a-uri"),
)}
class TlsSanTests(unittest.TestCase):
def test_local_api_and_lb_identities_are_exact(self):
self.assertEqual(API_SERVER_DNS_SAN, "api")
self.assertEqual(LB_URI_SAN, "URI:spiffe://lab7/role/load-balancer")
def test_allowlist_accepts_exact_spiffe_uri(self):
peer = peer_uri_identites(FakeSslObject())
allowed = normalize_allowed_sans(["spiffe://lab7/role/load-balancer"])
self.assertIn("URI:spiffe://lab7/role/load-balancer", peer)
self.assertTrue(peer & allowed)
def test_allowlist_rejects_different_uri(self):
peer = peer_uri_identites(FakeSslObject())
allowed = normalize_allowed_sans(["URI:spiffe://lab7/role/other"])
self.assertFalse(peer & allowed)
class ConfigIntegrationTests(unittest.TestCase):
def test_scoped_bao_files_instance_and_otel_ca(self):
with tempfile.NamedTemporaryFile(mode="w", delete=False) as role, tempfile.NamedTemporaryFile(mode="w", delete=False) as secret:
role.write("api-role-id")
secret.write("api-secret-id")
role_path, secret_path = role.name, secret.name
try:
os.environ["BAO_API_ROLE_ID_FILE"] = role_path
os.environ["BAO_API_SECRET_ID_FILE"] = secret_path
os.environ["BAO_API_SECRET_PATH"] = "secret/data/messenger/api"
os.environ["BAO_ADDR"] = "https://openbao:8200"
os.environ["BAO_CACERT"] = "/run/secrets/bao-ca.crt"
os.environ["INSTANCE_ID"] = "api-01"
os.environ["OTEL_EXPORTER_TLS_CA"] = "/run/secrets/otel-ca.crt"
os.environ["DATABASE_URL"] = "postgresql://api:pass@postgres/db"
settings = load_settings("api")
self.assertEqual(settings.bao_role_id, "api-role-id")
self.assertEqual(settings.bao_secret_id, "api-secret-id")
self.assertEqual(settings.bao_api_secret_path, "secret/data/messenger/api")
self.assertEqual(settings.instance_id, "api-01")
self.assertEqual(settings.otlp_verify, "/run/secrets/otel-ca.crt")
finally:
os.unlink(role_path)
os.unlink(secret_path)
for key in (
"BAO_API_ROLE_ID_FILE", "BAO_API_SECRET_ID_FILE", "BAO_API_SECRET_PATH",
"BAO_ADDR", "BAO_CACERT", "INSTANCE_ID", "OTEL_EXPORTER_TLS_CA", "DATABASE_URL",
):
os.environ.pop(key, None)
if __name__ == "__main__":
unittest.main()
+31
View File
@@ -0,0 +1,31 @@
import ssl
API_SERVER_DNS_SAN = "api"
LB_URI_SAN = "URI:spiffe://lab7/role/load-balancer"
def peer_uri_identites(ssl_object) -> set[str]:
"""Read URI SANs from the TLS socket peer certificate."""
if ssl_object is None:
return set()
try:
cert = ssl_object.getpeercert(binary_form=False)
except (AttributeError, ssl.SSLError):
return set()
if not isinstance(cert, dict):
return set()
return {
"URI:" + value
for kind, value in cert.get("subjectAltName", ())
if kind == "URI"
}
def normalize_allowed_sans(values) -> set[str]:
normalized = set()
for value in values:
value = value.strip()
if not value:
continue
normalized.add(value if value.startswith("URI:") else "URI:" + value)
return normalized
+51
View File
@@ -0,0 +1,51 @@
import json
import ssl
from pathlib import Path
from urllib.request import Request, urlopen
from .config import Settings
def _post_json(url: str, payload: dict, ca: str) -> dict:
context = ssl.create_default_context(cafile=ca)
req = Request(url, data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"}, method="POST")
with urlopen(req, context=context, timeout=10) as response:
return json.loads(response.read())
def login(settings: Settings, role: str) -> dict:
"""Authenticate via the role-scoped AppRole and fetch only that role's KV path."""
if not settings.bao_addr or not settings.bao_cacert:
raise RuntimeError("OpenBao address and TLS CA are required")
if not settings.bao_role_id or not settings.bao_secret_id:
raise RuntimeError("OpenBao AppRole role_id and secret_id are required")
ca = settings.bao_cacert
if not Path(ca).is_file():
raise RuntimeError("OpenBao TLS CA file is unavailable")
login = _post_json(
settings.bao_addr.rstrip("/") + "/v1/auth/approle/login",
{"role_id": settings.bao_role_id, "secret_id": settings.bao_secret_id},
ca,
)
token = login.get("auth", {}).get("client_token")
if not token:
raise RuntimeError("OpenBao AppRole authentication did not return a scoped token")
path = settings.bao_api_secret_path if role == "api" else settings.bao_worker_secret_path
context = ssl.create_default_context(cafile=ca)
req = Request(settings.bao_addr.rstrip("/") + "/v1/" + path.lstrip("v1/"),
headers={"X-Vault-Token": token})
with urlopen(req, context=context, timeout=10) as response:
envelope = json.loads(response.read())
data = envelope.get("data", {})
secrets = data.get("data", data)
if not isinstance(secrets, dict):
raise RuntimeError("OpenBao returned an invalid scoped secret envelope")
if role == "api":
required = ("database_url", "broker_url", "s3_access_key", "s3_secret_key")
else:
required = ("database_url", "broker_url", "s3_access_key", "s3_secret_key")
missing = [key for key in required if not secrets.get(key)]
if missing:
raise RuntimeError("OpenBao scoped secret path is missing required credentials")
return {"token": token, "secrets": secrets}
+232
View File
@@ -0,0 +1,232 @@
import asyncio
import hashlib
import json
import logging
import ssl
import sys
import uuid
from io import BytesIO
import asyncpg
import boto3
import pika
from PIL import Image, ImageOps
from .config import load_settings, env
from .db import pg_ssl
from .vault import login
settings = load_settings("worker")
try:
vault = login(settings, "worker")
except Exception as exc:
logger = logging.getLogger("messenger-worker")
logger.error("worker_startup_secret_auth_failed", extra={
"event": "worker_startup_secret_auth_failed",
"error_type": type(exc).__name__,
})
raise RuntimeError("worker OpenBao AppRole authentication unavailable") from None
secrets = vault["secrets"]
settings = settings.__class__(**{**settings.__dict__,
"database_url": secrets["database_url"],
"broker_url": secrets["broker_url"],
"s3_access_key": secrets["s3_access_key"],
"s3_secret_key": secrets["s3_secret_key"],
})
logger = logging.getLogger("messenger-worker")
async def pool():
ca = env("PG_CACERT", env("TLS_CA_FILE"))
pool = await asyncpg.create_pool(settings.database_url, ssl=pg_ssl(settings.database_url, ca),
min_size=1, max_size=5)
return pool
def s3():
return boto3.client(
"s3",
endpoint_url=settings.s3_endpoint,
region_name=settings.s3_region,
aws_access_key_id=settings.s3_access_key,
aws_secret_access_key=settings.s3_secret_key,
verify=settings.s3_verify,
)
async def process_attachment(pool, attachment_id):
async with pool.acquire() as con:
row = await con.fetchrow("SELECT * FROM attachments WHERE id=$1", attachment_id)
if not row:
return "missing"
if row["status"] == "ready":
return "ready"
await con.execute(
"UPDATE attachments SET status='processing',updated_at=NOW() WHERE id=$1",
attachment_id,
)
client = s3()
original = await asyncio.to_thread(
client.get_object, Bucket=settings.s3_bucket, Key=row["staging_key"]
)
data = await asyncio.to_thread(original["Body"].read)
try:
with Image.open(BytesIO(data)) as source:
source.load()
image = ImageOps.exif_transpose(source)
if image.mode in ("RGBA", "LA") or "transparency" in image.info:
alpha = image.convert("RGBA")
white = Image.new("RGBA", alpha.size, (255, 255, 255, 255))
white.alpha_composite(alpha)
image = white.convert("RGB")
else:
image = image.convert("RGB")
width, height = image.size
if width >= 1 and height >= 1:
scale = min(256 / width, 256 / height, 1.0)
tw = max(1, int(width * scale))
th = max(1, int(height * scale))
thumbnail = image.resize((tw, th), Image.Resampling.LANCZOS)
else:
raise ValueError("invalid image dimensions")
output = BytesIO()
thumbnail.save(output, format="JPEG", quality=85, optimize=True)
thumb = output.getvalue()
except Exception as exc:
logger.error("attachment_processing_failed_safe", extra={
"event": "attachment_processing_failed",
"attachment_id": str(attachment_id),
"error_type": type(exc).__name__,
})
async with pool.acquire() as con:
await con.execute(
"UPDATE attachments SET status='failed',error_code='invalid_image',"
"updated_at=NOW() WHERE id=$1", attachment_id,
)
return "failed"
final_key = f"attachments/{attachment_id}/original"
thumb_key = f"attachments/{attachment_id}/thumbnail"
try:
await asyncio.to_thread(
client.put_object, Bucket=settings.s3_bucket, Key=final_key,
Body=data, ContentType=row["content_type"],
)
await asyncio.to_thread(
client.put_object, Bucket=settings.s3_bucket, Key=thumb_key,
Body=thumb, ContentType="image/jpeg",
)
except Exception as exc:
logger.error("attachment_publish_failed_safe", extra={
"event": "attachment_publish_failed",
"attachment_id": str(attachment_id),
"error_type": type(exc).__name__,
})
async with pool.acquire() as con:
await con.execute(
"UPDATE attachments SET status='failed',error_code='processing_failed',"
"updated_at=NOW() WHERE id=$1", attachment_id,
)
return "failed"
thumb_sha = hashlib.sha256(thumb).hexdigest()
async with pool.acquire() as con:
async with con.transaction():
await con.execute(
"INSERT INTO attachment_variants"
"(attachment_id,name,content_type,size_bytes,width,height,sha256,object_key)"
" VALUES($1,'thumbnail','image/jpeg',$2,$3,$4,$5,$6)"
" ON CONFLICT (attachment_id,name) DO UPDATE SET "
"size_bytes=EXCLUDED.size_bytes,width=EXCLUDED.width,height=EXCLUDED.height,"
"sha256=EXCLUDED.sha256,object_key=EXCLUDED.object_key",
attachment_id, len(thumb), tw, th, thumb_sha, thumb_key,
)
await con.execute(
"UPDATE attachments SET status='ready',error_code=NULL,final_key=$1,"
"updated_at=NOW() WHERE id=$2",
final_key, attachment_id,
)
return "ready"
async def fail_retry_exhausted(pool, attachment_id):
async with pool.acquire() as con:
await con.execute(
"UPDATE attachments SET status='failed',error_code='retry_exhausted',"
"updated_at=NOW() WHERE id=$1",
attachment_id,
)
def main():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
db_pool = loop.run_until_complete(pool())
params = pika.URLParameters(settings.broker_url)
if settings.broker_url.startswith("amqps://"):
ssl_context = ssl.create_default_context(cafile=settings.broker_verify)
ssl_context.check_hostname = True
ssl_context.verify_mode = ssl.CERT_REQUIRED
params.ssl_options = pika.SSLOptions(ssl_context)
connection = pika.BlockingConnection(params)
channel = connection.channel()
channel.queue_declare(queue="attachment.jobs", durable=True)
channel.basic_qos(prefetch_count=settings.job_attempts)
channel.confirm_delivery()
def on_message(ch, method, properties, body):
job = None
try:
job = json.loads(body)
if set(job) - {"schema_version","job_id","type","attachment_id","pipeline_version","attempt","created_at","traceparent","tracestate"}:
raise ValueError("invalid job")
if job.get("schema_version") != 1 or job.get("type") != "attachment.process.v1":
raise ValueError("invalid job")
import uuid
uuid.UUID(job["job_id"])
aid = uuid.UUID(job["attachment_id"])
outcome = loop.run_until_complete(process_attachment(db_pool, aid))
if outcome in ("ready", "missing", "failed"):
ch.basic_ack(delivery_tag=method.delivery_tag)
else:
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
except Exception as exc:
logger.error("worker_job_failed_safe", extra={
"event": "worker_job_failed",
"job_id": job.get("job_id") if isinstance(job, dict) else None,
"attachment_id": job.get("attachment_id") if isinstance(job, dict) else None,
"error_type": type(exc).__name__,
})
attempt = int(job.get("attempt", 1)) if isinstance(job, dict) else 1
if attempt >= settings.job_attempts:
try:
aid = uuid.UUID(job["attachment_id"])
loop.run_until_complete(fail_retry_exhausted(db_pool, aid))
except Exception as exc:
logger.error("retry_exhausted_update_failed_safe", extra={
"event": "retry_exhausted_update_failed",
"attachment_id": job.get("attachment_id") if isinstance(job, dict) else None,
"error_type": type(exc).__name__,
})
ch.basic_ack(delivery_tag=method.delivery_tag)
else:
next_job = dict(job)
next_job["attempt"] = attempt + 1
ch.basic_publish(
exchange="", routing_key="attachment.jobs",
body=json.dumps(next_job, separators=(",", ":")).encode("utf-8"),
properties=pika.BasicProperties(delivery_mode=2),
)
ch.basic_ack(delivery_tag=method.delivery_tag)
channel.basic_consume(queue="attachment.jobs", on_message_callback=on_message)
channel.start_consuming()
if __name__ == "__main__":
main()