Implement TLS identities, scoped OpenBao access and worker security study

This commit is contained in:
2026-11-16 11:57:32 +03:00
parent 20afc2c790
commit 32795a92ac
78 changed files with 8798 additions and 19 deletions
+1
View File
@@ -0,0 +1 @@
"""Учебный REST-мессенджер."""
+12
View File
@@ -0,0 +1,12 @@
import os
import uvicorn
uvicorn.run(
"messenger.app:app",
host=os.getenv("APP_HOST", "0.0.0.0"),
port=int(os.getenv("APP_PORT", "8080")),
workers=1,
access_log=False,
timeout_graceful_shutdown=5,
)
+384
View File
@@ -0,0 +1,384 @@
import base64
import binascii
import json
import logging
import os
import re
import time
from contextlib import asynccontextmanager
from threading import BoundedSemaphore
from uuid import uuid4
from fastapi import Depends, FastAPI, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from opentelemetry import propagate
from opentelemetry.trace import SpanKind, Status, StatusCode
from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException
from . import telemetry
from .attachments import AttachmentService
from .domain import Failure, boundary, identifier, page
from .models import CreateChat, CreateMessage, CreateUser
from .postgres import PostgresStore
from .secrets_provider import refresh
from .storage import ObjectStorage
logger = logging.getLogger("messenger")
logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"), format="%(message)s")
INSTANCE_ID = telemetry.INSTANCE_ID
CODES = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
429: "rate_limited",
503: "unavailable",
500: "internal_error",
}
@asynccontextmanager
async def lifespan(app):
app.state.telemetry = telemetry.setup("messenger-api")
app.state.store = PostgresStore()
app.state.telemetry.start_background(app.state.store)
app.state.storage = ObjectStorage()
app.state.attachments = AttachmentService(app.state.store, app.state.storage)
app.state.upload_slots = BoundedSemaphore(1)
logger.info(json.dumps({"event": "started", "storage": "postgres"}))
yield
logger.info(json.dumps({"event": "stopped"}))
app.state.telemetry.close()
app.state.storage.close()
app.state.store.close()
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
def error(request, status, message, headers=None):
return JSONResponse(
{
"error": {
"code": CODES.get(status, "invalid_request"),
"message": message,
"request_id": request.state.request_id,
}
},
status_code=status,
headers=headers,
)
async def invalid_json_encoding(request: Request):
path = request.url.path
if request.method != "POST" or not (
path in {"/api/v1/users", "/api/v1/chats"}
or re.fullmatch(r"/api/v1/chats/[^/]+/messages", path)
):
return False
raw = await request.body()
try:
raw.decode("utf-8")
except UnicodeDecodeError:
return True
# Literal NUL is invalid JSON; it also prevents json.loads(bytes) from
# autodetecting BOM-less UTF-16/32. Escaped JSON \u0000 remains valid.
return b"\x00" in raw
@app.middleware("http")
async def request_log(request: Request, call_next):
request.state.request_id = str(uuid4())
start = time.perf_counter()
observed = not request.url.path.startswith("/health/")
if not observed:
try:
if request.url.path != "/health/live":
await run_in_threadpool(refresh)
response = await call_next(request)
except Failure as exc:
response = error(request, exc.status, exc.message, exc.headers)
response.headers["X-Request-Id"] = request.state.request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
method = (
request.method
if request.method in {"GET", "POST", "DELETE", "PUT", "PATCH", "HEAD", "OPTIONS"}
else "OTHER"
)
context = propagate.extract(dict(request.headers))
with telemetry.operation("HTTP " + method, context=context, kind=SpanKind.SERVER) as span:
try:
await run_in_threadpool(refresh)
if (
request.method == "POST"
and request.url.path == "/api/v1/auth/sessions"
and await request.body()
):
response = error(request, 400, "Вход не принимает тело запроса")
elif await invalid_json_encoding(request):
response = error(request, 400, "JSON должен быть закодирован в UTF-8")
else:
response = await call_next(request)
except Failure as exc:
response = error(request, exc.status, exc.message, exc.headers)
except Exception:
logger.error(
json.dumps({"event": "unexpected_error", "request_id": request.state.request_id})
)
response = error(request, 500, "Внутренняя ошибка")
response.headers["X-Request-Id"] = request.state.request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
response.headers["X-Trace-Id"] = format(span.get_span_context().trace_id, "032x")
response.headers["X-Trace-Sampled"] = "true" if span.is_recording() else "false"
route = getattr(request.scope.get("route"), "path", "unknown")
elapsed = time.perf_counter() - start
attrs = {
"method": method,
"route": route,
"status_class": str(response.status_code // 100) + "xx",
}
span.update_name(method + " " + route)
span.set_attributes(
{
"http.request.method": method,
"http.route": route,
"http.response.status_code": response.status_code,
}
)
if response.status_code >= 500:
span.set_status(Status(StatusCode.ERROR, "server_error"))
t = telemetry.current()
if observed and t:
t.requests.add(1, attrs)
t.http_duration.record(elapsed, attrs)
t.sampling.add(1, {"decision": "sampled" if span.is_recording() else "not_sampled"})
logger.info(
json.dumps(
{
"event": "request",
"request_id": request.state.request_id,
**attrs,
"status": response.status_code,
"duration_ms": round(elapsed * 1000, 3),
}
)
)
return response
@app.exception_handler(Failure)
async def domain_error(request, exc):
return error(request, exc.status, exc.message, exc.headers)
@app.exception_handler(RequestValidationError)
async def validation_error(request, exc):
return error(request, 400, "Неверный JSON или поля запроса")
@app.exception_handler(HTTPException)
async def http_error(request, exc):
return error(request, exc.status_code, "Неверный запрос", exc.headers)
def bearer_failure():
return Failure(
401, "Требуется действующая сессия", {"WWW-Authenticate": 'Bearer realm="messenger"'}
)
def bearer(request):
parts = request.headers.get("Authorization", "").split()
if len(parts) != 2 or parts[0].lower() != "bearer":
raise bearer_failure()
return parts[1]
def actor(request: Request):
user = request.app.state.store.authenticate(bearer(request))
if user is None:
raise bearer_failure()
return user
@app.post("/api/v1/auth/sessions", status_code=201)
def login(request: Request):
headers = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
parts = request.headers.get("Authorization", "").split()
try:
if len(parts) != 2 or parts[0].lower() != "basic" or len(parts[1]) > 2048:
raise ValueError
decoded = base64.b64decode(parts[1], validate=True).decode("utf-8")
username, password = decoded.split(":", 1)
if not re.fullmatch(r"[a-z0-9_]{3,32}", username) or not 12 <= len(password) <= 128:
raise ValueError
except (ValueError, UnicodeError, binascii.Error):
raise Failure(401, "Неверные учётные данные", headers) from None
session = request.app.state.store.login(username, password)
if session is None:
raise Failure(401, "Неверные учётные данные", headers)
return session
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def logout(request: Request, user=Depends(actor)):
if not request.app.state.store.logout(bearer(request)):
raise bearer_failure()
return Response(status_code=204)
def pagination(request, scope):
allowed = {"limit", "cursor"}
if any(k not in allowed for k in request.query_params):
raise Failure(400, "Неизвестный параметр запроса")
if any(len(request.query_params.getlist(k)) > 1 for k in allowed):
raise Failure(400, "Повторный параметр запроса")
value = request.query_params.get("limit", "50")
if len(value) > 3 or not re.fullmatch(r"[0-9]+", value) or not 1 <= int(value) <= 100:
raise Failure(400, "limit должен быть целым от 1 до 100")
return int(value), boundary(scope, request.query_params.get("cursor"))
@app.get("/health/live")
def live():
return {"status": "ok"}
@app.get("/health/ready")
def ready(request: Request):
if not request.app.state.store.ready() or not request.app.state.storage.ready():
raise Failure(503, "Хранилище недоступно")
return {"status": "ok"}
@app.post("/api/v1/users", status_code=201)
def register(data: CreateUser, request: Request):
return request.app.state.store.register(data.model_dump(mode="json"))
@app.get("/api/v1/users/me")
def me(user=Depends(actor)):
return user
@app.post("/api/v1/chats", status_code=201)
def create_chat(data: CreateChat, request: Request, user=Depends(actor)):
return request.app.state.store.create_chat(user["id"], data.model_dump(mode="json"))
@app.get("/api/v1/chats")
def chats(request: Request, user=Depends(actor)):
scope = "chats:" + user["id"]
limit, after = pagination(request, scope)
return page(request.app.state.store.list_chats(user["id"], after, limit), limit, scope)
@app.get("/api/v1/chats/{chat_id}")
def chat(chat_id: str, request: Request, user=Depends(actor)):
return request.app.state.store.chat(user["id"], identifier(chat_id))
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def send(chat_id: str, data: CreateMessage, request: Request, user=Depends(actor)):
key = request.headers.get("Idempotency-Key", "")
if not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key):
raise Failure(400, "Требуется корректный Idempotency-Key")
return request.app.state.store.send(
user["id"], identifier(chat_id), data.text, key, [str(a) for a in data.attachment_ids]
)
@app.get("/api/v1/chats/{chat_id}/messages")
def history(chat_id: str, request: Request, user=Depends(actor)):
cid = identifier(chat_id)
scope = "messages:" + cid
limit, after = pagination(request, scope)
return page(request.app.state.store.history(user["id"], cid, after, limit), limit, scope)
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
async def upload_attachment(chat_id: str, request: Request, user=Depends(actor)):
import asyncio
import tempfile
from starlette.concurrency import run_in_threadpool
from .attachments import MAX_BYTES, filename_valid
if (
set(request.query_params) != {"filename"}
or len(request.query_params.getlist("filename")) != 1
):
raise Failure(400, "Требуется одно имя файла")
filename = filename_valid(request.query_params["filename"])
cid = identifier(chat_id)
await run_in_threadpool(request.app.state.store.chat, user["id"], cid)
content_type = request.headers.get("content-type", "").lower()
if content_type not in {"image/png", "image/jpeg"}:
raise Failure(415, "Ожидается PNG или JPEG")
if not request.app.state.upload_slots.acquire(blocking=False):
raise Failure(429, "Все места загрузки заняты", {"Retry-After": "1"})
try:
with tempfile.SpooledTemporaryFile(max_size=256 * 1024) as spool:
size = 0
try:
async with asyncio.timeout(15):
async for chunk in request.stream():
size += len(chunk)
if size > MAX_BYTES:
raise Failure(413, "Файл больше 10 MiB")
spool.write(chunk)
except TimeoutError:
raise Failure(400, "Истекло время загрузки") from None
spool.seek(0)
return await run_in_threadpool(
request.app.state.attachments.upload,
user["id"],
cid,
filename,
content_type,
spool,
size,
)
finally:
request.app.state.upload_slots.release()
@app.get("/api/v1/attachments/{attachment_id}")
def attachment_metadata(attachment_id: str, request: Request, user=Depends(actor)):
return request.app.state.attachments.metadata(user["id"], identifier(attachment_id))
@app.get("/api/v1/attachments/{attachment_id}/content")
def attachment_content(attachment_id: str, request: Request, user=Depends(actor)):
from fastapi.responses import StreamingResponse
if (
any(k != "variant" for k in request.query_params)
or len(request.query_params.getlist("variant")) > 1
):
raise Failure(400, "Неверный вариант")
variant = request.query_params.get("variant", "original")
if variant not in {"original", "thumbnail", "crop", "optimized"}:
raise Failure(400, "Неверный вариант")
obj = request.app.state.attachments.content(user["id"], identifier(attachment_id), variant)
def chunks():
try:
while data := obj["Body"].read(64 * 1024):
yield data
finally:
obj["Body"].close()
return StreamingResponse(
chunks(),
media_type=obj["ContentType"],
headers={"Content-Length": str(obj["ContentLength"])},
)
+176
View File
@@ -0,0 +1,176 @@
"""Durable asynchronous intake with full bounded validation before acceptance."""
import hashlib
import json
import os
import signal
import subprocess
import sys
import unicodedata
from pathlib import Path
from uuid import uuid4
from .domain import Failure, timestamp
from .jobs import Jobs, fault
from .postgres import public
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
PUBLIC_FIELDS = (
"id",
"chat_id",
"owner_id",
"filename",
"content_type",
"size_bytes",
"sha256",
"status",
"error_code",
"created_at",
"updated_at",
)
def filename_valid(name):
if not isinstance(name, str) or not 1 <= len(name) <= 255 or not name.strip():
raise Failure(400, "Неверное имя файла")
if any(c in "/\\" or unicodedata.category(c) == "Cc" for c in name):
raise Failure(400, "Неверное имя файла")
return name
def validate_image(fileobj, declared_type):
if declared_type not in {"image/png", "image/jpeg"}:
raise Failure(415, "Ожидается PNG или JPEG")
fileobj.seek(0)
encoded = fileobj.read(MAX_BYTES + 1)
if len(encoded) > MAX_BYTES:
raise Failure(413, "Файл больше 10 MiB")
try:
with subprocess.Popen(
[sys.executable, "-m", "messenger.image_validation", declared_type],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
start_new_session=True,
env={
"PATH": os.environ.get("PATH", os.defpath),
"PYTHONPATH": str(Path(__file__).resolve().parents[1]),
"PYTHONDONTWRITEBYTECODE": "1",
"LANG": "C.UTF-8",
},
) as process:
try:
output, _ = process.communicate(input=encoded, timeout=5)
except subprocess.TimeoutExpired:
# The validator can itself run djpeg: kill its whole process group
# before releasing the upload slot, not only the Python parent.
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass # The child may have exited at the timeout boundary.
process.communicate()
raise Failure(415, "Изображение не прошло ограниченную проверку") from None
if process.returncode:
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
raise Failure(415, "Изображение не прошло ограниченную проверку")
except OSError:
raise Failure(503, "Проверка изображения временно недоступна") from None
finally:
del encoded
try:
outcome = json.loads(output)
except (ValueError, UnicodeError):
raise Failure(415, "Повреждённое изображение") from None
if not isinstance(outcome, dict):
raise Failure(415, "Изображение не прошло ограниченную проверку")
if "error" in outcome:
status = outcome["error"]
if type(status) is not int or status not in {413, 415}:
status = 415
raise Failure(status, "Изображение не прошло ограниченную проверку")
values = outcome.get("ok")
if not isinstance(values, list) or len(values) != 3:
raise Failure(415, "Изображение не прошло ограниченную проверку")
fileobj.seek(0)
return tuple(values)
def metadata_public(row):
return {**public({k: row[k] for k in PUBLIC_FIELDS}), "variants": row["variants"]}
class AttachmentService:
def __init__(self, store, storage):
self.store = store
self.storage = storage
self.jobs = Jobs(store)
def upload(self, actor, cid, filename, content_type, fileobj, size):
filename_valid(filename)
if not 1 <= size <= MAX_BYTES:
raise Failure(413 if size > MAX_BYTES else 415, "Неверный размер изображения")
validate_image(fileobj, content_type)
digest = hashlib.file_digest(fileobj, "sha256").hexdigest()
aid = str(uuid4())
key = "staging/" + aid
now = timestamp()
with self.store.connection() as conn:
self.store._chat(conn, actor, cid)
conn.execute(
"INSERT INTO upload_intents(id,object_key,created_at) VALUES (%s,%s,%s)",
(aid, key, now),
)
# Keep the intent locked throughout PUT/finalization: reconciler skips live
# uploads even if a slow request crosses the grace boundary.
with self.store.connection() as conn, conn.transaction():
intent = conn.execute(
"SELECT id FROM upload_intents WHERE id=%s FOR UPDATE", (aid,)
).fetchone()
if not intent:
raise Failure(503, "Загрузка больше не активна")
self.storage.put(key, fileobj, size, content_type)
fault(self.store, "after_staging", aid)
row = conn.execute(
"INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,"
"status,error_code,created_at,updated_at,object_key,stage_key) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,'queued',NULL,%s,%s,%s,%s) RETURNING *",
(aid, cid, actor, filename, content_type, size, digest, now, now, key, key),
).fetchone()
self.jobs.enqueue(conn, aid, key)
conn.execute("DELETE FROM upload_intents WHERE id=%s", (aid,))
# Never delete S3 on an ambiguous COMMIT: the transaction may have committed.
fault(self.store, "after_upload_commit", aid)
return metadata_public(row)
def metadata(self, actor, aid):
with self.store.connection() as conn:
row = conn.execute(
"SELECT a.* FROM attachments a JOIN members m ON m.chat_id=a.chat_id "
"WHERE a.id=%s AND m.user_id=%s",
(aid, actor),
).fetchone()
if not row:
raise Failure(404, "Объект не найден")
return metadata_public(row)
def content(self, actor, aid, variant="original"):
with self.store.connection() as conn:
row = conn.execute(
"SELECT a.* FROM attachments a JOIN members m ON m.chat_id=a.chat_id "
"WHERE a.id=%s AND m.user_id=%s",
(aid, actor),
).fetchone()
if not row:
raise Failure(404, "Объект не найден")
if row["status"] != "ready":
raise Failure(409, "Вложение не готово")
key = row["object_key"]
if variant != "original":
if variant not in {v["name"] for v in row["variants"]}:
raise Failure(404, "Вариант не найден")
key = key.rsplit("/", 1)[0] + "/" + variant
return self.storage.get(key)
+81
View File
@@ -0,0 +1,81 @@
"""Same SQL with actual PG roles, confined to a disposable synthetic schema."""
import json
import secrets
import psycopg
from psycopg import sql
from .config import secret
def main():
suffix = secrets.token_hex(5)
schema, wide, limited = (prefix + suffix for prefix in ("study_", "wide_", "limited_"))
admin = psycopg.connect(secret("DATABASE_URL"), autocommit=True)
rows = []
try:
# SET ROLE is an explicit operator act. Both NOLOGIN test roles have no
# grants on application tables. Wide owns ONLY the synthetic namespace.
for role in (wide, limited):
admin.execute(sql.SQL("CREATE ROLE {} NOLOGIN").format(sql.Identifier(role)))
admin.execute(
sql.SQL("CREATE SCHEMA {} AUTHORIZATION {}").format(
sql.Identifier(schema), sql.Identifier(wide)
)
)
admin.execute(sql.SQL("SET search_path TO {}").format(sql.Identifier(schema)))
admin.execute(sql.SQL("SET ROLE {}").format(sql.Identifier(wide)))
admin.execute("CREATE TABLE users(password_hash text); CREATE TABLE jobs(id int)")
admin.execute(
sql.SQL("GRANT USAGE ON SCHEMA {} TO {}; GRANT SELECT ON jobs TO {}").format(
sql.Identifier(schema), sql.Identifier(limited), sql.Identifier(limited)
)
)
admin.execute("RESET ROLE")
for label, role in (("wide", wide), ("limited", limited)):
admin.execute(sql.SQL("SET ROLE {}").format(sql.Identifier(role)))
assert admin.execute("SELECT current_user").fetchone()[0] == role
for name, query, restricted_expected in (
("read_password_hash", "SELECT password_hash FROM users LIMIT 0", False),
("create_table", "CREATE TABLE forbidden(id int)", False),
("read_jobs", "SELECT id FROM jobs LIMIT 0", True),
):
try:
admin.execute(query)
allowed = True
if name == "create_table":
admin.execute("DROP TABLE forbidden")
except psycopg.errors.InsufficientPrivilege:
allowed = False
rows.append(
{
"role": label,
"operation": name,
"allowed": allowed,
"expected": restricted_expected if label == "limited" else True,
}
)
admin.execute("RESET ROLE")
passed = all(r["allowed"] == r["expected"] for r in rows)
print(
json.dumps(
{
"scope": "disposable synthetic schema; operator SET ROLE to NOLOGIN roles",
"rows": rows,
"passed": passed,
}
)
)
if not passed:
raise SystemExit(1)
finally:
admin.execute("RESET ROLE")
admin.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(sql.Identifier(schema)))
for role in (limited, wide):
admin.execute(sql.SQL("DROP ROLE IF EXISTS {}").format(sql.Identifier(role)))
admin.close()
if __name__ == "__main__":
main()
+65
View File
@@ -0,0 +1,65 @@
"""Isolated loopback-only Valkey control: same operations before/after ACL narrowing."""
import json
import secrets
import redis
def main():
admin = redis.Redis(host="127.0.0.1", port=6378, decode_responses=True)
wide_pass, limited_pass = secrets.token_urlsafe(24), secrets.token_urlsafe(24)
admin.execute_command(
"ACL", "SETUSER", "wide", "on", ">" + wide_pass, "~security-study:*", "+@all"
)
admin.execute_command(
"ACL",
"SETUSER",
"limited",
"on",
">" + limited_pass,
"~security-study:jobs",
"+ping",
"+xgroup|create",
"+xreadgroup",
"+xautoclaim",
"+xack",
"+xdel",
)
rows = []
for role, password in (("wide", wide_pass), ("limited", limited_pass)):
client = redis.Redis(
host="127.0.0.1", port=6378, username=role, password=password, decode_responses=True
)
for name, operation in (
("queue_admin_acl_list", lambda client=client: client.acl_list()),
(
"queue_publish",
lambda client=client: client.xadd("security-study:jobs", {"body": "synthetic"}),
),
(
"queue_other_key_write",
lambda client=client: client.set("security-study:other", "synthetic"),
),
):
try:
operation()
allowed = True
except redis.ResponseError:
allowed = False
rows.append({"role": role, "operation": name, "allowed": allowed})
client.close()
print(
json.dumps(
{
"isolated_port": 6378,
"rows": rows,
"passed": all(r["allowed"] == (r["role"] == "wide") for r in rows),
}
)
)
admin.shutdown(nosave=True)
if __name__ == "__main__":
main()
+88
View File
@@ -0,0 +1,88 @@
"""Disposable bucket comparison; baseline credentials cannot access messenger."""
import json
from pathlib import Path
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
def client(access, secret, identity):
return boto3.client(
"s3",
endpoint_url="https://storage:8443",
aws_access_key_id=access,
aws_secret_access_key=secret,
region_name="us-east-1",
verify="/run/tls/ca.pem",
config=Config(
client_cert=(
f"/run/audit-identities/{identity}/cert.pem",
f"/run/audit-identities/{identity}/key.pem",
),
connect_timeout=2,
read_timeout=3,
retries={"total_max_attempts": 1},
s3={"addressing_style": "path"},
request_checksum_calculation="when_required",
response_checksum_validation="when_required",
),
)
def main():
root = Path("/run/audit-material")
def read(name):
return (root / name).read_text().strip()
admin = client(read("admin_s3_access"), read("admin_s3_secret"), "operator")
wide = client(read("study_wide_s3_access"), read("study_wide_s3_secret"), "operator")
limited = client(read("worker_s3_access"), read("worker_s3_secret"), "worker")
bucket = "security-study"
rows = []
try:
wide.get_object(Bucket="messenger", Key="private/not-a-real-user-object")
isolated = False
except ClientError as exc:
isolated = exc.response["ResponseMetadata"]["HTTPStatusCode"] == 403
admin.create_bucket(Bucket=bucket)
admin.put_object(Bucket=bucket, Key="private/synthetic", Body=b"synthetic-not-user-data")
try:
for role, c in (("wide", wide), ("limited", limited)):
for operation in ("read_private", "write_private"):
try:
if operation == "read_private":
response = c.get_object(Bucket=bucket, Key="private/synthetic")
response["Body"].read()
response["Body"].close()
else:
c.put_object(Bucket=bucket, Key="private/written", Body=b"synthetic")
allowed = True
except ClientError as exc:
if exc.response["ResponseMetadata"]["HTTPStatusCode"] != 403:
raise
allowed = False
rows.append({"role": role, "operation": operation, "allowed": allowed})
print(
json.dumps(
{
"scope": "disposable bucket security-study; broad role has no messenger rights",
"rows": rows,
"wide_role_denied_application_bucket": isolated,
"passed": isolated
and all(row["allowed"] == (row["role"] == "wide") for row in rows),
}
)
)
finally:
for key in ("private/synthetic", "private/written"):
admin.delete_object(Bucket=bucket, Key=key)
admin.delete_bucket(Bucket=bucket)
for c in (admin, wide, limited):
c.close()
if __name__ == "__main__":
main()
+14
View File
@@ -0,0 +1,14 @@
import os
from pathlib import Path
def secret(name: str) -> str:
if os.getenv("BAO_ROLE"):
from .secrets_provider import value
return value(name)
filename = os.environ.get(name + "_FILE")
value = Path(filename).read_text().strip() if filename else os.environ.get(name, "")
if not value:
raise RuntimeError("Отсутствует настройка " + name)
return value
+63
View File
@@ -0,0 +1,63 @@
import base64
import json
import re
from datetime import UTC, datetime
from uuid import UUID
class Failure(Exception):
def __init__(self, status: int, message: str, headers: dict | None = None):
self.status = status
self.message = message
self.headers = headers or {}
def timestamp() -> str:
return datetime.now(UTC).isoformat(timespec="microseconds").replace("+00:00", "Z")
def identifier(value: str) -> str:
try:
return str(UUID(value))
except (ValueError, TypeError, AttributeError):
raise Failure(400, "Некорректный UUID") from None
def boundary(scope: str, cursor: str | None) -> tuple[str, str] | None:
if cursor is None:
return None
try:
if not cursor or len(cursor) > 1024 or not re.fullmatch(r"[A-Za-z0-9_-]+", cursor):
raise ValueError
data = json.loads(base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)))
if (
not isinstance(data, list)
or len(data) != 4
or type(data[0]) is not int
or data[0] != 1
or data[1] != scope
):
raise ValueError
date, uid = data[2:]
if not isinstance(date, str) or not re.fullmatch(
r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?Z",
date,
):
raise ValueError
datetime.fromisoformat(date.replace("Z", "+00:00"))
if not isinstance(uid, str) or str(UUID(uid)) != uid:
raise ValueError
return date, uid
except (ValueError, TypeError, KeyError, UnicodeError):
raise Failure(400, "Некорректный cursor или область запроса") from None
def page(items: list[dict], limit: int, scope: str) -> dict:
more = len(items) > limit
selected = items[:limit]
cursor = None
if more:
last = selected[-1]
payload = json.dumps([1, scope, last["created_at"], last["id"]], separators=(",", ":"))
cursor = base64.urlsafe_b64encode(payload.encode()).decode().rstrip("=")
return {"items": selected, "next_cursor": cursor}
+82
View File
@@ -0,0 +1,82 @@
"""Image transformations, run in a bounded child process by the worker."""
import hashlib
import json
import sys
from pathlib import Path
from PIL import Image, ImageOps
Image.MAX_IMAGE_PIXELS = 40_000_000
def fitted_size(width, height, bound):
"""Fit without upscale; integer arithmetic deliberately rounds down."""
longest = max(width, height)
if longest <= bound:
return width, height
return max(1, width * bound // longest), max(1, height * bound // longest)
def render(source, destination, version=1):
if version not in (1, 2):
raise ValueError("unsupported_pipeline")
destination = Path(destination)
with Image.open(source) as image:
if image.width * image.height > 40_000_000:
raise ValueError("pixel_limit")
image.load()
ImageOps.exif_transpose(image, in_place=True)
if "A" in image.getbands() or (image.mode == "P" and "transparency" in image.info):
rgba = image if image.mode == "RGBA" else image.convert("RGBA")
rgb = Image.new("RGB", rgba.size, "white")
alpha = rgba.getchannel("A")
rgb.paste(rgba, mask=alpha)
alpha.close()
if rgba is not image:
rgba.close()
else:
rgb = image if image.mode == "RGB" else image.convert("RGB")
thumbnail = rgb.resize(fitted_size(*rgb.size, 256), Image.Resampling.LANCZOS)
crop = ImageOps.fit(rgb, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5))
optimized = rgb.resize(fitted_size(*rgb.size, 1280), Image.Resampling.LANCZOS)
variants = []
for name, variant, kind, mime, options in (
("thumbnail", thumbnail, "JPEG", "image/jpeg", {"quality": 85}),
("crop", crop, "JPEG", "image/jpeg", {"quality": 85}),
(
"optimized",
optimized,
"WEBP",
"image/webp",
{"quality": 80 if version == 1 else 75, "method": 4},
),
):
# No EXIF/ICC arguments: outputs do not propagate source metadata.
path = destination / name
variant.save(path, format=kind, **options)
data = path.read_bytes()
variants.append(
{
"name": name,
"content_type": mime,
"size_bytes": len(data),
"width": variant.width,
"height": variant.height,
"sha256": hashlib.sha256(data).hexdigest(),
}
)
variant.close()
if rgb is not image:
rgb.close()
return variants
if __name__ == "__main__":
import resource
resource.setrlimit(resource.RLIMIT_AS, (700 * 1024**2, 700 * 1024**2))
resource.setrlimit(resource.RLIMIT_CPU, (15, 15))
source, destination, version = sys.argv[1:]
result = render(source, destination, int(version))
(Path(destination) / "variants.json").write_text(json.dumps(result))
+146
View File
@@ -0,0 +1,146 @@
"""Short-lived bounded pixel validation; no DB, credentials or application imports."""
import json
import resource
import subprocess
import sys
from io import BytesIO
from PIL import Image, UnidentifiedImageError
from .domain import Failure
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
def inspect_image(fileobj, declared_type):
if declared_type not in {"image/png", "image/jpeg"}:
raise Failure(415, "Ожидается PNG или JPEG")
try:
fileobj.seek(0)
with Image.open(fileobj) as header:
width, height = header.size
if width * height > MAX_PIXELS:
raise Failure(413, "Слишком много пикселей")
actual = {"PNG": "image/png", "JPEG": "image/jpeg"}.get(header.format)
if actual != declared_type:
raise Failure(415, "Формат изображения не соответствует MIME")
frames = getattr(header, "n_frames", 1)
default_image = bool(getattr(header, "default_image", False))
if width * height * frames > MAX_PIXELS:
raise Failure(413, "Слишком много пикселей во всех кадрах")
header.verify()
# Drop parsed metadata before the separate strict decoder process starts.
del header
if actual == "image/png":
# verify() checks CRC, but does not compare acTL's frame count with
# every fcTL. Do not let a forged count hide a corrupt later frame.
fileobj.seek(8)
controls = frame_controls = 0
declared_frames = None
animation_data = False
while True:
chunk_header = fileobj.read(8)
if len(chunk_header) != 8:
raise ValueError("Truncated PNG chunk")
length = int.from_bytes(chunk_header[:4], "big")
kind = chunk_header[4:]
controls += kind == b"acTL"
frame_controls += kind == b"fcTL"
animation_data |= kind == b"fdAT"
if kind == b"acTL":
if length != 8:
raise ValueError("Invalid acTL length")
declared_frames = int.from_bytes(fileobj.read(4), "big")
fileobj.seek(length, 1) # remaining payload plus CRC
else:
fileobj.seek(length + 4, 1)
if kind == b"IEND":
break
if controls:
if (
controls != 1
or not declared_frames
or frame_controls != declared_frames
or declared_frames + int(default_image) != frames
):
raise ValueError("Invalid APNG frame count")
elif frame_controls or animation_data:
raise ValueError("Animation chunks without acTL")
if actual == "image/jpeg":
# Validate scan warnings before allocating Pillow's decoded canvas.
# 384 MiB covers coefficient arrays for <=40M pixels and <=4 channels;
# keeping both full decoded buffers alive could exceed the API cgroup.
fileobj.seek(0)
# A bounded compressed copy avoids sharing buffered file-descriptor
# offsets with the child, and supports BytesIO callers as well.
encoded = fileobj.read(MAX_BYTES + 1)
if len(encoded) > MAX_BYTES:
raise Failure(413, "Файл больше 10 MiB")
try:
decoded = subprocess.run(
["djpeg", "-strict", "-maxmemory", "384m", "-outfile", "/dev/null"],
input=encoded,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
timeout=4,
check=False,
)
except subprocess.TimeoutExpired:
raise Failure(415, "Изображение не прошло ограниченную проверку") from None
finally:
del encoded
if decoded.returncode:
raise Failure(415, "Повреждённое изображение")
# djpeg has already decoded every JPEG pixel, streaming output rows.
# A second Pillow load would overlap full progressive coefficient
# arrays with a 160 MiB CMYK canvas and violate the API's 512 MiB cap.
fileobj.seek(0)
return actual, width, height
# Decode one frame at a time. Pillow may retain a previous APNG canvas
# for compositing, but no list/copies of every decoded frame is collected.
fileobj.seek(0)
with Image.open(fileobj) as image:
decoded_pixels = 0
for frame in range(frames):
if decoded_pixels + width * height > MAX_PIXELS:
raise Failure(413, "Слишком много пикселей во всех кадрах")
image.seek(frame)
decoded_pixels += image.size[0] * image.size[1]
if decoded_pixels > MAX_PIXELS:
raise Failure(413, "Слишком много пикселей во всех кадрах")
image.load()
# Image's context manager closes its input handle, not the decoded core.
# Releasing the object frees native canvases before hashing/S3 publication.
del image
fileobj.seek(0)
return actual, width, height
except Image.DecompressionBombError:
raise Failure(413, "Слишком много пикселей") from None
except (UnidentifiedImageError, OSError, ValueError, SyntaxError, EOFError):
raise Failure(415, "Повреждённое изображение") from None
def main():
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
resource.setrlimit(resource.RLIMIT_CPU, (4, 5))
if sys.platform == "linux":
resource.setrlimit(resource.RLIMIT_AS, (512 * 1024 * 1024, 512 * 1024 * 1024))
try:
data = sys.stdin.buffer.read(MAX_BYTES + 1)
if len(data) > MAX_BYTES:
raise Failure(413, "Файл больше 10 MiB")
result = inspect_image(BytesIO(data), sys.argv[1])
print(json.dumps({"ok": result}))
except Failure as exc:
print(json.dumps({"error": exc.status}))
except MemoryError:
print(json.dumps({"error": 415}))
except Exception:
print(json.dumps({"error": 415}))
if __name__ == "__main__":
main()
+123
View File
@@ -0,0 +1,123 @@
"""Local operator commands; no public HTTP replay or arbitrary object paths."""
import argparse
import json
from .domain import Failure
from .jobs import Jobs, fault
from .postgres import PostgresStore
from .storage import ObjectStorage
from .worker import cleanup_ready
def cleanup(store, storage, failed_hours=168, intent_seconds=3600):
if failed_hours < 0 or intent_seconds < 0:
raise ValueError("Retention must be nonnegative")
counts = {"ready_staging": 0, "failed_sources": 0, "orphan_intents": 0}
with store.connection() as conn:
ready = conn.execute(
"SELECT id FROM attachments WHERE status='ready' AND stage_key IS NOT NULL"
).fetchall()
for row in ready:
cleanup_ready(store, storage, row["id"])
counts["ready_staging"] += 1
with store.connection() as conn:
candidates = conn.execute(
"SELECT id FROM attachments WHERE status='failed' AND updated_at<now()-(%s * interval '1 hour')",
(failed_hours,),
).fetchall()
for row in candidates:
with store.connection() as conn, conn.transaction():
a = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (row["id"],)
).fetchone()
# Recheck under the same row lock used by replay and publication.
if not a or a["status"] != "failed":
continue
current = conn.execute(
"SELECT * FROM attachment_jobs WHERE attachment_id=%s AND pipeline_version=%s FOR UPDATE",
(a["id"], a["pipeline_version"]),
).fetchone()
if not current or current["state"] != "failed" or current["source_key"] is None:
continue
old = conn.execute(
"SELECT updated_at<now()-(%s * interval '1 hour') AS old FROM attachments WHERE id=%s",
(failed_hours, a["id"]),
).fetchone()["old"]
if not old:
continue
fault(store, "cleanup_before_delete", a["id"])
# If cleanup commits first, later replay refuses source_missing. If replay
# commits first, status is queued and cleanup skips it. DELETE stays locked.
source = current["source_key"]
storage.delete(source)
prefix = f"attachments/{a['id']}/v{a['pipeline_version']}"
for variant in ("original", "thumbnail", "crop", "optimized"):
storage.delete(prefix + "/" + variant)
conn.execute("UPDATE attachment_jobs SET source_key=NULL WHERE id=%s", (current["id"],))
conn.execute("UPDATE attachments SET stage_key=NULL WHERE id=%s", (a["id"],))
Jobs.audit(conn, current["id"], "source_retention_expired", current["attempt"])
counts["failed_sources"] += 1
with store.connection() as conn:
intents = conn.execute(
"SELECT id FROM upload_intents WHERE created_at<now()-(%s * interval '1 second')",
(intent_seconds,),
).fetchall()
for row in intents:
with store.connection() as conn, conn.transaction():
intent = conn.execute(
"SELECT * FROM upload_intents WHERE id=%s FOR UPDATE SKIP LOCKED", (row["id"],)
).fetchone()
if intent is None:
continue
referenced = conn.execute(
"SELECT 1 FROM attachments WHERE id=%s", (row["id"],)
).fetchone()
if referenced is None:
storage.delete(intent["object_key"])
counts["orphan_intents"] += 1
conn.execute("DELETE FROM upload_intents WHERE id=%s", (row["id"],))
return counts
def main():
parser = argparse.ArgumentParser()
sub = parser.add_subparsers(dest="command", required=True)
for name in ("replay", "reprocess"):
command = sub.add_parser(name)
command.add_argument("attachment_id")
if name == "reprocess":
command.add_argument("--version", type=int, required=True)
sub.add_parser("failed")
command = sub.add_parser("cleanup")
command.add_argument("--failed-hours", type=float, default=168)
command.add_argument("--intent-seconds", type=float, default=3600)
args = parser.parse_args()
store, storage = PostgresStore(), ObjectStorage()
try:
jobs = Jobs(store)
if args.command == "replay":
result = {"job_id": jobs.replay(args.attachment_id, storage)}
elif args.command == "reprocess":
result = {"job_id": jobs.reprocess(args.attachment_id, args.version, storage)}
elif args.command == "cleanup":
result = cleanup(store, storage, args.failed_hours, args.intent_seconds)
else:
with store.connection() as conn:
result = [
dict(row)
for row in conn.execute(
"SELECT j.id,j.attachment_id,j.attempt,f.error_code,f.replay_count FROM failed_jobs f JOIN attachment_jobs j ON j.id=f.job_id WHERE j.state='failed'"
).fetchall()
]
print(json.dumps(result, default=str))
except Failure as exc:
print(json.dumps({"status": exc.status, "error": exc.message}))
raise SystemExit(1) from None
finally:
storage.close()
store.close()
if __name__ == "__main__":
main()
+345
View File
@@ -0,0 +1,345 @@
"""PostgreSQL owns job state; broker deliveries are repeatable notifications."""
import json
import logging
import os
import random
import time
from datetime import UTC, datetime
from uuid import uuid4
import redis
from opentelemetry import propagate
from opentelemetry.trace import SpanKind
from . import telemetry
from .config import secret
from .domain import Failure
from .postgres import public
logger = logging.getLogger("messenger.jobs")
STREAM = "attachment-jobs:v1"
GROUP = "image-workers"
def broker_client():
return redis.Redis.from_url(
secret("BROKER_URL"),
decode_responses=False,
socket_connect_timeout=2,
socket_timeout=3,
)
def fault(store, point, attachment_id):
"""Only enabled in the explicit fault-test overlay; never accepts HTTP controls."""
if os.getenv("ENABLE_FAULT_INJECTION") != "1":
return
with store.connection() as conn:
row = conn.execute(
"UPDATE test_faults SET reached_at=now() WHERE id=("
"SELECT id FROM test_faults WHERE point=%s AND reached_at IS NULL "
"AND (attachment_id IS NULL OR attachment_id=%s) ORDER BY id LIMIT 1) RETURNING *",
(point, attachment_id),
).fetchone()
if row is None:
return
logger.warning(json.dumps({"event": "fault_reached", "point": point, "fault_id": row["id"]}))
if row["action"] == "crash":
os._exit(86)
if row["action"] == "error":
raise RuntimeError("injected_transient_failure")
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
with store.connection() as conn:
released = conn.execute(
"SELECT released FROM test_faults WHERE id=%s", (row["id"],)
).fetchone()
if released and released["released"]:
return
time.sleep(0.1)
raise RuntimeError("fault_barrier_timeout")
class Jobs:
def __init__(self, store):
self.store = store
self.attempt_limit = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
self.lease_seconds = int(os.getenv("JOB_LEASE_SECONDS", "45"))
if not 1 <= self.attempt_limit <= 20 or not 5 <= self.lease_seconds <= 300:
raise RuntimeError("Invalid job retry/lease configuration")
def enqueue(self, conn, attachment_id, source_key, version=1):
job_id = str(uuid4())
conn.execute(
"INSERT INTO attachment_jobs(id,attachment_id,pipeline_version,source_key,state,attempt_limit,traceparent,tracestate,accepted_at) "
"VALUES (%s,%s,%s,%s,'queued',%s,%s,%s,clock_timestamp())",
(
job_id,
attachment_id,
version,
source_key,
self.attempt_limit,
telemetry.carrier().get("traceparent"),
telemetry.carrier().get("tracestate"),
),
)
conn.execute("INSERT INTO job_outbox(job_id) VALUES (%s)", (job_id,))
self.audit(conn, job_id, "accepted", 0)
return job_id
@staticmethod
def audit(conn, job_id, event, attempt):
conn.execute(
"INSERT INTO job_audit(job_id,event,attempt) VALUES (%s,%s,%s)",
(job_id, event, attempt),
)
def publish_one(self, broker):
with self.store.connection() as conn, conn.transaction():
job = conn.execute(
"SELECT j.* FROM job_outbox o JOIN attachment_jobs j ON j.id=o.job_id "
"WHERE o.published_at IS NULL AND j.available_at<=now() "
"ORDER BY j.available_at LIMIT 1 FOR UPDATE OF o SKIP LOCKED"
).fetchone()
if job is None:
return False
if job["state"] == "queued":
body = {
"schema_version": 1,
"job_id": str(job["id"]),
"type": "attachment.process.v1",
"attachment_id": str(job["attachment_id"]),
"pipeline_version": job["pipeline_version"],
"attempt": job["attempt"] + 1,
"created_at": public({"v": job["created_at"]})["v"],
}
# XADD response with appendfsync=always is the broker acceptance boundary.
parent = {
key: job.get(key) for key in ("traceparent", "tracestate") if job.get(key)
}
with telemetry.operation(
"attachments publish", context=propagate.extract(parent), kind=SpanKind.PRODUCER
):
body.update(telemetry.carrier())
broker.xadd(STREAM, {"body": json.dumps(body)})
fault(self.store, "after_publish", job["attachment_id"])
conn.execute("UPDATE job_outbox SET published_at=now() WHERE job_id=%s", (job["id"],))
return True
def claim(self, job_id, attachment_id, version):
with self.store.connection() as conn, conn.transaction():
attachment = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment_id,)
).fetchone()
if attachment is None:
return None
job = conn.execute(
"SELECT * FROM attachment_jobs WHERE id=%s FOR UPDATE", (job_id,)
).fetchone()
if (
job is None
or str(job["attachment_id"]) != str(attachment_id)
or job["pipeline_version"] != version
):
return None
if attachment["pipeline_version"] != version:
conn.execute(
"UPDATE attachment_jobs SET state='superseded',updated_at=now() WHERE id=%s AND state NOT IN ('ready','superseded')",
(job_id,),
)
return None
if job["state"] != "queued":
return None
lease_id = str(uuid4())
job = conn.execute(
"UPDATE attachment_jobs SET state='processing',attempt=attempt+1,lease_id=%s,"
"lease_until=now()+(%s * interval '1 second'),updated_at=now() "
"WHERE id=%s AND available_at<=now() RETURNING *",
(lease_id, self.lease_seconds, job_id),
).fetchone()
if job is None:
return None
conn.execute(
"UPDATE attachments SET status='processing',updated_at=now() WHERE id=%s",
(attachment_id,),
)
self.audit(conn, job_id, "claimed", job["attempt"])
job["source_sha256"] = attachment["sha256"]
job["source_size"] = attachment["size_bytes"]
job["source_content_type"] = attachment["content_type"]
return job
def complete(self, job, object_key, variants):
with self.store.connection() as conn, conn.transaction():
attachment = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (job["attachment_id"],)
).fetchone()
current = conn.execute(
"SELECT * FROM attachment_jobs WHERE id=%s FOR UPDATE", (job["id"],)
).fetchone()
if (
attachment["pipeline_version"] != job["pipeline_version"]
or current["state"] != "processing"
or current["lease_id"] != job["lease_id"]
):
self.audit(conn, job["id"], "stale_publish_rejected", job["attempt"])
return False
conn.execute(
"UPDATE attachments SET status='ready',error_code=NULL,object_key=%s,variants=%s::jsonb,updated_at=now() WHERE id=%s",
(object_key, json.dumps(variants), job["attachment_id"]),
)
conn.execute(
"UPDATE attachment_jobs SET state='ready',lease_until=NULL,error_code=NULL,updated_at=now() WHERE id=%s",
(job["id"],),
)
self.audit(conn, job["id"], "published", job["attempt"])
t = telemetry.current()
if t:
t.ready_duration.record(
(datetime.now(UTC) - job["accepted_at"]).total_seconds(),
{"job_type": "attachment.process.v1"},
)
return True
def fail(self, job, code, permanent=False):
with self.store.connection() as conn, conn.transaction():
attachment = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (job["attachment_id"],)
).fetchone()
current = conn.execute(
"SELECT * FROM attachment_jobs WHERE id=%s FOR UPDATE", (job["id"],)
).fetchone()
if (
attachment["pipeline_version"] != job["pipeline_version"]
or current["lease_id"] != job["lease_id"]
or current["state"] != "processing"
):
return
if permanent or current["attempt"] >= current["attempt_limit"]:
final_code = code if permanent else "retry_exhausted"
self._failed(conn, current, final_code)
else:
delay = min(30, 2 ** (current["attempt"] - 1)) + random.uniform(0, 0.5)
conn.execute(
"UPDATE attachment_jobs SET state='queued',error_code=%s,lease_until=NULL,"
"available_at=now()+(%s * interval '1 second'),updated_at=now() WHERE id=%s",
(code, delay, job["id"]),
)
conn.execute(
"UPDATE job_outbox SET published_at=NULL WHERE job_id=%s", (job["id"],)
)
conn.execute(
"UPDATE attachments SET status='queued',updated_at=now() WHERE id=%s",
(job["attachment_id"],),
)
self.audit(conn, job["id"], "retry_scheduled", job["attempt"])
def _failed(self, conn, job, code):
conn.execute(
"UPDATE attachment_jobs SET state='failed',error_code=%s,lease_until=NULL,updated_at=now() WHERE id=%s",
(code, job["id"]),
)
conn.execute(
"UPDATE attachments SET status='failed',error_code=%s,updated_at=now() WHERE id=%s",
(code, job["attachment_id"]),
)
conn.execute(
"INSERT INTO failed_jobs(job_id,error_code) VALUES (%s,%s) "
"ON CONFLICT(job_id) DO UPDATE SET error_code=excluded.error_code,failed_at=now()",
(job["id"], code),
)
self.audit(conn, job["id"], "failed:" + code, job["attempt"])
def recover_one(self):
with self.store.connection() as conn, conn.transaction():
candidate = conn.execute(
"SELECT a.id FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id "
"WHERE j.state='processing' AND j.lease_until<now() LIMIT 1 FOR UPDATE OF a SKIP LOCKED"
).fetchone()
if candidate is None:
return False
job = conn.execute(
"SELECT j.* FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id "
"WHERE j.attachment_id=%s AND j.state='processing' AND j.lease_until<now() "
"AND j.pipeline_version=a.pipeline_version FOR UPDATE OF j",
(candidate["id"],),
).fetchone()
if job is None:
return False
if job["attempt"] >= job["attempt_limit"]:
self._failed(conn, job, "retry_exhausted")
else:
conn.execute(
"UPDATE attachment_jobs SET state='queued',lease_until=NULL,available_at=now(),updated_at=now() WHERE id=%s",
(job["id"],),
)
conn.execute(
"UPDATE attachments SET status='queued',updated_at=now() WHERE id=%s",
(job["attachment_id"],),
)
conn.execute(
"UPDATE job_outbox SET published_at=NULL WHERE job_id=%s", (job["id"],)
)
self.audit(conn, job["id"], "lease_recovered", job["attempt"])
return True
def replay(self, attachment_id, storage):
with self.store.connection() as conn, conn.transaction():
a = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment_id,)
).fetchone()
if not a or a["status"] != "failed":
raise Failure(409, "Повтор разрешён только для failed")
job = conn.execute(
"SELECT * FROM attachment_jobs WHERE attachment_id=%s AND pipeline_version=%s FOR UPDATE",
(attachment_id, a["pipeline_version"]),
).fetchone()
if not job["source_key"] or not storage.exists(job["source_key"]):
raise Failure(409, "Источник больше недоступен")
fault(self.store, "replay_before_commit", attachment_id)
conn.execute(
"UPDATE attachment_jobs SET state='queued',attempt_limit=attempt+%s,available_at=now(),error_code=NULL,updated_at=now() WHERE id=%s",
(self.attempt_limit, job["id"]),
)
conn.execute(
"UPDATE attachments SET status='queued',error_code=NULL,updated_at=now() WHERE id=%s",
(attachment_id,),
)
conn.execute("UPDATE job_outbox SET published_at=NULL WHERE job_id=%s", (job["id"],))
conn.execute(
"UPDATE failed_jobs SET replay_count=replay_count+1 WHERE job_id=%s", (job["id"],)
)
self.audit(conn, job["id"], "operator_replay", job["attempt"])
return str(job["id"])
def reprocess(self, attachment_id, version, storage):
if version not in (1, 2):
raise Failure(400, "Поддерживаются версии pipeline 1 и 2")
with self.store.connection() as conn, conn.transaction():
a = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment_id,)
).fetchone()
if not a:
raise Failure(404, "Вложение отсутствует")
if version <= a["pipeline_version"]:
raise Failure(409, "Нужна более новая версия pipeline")
source = a["object_key"] if a["status"] == "ready" else a["stage_key"]
if not source or not storage.exists(source):
raise Failure(409, "Источник больше недоступен")
if a["status"] == "ready" and a["stage_key"] and a["stage_key"].startswith("staging/"):
# A worker can be paused after publishing ready but before its
# staging cleanup. Do not orphan that key when choosing final v1
# as the new source. Delete stays under the same attachment lock;
# a storage failure leaves the ready version unchanged.
fault(self.store, "reprocess_before_staging_delete", attachment_id)
storage.delete(a["stage_key"])
conn.execute(
"UPDATE attachment_jobs SET state='superseded',updated_at=now() WHERE attachment_id=%s AND state IN ('queued','processing','failed')",
(attachment_id,),
)
conn.execute(
"UPDATE attachments SET pipeline_version=%s,status='queued',variants='[]',error_code=NULL,stage_key=%s,updated_at=now() WHERE id=%s",
(version, source, attachment_id),
)
return self.enqueue(conn, attachment_id, source, version)
+49
View File
@@ -0,0 +1,49 @@
"""Measure configured Argon2 costs without keeping passwords or hashes in evidence."""
import json
import resource
import statistics
import time
from concurrent.futures import ThreadPoolExecutor
from argon2 import PasswordHasher
def main():
kdf = PasswordHasher(time_cost=2, memory_cost=65536, parallelism=1)
samples = []
for _ in range(7):
start = time.perf_counter()
digest = kdf.hash("synthetic-measurement-password")
kdf.verify(digest, "synthetic-measurement-password")
samples.append((time.perf_counter() - start) * 1000)
def one(_):
start = time.perf_counter()
kdf.hash("synthetic-parallel-password")
return (time.perf_counter() - start) * 1000
with ThreadPoolExecutor(max_workers=2) as pool:
parallel = list(pool.map(one, range(4)))
print(
json.dumps(
{
"algorithm": "argon2id",
"memory_kib": 65536,
"time_cost": 2,
"parallelism": 1,
"runs_hash_plus_verify_ms": samples,
"median_hash_plus_verify_ms": statistics.median(samples),
"max_hash_plus_verify_ms": max(samples),
"two_concurrent_hash_ms": parallel,
"process_peak_rss_kib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
"kdf_slots_per_api": 2,
"api_replicas": 2,
"maximum_active_kdf_memory_mib": 256,
}
)
)
if __name__ == "__main__":
main()
+32
View File
@@ -0,0 +1,32 @@
import hashlib
from pathlib import Path
import psycopg
from .config import secret
def migrate():
with psycopg.connect(secret("DATABASE_URL")) as conn:
# Serialize independent migration processes without changing application data.
conn.execute("SELECT pg_advisory_xact_lock(2301002)")
conn.execute(
"CREATE TABLE IF NOT EXISTS schema_migrations "
"(name text PRIMARY KEY, checksum text NOT NULL)"
)
for path in sorted(Path("migrations").glob("*.sql")):
checksum = hashlib.sha256(path.read_bytes()).hexdigest()
old = conn.execute(
"SELECT checksum FROM schema_migrations WHERE name=%s", (path.name,)
).fetchone()
if old:
if old[0] != checksum:
raise RuntimeError("Изменена применённая миграция: " + path.name)
continue
conn.execute(path.read_text())
conn.execute("INSERT INTO schema_migrations VALUES (%s,%s)", (path.name, checksum))
print("Applied", path.name)
if __name__ == "__main__":
migrate()
+71
View File
@@ -0,0 +1,71 @@
import re
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator, model_validator
class RequestModel(BaseModel):
model_config = ConfigDict(extra="forbid")
@field_validator("*", mode="after")
@classmethod
def nonblank(cls, value):
if isinstance(value, str):
value.encode("utf-8")
if isinstance(value, str) and not value.strip():
raise ValueError("Строка не может состоять из пробелов")
return value
class CreateUser(RequestModel):
username: StrictStr = Field(pattern=r"^[a-z0-9_]{3,32}$")
display_name: StrictStr = Field(min_length=1, max_length=100)
password: StrictStr = Field(min_length=12, max_length=128)
@field_validator("username")
@classmethod
def full_username(cls, value):
if not re.fullmatch(r"[a-z0-9_]{3,32}", value):
raise ValueError("Неверное имя пользователя")
return value
class CreateChat(RequestModel):
title: StrictStr = Field(min_length=1, max_length=100)
member_ids: list[UUID] = Field(min_length=1, max_length=100)
@field_validator("member_ids", mode="before")
@classmethod
def string_ids(cls, value):
if not isinstance(value, list) or any(not isinstance(x, str) for x in value):
raise ValueError("Ожидается массив UUID-строк")
return value
@field_validator("member_ids")
@classmethod
def unique_ids(cls, value):
if len(set(value)) != len(value):
raise ValueError("Участники не должны повторяться")
return value
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: StrictStr = Field(max_length=4000)
attachment_ids: list[UUID] = Field(default_factory=list, max_length=10)
@field_validator("attachment_ids", mode="before")
@classmethod
def string_ids(cls, value):
if not isinstance(value, list) or any(not isinstance(x, str) for x in value):
raise ValueError("Ожидается массив UUID-строк")
return value
@model_validator(mode="after")
def content(self):
self.text.encode("utf-8")
if len(set(self.attachment_ids)) != len(self.attachment_ids):
raise ValueError("Вложения не должны повторяться")
if not self.text.strip() and not self.attachment_ids:
raise ValueError("Пустое сообщение без вложений")
return self
+365
View File
@@ -0,0 +1,365 @@
import hashlib
import json
import logging
import os
import secrets
from contextlib import contextmanager
from datetime import UTC, datetime, timedelta
from threading import BoundedSemaphore
from uuid import UUID, uuid4
import psycopg
import redis
from argon2 import PasswordHasher
from argon2.exceptions import VerificationError
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool, PoolTimeout, TooManyRequests
from .config import secret
from .domain import Failure, timestamp
from .secrets_provider import refresh
from .telemetry import operation
logger = logging.getLogger("messenger")
KDF_SLOTS = BoundedSemaphore(2)
KDF = PasswordHasher(time_cost=2, memory_cost=65536, parallelism=1)
DUMMY_HASH = KDF.hash("invalid-user-dummy-password")
class DeadlineConnection(psycopg.Connection):
def wait(self, gen, interval=0.1, timeout=None):
try:
return super().wait(gen, interval=interval, timeout=timeout or 3.0)
except psycopg.errors._WaitTimeout:
# A paused server cannot complete cancellation. Discard an uncertain
# connection instead of returning it to the pool or waiting forever.
self.pgconn.finish()
raise
def public(row):
return {
k: (
str(v)
if isinstance(v, UUID)
else v.astimezone(UTC).isoformat(timespec="microseconds").replace("+00:00", "Z")
if isinstance(v, datetime)
else bytes(v).decode("utf-8")
if isinstance(v, (bytes, memoryview))
else v
)
for k, v in row.items()
if k not in {"password_hash", "token_digest"}
}
class PostgresStore:
def __init__(self):
self.pool = ConnectionPool(
secret("DATABASE_URL"),
connection_class=DeadlineConnection,
min_size=1,
max_size=int(os.getenv("POOL_MAX_SIZE", "8")),
timeout=2,
max_waiting=32,
kwargs={
"autocommit": True,
"row_factory": dict_row,
"connect_timeout": 2,
"options": "-c statement_timeout=2500 -c lock_timeout=1500",
},
check=ConnectionPool.check_connection,
)
self.pool.wait(timeout=15)
self.cache = redis.Redis.from_url(
secret("CACHE_URL"),
socket_connect_timeout=0.2,
socket_timeout=0.2,
decode_responses=True,
)
self.ttl = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
if self.ttl < 1:
raise RuntimeError("SESSION_TTL_SECONDS должен быть положительным")
@contextmanager
def connection(self):
refresh()
try:
with operation("postgres.transaction", {"db.system.name": "postgresql"}):
with self.pool.connection() as conn:
yield conn
except (
psycopg.OperationalError,
psycopg.InterfaceError,
PoolTimeout,
TooManyRequests,
psycopg.errors.QueryCanceled,
psycopg.errors.LockNotAvailable,
):
raise Failure(503, "Хранилище временно недоступно") from None
def close(self):
self.cache.close()
self.pool.close()
def ready(self):
try:
with self.connection() as conn:
conn.execute(
"SELECT u.id,u.password_hash,c.id,m.chat_id,msg.id,s.token_digest,r.key,"
"a.id,a.stage_key,a.pipeline_version,a.variants,ma.attachment_id,ui.object_key,"
"j.id,j.source_key,j.attempt_limit,j.lease_until,j.traceparent,j.tracestate,j.accepted_at,o.job_id,o.published_at,"
"audit.job_id,f.error_code FROM users u,chats c,members m,messages msg,"
"sessions s,message_requests r,attachments a,message_attachments ma,"
"upload_intents ui,attachment_jobs j,job_outbox o,job_audit audit,failed_jobs f "
"WHERE false"
)
return True
except (Failure, psycopg.Error):
return False
def _cached_user(self, uid):
key = "user:v1:" + uid
try:
value = self.cache.get(key)
if value:
cached = json.loads(value)
if (
isinstance(cached, dict)
and cached.get("id") == uid
and set(cached) == {"id", "username", "display_name", "created_at"}
):
return cached
except (redis.RedisError, ValueError, TypeError):
logger.warning(json.dumps({"event": "cache_bypass"}))
user = self.user(uid)
if user:
try:
self.cache.setex(key, 60, json.dumps(user))
except redis.RedisError:
logger.warning(json.dumps({"event": "cache_bypass"}))
return user
def user(self, uid):
with self.connection() as conn:
row = conn.execute(
"SELECT id,username,display_name,created_at FROM users WHERE id=%s", (uid,)
).fetchone()
return public(row) if row else None
def register(self, data):
with KDF_SLOTS:
hashed = KDF.hash(data.pop("password"))
uid = str(uuid4())
try:
with self.connection() as conn:
row = conn.execute(
"INSERT INTO users VALUES (%s,%s,%s,%s,%s) "
"RETURNING id,username,display_name,created_at",
(
uid,
data["username"],
data["display_name"].encode("utf-8"),
hashed,
timestamp(),
),
).fetchone()
return public(row)
except psycopg.errors.UniqueViolation:
raise Failure(409, "Имя пользователя занято") from None
def login(self, username, password):
self.login_budget(username)
with self.connection() as conn:
row = conn.execute("SELECT * FROM users WHERE username=%s", (username,)).fetchone()
try:
if not KDF_SLOTS.acquire(blocking=False):
raise Failure(429, "Слишком много попыток входа", {"Retry-After": "1"})
try:
KDF.verify(row["password_hash"] if row else DUMMY_HASH, password)
finally:
KDF_SLOTS.release()
except VerificationError:
return None
if row is None:
return None
if KDF.check_needs_rehash(row["password_hash"]):
with KDF_SLOTS:
upgraded = KDF.hash(password)
with self.connection() as conn:
conn.execute(
"UPDATE users SET password_hash=%s WHERE id=%s AND password_hash=%s",
(upgraded, row["id"], row["password_hash"]),
)
token = secrets.token_urlsafe(32)
digest = hashlib.sha256(token.encode()).hexdigest()
expires = datetime.now(UTC) + timedelta(seconds=self.ttl)
with self.connection() as conn:
conn.execute("INSERT INTO sessions VALUES (%s,%s,%s)", (digest, row["id"], expires))
return {
"token": token,
"token_type": "Bearer",
"expires_at": public({"v": expires})["v"],
"user": public(row),
}
def login_budget(self, username):
key = hashlib.sha256(username.encode("utf-8")).hexdigest()
with self.connection() as conn, conn.transaction():
# Shared PostgreSQL window, serialized across both API replicas.
conn.execute("SELECT pg_advisory_xact_lock(2301007)")
conn.execute("DELETE FROM login_windows WHERE window_start<now()-interval '1 hour'")
for bucket, maximum in (("global", 30), ("user:" + key, 10)):
count = conn.execute(
"INSERT INTO login_windows(bucket,window_start,count) VALUES (%s,now(),1) "
"ON CONFLICT(bucket) DO UPDATE SET count=CASE WHEN login_windows.window_start<now()-interval '10 seconds' THEN 1 ELSE login_windows.count+1 END, "
"window_start=CASE WHEN login_windows.window_start<now()-interval '10 seconds' THEN now() ELSE login_windows.window_start END RETURNING count",
(bucket,),
).fetchone()["count"]
if count > maximum:
raise Failure(429, "Слишком много попыток входа", {"Retry-After": "10"})
def authenticate(self, token):
if not token or len(token) > 512:
return None
digest = hashlib.sha256(token.encode()).hexdigest()
# Session validity always comes from PostgreSQL, including on a cache hit.
with self.connection() as conn:
row = conn.execute(
"SELECT s.user_id FROM sessions s WHERE s.token_digest=%s AND s.expires_at>now()",
(digest,),
).fetchone()
return self._cached_user(str(row["user_id"])) if row else None
def logout(self, token):
with self.connection() as conn:
row = conn.execute(
"DELETE FROM sessions WHERE token_digest=%s AND expires_at>now() RETURNING user_id",
(hashlib.sha256(token.encode()).hexdigest(),),
).fetchone()
return row is not None
def create_chat(self, actor, data):
if actor not in data["member_ids"]:
raise Failure(400, "Вызывающий должен входить в чат")
cid = str(uuid4())
try:
with self.connection() as conn, conn.transaction():
row = conn.execute(
"INSERT INTO chats VALUES (%s,%s,%s) RETURNING *",
(cid, data["title"].encode("utf-8"), timestamp()),
).fetchone()
for index, uid in enumerate(data["member_ids"]):
conn.execute("INSERT INTO members VALUES (%s,%s,%s)", (cid, uid, index))
return {**public(row), "member_ids": data["member_ids"]}
except psycopg.errors.ForeignKeyViolation:
raise Failure(400, "Неизвестный участник") from None
@staticmethod
def _chat(conn, actor, cid):
row = conn.execute(
"SELECT c.* FROM chats c JOIN members m ON m.chat_id=c.id "
"WHERE c.id=%s AND m.user_id=%s",
(cid, actor),
).fetchone()
if row is None:
raise Failure(404, "Объект не найден")
members = conn.execute(
"SELECT user_id FROM members WHERE chat_id=%s ORDER BY position", (cid,)
).fetchall()
return {**public(row), "member_ids": [str(m["user_id"]) for m in members]}
def chat(self, actor, cid):
with self.connection() as conn:
return self._chat(conn, actor, cid)
def list_chats(self, actor, after, limit):
with self.connection() as conn:
sql = "SELECT c.* FROM chats c JOIN members m ON m.chat_id=c.id WHERE m.user_id=%s"
params = [actor]
if after:
sql += " AND (c.created_at,c.id)>(%s,%s)"
params.extend(after)
sql += " ORDER BY c.created_at,c.id LIMIT %s"
params.append(limit + 1)
rows = conn.execute(sql, params).fetchall()
return [self._chat(conn, actor, str(row["id"])) for row in rows]
def send(self, actor, cid, text, key, attachment_ids=None):
attachment_ids = attachment_ids or []
body_digest = hashlib.sha256(
json.dumps(
{"text": text, "attachment_ids": attachment_ids},
sort_keys=True,
ensure_ascii=False,
separators=(",", ":"),
).encode()
).hexdigest()
with self.connection() as conn, conn.transaction():
self._chat(conn, actor, cid)
# Serializes exactly this semantic key across all API processes. Hash
# collisions can only serialize unrelated requests, never mix results.
scope = json.dumps([actor, "POST", cid, key], separators=(",", ":"))
lock = int.from_bytes(hashlib.sha256(scope.encode()).digest()[:8], "big", signed=True)
conn.execute("SELECT pg_advisory_xact_lock(%s)", (lock,))
old = conn.execute(
"SELECT body_digest,response FROM message_requests "
"WHERE actor_id=%s AND chat_id=%s AND key=%s AND expires_at>now()",
(actor, cid, key),
).fetchone()
if old:
if old["body_digest"] != body_digest:
raise Failure(409, "Ключ уже использован для другого сообщения")
return json.loads(bytes(old["response"]))
conn.execute(
"DELETE FROM message_requests WHERE actor_id=%s AND chat_id=%s AND key=%s",
(actor, cid, key),
)
for aid in attachment_ids:
attachment = conn.execute(
"SELECT id,status FROM attachments WHERE id=%s AND chat_id=%s FOR SHARE",
(aid, cid),
).fetchone()
if not attachment:
raise Failure(404, "Объект не найден")
if attachment["status"] == "failed":
raise Failure(409, "Вложение недоступно")
row = conn.execute(
"INSERT INTO messages VALUES (%s,%s,%s,%s,%s) RETURNING *",
(str(uuid4()), cid, actor, text.encode("utf-8"), timestamp()),
).fetchone()
for position, aid in enumerate(attachment_ids):
conn.execute(
"INSERT INTO message_attachments VALUES (%s,%s,%s)", (row["id"], aid, position)
)
response = {**public(row), "attachment_ids": attachment_ids}
conn.execute(
"INSERT INTO message_requests(actor_id,chat_id,key,body_digest,response,expires_at) "
"VALUES (%s,%s,%s,%s,%s,now()+interval '24 hours')",
(actor, cid, key, body_digest, json.dumps(response).encode("utf-8")),
)
return response
def history(self, actor, cid, after, limit):
with self.connection() as conn:
self._chat(conn, actor, cid)
sql = "SELECT * FROM messages WHERE chat_id=%s"
params = [cid]
if after:
sql += " AND (created_at,id)>(%s,%s)"
params.extend(after)
sql += " ORDER BY created_at,id LIMIT %s"
params.append(limit + 1)
result = []
for row in conn.execute(sql, params).fetchall():
attachments = conn.execute(
"SELECT attachment_id FROM message_attachments WHERE message_id=%s ORDER BY position",
(row["id"],),
).fetchall()
result.append(
{
**public(row),
"attachment_ids": [str(a["attachment_id"]) for a in attachments],
}
)
return result
+60
View File
@@ -0,0 +1,60 @@
"""Fresh connections with deliberately revoked worker material; no fallback."""
import json
import ssl
import urllib.error
import urllib.request
from pathlib import Path
import psycopg
import redis
def main():
old = json.loads(Path("/run/old-worker/material.json").read_text())
checks = {}
try:
conn = psycopg.connect(old["DATABASE_URL"], connect_timeout=2)
conn.close()
checks["old_database_password_denied"] = False
except psycopg.OperationalError:
checks["old_database_password_denied"] = True
url = old["BROKER_URL"].replace("/run/tls/identity/", "/run/old-worker/")
broker = redis.Redis.from_url(url, socket_connect_timeout=2, socket_timeout=2)
try:
broker.ping()
checks["old_broker_client_certificate_denied"] = False
except redis.RedisError:
checks["old_broker_client_certificate_denied"] = True
finally:
broker.close()
ctx = ssl.create_default_context(cafile="/run/tls/ca.pem")
ctx.load_cert_chain("/run/old-worker/cert.pem", "/run/old-worker/key.pem")
for name, url, body in (
("old_s3_certificate_denied", "https://storage:8443/messenger/staging/probe", None),
(
"old_bao_certificate_auth_denied",
"https://openbao:8200/v1/auth/cert/login",
b'{"name":"worker"}',
),
):
try:
with urllib.request.urlopen(
urllib.request.Request(
url, data=body, headers={"Content-Type": "application/json"}
),
context=ctx,
timeout=3,
):
checks[name] = False
except urllib.error.HTTPError as exc:
checks[name] = exc.code in {400, 403}
except (OSError, urllib.error.URLError):
checks[name] = True
print(json.dumps({"checks": checks, "passed": all(checks.values())}))
if not all(checks.values()):
raise SystemExit(1)
if __name__ == "__main__":
main()
+59
View File
@@ -0,0 +1,59 @@
"""Short-lived OpenBao certificate authentication; no root token or SecretID in app."""
import json
import os
import ssl
import threading
import time
import urllib.error
import urllib.request
from .domain import Failure
_lock = threading.Lock()
_values = {}
_valid_until = 0.0
def request(path, *, data=None, token=None):
context = ssl.create_default_context(cafile=os.getenv("BAO_CA_FILE", "/run/tls/ca.pem"))
context.load_cert_chain("/run/tls/identity/cert.pem", "/run/tls/identity/key.pem")
headers = {"Content-Type": "application/json"}
if token:
headers["X-Vault-Token"] = token
payload = json.dumps(data).encode() if data is not None else None
req = urllib.request.Request(
os.environ["BAO_ADDR"] + "/v1/" + path, data=payload, headers=headers
)
with urllib.request.urlopen(req, context=context, timeout=2) as response:
return json.load(response)
def refresh():
global _values, _valid_until
if not os.getenv("BAO_ROLE"):
return
with _lock:
if time.monotonic() < _valid_until:
return
try:
role = os.environ["BAO_ROLE"]
auth = request("auth/cert/login", data={"name": role})["auth"]
values = request("secret/data/services/" + role, token=auth["client_token"])["data"][
"data"
]
# Never keep credentials usable beyond the auth token's short lease.
_values = values
_valid_until = time.monotonic() + min(float(auth["lease_duration"]), 30) - 1
except (OSError, ValueError, KeyError, urllib.error.URLError):
_values = {}
_valid_until = 0
raise Failure(503, "Сервис секретов временно недоступен") from None
def value(name):
refresh()
try:
return _values[name]
except KeyError:
raise RuntimeError("Scoped secret unavailable: " + name) from None
+35
View File
@@ -0,0 +1,35 @@
"""Run API TLS boundary and loopback business server in one namespace."""
import os
import signal
import subprocess
import sys
import time
def main():
children = [subprocess.Popen([sys.executable, "-m", "messenger.tls_gateway"])]
env = dict(os.environ, APP_HOST="127.0.0.1")
children.append(subprocess.Popen([sys.executable, "-m", "messenger"], env=env))
def stop(*_):
for child in children:
child.terminate()
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
try:
while all(child.poll() is None for child in children):
time.sleep(0.2)
finally:
stop()
for child in children:
try:
child.wait(timeout=6)
except subprocess.TimeoutExpired:
child.kill()
child.wait()
if __name__ == "__main__":
main()
+108
View File
@@ -0,0 +1,108 @@
"""Read-only/rollback permission probes plus disposable synthetic prefix objects."""
import io
import json
import os
import socket
import psycopg
import redis
from .domain import Failure
from .jobs import STREAM, broker_client
from .postgres import PostgresStore
from .secrets_provider import request
from .storage import ObjectStorage
def denied(action):
try:
action()
except (psycopg.errors.InsufficientPrivilege, redis.ResponseError, Failure):
return True
return False
def main():
checks = {}
store = PostgresStore()
broker = broker_client()
storage = ObjectStorage()
try:
with store.connection() as conn:
checks["db_identity_worker"] = (
conn.execute("SELECT current_user AS role").fetchone()["role"] == "worker"
)
checks["db_business_users_denied"] = denied(
lambda: conn.execute("SELECT password_hash FROM users LIMIT 0")
)
checks["db_business_messages_denied"] = denied(
lambda: conn.execute("SELECT text FROM messages LIMIT 0")
)
checks["db_create_denied"] = denied(
lambda: conn.execute("CREATE TABLE security_forbidden(id int)")
)
checks["db_owner_mutation_denied"] = denied(
lambda: conn.execute("UPDATE attachments SET owner_id=owner_id WHERE false")
)
checks["db_job_read_allowed"] = (
conn.execute("SELECT count(*) AS n FROM attachment_jobs").fetchone()["n"] >= 0
)
checks["broker_ping_allowed"] = broker.ping()
checks["broker_acl_admin_denied"] = denied(lambda: broker.acl_list())
checks["broker_publish_denied"] = denied(lambda: broker.xadd(STREAM, {"body": "forbidden"}))
checks["broker_wrong_stream_denied"] = denied(lambda: broker.xlen("other-stream"))
checks["broker_group_destroy_denied"] = denied(
lambda: broker.xgroup_destroy(STREAM, "nonexistent-security-probe")
)
key = "attachments/security-probe/v1/original"
storage.put(key, io.BytesIO(b"synthetic"), 9, "application/octet-stream")
checks["s3_results_prefix_write_allowed"] = storage.head(key)["ContentLength"] == 9
checks["s3_staging_write_denied"] = denied(
lambda: storage.put("staging/security-forbidden", io.BytesIO(b"x"), 1, "text/plain")
)
checks["s3_private_prefix_read_denied"] = denied(
lambda: storage.get("private/security-probe")
)
auth = request("auth/cert/login", data={"name": "worker"})["auth"]["client_token"]
checks["bao_own_path_allowed"] = bool(
request("secret/data/services/worker", token=auth)["data"]["data"]
)
import urllib.error
for name, path, data in (
("bao_other_path_denied", "secret/data/services/api", None),
("bao_policy_write_denied", "sys/policies/acl/forbidden", {"policy": ""}),
):
try:
request(path, data=data, token=auth)
checks[name] = False
except urllib.error.HTTPError as exc:
checks[name] = exc.code == 403
for host, port in (
("storage", 8333),
("storage", 9333),
("storage", 8888),
("broker", 6379),
("cache", 6379),
("api", 8080),
):
try:
with socket.create_connection((host, port), 1):
checks[f"no_plaintext_bypass_{host}_{port}"] = False
except OSError:
checks[f"no_plaintext_bypass_{host}_{port}"] = True
checks["worker_image_has_no_root_token"] = not os.path.exists(
"/operator-private/root-token"
)
print(json.dumps({"checks": checks, "passed": all(checks.values())}, sort_keys=True))
if not all(checks.values()):
raise SystemExit(1)
finally:
storage.close()
broker.close()
store.close()
if __name__ == "__main__":
main()
+106
View File
@@ -0,0 +1,106 @@
"""Private S3 access with bounded network waits; never expose storage keys in API."""
import os
from contextlib import contextmanager
import boto3
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError
from .config import secret
from .domain import Failure
from .secrets_provider import refresh
from .telemetry import operation
class ObjectStorage:
def __init__(self, admin=False):
self.bucket = os.getenv("S3_BUCKET", "messenger")
prefix = "S3_ADMIN" if admin else "S3"
self.client = boto3.client(
"s3",
endpoint_url=os.getenv("S3_ENDPOINT", "http://s3:8333"),
aws_access_key_id=secret(prefix + "_ACCESS_KEY"),
aws_secret_access_key=secret(prefix + "_SECRET_KEY"),
region_name="us-east-1",
verify=os.getenv("S3_CA_FILE", "/run/tls/ca.pem"),
config=Config(
client_cert=("/run/tls/identity/cert.pem", "/run/tls/identity/key.pem"),
connect_timeout=1,
read_timeout=2,
retries={"total_max_attempts": 1},
s3={"addressing_style": "path"},
request_checksum_calculation="when_required",
response_checksum_validation="when_required",
),
)
@contextmanager
def boundary(self):
refresh()
try:
with operation("s3.request", {"rpc.system": "aws-api", "rpc.service": "S3"}):
yield
except (BotoCoreError, ClientError):
raise Failure(503, "Хранилище файлов временно недоступно") from None
def put(self, key, fileobj, size, content_type):
fileobj.seek(0)
with self.boundary():
self.client.put_object(
Bucket=self.bucket,
Key=key,
Body=fileobj,
ContentLength=size,
ContentType=content_type,
)
def get(self, key):
refresh()
try:
with operation("s3.get", {"rpc.system": "aws-api", "rpc.service": "S3"}):
return self.client.get_object(Bucket=self.bucket, Key=key)
except ClientError as exc:
if exc.response.get("Error", {}).get("Code") in {"NoSuchKey", "404"}:
raise Failure(404, "Объект не найден") from None
raise Failure(503, "Хранилище файлов временно недоступно") from None
except BotoCoreError:
raise Failure(503, "Хранилище файлов временно недоступно") from None
def head(self, key):
refresh()
try:
with operation("s3.head", {"rpc.system": "aws-api", "rpc.service": "S3"}):
return self.client.head_object(Bucket=self.bucket, Key=key)
except ClientError as exc:
if exc.response.get("Error", {}).get("Code") in {"NoSuchKey", "404", "NotFound"}:
return None
raise Failure(503, "Хранилище файлов временно недоступно") from None
except BotoCoreError:
raise Failure(503, "Хранилище файлов временно недоступно") from None
def exists(self, key):
return self.head(key) is not None
def delete(self, key):
with self.boundary():
self.client.delete_object(Bucket=self.bucket, Key=key)
def objects(self, page_size=100):
with self.boundary():
paginator = self.client.get_paginator("list_objects_v2")
for page in paginator.paginate(
Bucket=self.bucket, PaginationConfig={"PageSize": page_size}
):
yield from page.get("Contents", [])
def ready(self):
try:
with self.boundary():
self.client.head_bucket(Bucket=self.bucket)
return True
except Failure:
return False
def close(self):
self.client.close()
+30
View File
@@ -0,0 +1,30 @@
"""Idempotent private bucket bootstrap; this process alone receives admin keys."""
import time
from botocore.exceptions import BotoCoreError, ClientError
from .storage import ObjectStorage
def main():
storage = ObjectStorage(admin=True)
for attempt in range(30):
try:
try:
storage.client.head_bucket(Bucket=storage.bucket)
except ClientError as exc:
if exc.response["Error"]["Code"] not in {"404", "NoSuchBucket", "NotFound"}:
raise
storage.client.create_bucket(Bucket=storage.bucket)
print("Private bucket ready; anonymous identity is not configured.")
storage.close()
return
except (ClientError, BotoCoreError):
if attempt == 29:
raise RuntimeError("S3 bootstrap timeout") from None
time.sleep(1)
if __name__ == "__main__":
main()
+357
View File
@@ -0,0 +1,357 @@
"""Bounded OTLP telemetry; technical attributes only, no payload/credential capture."""
import json
import logging
import os
import threading
from contextlib import contextmanager
from datetime import UTC, datetime
from uuid import uuid4
import psutil
import requests
from opentelemetry import metrics, propagate, trace
from opentelemetry._logs import set_logger_provider
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, SpanExportResult
from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBased
from opentelemetry.trace import SpanKind, Status, StatusCode
HTTP_BUCKETS = (0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10)
JOB_BUCKETS = (0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 20, 45, 60, 120)
INSTANCE_ID = str(uuid4())
_runtime = None
class Accounting(dict):
def __init__(self, keys):
super().__init__((key, 0) for key in keys)
self.lock = threading.Lock()
def add(self, key, value):
with self.lock:
self[key] += value
def snapshot(self):
with self.lock:
return dict(self)
class RecordedSpans(SpanProcessor):
def __init__(self, stats):
self.stats = stats
def on_start(self, span, parent_context=None):
pass
def on_end(self, span):
if span.context.trace_flags.sampled:
self.stats.add("spans_recorded", 1)
class CountingSession(requests.Session):
"""Count actual protobuf HTTP sends, including transport retries, without retaining data."""
def __init__(self, stats, signal):
super().__init__()
self.stats, self.signal = stats, signal
def send(self, request, **kwargs):
self.stats.add(self.signal + "_wire_bytes", len(request.body or b""))
self.stats.add(self.signal + "_http_sends", 1)
return super().send(request, **kwargs)
class ObservedSpanExporter(OTLPSpanExporter):
def __init__(self, stats, **kwargs):
self.stats = stats
super().__init__(**kwargs)
def export(self, spans):
self.stats.add("spans_in_flight", len(spans))
try:
result = super().export(spans)
key = "spans_exported" if result == SpanExportResult.SUCCESS else "spans_export_failed"
self.stats.add(key, len(spans))
return result
except Exception:
self.stats.add("spans_export_failed", len(spans))
raise
finally:
self.stats.add("spans_in_flight", -len(spans))
class TechnicalLogs(logging.Filter):
def filter(self, record):
return record.name.startswith("messenger")
class JsonFormatter(logging.Formatter):
def format(self, record):
try:
event = json.loads(record.getMessage())
if not isinstance(event, dict):
event = {"event": "application_event"}
except ValueError:
event = {"event": "application_event"}
context = trace.get_current_span().get_span_context()
return json.dumps(
{
**event,
"timestamp": datetime.now(UTC).isoformat(),
"severity": record.levelname,
"service.name": os.getenv("OTEL_SERVICE_NAME", "messenger-api"),
"trace_id": format(context.trace_id, "032x") if context.is_valid else None,
"span_id": format(context.span_id, "016x") if context.is_valid else None,
}
)
class Telemetry:
def __init__(self, service):
self.service = service
self.enabled = os.getenv("OTEL_ENABLED", "1") == "1"
self.busy = 0
self.providers = []
self.export_stats = Accounting(
(
"spans_recorded",
"spans_in_flight",
"spans_exported",
"spans_export_failed",
"traces_wire_bytes",
"traces_http_sends",
"metrics_wire_bytes",
"metrics_http_sends",
"logs_wire_bytes",
"logs_http_sends",
)
)
self.stop = threading.Event()
self.thread = None
resource = Resource.create(
{
"service.name": service,
"service.version": os.getenv("SERVICE_VERSION", "lab7-v1"),
"service.instance.id": INSTANCE_ID,
"deployment.environment.name": "lab",
}
)
os.environ["OTEL_SERVICE_NAME"] = service
root = logging.getLogger()
root.setLevel(logging.INFO)
for handler in root.handlers:
handler.setFormatter(JsonFormatter())
if not root.handlers:
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
root.addHandler(handler)
if self.enabled:
endpoint = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector:4318").rstrip("/")
common = {"timeout": 1.0}
# Standard OTLP environment variables also support HTTPS/mTLS in lab7.
trace_provider = TracerProvider(
resource=resource,
sampler=ParentBased(TraceIdRatioBased(float(os.getenv("OTEL_SAMPLE_RATIO", "1")))),
)
trace_provider.add_span_processor(RecordedSpans(self.export_stats))
self.batch_spans = BatchSpanProcessor(
ObservedSpanExporter(
self.export_stats,
endpoint=endpoint + "/v1/traces",
session=CountingSession(self.export_stats, "traces"),
**common,
),
max_queue_size=256,
max_export_batch_size=64,
schedule_delay_millis=500,
export_timeout_millis=1500,
)
trace_provider.add_span_processor(self.batch_spans)
trace.set_tracer_provider(trace_provider)
reader = PeriodicExportingMetricReader(
OTLPMetricExporter(
endpoint=endpoint + "/v1/metrics",
session=CountingSession(self.export_stats, "metrics"),
**common,
),
export_interval_millis=int(os.getenv("OTEL_METRIC_INTERVAL_MS", "5000")),
export_timeout_millis=1500,
)
meter_provider = MeterProvider(
resource=resource,
metric_readers=[reader],
views=[
View(
instrument_name="messenger.http.duration",
aggregation=ExplicitBucketHistogramAggregation(HTTP_BUCKETS),
),
View(
instrument_name="messenger.job.duration",
aggregation=ExplicitBucketHistogramAggregation(JOB_BUCKETS),
),
View(
instrument_name="messenger.attachment.ready.duration",
aggregation=ExplicitBucketHistogramAggregation(JOB_BUCKETS),
),
],
)
metrics.set_meter_provider(meter_provider)
logger_provider = LoggerProvider(resource=resource)
logger_provider.add_log_record_processor(
BatchLogRecordProcessor(
OTLPLogExporter(
endpoint=endpoint + "/v1/logs",
session=CountingSession(self.export_stats, "logs"),
**common,
),
max_queue_size=256,
max_export_batch_size=64,
schedule_delay_millis=500,
export_timeout_millis=1500,
)
)
set_logger_provider(logger_provider)
otlp_handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
otlp_handler.addFilter(TechnicalLogs())
# Keep machine-readable JSON in OTLP log body, preserving request ID.
otlp_handler.setFormatter(JsonFormatter())
root.addHandler(otlp_handler)
self.providers = [trace_provider, meter_provider, logger_provider]
self.tracer = trace.get_tracer("messenger", "1.0")
meter = metrics.get_meter("messenger", "1.0")
self.requests = meter.create_counter("messenger.http.requests", unit="{request}")
self.http_duration = meter.create_histogram("messenger.http.duration", unit="s")
self.sampling = meter.create_counter("messenger.http.trace.decisions", unit="{request}")
self.jobs = meter.create_counter("messenger.jobs", unit="{job}")
self.job_duration = meter.create_histogram("messenger.job.duration", unit="s")
self.ready_duration = meter.create_histogram(
"messenger.attachment.ready.duration", unit="s"
)
self.queue_depth = meter.create_gauge("messenger.queue.depth", unit="{job}")
self.oldest_age = meter.create_gauge("messenger.queue.oldest.age", unit="s")
self.pool_used = meter.create_gauge("messenger.db.pool.used", unit="{connection}")
self.pool_waiting = meter.create_gauge("messenger.db.pool.waiting", unit="{request}")
self.worker_busy = meter.create_gauge("messenger.worker.busy", unit="{worker}")
self.worker_capacity = meter.create_gauge("messenger.worker.capacity", unit="{worker}")
self.process_cpu = meter.create_gauge("messenger.process.cpu", unit="%")
self.process_memory = meter.create_gauge("messenger.process.memory", unit="By")
self.export_observation = meter.create_gauge("messenger.telemetry.export", unit="{item}")
def start_background(self, store):
process = psutil.Process()
process.cpu_percent()
def collect():
while not self.stop.wait(2):
counts = self.export_stats.snapshot()
# Read-only queue observation of pinned SDK 1.45.2. Conservation
# is evaluated after quiescence, not during concurrent export.
pending = len(self.batch_spans._batch_processor._queue)
counts["spans_pending"] = pending
counts["span_queue_capacity"] = 256
counts["spans_queue_lost"] = max(
0,
counts["spans_recorded"]
- counts["spans_exported"]
- counts["spans_export_failed"]
- counts["spans_in_flight"]
- pending,
)
for name, value in counts.items():
self.export_observation.set(value, {"observation": name})
stats = store.pool.get_stats()
self.pool_used.set(
max(0, stats.get("pool_size", 0) - stats.get("pool_available", 0))
)
self.pool_waiting.set(stats.get("requests_waiting", 0))
self.process_cpu.set(process.cpu_percent())
self.process_memory.set(process.memory_info().rss)
if self.service == "messenger-worker":
self.worker_busy.set(self.busy)
self.worker_capacity.set(1)
if self.service == "messenger-dispatcher":
try:
with store.connection() as conn:
row = conn.execute(
"SELECT count(*) AS depth, COALESCE(EXTRACT(EPOCH FROM now()-min(created_at)),0) AS age FROM attachment_jobs WHERE state IN ('queued','processing')"
).fetchone()
self.queue_depth.set(row["depth"], {"queue": "attachments"})
self.oldest_age.set(float(row["age"]), {"queue": "attachments"})
except Exception:
logging.getLogger("messenger.telemetry").warning(
json.dumps({"event": "queue_observation_unavailable"})
)
if self.enabled:
self.thread = threading.Thread(
target=collect, name="telemetry-observations", daemon=True
)
self.thread.start()
def close(self):
self.stop.set()
if self.thread:
self.thread.join(timeout=4)
# Business shutdown has a fixed budget even if telemetry endpoints are down.
def shutdown_providers():
for provider in self.providers:
provider.shutdown()
shutdown = threading.Thread(
target=shutdown_providers, name="telemetry-shutdown", daemon=True
)
shutdown.start()
shutdown.join(timeout=2)
def setup(service):
global _runtime
if _runtime is None:
_runtime = Telemetry(service)
return _runtime
def current():
return _runtime
def carrier():
result = {}
propagate.inject(result)
return {key: result[key] for key in ("traceparent", "tracestate") if key in result}
@contextmanager
def operation(name, attributes=None, context=None, kind=SpanKind.CLIENT):
if (
kind == SpanKind.CLIENT
and context is None
and not trace.get_current_span().get_span_context().is_valid
):
yield trace.get_current_span()
return
tracer = trace.get_tracer("messenger", "1.0")
with tracer.start_as_current_span(
name,
attributes=attributes or {},
context=context,
kind=kind,
record_exception=False,
set_status_on_exception=False,
) as span:
try:
yield span
except BaseException as exc:
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
raise
+272
View File
@@ -0,0 +1,272 @@
"""Small TLS boundary: exact DNS SAN allowlist, revocation, bounded TCP forwarding.
The upstream is always loopback in the same network namespace. HTTP mode is used
only for S3 prefix authorization; AWS signatures are still checked by S3 itself.
"""
import argparse
import http.client
import json
import os
import selectors
import socket
import socketserver
import ssl
import threading
from contextlib import closing
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import unquote, urlsplit
MAX_BODY = 10 * 1024 * 1024
def settings():
return json.loads(Path(os.environ["TLS_GATEWAY_CONFIG"]).read_text())
def role(cert, allowed):
names = {v for k, v in cert.get("subjectAltName", ()) if k == "DNS"}
found = names.intersection(allowed)
if len(found) != 1:
raise ssl.SSLError("service_identity_denied")
revoked = Path(os.getenv("TLS_REVOKED_FILE", "/run/tls/revoked.json"))
serials = json.loads(revoked.read_text()) if revoked.exists() else []
if cert.get("serialNumber", "").lstrip("0").lower() in serials:
raise ssl.SSLError("certificate_revoked")
return next(iter(found))
def context(cfg):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.set_alpn_protocols(["http/1.1"] if cfg.get("http") else ["h2", "http/1.1"])
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
ctx.load_cert_chain(cfg["cert"], cfg["key"])
if cfg.get("allowed"):
ctx.verify_mode = ssl.CERT_REQUIRED
ctx.load_verify_locations(cfg["ca"])
ctx.options |= ssl.OP_NO_TICKET
return ctx
class Boundary:
def process_request(self, request, address):
if not self.slots.acquire(blocking=False):
request.close()
return
try:
super().process_request(request, address)
except Exception:
self.slots.release()
raise
def process_request_thread(self, request, address):
try:
request.settimeout(2)
wrapped = context(self.cfg).wrap_socket(request, server_side=True)
wrapped.identity = (
role(wrapped.getpeercert(), self.cfg["allowed"])
if self.cfg.get("allowed")
else "public"
)
wrapped.settimeout(15)
super().process_request_thread(wrapped, address)
except (OSError, ValueError):
request.close()
finally:
self.slots.release()
class TCPHandler(socketserver.BaseRequestHandler):
def handle(self):
try:
with socket.create_connection(
("127.0.0.1", self.server.cfg["upstream"]), 2
) as upstream:
self.request.setblocking(False)
upstream.setblocking(False)
with selectors.DefaultSelector() as selector:
selector.register(self.request, selectors.EVENT_READ, upstream)
selector.register(upstream, selectors.EVENT_READ, self.request)
while True:
role(self.request.getpeercert(), self.server.cfg["allowed"])
pending = self.request.pending()
events = selector.select(timeout=0 if pending else 30)
if pending and not any(key.fileobj is self.request for key, _ in events):
events.append((selector.get_key(self.request), selectors.EVENT_READ))
if not events:
return
for key, _ in events:
# Recheck after the bounded wait: a revoked peer must
# not forward one extra command when it wakes select.
role(self.request.getpeercert(), self.server.cfg["allowed"])
try:
chunk = key.fileobj.recv(65536)
except ssl.SSLWantReadError:
continue
if not chunk:
return
# Small writes with finite socket timeout prevent unbounded
# per-connection queues when a peer stops consuming.
destination = key.data
destination.settimeout(5)
destination.sendall(chunk)
destination.setblocking(False)
except (OSError, ssl.SSLError):
return
class TCPServer(Boundary, socketserver.ThreadingTCPServer):
allow_reuse_address = True
daemon_threads = True
request_queue_size = 64
class HTTPHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def handle_expect_100(self):
return True
def log_message(self, *_):
pass
def do_GET(self):
self.forward()
do_HEAD = do_GET
do_PUT = do_GET
do_POST = do_GET
do_DELETE = do_GET
def forward(self):
self.close_connection = True
cfg = self.server.cfg
identity = self.connection.identity
parsed = urlsplit(self.path)
path = unquote(parsed.path)
parts = path.split("/")
if (
parsed.scheme
or parsed.netloc
or parsed.fragment
or any(p in {".", ".."} for p in parts)
or "\\" in path
or "%" in parsed.path
or any(ord(c) < 32 for c in path)
):
self.send_error(403)
return
if cfg.get("backend") and identity != "operator":
allowed = (
self.command == "GET"
if identity == "grafana"
else (
identity == "collector"
and cfg["backend"] == "loki"
and self.command == "POST"
and parsed.path == "/otlp/v1/logs"
)
)
if not allowed:
self.send_error(403)
return
if cfg.get("s3"):
if (
self.headers.get("Host", "").lower() != "storage:8443"
or (identity != "operator" and parsed.query)
or self.headers.get("x-amz-copy-source")
):
self.send_error(403)
return
# A worker can read its sources, write versioned results and remove
# staging. It cannot list buckets, overwrite staging or touch others.
permitted = identity == "operator"
if identity == "api":
permitted = (
path == "/messenger"
and self.command == "HEAD"
or (
path.startswith("/messenger/staging/")
and self.command in {"PUT", "GET", "HEAD", "DELETE"}
)
or (
path.startswith("/messenger/attachments/")
and self.command in {"GET", "HEAD"}
)
)
elif identity == "worker":
permitted = (
path.startswith("/messenger/staging/")
and self.command in {"GET", "HEAD", "DELETE"}
) or (
path.startswith("/messenger/attachments/")
and self.command in {"PUT", "GET", "HEAD"}
)
if not permitted:
self.send_error(403)
return
try:
length = int(self.headers.get("Content-Length", "0"))
body_limit = MAX_BODY if cfg.get("s3") else 1024 * 1024
if length < 0 or length > body_limit or self.headers.get("Transfer-Encoding"):
self.send_error(413)
return
if self.headers.get("Expect", "").lower() == "100-continue":
self.wfile.write(b"HTTP/1.1 100 Continue\r\n\r\n")
self.wfile.flush()
body = self.rfile.read(length)
if len(body) != length:
self.send_error(400)
return
headers = {
k: v
for k, v in self.headers.items()
if k.lower() not in {"connection", "proxy-connection", "expect"}
}
with closing(
http.client.HTTPConnection("127.0.0.1", cfg["upstream"], timeout=5)
) as upstream:
upstream.request(self.command, self.path, body=body, headers=headers)
response = upstream.getresponse()
self.send_response(response.status)
for key, value in response.getheaders():
if key.lower() not in {"connection", "transfer-encoding", "server", "date"}:
self.send_header(key, value)
self.send_header("Connection", "close")
self.end_headers()
if self.command != "HEAD":
while chunk := response.read(65536):
self.wfile.write(chunk)
except (OSError, ValueError, http.client.HTTPException):
self.close_connection = True
class HTTPServer(Boundary, ThreadingHTTPServer):
daemon_threads = True
def serve(cfg):
cls = HTTPServer if cfg.get("http") else TCPServer
handler = HTTPHandler if cfg.get("http") else TCPHandler
with cls(("0.0.0.0", cfg["port"]), handler) as server:
server.cfg = cfg
server.slots = threading.BoundedSemaphore(2 if cfg.get("http") else 32)
server.serve_forever(poll_interval=0.2)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--config")
args = parser.parse_args()
cfg = json.loads(Path(args.config).read_text()) if args.config else settings()
listeners = cfg if isinstance(cfg, list) else [cfg]
threads = [threading.Thread(target=serve, args=(item,), daemon=True) for item in listeners]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
if __name__ == "__main__":
main()
+132
View File
@@ -0,0 +1,132 @@
"""Operator-only network probe: real TLS, exact role authorization and closed raw ports."""
import json
import socket
import ssl
from pathlib import Path
CA = "/run/tls/ca.pem"
IDENTITIES = Path("/run/audit-identities")
def exchange(host, port, role, payload, *, hostname=None, trust=True):
context = (
ssl.create_default_context(cafile=CA) if trust else ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
)
if role:
context.load_cert_chain(IDENTITIES / role / "cert.pem", IDENTITIES / role / "key.pem")
context.set_alpn_protocols(["h2"] if port == 44317 else ["http/1.1"])
try:
with socket.create_connection((host, port), 2) as raw:
with context.wrap_socket(raw, server_hostname=hostname or host) as secured:
secured.settimeout(3)
secured.sendall(payload)
result = secured.recv(4096)
return bool(result), result
except (OSError, ssl.SSLError):
return False, b""
def main():
checks = {}
# Every gateway is tested positively with its intended role and negatively
# with another valid certificate from the SAME CA, no certificate, foreign
# CA certificate, empty trust and wrong server hostname.
targets = [
(
"api",
9443,
"lb",
b"GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n",
),
("broker", 6380, "worker", b"*1\r\n$4\r\nPING\r\n"),
("cache", 6380, "api", b"*1\r\n$4\r\nPING\r\n"),
(
"storage",
8443,
"worker",
b"HEAD /messenger HTTP/1.1\r\nHost: storage:8443\r\nConnection: close\r\n\r\n",
),
(
"collector",
4318,
"api",
b"POST /v1/traces HTTP/1.1\r\nHost: collector\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}",
),
(
"collector",
9464,
"prometheus",
b"GET /metrics HTTP/1.1\r\nHost: collector\r\nConnection: close\r\n\r\n",
),
(
"collector",
8888,
"prometheus",
b"GET /metrics HTTP/1.1\r\nHost: collector\r\nConnection: close\r\n\r\n",
),
(
"prometheus",
9443,
"grafana",
b"GET /api/v1/query?query=up HTTP/1.1\r\nHost: prometheus\r\nConnection: close\r\n\r\n",
),
(
"loki",
9443,
"grafana",
b"GET /loki/api/v1/labels HTTP/1.1\r\nHost: loki\r\nConnection: close\r\n\r\n",
),
(
"tempo",
9443,
"grafana",
b"GET /api/search HTTP/1.1\r\nHost: tempo\r\nConnection: close\r\n\r\n",
),
]
for host, port, role, payload in targets:
key = f"{host}_{port}"
ok, response = exchange(host, port, role, payload)
checks[key + "_allowed_identity"] = ok and (
response.startswith(b"HTTP/1.1") or response.startswith(b"-NOAUTH")
)
wrong = "worker" if host == "api" else "lb"
for label, identity, hostname, trust in (
("wrong_trusted_identity", wrong, None, True),
("no_client_cert", None, None, True),
("foreign_ca_client", "foreign", None, True),
("wrong_server_hostname", role, "invalid.example", True),
("empty_trust", role, None, False),
):
ok, _ = exchange(host, port, identity, payload, hostname=hostname, trust=trust)
checks[key + "_" + label + "_denied"] = not ok
otlp = b"POST /v1/traces HTTP/1.1\r\nHost: tempo\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}"
checks["tempo_otlp_collector_allowed"] = exchange("tempo", 44318, "collector", otlp)[0]
checks["tempo_otlp_wrong_role_denied"] = not exchange("tempo", 44318, "worker", otlp)[0]
for host, ports in (
("api", [8080]),
("storage", [8333, 8888, 9333]),
("broker", [6379]),
("cache", [6379]),
("collector", [14318, 19464, 18888, 13133]),
("prometheus", [9090]),
("loki", [3100]),
("tempo", [3200, 4317, 4318]),
):
for port in ports:
try:
with socket.create_connection((host, port), 1):
checks[f"raw_{host}_{port}_closed"] = False
except OSError:
checks[f"raw_{host}_{port}_closed"] = True
# Datasource roles cannot submit arbitrary telemetry or mutate Prometheus.
forbidden = b"POST /otlp/v1/logs HTTP/1.1\r\nHost: loki\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}"
ok, body = exchange("loki", 9443, "grafana", forbidden)
checks["grafana_loki_write_denied"] = ok and b" 403 " in body.split(b"\r\n", 1)[0]
print(json.dumps({"checks": checks, "passed": all(checks.values())}, sort_keys=True))
if not all(checks.values()):
raise SystemExit(1)
if __name__ == "__main__":
main()
+292
View File
@@ -0,0 +1,292 @@
"""Separate serial worker (prefetch=1) and transactional-outbox dispatcher."""
import argparse
import hashlib
import json
import logging
import re
import signal
import subprocess
import sys
import tempfile
import time
from datetime import datetime
from pathlib import Path
from uuid import UUID, uuid4
import redis
from opentelemetry import propagate, trace
from opentelemetry.trace import SpanKind, Status, StatusCode
from . import telemetry
from .domain import Failure
from .jobs import GROUP, STREAM, Jobs, broker_client, fault
from .postgres import PostgresStore
from .secrets_provider import refresh
from .storage import ObjectStorage
logger = logging.getLogger("messenger.worker")
logging.basicConfig(level=logging.INFO, format="%(message)s")
stopping = False
MAX_JOB_BYTES = 8192
def stop(signum, frame):
global stopping
stopping = True
def process(job, jobs, storage):
fault(jobs.store, "before_effect", job["attachment_id"])
with tempfile.TemporaryDirectory(prefix="image-job-") as directory:
root = Path(directory)
source = root / "source"
response = storage.get(job["source_key"])
try:
if response["ContentLength"] > 10_485_760:
raise ValueError("invalid_image")
with source.open("wb") as target:
while block := response["Body"].read(64 * 1024):
target.write(block)
if target.tell() > 10_485_760:
raise ValueError("invalid_image")
finally:
response["Body"].close()
with source.open("rb") as file:
digest = hashlib.file_digest(file, "sha256").hexdigest()
if digest != job["source_sha256"] or source.stat().st_size != job["source_size"]:
raise ValueError("invalid_image")
# Resize executes outside the API and is bounded in wall time, CPU and address space.
result = subprocess.run(
[
sys.executable,
"-m",
"messenger.image_pipeline",
str(source),
directory,
str(job["pipeline_version"]),
],
timeout=20,
capture_output=True,
check=False,
)
if result.returncode:
raise ValueError("invalid_image")
variants = json.loads((root / "variants.json").read_text())
prefix = f"attachments/{job['attachment_id']}/v{job['pipeline_version']}"
with source.open("rb") as file:
storage.put(
prefix + "/original", file, source.stat().st_size, job["source_content_type"]
)
for variant in variants:
path = root / variant["name"]
with path.open("rb") as file:
storage.put(
prefix + "/" + variant["name"],
file,
variant["size_bytes"],
variant["content_type"],
)
fault(jobs.store, "after_effect", job["attachment_id"])
published = jobs.complete(job, prefix + "/original", variants)
if published:
fault(jobs.store, "after_result_commit", job["attachment_id"])
cleanup_ready(jobs.store, storage, job["attachment_id"])
return published
def cleanup_ready(store, storage, attachment_id):
# Same row lock as reprocess/replay: cannot delete a source chosen by a new job.
with store.connection() as conn, conn.transaction():
a = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment_id,)
).fetchone()
if (
a
and a["status"] == "ready"
and a["stage_key"]
and a["stage_key"].startswith("staging/")
):
storage.delete(a["stage_key"])
conn.execute("UPDATE attachments SET stage_key=NULL WHERE id=%s", (attachment_id,))
def validate_delivery(body):
if not isinstance(body, (str, bytes, bytearray)):
raise ValueError("invalid_job")
encoded = body.encode("utf-8") if isinstance(body, str) else body
if len(encoded) > MAX_JOB_BYTES:
raise ValueError("invalid_job")
try:
data = json.loads(encoded)
except RecursionError:
raise ValueError("invalid_job") from None
expected = {
"schema_version",
"job_id",
"type",
"attachment_id",
"pipeline_version",
"attempt",
"created_at",
}
optional = {"traceparent", "tracestate"}
if not isinstance(data, dict) or not expected <= set(data) or set(data) - expected - optional:
raise ValueError("invalid_job")
if (
type(data["schema_version"]) is not int
or data["schema_version"] != 1
or data["type"] != "attachment.process.v1"
):
raise ValueError("invalid_job")
if not isinstance(data["job_id"], str) or not isinstance(data["attachment_id"], str):
raise ValueError("invalid_job")
for field in ("job_id", "attachment_id"):
canonical = str(UUID(data[field]))
if data[field].lower() != canonical:
raise ValueError("invalid_job")
# RFC UUID hex is case-insensitive; PostgreSQL and state comparisons use
# the same canonical spelling, so a valid uppercase delivery is not lost.
data[field] = canonical
if type(data["pipeline_version"]) is not int or data["pipeline_version"] < 1:
raise ValueError("invalid_job")
if type(data["attempt"]) is not int or data["attempt"] < 1:
raise ValueError("invalid_job")
created = data["created_at"]
if (
not isinstance(created, str)
or len(created) > 64
or not re.fullmatch(
r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]+)?Z", created
)
):
raise ValueError("invalid_job")
datetime.fromisoformat(created[:-1] + "+00:00")
if "traceparent" in data and (
not isinstance(data["traceparent"], str)
or not re.fullmatch(r"00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}", data["traceparent"])
):
raise ValueError("invalid_job")
if "tracestate" in data and (
not isinstance(data["tracestate"], str) or len(data["tracestate"]) > 512
):
raise ValueError("invalid_job")
return data
def consume_one(store, jobs, storage, broker, entry):
entry_id, fields = entry
try:
body = validate_delivery(fields.get("body", fields.get(b"body")))
except (KeyError, ValueError, TypeError):
logger.error(json.dumps({"event": "invalid_delivery"}))
broker.xack(STREAM, GROUP, entry_id)
broker.xdel(STREAM, entry_id)
return
with telemetry.operation(
"attachments consume", context=propagate.extract(body), kind=SpanKind.CONSUMER
):
consume_job(store, jobs, storage, broker, body)
# Durable state owns recovery even when notification acknowledgements repeat.
broker.xack(STREAM, GROUP, entry_id)
broker.xdel(STREAM, entry_id)
def consume_job(store, jobs, storage, broker, body):
job = jobs.claim(body["job_id"], body["attachment_id"], body["pipeline_version"])
t = telemetry.current()
started = time.perf_counter()
outcome = "duplicate"
if job:
try:
if t:
t.busy = 1
outcome = "success" if process(job, jobs, storage) else "superseded"
except ValueError:
jobs.fail(job, "invalid_image", permanent=True)
outcome = "failed"
except (Failure, subprocess.TimeoutExpired, OSError, RuntimeError) as exc:
logger.warning(
json.dumps(
{"event": "job_retry", "job_id": str(job["id"]), "kind": type(exc).__name__}
)
)
jobs.fail(job, "processing_failed")
outcome = "retry" if job["attempt"] < job["attempt_limit"] else "failed"
finally:
if t:
t.busy = 0
attrs = {"job_type": "attachment.process.v1", "outcome": outcome}
t.jobs.add(1, attrs)
t.job_duration.record(time.perf_counter() - started, attrs)
span = trace.get_current_span()
span.set_attributes({"job.type": "attachment.process.v1", "job.outcome": outcome})
if outcome in {"failed", "retry"}:
span.set_status(Status(StatusCode.ERROR, "processing_failed"))
logger.info(json.dumps({"event": "job_finished", "outcome": outcome}))
else:
trace.get_current_span().set_attributes(
{"job.type": "attachment.process.v1", "job.outcome": "duplicate"}
)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--dispatcher", action="store_true")
args = parser.parse_args()
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
t = telemetry.setup("messenger-dispatcher" if args.dispatcher else "messenger-worker")
store = PostgresStore()
t.start_background(store)
jobs = Jobs(store)
broker = broker_client()
storage = None if args.dispatcher else ObjectStorage()
consumer = "worker-" + str(uuid4())
last_claim = 0
try:
while not stopping:
try:
refresh()
if args.dispatcher:
jobs.recover_one()
if not jobs.publish_one(broker):
time.sleep(0.2)
continue
try:
broker.xgroup_create(STREAM, GROUP, id="0", mkstream=True)
except redis.ResponseError as exc:
if "BUSYGROUP" not in str(exc):
raise
entries = []
if time.monotonic() - last_claim >= 5:
claimed = broker.xautoclaim(
STREAM,
GROUP,
consumer,
min_idle_time=jobs.lease_seconds * 1000,
start_id="0-0",
count=1,
)
entries = claimed[1]
last_claim = time.monotonic()
if not entries:
batches = broker.xreadgroup(GROUP, consumer, {STREAM: ">"}, count=1, block=500)
entries = batches[0][1] if batches else []
for entry in entries:
consume_one(store, jobs, storage, broker, entry)
except (redis.RedisError, Failure) as exc:
logger.warning(
json.dumps({"event": "dependency_retry", "kind": type(exc).__name__})
)
time.sleep(0.5)
finally:
broker.close()
if storage is not None:
storage.close()
t.close()
store.close()
if __name__ == "__main__":
main()