lab 7 openbao

This commit is contained in:
2026-11-23 14:39:13 +03:00
parent 20afc2c790
commit 912a874f00
118 changed files with 12464 additions and 5108 deletions
View File
+141
View File
@@ -0,0 +1,141 @@
"""Lab 6 dispatcher (lab 5 + OpenTelemetry): transactional-outbox relay + lease reaper + queue gauges.
* relay : outbox rows (committed together with the state change) -> Kafka (acks=all, idempotent producer, delivery report)
* reaper : processing job with an expired lease (worker died) -> queued again (or failed when attempts are exhausted)
"""
from __future__ import annotations
import json
import logging
import os
import time
from pathlib import Path
import psycopg
from confluent_kafka import Producer
from opentelemetry import metrics, trace
from opentelemetry.propagate import extract, inject
from opentelemetry.trace import SpanKind, Status, StatusCode
from . import jobs, telemetry, vault
# Lab 7: dispatcher = DB role messenger_dispatcher + Kafka producer identity; no S3, no Redis credentials.
vault.load_into_env("dispatcher")
telemetry.init("messenger-dispatcher", instrument=("psycopg",))
log = logging.getLogger("dispatcher")
TRACER = telemetry.tracer()
# ---- Lab 6: queue gauges are computed HERE (not in the worker) so they stay visible when the worker is stopped. ----
QUEUE_SAMPLE_SECONDS = 5.0
_queue = {"depth": 0.0, "oldest": 0.0, "at": None}
def _queue_gauge(key: str):
def callback(_options):
at = _queue["at"]
if at is not None and time.monotonic() - at < 30: # stale (DB down) => no observation instead of a fake value
yield metrics.Observation(_queue[key], {"queue.name": jobs.JOBS_TOPIC})
return callback
telemetry.meter().create_observable_gauge("messenger.queue.depth", callbacks=[_queue_gauge("depth")], unit="{job}",
description="Jobs waiting for a worker: status=queued and due (backoff elapsed)")
telemetry.meter().create_observable_gauge("messenger.queue.oldest_job_age", callbacks=[_queue_gauge("oldest")], unit="s",
description="Age of the oldest waiting job (now - time it became due); 0 if the queue is empty")
telemetry.register_process_metrics()
def sample_queue(conn) -> None:
depth, oldest = conn.execute(
"SELECT count(*), COALESCE(EXTRACT(EPOCH FROM (now() - min(next_attempt_at))), 0) "
"FROM attachment_jobs WHERE status='queued' AND next_attempt_at <= now()").fetchone()
_queue.update(depth=float(depth), oldest=max(0.0, float(oldest)), at=time.monotonic())
POLL_SECONDS = float(os.getenv("DISPATCH_POLL_SECONDS", "1"))
BATCH = int(os.getenv("OUTBOX_BATCH", "100"))
FAULT_FLAG = Path("/tmp/dispatcher_fault_done")
FAULT_EXIT_BEFORE_PUBLISH = os.getenv("FAULT_DISPATCHER_EXIT_BEFORE_PUBLISH", "0") == "1" # test hook: crash between COMMIT and publish
def relay(conn, producer: Producer) -> int:
with conn.transaction():
rows = conn.execute("SELECT id, topic, msg_key, payload::text FROM outbox WHERE published_at IS NULL AND available_at <= now() "
"ORDER BY id LIMIT %s FOR UPDATE SKIP LOCKED", (BATCH,)).fetchall()
if not rows:
return 0
if FAULT_EXIT_BEFORE_PUBLISH and not FAULT_FLAG.exists():
FAULT_FLAG.touch()
log.error("FAULT: exiting after reading the outbox, before publishing (COMMIT happened, publish did not)")
os._exit(137)
delivered, errors = set(), {}
for oid, topic, key, payload in rows:
msg = json.loads(payload)
# PRODUCER span: child of the span that wrote the outbox row (API upload / worker retry); the payload then
# carries THIS span's traceparent, so the worker's CONSUMER span becomes its child.
span = TRACER.start_span(f"{topic} publish", context=extract(msg), kind=SpanKind.PRODUCER,
attributes={"messaging.system": "kafka", "messaging.destination.name": topic,
"messaging.operation.type": "publish", "job.id": msg.get("job_id", ""),
"job.attempt": msg.get("attempt", 0)})
with trace.use_span(span, end_on_exit=False):
inject(msg)
def cb(err, _m, oid=oid, span=span):
if err:
errors[oid] = str(err)
span.set_status(Status(StatusCode.ERROR, "delivery not confirmed"))
else:
delivered.add(oid) # publisher confirm arrives here
span.end()
producer.produce(topic, key=key.encode(), value=json.dumps(msg).encode(), on_delivery=cb)
producer.flush(15)
if delivered:
conn.execute("UPDATE outbox SET published_at=now() WHERE id = ANY(%s)", (list(delivered),))
if errors:
telemetry.log_event(log, logging.WARNING, "outbox_publish_unconfirmed", f"{len(errors)} outbox rows not confirmed by the broker, will retry", count=len(errors))
return len(delivered)
def reap(conn) -> int:
n = 0
with conn.transaction():
for job_id, att_id, attempt, max_attempts, pv in conn.execute(
"SELECT job_id, attachment_id, attempt, max_attempts, pipeline_version FROM attachment_jobs "
"WHERE status='processing' AND lease_until < now() FOR UPDATE SKIP LOCKED").fetchall():
if attempt >= max_attempts:
jobs.fail_job(conn, job_id, att_id, "retry_exhausted", attempt)
else:
conn.execute("UPDATE attachment_jobs SET status='queued', lease_until=NULL, next_attempt_at=now(), updated_at=now() WHERE job_id=%s", (job_id,))
conn.execute("UPDATE attachments SET status='queued', updated_at=now() WHERE id=%s", (att_id,))
jobs.add_event(conn, job_id, "lease_expired", f"attempt={attempt}")
jobs.enqueue(conn, job_id, att_id, pv, attempt + 1)
n += 1
return n
def main() -> None:
producer = Producer({**jobs.kafka_ssl(), "bootstrap.servers": jobs.KAFKA_BOOTSTRAP, "acks": "all", "enable.idempotence": True,
"message.timeout.ms": 15000, "linger.ms": 5})
telemetry.log_event(log, logging.INFO, "dispatcher_started", f"dispatcher started (poll={POLL_SECONDS:.1f}s)")
last_sample = 0.0
while True:
try:
with psycopg.connect(connect_timeout=5, autocommit=True, options="-c statement_timeout=20000") as conn:
while True:
done = reap(conn)
sent = relay(conn, producer)
if done or sent:
telemetry.log_event(log, logging.INFO, "dispatcher_cycle", f"reaped={done} published={sent}", count=sent)
if time.monotonic() - last_sample >= QUEUE_SAMPLE_SECONDS:
sample_queue(conn)
last_sample = time.monotonic()
if not sent:
time.sleep(POLL_SECONDS)
except psycopg.Error as exc:
log.warning("database unavailable: %s", type(exc).__name__); time.sleep(2)
except Exception as exc:
log.warning("dispatcher iteration failed: %s", type(exc).__name__); time.sleep(2)
if __name__ == "__main__":
main()
+97
View File
@@ -0,0 +1,97 @@
"""Image pipeline v1. Runs in a CHILD process with hard CPU/address-space limits (called by worker.py).
python -m src.imgproc <input-file> <output-dir>
Writes thumbnail.jpg, crop.jpg, optimized.webp and prints JSON metadata on stdout.
Exit codes: 0 ok, 2 invalid image, 3 too many pixels, 4 out of memory, other = unexpected (treated as transient).
"""
from __future__ import annotations
import hashlib
import json
import os
import resource
import sys
from pathlib import Path
from PIL import Image, ImageOps
MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
THUMB_BOX, CROP_SIZE, OPT_BOX = 256, 128, 1280
JPEG_QUALITY, WEBP_QUALITY = 85, 80 # documented in REPORT.md
EXIT_INVALID, EXIT_TOO_LARGE, EXIT_OOM = 2, 3, 4
def fit_box(w: int, h: int, box: int) -> tuple[int, int]:
"""Fit (w,h) into box x box, keep aspect ratio, never upscale, floor, min 1 px. Integer math: 320x200 -> 256x160."""
if w <= box and h <= box:
return w, h
if w >= h:
return box, max(1, h * box // w)
return max(1, w * box // h), box
def flatten_on_white(img: Image.Image) -> Image.Image:
"""RGB image; any alpha is composited on white (JPEG has no alpha)."""
if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
rgba = img.convert("RGBA")
bg = Image.new("RGB", rgba.size, (255, 255, 255))
bg.paste(rgba, mask=rgba.getchannel("A"))
return bg
return img.convert("RGB")
def save(img: Image.Image, path: Path, fmt: str, **opts) -> dict:
img.save(path, fmt, **opts) # no exif=/icc_profile= passed => metadata is stripped
data = path.read_bytes()
return {"size_bytes": len(data), "width": img.width, "height": img.height, "sha256": hashlib.sha256(data).hexdigest()}
def process(src: Path, out: Path) -> dict:
with Image.open(src) as img:
if img.format not in ("PNG", "JPEG"):
raise ValueError("unsupported format")
if img.width < 1 or img.height < 1:
raise ValueError("empty image")
if img.width * img.height > MAX_IMAGE_PIXELS: # decided from the header, before any pixel buffer exists
raise OverflowError("too many pixels")
img.load()
base = ImageOps.exif_transpose(img) # apply EXIF orientation once; result has no orientation tag
base.load()
result = {}
# thumbnail: JPEG, fit 256x256, no upscale, alpha -> white
flat = flatten_on_white(base)
t = flat.resize(fit_box(*flat.size, THUMB_BOX), Image.LANCZOS) if fit_box(*flat.size, THUMB_BOX) != flat.size else flat
result["thumbnail"] = {"content_type": "image/jpeg", **save(t, out / "thumbnail.jpg", "JPEG", quality=JPEG_QUALITY, optimize=True)}
# crop: JPEG, centered square 128x128 (small sources may be upscaled)
c = ImageOps.fit(flat, (CROP_SIZE, CROP_SIZE), Image.LANCZOS, centering=(0.5, 0.5))
result["crop"] = {"content_type": "image/jpeg", **save(c, out / "crop.jpg", "JPEG", quality=JPEG_QUALITY, optimize=True)}
# optimized: WebP, fit 1280x1280, no upscale, keeps alpha, lossy q=80, no EXIF/ICC
o = base if base.mode in ("RGB", "RGBA") else (base.convert("RGBA") if "A" in base.getbands() or base.mode == "P" else base.convert("RGB"))
size = fit_box(*o.size, OPT_BOX)
if size != o.size:
o = o.resize(size, Image.LANCZOS)
result["optimized"] = {"content_type": "image/webp", **save(o, out / "optimized.webp", "WEBP", quality=WEBP_QUALITY, method=4)}
return result
def main() -> int:
mem_mb, cpu_s = int(os.getenv("IMG_MEMORY_MB", "1024")), int(os.getenv("IMG_CPU_SECONDS", "60"))
resource.setrlimit(resource.RLIMIT_AS, (mem_mb * 1024 * 1024, mem_mb * 1024 * 1024))
resource.setrlimit(resource.RLIMIT_CPU, (cpu_s, cpu_s + 5))
Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
try:
print(json.dumps(process(Path(sys.argv[1]), Path(sys.argv[2]))))
return 0
except OverflowError:
return EXIT_TOO_LARGE
except Image.DecompressionBombError:
return EXIT_TOO_LARGE
except MemoryError:
return EXIT_OOM
except (ValueError, OSError, SyntaxError, Image.UnidentifiedImageError):
return EXIT_INVALID
if __name__ == "__main__":
sys.exit(main())
+96
View File
@@ -0,0 +1,96 @@
"""Shared constants and helpers for the API, the worker and the dispatcher (lab 5)."""
from __future__ import annotations
import json
import os
import random
import uuid
from datetime import datetime, timezone
import boto3
from botocore.config import Config as BotoConfig
from opentelemetry import trace
from opentelemetry.propagate import inject
KAFKA_BOOTSTRAP = os.getenv("KAFKA_BOOTSTRAP_SERVERS", "kafka:9092")
TLS_CA_FILE = os.getenv("TLS_CA_FILE", "/run/pki/ca.crt")
def kafka_ssl() -> dict:
"""Lab 7: mTLS to the broker. The certificate CN is the Kafka principal (dispatcher = producer, worker = consumer); ACLs decide the rights."""
return {"security.protocol": "SSL", "ssl.ca.location": TLS_CA_FILE,
"ssl.certificate.location": os.getenv("TLS_CERT_FILE", "/run/pki/tls.crt"), "ssl.key.location": os.getenv("TLS_KEY_FILE", "/run/pki/tls.key"),
"ssl.endpoint.identification.algorithm": "https"}
JOBS_TOPIC = os.getenv("JOBS_TOPIC", "attachment-jobs")
PIPELINE_VERSION = 1
JOB_TYPE = "attachment.process.v1"
JOB_MAX_ATTEMPTS = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
JOB_TIMEOUT_SECONDS = int(os.getenv("JOB_TIMEOUT_SECONDS", "60"))
LEASE_GRACE_SECONDS = int(os.getenv("LEASE_GRACE_SECONDS", "15"))
LEASE_SECONDS = JOB_TIMEOUT_SECONDS + LEASE_GRACE_SECONDS # lease > hard job timeout: a live worker never loses it
BACKOFF_BASE_SECONDS = float(os.getenv("JOB_BACKOFF_BASE_SECONDS", "2"))
BACKOFF_CAP_SECONDS = float(os.getenv("JOB_BACKOFF_CAP_SECONDS", "60"))
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "https://s3:9000")
S3_REGION = os.getenv("S3_REGION", "us-east-1")
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
STAGING_PREFIX = "staging/"
FINAL_PREFIX = "attachments/"
VARIANT_ORDER = ("thumbnail", "crop", "optimized")
def final_key(attachment_id, pipeline_version: int, name: str) -> str:
"""Deterministic key: the effect key (attachment_id, pipeline_version, variant) maps 1:1 to an S3 object."""
return f"{FINAL_PREFIX}{attachment_id}/v{pipeline_version}/{name}"
def make_s3():
return boto3.client(
"s3", endpoint_url=S3_ENDPOINT, region_name=S3_REGION, verify=TLS_CA_FILE,
aws_access_key_id=os.getenv("S3_ACCESS_KEY_ID", ""), aws_secret_access_key=os.getenv("S3_SECRET_ACCESS_KEY", ""),
config=BotoConfig(signature_version="s3v4", s3={"addressing_style": "path"}, connect_timeout=2, read_timeout=20,
retries={"max_attempts": 2, "mode": "standard"},
request_checksum_calculation="when_required", response_checksum_validation="when_required"))
def backoff_seconds(attempt: int) -> float:
"""Exponential backoff with 'equal jitter': delay in [d/2, d], d = min(cap, base * 2^(attempt-1))."""
d = min(BACKOFF_CAP_SECONDS, BACKOFF_BASE_SECONDS * (2 ** max(0, attempt - 1)))
return random.uniform(d / 2, d)
def iso_now() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
def add_event(conn, job_id, event: str, detail: str | None = None) -> None:
conn.execute("INSERT INTO job_events(job_id,event,detail) VALUES (%s,%s,%s)", (job_id, event, detail))
def enqueue(conn, job_id, attachment_id, pipeline_version: int, attempt: int, delay_seconds: float = 0.0) -> None:
"""Record the intent to publish a job message in the SAME transaction as the state change (transactional outbox).
The message carries only IDs (jobs.schema.json): no bytes, no credentials, no URLs.
Lab 6: the W3C trace context of the CURRENT span is stored in the payload (traceparent/tracestate), so the causal
link survives the outbox -> dispatcher -> Kafka -> worker hops (and the retry loop: worker -> enqueue -> ...).
"""
payload = {"schema_version": 1, "job_id": str(job_id), "type": JOB_TYPE, "attachment_id": str(attachment_id),
"pipeline_version": pipeline_version, "attempt": attempt, "created_at": iso_now()}
with trace.get_tracer("messenger").start_as_current_span(
"outbox.enqueue", attributes={"messaging.system": "kafka", "messaging.destination.name": JOBS_TOPIC, "job.attempt": attempt}):
inject(payload) # adds "traceparent" (+ "tracestate" when present): carrier = the JSON payload itself
conn.execute(
"INSERT INTO outbox(job_id,topic,msg_key,payload,available_at) VALUES (%s,%s,%s,%s::jsonb, now() + make_interval(secs => %s))",
(job_id, JOBS_TOPIC, str(attachment_id), json.dumps(payload), delay_seconds))
def new_job_id() -> uuid.UUID:
return uuid.uuid4()
def fail_job(conn, job_id, att_id, code: str, attempt: int) -> None:
conn.execute("UPDATE attachment_jobs SET status='failed', error_code=%s, lease_until=NULL, updated_at=now() WHERE job_id=%s", (code, job_id))
conn.execute("UPDATE attachments SET status='failed', error_code=%s, updated_at=now() WHERE id=%s", (code, att_id))
add_event(conn, job_id, "failed", code)
+869
View File
@@ -0,0 +1,869 @@
"""Lab 7 REST API: lab 6 business API + TLS/mTLS, OpenBao secrets, Argon2id (rehash), shared login rate limit, request size limits."""
from __future__ import annotations
import asyncio
import anyio
import anyio.to_thread
import base64
import hashlib
import json
import logging
import os
import re
import secrets
import socket
import tempfile
import time
import unicodedata
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
from urllib.parse import quote
import psycopg
from psycopg_pool import ConnectionPool, PoolTimeout
import anyio
import boto3
import redis
from botocore.config import Config as BotoConfig
from botocore.exceptions import BotoCoreError, ClientError
from PIL import Image
from redis.exceptions import RedisError
from argon2 import PasswordHasher, Type
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response, StreamingResponse
from starlette.concurrency import iterate_in_threadpool, run_in_threadpool
from starlette.requests import ClientDisconnect
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from opentelemetry import metrics, trace
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from . import jobs, telemetry, vault
# Lab 7: secrets (PGPASSWORD, Redis password, S3 keys) come from OpenBao BEFORE any client below is created.
vault.load_into_env("api")
TLS_CA_FILE = os.getenv("TLS_CA_FILE", "/run/pki/ca.crt")
# Lab 6: JSON logs on stdout + OTLP (traces, metrics, logs) to the Collector. psycopg/botocore spans are automatic.
telemetry.init("messenger-api", instrument=("psycopg", "botocore"))
log = logging.getLogger("messenger")
DATABASE_URL = os.getenv("DATABASE_URL", "")
INSTANCE_ID = os.getenv("INSTANCE_ID") or socket.gethostname()
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
if SESSION_TTL_SECONDS < 1:
raise RuntimeError("SESSION_TTL_SECONDS must be positive")
# Redis uses its connection pool; session keys contain only a hash of the opaque token.
# Lab 7: TLS with server verification (CA + hostname) and a dedicated least-privilege ACL user (keys session:* and rl:* only).
session_store = redis.Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379, db=0, username="api", password=os.environ["REDIS_PASSWORD"], ssl=True,
ssl_ca_certs=TLS_CA_FILE, ssl_cert_reqs="required", ssl_check_hostname=True,
decode_responses=True, socket_connect_timeout=3, socket_timeout=3, health_check_interval=30)
DB_POOL_MIN_SIZE = int(os.getenv("DB_POOL_MIN_SIZE", "1"))
DB_POOL_MAX_SIZE = int(os.getenv("DB_POOL_MAX_SIZE", "10"))
DB_POOL_TIMEOUT_SECONDS = float(os.getenv("DB_POOL_TIMEOUT_SECONDS", "5"))
if DB_POOL_MIN_SIZE < 1 or DB_POOL_MAX_SIZE < DB_POOL_MIN_SIZE:
raise RuntimeError("Invalid PostgreSQL pool size configuration")
# Every pooled connection gets bounded connect/query/idle-transaction timeouts.
db_pool = ConnectionPool(
conninfo=DATABASE_URL,
min_size=DB_POOL_MIN_SIZE,
max_size=DB_POOL_MAX_SIZE,
timeout=DB_POOL_TIMEOUT_SECONDS,
kwargs={
"connect_timeout": 5,
"options": "-c statement_timeout=5000 -c idle_in_transaction_session_timeout=10000",
},
open=False,
name="messenger-postgres",
)
# ---- Lab 4: S3 / attachment limits (names follow .env.example of the lab) ----
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "https://s3:9000")
S3_REGION = os.getenv("S3_REGION", "us-east-1")
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
S3_ACCESS_KEY_ID = os.getenv("S3_ACCESS_KEY_ID", "")
S3_SECRET_ACCESS_KEY = os.getenv("S3_SECRET_ACCESS_KEY", "")
S3_KEY_PREFIX = "attachments/"
STAGING_PREFIX = jobs.STAGING_PREFIX # lab5: durable staging (private S3 prefix) for bytes accepted but not yet processed
MAX_UPLOAD_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", "10485760"))
MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
UPLOAD_IDLE_TIMEOUT_SECONDS = float(os.getenv("UPLOAD_IDLE_TIMEOUT_SECONDS", "10"))
UPLOAD_TOTAL_TIMEOUT_SECONDS = float(os.getenv("UPLOAD_TOTAL_TIMEOUT_SECONDS", "60"))
IMAGE_DECODE_CONCURRENCY = int(os.getenv("IMAGE_DECODE_CONCURRENCY", "1"))
SPOOL_MEMORY_BYTES = 1024 * 1024 # larger bodies roll over to an anonymous temp file, never to RAM
CHUNK_BYTES = 64 * 1024
# Pillow's own bomb guard is a second line of defence behind the explicit check below.
Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
# Credentials are the restricted application user created by s3_init, never the MinIO root user.
_s3_common = dict(endpoint_url=S3_ENDPOINT, region_name=S3_REGION, aws_access_key_id=S3_ACCESS_KEY_ID, aws_secret_access_key=S3_SECRET_ACCESS_KEY, verify=TLS_CA_FILE)
s3 = boto3.client("s3", **_s3_common, config=BotoConfig(
signature_version="s3v4", s3={"addressing_style": "path"}, connect_timeout=2, read_timeout=20,
retries={"max_attempts": 2, "mode": "standard"}, max_pool_connections=32,
request_checksum_calculation="when_required", response_checksum_validation="when_required"))
# Readiness probe client: one attempt and tight timeouts so HAProxy's 2 s check never hangs on it.
s3_probe = boto3.client("s3", **_s3_common, config=BotoConfig(
signature_version="s3v4", s3={"addressing_style": "path"}, connect_timeout=1, read_timeout=1,
retries={"max_attempts": 1}, request_checksum_calculation="when_required", response_checksum_validation="when_required"))
decode_limiter = anyio.CapacityLimiter(IMAGE_DECODE_CONCURRENCY)
IMAGE_TYPES = {"PNG": "image/png", "JPEG": "image/jpeg"}
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
# Lab 7: Argon2id with explicit parameters (OWASP minimum 19 MiB, t=2, p=1); parameters are stored inside every hash.
ARGON2_MEMORY_KIB = int(os.getenv("ARGON2_MEMORY_KIB", "19456"))
ARGON2_ITERATIONS = int(os.getenv("ARGON2_ITERATIONS", "2"))
ARGON2_PARALLELISM = int(os.getenv("ARGON2_PARALLELISM", "1"))
PASSWORDS = PasswordHasher(time_cost=ARGON2_ITERATIONS, memory_cost=ARGON2_MEMORY_KIB, parallelism=ARGON2_PARALLELISM, type=Type.ID)
DUMMY_HASH = PASSWORDS.hash("dummy-password-for-timing-equalisation") # verified for unknown users: same cost as a real login
# Login DoS budget: at most N concurrent Argon2 operations per replica (N x ~19 MiB RAM, N cores); extra requests queue or hit the rate limit.
HASH_LIMITER = anyio.CapacityLimiter(int(os.getenv("ARGON2_CONCURRENCY", "2")))
MAX_JSON_BYTES = int(os.getenv("MAX_JSON_BYTES", "65536"))
# Shared (Redis) fixed-window limits: identical counters for every API replica.
LOGIN_IP_LIMIT = int(os.getenv("LOGIN_IP_LIMIT", "30")) # attempts per source IP per window
LOGIN_USER_FAIL_LIMIT = int(os.getenv("LOGIN_USER_FAIL_LIMIT", "10")) # failed attempts per username per window
REGISTER_IP_LIMIT = int(os.getenv("REGISTER_IP_LIMIT", "30"))
RATE_WINDOW_SECONDS = int(os.getenv("RATE_WINDOW_SECONDS", "60"))
class ApiError(Exception):
def __init__(self, status: int, code: str, message: str, headers: dict[str, str] | None = None):
self.status, self.code, self.message, self.headers = status, code, message, headers or {}
def fail(status: int, code: str, message: str, headers: dict[str, str] | None = None):
raise ApiError(status, code, message, headers)
class StrictModel(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
class RegisterBody(StrictModel):
username: str
display_name: str
password: str
class ChatBody(StrictModel):
title: str
member_ids: list[str] = Field(min_length=1, max_length=100)
class MessageBody(StrictModel):
text: str
attachment_ids: list[str] = Field(default_factory=list, max_length=10)
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
# ---- Lab 6: HTTP metrics (names/units: REPORT.md). Labels are LOW cardinality: method, route TEMPLATE, status class. ----
HTTP_DURATION = telemetry.meter().create_histogram(
"http.server.request.duration", unit="s", description="Server-side duration of business HTTP requests (health excluded)",
explicit_bucket_boundaries_advisory=[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60])
KNOWN_METHODS = {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}
def observe_http(request: Request, status: int, started: float) -> None:
if request.url.path.startswith("/health/"):
return # error ratio denominator = business requests, health probes are excluded
route = getattr(request.scope.get("route"), "path", None) or "unmatched" # "/api/v1/chats/{chat_id}/messages", never a real UUID
HTTP_DURATION.record(time.perf_counter() - started, {
"http.request.method": request.method if request.method in KNOWN_METHODS else "OTHER",
"http.route": route, "http.response.status_class": f"{status // 100}xx"})
def _pool_gauge(field: str):
def callback(_options):
stats = db_pool.get_stats()
value = stats["pool_size"] - stats["pool_available"] if field == "used" else stats[field]
yield metrics.Observation(value, {"pool.name": "messenger-postgres"})
return callback
for _name, _field, _desc in (("messenger.db.pool.used", "used", "Connections checked out of the pool"),
("messenger.db.pool.waiting", "requests_waiting", "Requests waiting for a free pooled connection")):
telemetry.meter().create_observable_gauge(_name, callbacks=[_pool_gauge(_field)], unit="{connection}", description=_desc)
telemetry.register_process_metrics()
@app.middleware("http")
async def request_id_middleware(request: Request, call_next):
request.state.request_id = uuid.uuid4().hex
started = time.perf_counter()
# X-Request-Id <-> trace: the id is stored on the server span; logs carry both request_id and trace_id.
trace.get_current_span().set_attribute("messenger.request_id", request.state.request_id)
try:
response = await call_next(request)
except Exception as exc:
telemetry.log_event(log, logging.ERROR, "unhandled_exception", "Unhandled API exception", request_id=request.state.request_id, reason=type(exc).__name__)
response = JSONResponse(status_code=500, content={"error": {"code": "internal_error", "message": "Internal server error", "request_id": request.state.request_id}})
response.headers["X-Request-Id"] = request.state.request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
observe_http(request, response.status_code, started)
return response
# Added LAST => outermost middleware: the server span is active inside request_id_middleware. No metrics from the instrumentor:
# our own histogram above is the only HTTP metric (no duplicate instruments). Health probes produce no spans.
FastAPIInstrumentor.instrument_app(app, excluded_urls="/health/(live|ready)", meter_provider=metrics.NoOpMeterProvider())
def error_response(status: int, code: str, message: str, request_id: str, headers: dict[str, str] | None = None):
return JSONResponse(status_code=status, content={"error": {"code": code, "message": message, "request_id": request_id}}, headers=headers or {})
@app.exception_handler(ApiError)
async def api_error_handler(request: Request, exc: ApiError):
return error_response(exc.status, exc.code, exc.message, request.state.request_id, exc.headers)
@app.exception_handler(PoolTimeout)
async def database_pool_timeout_handler(request: Request, exc: PoolTimeout):
telemetry.log_event(log, logging.WARNING, "db_pool_timeout", "Database connection pool timed out", request_id=request.state.request_id)
return error_response(503, "unavailable", "Required storage is unavailable", request.state.request_id)
@app.exception_handler(psycopg.Error)
async def database_error_handler(request: Request, exc: psycopg.Error):
telemetry.log_event(log, logging.WARNING, "db_error", "Database operation failed", request_id=request.state.request_id, reason=type(exc).__name__)
return error_response(503, "unavailable", "Required storage is unavailable", request.state.request_id)
@app.exception_handler(RedisError)
async def redis_error_handler(request: Request, exc: RedisError):
telemetry.log_event(log, logging.WARNING, "session_store_error", "Session store operation failed", request_id=request.state.request_id)
return error_response(503, "unavailable", "Required storage is unavailable", request.state.request_id)
@app.exception_handler(BotoCoreError)
async def s3_core_error_handler(request: Request, exc: BotoCoreError):
telemetry.log_event(log, logging.WARNING, "s3_error", "Object storage failure", request_id=request.state.request_id, reason=type(exc).__name__)
return error_response(503, "unavailable", "Required storage is unavailable", request.state.request_id)
@app.exception_handler(ClientError)
async def s3_client_error_handler(request: Request, exc: ClientError):
telemetry.log_event(log, logging.WARNING, "s3_error", "Object storage error", request_id=request.state.request_id, reason=str(exc.response.get("Error", {}).get("Code")))
return error_response(503, "unavailable", "Required storage is unavailable", request.state.request_id)
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
return error_response(400, "invalid_request", "Invalid request", request.state.request_id)
@app.exception_handler(StarletteHTTPException)
async def http_error_handler(request: Request, exc: StarletteHTTPException):
status = exc.status_code
code = "not_found" if status == 404 else "invalid_request"
message = "Object not found" if status == 404 else "Invalid request"
headers = dict(exc.headers or {})
return error_response(status, code, message, request.state.request_id, headers)
def db():
"""Borrow a bounded pooled connection; context exit commits/rolls back and returns it."""
return db_pool.connection(timeout=DB_POOL_TIMEOUT_SECONDS)
@app.on_event("startup")
def startup():
# Migrations run once in the dedicated `migrate` service before API replicas.
db_pool.open(wait=False)
last_error = None
for _ in range(30):
try:
with db() as conn:
conn.execute("SELECT 1")
conn.execute("SELECT 1 FROM idempotency_records LIMIT 0")
conn.execute("SELECT 1 FROM outbox LIMIT 0")
session_store.ping()
s3.head_object(Bucket=S3_BUCKET, Key=S3_KEY_PREFIX + ".ready")
telemetry.log_event(log, logging.INFO, "api_ready", f"PostgreSQL, Redis and S3 bucket are ready; instance={INSTANCE_ID}")
return
except Exception as exc:
last_error = exc
time.sleep(1)
raise RuntimeError("PostgreSQL schema, Redis or S3 bucket unavailable during startup") from last_error
@app.on_event("shutdown")
def shutdown():
session_store.close()
db_pool.close()
def now_utc() -> datetime:
return datetime.now(timezone.utc)
def iso(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
def user_dict(row: dict[str, Any]) -> dict[str, Any]:
return {"id": str(row["id"]), "username": row["username"], "display_name": row["display_name"], "created_at": iso(row["created_at"])}
def chat_dict(row: dict[str, Any], member_ids: list[str]) -> dict[str, Any]:
return {"id": str(row["id"]), "title": row["title"], "member_ids": member_ids, "created_at": iso(row["created_at"])}
def message_dict(row: dict[str, Any], attachment_ids: list[str] | None = None) -> dict[str, Any]:
return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), "text": row["text"], "created_at": iso(row["created_at"]), "attachment_ids": attachment_ids or []}
def validate_unicode(value: str, label: str) -> str:
"""Reject unpaired UTF-16 surrogates before sending text to PostgreSQL/KDF."""
try:
value.encode("utf-8")
except UnicodeEncodeError:
fail(400, "invalid_request", "Invalid Unicode in " + label)
return value
def parse_uuid(value: str, label: str = "UUID") -> uuid.UUID:
try:
# Keep the canonical UUID representation used by the Lab 1 API.
if not isinstance(value, str) or len(value) != 36:
raise ValueError("non-canonical UUID")
parsed = uuid.UUID(value)
if str(parsed) != value:
raise ValueError("non-canonical UUID")
return parsed
except (ValueError, TypeError, AttributeError):
fail(400, "invalid_request", "Invalid " + label)
def validate_body_type(request: Request):
content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
if content_type != "application/json":
fail(415, "unsupported_media_type", "Content-Type must be application/json")
async def parse_body(request: Request, model):
validate_body_type(request)
try:
raw = await request.body()
if len(raw) > MAX_JSON_BYTES:
fail(413, "payload_too_large", "JSON body is too large")
data = json.loads(raw.decode("utf-8"))
return model.model_validate(data)
except (UnicodeDecodeError, json.JSONDecodeError, ValidationError, TypeError):
fail(400, "invalid_request", "Invalid JSON request body")
def challenge(scheme: str) -> dict[str, str]:
if scheme == "Basic":
return {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
return {"WWW-Authenticate": 'Bearer realm="messenger"'}
def current_user(request: Request) -> dict[str, Any]:
auth = request.headers.get("authorization", "")
if not auth.startswith("Bearer ") or not auth[7:].strip():
fail(401, "unauthorized", "Valid Bearer session required", challenge("Bearer"))
token_hash = hashlib.sha256(auth[7:].strip().encode("utf-8")).hexdigest()
session_json = session_store.get("session:" + token_hash)
if session_json is None:
fail(401, "unauthorized", "Valid Bearer session required", challenge("Bearer"))
try:
session = json.loads(session_json)
user_id = uuid.UUID(session["user_id"])
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
except (ValueError, KeyError, TypeError, json.JSONDecodeError):
# Corrupt session data is invalidated instead of trusted.
session_store.delete("session:" + token_hash)
fail(401, "unauthorized", "Valid Bearer session required", challenge("Bearer"))
if expires_at <= now_utc():
session_store.delete("session:" + token_hash)
fail(401, "unauthorized", "Valid Bearer session required", challenge("Bearer"))
with db() as conn:
row = conn.execute("SELECT id,username,display_name,created_at FROM users WHERE id=%s", (user_id,)).fetchone()
if row is None:
session_store.delete("session:" + token_hash)
fail(401, "unauthorized", "Valid Bearer session required", challenge("Bearer"))
return {"id": row[0], "username": row[1], "display_name": row[2], "created_at": row[3], "expires_at": expires_at, "user": {"id": str(row[0]), "username": row[1], "display_name": row[2], "created_at": iso(row[3])}, "token_hash": token_hash}
def ensure_member(actor_id: uuid.UUID, chat_id: uuid.UUID):
with db() as conn:
row = conn.execute("SELECT 1 FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE c.id=%s AND m.user_id=%s", (chat_id, actor_id)).fetchone()
if row is None:
fail(404, "not_found", "Object not found")
def parse_page_args(limit: int | None, cursor: str | None, resource: str):
actual_limit = 50 if limit is None else limit
if isinstance(actual_limit, bool) or actual_limit < 1 or actual_limit > 100:
fail(400, "invalid_request", "limit must be an integer from 1 to 100")
after = None
if cursor is not None:
if not cursor:
fail(400, "invalid_request", "Invalid cursor")
try:
decoded = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)).decode("utf-8")
obj = json.loads(decoded)
if obj.get("resource") != resource:
fail(400, "invalid_request", "Cursor belongs to another resource")
after = (datetime.fromisoformat(obj["created_at"].replace("Z", "+00:00")), uuid.UUID(obj["id"]))
except ApiError:
raise
except Exception:
fail(400, "invalid_request", "Invalid cursor")
return actual_limit, after
def make_cursor(resource: str, created_at: datetime, item_id: uuid.UUID) -> str:
raw = json.dumps({"resource": resource, "created_at": iso(created_at), "id": str(item_id)}, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
def json_rows(cursor, query: str, params=()):
with db() as conn:
cur = conn.execute(query, params)
names = [d.name for d in cur.description]
return [dict(zip(names, row)) for row in cur.fetchall()]
@app.get("/health/live")
def live():
return {"status": "ok"}
@app.get("/health/ready")
def ready():
try:
with db() as conn:
conn.execute("SELECT 1")
session_store.ping()
s3_probe.head_object(Bucket=S3_BUCKET, Key=S3_KEY_PREFIX + ".ready") # S3 is critical: uploads/downloads are part of the mandatory path
return {"status": "ok"}
except (psycopg.Error, PoolTimeout, RedisError, BotoCoreError, ClientError):
fail(503, "unavailable", "Required storage is unavailable")
def client_ip(request: Request) -> str:
"""The LB (the only allowed mTLS client) overwrites X-Real-IP with the TCP source address; the client cannot forge it."""
return request.headers.get("x-real-ip", "unknown")[:45]
def hit(key: str, window: int) -> tuple[int, int]:
"""Increment a shared Redis counter; returns (count, seconds_left). INCR + EXPIRE NX in one MULTI/EXEC."""
pipe = session_store.pipeline(transaction=True)
pipe.incr(key); pipe.expire(key, window, nx=True); pipe.ttl(key)
count, _, ttl = pipe.execute()
return int(count), max(int(ttl), 1)
def too_many(retry_after: int):
fail(429, "rate_limited", "Too many requests", {"Retry-After": str(retry_after)})
@app.post("/api/v1/users", status_code=201)
async def register(request: Request):
body = await parse_body(request, RegisterBody)
if not USERNAME_RE.fullmatch(body.username):
fail(400, "invalid_request", "Invalid username")
validate_unicode(body.display_name, "display_name")
validate_unicode(body.password, "password")
if not body.display_name.strip() or len(body.display_name) > 100:
fail(400, "invalid_request", "Invalid display_name")
if not 12 <= len(body.password) <= 128:
fail(400, "invalid_request", "Password must contain 12 to 128 Unicode code points")
count, ttl = hit("rl:reg:ip:" + client_ip(request), RATE_WINDOW_SECONDS)
if count > REGISTER_IP_LIMIT:
too_many(ttl)
user_id = uuid.uuid4()
password_hash = await anyio.to_thread.run_sync(PASSWORDS.hash, body.password, limiter=HASH_LIMITER)
try:
with db() as conn:
row = conn.execute("INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING id,username,display_name,created_at", (user_id, body.username, body.display_name, password_hash)).fetchone()
except psycopg.errors.UniqueViolation:
fail(409, "conflict", "Username already exists")
return user_dict(dict(zip(("id", "username", "display_name", "created_at"), row)))
@app.get("/api/v1/users/me")
def me(request: Request):
return current_user(request)["user"]
@app.post("/api/v1/auth/sessions", status_code=201)
async def create_session(request: Request):
if await request.body():
fail(400, "invalid_request", "Session creation does not accept a request body")
auth = request.headers.get("authorization", "")
if not auth[:6].lower() == "basic ":
fail(401, "unauthorized", "Valid Basic credentials required", challenge("Basic"))
try:
decoded = base64.b64decode(auth[6:], validate=True).decode("utf-8")
username, password = decoded.split(":", 1)
except Exception:
fail(401, "unauthorized", "Invalid credentials", challenge("Basic"))
try:
validate_unicode(password, "password")
except ApiError:
fail(401, "unauthorized", "Invalid credentials", challenge("Basic"))
if not password or len(password) < 12 or len(password) > 128:
fail(401, "unauthorized", "Invalid credentials", challenge("Basic"))
# Lab 7: shared rate limit BEFORE any expensive work. Per-IP: every attempt; per-username: failed attempts only.
ip_count, ip_ttl = hit("rl:login:ip:" + client_ip(request), RATE_WINDOW_SECONDS)
if ip_count > LOGIN_IP_LIMIT:
too_many(ip_ttl)
user_key = "rl:login:user:" + hashlib.sha256(username.encode("utf-8")).hexdigest()[:32] # no raw username in Redis keys
failed = session_store.get(user_key)
if failed is not None and int(failed) >= LOGIN_USER_FAIL_LIMIT:
too_many(max(session_store.ttl(user_key), 1))
with db() as conn:
row = conn.execute("SELECT id,username,display_name,password_hash,created_at FROM users WHERE username=%s", (username,)).fetchone()
stored_hash = row[3] if row is not None else DUMMY_HASH # unknown user costs the same Argon2 time: no enumeration by timing
try:
await anyio.to_thread.run_sync(PASSWORDS.verify, stored_hash, password, limiter=HASH_LIMITER)
verified = row is not None
except (VerifyMismatchError, VerificationError, InvalidHashError):
verified = False
if not verified:
count, ttl = hit(user_key, RATE_WINDOW_SECONDS)
if count > LOGIN_USER_FAIL_LIMIT:
too_many(ttl)
fail(401, "unauthorized", "Invalid credentials", challenge("Basic"))
session_store.delete(user_key)
# Lab 7: transparent upgrade of old hashes (lab 6 used library defaults m=64 MiB,t=3,p=4) to the current parameters.
if PASSWORDS.check_needs_rehash(row[3]):
new_hash = await anyio.to_thread.run_sync(PASSWORDS.hash, password, limiter=HASH_LIMITER)
with db() as conn:
conn.execute("UPDATE users SET password_hash=%s WHERE id=%s AND password_hash=%s", (new_hash, row[0], row[3]))
token = secrets.token_urlsafe(32)
token_hash = hashlib.sha256(token.encode()).hexdigest()
expires_at = now_utc() + timedelta(seconds=SESSION_TTL_SECONDS)
session_json = json.dumps({"user_id": str(row[0]), "expires_at": iso(expires_at)}, separators=(",", ":"))
# Redis TTL enforces expiry; AOF + named volume make active sessions survive stack restarts.
session_store.setex("session:" + token_hash, SESSION_TTL_SECONDS, session_json)
user = user_dict({"id": row[0], "username": row[1], "display_name": row[2], "created_at": row[4]})
return {"token": token, "token_type": "Bearer", "expires_at": iso(expires_at), "user": user}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def revoke_session(request: Request):
actor = current_user(request)
session_store.delete("session:" + actor["token_hash"])
return Response(status_code=204)
@app.post("/api/v1/chats", status_code=201)
async def create_chat(request: Request):
actor = current_user(request)
body = await parse_body(request, ChatBody)
validate_unicode(body.title, "title")
if not body.title.strip() or len(body.title) > 100:
fail(400, "invalid_request", "Invalid title")
ids = [parse_uuid(value, "member UUID") for value in body.member_ids]
if len(ids) != len(set(ids)) or actor["id"] not in ids:
fail(400, "invalid_request", "Members must be unique and include the caller")
chat_id = uuid.uuid4()
try:
with db() as conn:
existing = conn.execute("SELECT id FROM users WHERE id = ANY(%s)", (ids,)).fetchall()
if len(existing) != len(ids):
fail(400, "invalid_request", "Unknown chat member")
row = conn.execute("INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING id,title,created_at", (chat_id, body.title)).fetchone()
# psycopg 3: executemany exists on cursors, not on Connection (fix of a latent lab3 bug)
with conn.cursor() as cur:
cur.executemany("INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,%s)", [(chat_id, uid, position) for position, uid in enumerate(ids)])
except psycopg.errors.ForeignKeyViolation:
fail(400, "invalid_request", "Unknown chat member")
return chat_dict({"id": row[0], "title": row[1], "created_at": row[2]}, [str(x) for x in ids])
@app.get("/api/v1/chats")
def list_chats(request: Request, limit: int | None = None, cursor: str | None = None):
actor = current_user(request)
chat_list_resource = "chats:" + str(actor["id"])
actual_limit, after = parse_page_args(limit, cursor, chat_list_resource)
params: list[Any] = [actor["id"]]
where = "m.user_id=%s"
if after:
where += " AND (c.created_at,c.id)>(%s,%s)"
params.extend(after)
params.append(actual_limit + 1)
rows = json_rows(None, f"SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE {where} ORDER BY c.created_at,c.id LIMIT %s", tuple(params))
more = len(rows) > actual_limit
rows = rows[:actual_limit]
items = []
for row in rows:
members = json_rows(None, "SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY position,user_id", (row["id"],))
items.append(chat_dict(row, [str(m["user_id"]) for m in members]))
next_cursor = make_cursor(chat_list_resource, rows[-1]["created_at"], rows[-1]["id"]) if more and rows else None
return {"items": items, "next_cursor": next_cursor}
@app.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: str, request: Request):
actor = current_user(request)
parsed = parse_uuid(chat_id, "chat UUID")
ensure_member(actor["id"], parsed)
rows = json_rows(None, "SELECT id,title,created_at FROM chats WHERE id=%s", (parsed,))
members = json_rows(None, "SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY position,user_id", (parsed,))
return chat_dict(rows[0], [str(m["user_id"]) for m in members])
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def create_message(chat_id: str, request: Request):
actor = current_user(request)
parsed_chat = parse_uuid(chat_id, "chat UUID")
ensure_member(actor["id"], parsed_chat)
body = await parse_body(request, MessageBody)
validate_unicode(body.text, "text")
attachment_ids = [parse_uuid(value, "attachment UUID") for value in body.attachment_ids]
if len(attachment_ids) != len(set(attachment_ids)):
fail(400, "invalid_request", "attachment_ids must be unique")
if len(body.text) > 4000 or (not body.text.strip() and not attachment_ids):
fail(400, "invalid_request", "Message needs 1 to 4000 non-whitespace code points of text or at least one attachment")
key = request.headers.get("Idempotency-Key", "")
if not IDEMPOTENCY_KEY_RE.fullmatch(key):
fail(400, "invalid_request", "Idempotency-Key must contain 1 to 128 ASCII letters, digits, '.', '_', ':', or '-'")
# Hash semantic JSON rather than raw bytes, so insignificant JSON formatting does not matter.
# attachment_ids is part of the hash only when non-empty: absent == [] and lab3 records stay valid.
canonical = {"text": body.text}
if attachment_ids:
canonical["attachment_ids"] = [str(x) for x in attachment_ids]
canonical_body = json.dumps(canonical, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
request_hash = hashlib.sha256(canonical_body.encode("utf-8")).hexdigest()
scope = f"{actor['id']}|POST|/api/v1/chats/{parsed_chat}/messages|{key}"
# The advisory transaction lock serializes the same key across every API replica.
# Message and idempotency result are committed atomically in the same PostgreSQL transaction.
with db() as conn:
conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (scope,))
existing = conn.execute(
"SELECT request_hash, response_body FROM idempotency_records "
"WHERE user_id=%s AND chat_id=%s AND idempotency_key=%s AND created_at >= now() - interval '24 hours'",
(actor["id"], parsed_chat, key),
).fetchone()
if existing is not None:
if existing[0] != request_hash:
fail(409, "conflict", "Idempotency-Key was already used with a different request body")
replay = dict(existing[1])
replay.setdefault("attachment_ids", [])
return JSONResponse(status_code=201, content=replay)
# Keys are guaranteed for 24 hours; expired records may be replaced by a new attempt.
conn.execute(
"DELETE FROM idempotency_records WHERE user_id=%s AND chat_id=%s AND idempotency_key=%s AND created_at < now() - interval '24 hours'",
(actor["id"], parsed_chat, key),
)
if attachment_ids:
# Foreign, unknown and other-chat attachments are indistinguishable: all -> 404.
found = conn.execute("SELECT count(*) FROM attachments WHERE id = ANY(%s) AND chat_id=%s", (attachment_ids, parsed_chat)).fetchone()[0]
if found != len(attachment_ids):
fail(404, "not_found", "Object not found")
# lab5: queued/processing attachments may be attached, failed ones may not
if conn.execute("SELECT 1 FROM attachments WHERE id = ANY(%s) AND status='failed' LIMIT 1", (attachment_ids,)).fetchone():
fail(409, "conflict", "Attachment processing failed")
row = conn.execute(
"INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) "
"RETURNING id,chat_id,sender_id,text,created_at",
(uuid.uuid4(), parsed_chat, actor["id"], body.text),
).fetchone()
result = message_dict(dict(zip(("id", "chat_id", "sender_id", "text", "created_at"), row)), [str(x) for x in attachment_ids])
if attachment_ids:
with conn.cursor() as cur:
cur.executemany("INSERT INTO message_attachments(message_id,attachment_id,position) VALUES (%s,%s,%s)", [(row[0], aid, i) for i, aid in enumerate(attachment_ids)])
conn.execute(
"INSERT INTO idempotency_records(user_id,chat_id,idempotency_key,request_hash,response_body) "
"VALUES (%s,%s,%s,%s,%s::jsonb)",
(actor["id"], parsed_chat, key, request_hash, json.dumps(result, ensure_ascii=False)),
)
return result
@app.get("/api/v1/chats/{chat_id}/messages")
def list_messages(chat_id: str, request: Request, limit: int | None = None, cursor: str | None = None):
actor = current_user(request)
parsed_chat = parse_uuid(chat_id, "chat UUID")
ensure_member(actor["id"], parsed_chat)
actual_limit, after = parse_page_args(limit, cursor, "messages:" + str(parsed_chat))
params: list[Any] = [parsed_chat]
where = "chat_id=%s"
if after:
where += " AND (created_at,id)>(%s,%s)"
params.extend(after)
params.append(actual_limit + 1)
rows = json_rows(None, f"SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE {where} ORDER BY created_at,id LIMIT %s", tuple(params))
more = len(rows) > actual_limit
rows = rows[:actual_limit]
links: dict[Any, list[str]] = {}
if rows:
link_rows = json_rows(None, "SELECT message_id, attachment_id FROM message_attachments WHERE message_id = ANY(%s) ORDER BY message_id, position", ([r["id"] for r in rows],))
for link in link_rows:
links.setdefault(link["message_id"], []).append(str(link["attachment_id"]))
items = [message_dict(row, links.get(row["id"])) for row in rows]
next_cursor = make_cursor("messages:" + str(parsed_chat), rows[-1]["created_at"], rows[-1]["id"]) if more and rows else None
return {"items": items, "next_cursor": next_cursor}
# ======================= Lab 4: attachments =======================
def attachment_dict(row: dict[str, Any], variants: list[dict[str, Any]] | None = None) -> dict[str, Any]:
return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "owner_id": str(row["owner_id"]), "filename": row["filename"],
"content_type": row["content_type"], "size_bytes": row["size_bytes"], "sha256": row["sha256"], "status": row["status"],
"variants": variants or [], "error_code": row["error_code"] if row["status"] == "failed" else None,
"created_at": iso(row["created_at"]), "updated_at": iso(row["updated_at"])}
def validate_filename(values: list[str]) -> str:
"""filename is display-only: it never reaches a path or an S3 key, but dangerous values are still rejected."""
if len(values) != 1:
fail(400, "invalid_request", "Exactly one filename query parameter is required")
name = values[0]
validate_unicode(name, "filename")
if not 1 <= len(name) <= 255 or not name.strip() or name in (".", ".."):
fail(400, "invalid_request", "Invalid filename")
if "/" in name or "\\" in name or any(unicodedata.category(ch) == "Cc" for ch in name):
fail(400, "invalid_request", "Invalid filename")
return name
def sniff_image_type(head: bytes) -> str | None:
if head.startswith(b"\x89PNG\r\n\x1a\n"):
return "image/png"
if head.startswith(b"\xff\xd8\xff"):
return "image/jpeg"
return None
async def read_body_to_spool(request: Request, declared: str):
"""Stream the request body into a bounded spool while hashing; abort as soon as a limit is broken.
RAM per upload stays ~1 MiB: bodies above SPOOL_MEMORY_BYTES roll over to an anonymous (already unlinked) temp file.
"""
spool = tempfile.SpooledTemporaryFile(max_size=SPOOL_MEMORY_BYTES)
digest, total, head = hashlib.sha256(), 0, b""
try:
iterator = request.stream().__aiter__()
with anyio.fail_after(UPLOAD_TOTAL_TIMEOUT_SECONDS):
while True:
try:
chunk = await asyncio.wait_for(iterator.__anext__(), UPLOAD_IDLE_TIMEOUT_SECONDS)
except StopAsyncIteration:
break
if not chunk:
continue
total += len(chunk)
if total > MAX_UPLOAD_BYTES:
fail(413, "payload_too_large", "Attachment exceeds the size limit")
if len(head) < 8:
head += chunk[: 8 - len(head)]
if len(head) >= 8 and sniff_image_type(head) != declared:
fail(415, "unsupported_media_type", "Content does not match the declared image type")
digest.update(chunk)
spool.write(chunk)
except ApiError:
spool.close()
raise
except (TimeoutError, asyncio.TimeoutError):
spool.close()
fail(400, "invalid_request", "Upload timed out")
except BaseException: # ClientDisconnect, cancellation: nothing was written to S3 yet
spool.close()
raise
if total == 0 or sniff_image_type(head) != declared:
spool.close()
fail(415, "unsupported_media_type", "Content is not a supported image")
return spool, total, digest.hexdigest()
def decode_image_checked(spool, declared: str) -> None:
"""Runs in a worker thread: header -> pixel limit -> full decode. Raises ApiError for every user mistake."""
try:
spool.seek(0)
with Image.open(spool) as img:
if IMAGE_TYPES.get(img.format or "") != declared:
fail(415, "unsupported_media_type", "Content does not match the declared image type")
width, height = img.size
if width < 1 or height < 1:
fail(415, "unsupported_media_type", "Corrupt image")
if width * height > MAX_IMAGE_PIXELS: # decided from the header, before any pixel buffer exists
fail(413, "payload_too_large", "Image has too many pixels")
img.load() # full decode detects truncated/corrupt data
except ApiError:
raise
except Image.DecompressionBombError:
fail(413, "payload_too_large", "Image has too many pixels")
except MemoryError:
fail(503, "unavailable", "Temporarily unable to process the image")
except Exception: # Pillow raises OSError/SyntaxError/ValueError/struct.error/... for corrupt input
fail(415, "unsupported_media_type", "Corrupt or unsupported image")
finally:
spool.seek(0)
def s3_put(key: str, spool, size: int, content_type: str) -> None:
spool.seek(0)
s3.put_object(Bucket=S3_BUCKET, Key=key, Body=spool, ContentLength=size, ContentType=content_type)
def s3_delete_quietly(key: str) -> None:
try:
s3.delete_object(Bucket=S3_BUCKET, Key=key)
except Exception:
# The periodic sweeper (scripts/s3_sweep.py) removes it after the grace period.
log.warning("Compensation delete failed; orphan left for sweeper key=%s", key)
async def compensate(key: str) -> None:
with anyio.CancelScope(shield=True):
await run_in_threadpool(s3_delete_quietly, key)
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
async def upload_attachment(chat_id: str, request: Request):
actor = current_user(request)
parsed_chat = parse_uuid(chat_id, "chat UUID")
ensure_member(actor["id"], parsed_chat)
filename = validate_filename(request.query_params.getlist("filename"))
declared = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
if declared not in ("image/png", "image/jpeg"):
fail(415, "unsupported_media_type", "Content-Type must be image/png or image/jpeg")
length = request.headers.get("content-length")
if length is not None:
if not length.isascii() or not length.isdigit():
fail(400, "invalid_request", "Invalid Content-Length")
if int(length) > MAX_UPLOAD_BYTES: # reject before reading a single body byte
fail(413, "payload_too_large", "Attachment exceeds the size limit")
spool, size, sha256 = await read_body_to_spool(request, declared)
key = STAGING_PREFIX + secrets.token_hex(16) # server-chosen random STAGING key, unrelated to filename or attachment id
try:
await anyio.to_thread.run_sync(decode_image_checked, spool, declared, limiter=decode_limiter)
await run_in_threadpool(s3_put, key, spool, size, declared)
except ApiError: # user error found by validation, before any S3 write
spool.close()
raise
except BaseException:
spool.close()
await compensate(key) # a PUT whose reply was lost may still have stored the object
raise
spool.close()
attachment_id, job_id = uuid.uuid4(), uuid.uuid4()
final_original = jobs.final_key(attachment_id, jobs.PIPELINE_VERSION, "original")
try:
# ONE transaction: metadata + job + outbox row. 202 is returned only after this COMMIT (durable handoff).
with db() as conn:
row = conn.execute(
"INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,s3_key,staging_key,status,pipeline_version) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,'queued',%s) "
"RETURNING id,chat_id,owner_id,filename,content_type,size_bytes,sha256,status,error_code,created_at,updated_at",
(attachment_id, parsed_chat, actor["id"], filename, declared, size, sha256, final_original, key, jobs.PIPELINE_VERSION)).fetchone()
conn.execute("INSERT INTO attachment_jobs(job_id,attachment_id,pipeline_version,status,max_attempts) VALUES (%s,%s,%s,'queued',%s)",
(job_id, attachment_id, jobs.PIPELINE_VERSION, jobs.JOB_MAX_ATTEMPTS))
jobs.add_event(conn, job_id, "accepted")
jobs.enqueue(conn, job_id, attachment_id, jobs.PIPELINE_VERSION, 1)
except BaseException:
await compensate(key) # staging PUT succeeded but the COMMIT did not: remove the unaccounted object
raise
telemetry.log_event(log, logging.INFO, "attachment_accepted", "Attachment accepted, job queued", job_id=str(job_id), attachment_id=str(attachment_id))
cols = ("id", "chat_id", "owner_id", "filename", "content_type", "size_bytes", "sha256", "status", "error_code", "created_at", "updated_at")
return JSONResponse(status_code=202, content=attachment_dict(dict(zip(cols, row))))
ATT_COLS = ("id", "chat_id", "owner_id", "filename", "content_type", "size_bytes", "sha256", "s3_key", "status", "error_code", "created_at", "updated_at")
def load_attachment(attachment_id: str, request: Request) -> dict[str, Any]:
actor = current_user(request)
parsed = parse_uuid(attachment_id, "attachment UUID")
rows = json_rows(None, "SELECT a.id,a.chat_id,a.owner_id,a.filename,a.content_type,a.size_bytes,a.sha256,a.s3_key,a.status,a.error_code,a.created_at,a.updated_at "
"FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id WHERE a.id=%s AND m.user_id=%s", (parsed, actor["id"]))
if not rows:
fail(404, "not_found", "Object not found")
return rows[0]
def variant_rows(attachment_id, pipeline_version: int = jobs.PIPELINE_VERSION) -> list[dict[str, Any]]:
rows = json_rows(None, "SELECT name,s3_key,content_type,size_bytes,width,height,sha256 FROM attachment_variants WHERE attachment_id=%s AND pipeline_version=%s", (attachment_id, pipeline_version))
return sorted(rows, key=lambda r: jobs.VARIANT_ORDER.index(r["name"]))
@app.get("/api/v1/attachments/{attachment_id}")
def get_attachment(attachment_id: str, request: Request):
row = load_attachment(attachment_id, request)
variants = []
if row["status"] == "ready": # variants are published only together with ready (one COMMIT in the worker)
variants = [{k: v[k] for k in ("name", "content_type", "size_bytes", "width", "height", "sha256")} for v in variant_rows(row["id"])]
return attachment_dict(row, variants)
@app.get("/api/v1/attachments/{attachment_id}/content")
def download_attachment(attachment_id: str, request: Request, variant: str = "original"):
row = load_attachment(attachment_id, request)
if variant != "original" and variant not in jobs.VARIANT_ORDER:
fail(400, "invalid_request", "Unknown variant")
if row["status"] != "ready":
fail(409, "conflict", "Attachment is not ready") # queued, processing and failed: no content
key, content_type, size = row["s3_key"], row["content_type"], row["size_bytes"]
if variant != "original":
found = [v for v in variant_rows(row["id"]) if v["name"] == variant]
if not found:
fail(404, "not_found", "Object not found")
key, content_type, size = found[0]["s3_key"], found[0]["content_type"], found[0]["size_bytes"]
try:
obj = s3.get_object(Bucket=S3_BUCKET, Key=key)
except ClientError as exc:
if exc.response.get("Error", {}).get("Code") in ("NoSuchKey", "404"):
log.error("INTEGRITY: metadata without object attachment=%s variant=%s", row["id"], variant)
fail(500, "internal_error", "Internal server error")
raise
body = obj["Body"]
async def stream():
try:
async for chunk in iterate_in_threadpool(body.iter_chunks(CHUNK_BYTES)):
yield chunk
finally:
body.close()
headers = {"Content-Length": str(size), "X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store",
"Content-Disposition": "inline; filename*=UTF-8''" + quote(row["filename"], safe="")}
return StreamingResponse(stream(), media_type=content_type, headers=headers)
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host=os.getenv("APP_HOST", "0.0.0.0"), port=int(os.getenv("APP_PORT", "8080")), timeout_graceful_shutdown=5)
+50
View File
@@ -0,0 +1,50 @@
"""Lab 7 API entrypoint: uvicorn with mandatory mTLS and a client-identity allowlist.
The CA check (ssl.CERT_REQUIRED) only proves "signed by our CA". Every service and the operator-issued
"outsider" certificate pass it, so the identity (SAN) is checked here, right after the handshake and
before a single HTTP byte is parsed. Not allowed => the connection is closed.
"""
from __future__ import annotations
import logging
import os
import ssl
import uvicorn
from uvicorn.protocols.http.h11_impl import H11Protocol
log = logging.getLogger("messenger.tls")
ALLOWED_SANS = {s.strip().lower() for s in os.getenv("ALLOWED_CLIENT_SANS", "lb").split(",") if s.strip()}
class AllowListProtocol(H11Protocol):
"""asyncio calls connection_made only after the TLS handshake finished, so getpeercert() is the verified certificate."""
_accepted = False
def connection_made(self, transport):
ssl_obj = transport.get_extra_info("ssl_object")
cert = ssl_obj.getpeercert() if ssl_obj else None
sans = {v.lower() for k, v in (cert or {}).get("subjectAltName", ()) if k == "DNS"}
if not sans & ALLOWED_SANS:
log.warning("mTLS identity rejected: %s", sorted(sans) or "no SAN")
transport.close()
return
self._accepted = True
super().connection_made(transport)
def connection_lost(self, exc):
if self._accepted:
super().connection_lost(exc)
def main() -> None:
config = uvicorn.Config(
os.getenv("APP", "src.main:app"), host=os.getenv("APP_HOST", "0.0.0.0"), port=int(os.getenv("APP_PORT", "8443")),
ssl_certfile=os.environ["TLS_CERT_FILE"], ssl_keyfile=os.environ["TLS_KEY_FILE"],
ssl_ca_certs=os.environ["TLS_CA_FILE"], ssl_cert_reqs=ssl.CERT_REQUIRED,
http=AllowListProtocol, proxy_headers=False, server_header=False, timeout_graceful_shutdown=10, access_log=False)
uvicorn.Server(config).run()
if __name__ == "__main__":
main()
+145
View File
@@ -0,0 +1,145 @@
"""Lab 6: one OpenTelemetry bootstrap shared by the API, the worker and the dispatcher.
* traces -> BatchSpanProcessor -> OTLP/HTTP -> Collector -> Tempo
* metrics -> PeriodicExportingMetricReader -> OTLP/HTTP -> Collector -> Prometheus (remote write)
* logs -> stdout (JSON) + BatchLogRecordProcessor -> OTLP/HTTP -> Collector -> Loki
Telemetry is best effort: every queue is bounded and exporters have short timeouts, so a dead Collector or
backend can only cost telemetry (dropped batches), never an API response or a job.
"""
from __future__ import annotations
import json
import logging
import os
import socket
import sys
from datetime import datetime, timezone
from opentelemetry import metrics, trace
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.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
SERVICE_NAME = "unknown"
EXPORT_TIMEOUT_S = 3 # a dead Collector must not block the exporter thread for long
METRIC_INTERVAL_MS = 10_000
# Technical (synthetic) identifiers allowed in logs/traces; never in metric labels, never bodies/tokens/URLs.
LOG_FIELDS = ("job_id", "attachment_id", "attempt", "request_id", "outcome", "reason", "topic", "count")
class _EventFilter(logging.Filter):
"""Every record gets an `event` (contract: logs have `event`); explicit extra={"event": ...} wins."""
def filter(self, record: logging.LogRecord) -> bool:
if not hasattr(record, "event"):
record.event = record.name
return True
class _NoOtelSelfLogs(logging.Filter):
"""Exporter errors are logged by the opentelemetry package itself: never feed them back into the OTLP handler."""
def filter(self, record: logging.LogRecord) -> bool:
return not record.name.startswith(("opentelemetry", "urllib3"))
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
ctx = trace.get_current_span().get_span_context()
doc = {
"timestamp": datetime.fromtimestamp(record.created, timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
"severity": record.levelname,
"service.name": SERVICE_NAME,
"event": getattr(record, "event", record.name),
"message": record.getMessage(),
}
if ctx.is_valid:
doc["trace_id"] = format(ctx.trace_id, "032x")
doc["span_id"] = format(ctx.span_id, "016x")
for field in LOG_FIELDS:
if hasattr(record, field):
doc[field] = getattr(record, field)
if record.exc_info and record.exc_info[0]:
doc["exception.type"] = record.exc_info[0].__name__ # type only: no stack trace, no SQL, no values
return json.dumps(doc, ensure_ascii=False)
def log_event(logger: logging.Logger, level: int, event: str, message: str, **fields) -> None:
"""Structured log: `event` + whitelisted technical fields; trace_id/span_id come from the active span."""
logger.log(level, message, extra={"event": event, **fields})
def init(service_name: str, instrument: tuple[str, ...] = ()) -> None:
"""Configure providers once per process. `instrument` selects auto-instrumentation libraries."""
global SERVICE_NAME
SERVICE_NAME = service_name
instance = os.getenv("INSTANCE_ID") or socket.gethostname()
resource = Resource.create({
"service.name": service_name,
"service.version": os.getenv("SERVICE_VERSION", "1.6.0"),
"service.instance.id": instance,
"deployment.environment.name": os.getenv("DEPLOYMENT_ENVIRONMENT", "lab"),
})
tracer_provider = TracerProvider(resource=resource)
tracer_provider.add_span_processor(BatchSpanProcessor(
OTLPSpanExporter(timeout=EXPORT_TIMEOUT_S),
max_queue_size=2048, max_export_batch_size=512, schedule_delay_millis=2000, export_timeout_millis=EXPORT_TIMEOUT_S * 1000))
trace.set_tracer_provider(tracer_provider)
reader = PeriodicExportingMetricReader(
OTLPMetricExporter(timeout=EXPORT_TIMEOUT_S), export_interval_millis=METRIC_INTERVAL_MS, export_timeout_millis=5000)
metrics.set_meter_provider(MeterProvider(resource=resource, metric_readers=[reader]))
logger_provider = LoggerProvider(resource=resource)
logger_provider.add_log_record_processor(BatchLogRecordProcessor(
OTLPLogExporter(timeout=EXPORT_TIMEOUT_S),
max_queue_size=2048, max_export_batch_size=512, schedule_delay_millis=2000, export_timeout_millis=EXPORT_TIMEOUT_S * 1000))
otlp_handler = LoggingHandler(level=logging.NOTSET, logger_provider=logger_provider)
otlp_handler.addFilter(_NoOtelSelfLogs())
otlp_handler.addFilter(_EventFilter())
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(JsonFormatter())
stdout_handler.addFilter(_EventFilter())
root = logging.getLogger()
root.handlers[:] = [stdout_handler, otlp_handler]
root.setLevel(os.getenv("LOG_LEVEL", "INFO"))
if "psycopg" in instrument:
from opentelemetry.instrumentation.psycopg import PsycopgInstrumentor
PsycopgInstrumentor().instrument()
if "botocore" in instrument:
from opentelemetry.instrumentation.botocore import BotocoreInstrumentor
BotocoreInstrumentor().instrument()
# Redis is deliberately NOT auto-instrumented: session keys are derived from the session token.
def tracer(name: str = "messenger") -> trace.Tracer:
return trace.get_tracer(name)
def meter(name: str = "messenger") -> metrics.Meter:
return metrics.get_meter(name)
def _rss_bytes() -> int:
with open("/proc/self/statm") as f:
return int(f.read().split()[1]) * os.sysconf("SC_PAGE_SIZE")
def register_process_metrics() -> None:
"""Process CPU/RAM of this container's main process (own gauges: no psutil dependency)."""
m = meter()
m.create_observable_counter("process.cpu.time", callbacks=[lambda _o: [metrics.Observation(sum(os.times()[:2]))]],
unit="s", description="CPU seconds (user+system) used by this process")
m.create_observable_gauge("process.memory.usage", callbacks=[lambda _o: [metrics.Observation(_rss_bytes())]],
unit="By", description="Resident set size of this process")
+78
View File
@@ -0,0 +1,78 @@
"""Secrets for api/worker/dispatcher/sweeper from OpenBao (AppRole -> short-lived scoped token -> one KV v2 secret).
Bootstrap trust: the only things on disk are the PUBLIC CA, the RoleID (not a secret) and a SecretID with a 24 h TTL that the
operator issues into /run/approle. The service logs in, reads exactly one path allowed by its policy, revokes its own token and
keeps the values only in process memory / environment. No root token, no unseal key, no long-lived token is ever present.
Sealed/unreachable OpenBao at start => bounded retries, then exit (compose restarts the container); a running process is not affected.
"""
from __future__ import annotations
import json
import os
import ssl
import time
import urllib.error
import urllib.request
BAO_ADDR = os.getenv("BAO_ADDR", "https://openbao:8200").rstrip("/")
BAO_CACERT = os.getenv("BAO_CACERT", "/run/pki/ca.crt")
APPROLE_DIR = os.getenv("APPROLE_DIR", "/run/approle")
# secret field in OpenBao -> environment variable consumed by the unchanged lab 6 code (psycopg reads PGPASSWORD itself).
ENV_MAP = {
"api": {"db_password": "PGPASSWORD", "redis_password": "REDIS_PASSWORD", "s3_access_key": "S3_ACCESS_KEY_ID", "s3_secret_key": "S3_SECRET_ACCESS_KEY"},
"worker": {"db_password": "PGPASSWORD", "s3_access_key": "S3_ACCESS_KEY_ID", "s3_secret_key": "S3_SECRET_ACCESS_KEY"},
"dispatcher": {"db_password": "PGPASSWORD"},
"sweeper": {"db_password": "PGPASSWORD", "s3_access_key": "S3_ACCESS_KEY_ID", "s3_secret_key": "S3_SECRET_ACCESS_KEY"},
}
class VaultError(RuntimeError):
"""Message never contains secret values or tokens."""
def _call(method: str, path: str, body: dict | None = None, token: str | None = None) -> dict:
ctx = ssl.create_default_context(cafile=BAO_CACERT) # CA + hostname (SAN) verification, never disabled
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(f"{BAO_ADDR}/v1/{path}", data=data, method=method)
if token:
req.add_header("X-Vault-Token", token)
try:
with urllib.request.urlopen(req, timeout=5, context=ctx) as resp:
raw = resp.read()
except urllib.error.HTTPError as exc:
raise VaultError(f"OpenBao {method} {path}: HTTP {exc.code}") from None
except (urllib.error.URLError, OSError) as exc:
raise VaultError(f"OpenBao unreachable: {type(exc).__name__}") from None
return json.loads(raw) if raw else {}
def _read(name: str) -> str:
with open(os.path.join(APPROLE_DIR, name), encoding="utf-8") as fh:
return fh.read().strip()
def fetch(role: str) -> dict[str, str]:
"""One login -> one read -> token revoked. Raises VaultError if sealed, SecretID expired/destroyed, or policy denies."""
login = _call("POST", "auth/approle/login", {"role_id": _read("role_id"), "secret_id": _read("secret_id")})
token = login["auth"]["client_token"]
try:
return _call("GET", f"kv/data/{role}", token=token)["data"]["data"]
finally:
try:
_call("POST", "auth/token/revoke-self", token=token)
except VaultError:
pass # the token expires by TTL anyway
def load_into_env(role: str, attempts: int = 30, delay: float = 2.0) -> None:
last = None
for _ in range(attempts):
try:
secret = fetch(role)
for field, env in ENV_MAP[role].items():
os.environ[env] = secret[field]
return
except (VaultError, KeyError, OSError) as exc:
last = exc
time.sleep(delay)
raise SystemExit(f"cannot obtain secrets for {role} from OpenBao: {last}")
+297
View File
@@ -0,0 +1,297 @@
"""Lab 6 worker (lab 5 + OpenTelemetry): Kafka consumer -> claim (lease) in PostgreSQL -> staging -> pipeline -> final S3 + COMMIT -> offset commit.
PostgreSQL is the source of truth for job state; Kafka is the at-least-once transport. The Kafka offset is committed
only AFTER the durable effect (final objects + COMMIT of the result) or after a durable decision (retry scheduled / failed).
"""
from __future__ import annotations
import hashlib
import json
import logging
import os
import signal
import socket
import subprocess
import sys
import tempfile
import threading
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import psycopg
from botocore.exceptions import BotoCoreError, ClientError
from boto3.s3.transfer import TransferConfig
from confluent_kafka import Consumer, TopicPartition
from opentelemetry import metrics, trace
from opentelemetry.propagate import extract
from opentelemetry.trace import SpanKind, Status, StatusCode
from . import jobs, telemetry, vault
# Lab 7: the worker identity gets ONLY its own secret (DB role messenger_worker, S3 key svc-worker); never api/admin credentials.
vault.load_into_env("worker")
telemetry.init("messenger-worker", instrument=("psycopg", "botocore"))
log = logging.getLogger("worker")
TRACER = telemetry.tracer()
NO_THREADS = TransferConfig(use_threads=False) # s3transfer threads would lose the trace context: keep transfers in the job thread
WORKER_ID = os.getenv("INSTANCE_ID") or socket.gethostname()
CONCURRENCY = int(os.getenv("WORKER_CONCURRENCY", "2"))
FAULT_EXIT_AFTER_S3 = os.getenv("FAULT_WORKER_EXIT_AFTER_S3", "0") == "1" # test hook: crash after the S3 write, before COMMIT/ack
IMG_MEMORY_MB = os.getenv("IMG_MEMORY_MB", "1024")
CODE_BY_EXIT = {2: "invalid_image", 3: "image_too_large", 4: "image_too_complex"} # permanent errors of imgproc
STOP = False
# ---- Lab 6 metrics. Labels: job.type + outcome only (never job_id / attachment_id). ----
_M = telemetry.meter()
JOBS_PROCESSED = _M.create_counter("messenger.jobs.processed", unit="{job}", description="Finished job attempts by outcome: success|retry|failed|lost|noop|error")
JOB_DURATION = _M.create_histogram("messenger.job.duration", unit="s", description="Worker processing time of one attempt (claim -> outcome), backlog wait excluded",
explicit_bucket_boundaries_advisory=[0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120])
TIME_TO_READY = _M.create_histogram("messenger.job.time_to_ready", unit="s", description="End-to-end: durable acceptance (job row created) -> ready committed",
explicit_bucket_boundaries_advisory=[0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 1800])
_busy, _busy_lock = 0, threading.Lock()
_M.create_observable_gauge("messenger.worker.busy", callbacks=[lambda _o: [metrics.Observation(_busy)]], unit="{job}", description="Jobs being handled right now")
_M.create_observable_gauge("messenger.worker.capacity", callbacks=[lambda _o: [metrics.Observation(CONCURRENCY)]], unit="{job}", description="WORKER_CONCURRENCY")
telemetry.register_process_metrics()
class Permanent(Exception):
def __init__(self, code: str):
super().__init__(code)
self.code = code
class Transient(Exception):
pass
def connect():
return psycopg.connect(connect_timeout=5, options="-c statement_timeout=10000")
def parse_job(raw: bytes) -> dict | None:
"""Validate against jobs.schema.json (the subset that matters). Poison messages are logged and skipped."""
try:
m = json.loads(raw)
assert m["schema_version"] == 1 and m["type"] == jobs.JOB_TYPE
uuid.UUID(m["job_id"]); uuid.UUID(m["attachment_id"])
assert isinstance(m["pipeline_version"], int) and m["pipeline_version"] >= 1
return m
except Exception:
telemetry.log_event(log, logging.ERROR, "job_poison_skipped", f"poison message skipped (schema violation), size={len(raw)}")
return None
def claim(msg: dict) -> dict | None:
"""queued -> processing with a lease. Returns None when this delivery must be a no-op (ack)."""
with connect() as conn:
row = conn.execute(
"SELECT status, attempt, max_attempts, attachment_id, pipeline_version, "
"(next_attempt_at <= now()) AS due, (lease_until IS NOT NULL AND lease_until < now()) AS lease_expired "
"FROM attachment_jobs WHERE job_id=%s FOR UPDATE", (msg["job_id"],)).fetchone()
if row is None:
telemetry.log_event(log, logging.WARNING, "job_unknown", "job unknown, skipped", job_id=msg["job_id"]); return None
status, attempt, max_attempts, att_id, pv, due, expired = row
if pv != msg["pipeline_version"]:
return None # stale job of another pipeline version never overwrites the newer one
if status in ("ready", "failed"):
telemetry.log_event(log, logging.INFO, "job_duplicate_noop", f"job already {status}: duplicate delivery is a no-op", job_id=msg["job_id"]); return None
if status == "queued" and not due:
return None # early duplicate: the delayed outbox row will deliver it later
if status == "processing" and not expired:
telemetry.log_event(log, logging.INFO, "job_leased_skip", "job is leased by another worker: skip", job_id=msg["job_id"]); return None
if attempt >= max_attempts: # lease expired and no attempts left
jobs.fail_job(conn, msg["job_id"], att_id, "retry_exhausted", attempt)
return None
attempt += 1
conn.execute("UPDATE attachment_jobs SET status='processing', attempt=%s, worker_id=%s, "
"lease_until=now()+make_interval(secs=>%s), updated_at=now() WHERE job_id=%s",
(attempt, WORKER_ID, jobs.LEASE_SECONDS, msg["job_id"]))
conn.execute("UPDATE attachments SET status='processing', updated_at=now() WHERE id=%s", (att_id,))
jobs.add_event(conn, msg["job_id"], "claimed", f"attempt={attempt} worker={WORKER_ID}")
telemetry.log_event(log, logging.INFO, "job_claimed", "job claimed", job_id=msg["job_id"], attempt=attempt)
a = conn.execute("SELECT sha256, staging_key, s3_key, content_type, filename FROM attachments WHERE id=%s", (att_id,)).fetchone()
return {"job_id": msg["job_id"], "attachment_id": att_id, "pv": pv, "attempt": attempt, "max_attempts": max_attempts,
"sha256": a[0].strip(), "staging_key": a[1], "original_key": a[2], "content_type": a[3]}
def run_pipeline(s3, c: dict) -> dict:
"""Download staging -> verify -> child process with limits -> idempotent PUTs of deterministic keys."""
if not c["staging_key"]:
raise Permanent("staging_missing")
with tempfile.TemporaryDirectory(prefix="job-") as tmp:
src, out = Path(tmp) / "in.bin", Path(tmp) / "out"
out.mkdir()
try:
with TRACER.start_as_current_span("s3.download_staging"):
s3.download_file(jobs.S3_BUCKET, c["staging_key"], str(src), Config=NO_THREADS)
except ClientError as e:
if e.response.get("Error", {}).get("Code") in ("NoSuchKey", "404"):
raise Permanent("staging_missing")
raise
if hashlib.sha256(src.read_bytes()).hexdigest() != c["sha256"]:
raise Permanent("integrity_error") # bytes differ from what the API accepted
try:
with TRACER.start_as_current_span("imgproc.run"):
r = subprocess.run([sys.executable, "-m", "src.imgproc", str(src), str(out)], capture_output=True, text=True,
timeout=jobs.JOB_TIMEOUT_SECONDS, env={"PATH": os.environ.get("PATH", ""), "IMG_MEMORY_MB": IMG_MEMORY_MB,
"IMG_CPU_SECONDS": str(jobs.JOB_TIMEOUT_SECONDS),
"MAX_IMAGE_PIXELS": os.getenv("MAX_IMAGE_PIXELS", "40000000")}) # no secrets in the child
except subprocess.TimeoutExpired:
raise Transient("job timeout") # child is killed by subprocess.run
if r.returncode in CODE_BY_EXIT:
raise Permanent(CODE_BY_EXIT[r.returncode])
if r.returncode != 0:
raise Transient(f"imgproc exit {r.returncode}")
meta = json.loads(r.stdout)
files = {"thumbnail": "thumbnail.jpg", "crop": "crop.jpg", "optimized": "optimized.webp"}
# 1) original into the final prefix (same key every time => repeated PUT is harmless)
with TRACER.start_as_current_span("s3.upload_final"):
s3.upload_file(str(src), jobs.S3_BUCKET, c["original_key"], ExtraArgs={"ContentType": c["content_type"]}, Config=NO_THREADS)
# 2) variants
for name in jobs.VARIANT_ORDER:
key = jobs.final_key(c["attachment_id"], c["pv"], name)
s3.upload_file(str(out / files[name]), jobs.S3_BUCKET, key, ExtraArgs={"ContentType": meta[name]["content_type"]}, Config=NO_THREADS)
meta[name]["s3_key"] = key
return meta
def commit_ready(c: dict, meta: dict) -> bool:
"""Atomically publish the result. False if this attempt no longer owns the job (lease lost to a newer attempt)."""
with connect() as conn:
row = conn.execute("SELECT status, attempt FROM attachment_jobs WHERE job_id=%s FOR UPDATE", (c["job_id"],)).fetchone()
if row is None or row[0] != "processing" or row[1] != c["attempt"]:
telemetry.log_event(log, logging.WARNING, "job_lease_lost", "attempt lost ownership, result not committed", job_id=c["job_id"], attempt=c["attempt"]); return False
for name in jobs.VARIANT_ORDER:
v = meta[name]
conn.execute("INSERT INTO attachment_variants(attachment_id,pipeline_version,name,s3_key,content_type,size_bytes,width,height,sha256) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT (attachment_id,pipeline_version,name) DO NOTHING",
(c["attachment_id"], c["pv"], name, v["s3_key"], v["content_type"], v["size_bytes"], v["width"], v["height"], v["sha256"]))
waited = conn.execute("UPDATE attachment_jobs SET status='ready', error_code=NULL, lease_until=NULL, updated_at=now() WHERE job_id=%s "
"RETURNING EXTRACT(EPOCH FROM (now() - created_at))", (c["job_id"],)).fetchone()[0]
TIME_TO_READY.record(float(waited), {"job.type": jobs.JOB_TYPE})
conn.execute("UPDATE attachments SET status='ready', error_code=NULL, staging_key=NULL, updated_at=now() WHERE id=%s", (c["attachment_id"],))
jobs.add_event(conn, c["job_id"], "ready", f"attempt={c['attempt']}")
return True
def record_failure(c: dict, exc: Exception) -> None:
"""Permanent -> failed in the PostgreSQL registry. Transient -> queued with backoff+jitter (delayed outbox row) or failed when attempts are exhausted."""
with connect() as conn:
row = conn.execute("SELECT status, attempt FROM attachment_jobs WHERE job_id=%s FOR UPDATE", (c["job_id"],)).fetchone()
if row is None or row[0] != "processing" or row[1] != c["attempt"]:
return
if isinstance(exc, Permanent):
jobs.fail_job(conn, c["job_id"], c["attachment_id"], exc.code, c["attempt"])
elif c["attempt"] >= c["max_attempts"]:
jobs.fail_job(conn, c["job_id"], c["attachment_id"], "retry_exhausted", c["attempt"])
else:
delay = jobs.backoff_seconds(c["attempt"])
conn.execute("UPDATE attachment_jobs SET status='queued', lease_until=NULL, next_attempt_at=now()+make_interval(secs=>%s), "
"error_code=NULL, updated_at=now() WHERE job_id=%s", (delay, c["job_id"]))
conn.execute("UPDATE attachments SET status='queued', updated_at=now() WHERE id=%s", (c["attachment_id"],))
jobs.add_event(conn, c["job_id"], "retry_scheduled", f"attempt={c['attempt']} delay={delay:.1f}s reason={type(exc).__name__}")
jobs.enqueue(conn, c["job_id"], c["attachment_id"], c["pv"], c["attempt"] + 1, delay_seconds=delay)
def _process(s3, msg: dict, span) -> str:
"""The lab 5 job logic, now with stage spans. Returns the outcome label used by metrics and the consumer span."""
with TRACER.start_as_current_span("job.claim"):
c = claim(msg)
if c is None:
return "noop"
span.set_attribute("job.attempt", c["attempt"])
try:
with TRACER.start_as_current_span("job.pipeline"):
meta = run_pipeline(s3, c)
if FAULT_EXIT_AFTER_S3 and c["attempt"] == 1:
log.error("FAULT: exiting after S3 write, before COMMIT and offset commit")
os._exit(137)
with TRACER.start_as_current_span("job.commit_ready"):
committed = commit_ready(c, meta)
if not committed:
return "lost"
telemetry.log_event(log, logging.INFO, "job_ready", "job ready", job_id=c["job_id"], attempt=c["attempt"], outcome="success")
try:
s3.delete_object(Bucket=jobs.S3_BUCKET, Key=c["staging_key"]) # staging cleanup after the safe COMMIT
except Exception:
log.warning("staging cleanup failed; sweeper will remove it")
return "success"
except (Permanent, Transient, ClientError, BotoCoreError, OSError, json.JSONDecodeError) as exc:
final = isinstance(exc, Permanent) or c["attempt"] >= c["max_attempts"]
outcome = "failed" if final else "retry"
span.record_exception(exc, attributes={"exception.escaped": False})
telemetry.log_event(log, logging.WARNING, "job_attempt_failed", f"job attempt failed: {type(exc).__name__}",
job_id=c["job_id"], attempt=c["attempt"], outcome=outcome, reason=getattr(exc, "code", type(exc).__name__))
with TRACER.start_as_current_span("job.record_failure"):
record_failure(c, exc)
return outcome
def handle(s3, raw: bytes) -> None:
global _busy
msg = parse_job(raw)
if msg is None:
return
# W3C trace context travels in the message: this CONSUMER span is a child of the dispatcher's PRODUCER span.
with TRACER.start_as_current_span(
f"{jobs.JOBS_TOPIC} process", context=extract(msg), kind=SpanKind.CONSUMER,
attributes={"messaging.system": "kafka", "messaging.destination.name": jobs.JOBS_TOPIC, "messaging.operation.type": "process",
"job.type": jobs.JOB_TYPE, "job.id": msg["job_id"], "attachment.id": msg["attachment_id"], "job.attempt": msg.get("attempt", 0)}) as span:
started, outcome = time.perf_counter(), "error"
with _busy_lock:
_busy += 1
try:
outcome = _process(s3, msg, span)
finally: # unexpected exception: outcome stays "error", the exception propagates (process exits)
with _busy_lock:
_busy -= 1
attrs = {"job.type": jobs.JOB_TYPE, "outcome": outcome}
JOBS_PROCESSED.add(1, attrs)
if outcome != "noop":
JOB_DURATION.record(time.perf_counter() - started, attrs)
span.set_attribute("job.outcome", outcome)
if outcome in ("retry", "failed", "lost", "error"):
span.set_status(Status(StatusCode.ERROR, outcome))
def main() -> None:
def request_stop(*_):
global STOP
STOP = True
signal.signal(signal.SIGTERM, request_stop)
signal.signal(signal.SIGINT, request_stop)
s3 = jobs.make_s3()
consumer = Consumer({
**jobs.kafka_ssl(), "bootstrap.servers": jobs.KAFKA_BOOTSTRAP, "group.id": "attachment-workers",
"enable.auto.commit": False, "auto.offset.reset": "earliest", "isolation.level": "read_committed",
"max.poll.interval.ms": 600000, "session.timeout.ms": 30000,
"queued.max.messages.kbytes": 1024, "fetch.max.bytes": 1048576, # bounded client-side prefetch
})
consumer.subscribe([jobs.JOBS_TOPIC])
telemetry.log_event(log, logging.INFO, "worker_started", f"worker {WORKER_ID} started, concurrency={CONCURRENCY}, max_attempts={jobs.JOB_MAX_ATTEMPTS}, lease={jobs.LEASE_SECONDS}s")
with ThreadPoolExecutor(max_workers=CONCURRENCY) as pool:
while not STOP:
msgs = consumer.consume(num_messages=CONCURRENCY, timeout=1.0) # at most CONCURRENCY jobs in flight
batch = []
for m in msgs:
if m.error():
log.warning("kafka error: %s", m.error()); continue
batch.append(m)
if not batch:
continue
futures = [pool.submit(handle, s3, m.value()) for m in batch]
for f in futures:
f.result() # unexpected exception => process exits, offsets stay uncommitted, Kafka redelivers
# ACK boundary: commit the highest processed offset+1 per partition, only after every job of the batch is durable
top = {}
for m in batch:
top[(m.topic(), m.partition())] = max(top.get((m.topic(), m.partition()), -1), m.offset() + 1)
consumer.commit(offsets=[TopicPartition(t, p, o) for (t, p), o in top.items()], asynchronous=False)
consumer.close()
if __name__ == "__main__":
main()