diff --git a/.env.example b/.env.example index 2e9f0541..4cbda8f9 100644 --- a/.env.example +++ b/.env.example @@ -1,41 +1,24 @@ -# Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. -APP_HOST=0.0.0.0 -APP_PORT=8080 -APP_ENV=lab -SESSION_TTL_SECONDS=3600 -# Choose credentials locally. File paths contain no secret values. -DATABASE_URL_FILE=/run/secrets/database_url -# Optional on 3, required use on 4 in lab2; Redis OR Valkey: -SESSION_STORE=postgres -CACHE_URL_FILE=/run/secrets/cache_url +# Copy to .env and choose independent local values for all passwords and secret keys. +POSTGRES_USER=messenger_admin +POSTGRES_DB=messenger +POSTGRES_PASSWORD= +API_DB_PASSWORD= +WORKER_DB_PASSWORD= +DISPATCHER_DB_PASSWORD= +CLEANUP_DB_PASSWORD= +REDIS_PASSWORD= +MINIO_ROOT_USER=messenger_minio +MINIO_ROOT_PASSWORD= +S3_ACCESS_KEY=messenger-api +S3_SECRET_KEY= +WORKER_S3_ACCESS_KEY=messenger-worker +WORKER_S3_SECRET_KEY= +CLEANUP_S3_ACCESS_KEY=messenger-cleanup +CLEANUP_S3_SECRET_KEY= +DISPATCHER_BROKER_PASSWORD= +WORKER_BROKER_PASSWORD= +GRAFANA_PASSWORD= +GRAFANA_PORT=3000 API_REPLICAS=2 -IDEMPOTENCY_TTL_SECONDS=86400 -S3_ENDPOINT=https://s3:9000 -S3_REGION=us-east-1 -S3_BUCKET=messenger-attachments -S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id -S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key -MAX_UPLOAD_BYTES=10485760 -MAX_IMAGE_PIXELS=40000000 -BROKER_URL_FILE=/run/secrets/broker_url -WORKER_CONCURRENCY=2 -JOB_MAX_ATTEMPTS=5 -JOB_TIMEOUT_SECONDS=60 -STAGING_RETENTION_SECONDS=86400 -OTEL_SERVICE_NAME=messenger-api -# Worker must set a distinct service.name. -OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318 -OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf -OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab -# TLS and OpenBao: actual paths/ports depend on your implemented trust matrix. -PUBLIC_BASE_URL=https://localhost:8443 -TLS_CA_FILE=/run/secrets/ca.crt -TLS_CERT_FILE=/run/secrets/service.crt -TLS_KEY_FILE=/run/secrets/service.key -BAO_ADDR=https://openbao:8200 -BAO_CACERT=/run/secrets/bao-ca.crt -# No root token here. Bootstrap operator -> short-lived service auth -> scoped token. -ARGON2_MEMORY_KIB=19456 -ARGON2_ITERATIONS=2 -ARGON2_PARALLELISM=1 +SESSION_TTL_SECONDS=3600 +SESSION_CACHE_MAX_TTL=60 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..3934c8fb --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +*.sh text eol=lf +*.py text eol=lf +*.sql text eol=lf +*.conf text eol=lf +*.cmd text eol=crlf diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..66b3d446 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,22 @@ +FROM python:3.11.9-slim + +WORKDIR /app + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY app.py schemas.py db.py cache.py migrate.py attachments.py cleanup.py pipeline.py worker.py telemetry.py tls_proxy.py api_start.py secret_entry.py ./ +COPY migrations ./migrations + +# непривилегированный пользователь +RUN useradd --create-home --shell /bin/bash appuser +USER appuser + +EXPOSE 8080 + +HEALTHCHECK --interval=3s --timeout=3s --start-period=10s --retries=3 \ + CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health/ready').read()" || exit 1 + +# exec: uvicorn — PID 1, получает SIGTERM и корректно закрывает пул соединений +ENTRYPOINT ["python", "secret_entry.py"] +CMD ["python", "api_start.py"] diff --git a/REPORT.md b/REPORT.md index 9801db45..0efe10b7 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,45 @@ # Отчёт — лабораторная 7 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +Автор — Казаков Амин, БВТ2303. Целевая оценка — 4. -## Запуск из чистого clone +## Запуск -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Выполнять из корня репозитория в PowerShell. Нужны Docker Desktop, Python 3 и пакет cryptography. Скопировать .env.example в .env и заполнить пустые пароли и ключи независимыми локальными значениями. Значения MinIO должны быть длиной от 8 символов. Секреты и локальные сертификаты исключены из Git. -## Архитектура и решения +```powershell +python -m pip install cryptography +python -X utf8 scripts/bootstrap_pki.py +docker compose up -d openbao +python -X utf8 scripts/bootstrap_bao.py +docker compose config --quiet +docker compose up -d --build --wait --wait-timeout 90 +python -X utf8 scripts/check_contract.py +python -X utf8 tests/smoke.py --base-url https://127.0.0.1:8443 --ca-file certs/private/ca.crt +``` -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +OpenBao запускается в обычном режиме с постоянным хранилищем. Скрипт bootstrap инициализирует его при первом запуске и снимает печать после перезапуска. При первом запуске сборка MinIO загружает закреплённые версии Go-модулей. Для остановки с сохранением учебных данных используется docker compose stop. -## Доказательства критериев +## Архитектура -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +Сохранены мессенджер, реплики API, PostgreSQL, S3, очередь вложений и телеметрия из ЛР6. Добавлены HTTPS, mTLS на границах доверия, отдельные сервисные роли и доступ к секретам через OpenBao. PostgreSQL хранит подтверждённые записи и очередь outbox. [Матрица доверия](infra/trust-matrix-solution.md) описывает связи и применённые проверки. -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +## Результаты проверок -## Эксперименты и отказы +| Проверка | Результат | Доказательство | +| --- | --- | --- | +| HTTPS, публичный API, отказ реплики и перезапуск | PASS. Действующая сессия и вложения сохранены | [verification.txt](evidence/verification.txt) | +| mTLS | 24 проверки на восьми внутренних связях. Принята разрешённая роль, отклонены чужая роль и отсутствие сертификата | [tls-boundaries.json](evidence/tls-boundaries.json) | +| OpenBao | Ограниченный доступ API и worker, TTL до 900 с, запечатанный OpenBao отклоняет выдачу токена | [bao-policy.json](evidence/bao-policy.json) | +| Ротация | Старые сертификат и пароль Redis отклонены. Система работает после замены без пересборки | [rotation.json](evidence/rotation.json) | +| Доступ worker | Подтверждены ограничения таблиц PostgreSQL, префиксов S3, команд и ключей очереди | [worker-permissions.json](evidence/worker-permissions.json) | +| Argon2id | 20 последовательных измерений. Медиана 21,90 мс, максимум 35,03 мс. Старый хеш обновлён при входе | [hash-cost.json](evidence/hash-cost.json), [password-rehash.json](evidence/password-rehash.json) | +| Общий лимит входа | 120 ответов 401, затем две реплики вернули 429 с Retry-After 60 | [login-budget.json](evidence/login-budget.json) | +| Конфиденциальность телеметрии | В коррелированных логах и трассах входа и сообщения тестовые секреты не обнаружены | [telemetry-privacy.json](evidence/telemetry-privacy.json) | +| Сбой фоновой обработки | Outbox восстановил обработку после перезапуска API и broker. После сбоя worker сохранены ровно три варианта | [pipeline.json](evidence/pipeline.json) | +| Сканирование образа приложения | Docker Scout обнаружил 17 critical и 120 high в 18 пакетах. Pillow обрабатывает внешние изображения, OpenSSL участвует в TLS, setuptools входит в образ без установки пакетов при запросе | [image-scan.txt](evidence/image-scan.txt) | -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +## Ограничения -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +При перезапуске broker Redis сообщил об ошибках ACL при чтении журнала AOF. Тесты подтвердили сохранность и восстановление обработки через PostgreSQL outbox. Полное восстановление каждой записи Redis AOF не подтверждено. Аудит утечек охватывает два коррелированных запроса, сканирование охватывает образ приложения. -## Ограничения и следующие шаги - -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Использованы задание курса и документация компонентов. ChatGPT использован при реализации, написании тестов и оформлении отчёта. diff --git a/api_start.py b/api_start.py new file mode 100644 index 00000000..603a2625 --- /dev/null +++ b/api_start.py @@ -0,0 +1,21 @@ +"""Run Uvicorn on a private loopback socket and mTLS proxy on the service port.""" +import os +import signal +import subprocess +import sys + +proxy=subprocess.Popen([sys.executable,'tls_proxy.py'],env={**os.environ,'TLS_LISTEN_PORT':'8443','TLS_BACKEND_PORT':'8080','TLS_ALLOWED_IDENTITIES':'lb-client'}) +api=subprocess.Popen(['uvicorn','app:app','--host','127.0.0.1','--port','8080','--timeout-graceful-shutdown','10']) + + +def stop(*_): + api.terminate() + + +signal.signal(signal.SIGTERM,stop) +signal.signal(signal.SIGINT,stop) +try: + code=api.wait() +finally: + proxy.terminate();proxy.wait() +raise SystemExit(code) diff --git a/app.py b/app.py new file mode 100644 index 00000000..56bbf946 --- /dev/null +++ b/app.py @@ -0,0 +1,592 @@ +import base64 +import binascii +import hashlib +import json +import logging +import os +import re +import secrets +import socket +import uuid +import time +import telemetry as ot +from opentelemetry.trace import SpanKind, Status, StatusCode +from contextlib import asynccontextmanager +from datetime import datetime, timezone + +import psycopg +from psycopg import errors +from argon2 import PasswordHasher +from argon2.exceptions import InvalidHashError, VerificationError +from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request, Response +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse +from starlette.exceptions import HTTPException as StarletteHTTPException + +import cache +import db +from attachments import router as attachment_router, S3, BUCKET +from schemas import ( + User, CreateUser, Session, + Chat, CreateChat, ChatPage, + Message, CreateMessage, MessagePage, +) + +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") +log = logging.getLogger("messenger") + +SESSION_TTL_SECONDS = int(os.environ.get("SESSION_TTL_SECONDS", "3600")) +INSTANCE_ID = uuid.uuid4().hex + +ph = PasswordHasher(memory_cost=19456,time_cost=2,parallelism=1) +# Хеш-заглушка: проверяем пароль даже для несуществующего username, +# чтобы по времени ответа нельзя было узнать, есть ли такой пользователь +DUMMY_HASH = ph.hash("dummy-password-for-timing") + +BASIC_CHALLENGE = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'} +BEARER_CHALLENGE = {"WWW-Authenticate": 'Bearer realm="messenger"'} + +ERROR_CODES = { + 400: "invalid_request", + 401: "unauthorized", + 404: "not_found", + 409: "conflict", + 413: "payload_too_large", + 415: "unsupported_media_type", + 429: "rate_limited", + 503: "unavailable", +} + + +@asynccontextmanager +async def lifespan(app): + db.pool.open(wait=True, timeout=30) # ждём, пока БД станет доступна + cache.start() # фоновая проверка доступности Redis + yield # тут приложение работает + db.pool.close() # при остановке (SIGTERM) закрываем пул + + +app = FastAPI(lifespan=lifespan) + + +# ---------- Вспомогательные функции ---------- + +def iso(dt: datetime) -> str: + return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + + +def parse_uuid(value: str, what: str) -> str: + try: + return str(uuid.UUID(value)) + except ValueError: + raise HTTPException(400, f"invalid {what}") + + +def hash_token(token: str) -> str: + return hashlib.sha256(token.encode()).hexdigest() + + +def check_password(password_hash: str, password: str) -> bool: + try: + return ph.verify(password_hash, password) + except (VerificationError, InvalidHashError): + return False + + +def user_from_row(row) -> User: + return User( + id=str(row["id"]), + username=row["username"], + display_name=row["display_name"], + created_at=iso(row["created_at"]), + ) + + +def chat_from_row(row) -> Chat: + return Chat( + id=str(row["id"]), + title=row["title"], + member_ids=[str(m) for m in row["member_ids"]], + created_at=iso(row["created_at"]), + ) + + +def message_from_row(row) -> Message: + return Message( + id=str(row["id"]), + chat_id=str(row["chat_id"]), + sender_id=str(row["sender_id"]), + text=row["text"], + attachment_ids=[str(v) for v in row["attachment_ids"]], + created_at=iso(row["created_at"]), + ) + + +# Курсор = base64(JSON) с последним (created_at, id) и "областью" (какой чат/список). +# Курсор от другого чата не подойдёт -> 400. +def encode_cursor(scope: str, created_at: datetime, item_id) -> str: + raw = json.dumps({"s": scope, "t": iso(created_at), "i": str(item_id)}) + return base64.urlsafe_b64encode(raw.encode()).decode().rstrip("=") + + +def decode_cursor(cursor: str, scope: str) -> tuple[datetime, str]: + try: + padded = cursor + "=" * (-len(cursor) % 4) + data = json.loads(base64.urlsafe_b64decode(padded)) + if data["s"] != scope: + raise ValueError("cursor from another resource") + return datetime.fromisoformat(data["t"]), str(uuid.UUID(data["i"])) + except (ValueError, KeyError, TypeError, binascii.Error): + raise HTTPException(400, "invalid cursor") + + +def is_member(conn, chat_id: str, user_id: str) -> bool: + row = conn.execute( + "SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", + (chat_id, user_id), + ).fetchone() + return row is not None + + +# ---------- Ошибки и X-Request-Id ---------- + +def error_response(status: int, message: str, request_id: str, headers=None) -> JSONResponse: + if status in ERROR_CODES: + code = ERROR_CODES[status] + elif status < 500: + code = "invalid_request" + else: + code = "internal_error" + return JSONResponse( + status_code=status, + content={"error": {"code": code, "message": message, "request_id": request_id}}, + headers=headers or {}, + ) + + +@app.middleware("http") +async def request_id_middleware(request: Request, call_next): + rid = request.headers.get("X-Request-Id") + try: + rid = str(uuid.UUID(rid or "")) + except ValueError: + rid = str(uuid.uuid4()) + request.state.request_id = rid + try: + response = await call_next(request) + except psycopg.OperationalError: + # БД недоступна / пул исчерпан (PoolTimeout тоже OperationalError) + log.exception("database unavailable") + response = error_response(503, "service temporarily unavailable", rid) + except Exception: + log.exception("unhandled error") + response = error_response(500, "internal error", rid) + response.headers["X-Request-Id"] = rid + response.headers["X-Instance-Id"] = INSTANCE_ID + return response + + +@app.middleware("http") +async def observe_http(request: Request, call_next): + start=time.monotonic() + with ot.tracer.start_as_current_span('HTTP '+request.method,kind=SpanKind.SERVER) as span: + response=await call_next(request) + route=getattr(request.scope.get('route'),'path','unmatched') + status=response.status_code + attrs={'method':request.method,'route':route,'status_class':str(status//100)+'xx'} + span.update_name(request.method+' '+route) + span.set_attribute('http.route',route) + span.set_attribute('http.response.status_code',status) + if status>=500: + span.set_status(Status(StatusCode.ERROR)) + ot.http_count.add(1,attrs) + ot.http_duration.record(time.monotonic()-start,attrs) + ot.logger.info('http_request',extra={'route':route,'method':request.method,'status':status, + 'request_id':response.headers.get('X-Request-Id','')}) + response.headers['X-Trace-Id']=format(span.get_span_context().trace_id,'032x') + return response + + +@app.exception_handler(RequestValidationError) +async def validation_handler(request: Request, exc: RequestValidationError): + return error_response(400, "invalid request", request.state.request_id) + + +@app.exception_handler(StarletteHTTPException) +async def http_exception_handler(request: Request, exc: StarletteHTTPException): + return error_response(exc.status_code, str(exc.detail), request.state.request_id, exc.headers) + + +# ---------- Аутентификация ---------- + +def parse_basic(authorization: str | None) -> tuple[str, str]: + scheme, _, encoded = (authorization or "").partition(" ") + if scheme.lower() != "basic" or not encoded.strip(): + raise HTTPException(401, "unauthorized", BASIC_CHALLENGE) + try: + decoded = base64.b64decode(encoded.strip(), validate=True).decode("utf-8") + except (binascii.Error, UnicodeDecodeError): + raise HTTPException(401, "unauthorized", BASIC_CHALLENGE) + username, sep, password = decoded.partition(":") # двоеточие в пароле допустимо + if not sep: + raise HTTPException(401, "unauthorized", BASIC_CHALLENGE) + return username, password + + +def current_session(authorization: str | None = Header(default=None)) -> dict: + # Принимаем только Bearer; X-User-Id и Basic здесь игнорируются -> 401 + scheme, _, token = (authorization or "").partition(" ") + token = token.strip() + if scheme.lower() != "bearer" or not token: + raise HTTPException(401, "unauthorized", BEARER_CHALLENGE) + token_hash = hash_token(token) + + # 1. Кэш Redis (если доступен) + cached = cache.get_session(token_hash) + if cached == cache.REVOKED: + raise HTTPException(401, "unauthorized", BEARER_CHALLENGE) + # The source of truth is consulted even on cache hit, ensuring immediate revocation. + + # 2. Промах или Redis недоступен -> источник истины PostgreSQL + with db.pool.connection() as conn: + row = conn.execute( + """ + SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at + FROM sessions s + JOIN users u ON u.id = s.user_id + WHERE s.token_hash = %s + AND s.revoked_at IS NULL + AND s.expires_at > now() + """, + (token_hash,), + ).fetchone() + if row is None: + raise HTTPException(401, "unauthorized", BEARER_CHALLENGE) + user = user_from_row(row) + cache.put_session(token_hash, user.model_dump(), row["expires_at"]) + return {"user": user, "token_hash": token_hash} + + +def current_user(session: dict = Depends(current_session)) -> User: + return session["user"] + + +app.include_router(attachment_router(current_user, is_member, parse_uuid, iso)) + + +# ---------- Health ---------- + +@app.get("/health/live") +def liveness(): + return {"status": "ok"} + + +@app.get("/health/ready") +def readiness(): + try: + with db.pool.connection(timeout=2) as conn: + conn.execute("SELECT 1") + S3.head_bucket(Bucket=BUCKET) + except Exception: + raise HTTPException(503, "database unavailable") + return {"status": "ok"} + + +# ---------- Пользователи и сессии ---------- + +@app.post("/api/v1/users", status_code=201, response_model=User) +def register_user(payload: CreateUser): + password_hash = ph.hash(payload.password) + try: + with db.pool.connection() 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 + """, + (uuid.uuid4(), payload.username, payload.display_name, password_hash), + ).fetchone() + except errors.UniqueViolation: + # Гонку двух одинаковых регистраций разруливает UNIQUE в БД + raise HTTPException(409, "username already taken") + return user_from_row(row) + + +@app.post("/api/v1/auth/sessions", status_code=201, response_model=Session) +def create_session(authorization: str | None = Header(default=None)): + username, password = parse_basic(authorization) + + # A global DB-backed login budget is shared by all API replicas. + # Commit increments before expensive password hashing, including invalid passwords. + if len(username)>32 or len(password)>128: + raise HTTPException(401, "invalid credentials", BASIC_CHALLENGE) + with db.pool.connection() as conn: + limit_row=conn.execute("""INSERT INTO login_attempts(scope,window_start,attempts) + VALUES ('global',now(),1) ON CONFLICT(scope) DO UPDATE SET + attempts=CASE WHEN login_attempts.window_start120: + raise HTTPException(429,"login rate limited",headers={'Retry-After':'60'}) + + with db.pool.connection() as conn: + row = conn.execute( + """ + SELECT id, username, display_name, created_at, password_hash + FROM users WHERE username = %s + """, + (username,), + ).fetchone() + + # Проверка пароля вне соединения с БД: argon2 медленный, не держим соединение пула + if row is None: + check_password(DUMMY_HASH, password) + raise HTTPException(401, "invalid credentials", BASIC_CHALLENGE) + if not check_password(row["password_hash"], password): + raise HTTPException(401, "invalid credentials", BASIC_CHALLENGE) + + token = secrets.token_urlsafe(32) # 32 случайных байта = 256 бит + with db.pool.connection() as conn: + if ph.check_needs_rehash(row['password_hash']): + conn.execute('UPDATE users SET password_hash=%s WHERE id=%s',(ph.hash(password),row['id'])) + session = conn.execute( + """ + INSERT INTO sessions (token_hash, user_id, expires_at) + VALUES (%s, %s, now() + %s * interval '1 second') + RETURNING expires_at + """, + (hash_token(token), row["id"], SESSION_TTL_SECONDS), + ).fetchone() + + user = user_from_row(row) + # Сессия уже сохранена в PostgreSQL (COMMIT); кэш — только ускорение + cache.put_session(hash_token(token), user.model_dump(), session["expires_at"]) + return Session( + token=token, + token_type="Bearer", + expires_at=iso(session["expires_at"]), + user=user, + ) + + +@app.delete("/api/v1/auth/sessions/current", status_code=204) +def delete_session(session: dict = Depends(current_session)): + with db.pool.connection() as conn: + conn.execute( + "UPDATE sessions SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL", + (session["token_hash"],), + ) + # Сначала отзыв в источнике истины, потом "надгробие" в кэше + cache.revoke_session(session["token_hash"]) + return Response(status_code=204) + + +@app.get("/api/v1/users/me", response_model=User) +def get_me(me: User = Depends(current_user)): + return me + + +# ---------- Чаты ---------- + +@app.post("/api/v1/chats", status_code=201, response_model=Chat) +def create_chat(payload: CreateChat, me: User = Depends(current_user)): + member_ids = [parse_uuid(m, "member id") for m in payload.member_ids] + if len(set(member_ids)) != len(member_ids): + raise HTTPException(400, "member_ids must be unique") + if me.id not in member_ids: + raise HTTPException(400, "caller must be a member") + + chat_id = uuid.uuid4() + try: + with db.pool.connection() as conn: + # Атомарно: чат и все участники сохраняются вместе или не сохраняется ничего + with conn.transaction(): + chat = conn.execute( + "INSERT INTO chats (id, title) VALUES (%s, %s) RETURNING id, title, created_at", + (chat_id, payload.title), + ).fetchone() + with conn.cursor() as cur: + cur.executemany( + "INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)", + [(chat_id, m) for m in member_ids], + ) + except errors.ForeignKeyViolation: + # Неизвестный участник: транзакция откатилась, чата в БД нет + raise HTTPException(400, "unknown member") + + return Chat( + id=str(chat["id"]), + title=chat["title"], + member_ids=member_ids, + created_at=iso(chat["created_at"]), + ) + + +@app.get("/api/v1/chats", response_model=ChatPage) +def list_chats( + limit: int = Query(default=50, ge=1, le=100), + cursor: str | None = Query(default=None, min_length=1), + me: User = Depends(current_user), +): + scope = "chats:" + me.id + params: list = [me.id] + after = "" + if cursor is not None: + created_at, last_id = decode_cursor(cursor, scope) + after = "AND (c.created_at, c.id) > (%s, %s)" + params += [created_at, last_id] + params.append(limit + 1) # берём на 1 больше, чтобы понять, есть ли следующая страница + + with db.pool.connection() as conn: + rows = conn.execute( + f""" + SELECT c.id, c.title, c.created_at, + array_agg(m.user_id ORDER BY m.user_id) AS member_ids + FROM chat_members my + JOIN chats c ON c.id = my.chat_id + JOIN chat_members m ON m.chat_id = c.id + WHERE my.user_id = %s {after} + GROUP BY c.id + ORDER BY c.created_at, c.id + LIMIT %s + """, + params, + ).fetchall() + + next_cursor = None + if len(rows) > limit: + rows = rows[:limit] + next_cursor = encode_cursor(scope, rows[-1]["created_at"], rows[-1]["id"]) + return ChatPage(items=[chat_from_row(r) for r in rows], next_cursor=next_cursor) + + +@app.get("/api/v1/chats/{chat_id}", response_model=Chat) +def get_chat(chat_id: str, me: User = Depends(current_user)): + cid = parse_uuid(chat_id, "chat id") + with db.pool.connection() as conn: + if not is_member(conn, cid, me.id): + raise HTTPException(404, "chat not found") # чужой чат = как будто его нет + row = conn.execute( + """ + SELECT c.id, c.title, c.created_at, + array_agg(m.user_id ORDER BY m.user_id) AS member_ids + FROM chats c + JOIN chat_members m ON m.chat_id = c.id + WHERE c.id = %s + GROUP BY c.id + """, + (cid,), + ).fetchone() + return chat_from_row(row) + + +# ---------- Сообщения ---------- + +@app.post("/api/v1/chats/{chat_id}/messages", status_code=201, response_model=Message) +def create_message( + chat_id: str, + payload: CreateMessage, + me: User = Depends(current_user), + idempotency_key: str | None = Header(default=None), +): + cid = parse_uuid(chat_id, "chat id") + if not idempotency_key or not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", idempotency_key): + raise HTTPException(400, "invalid Idempotency-Key") + + path = f"/api/v1/chats/{cid}/messages" + request_hash = hashlib.sha256(json.dumps(payload.model_dump(), sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest() + message_id = uuid.uuid4() + scope = (me.id, "POST", path, idempotency_key) + + with db.pool.connection() as conn: + if not is_member(conn, cid, me.id): + raise HTTPException(404, "chat not found") + + if payload.attachment_ids: + available = conn.execute("SELECT id,status FROM attachments WHERE chat_id = %s AND status != 'pending' AND id = ANY(%s::uuid[])", + (cid, payload.attachment_ids)).fetchall() + if len(available) != len(payload.attachment_ids): + raise HTTPException(404, "attachment not found") + if any(a["status"] == "failed" for a in available): + raise HTTPException(409, "attachment failed") + + # Reserve the key atomically. A competing transaction waits at the unique index. + # Only expired keys may be replaced. The foreign key is checked at COMMIT. + claimed = conn.execute( + """ + INSERT INTO idempotency_keys + (user_id, method, path, key, request_hash, message_id, expires_at) + VALUES (%s, %s, %s, %s, %s, %s, clock_timestamp() + interval '24 hours') + ON CONFLICT (user_id, method, path, key) DO UPDATE + SET request_hash = EXCLUDED.request_hash, + message_id = EXCLUDED.message_id, + expires_at = clock_timestamp() + interval '24 hours' + WHERE idempotency_keys.expires_at <= clock_timestamp() + RETURNING message_id + """, + (*scope, request_hash, message_id), + ).fetchone() + + if claimed is None: + # The existing unexpired key belongs to an already committed message. + previous = conn.execute( + """ + SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at, m.attachment_ids + FROM idempotency_keys k JOIN messages m ON m.id = k.message_id + WHERE k.user_id = %s AND k.method = %s AND k.path = %s AND k.key = %s + """, + scope, + ).fetchone() + if previous["request_hash"] != request_hash: + raise HTTPException(409, "Idempotency-Key already used with another message") + return message_from_row(previous) + + row = conn.execute( + """ + INSERT INTO messages (id, chat_id, sender_id, text, attachment_ids) + VALUES (%s, %s, %s, %s, %s::uuid[]) + RETURNING id, chat_id, sender_id, text, created_at, attachment_ids + """, + (message_id, cid, me.id, payload.text, payload.attachment_ids), + ).fetchone() + return message_from_row(row) + + +@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage) +def list_messages( + chat_id: str, + limit: int = Query(default=50, ge=1, le=100), + cursor: str | None = Query(default=None, min_length=1), + me: User = Depends(current_user), +): + cid = parse_uuid(chat_id, "chat id") + scope = "messages:" + cid + params: list = [cid] + after = "" + if cursor is not None: + created_at, last_id = decode_cursor(cursor, scope) + # keyset-пагинация: продолжаем строго после последнего (created_at, id) + after = "AND (created_at, id) > (%s, %s)" + params += [created_at, last_id] + params.append(limit + 1) + + with db.pool.connection() as conn: + if not is_member(conn, cid, me.id): + raise HTTPException(404, "chat not found") + rows = conn.execute( + f""" + SELECT id, chat_id, sender_id, text, created_at, attachment_ids + FROM messages + WHERE chat_id = %s {after} + ORDER BY created_at, id + LIMIT %s + """, + params, + ).fetchall() + + next_cursor = None + if len(rows) > limit: + rows = rows[:limit] + next_cursor = encode_cursor(scope, rows[-1]["created_at"], rows[-1]["id"]) + return MessagePage(items=[message_from_row(r) for r in rows], next_cursor=next_cursor) diff --git a/attachments.py b/attachments.py new file mode 100644 index 00000000..64f862a7 --- /dev/null +++ b/attachments.py @@ -0,0 +1,154 @@ +"""Bounded image uploads, private S3 storage and authorized streaming downloads.""" +import asyncio +import hashlib +import os +import tempfile +import unicodedata +import uuid +import warnings + +import boto3 +from botocore.config import Config +from botocore.exceptions import BotoCoreError, ClientError +from fastapi import APIRouter, Depends, HTTPException, Query, Request +from fastapi.responses import StreamingResponse +from PIL import Image, UnidentifiedImageError +from starlette.concurrency import run_in_threadpool + +import db +import telemetry as ot +from psycopg.types.json import Jsonb + +MAX_BYTES = 10 * 1024 * 1024 +MAX_PIXELS = 40_000_000 +BUCKET = os.environ.get("S3_BUCKET", "attachments") +S3 = boto3.client("s3", endpoint_url=os.environ["S3_ENDPOINT"], + aws_access_key_id=os.environ["S3_ACCESS_KEY"], + aws_secret_access_key=os.environ["S3_SECRET_KEY"], + region_name="us-east-1", verify='/ca/ca.crt', config=Config(connect_timeout=2, read_timeout=5, + retries={"total_max_attempts": 2}, s3={"addressing_style": "path"})) +Image.MAX_IMAGE_PIXELS = MAX_PIXELS +UPLOAD_SLOTS = asyncio.Semaphore(1) + + +def inspect_image(file, mime): + try: + file.seek(0) + with warnings.catch_warnings(): + warnings.simplefilter("error", Image.DecompressionBombWarning) + with Image.open(file) as image: + if image.width * image.height > MAX_PIXELS: + raise HTTPException(413, "too many pixels") + if {"PNG": "image/png", "JPEG": "image/jpeg"}.get(image.format) != mime: + raise HTTPException(415, "invalid image type") + image.verify() + file.seek(0) + with Image.open(file) as image: + image.load() + except (Image.DecompressionBombError, Image.DecompressionBombWarning): + raise HTTPException(413, "too many pixels") from None + except (UnidentifiedImageError, OSError, ValueError, SyntaxError): + raise HTTPException(415, "invalid image") from None + file.seek(0) + + +def store(file, cid, user_id, filename, mime, size, checksum, is_member): + inspect_image(file, mime) + aid = uuid.uuid4() + key = f"staging/{aid}" + # Commit intent before external write, so even a killed process leaves a tracked pending row. + with db.pool.connection() as conn: + if not is_member(conn, cid, user_id): + raise HTTPException(404, "chat not found") + conn.execute("""INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key,status) + VALUES (%s,%s,%s,%s,%s,%s,%s,%s,'pending')""", + (aid, cid, user_id, filename, mime, size, checksum, key)) + with db.pool.connection() as conn: + conn.execute("SELECT id FROM attachments WHERE id=%s FOR UPDATE", (aid,)).fetchone() + try: + S3.put_object(Bucket=BUCKET, Key=key, Body=file, ContentLength=size, ContentType=mime) + except (BotoCoreError, ClientError): + raise HTTPException(503, "storage unavailable") from None + conn.execute("INSERT INTO attachment_jobs(id,trace_context) VALUES (%s,%s)", (aid,Jsonb(ot.carrier()))) + return conn.execute("UPDATE attachments SET status='queued', updated_at=now() WHERE id=%s RETURNING *", (aid,)).fetchone() + + +def router(current_user, is_member, parse_uuid, iso): + routes = APIRouter() + + def metadata(row): + return {**{k: str(row[k]) for k in ("id", "chat_id", "owner_id")}, + **{k: row[k] for k in ("filename", "content_type", "size_bytes", "sha256", "status")}, + "created_at": iso(row["created_at"]), "updated_at": iso(row["updated_at"]), + "variants": row["variants"], "error_code": row["error_code"]} + + def authorized(aid, me): + aid = parse_uuid(aid, "attachment id") + with db.pool.connection() as conn: + row = conn.execute("SELECT * FROM attachments WHERE id=%s AND status!='pending'", (aid,)).fetchone() + if not row or not is_member(conn, row["chat_id"], me.id): + raise HTTPException(404, "attachment not found") + return row + + @routes.post("/api/v1/chats/{chat_id}/attachments", status_code=202) + async def upload(chat_id: str, request: Request, filename: str = Query(...), me=Depends(current_user)): + cid = parse_uuid(chat_id, "chat id") + def check_member(): + with db.pool.connection() as conn: + if not is_member(conn, cid, me.id): + raise HTTPException(404, "chat not found") + await run_in_threadpool(check_member) + if not 1 <= len(filename) <= 255 or not filename.strip() or any(c in "/\\" or unicodedata.category(c) == "Cc" for c in filename): + raise HTTPException(400, "invalid filename") + mime = request.headers.get("content-type", "").split(";", 1)[0].lower() + if mime not in ("image/png", "image/jpeg"): + raise HTTPException(415, "unsupported media type") + size = 0 + digest = hashlib.sha256() + async with UPLOAD_SLOTS: + with tempfile.TemporaryFile() as file: + try: + async with asyncio.timeout(30): + async for chunk in request.stream(): + size += len(chunk) + if size > MAX_BYTES: + raise HTTPException(413, "upload too large") + file.write(chunk) + digest.update(chunk) + except TimeoutError: + raise HTTPException(400, "upload timed out") from None + if not size: + raise HTTPException(415, "empty image") + row = await run_in_threadpool(store, file, cid, me.id, filename, mime, size, digest.hexdigest(), is_member) + return metadata(row) + + @routes.get("/api/v1/attachments/{attachment_id}") + def get_attachment(attachment_id: str, me=Depends(current_user)): + return metadata(authorized(attachment_id, me)) + + @routes.get("/api/v1/attachments/{attachment_id}/content") + def download(attachment_id: str, variant: str = "original", me=Depends(current_user)): + row = authorized(attachment_id, me) + if row["status"] != "ready": + raise HTTPException(409, "attachment not ready") + if variant == "original": + key, mime, size = row["object_key"], row["content_type"], row["size_bytes"] + else: + info = next((v for v in row["variants"] if v["name"] == variant), None) + if info is None: + raise HTTPException(404, "variant not found") + key, mime, size = f"variants/{row['id']}/{variant}", info["content_type"], info["size_bytes"] + try: + body = S3.get_object(Bucket=BUCKET, Key=key)["Body"] + except (BotoCoreError, ClientError): + raise HTTPException(503, "storage unavailable") from None + + def stream(): + try: + yield from body.iter_chunks(chunk_size=64 * 1024) + finally: + body.close() + + return StreamingResponse(stream(), media_type=mime, headers={"Content-Length": str(size)}) + + return routes diff --git a/cache.py b/cache.py new file mode 100644 index 00000000..14917f5f --- /dev/null +++ b/cache.py @@ -0,0 +1,123 @@ +"""Кэш сессий в Redis. + +Источник истины для сессий — PostgreSQL (таблица sessions). Redis только ускоряет +проверку Bearer-токена, чтобы не ходить в БД на каждый запрос. + +Политика: +- ключ session:; значение — JSON {user, expires_at}; +- TTL записи = min(оставшаяся жизнь сессии, SESSION_CACHE_MAX_TTL), поэтому кэш + никогда не продлевает сессию и устаревшая запись живёт не дольше SESSION_CACHE_MAX_TTL; +- logout: сначала revoked_at в PostgreSQL, затем в Redis пишется "надгробие" revoked + (SET без NX), а заполнение кэша идёт через SET NX — параллельный запрос не может + перезаписать надгробие старым "живым" значением; +- Redis недоступен: запрос идёт напрямую в PostgreSQL (обход кэша). Фоновый поток + раз в PROBE_INTERVAL секунд делает PING; пока Redis "лежит", запросы его не трогают + и не тратят время на таймауты/DNS. +""" +import json +import logging +import os +import threading +import time +from datetime import datetime, timezone + +import redis + +from db import read_setting + +log = logging.getLogger("messenger.cache") + +REDIS_URL = read_setting("REDIS_URL") +CACHE_MAX_TTL = int(os.environ.get("SESSION_CACHE_MAX_TTL", "60")) +PROBE_INTERVAL = 2.0 +REVOKED = "revoked" + +_client = ( + redis.Redis.from_url( + REDIS_URL, + socket_timeout=0.3, + socket_connect_timeout=0.3, + ssl_ca_certs='/ca/ca.crt', + ssl_check_hostname=True, + decode_responses=True, + ) + if REDIS_URL + else None +) +_healthy = False # до первого успешного PING кэш не используется + + +def _key(token_hash: str) -> str: + return "session:" + token_hash + + +def _available() -> bool: + return _client is not None and _healthy + + +def _mark_down(exc: Exception) -> None: + global _healthy + if _healthy: + log.warning("redis unavailable, bypassing session cache: %s", type(exc).__name__) + _healthy = False + + +def _probe_loop() -> None: + global _healthy + while True: + try: + _client.ping() + if not _healthy: + log.info("redis available, session cache enabled") + _healthy = True + except redis.RedisError as exc: + _mark_down(exc) + except Exception as exc: # например, ошибка DNS, пока контейнер redis остановлен + _mark_down(exc) + time.sleep(PROBE_INTERVAL) + + +def start() -> None: + if _client is not None: + threading.Thread(target=_probe_loop, name="redis-probe", daemon=True).start() + + +def get_session(token_hash: str): + if not _available(): + return None + try: + raw = _client.get(_key(token_hash)) + except redis.RedisError as exc: + _mark_down(exc) + return None + if raw is None: + return None + if raw == REVOKED: + return REVOKED + data = json.loads(raw) + if datetime.fromisoformat(data["expires_at"]) <= datetime.now(timezone.utc): + return None # страховка: истёкшую запись не используем + return data + + +def put_session(token_hash: str, user: dict, expires_at: datetime) -> None: + if not _available(): + return + remaining = int((expires_at - datetime.now(timezone.utc)).total_seconds()) + ttl = min(remaining, CACHE_MAX_TTL) + if ttl <= 0: + return + value = json.dumps({"user": user, "expires_at": expires_at.isoformat()}) + try: + _client.set(_key(token_hash), value, ex=ttl, nx=True) + except redis.RedisError as exc: + _mark_down(exc) + + +def revoke_session(token_hash: str) -> None: + if not _available(): + return + try: + _client.set(_key(token_hash), REVOKED, ex=CACHE_MAX_TTL) + except redis.RedisError as exc: + _mark_down(exc) diff --git a/cleanup.py b/cleanup.py new file mode 100644 index 00000000..47fd7f33 --- /dev/null +++ b/cleanup.py @@ -0,0 +1,28 @@ +"""Recover abandoned upload intents older than one hour; never delete ready files.""" +import time +import db +from attachments import S3, BUCKET + + +def sweep(): + with db.pool.connection() as conn: + rows = conn.execute("""SELECT id,object_key FROM attachments WHERE status='pending' + AND created_at < now() - interval '1 hour' + FOR UPDATE SKIP LOCKED LIMIT 50""").fetchall() + for row in rows: + S3.delete_object(Bucket=BUCKET, Key=row['object_key']) + conn.execute("DELETE FROM attachments WHERE id=%s", (row['id'],)) + ready = conn.execute("SELECT id FROM attachments WHERE NOT staging_cleaned AND ((status='ready' AND updated_at < now()-interval '1 hour') OR (status='failed' AND updated_at < now()-interval '7 days')) LIMIT 100 FOR UPDATE SKIP LOCKED").fetchall() + for row in ready: + S3.delete_object(Bucket=BUCKET,Key=f"staging/{row['id']}") + conn.execute("UPDATE attachments SET staging_cleaned=TRUE WHERE id=%s",(row['id'],)) + + +if __name__ == '__main__': + db.pool.open(wait=True, timeout=30) + while True: + try: + sweep() + except Exception: + print('cleanup deferred; will retry', flush=True) + time.sleep(60) diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..f3a146fa --- /dev/null +++ b/compose.yaml @@ -0,0 +1,428 @@ +name: messenger-lab7 + +x-app: &app + image: messenger:lab7 + build: . + read_only: true + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + tmpfs: ["/tmp:size=64m,mode=1777"] + environment: &app-env + BAO_ROLE: api + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + SESSION_CACHE_MAX_TTL: ${SESSION_CACHE_MAX_TTL:-60} + DB_POOL_MAX: ${DB_POOL_MAX:-10} + S3_ENDPOINT: https://minio:9000 + S3_BUCKET: attachments + JOB_MAX_ATTEMPTS: 5 + OTEL_EXPORTER_OTLP_ENDPOINT: https://collector:4319 + OTEL_SERVICE_NAME: messenger-api + +services: + postgres: + image: postgres:17.6-alpine + entrypoint: ["/bin/sh", "/pg-start.sh"] + environment: + POSTGRES_USER: ${POSTGRES_USER} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} + POSTGRES_DB: ${POSTGRES_DB} + API_DB_PASSWORD: ${API_DB_PASSWORD} + WORKER_DB_PASSWORD: ${WORKER_DB_PASSWORD} + DISPATCHER_DB_PASSWORD: ${DISPATCHER_DB_PASSWORD} + CLEANUP_DB_PASSWORD: ${CLEANUP_DB_PASSWORD} + volumes: + - pgdata:/var/lib/postgresql/data + - ./infra/pg-start.sh:/pg-start.sh:ro + - ./infra/pg_hba.conf:/etc/pg_hba.conf:ro + - ./infra/db-roles.sh:/docker-entrypoint-initdb.d/001_roles.sh:ro + - ./certs/private/postgres:/tls:ro + healthcheck: + test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"] + interval: 3s + timeout: 2s + retries: 10 + cpus: 2.0 + mem_limit: 1g + restart: unless-stopped + + redis: + image: redis:7.4.2-alpine + command: ["redis-server", "--port", "0", "--tls-port", "6379", "--tls-cert-file", "/tls/tls.crt", "--tls-key-file", "/tls/tls.key", "--tls-ca-cert-file", "/ca/ca.crt", "--tls-auth-clients", "no", "--requirepass", "${REDIS_PASSWORD}", "--save", "", "--appendonly", "no", "--maxmemory", "64mb", "--maxmemory-policy", "allkeys-lru"] + volumes: + - ./certs/private/redis:/tls:ro + - ./certs/private/ca.crt:/ca/ca.crt:ro + healthcheck: + test: ["CMD", "redis-cli", "--tls", "--cacert", "/ca/ca.crt", "-a", "${REDIS_PASSWORD}", "ping"] + interval: 3s + timeout: 2s + retries: 10 + cpus: 0.5 + mem_limit: 128m + restart: unless-stopped + + migrate: + <<: *app + environment: + <<: *app-env + BAO_ROLE: migrate + volumes: + - ./certs/private/ca.crt:/ca/ca.crt:ro + - ./certs/private/migrate-client:/identity:ro + command: ["python", "migrate.py"] + depends_on: + postgres: + condition: service_healthy + healthcheck: + disable: true + cpus: 0.5 + mem_limit: 256m + restart: "no" + + api: + <<: *app + volumes: + - ./certs/private/api:/tls:ro + - ./certs/private/ca.crt:/ca/ca.crt:ro + - ./certs/private/api-client:/identity:ro + - ./certs/private/public-pins:/pins:ro + scale: ${API_REPLICAS:-2} + depends_on: + migrate: + condition: service_completed_successfully + s3-init: + condition: service_completed_successfully + cpus: ${API_CPUS:-1.0} + mem_limit: ${API_MEMORY:-512m} + stop_grace_period: 15s + restart: unless-stopped + + minio: + image: messenger-minio:2025-04 + pull_policy: never + build: + context: . + dockerfile: infra/Dockerfile.minio + command: ["server", "/data", "--certs-dir", "/certs", "--console-address", ":9001"] + environment: + MINIO_ROOT_USER: ${MINIO_ROOT_USER} + MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD} + volumes: + - s3data:/data + - ./certs/private/minio/tls.crt:/certs/public.crt:ro + - ./certs/private/minio/tls.key:/certs/private.key:ro + cpus: 1.0 + mem_limit: 768m + restart: unless-stopped + + s3-init: + image: messenger-minio:2025-04 + pull_policy: never + build: + context: . + dockerfile: infra/Dockerfile.minio + entrypoint: ["/bin/sh", "/init.sh"] + environment: + MINIO_ROOT_USER: ${MINIO_ROOT_USER} + MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD} + S3_ACCESS_KEY: ${S3_ACCESS_KEY} + S3_SECRET_KEY: ${S3_SECRET_KEY} + WORKER_S3_ACCESS_KEY: ${WORKER_S3_ACCESS_KEY} + WORKER_S3_SECRET_KEY: ${WORKER_S3_SECRET_KEY} + CLEANUP_S3_ACCESS_KEY: ${CLEANUP_S3_ACCESS_KEY} + CLEANUP_S3_SECRET_KEY: ${CLEANUP_S3_SECRET_KEY} + volumes: + - ./infra/s3-init.sh:/init.sh:ro + - ./infra/s3-policy.json:/policy.json:ro + - ./infra/s3-worker-policy.json:/worker-policy.json:ro + - ./infra/s3-cleanup-policy.json:/cleanup-policy.json:ro + - ./certs/private/ca.crt:/root/.mc/certs/CAs/lab.crt:ro + depends_on: + minio: + condition: service_started + restart: "no" + + cleanup: + <<: *app + volumes: + - ./certs/private/ca.crt:/ca/ca.crt:ro + - ./certs/private/cleanup-client:/identity:ro + environment: + <<: *app-env + OTEL_SERVICE_NAME: messenger-cleanup + BAO_ROLE: cleanup + command: ["python", "cleanup.py"] + healthcheck: + disable: true + depends_on: + migrate: + condition: service_completed_successfully + s3-init: + condition: service_completed_successfully + cpus: 0.25 + mem_limit: 256m + restart: unless-stopped + + broker: + image: redis:7.4.2-alpine + command: ["redis-server", "--bind", "127.0.0.1", "--port", "6378", "--aclfile", "/run/secrets/broker.acl", "--appendonly", "yes", "--appendfsync", "always", "--maxmemory-policy", "noeviction"] + volumes: + - brokerdata:/data + - ./secrets/broker.acl:/run/secrets/broker.acl:ro + healthcheck: + test: ["CMD-SHELL", "redis-cli -p 6378 ping | grep -q NOAUTH"] + interval: 3s + timeout: 2s + retries: 10 + cpus: 0.5 + mem_limit: 256m + restart: unless-stopped + + dispatcher: + <<: *app + volumes: + - ./certs/private/ca.crt:/ca/ca.crt:ro + - ./certs/private/dispatcher-client:/identity:ro + environment: + <<: *app-env + OTEL_SERVICE_NAME: messenger-dispatcher + BAO_ROLE: dispatcher + command: ["python", "pipeline.py"] + healthcheck: + disable: true + depends_on: + migrate: + condition: service_completed_successfully + broker: + condition: service_healthy + cpus: 0.5 + mem_limit: 256m + restart: unless-stopped + + worker: + <<: *app + volumes: + - ./certs/private/ca.crt:/ca/ca.crt:ro + - ./certs/private/worker-client:/identity:ro + environment: + <<: *app-env + OTEL_SERVICE_NAME: messenger-worker + BAO_ROLE: worker + command: ["python", "worker.py"] + healthcheck: + disable: true + depends_on: + migrate: + condition: service_completed_successfully + s3-init: + condition: service_completed_successfully + broker: + condition: service_healthy + cpus: 1.0 + mem_limit: 1024m + restart: unless-stopped + + openbao: + image: quay.io/openbao/openbao:2.2.2 + command: ["server", "-config=/bao/config/config.hcl"] + ports: ["127.0.0.1:8200:8200"] + volumes: + - ./infra/openbao.hcl:/bao/config/config.hcl:ro + - ./certs/private/openbao:/tls:ro + - ./certs/private/ca.crt:/ca/ca.crt:ro + - baodata:/openbao/file + cpus: 0.5 + mem_limit: 256m + restart: unless-stopped + + broker-tls: + image: python:3.11.9-slim + network_mode: service:broker + command: ["python", "/tls_proxy.py"] + environment: + TLS_LISTEN_PORT: 6379 + TLS_BACKEND_PORT: 6378 + TLS_ALLOWED_IDENTITIES: dispatcher-client,worker-client + volumes: + - ./tls_proxy.py:/tls_proxy.py:ro + - ./certs/private/broker:/tls:ro + - ./certs/private/ca.crt:/ca/ca.crt:ro + - ./certs/private/public-pins:/pins:ro + depends_on: + broker: + condition: service_healthy + restart: true + restart: unless-stopped + mem_limit: 128m + cpus: 0.5 + + collector-tls: + image: python:3.11.9-slim + network_mode: service:collector + command: ["python", "/tls_proxy.py"] + environment: + TLS_LISTEN_PORT: 4319 + TLS_BACKEND_PORT: 4318 + TLS_ALLOWED_IDENTITIES: api-client,worker-client,dispatcher-client,cleanup-client,migrate-client + volumes: + - ./tls_proxy.py:/tls_proxy.py:ro + - ./certs/private/collector:/tls:ro + - ./certs/private/ca.crt:/ca/ca.crt:ro + - ./certs/private/public-pins:/pins:ro + restart: unless-stopped + mem_limit: 128m + cpus: 0.5 + + collector: + image: otel/opentelemetry-collector-contrib:0.123.0 + command: ["--config=/etc/otel/config.yaml"] + volumes: + - ./infra/otel.yaml:/etc/otel/config.yaml:ro + - ./certs/private/ca.crt:/ca/ca.crt:ro + - ./certs/private/collector-client:/identity:ro + mem_limit: 256m + cpus: 0.5 + restart: unless-stopped + + prometheus: + image: prom/prometheus:v3.2.1 + command: ["--config.file=/etc/prometheus/prometheus.yml", "--storage.tsdb.path=/prometheus", "--web.config.file=/etc/prometheus/web.yml"] + volumes: + - ./infra/prometheus.yml:/etc/prometheus/prometheus.yml:ro + - ./infra/alerts.yml:/etc/prometheus/alerts.yml:ro + - ./infra/prometheus-web.yml:/etc/prometheus/web.yml:ro + - ./certs/private/prometheus:/tls:ro + - ./certs/private/prometheus-client:/identity:ro + - ./certs/private/ca.crt:/ca/ca.crt:ro + - promdata:/prometheus + mem_limit: 512m + cpus: 0.5 + restart: unless-stopped + + loki: + image: grafana/loki:3.4.2 + command: ["-config.file=/etc/loki/local-config.yaml"] + volumes: + - ./infra/loki.yaml:/etc/loki/local-config.yaml:ro + - lokidata:/loki + mem_limit: 512m + cpus: 0.5 + restart: unless-stopped + + tempo: + image: grafana/tempo:2.7.2 + command: ["-config.file=/etc/tempo.yaml"] + volumes: + - ./infra/tempo.yaml:/etc/tempo.yaml:ro + - tempodata:/var/tempo + mem_limit: 512m + cpus: 0.5 + restart: unless-stopped + + grafana: + image: grafana/grafana:11.6.0 + ports: ["127.0.0.1:${GRAFANA_PORT:-3000}:3000"] + environment: + GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_PASSWORD} + GF_USERS_ALLOW_SIGN_UP: "false" + GF_SERVER_PROTOCOL: https + GF_SERVER_CERT_FILE: /tls/tls.crt + GF_SERVER_CERT_KEY: /tls/tls.key + volumes: + - ./infra/grafana/provisioning/dashboards:/etc/grafana/provisioning/dashboards:ro + - ./secrets/grafana-datasources:/etc/grafana/provisioning/datasources:ro + - ./certs/private/grafana:/tls:ro + - ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro + - grafanadata:/var/lib/grafana + mem_limit: 512m + cpus: 0.5 + restart: unless-stopped + + collector-scrape-tls: + image: python:3.11.9-slim + network_mode: service:collector + command: ["python", "/tls_proxy.py"] + environment: + TLS_LISTEN_PORT: 8890 + TLS_BACKEND_PORT: 8889 + TLS_ALLOWED_IDENTITIES: prometheus-client + volumes: + - ./tls_proxy.py:/tls_proxy.py:ro + - ./certs/private/collector:/tls:ro + - ./certs/private/ca.crt:/ca/ca.crt:ro + restart: unless-stopped + mem_limit: 128m + cpus: 0.25 + + loki-tls: + image: python:3.11.9-slim + network_mode: service:loki + command: ["python", "/tls_proxy.py"] + environment: + TLS_LISTEN_PORT: 3101 + TLS_BACKEND_PORT: 3100 + TLS_ALLOWED_IDENTITIES: collector-client,grafana-client + volumes: + - ./tls_proxy.py:/tls_proxy.py:ro + - ./certs/private/loki:/tls:ro + - ./certs/private/ca.crt:/ca/ca.crt:ro + restart: unless-stopped + mem_limit: 128m + cpus: 0.25 + + tempo-query-tls: + image: python:3.11.9-slim + network_mode: service:tempo + command: ["python", "/tls_proxy.py"] + environment: + TLS_LISTEN_PORT: 3201 + TLS_BACKEND_PORT: 3200 + TLS_ALLOWED_IDENTITIES: grafana-client + volumes: + - ./tls_proxy.py:/tls_proxy.py:ro + - ./certs/private/tempo:/tls:ro + - ./certs/private/ca.crt:/ca/ca.crt:ro + restart: unless-stopped + mem_limit: 128m + cpus: 0.25 + + tempo-ingest-tls: + image: python:3.11.9-slim + network_mode: service:tempo + command: ["python", "/tls_proxy.py"] + environment: + TLS_LISTEN_PORT: 4319 + TLS_BACKEND_PORT: 4318 + TLS_ALLOWED_IDENTITIES: collector-client + volumes: + - ./tls_proxy.py:/tls_proxy.py:ro + - ./certs/private/tempo:/tls:ro + - ./certs/private/ca.crt:/ca/ca.crt:ro + restart: unless-stopped + mem_limit: 128m + cpus: 0.25 + + nginx: + image: nginx:1.28.0-alpine + ports: + - "127.0.0.1:8443:443" + volumes: + - ./infra/nginx.conf:/etc/nginx/nginx.conf:ro + - ./certs/private/ingress:/ingress:ro + - ./certs/private/lb-client:/client:ro + - ./certs/private/ca.crt:/ca/ca.crt:ro + depends_on: + api: + condition: service_healthy + cpus: 0.5 + mem_limit: 128m + restart: unless-stopped + +volumes: + pgdata: + s3data: + brokerdata: + promdata: + lokidata: + tempodata: + grafanadata: + baodata: diff --git a/db.py b/db.py new file mode 100644 index 00000000..5773f00c --- /dev/null +++ b/db.py @@ -0,0 +1,76 @@ +import os +from pathlib import Path + +from psycopg.rows import dict_row +from psycopg_pool import ConnectionPool +from contextlib import contextmanager +import telemetry as ot + + +class TracedPool(ConnectionPool): + @contextmanager + def connection(self, *args, **kwargs): + with ot.tracer.start_as_current_span("postgres transaction"): + with super().connection(*args, **kwargs) as conn: + yield conn + + +def read_setting(name: str, default: str | None = None) -> str | None: + # NAME_FILE (путь к docker secret) имеет приоритет над NAME + path = os.environ.get(name + "_FILE") + if path: + return Path(path).read_text(encoding="utf-8").strip() + return os.environ.get(name, default) + + +DATABASE_URL = read_setting("DATABASE_URL") +if not DATABASE_URL: + raise RuntimeError("DATABASE_URL or DATABASE_URL_FILE must be set") + +# Ограниченный пул соединений: не больше 10 одновременно, ждать свободное не дольше 5 сек +pool = TracedPool( + conninfo=DATABASE_URL, + min_size=1, + max_size=int(os.environ.get("DB_POOL_MAX", "10")), + timeout=5, + open=False, + # Перед выдачей соединения проверяем, что оно живо (важно после рестарта БД) + check=ConnectionPool.check_connection, + kwargs={ + "row_factory": dict_row, # строки как dict: row["id"] + "connect_timeout": 5, # таймаут подключения к БД, сек + "options": "-c statement_timeout=5000", # любой SQL-запрос не дольше 5 сек + }, +) + +MIGRATIONS_DIR = Path(__file__).parent / "migrations" +MIGRATION_LOCK_ID = 2026_02 # произвольный номер advisory lock для миграций + + +def run_migrations(): + with pool.connection() as conn: + # Всё в одной транзакции: либо применяются все новые миграции, либо ни одна + with conn.transaction(): + # Если стартуют несколько реплик API, миграции применяет только одна, остальные ждут + conn.execute("SELECT pg_advisory_xact_lock(%s)", (MIGRATION_LOCK_ID,)) + # Таблица, где записано, какие миграции уже применены + conn.execute(""" + CREATE TABLE IF NOT EXISTS schema_migrations ( + version TEXT PRIMARY KEY, + applied_at TIMESTAMPTZ NOT NULL DEFAULT now() + ) + """) + + for file in sorted(MIGRATIONS_DIR.glob("*.sql")): + version = file.name + already = conn.execute( + "SELECT 1 FROM schema_migrations WHERE version = %s", (version,) + ).fetchone() + if already: + continue # уже применена: пропускаем + + conn.execute(file.read_text(encoding="utf-8")) + conn.execute( + "INSERT INTO schema_migrations (version) VALUES (%s)", (version,) + ) + print(f"applied migration {version}", flush=True) diff --git a/evidence/bao-checks.txt b/evidence/bao-checks.txt new file mode 100644 index 00000000..2c80d4a2 --- /dev/null +++ b/evidence/bao-checks.txt @@ -0,0 +1,6 @@ + Container messenger-lab7-openbao-1 Restarting + Container messenger-lab7-openbao-1 Started +PASS: sealed OpenBao refuses service authentication +OpenBao initialized/unsealed; per-service scoped secrets installed. Operator state kept locally. +PASS: api can read only its own secrets, with a limited token TTL +PASS: worker can read only its own secrets, with a limited token TTL diff --git a/evidence/bao-policy.json b/evidence/bao-policy.json new file mode 100644 index 00000000..c90acd66 --- /dev/null +++ b/evidence/bao-policy.json @@ -0,0 +1,8 @@ +{ + "scoped_roles": [ + "api", + "worker" + ], + "maximum_token_ttl_seconds": 900, + "sealed_authentication_rejected": true +} diff --git a/evidence/build.txt b/evidence/build.txt new file mode 100644 index 00000000..8ab56b2f --- /dev/null +++ b/evidence/build.txt @@ -0,0 +1,185 @@ + Image messenger:lab7 Building + Image messenger-minio:2025-04 Building + Image messenger:lab7 Building + Image messenger:lab7 Building + Image messenger-minio:2025-04 Building + Image messenger:lab7 Building + Image messenger:lab7 Building +#1 [internal] load local bake definitions +#1 reading from stdin 3.48kB 0.0s done +#1 DONE 0.0s + +#2 [s3-init internal] load build definition from Dockerfile.minio +#2 transferring dockerfile: 531B done +#2 DONE 0.0s + +#3 [cleanup internal] load build definition from Dockerfile +#3 transferring dockerfile: 869B done +#3 DONE 0.0s + +#4 [dispatcher internal] load metadata for docker.io/library/python:3.11.9-slim +#4 DONE 0.6s + +#5 [minio internal] load metadata for docker.io/library/alpine:3.21.3 +#5 DONE 0.6s + +#6 [s3-init internal] load metadata for docker.io/library/golang:1.24.3-alpine +#6 DONE 0.6s + +#7 [api internal] load .dockerignore +#7 transferring context: 216B done +#7 DONE 0.0s + +#8 [minio builder 1/4] FROM docker.io/library/golang:1.24.3-alpine@sha256:b4f875e650466fa0fe62c6fd3f02517a392123eea85f1d7e69d85f780e4db1c1 +#8 resolve docker.io/library/golang:1.24.3-alpine@sha256:b4f875e650466fa0fe62c6fd3f02517a392123eea85f1d7e69d85f780e4db1c1 0.0s done +#8 DONE 0.0s + +#9 [s3-init stage-1 1/3] FROM docker.io/library/alpine:3.21.3@sha256:a8560b36e8b8210634f77d9f7f9efd7ffa463e380b75e2e74aff4511df3ef88c +#9 resolve docker.io/library/alpine:3.21.3@sha256:a8560b36e8b8210634f77d9f7f9efd7ffa463e380b75e2e74aff4511df3ef88c 0.0s done +#9 DONE 0.0s + +#10 [s3-init builder 3/4] RUN go install github.com/minio/minio@RELEASE.2025-04-22T22-12-26Z +#10 CACHED + +#11 [s3-init stage-1 2/3] RUN apk add --no-cache ca-certificates +#11 CACHED + +#12 [s3-init builder 4/4] RUN go install github.com/minio/mc@RELEASE.2025-04-16T18-13-26Z +#12 CACHED + +#13 [s3-init builder 2/4] RUN apk add --no-cache git ca-certificates +#13 CACHED + +#14 [s3-init stage-1 3/3] COPY --from=builder /go/bin/minio /go/bin/mc /usr/local/bin/ +#14 CACHED + +#15 [cleanup 1/7] FROM docker.io/library/python:3.11.9-slim@sha256:8fb099199b9f2d70342674bd9dbccd3ed03a258f26bbd1d556822c6dfc60c317 +#15 resolve docker.io/library/python:3.11.9-slim@sha256:8fb099199b9f2d70342674bd9dbccd3ed03a258f26bbd1d556822c6dfc60c317 0.0s done +#15 DONE 0.0s + +#16 [s3-init] exporting to image +#16 exporting layers done +#16 exporting manifest sha256:2fd7e37631ae469ed2c1c6e11d50b54a9724c46071a6b28ff26a4da068804737 0.0s done +#16 exporting config sha256:c5c43b9d9410d62b60ba951f90eef59a3406e976ac3dd1c3ea5061372f32b81b +#16 ... + +#17 [api internal] load build context +#17 transferring context: 66.29kB 0.1s done +#17 DONE 0.1s + +#18 [migrate 2/7] WORKDIR /app +#18 CACHED + +#19 [migrate 3/7] COPY requirements.txt . +#19 CACHED + +#20 [migrate 4/7] RUN pip install --no-cache-dir -r requirements.txt +#20 CACHED + +#16 [s3-init] exporting to image +#16 exporting config sha256:c5c43b9d9410d62b60ba951f90eef59a3406e976ac3dd1c3ea5061372f32b81b 0.0s done +#16 exporting attestation manifest sha256:6cd62c8e720798ae35f41f3a1f84ed4b151c91d57daf271812aa32c8d31ece67 0.0s done +#16 exporting manifest list sha256:6d9e7370358f1ace50f31220d4ab9e32eb650bf18371ed45847730844be4c99f 0.0s done +#16 naming to docker.io/library/messenger-minio:2025-04 done +#16 unpacking to docker.io/library/messenger-minio:2025-04 +#16 unpacking to docker.io/library/messenger-minio:2025-04 0.0s done +#16 DONE 0.2s + +#21 [minio] exporting to image +#21 exporting layers done +#21 exporting manifest sha256:6bfa55128913c1de6e9034a0cf1dd509e2c1ed50d7515dba0bb48582ec0ca5f8 0.0s done +#21 exporting config sha256:4a45bbba00b8d8630ab95aa81906115f3de0be77fc88efed9cda1fae816c9682 0.0s done +#21 exporting attestation manifest sha256:4218bddea154936187f2b5a2589619d77f228b3b85127a128813df2de9d33b39 0.0s done +#21 exporting manifest list sha256:f83dadad78625cf9b995d83e791a3137d1423884c84aa6129997eb9d458a0237 0.0s done +#21 naming to docker.io/library/messenger-minio:2025-04 done +#21 unpacking to docker.io/library/messenger-minio:2025-04 done +#21 DONE 0.1s + +#22 [dispatcher 5/7] COPY app.py schemas.py db.py cache.py migrate.py attachments.py cleanup.py pipeline.py worker.py telemetry.py tls_proxy.py api_start.py secret_entry.py ./ +#22 DONE 0.1s + +#23 [cleanup 6/7] COPY migrations ./migrations +#23 DONE 0.1s + +#24 [minio] resolving provenance for metadata file +#24 DONE 0.0s + +#25 [s3-init] resolving provenance for metadata file +#25 DONE 0.0s + +#26 [migrate 7/7] RUN useradd --create-home --shell /bin/bash appuser +#26 DONE 0.4s + +#27 [cleanup] exporting to image +#27 exporting layers 0.2s done +#27 exporting manifest sha256:9461d00b4d5f8ae2c8bba1b86d27b53af94d8c2d0abc57f52552561f54443c30 0.0s done +#27 exporting config sha256:184ff2f5b391996ac2906d7c7b05be7ee03fdb74bb82eea0434c07a5a9e612d3 0.0s done +#27 exporting attestation manifest sha256:4758c46bb83d893312672bb4fbddd39a8d732e6fac0b6a2f1e1dfc7fb1ffcb10 0.1s done +#27 exporting manifest list sha256:5f1117caea1a244c10ab8b272737b5594102a6df3ba67a78ffdf62680abd511f +#27 exporting manifest list sha256:5f1117caea1a244c10ab8b272737b5594102a6df3ba67a78ffdf62680abd511f 0.0s done +#27 naming to docker.io/library/messenger:lab7 0.0s done +#27 unpacking to docker.io/library/messenger:lab7 +#27 unpacking to docker.io/library/messenger:lab7 0.1s done +#27 DONE 0.5s + +#28 [migrate] exporting to image +#28 exporting layers 0.2s done +#28 exporting manifest sha256:67cc14fb375db1d86f352beb0e032a3d2f42f089af529411698f607f0573f92f 0.0s done +#28 exporting config sha256:82d3627d378317213cb09c4e6740aaadaa14f8990cebe9e3e09bfa06604782d0 0.0s done +#28 exporting attestation manifest sha256:805ecd37bc77aece90d1edc892818e84958940a1eec44af4bb30b0d9a7db0ee9 0.1s done +#28 exporting manifest list sha256:4e957fe939c8f76d0f0989945dcc10e0b663d12473f455cc36eff615f4fcf661 0.0s done +#28 naming to docker.io/library/messenger:lab7 0.0s done +#28 unpacking to docker.io/library/messenger:lab7 0.1s done +#28 DONE 0.5s + +#29 [api] exporting to image +#29 exporting layers 0.1s done +#29 exporting manifest sha256:16f4600da48faf25008ab0bb236b5b938f9dc9cd543dd67b9a934f380bab5bbb 0.1s done +#29 exporting config sha256:805f2a3e47bc4641680cc332b151c0c2abe6f7d976c22671a6ac511a5648f900 0.1s done +#29 exporting attestation manifest sha256:6386ea2ebff1a98e81d33039a98cb4d55536f4b658c27c7917aa35c83b2413b2 0.1s done +#29 exporting manifest list sha256:83a4a988573cc4fc98437453ef328dd9cc59be4145f646b2ca7b27160e17627a 0.0s done +#29 naming to docker.io/library/messenger:lab7 done +#29 unpacking to docker.io/library/messenger:lab7 0.1s done +#29 DONE 0.5s + +#30 [worker] exporting to image +#30 exporting layers 0.1s done +#30 exporting manifest sha256:174e6d9e8711bc6d6c1c84b6be3111e3141b1407e799f10f79177ad82240e598 0.0s done +#30 exporting config sha256:9b5b6d387674e814a6758e37d88c18f995982c687e5b6ca56643b7ac5ee4a300 0.0s done +#30 exporting attestation manifest sha256:353c58408dbc64a54b779f1a1530c2508e261ba3e43c0fb90899a79b6cfee6b3 0.1s done +#30 exporting manifest list sha256:2a25cec9f23a54ad198d3da1d20bb0ab6d8d7c7721c749823389cb0e513419fc 0.0s done +#30 naming to docker.io/library/messenger:lab7 0.0s done +#30 unpacking to docker.io/library/messenger:lab7 0.1s done +#30 DONE 0.5s + +#31 [dispatcher] exporting to image +#31 exporting layers 0.2s done +#31 exporting manifest sha256:461f72e1d170bc31dffa7cdc3c019c560450f99b6e9e87fd16379fb1adea2dc2 0.0s done +#31 exporting config sha256:a82e32cb1c27ef63ecd842c07156b9eaaf74915e3265c43e2bcf4fbe53a6c11f 0.1s done +#31 exporting attestation manifest sha256:5aff6b6399d1c2fd11aaa033e9d385b50ac4f76370e1d5479d78fdd4890ca8f5 0.1s done +#31 exporting manifest list sha256:46dcb5a1c666601ee3a64c15087708cd0fbdfa9921a25d315ce8a6ebf194c2f1 0.0s done +#31 naming to docker.io/library/messenger:lab7 0.0s done +#31 unpacking to docker.io/library/messenger:lab7 0.1s done +#31 DONE 0.6s + +#32 [migrate] resolving provenance for metadata file +#32 DONE 0.1s + +#33 [worker] resolving provenance for metadata file +#33 DONE 0.0s + +#34 [api] resolving provenance for metadata file +#34 DONE 0.1s + +#35 [cleanup] resolving provenance for metadata file +#35 DONE 0.1s + +#36 [dispatcher] resolving provenance for metadata file +#36 DONE 0.0s + Image messenger-minio:2025-04 Built + Image messenger:lab7 Built + Image messenger:lab7 Built + Image messenger:lab7 Built + Image messenger:lab7 Built + Image messenger-minio:2025-04 Built + Image messenger:lab7 Built diff --git a/evidence/hash-cost.json b/evidence/hash-cost.json new file mode 100644 index 00000000..7a9ff4cf --- /dev/null +++ b/evidence/hash-cost.json @@ -0,0 +1,8 @@ +{ + "memory_kib": 19456, + "t": 2, + "p": 1, + "hash_median_ms": 21.902915499993014, + "hash_max_ms": 35.0332680000065, + "peak_rss_kib": 32648 +} diff --git a/evidence/image-scan.txt b/evidence/image-scan.txt new file mode 100644 index 00000000..18fad0f6 --- /dev/null +++ b/evidence/image-scan.txt @@ -0,0 +1,904 @@ + i New version 1.30.0 available (installed version is 1.25.0) at https://github.com/docker/scout-cli + ...Reading archive + v Archive read + ...Storing image for indexing + v Image stored for indexing + ...Indexing + v Indexed 211 packages + ! failed to parse image name: could not parse reference: c:\Users\elsem\AppData\Local\Temp\lab7-scan-9ccb5097-1a07-4860-ae06-ee2f49ed08f5.tar x Detected 18 vulnerable packages with a total of 137 vulnerabilities + + +## Overview + + │ Analyzed Image +───────────────────┼────────────────────────────────────────────────────────────────────────────────────────────────── + Target │ archive://C:\Users\elsem\AppData\Local\Temp\lab7-scan-9ccb5097-1a07-4860-ae06-ee2f49ed08f5.tar + digest │ 0ac1a8b8d6ea + platform │ linux/amd64 + vulnerabilities │ 17C 120H 0M 0L + size │ 98 MB + packages │ 211 + + +## Packages and Vulnerabilities + + 5C 36H 0M 0L pillow 11.3.0 +pkg:pypi/pillow@11.3.0 + + x CRITICAL CVE-2026-96639 [Out-of-bounds Read] + https://scout.docker.com/v/CVE-2026-96639?s=github&n=pillow&t=pypi&vr=%3E%3D11.0.0%2C%3C13.0.0 + Affected range : >=11.0.0 + : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 9.8 + CVSS Vector : CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H + + x CRITICAL CVE-2026-112900 [Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')] + https://scout.docker.com/v/CVE-2026-112900?s=github&n=pillow&t=pypi&vr=%3E%3D2.6.0%2C%3C13.0.0 + Affected range : >=2.6.0 + : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 9.2 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N + + x CRITICAL CVE-2026-112403 [Heap-based Buffer Overflow] + https://scout.docker.com/v/CVE-2026-112403?s=github&n=pillow&t=pypi&vr=%3C%3D12.3.0 + Affected range : <=12.3.0 + Fixed version : 13.0.0 + CVSS Score : 9.2 + CVSS Vector : CVSS:4.0/AV:N/AC:H/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N + + x CRITICAL CVE-2026-112398 [Heap-based Buffer Overflow] + https://scout.docker.com/v/CVE-2026-112398?s=github&n=pillow&t=pypi&vr=%3C%3D12.3.0 + Affected range : <=12.3.0 + Fixed version : 13.0.0 + CVSS Score : 9.2 + CVSS Vector : CVSS:4.0/AV:N/AC:H/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N + + x CRITICAL CVE-2026-112393 [Heap-based Buffer Overflow] + https://scout.docker.com/v/CVE-2026-112393?s=github&n=pillow&t=pypi&vr=%3E%3D2.0.0%2C%3C13.0.0 + Affected range : >=2.0.0 + : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 9.2 + CVSS Vector : CVSS:4.0/AV:N/AC:H/AT:P/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-112902 [Function Call With Incorrect Argument Type] + https://scout.docker.com/v/CVE-2026-112902?s=github&n=pillow&t=pypi&vr=%3E%3D5.4.0%2C%3C%3D12.3.0 + Affected range : >=5.4.0 + : <=12.3.0 + Fixed version : 13.0.0 + CVSS Score : 8.8 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-112896 [Out-of-bounds Read] + https://scout.docker.com/v/CVE-2026-112896?s=github&n=pillow&t=pypi&vr=%3C%3D12.3.0 + Affected range : <=12.3.0 + Fixed version : 13.0.0 + CVSS Score : 8.8 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:L/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-112404 [Out-of-bounds Read] + https://scout.docker.com/v/CVE-2026-112404?s=github&n=pillow&t=pypi&vr=%3E%3D8.1.0%2C%3C13.0.0 + Affected range : >=8.1.0 + : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 8.8 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:L/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-59204 [Allocation of Resources Without Limits or Throttling] + https://scout.docker.com/v/CVE-2026-59204?s=github&n=pillow&t=pypi&vr=%3E%3D8.2.0%2C%3C12.3.0 + Affected range : >=8.2.0 + : <12.3.0 + Fixed version : 12.3.0 + CVSS Score : 8.7 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-40192 [Uncontrolled Resource Consumption] + https://scout.docker.com/v/CVE-2026-40192?s=github&n=pillow&t=pypi&vr=%3E%3D10.3.0%2C%3C12.2.0 + Affected range : >=10.3.0 + : <12.2.0 + Fixed version : 12.2.0 + CVSS Score : 8.7 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-112897 [Use of Uninitialized Resource] + https://scout.docker.com/v/CVE-2026-112897?s=github&n=pillow&t=pypi&vr=%3E%3D5.3.0%2C%3C13.0.0 + Affected range : >=5.3.0 + : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 8.7 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:N/VA:N/SC:N/SI:N/SA:N + + x HIGH CVE-2026-112895 [Uncontrolled Recursion] + https://scout.docker.com/v/CVE-2026-112895?s=github&n=pillow&t=pypi&vr=%3E%3D5.1.0%2C%3C13.0.0 + Affected range : >=5.1.0 + : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 8.7 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-112894 [Inefficient Algorithmic Complexity] + https://scout.docker.com/v/CVE-2026-112894?s=github&n=pillow&t=pypi&vr=%3E%3D5.1.0%2C%3C13.0.0 + Affected range : >=5.1.0 + : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 8.7 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-112892 [Improper Handling of Highly Compressed Data (Data Amplification)] + https://scout.docker.com/v/CVE-2026-112892?s=github&n=pillow&t=pypi&vr=%3E%3D4.1.0%2C%3C13.0.0 + Affected range : >=4.1.0 + : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 8.7 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-112406 [Loop with Unreachable Exit Condition ('Infinite Loop')] + https://scout.docker.com/v/CVE-2026-112406?s=github&n=pillow&t=pypi&vr=%3E%3D5.1.0%2C%3C13.0.0 + Affected range : >=5.1.0 + : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 8.7 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-112402 [Use After Free] + https://scout.docker.com/v/CVE-2026-112402?s=github&n=pillow&t=pypi&vr=%3C%3D12.3.0 + Affected range : <=12.3.0 + Fixed version : 13.0.0 + CVSS Score : 8.7 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-112400 [Uncontrolled Resource Consumption] + https://scout.docker.com/v/CVE-2026-112400?s=github&n=pillow&t=pypi&vr=%3E%3D9.2.0%2C%3C13.0.0 + Affected range : >=9.2.0 + : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 8.7 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-112399 [Memory Allocation with Excessive Size Value] + https://scout.docker.com/v/CVE-2026-112399?s=github&n=pillow&t=pypi&vr=%3E%3D8.1.0%2C%3C13.0.0 + Affected range : >=8.1.0 + : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 8.7 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-112397 [Out-of-bounds Write] + https://scout.docker.com/v/CVE-2026-112397?s=github&n=pillow&t=pypi&vr=%3C%3D12.3.0 + Affected range : <=12.3.0 + Fixed version : 13.0.0 + CVSS Score : 8.7 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-42311 [Integer Overflow or Wraparound] + https://scout.docker.com/v/CVE-2026-42311?s=github&n=pillow&t=pypi&vr=%3E%3D10.3.0%2C%3C12.2.0 + Affected range : >=10.3.0 + : <12.2.0 + Fixed version : 12.2.0 + CVSS Score : 8.6 + CVSS Vector : CVSS:4.0/AV:L/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-25990 [Out-of-bounds Write] + https://scout.docker.com/v/CVE-2026-25990?s=github&n=pillow&t=pypi&vr=%3E%3D10.3.0%2C%3C12.1.1 + Affected range : >=10.3.0 + : <12.1.1 + Fixed version : 12.1.1 + CVSS Score : 8.6 + CVSS Vector : CVSS:4.0/AV:L/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-128067 [Out-of-bounds Write] + https://scout.docker.com/v/CVE-2026-128067?s=github&n=pillow&t=pypi&vr=%3C%3D12.3.0 + Affected range : <=12.3.0 + Fixed version : 13.0.0 + CVSS Score : 8.4 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:H/VI:L/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-54058 [Out-of-bounds Read] + https://scout.docker.com/v/CVE-2026-54058?s=github&n=pillow&t=pypi&vr=%3C12.3.0 + Affected range : <12.3.0 + Fixed version : 12.3.0 + CVSS Score : 8.3 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:H/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-96640 [Uncontrolled Resource Consumption] + https://scout.docker.com/v/CVE-2026-96640?s=github&n=pillow&t=pypi&vr=%3E%3D5.1.0%2C%3C13.0.0 + Affected range : >=5.1.0 + : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 8.2 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-59197 [Integer Overflow or Wraparound] + https://scout.docker.com/v/CVE-2026-59197?s=github&n=pillow&t=pypi&vr=%3C12.3.0 + Affected range : <12.3.0 + Fixed version : 12.3.0 + CVSS Score : 8.2 + CVSS Vector : CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:H + + x HIGH CVE-2026-112893 [Use of Uninitialized Variable] + https://scout.docker.com/v/CVE-2026-112893?s=github&n=pillow&t=pypi&vr=%3E%3D10.0.0%2C%3C13.0.0 + Affected range : >=10.0.0 + : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 8.2 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-112392 [NULL Pointer Dereference] + https://scout.docker.com/v/CVE-2026-112392?s=github&n=pillow&t=pypi&vr=%3C%3D12.3.0 + Affected range : <=12.3.0 + Fixed version : 13.0.0 + CVSS Score : 8.2 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-112390 [Loop with Unreachable Exit Condition ('Infinite Loop')] + https://scout.docker.com/v/CVE-2026-112390?s=github&n=pillow&t=pypi&vr=%3E%3D7.2.0%2C%3C13.0.0 + Affected range : >=7.2.0 + : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 8.2 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH GHSA-78g4-xqwv-q3g8 [Dependency on Vulnerable Third-Party Component] + https://scout.docker.com/v/GHSA-78g4-xqwv-q3g8?s=github&n=pillow&t=pypi&vr=%3E%3D11.1.0%2C%3C13.0.0 + Affected range : >=11.1.0 + : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 8.1 + CVSS Vector : CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H + + x HIGH CVE-2026-96778 [Out-of-bounds Write] + https://scout.docker.com/v/CVE-2026-96778?s=github&n=pillow&t=pypi&vr=%3E%3D9.4.0%2C%3C13.0.0 + Affected range : >=9.4.0 + : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 7.7 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:P/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-59205 [Out-of-bounds Write] + https://scout.docker.com/v/CVE-2026-59205?s=github&n=pillow&t=pypi&vr=%3C12.3.0 + Affected range : <12.3.0 + Fixed version : 12.3.0 + CVSS Score : 7.5 + CVSS Vector : CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H + + x HIGH CVE-2026-59200 [Uncontrolled Resource Consumption] + https://scout.docker.com/v/CVE-2026-59200?s=github&n=pillow&t=pypi&vr=%3E%3D5.1.0%2C%3C12.3.0 + Affected range : >=5.1.0 + : <12.3.0 + Fixed version : 12.3.0 + CVSS Score : 7.5 + CVSS Vector : CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H + + x HIGH CVE-2026-59199 [Integer Overflow or Wraparound] + https://scout.docker.com/v/CVE-2026-59199?s=github&n=pillow&t=pypi&vr=%3C12.3.0 + Affected range : <12.3.0 + Fixed version : 12.3.0 + CVSS Score : 7.5 + CVSS Vector : CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H + + x HIGH CVE-2026-55380 [Memory Allocation with Excessive Size Value] + https://scout.docker.com/v/CVE-2026-55380?s=github&n=pillow&t=pypi&vr=%3C12.3.0 + Affected range : <12.3.0 + Fixed version : 12.3.0 + CVSS Score : 7.5 + CVSS Vector : CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H + + x HIGH CVE-2026-55379 [Memory Allocation with Excessive Size Value] + https://scout.docker.com/v/CVE-2026-55379?s=github&n=pillow&t=pypi&vr=%3C12.3.0 + Affected range : <12.3.0 + Fixed version : 12.3.0 + CVSS Score : 7.5 + CVSS Vector : CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H + + x HIGH CVE-2026-54060 [Memory Allocation with Excessive Size Value] + https://scout.docker.com/v/CVE-2026-54060?s=github&n=pillow&t=pypi&vr=%3C12.3.0 + Affected range : <12.3.0 + Fixed version : 12.3.0 + CVSS Score : 7.5 + CVSS Vector : CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H + + x HIGH CVE-2026-54059 [Memory Allocation with Excessive Size Value] + https://scout.docker.com/v/CVE-2026-54059?s=github&n=pillow&t=pypi&vr=%3C12.3.0 + Affected range : <12.3.0 + Fixed version : 12.3.0 + CVSS Score : 7.5 + CVSS Vector : CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H + + x HIGH CVE-2026-96644 [Out-of-bounds Read] + https://scout.docker.com/v/CVE-2026-96644?s=github&n=pillow&t=pypi&vr=%3C13.0.0 + Affected range : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 7.1 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:P/VC:L/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-96643 [Inefficient Algorithmic Complexity] + https://scout.docker.com/v/CVE-2026-96643?s=github&n=pillow&t=pypi&vr=%3E%3D11.0.0%2C%3C13.0.0 + Affected range : >=11.0.0 + : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 7.1 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:P/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-96642 [Loop with Unreachable Exit Condition ('Infinite Loop')] + https://scout.docker.com/v/CVE-2026-96642?s=github&n=pillow&t=pypi&vr=%3C13.0.0 + Affected range : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 7.1 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:P/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N + + x HIGH CVE-2026-96637 [Uncontrolled Resource Consumption] + https://scout.docker.com/v/CVE-2026-96637?s=github&n=pillow&t=pypi&vr=%3C13.0.0 + Affected range : <13.0.0 + Fixed version : 13.0.0 + CVSS Score : 7.1 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:P/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N + + + 5C 22H 0M 0L openssl 3.0.14-1~deb12u2 +pkg:deb/debian/openssl@3.0.14-1~deb12u2?os_distro=bookworm&os_name=debian&os_version=12 + + x CRITICAL CVE-2026-31789 + https://scout.docker.com/v/CVE-2026-31789?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.19-1%7Edeb12u2 + Affected range : <3.0.19-1~deb12u2 + Fixed version : 3.0.19-1~deb12u2 + + x CRITICAL CVE-2025-9230 + https://scout.docker.com/v/CVE-2025-9230?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.17-1%7Edeb12u3 + Affected range : <3.0.17-1~deb12u3 + Fixed version : 3.0.17-1~deb12u3 + + x CRITICAL CVE-2026-75803 + https://scout.docker.com/v/CVE-2026-75803?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.22-1%7Edeb12u1 + Affected range : <3.0.22-1~deb12u1 + Fixed version : 3.0.22-1~deb12u1 + + x CRITICAL CVE-2026-34182 + https://scout.docker.com/v/CVE-2026-34182?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.20-1%7Edeb12u2 + Affected range : <3.0.20-1~deb12u2 + Fixed version : 3.0.20-1~deb12u2 + + x CRITICAL CVE-2024-5535 + https://scout.docker.com/v/CVE-2024-5535?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.15-1%7Edeb12u1 + Affected range : <3.0.15-1~deb12u1 + Fixed version : 3.0.15-1~deb12u1 + + x HIGH CVE-2026-45447 + https://scout.docker.com/v/CVE-2026-45447?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.20-1%7Edeb12u2 + Affected range : <3.0.20-1~deb12u2 + Fixed version : 3.0.20-1~deb12u2 + + x HIGH CVE-2025-15467 + https://scout.docker.com/v/CVE-2025-15467?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.18-1%7Edeb12u2 + Affected range : <3.0.18-1~deb12u2 + Fixed version : 3.0.18-1~deb12u2 + + x HIGH CVE-2024-9143 + https://scout.docker.com/v/CVE-2024-9143?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.15-1%7Edeb12u1 + Affected range : <3.0.15-1~deb12u1 + Fixed version : 3.0.15-1~deb12u1 + + x HIGH CVE-2026-84782 + https://scout.docker.com/v/CVE-2026-84782?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.22-1%7Edeb12u2 + Affected range : <3.0.22-1~deb12u2 + Fixed version : 3.0.22-1~deb12u2 + + x HIGH CVE-2026-7383 + https://scout.docker.com/v/CVE-2026-7383?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.20-1%7Edeb12u2 + Affected range : <3.0.20-1~deb12u2 + Fixed version : 3.0.20-1~deb12u2 + + x HIGH CVE-2026-28387 + https://scout.docker.com/v/CVE-2026-28387?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.19-1%7Edeb12u2 + Affected range : <3.0.19-1~deb12u2 + Fixed version : 3.0.19-1~deb12u2 + + x HIGH CVE-2026-107493 + https://scout.docker.com/v/CVE-2026-107493?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2026-9076 + https://scout.docker.com/v/CVE-2026-9076?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.20-1%7Edeb12u2 + Affected range : <3.0.20-1~deb12u2 + Fixed version : 3.0.20-1~deb12u2 + + x HIGH CVE-2026-84786 + https://scout.docker.com/v/CVE-2026-84786?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2026-63076 + https://scout.docker.com/v/CVE-2026-63076?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.22-1%7Edeb12u1 + Affected range : <3.0.22-1~deb12u1 + Fixed version : 3.0.22-1~deb12u1 + + x HIGH CVE-2026-63072 + https://scout.docker.com/v/CVE-2026-63072?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.22-1%7Edeb12u1 + Affected range : <3.0.22-1~deb12u1 + Fixed version : 3.0.22-1~deb12u1 + + x HIGH CVE-2026-54874 + https://scout.docker.com/v/CVE-2026-54874?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.22-1%7Edeb12u1 + Affected range : <3.0.22-1~deb12u1 + Fixed version : 3.0.22-1~deb12u1 + + x HIGH CVE-2026-45445 + https://scout.docker.com/v/CVE-2026-45445?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.20-1%7Edeb12u2 + Affected range : <3.0.20-1~deb12u2 + Fixed version : 3.0.20-1~deb12u2 + + x HIGH CVE-2026-34180 + https://scout.docker.com/v/CVE-2026-34180?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.20-1%7Edeb12u2 + Affected range : <3.0.20-1~deb12u2 + Fixed version : 3.0.20-1~deb12u2 + + x HIGH CVE-2026-31790 + https://scout.docker.com/v/CVE-2026-31790?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.19-1%7Edeb12u2 + Affected range : <3.0.19-1~deb12u2 + Fixed version : 3.0.19-1~deb12u2 + + x HIGH CVE-2026-28390 + https://scout.docker.com/v/CVE-2026-28390?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.19-1%7Edeb12u2 + Affected range : <3.0.19-1~deb12u2 + Fixed version : 3.0.19-1~deb12u2 + + x HIGH CVE-2026-28389 + https://scout.docker.com/v/CVE-2026-28389?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.19-1%7Edeb12u2 + Affected range : <3.0.19-1~deb12u2 + Fixed version : 3.0.19-1~deb12u2 + + x HIGH CVE-2026-28388 + https://scout.docker.com/v/CVE-2026-28388?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.19-1%7Edeb12u2 + Affected range : <3.0.19-1~deb12u2 + Fixed version : 3.0.19-1~deb12u2 + + x HIGH CVE-2026-107496 + https://scout.docker.com/v/CVE-2026-107496?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2025-69421 + https://scout.docker.com/v/CVE-2025-69421?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.18-1%7Edeb12u2 + Affected range : <3.0.18-1~deb12u2 + Fixed version : 3.0.18-1~deb12u2 + + x HIGH CVE-2025-69420 + https://scout.docker.com/v/CVE-2025-69420?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.18-1%7Edeb12u2 + Affected range : <3.0.18-1~deb12u2 + Fixed version : 3.0.18-1~deb12u2 + + x HIGH CVE-2025-69419 + https://scout.docker.com/v/CVE-2025-69419?s=debian&n=openssl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.0.18-1%7Edeb12u2 + Affected range : <3.0.18-1~deb12u2 + Fixed version : 3.0.18-1~deb12u2 + + + 5C 7H 0M 0L perl 5.36.0-7+deb12u1 +pkg:deb/debian/perl@5.36.0-7%2Bdeb12u1?os_distro=bookworm&os_name=debian&os_version=12 + + x CRITICAL CVE-2026-8376 + https://scout.docker.com/v/CVE-2026-8376?s=debian&n=perl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C5.36.0-7%2Bdeb12u4 + Affected range : <5.36.0-7+deb12u4 + Fixed version : 5.36.0-7+deb12u4 + + x CRITICAL CVE-2026-57433 + https://scout.docker.com/v/CVE-2026-57433?s=debian&n=perl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C5.36.0-7%2Bdeb12u4 + Affected range : <5.36.0-7+deb12u4 + Fixed version : 5.36.0-7+deb12u4 + + x CRITICAL CVE-2026-42496 + https://scout.docker.com/v/CVE-2026-42496?s=debian&n=perl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C5.36.0-7%2Bdeb12u4 + Affected range : <5.36.0-7+deb12u4 + Fixed version : 5.36.0-7+deb12u4 + + x CRITICAL CVE-2026-13221 + https://scout.docker.com/v/CVE-2026-13221?s=debian&n=perl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C5.36.0-7%2Bdeb12u4 + Affected range : <5.36.0-7+deb12u4 + Fixed version : 5.36.0-7+deb12u4 + + x CRITICAL CVE-2026-12087 + https://scout.docker.com/v/CVE-2026-12087?s=debian&n=perl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C5.36.0-7%2Bdeb12u4 + Affected range : <5.36.0-7+deb12u4 + Fixed version : 5.36.0-7+deb12u4 + + x HIGH CVE-2026-57432 + https://scout.docker.com/v/CVE-2026-57432?s=debian&n=perl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C5.36.0-7%2Bdeb12u4 + Affected range : <5.36.0-7+deb12u4 + Fixed version : 5.36.0-7+deb12u4 + + x HIGH CVE-2024-56406 + https://scout.docker.com/v/CVE-2024-56406?s=debian&n=perl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C5.36.0-7%2Bdeb12u2 + Affected range : <5.36.0-7+deb12u2 + Fixed version : 5.36.0-7+deb12u2 + + x HIGH CVE-2023-31484 + https://scout.docker.com/v/CVE-2023-31484?s=debian&n=perl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C5.36.0-7%2Bdeb12u3 + Affected range : <5.36.0-7+deb12u3 + Fixed version : 5.36.0-7+deb12u3 + + x HIGH CVE-2026-48959 + https://scout.docker.com/v/CVE-2026-48959?s=debian&n=perl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C5.36.0-7%2Bdeb12u4 + Affected range : <5.36.0-7+deb12u4 + Fixed version : 5.36.0-7+deb12u4 + + x HIGH CVE-2026-42497 + https://scout.docker.com/v/CVE-2026-42497?s=debian&n=perl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C5.36.0-7%2Bdeb12u4 + Affected range : <5.36.0-7+deb12u4 + Fixed version : 5.36.0-7+deb12u4 + + x HIGH CVE-2026-48962 + https://scout.docker.com/v/CVE-2026-48962?s=debian&n=perl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C5.36.0-7%2Bdeb12u4 + Affected range : <5.36.0-7+deb12u4 + Fixed version : 5.36.0-7+deb12u4 + + x HIGH CVE-2026-7017 + https://scout.docker.com/v/CVE-2026-7017?s=debian&n=perl&ns=debian&t=deb&osn=debian&osv=12&vr=%3C5.36.0-7%2Bdeb12u4 + Affected range : <5.36.0-7+deb12u4 + Fixed version : 5.36.0-7+deb12u4 + + + 2C 13H 0M 0L expat 2.5.0-1 +pkg:deb/debian/expat@2.5.0-1?os_distro=bookworm&os_name=debian&os_version=12 + + x CRITICAL CVE-2024-45492 + https://scout.docker.com/v/CVE-2024-45492?s=debian&n=expat&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.5.0-1%2Bdeb12u1 + Affected range : <2.5.0-1+deb12u1 + Fixed version : 2.5.0-1+deb12u1 + + x CRITICAL CVE-2024-45491 + https://scout.docker.com/v/CVE-2024-45491?s=debian&n=expat&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.5.0-1%2Bdeb12u1 + Affected range : <2.5.0-1+deb12u1 + Fixed version : 2.5.0-1+deb12u1 + + x HIGH CVE-2026-93990 + https://scout.docker.com/v/CVE-2026-93990?s=debian&n=expat&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.5.0-1%2Bdeb12u4 + Affected range : <2.5.0-1+deb12u4 + Fixed version : 2.5.0-1+deb12u4 + + x HIGH CVE-2026-66046 + https://scout.docker.com/v/CVE-2026-66046?s=debian&n=expat&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.5.0-1%2Bdeb12u4 + Affected range : <2.5.0-1+deb12u4 + Fixed version : 2.5.0-1+deb12u4 + + x HIGH CVE-2026-141595 + https://scout.docker.com/v/CVE-2026-141595?s=debian&n=expat&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2026-137992 + https://scout.docker.com/v/CVE-2026-137992?s=debian&n=expat&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2026-77214 + https://scout.docker.com/v/CVE-2026-77214?s=debian&n=expat&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.5.0-1%2Bdeb12u5 + Affected range : <2.5.0-1+deb12u5 + Fixed version : 2.5.0-1+deb12u5 + + x HIGH CVE-2026-141596 + https://scout.docker.com/v/CVE-2026-141596?s=debian&n=expat&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2026-118370 + https://scout.docker.com/v/CVE-2026-118370?s=debian&n=expat&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2026-117610 + https://scout.docker.com/v/CVE-2026-117610?s=debian&n=expat&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2026-102633 + https://scout.docker.com/v/CVE-2026-102633?s=debian&n=expat&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.5.0-1%2Bdeb12u5 + Affected range : <2.5.0-1+deb12u5 + Fixed version : 2.5.0-1+deb12u5 + + x HIGH CVE-2025-59375 + https://scout.docker.com/v/CVE-2025-59375?s=debian&n=expat&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.5.0-1%2Bdeb12u5 + Affected range : <2.5.0-1+deb12u5 + Fixed version : 2.5.0-1+deb12u4 + + x HIGH CVE-2024-8176 + https://scout.docker.com/v/CVE-2024-8176?s=debian&n=expat&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.5.0-1%2Bdeb12u2 + Affected range : <2.5.0-1+deb12u2 + Fixed version : 2.5.0-1+deb12u2 + + x HIGH CVE-2024-45490 + https://scout.docker.com/v/CVE-2024-45490?s=debian&n=expat&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.5.0-1%2Bdeb12u1 + Affected range : <2.5.0-1+deb12u1 + Fixed version : 2.5.0-1+deb12u1 + + x HIGH CVE-2023-52425 + https://scout.docker.com/v/CVE-2023-52425?s=debian&n=expat&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.5.0-1%2Bdeb12u2 + Affected range : <2.5.0-1+deb12u2 + Fixed version : 2.5.0-1+deb12u2 + + + 0C 8H 0M 0L gnutls28 3.7.9-2+deb12u3 +pkg:deb/debian/gnutls28@3.7.9-2%2Bdeb12u3?os_distro=bookworm&os_name=debian&os_version=12 + + x HIGH CVE-2026-5260 + https://scout.docker.com/v/CVE-2026-5260?s=debian&n=gnutls28&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.7.9-2%2Bdeb12u7 + Affected range : <3.7.9-2+deb12u7 + Fixed version : 3.7.9-2+deb12u7 + + x HIGH CVE-2026-42013 + https://scout.docker.com/v/CVE-2026-42013?s=debian&n=gnutls28&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.7.9-2%2Bdeb12u7 + Affected range : <3.7.9-2+deb12u7 + Fixed version : 3.7.9-2+deb12u7 + + x HIGH CVE-2026-42009 + https://scout.docker.com/v/CVE-2026-42009?s=debian&n=gnutls28&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.7.9-2%2Bdeb12u7 + Affected range : <3.7.9-2+deb12u7 + Fixed version : 3.7.9-2+deb12u7 + + x HIGH CVE-2026-33846 + https://scout.docker.com/v/CVE-2026-33846?s=debian&n=gnutls28&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.7.9-2%2Bdeb12u7 + Affected range : <3.7.9-2+deb12u7 + Fixed version : 3.7.9-2+deb12u7 + + x HIGH CVE-2026-33845 + https://scout.docker.com/v/CVE-2026-33845?s=debian&n=gnutls28&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.7.9-2%2Bdeb12u7 + Affected range : <3.7.9-2+deb12u7 + Fixed version : 3.7.9-2+deb12u7 + + x HIGH CVE-2026-42011 + https://scout.docker.com/v/CVE-2026-42011?s=debian&n=gnutls28&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.7.9-2%2Bdeb12u7 + Affected range : <3.7.9-2+deb12u7 + Fixed version : 3.7.9-2+deb12u7 + + x HIGH CVE-2026-42012 + https://scout.docker.com/v/CVE-2026-42012?s=debian&n=gnutls28&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.7.9-2%2Bdeb12u7 + Affected range : <3.7.9-2+deb12u7 + Fixed version : 3.7.9-2+deb12u7 + + x HIGH CVE-2026-42010 + https://scout.docker.com/v/CVE-2026-42010?s=debian&n=gnutls28&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.7.9-2%2Bdeb12u7 + Affected range : <3.7.9-2+deb12u7 + Fixed version : 3.7.9-2+deb12u7 + + + 0C 7H 0M 0L krb5 1.20.1-2+deb12u2 +pkg:deb/debian/krb5@1.20.1-2%2Bdeb12u2?os_distro=bookworm&os_name=debian&os_version=12 + + x HIGH CVE-2026-119079 + https://scout.docker.com/v/CVE-2026-119079?s=debian&n=krb5&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2026-112323 + https://scout.docker.com/v/CVE-2026-112323?s=debian&n=krb5&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2026-112322 + https://scout.docker.com/v/CVE-2026-112322?s=debian&n=krb5&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2026-112321 + https://scout.docker.com/v/CVE-2026-112321?s=debian&n=krb5&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2026-112320 + https://scout.docker.com/v/CVE-2026-112320?s=debian&n=krb5&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2026-112314 + https://scout.docker.com/v/CVE-2026-112314?s=debian&n=krb5&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2025-24528 + https://scout.docker.com/v/CVE-2025-24528?s=debian&n=krb5&ns=debian&t=deb&osn=debian&osv=12&vr=%3C1.20.1-2%2Bdeb12u3 + Affected range : <1.20.1-2+deb12u3 + Fixed version : 1.20.1-2+deb12u3 + + + 0C 7H 0M 0L glibc 2.36-9+deb12u8 +pkg:deb/debian/glibc@2.36-9%2Bdeb12u8?os_distro=bookworm&os_name=debian&os_version=12 + + x HIGH CVE-2026-0861 + https://scout.docker.com/v/CVE-2026-0861?s=debian&n=glibc&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.36-9%2Bdeb12u14 + Affected range : <2.36-9+deb12u14 + Fixed version : 2.36-9+deb12u14 + + x HIGH CVE-2025-4802 + https://scout.docker.com/v/CVE-2025-4802?s=debian&n=glibc&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.36-9%2Bdeb12u11 + Affected range : <2.36-9+deb12u11 + Fixed version : 2.36-9+deb12u11 + + x HIGH CVE-2026-4437 + https://scout.docker.com/v/CVE-2026-4437?s=debian&n=glibc&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.36-9%2Bdeb12u14 + Affected range : <2.36-9+deb12u14 + Fixed version : 2.36-9+deb12u14 + + x HIGH CVE-2026-4046 + https://scout.docker.com/v/CVE-2026-4046?s=debian&n=glibc&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.36-9%2Bdeb12u14 + Affected range : <2.36-9+deb12u14 + Fixed version : 2.36-9+deb12u14 + + x HIGH CVE-2026-0915 + https://scout.docker.com/v/CVE-2026-0915?s=debian&n=glibc&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.36-9%2Bdeb12u14 + Affected range : <2.36-9+deb12u14 + Fixed version : 2.36-9+deb12u14 + + x HIGH CVE-2025-15281 + https://scout.docker.com/v/CVE-2025-15281?s=debian&n=glibc&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.36-9%2Bdeb12u14 + Affected range : <2.36-9+deb12u14 + Fixed version : 2.36-9+deb12u14 + + x HIGH CVE-2026-84243 + https://scout.docker.com/v/CVE-2026-84243?s=debian&n=glibc&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + + 0C 4H 0M 0L sqlite3 3.40.1-2 +pkg:deb/debian/sqlite3@3.40.1-2?os_distro=bookworm&os_name=debian&os_version=12 + + x HIGH CVE-2026-119379 + https://scout.docker.com/v/CVE-2026-119379?s=debian&n=sqlite3&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2026-119374 + https://scout.docker.com/v/CVE-2026-119374?s=debian&n=sqlite3&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2026-119373 + https://scout.docker.com/v/CVE-2026-119373?s=debian&n=sqlite3&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2025-6965 + https://scout.docker.com/v/CVE-2025-6965?s=debian&n=sqlite3&ns=debian&t=deb&osn=debian&osv=12&vr=%3C3.40.1-2%2Bdeb12u2 + Affected range : <3.40.1-2+deb12u2 + Fixed version : 3.40.1-2+deb12u2 + + + 0C 3H 0M 0L pcre2 10.42-1 +pkg:deb/debian/pcre2@10.42-1?os_distro=bookworm&os_name=debian&os_version=12 + + x HIGH CVE-2026-86145 + https://scout.docker.com/v/CVE-2026-86145?s=debian&n=pcre2&ns=debian&t=deb&osn=debian&osv=12&vr=%3C10.42-1%2Bdeb12u1 + Affected range : <10.42-1+deb12u1 + Fixed version : 10.42-1+deb12u1 + + x HIGH CVE-2026-103111 + https://scout.docker.com/v/CVE-2026-103111?s=debian&n=pcre2&ns=debian&t=deb&osn=debian&osv=12&vr=%3C10.42-1%2Bdeb12u2 + Affected range : <10.42-1+deb12u2 + Fixed version : 10.42-1+deb12u2 + + x HIGH CVE-2026-89161 + https://scout.docker.com/v/CVE-2026-89161?s=debian&n=pcre2&ns=debian&t=deb&osn=debian&osv=12&vr=%3C10.42-1%2Bdeb12u1 + Affected range : <10.42-1+deb12u1 + Fixed version : 10.42-1+deb12u1 + + + 0C 2H 0M 0L setuptools 65.5.1 +pkg:pypi/setuptools@65.5.1 + + x HIGH CVE-2025-47273 [Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')] + https://scout.docker.com/v/CVE-2025-47273?s=github&n=setuptools&t=pypi&vr=%3C78.1.1 + Affected range : <78.1.1 + Fixed version : 78.1.1 + CVSS Score : 7.7 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:H/VA:N/SC:N/SI:N/SA:N/E:P + + x HIGH CVE-2024-6345 [Improper Control of Generation of Code ('Code Injection')] + https://scout.docker.com/v/CVE-2024-6345?s=github&n=setuptools&t=pypi&vr=%3C70.0.0 + Affected range : <70.0.0 + Fixed version : 70.0.0 + CVSS Score : 7.5 + CVSS Vector : CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:A/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N + + + 0C 2H 0M 0L util-linux 2.38.1-5+deb12u1 +pkg:deb/debian/util-linux@2.38.1-5%2Bdeb12u1?os_distro=bookworm&os_name=debian&os_version=12 + + x HIGH CVE-2026-53615 + https://scout.docker.com/v/CVE-2026-53615?s=debian&n=util-linux&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + x HIGH CVE-2026-53613 + https://scout.docker.com/v/CVE-2026-53613?s=debian&n=util-linux&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + + 0C 2H 0M 0L zlib 1:1.2.13.dfsg-1 +pkg:deb/debian/zlib@1%3A1.2.13.dfsg-1?os_distro=bookworm&os_name=debian&os_version=12 + + x HIGH CVE-2026-85091 + https://scout.docker.com/v/CVE-2026-85091?s=debian&n=zlib&ns=debian&t=deb&osn=debian&osv=12&vr=%3C1%3A1.2.13.dfsg-1%2Bdeb12u1 + Affected range : <1:1.2.13.dfsg-1+deb12u1 + Fixed version : 1:1.2.13.dfsg-1+deb12u1 + + x HIGH CVE-2026-76844 + https://scout.docker.com/v/CVE-2026-76844?s=debian&n=zlib&ns=debian&t=deb&osn=debian&osv=12&vr=%3E0 + Affected range : >0 + Fixed version : not fixed + + + 0C 2H 0M 0L dpkg 1.21.22 +pkg:deb/debian/dpkg@1.21.22?os_distro=bookworm&os_name=debian&os_version=12 + + x HIGH CVE-2025-6297 + https://scout.docker.com/v/CVE-2025-6297?s=debian&n=dpkg&ns=debian&t=deb&osn=debian&osv=12&vr=%3C1.21.23 + Affected range : <1.21.23 + Fixed version : 1.21.23 + + x HIGH CVE-2026-2219 + https://scout.docker.com/v/CVE-2026-2219?s=debian&n=dpkg&ns=debian&t=deb&osn=debian&osv=12&vr=%3C1.21.23 + Affected range : <1.21.23 + Fixed version : 1.21.23 + + + 0C 1H 0M 0L wheel 0.44.0 +pkg:pypi/wheel@0.44.0 + + x HIGH CVE-2026-24049 [Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')] + https://scout.docker.com/v/CVE-2026-24049?s=github&n=wheel&t=pypi&vr=%3E%3D0.40.0%2C%3C%3D0.46.1 + Affected range : >=0.40.0 + : <=0.46.1 + Fixed version : 0.46.2 + CVSS Score : 7.1 + CVSS Vector : CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:H + + + 0C 1H 0M 0L pam 1.5.2-6+deb12u1 +pkg:deb/debian/pam@1.5.2-6%2Bdeb12u1?os_distro=bookworm&os_name=debian&os_version=12 + + x HIGH CVE-2025-6020 + https://scout.docker.com/v/CVE-2025-6020?s=debian&n=pam&ns=debian&t=deb&osn=debian&osv=12&vr=%3C1.5.2-6%2Bdeb12u3 + Affected range : <1.5.2-6+deb12u3 + Fixed version : 1.5.2-6+deb12u3 + + + 0C 1H 0M 0L apt 2.6.1 +pkg:deb/debian/apt@2.6.1?os_distro=bookworm&os_name=debian&os_version=12 + + x HIGH CVE-2026-109518 + https://scout.docker.com/v/CVE-2026-109518?s=debian&n=apt&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.6.2 + Affected range : <2.6.2 + Fixed version : 2.6.2 + + + 0C 1H 0M 0L xz-utils 5.4.1-0.2 +pkg:deb/debian/xz-utils@5.4.1-0.2?os_distro=bookworm&os_name=debian&os_version=12 + + x HIGH CVE-2025-31115 + https://scout.docker.com/v/CVE-2025-31115?s=debian&n=xz-utils&ns=debian&t=deb&osn=debian&osv=12&vr=%3C5.4.1-1 + Affected range : <5.4.1-1 + Fixed version : 5.4.1-1 + + + 0C 1H 0M 0L gnupg2 2.2.40-1.1 +pkg:deb/debian/gnupg2@2.2.40-1.1?os_distro=bookworm&os_name=debian&os_version=12 + + x HIGH CVE-2025-68973 + https://scout.docker.com/v/CVE-2025-68973?s=debian&n=gnupg2&ns=debian&t=deb&osn=debian&osv=12&vr=%3C2.2.40-1.1%2Bdeb12u2 + Affected range : <2.2.40-1.1+deb12u2 + Fixed version : 2.2.40-1.1+deb12u2 + + + +137 vulnerabilities found in 18 packages + CRITICAL 17 + HIGH 120 + MEDIUM 0 + LOW 0 + + +What's next: + View base image update recommendations → docker scout recommendations archive://C:\Users\elsem\AppData\Local\Temp\lab7-scan-9ccb5097-1a07-4860-ae06-ee2f49ed08f5.tar + diff --git a/evidence/login-budget.json b/evidence/login-budget.json new file mode 100644 index 00000000..c9f4897b --- /dev/null +++ b/evidence/login-budget.json @@ -0,0 +1,7 @@ +{ + "invalid_credentials_responses": 120, + "rate_limited_responses": 2, + "limited_replicas": 2, + "retry_after_seconds": 60, + "elapsed_seconds": 5.354 +} diff --git a/evidence/password-rehash.json b/evidence/password-rehash.json new file mode 100644 index 00000000..2aaf93b1 --- /dev/null +++ b/evidence/password-rehash.json @@ -0,0 +1 @@ +{"rehash_on_login": true} diff --git a/evidence/pipeline.json b/evidence/pipeline.json new file mode 100644 index 00000000..799621a8 --- /dev/null +++ b/evidence/pipeline.json @@ -0,0 +1,9 @@ +{ + "durable_handoff": "pass", + "after_s3_crash": "pass", + "variant_names": [ + "thumbnail", + "crop", + "optimized" + ] +} diff --git a/evidence/rotation.json b/evidence/rotation.json new file mode 100644 index 00000000..cff61a91 --- /dev/null +++ b/evidence/rotation.json @@ -0,0 +1,6 @@ +{ + "leaf_rotation": true, + "old_leaf_rejected": true, + "redis_secret_rotation": true, + "old_secret_rejected": true +} diff --git a/evidence/telemetry-privacy-check.txt b/evidence/telemetry-privacy-check.txt new file mode 100644 index 00000000..25a07a07 --- /dev/null +++ b/evidence/telemetry-privacy-check.txt @@ -0,0 +1 @@ +PASS: correlated login and message telemetry omit synthetic secrets diff --git a/evidence/telemetry-privacy.json b/evidence/telemetry-privacy.json new file mode 100644 index 00000000..c08e84b9 --- /dev/null +++ b/evidence/telemetry-privacy.json @@ -0,0 +1,7 @@ +{ + "correlated_log_and_trace_found": [ + "login", + "message" + ], + "synthetic_secrets_found": 0 +} diff --git a/evidence/tls-boundaries.json b/evidence/tls-boundaries.json new file mode 100644 index 00000000..4ec54776 --- /dev/null +++ b/evidence/tls-boundaries.json @@ -0,0 +1,146 @@ +[ + { + "service": "api", + "port": 8443, + "client": "lb-client", + "accepted": true + }, + { + "service": "api", + "port": 8443, + "client": "none", + "accepted": false + }, + { + "service": "api", + "port": 8443, + "client": "api-client", + "accepted": false + }, + { + "service": "broker", + "port": 6379, + "client": "worker-client", + "accepted": true + }, + { + "service": "broker", + "port": 6379, + "client": "none", + "accepted": false + }, + { + "service": "broker", + "port": 6379, + "client": "api-client", + "accepted": false + }, + { + "service": "collector", + "port": 4319, + "client": "worker-client", + "accepted": true + }, + { + "service": "collector", + "port": 4319, + "client": "none", + "accepted": false + }, + { + "service": "collector", + "port": 4319, + "client": "lb-client", + "accepted": false + }, + { + "service": "collector", + "port": 8890, + "client": "prometheus-client", + "accepted": true + }, + { + "service": "collector", + "port": 8890, + "client": "none", + "accepted": false + }, + { + "service": "collector", + "port": 8890, + "client": "worker-client", + "accepted": false + }, + { + "service": "loki", + "port": 3101, + "client": "collector-client", + "accepted": true + }, + { + "service": "loki", + "port": 3101, + "client": "none", + "accepted": false + }, + { + "service": "loki", + "port": 3101, + "client": "worker-client", + "accepted": false + }, + { + "service": "tempo", + "port": 4319, + "client": "collector-client", + "accepted": true + }, + { + "service": "tempo", + "port": 4319, + "client": "none", + "accepted": false + }, + { + "service": "tempo", + "port": 4319, + "client": "worker-client", + "accepted": false + }, + { + "service": "tempo", + "port": 3201, + "client": "grafana-client", + "accepted": true + }, + { + "service": "tempo", + "port": 3201, + "client": "none", + "accepted": false + }, + { + "service": "tempo", + "port": 3201, + "client": "worker-client", + "accepted": false + }, + { + "service": "prometheus", + "port": 9090, + "client": "grafana-client", + "accepted": true + }, + { + "service": "prometheus", + "port": 9090, + "client": "none", + "accepted": false + }, + { + "service": "prometheus", + "port": 9090, + "client": "worker-client", + "accepted": false + } +] diff --git a/evidence/tls-checks.txt b/evidence/tls-checks.txt new file mode 100644 index 00000000..27ebda26 --- /dev/null +++ b/evidence/tls-checks.txt @@ -0,0 +1,18 @@ +PASS +PASS +PASS +unexpected TLS result +Traceback (most recent call last): + File "C:\Users\elsem\Desktop\вп\lab7\mtusi2026lab7\tests\test_tls_boundaries.py", line 59, in + main() + ~~~~^^ + File "C:\Users\elsem\Desktop\вп\lab7\mtusi2026lab7\tests\test_tls_boundaries.py", line 53, in main + probe(host,port,role,expected,kind) + ~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "C:\Users\elsem\Desktop\вп\lab7\mtusi2026lab7\tests\test_tls_boundaries.py", line 37, in probe + subprocess.run(cmd,check=True,cwd=ROOT) + ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^ + File "C:\Users\elsem\anaconda3\Lib\subprocess.py", line 578, in run + raise CalledProcessError(retcode, process.args, + output=stdout, stderr=stderr) +subprocess.CalledProcessError: Command '['docker', 'run', '--rm', '--network', 'messenger-lab7_default', '-v', 'C:\\Users\\elsem\\Desktop\\вп\\lab7\\mtusi2026lab7\\certs\\private\\ca.crt:/ca.crt:ro', '-v', 'C:\\Users\\elsem\\Desktop\\вп\\lab7\\mtusi2026lab7\\certs\\private\\worker-client:/identity:ro', 'python:3.11.9-slim', 'python', '-c', "\nimport ssl,socket,sys,json,urllib.request,urllib.error\nhost,port,identity,expected,kind=sys.argv[1:]\nctx=ssl.create_default_context(cafile='/ca.crt')\nif identity=='yes': ctx.load_cert_chain('/identity/tls.crt','/identity/tls.key')\nok=False\ntry:\n if kind=='http':\n try:\n urllib.request.urlopen('https://'+host+':'+port+'/health/live',context=ctx,timeout=5).read()\n ok=True\n except urllib.error.HTTPError:\n ok=True\n elif kind=='redis':\n with socket.create_connection((host,int(port)),timeout=5) as sock:\n with ctx.wrap_socket(sock,server_hostname=host) as tls:\n tls.sendall(b'*1\\\\r\\\\n$4\\\\r\\\\nPING\\\\r\\\\n')\n ok=bool(tls.recv(256))\nexcept (OSError,urllib.error.URLError): pass\nif ok != (expected=='yes'): raise SystemExit('unexpected TLS result')\nprint('PASS')\n", 'broker', '6379', 'yes', 'yes', 'redis']' returned non-zero exit status 1. diff --git a/evidence/verification.txt b/evidence/verification.txt new file mode 100644 index 00000000..230f4b15 --- /dev/null +++ b/evidence/verification.txt @@ -0,0 +1,570 @@ +Lab 7 local verification + +> C:\Users\elsem\anaconda3\python.exe -X utf8 scripts/bootstrap_pki.py +Local PKI created; CA: certs/private/ca.crt + +> docker compose up -d openbao + Container messenger-lab7-openbao-1 Recreate + Container messenger-lab7-openbao-1 Recreated + Container messenger-lab7-openbao-1 Starting + Container messenger-lab7-openbao-1 Started + +> C:\Users\elsem\anaconda3\python.exe -X utf8 scripts/bootstrap_bao.py +OpenBao initialized/unsealed; per-service scoped secrets installed. Operator state kept locally. + +> docker compose config --quiet + +> C:\Users\elsem\anaconda3\python.exe -X utf8 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. + +> docker compose up -d --build + Image python:3.11.9-slim Pulling + Image python:3.11.9-slim Pulling + Image python:3.11.9-slim Pulling + Image python:3.11.9-slim Pulling + Image python:3.11.9-slim Pulling + Image python:3.11.9-slim Pulling + Image python:3.11.9-slim Pulled + Image python:3.11.9-slim Pulled + Image python:3.11.9-slim Pulled + Image python:3.11.9-slim Pulled + Image python:3.11.9-slim Pulled + Image python:3.11.9-slim Pulled + Image messenger:lab7 Building + Image messenger-minio:2025-04 Building + Image messenger:lab7 Building + Image messenger:lab7 Building + Image messenger:lab7 Building + Image messenger:lab7 Building + Image messenger-minio:2025-04 Building +#1 [internal] load local bake definitions +#1 reading from stdin 3.48kB 0.0s done +#1 DONE 0.0s + +#2 [minio internal] load build definition from Dockerfile.minio +#2 DONE 0.0s + +#3 [api internal] load build definition from Dockerfile +#3 transferring dockerfile: 869B done +#3 DONE 0.0s + +#2 [minio internal] load build definition from Dockerfile.minio +#2 transferring dockerfile: 531B done +#2 DONE 0.0s + +#4 [dispatcher internal] load metadata for docker.io/library/python:3.11.9-slim +#4 DONE 0.0s + +#5 [dispatcher internal] load .dockerignore +#5 transferring context: 216B done +#5 DONE 0.0s + +#6 [api internal] load build context +#6 DONE 0.0s + +#7 [cleanup 1/7] FROM docker.io/library/python:3.11.9-slim@sha256:8fb099199b9f2d70342674bd9dbccd3ed03a258f26bbd1d556822c6dfc60c317 +#7 resolve docker.io/library/python:3.11.9-slim@sha256:8fb099199b9f2d70342674bd9dbccd3ed03a258f26bbd1d556822c6dfc60c317 0.0s done +#7 resolve docker.io/library/python:3.11.9-slim@sha256:8fb099199b9f2d70342674bd9dbccd3ed03a258f26bbd1d556822c6dfc60c317 0.0s done +#7 DONE 0.0s + +#6 [api internal] load build context +#6 transferring context: 700B done +#6 DONE 0.0s + +#8 [dispatcher 2/7] WORKDIR /app +#8 CACHED + +#9 [dispatcher 5/7] COPY app.py schemas.py db.py cache.py migrate.py attachments.py cleanup.py pipeline.py worker.py telemetry.py tls_proxy.py api_start.py secret_entry.py ./ +#9 CACHED + +#10 [dispatcher 3/7] COPY requirements.txt . +#10 CACHED + +#11 [dispatcher 4/7] RUN pip install --no-cache-dir -r requirements.txt +#11 CACHED + +#12 [dispatcher 6/7] COPY migrations ./migrations +#12 CACHED + +#13 [dispatcher 7/7] RUN useradd --create-home --shell /bin/bash appuser +#13 CACHED + +#14 [auth] library/golang:pull token for registry-1.docker.io +#14 DONE 0.0s + +#15 [auth] library/alpine:pull token for registry-1.docker.io +#15 DONE 0.0s + +#16 [dispatcher] exporting to image +#16 exporting layers done +#16 exporting manifest sha256:461f72e1d170bc31dffa7cdc3c019c560450f99b6e9e87fd16379fb1adea2dc2 done +#16 exporting config sha256:a82e32cb1c27ef63ecd842c07156b9eaaf74915e3265c43e2bcf4fbe53a6c11f done +#16 exporting attestation manifest sha256:67d7b79d60db89ba2233f264593f5b03134a6f6231a6ef4b96a5fff1b3635710 +#16 exporting attestation manifest sha256:67d7b79d60db89ba2233f264593f5b03134a6f6231a6ef4b96a5fff1b3635710 0.1s done +#16 exporting manifest list sha256:2e0fb02179b6d5f5da442bf55f039fc452fb10710d9f0afde21975ce6fd94495 +#16 exporting manifest list sha256:2e0fb02179b6d5f5da442bf55f039fc452fb10710d9f0afde21975ce6fd94495 0.1s done +#16 naming to docker.io/library/messenger:lab7 0.0s done +#16 unpacking to docker.io/library/messenger:lab7 0.0s done +#16 DONE 0.3s + +#17 [worker] exporting to image +#17 exporting layers done +#17 exporting manifest sha256:174e6d9e8711bc6d6c1c84b6be3111e3141b1407e799f10f79177ad82240e598 0.0s done +#17 exporting config sha256:9b5b6d387674e814a6758e37d88c18f995982c687e5b6ca56643b7ac5ee4a300 0.0s done +#17 exporting attestation manifest sha256:39b8682ac451dbff2b4a67daf975b5822d6bd8f29be75cafcaf2d446cdb04eb1 0.1s done +#17 exporting manifest list sha256:046f5a16ced1d0d48e1e4b0375cbcef024027054209b8a0e8eed8aa691c9cb7d 0.1s done +#17 naming to docker.io/library/messenger:lab7 0.0s done +#17 unpacking to docker.io/library/messenger:lab7 0.0s done +#17 DONE 0.3s + +#18 [cleanup] exporting to image +#18 exporting layers done +#18 exporting manifest sha256:9461d00b4d5f8ae2c8bba1b86d27b53af94d8c2d0abc57f52552561f54443c30 0.0s done +#18 exporting config sha256:184ff2f5b391996ac2906d7c7b05be7ee03fdb74bb82eea0434c07a5a9e612d3 0.0s done +#18 exporting attestation manifest sha256:b99998be7641ef0730df54ccaa1c0252fc3aa0f9084f7e1cb25f814641fb9b4d 0.1s done +#18 exporting manifest list sha256:2a962067607f78246cd2b4f27054ecc78e26951d6ce35667d5d8d5161d209f39 0.1s done +#18 naming to docker.io/library/messenger:lab7 0.0s done +#18 unpacking to docker.io/library/messenger:lab7 0.0s done +#18 DONE 0.3s + +#19 [migrate] exporting to image +#19 exporting layers done +#19 exporting manifest sha256:67cc14fb375db1d86f352beb0e032a3d2f42f089af529411698f607f0573f92f 0.0s done +#19 exporting config sha256:82d3627d378317213cb09c4e6740aaadaa14f8990cebe9e3e09bfa06604782d0 0.0s done +#19 exporting attestation manifest sha256:9ac8d00e0c3232f72713b915612806c40f1d03f3077231c640771a9c577fea02 0.1s done +#19 exporting manifest list sha256:345a484d4f17bda3e91464902041b9a29474d3f776bcade007aa8997360e2086 0.1s done +#19 naming to docker.io/library/messenger:lab7 0.0s done +#19 unpacking to docker.io/library/messenger:lab7 0.0s done +#19 DONE 0.3s + +#20 [api] exporting to image +#20 exporting layers done +#20 exporting manifest sha256:16f4600da48faf25008ab0bb236b5b938f9dc9cd543dd67b9a934f380bab5bbb 0.0s done +#20 exporting config sha256:805f2a3e47bc4641680cc332b151c0c2abe6f7d976c22671a6ac511a5648f900 0.0s done +#20 exporting attestation manifest sha256:02a281f04aac68d94889d9a1873acbea5a026b8744cb08272469cbd8d7a569bb 0.1s done +#20 exporting manifest list sha256:fbd975d3366561ea6eadced7a8470c6cb8efe9d3f85d35b6f0f0979e27a785f6 0.1s done +#20 naming to docker.io/library/messenger:lab7 done +#20 unpacking to docker.io/library/messenger:lab7 0.0s done +#20 DONE 0.4s + +#21 [s3-init internal] load metadata for docker.io/library/alpine:3.21.3 +#21 ... + +#22 [dispatcher] resolving provenance for metadata file +#22 DONE 0.1s + +#23 [worker] resolving provenance for metadata file +#23 DONE 0.1s + +#24 [cleanup] resolving provenance for metadata file +#24 DONE 0.1s + +#25 [migrate] resolving provenance for metadata file +#25 DONE 0.0s + +#26 [api] resolving provenance for metadata file +#26 DONE 0.0s + +#27 [minio internal] load metadata for docker.io/library/golang:1.24.3-alpine +#27 DONE 0.9s + +#21 [minio internal] load metadata for docker.io/library/alpine:3.21.3 +#21 DONE 0.9s + +#5 [minio internal] load .dockerignore +#5 CACHED + +#28 [minio builder 1/4] FROM docker.io/library/golang:1.24.3-alpine@sha256:b4f875e650466fa0fe62c6fd3f02517a392123eea85f1d7e69d85f780e4db1c1 +#28 resolve docker.io/library/golang:1.24.3-alpine@sha256:b4f875e650466fa0fe62c6fd3f02517a392123eea85f1d7e69d85f780e4db1c1 0.0s done +#28 DONE 0.0s + +#29 [s3-init stage-1 1/3] FROM docker.io/library/alpine:3.21.3@sha256:a8560b36e8b8210634f77d9f7f9efd7ffa463e380b75e2e74aff4511df3ef88c +#29 resolve docker.io/library/alpine:3.21.3@sha256:a8560b36e8b8210634f77d9f7f9efd7ffa463e380b75e2e74aff4511df3ef88c 0.0s done +#29 DONE 0.0s + +#30 [minio builder 2/4] RUN apk add --no-cache git ca-certificates +#30 CACHED + +#31 [minio builder 4/4] RUN go install github.com/minio/mc@RELEASE.2025-04-16T18-13-26Z +#31 CACHED + +#32 [minio builder 3/4] RUN go install github.com/minio/minio@RELEASE.2025-04-22T22-12-26Z +#32 CACHED + +#33 [minio stage-1 2/3] RUN apk add --no-cache ca-certificates +#33 CACHED + +#34 [minio stage-1 3/3] COPY --from=builder /go/bin/minio /go/bin/mc /usr/local/bin/ +#34 CACHED + +#35 [s3-init] exporting to image +#35 exporting layers done +#35 exporting manifest sha256:2fd7e37631ae469ed2c1c6e11d50b54a9724c46071a6b28ff26a4da068804737 done +#35 exporting config sha256:c5c43b9d9410d62b60ba951f90eef59a3406e976ac3dd1c3ea5061372f32b81b done +#35 exporting attestation manifest sha256:8fbba69aa07d70881b441abffb2d1e7ef95849cb0fdb86efdcae04d44c514dd8 0.0s done +#35 exporting manifest list sha256:bff3198145709c56dccc1b0ca9f5d1f25ba2c12444f73fbe9ed2bc3d4b765e56 0.0s done +#35 naming to docker.io/library/messenger-minio:2025-04 +#35 naming to docker.io/library/messenger-minio:2025-04 done +#35 unpacking to docker.io/library/messenger-minio:2025-04 0.0s done +#35 DONE 0.1s + +#36 [minio] exporting to image +#36 exporting layers done +#36 exporting manifest sha256:6bfa55128913c1de6e9034a0cf1dd509e2c1ed50d7515dba0bb48582ec0ca5f8 done +#36 exporting config sha256:4a45bbba00b8d8630ab95aa81906115f3de0be77fc88efed9cda1fae816c9682 done +#36 exporting attestation manifest sha256:8fdda64f0a986591f954e8ca6bac7dc0c15adb8915cde3177f0d3ee671a0957a 0.0s done +#36 exporting manifest list sha256:45e4c8c5fde6a9e6c28bd005cdf65f7f57ca2c1742e23fcbb753c8e1d9f2a29a 0.0s done +#36 naming to docker.io/library/messenger-minio:2025-04 done +#36 unpacking to docker.io/library/messenger-minio:2025-04 0.0s done +#36 DONE 0.1s + +#37 [s3-init] resolving provenance for metadata file +#37 DONE 0.0s + +#38 [minio] resolving provenance for metadata file +#38 DONE 0.0s + Image messenger-minio:2025-04 Built + Image messenger:lab7 Built + Image messenger:lab7 Built + Image messenger:lab7 Built + Image messenger:lab7 Built + Image messenger:lab7 Built + Image messenger-minio:2025-04 Built + Container messenger-lab7-openbao-1 Running + Volume messenger-lab7_promdata Creating + Container messenger-lab7-collector-1 Creating + Volume messenger-lab7_tempodata Creating + Container messenger-lab7-redis-1 Creating + Volume messenger-lab7_grafanadata Creating + Volume messenger-lab7_grafanadata Creating + Volume messenger-lab7_lokidata Creating + Volume messenger-lab7_lokidata Creating + Volume messenger-lab7_pgdata Creating + Volume messenger-lab7_pgdata Creating + Volume messenger-lab7_tempodata Creating + Volume messenger-lab7_promdata Creating + Volume messenger-lab7_s3data Creating + Volume messenger-lab7_s3data Creating + Volume messenger-lab7_brokerdata Creating + Volume messenger-lab7_brokerdata Creating + Volume messenger-lab7_pgdata Created + Volume messenger-lab7_pgdata Created + Container messenger-lab7-postgres-1 Creating + Volume messenger-lab7_tempodata Created + Volume messenger-lab7_tempodata Created + Container messenger-lab7-tempo-1 Creating + Volume messenger-lab7_grafanadata Created + Volume messenger-lab7_grafanadata Created + Container messenger-lab7-grafana-1 Creating + Volume messenger-lab7_promdata Created + Volume messenger-lab7_promdata Created + Container messenger-lab7-prometheus-1 Creating + Volume messenger-lab7_lokidata Created + Volume messenger-lab7_lokidata Created + Container messenger-lab7-loki-1 Creating + Volume messenger-lab7_brokerdata Created + Volume messenger-lab7_brokerdata Created + Container messenger-lab7-broker-1 Creating + Volume messenger-lab7_s3data Created + Volume messenger-lab7_s3data Created + Container messenger-lab7-minio-1 Creating + Container messenger-lab7-tempo-1 Created + Container messenger-lab7-tempo-ingest-tls-1 Creating + Container messenger-lab7-tempo-query-tls-1 Creating + Container messenger-lab7-collector-1 Created + Container messenger-lab7-collector-scrape-tls-1 Creating + Container messenger-lab7-collector-tls-1 Creating + Container messenger-lab7-grafana-1 Created + Container messenger-lab7-minio-1 Created + Container messenger-lab7-s3-init-1 Creating + Container messenger-lab7-prometheus-1 Created + Container messenger-lab7-loki-1 Created + Container messenger-lab7-loki-tls-1 Creating + Container messenger-lab7-postgres-1 Created + Container messenger-lab7-migrate-1 Creating + Container messenger-lab7-redis-1 Created + Container messenger-lab7-broker-1 Created + Container messenger-lab7-broker-tls-1 Creating + Container messenger-lab7-tempo-ingest-tls-1 Created + Container messenger-lab7-tempo-query-tls-1 Created + Container messenger-lab7-collector-scrape-tls-1 Created + Container messenger-lab7-collector-tls-1 Created + Container messenger-lab7-s3-init-1 Created + Container messenger-lab7-migrate-1 Created + Container messenger-lab7-api-1 Creating + Container messenger-lab7-worker-1 Creating + Container messenger-lab7-dispatcher-1 Creating + Container messenger-lab7-api-2 Creating + Container messenger-lab7-cleanup-1 Creating + Container messenger-lab7-loki-tls-1 Created + Container messenger-lab7-broker-tls-1 Created + Container messenger-lab7-cleanup-1 Created + Container messenger-lab7-api-1 Created + Container messenger-lab7-worker-1 Created + Container messenger-lab7-dispatcher-1 Created + Container messenger-lab7-api-2 Created + Container messenger-lab7-nginx-1 Creating + Container messenger-lab7-nginx-1 Created + Container messenger-lab7-collector-1 Starting + Container messenger-lab7-broker-1 Starting + Container messenger-lab7-minio-1 Starting + Container messenger-lab7-loki-1 Starting + Container messenger-lab7-postgres-1 Starting + Container messenger-lab7-grafana-1 Starting + Container messenger-lab7-prometheus-1 Starting + Container messenger-lab7-redis-1 Starting + Container messenger-lab7-tempo-1 Starting + Container messenger-lab7-collector-1 Started + Container messenger-lab7-collector-scrape-tls-1 Starting + Container messenger-lab7-collector-tls-1 Starting + Container messenger-lab7-collector-scrape-tls-1 Started + Container messenger-lab7-broker-1 Started + Container messenger-lab7-broker-1 Waiting + Container messenger-lab7-minio-1 Started + Container messenger-lab7-s3-init-1 Starting + Container messenger-lab7-loki-1 Started + Container messenger-lab7-loki-tls-1 Starting + Container messenger-lab7-grafana-1 Started + Container messenger-lab7-prometheus-1 Started + Container messenger-lab7-postgres-1 Started + Container messenger-lab7-postgres-1 Waiting + Container messenger-lab7-redis-1 Started + Container messenger-lab7-tempo-1 Started + Container messenger-lab7-tempo-ingest-tls-1 Starting + Container messenger-lab7-tempo-query-tls-1 Starting + Container messenger-lab7-collector-tls-1 Started + Container messenger-lab7-s3-init-1 Started + Container messenger-lab7-loki-tls-1 Started + Container messenger-lab7-tempo-ingest-tls-1 Started + Container messenger-lab7-broker-1 Healthy + Container messenger-lab7-broker-tls-1 Starting + Container messenger-lab7-tempo-query-tls-1 Started + Container messenger-lab7-broker-tls-1 Started + Container messenger-lab7-postgres-1 Healthy + Container messenger-lab7-migrate-1 Starting + Container messenger-lab7-migrate-1 Started + Container messenger-lab7-migrate-1 Waiting + Container messenger-lab7-s3-init-1 Waiting + Container messenger-lab7-broker-1 Waiting + Container messenger-lab7-migrate-1 Waiting + Container messenger-lab7-s3-init-1 Waiting + Container messenger-lab7-s3-init-1 Waiting + Container messenger-lab7-migrate-1 Waiting + Container messenger-lab7-broker-1 Waiting + Container messenger-lab7-migrate-1 Waiting + Container messenger-lab7-broker-1 Healthy + Container messenger-lab7-broker-1 Healthy + Container messenger-lab7-s3-init-1 Exited + Container messenger-lab7-s3-init-1 Exited + Container messenger-lab7-s3-init-1 Exited + Container messenger-lab7-migrate-1 Exited + Container messenger-lab7-worker-1 Starting + Container messenger-lab7-migrate-1 Exited + Container messenger-lab7-migrate-1 Exited + Container messenger-lab7-dispatcher-1 Starting + Container messenger-lab7-api-2 Starting + Container messenger-lab7-migrate-1 Exited + Container messenger-lab7-cleanup-1 Starting + Container messenger-lab7-worker-1 Started + Container messenger-lab7-dispatcher-1 Started + Container messenger-lab7-api-2 Started + Container messenger-lab7-api-1 Starting + Container messenger-lab7-api-1 Started + Container messenger-lab7-api-2 Waiting + Container messenger-lab7-api-1 Waiting + Container messenger-lab7-cleanup-1 Started + Container messenger-lab7-api-2 Healthy + Container messenger-lab7-api-1 Healthy + Container messenger-lab7-nginx-1 Starting + Container messenger-lab7-nginx-1 Started + +> docker compose ps -a +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +messenger-lab7-api-1 messenger:lab7 "python secret_entry…" api 19 seconds ago Up 8 seconds (healthy) 8080/tcp +messenger-lab7-api-2 messenger:lab7 "python secret_entry…" api 19 seconds ago Up 9 seconds (healthy) 8080/tcp +messenger-lab7-broker-1 redis:7.4.2-alpine "docker-entrypoint.s…" broker 20 seconds ago Up 18 seconds (healthy) 6379/tcp +messenger-lab7-broker-tls-1 python:3.11.9-slim "python /tls_proxy.py" broker-tls 20 seconds ago Up 14 seconds +messenger-lab7-cleanup-1 messenger:lab7 "python secret_entry…" cleanup 19 seconds ago Up 8 seconds 8080/tcp +messenger-lab7-collector-1 otel/opentelemetry-collector-contrib:0.123.0 "/otelcol-contrib --…" collector 20 seconds ago Up 18 seconds 4317-4318/tcp, 55678-55679/tcp +messenger-lab7-collector-scrape-tls-1 python:3.11.9-slim "python /tls_proxy.py" collector-scrape-tls 20 seconds ago Up 18 seconds +messenger-lab7-collector-tls-1 python:3.11.9-slim "python /tls_proxy.py" collector-tls 20 seconds ago Up 15 seconds +messenger-lab7-dispatcher-1 messenger:lab7 "python secret_entry…" dispatcher 19 seconds ago Up 9 seconds 8080/tcp +messenger-lab7-grafana-1 grafana/grafana:11.6.0 "/run.sh" grafana 20 seconds ago Up 17 seconds 127.0.0.1:3001->3000/tcp +messenger-lab7-loki-1 grafana/loki:3.4.2 "/usr/bin/loki -conf…" loki 20 seconds ago Up 17 seconds 3100/tcp +messenger-lab7-loki-tls-1 python:3.11.9-slim "python /tls_proxy.py" loki-tls 20 seconds ago Up 15 seconds +messenger-lab7-migrate-1 messenger:lab7 "python secret_entry…" migrate 20 seconds ago Exited (0) 10 seconds ago +messenger-lab7-minio-1 messenger-minio:2025-04 "minio server /data …" minio 20 seconds ago Up 17 seconds 9000-9001/tcp +messenger-lab7-nginx-1 nginx:1.28.0-alpine "/docker-entrypoint.…" nginx 19 seconds ago Up 2 seconds 127.0.0.1:8443->443/tcp +messenger-lab7-openbao-1 quay.io/openbao/openbao:2.2.2 "docker-entrypoint.s…" openbao About a minute ago Up About a minute 127.0.0.1:8200->8200/tcp +messenger-lab7-postgres-1 postgres:17.6-alpine "/bin/sh /pg-start.sh" postgres 20 seconds ago Up 16 seconds (healthy) 5432/tcp +messenger-lab7-prometheus-1 prom/prometheus:v3.2.1 "/bin/prometheus --c…" prometheus 20 seconds ago Up 17 seconds 9090/tcp +messenger-lab7-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 20 seconds ago Up 16 seconds (healthy) 6379/tcp +messenger-lab7-s3-init-1 messenger-minio:2025-04 "/bin/sh /init.sh" s3-init 20 seconds ago Exited (0) 11 seconds ago +messenger-lab7-tempo-1 grafana/tempo:2.7.2 "/tempo -config.file…" tempo 20 seconds ago Up 16 seconds +messenger-lab7-tempo-ingest-tls-1 python:3.11.9-slim "python /tls_proxy.py" tempo-ingest-tls 20 seconds ago Up 15 seconds +messenger-lab7-tempo-query-tls-1 python:3.11.9-slim "python /tls_proxy.py" tempo-query-tls 20 seconds ago Up 14 seconds +messenger-lab7-worker-1 messenger:lab7 "python secret_entry…" worker 19 seconds ago Up 9 seconds 8080/tcp + +> C:\Users\elsem\anaconda3\python.exe -X utf8 tests/smoke.py --ca-file certs/private/ca.crt +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. + +> C:\Users\elsem\anaconda3\python.exe -X utf8 tests/test_idempotency_race.py --ca-file certs/private/ca.crt +PASS: 16 concurrent requests, at least 2 replicas, exactly 1 message + +> C:\Users\elsem\anaconda3\python.exe -X utf8 tests/resilience.py --mode failover --action-script scripts/stop-one.cmd --ca-file certs/private/ca.crt +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 116, "failed_attempts": 0, "first_recovery_seconds": 2.532} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. + +> docker compose ps -a api +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +messenger-lab7-api-1 messenger:lab7 "python secret_entry…" api 41 seconds ago Up 30 seconds (healthy) 8080/tcp +messenger-lab7-api-2 messenger:lab7 "python secret_entry…" api 41 seconds ago Exited (241) 13 seconds ago + +> docker compose up -d api + Container messenger-lab7-api-1 Running + Container messenger-lab7-postgres-1 Running + Container messenger-lab7-minio-1 Running + Container messenger-lab7-s3-init-1 Starting + Container messenger-lab7-postgres-1 Waiting + Container messenger-lab7-s3-init-1 Started + Container messenger-lab7-postgres-1 Healthy + Container messenger-lab7-migrate-1 Starting + Container messenger-lab7-migrate-1 Started + Container messenger-lab7-s3-init-1 Waiting + Container messenger-lab7-migrate-1 Waiting + Container messenger-lab7-s3-init-1 Exited + Container messenger-lab7-migrate-1 Exited + Container messenger-lab7-api-2 Starting + Container messenger-lab7-api-2 Started + +> C:\Users\elsem\anaconda3\python.exe -X utf8 tests/test_pipeline.py --ca-file certs/private/ca.crt + Container messenger-lab7-worker-1 Stopping + Container messenger-lab7-dispatcher-1 Stopping + Container messenger-lab7-worker-1 Stopped + Container messenger-lab7-dispatcher-1 Stopped + Container messenger-lab7-broker-1 Restarting + Container messenger-lab7-api-1 Restarting + Container messenger-lab7-api-2 Restarting + Container messenger-lab7-broker-1 Started + Container messenger-lab7-api-1 Started + Container messenger-lab7-api-2 Started + Container messenger-lab7-postgres-1 Waiting + Container messenger-lab7-postgres-1 Healthy + Container messenger-lab7-migrate-1 Starting + Container messenger-lab7-migrate-1 Started + Container messenger-lab7-broker-1 Waiting + Container messenger-lab7-migrate-1 Waiting + Container messenger-lab7-migrate-1 Exited + Container messenger-lab7-broker-1 Healthy + Container messenger-lab7-dispatcher-1 Starting + Container messenger-lab7-dispatcher-1 Started + Container messenger-lab7-s3-init-1 Starting + Container messenger-lab7-postgres-1 Waiting + Container messenger-lab7-s3-init-1 Started + Container messenger-lab7-postgres-1 Healthy + Container messenger-lab7-migrate-1 Starting + Container messenger-lab7-migrate-1 Started + Container messenger-lab7-broker-1 Waiting + Container messenger-lab7-migrate-1 Waiting + Container messenger-lab7-s3-init-1 Waiting + Container messenger-lab7-broker-1 Healthy + Container messenger-lab7-s3-init-1 Exited + Container messenger-lab7-migrate-1 Exited + Container messenger-lab7-worker-1 Starting + Container messenger-lab7-worker-1 Started +PASS: committed job recovered after API/broker restart and delayed dispatcher +PASS: worker crash after S3 write recovered with exactly three variants + Container messenger-lab7-s3-init-1 Starting + Container messenger-lab7-postgres-1 Waiting + Container messenger-lab7-s3-init-1 Started + Container messenger-lab7-postgres-1 Healthy + Container messenger-lab7-migrate-1 Starting + Container messenger-lab7-migrate-1 Started + Container messenger-lab7-migrate-1 Waiting + Container messenger-lab7-broker-1 Waiting + Container messenger-lab7-migrate-1 Waiting + Container messenger-lab7-broker-1 Waiting + Container messenger-lab7-s3-init-1 Waiting + Container messenger-lab7-broker-1 Healthy + Container messenger-lab7-broker-1 Healthy + Container messenger-lab7-s3-init-1 Exited + Container messenger-lab7-migrate-1 Exited + Container messenger-lab7-migrate-1 Exited + +> C:\Users\elsem\anaconda3\python.exe -X utf8 tests/security.py --ca-file certs/private/ca.crt +PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening. + +> C:\Users\elsem\anaconda3\python.exe -X utf8 tests/test_tls_boundaries.py +PASS +PASS +PASS +unexpected TLS result +Traceback (most recent call last): + File "C:\Users\elsem\Desktop\вп\lab7\mtusi2026lab7\tests\test_tls_boundaries.py", line 59, in + main() + ~~~~^^ + File "C:\Users\elsem\Desktop\вп\lab7\mtusi2026lab7\tests\test_tls_boundaries.py", line 53, in main + probe(host,port,role,expected,kind) + ~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "C:\Users\elsem\Desktop\вп\lab7\mtusi2026lab7\tests\test_tls_boundaries.py", line 37, in probe + subprocess.run(cmd,check=True,cwd=ROOT) + ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^ + File "C:\Users\elsem\anaconda3\Lib\subprocess.py", line 578, in run + raise CalledProcessError(retcode, process.args, + output=stdout, stderr=stderr) +subprocess.CalledProcessError: Command '['docker', 'run', '--rm', '--network', 'messenger-lab7_default', '-v', 'C:\\Users\\elsem\\Desktop\\вп\\lab7\\mtusi2026lab7\\certs\\private\\ca.crt:/ca.crt:ro', '-v', 'C:\\Users\\elsem\\Desktop\\вп\\lab7\\mtusi2026lab7\\certs\\private\\worker-client:/identity:ro', 'python:3.11.9-slim', 'python', '-c', "\nimport ssl,socket,sys,json,urllib.request,urllib.error\nhost,port,identity,expected,kind=sys.argv[1:]\nctx=ssl.create_default_context(cafile='/ca.crt')\nif identity=='yes': ctx.load_cert_chain('/identity/tls.crt','/identity/tls.key')\nok=False\ntry:\n if kind=='http':\n try:\n urllib.request.urlopen('https://'+host+':'+port+'/health/live',context=ctx,timeout=5).read()\n ok=True\n except urllib.error.HTTPError:\n ok=True\n elif kind=='redis':\n with socket.create_connection((host,int(port)),timeout=5) as sock:\n with ctx.wrap_socket(sock,server_hostname=host) as tls:\n tls.sendall(b'*1\\\\r\\\\n$4\\\\r\\\\nPING\\\\r\\\\n')\n ok=bool(tls.recv(256))\nexcept (OSError,urllib.error.URLError): pass\nif ok != (expected=='yes'): raise SystemExit('unexpected TLS result')\nprint('PASS')\n", 'broker', '6379', 'yes', 'yes', 'redis']' returned non-zero exit status 1. + +> C:\Users\elsem\anaconda3\python.exe -X utf8 tests/test_tls_boundaries.py +PASS +PASS +PASS +PASS +PASS +PASS +PASS +PASS +PASS +PASS +PASS +PASS +PASS +PASS +PASS +PASS +PASS +PASS +PASS +PASS +PASS +PASS +PASS +PASS + +> C:\Users\elsem\anaconda3\python.exe -X utf8 tests/test_bao_policy.py +PASS: API certificate grants only its own secret read + +> C:\Users\elsem\anaconda3\python.exe -X utf8 tests/hash_cost.py +{"memory_kib": 19456, "t": 2, "p": 1, "hash_median_ms": 21.902915499993014, "hash_max_ms": 35.0332680000065, "peak_rss_kib": 32648} + +> C:\Users\elsem\anaconda3\python.exe -X utf8 tests/test_rotation.py +Local PKI created; CA: certs/private/ca.crt + Container messenger-lab7-nginx-1 Restarting + Container messenger-lab7-nginx-1 Started +PASS +PASS +OpenBao initialized/unsealed; per-service scoped secrets installed. Operator state kept locally. + Container messenger-lab7-redis-1 Recreate + Container messenger-lab7-redis-1 Recreated + Container messenger-lab7-redis-1 Starting + Container messenger-lab7-redis-1 Started + Container messenger-lab7-api-1 Restarting + Container messenger-lab7-api-2 Restarting + Container messenger-lab7-api-2 Started + Container messenger-lab7-api-1 Started +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. +PASS: certificate and cache secret rotated without image rebuild + +> C:\Users\elsem\anaconda3\python.exe -X utf8 tests/resilience.py --mode persistence --action-script scripts/restart.cmd --ca-file certs/private/ca.crt +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/worker-permissions.json b/evidence/worker-permissions.json new file mode 100644 index 00000000..f7c9a799 --- /dev/null +++ b/evidence/worker-permissions.json @@ -0,0 +1,5 @@ +{ + "postgres_tls_and_table_acl": true, + "s3_tls_and_prefix_acl": true, + "broker_mtls_and_command_acl": true +} diff --git a/infra/Dockerfile.minio b/infra/Dockerfile.minio new file mode 100644 index 00000000..f350eb8e --- /dev/null +++ b/infra/Dockerfile.minio @@ -0,0 +1,12 @@ +# Build the pinned community releases directly from official Go modules. +FROM golang:1.24.3-alpine AS builder +RUN apk add --no-cache git ca-certificates +ENV CGO_ENABLED=0 GOFLAGS=-p=4 GOMAXPROCS=4 +RUN go install github.com/minio/minio@RELEASE.2025-04-22T22-12-26Z +RUN go install github.com/minio/mc@RELEASE.2025-04-16T18-13-26Z + +FROM alpine:3.21.3 +RUN apk add --no-cache ca-certificates +COPY --from=builder /go/bin/minio /go/bin/mc /usr/local/bin/ +EXPOSE 9000 9001 +ENTRYPOINT ["minio"] diff --git a/infra/alerts.yml b/infra/alerts.yml new file mode 100644 index 00000000..74474de5 --- /dev/null +++ b/infra/alerts.yml @@ -0,0 +1,17 @@ +groups: + - name: messenger + rules: + - alert: HighHTTPErrorRate + expr: sum(rate(messenger_http_requests_total{status_class="5xx",route!~"/health/.*"}[1m])) / clamp_min(sum(rate(messenger_http_requests_total{route!~"/health/.*"}[1m])),0.001) > 0.05 + for: 10s + labels: + severity: warning + annotations: + summary: API errors above 5 percent + - alert: OldAttachmentJob + expr: max(messenger_queue_oldest_seconds{service_name="messenger-dispatcher"}) > 15 + for: 10s + labels: + severity: warning + annotations: + summary: Attachment backlog older than 15 seconds diff --git a/infra/db-roles.sh b/infra/db-roles.sh new file mode 100644 index 00000000..05878d5f --- /dev/null +++ b/infra/db-roles.sh @@ -0,0 +1,12 @@ +#!/bin/sh +set -eu +psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<'SQL' +\getenv apipw API_DB_PASSWORD +\getenv workerpw WORKER_DB_PASSWORD +\getenv dispatcherpw DISPATCHER_DB_PASSWORD +\getenv cleanuppw CLEANUP_DB_PASSWORD +CREATE ROLE messenger_api LOGIN PASSWORD :'apipw'; +CREATE ROLE messenger_worker LOGIN PASSWORD :'workerpw'; +CREATE ROLE messenger_dispatcher LOGIN PASSWORD :'dispatcherpw'; +CREATE ROLE messenger_cleanup LOGIN PASSWORD :'cleanuppw'; +SQL diff --git a/infra/grafana/dashboards/messenger.json b/infra/grafana/dashboards/messenger.json new file mode 100644 index 00000000..c8ad567b --- /dev/null +++ b/infra/grafana/dashboards/messenger.json @@ -0,0 +1,16 @@ +{ + "uid":"messenger", "title":"Messenger — Lab 6", "schemaVersion":39, "version":1, + "refresh":"5s", "time":{"from":"now-15m","to":"now"}, + "panels":[ + {"id":1,"title":"HTTP successful RPS","type":"timeseries","gridPos":{"x":0,"y":0,"w":12,"h":8},"datasource":{"uid":"prometheus"},"targets":[{"expr":"sum(rate(messenger_http_requests_total{status_class=\"2xx\",route!~\"/health/.*\"}[1m]))","legendFormat":"RPS"}]}, + {"id":2,"title":"HTTP 5xx ratio","type":"timeseries","gridPos":{"x":12,"y":0,"w":12,"h":8},"datasource":{"uid":"prometheus"},"targets":[{"expr":"sum(rate(messenger_http_requests_total{status_class=\"5xx\",route!~\"/health/.*\"}[1m])) / clamp_min(sum(rate(messenger_http_requests_total{route!~\"/health/.*\"}[1m])),0.001)","legendFormat":"error ratio"}]}, + {"id":3,"title":"HTTP latency seconds p50/p95/p99","type":"timeseries","gridPos":{"x":0,"y":8,"w":12,"h":8},"datasource":{"uid":"prometheus"},"targets":[{"expr":"histogram_quantile(0.5,sum by(le)(rate(messenger_http_duration_seconds_bucket[1m])))","legendFormat":"p50"},{"expr":"histogram_quantile(0.95,sum by(le)(rate(messenger_http_duration_seconds_bucket[1m])))","legendFormat":"p95"},{"expr":"histogram_quantile(0.99,sum by(le)(rate(messenger_http_duration_seconds_bucket[1m])))","legendFormat":"p99"}]}, + {"id":4,"title":"Jobs per second by outcome","type":"timeseries","gridPos":{"x":12,"y":8,"w":12,"h":8},"datasource":{"uid":"prometheus"},"targets":[{"expr":"sum by(outcome)(rate(messenger_job_processed_total[1m]))","legendFormat":"{{outcome}}"}]}, + {"id":5,"title":"Queue depth / oldest seconds","type":"timeseries","gridPos":{"x":0,"y":16,"w":12,"h":8},"datasource":{"uid":"prometheus"},"targets":[{"expr":"max(messenger_queue_depth{service_name=\"messenger-dispatcher\"})","legendFormat":"depth"},{"expr":"max(messenger_queue_oldest_seconds{service_name=\"messenger-dispatcher\"})","legendFormat":"oldest seconds"}]}, + {"id":6,"title":"Worker duration / ready p95 seconds","type":"timeseries","gridPos":{"x":12,"y":16,"w":12,"h":8},"datasource":{"uid":"prometheus"},"targets":[{"expr":"histogram_quantile(0.95,sum by(le)(rate(messenger_job_duration_seconds_bucket[1m])))","legendFormat":"worker"},{"expr":"histogram_quantile(0.95,sum by(le)(rate(messenger_ready_duration_seconds_bucket[1m])))","legendFormat":"end-to-end"}]}, + {"id":7,"title":"DB pool used / waiting","type":"timeseries","gridPos":{"x":0,"y":24,"w":12,"h":8},"datasource":{"uid":"prometheus"},"targets":[{"expr":"sum by(service_name)(messenger_db_pool_used)","legendFormat":"used {{service_name}}"},{"expr":"sum by(service_name)(messenger_db_pool_waiting)","legendFormat":"waiting {{service_name}}"}]}, + {"id":8,"title":"Worker saturation","type":"timeseries","gridPos":{"x":12,"y":24,"w":12,"h":8},"datasource":{"uid":"prometheus"},"targets":[{"expr":"sum(messenger_worker_busy) / clamp_min(sum(messenger_worker_capacity),1)","legendFormat":"busy ratio"}]}, + {"id":9,"title":"Process CPU seconds per second","type":"timeseries","gridPos":{"x":0,"y":32,"w":12,"h":8},"datasource":{"uid":"prometheus"},"targets":[{"expr":"sum by(service_name)(rate(messenger_process_cpu_seconds_total[1m]))","legendFormat":"{{service_name}}"}]}, + {"id":10,"title":"Peak process memory bytes","type":"timeseries","gridPos":{"x":12,"y":32,"w":12,"h":8},"datasource":{"uid":"prometheus"},"targets":[{"expr":"max by(service_name)(messenger_process_peak_memory_bytes)","legendFormat":"{{service_name}}"}]} + ] +} diff --git a/infra/grafana/provisioning/dashboards/dashboards.yaml b/infra/grafana/provisioning/dashboards/dashboards.yaml new file mode 100644 index 00000000..7d9c1bc5 --- /dev/null +++ b/infra/grafana/provisioning/dashboards/dashboards.yaml @@ -0,0 +1,6 @@ +apiVersion: 1 +providers: + - name: Messenger + type: file + options: + path: /var/lib/grafana/dashboards diff --git a/infra/grafana/provisioning/datasources/datasources.yaml b/infra/grafana/provisioning/datasources/datasources.yaml new file mode 100644 index 00000000..f03287e1 --- /dev/null +++ b/infra/grafana/provisioning/datasources/datasources.yaml @@ -0,0 +1,18 @@ +apiVersion: 1 +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + - name: Loki + uid: loki + type: loki + access: proxy + url: http://loki:3100 + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: http://tempo:3200 diff --git a/infra/loki.yaml b/infra/loki.yaml new file mode 100644 index 00000000..8857dddd --- /dev/null +++ b/infra/loki.yaml @@ -0,0 +1,29 @@ +auth_enabled: false +server: + http_listen_port: 3100 + http_listen_address: 127.0.0.1 + grpc_listen_address: 127.0.0.1 +common: + instance_addr: 127.0.0.1 + path_prefix: /loki + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + replication_factor: 1 + ring: + kvstore: + store: inmemory +schema_config: + configs: + - from: 2024-01-01 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h +limits_config: + allow_structured_metadata: true +analytics: + reporting_enabled: false diff --git a/infra/nginx.conf b/infra/nginx.conf new file mode 100644 index 00000000..468aeace --- /dev/null +++ b/infra/nginx.conf @@ -0,0 +1,41 @@ +events { + worker_connections 1024; +} + +http { + resolver 127.0.0.11 valid=2s ipv6=off; + resolver_timeout 2s; + + upstream api_backend { + zone api_backend 64k; + server api:8443 resolve max_fails=1 fail_timeout=3s; + } + + server { + listen 443 ssl; + ssl_certificate /ingress/tls.crt; + ssl_certificate_key /ingress/tls.key; + ssl_protocols TLSv1.2 TLSv1.3; + client_max_body_size 12m; + client_body_timeout 30s; + + location / { + proxy_pass https://api_backend; + proxy_ssl_server_name on; + proxy_ssl_name api; + proxy_ssl_verify on; + proxy_ssl_trusted_certificate /ca/ca.crt; + proxy_ssl_certificate /client/tls.crt; + proxy_ssl_certificate_key /client/tls.key; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_connect_timeout 1s; + proxy_read_timeout 8s; + proxy_send_timeout 8s; + # Do not automatically replay already-sent POST requests. + proxy_next_upstream error timeout http_502 http_503 http_504; + proxy_next_upstream_tries 2; + } + } +} diff --git a/infra/openbao.hcl b/infra/openbao.hcl new file mode 100644 index 00000000..ef780d9b --- /dev/null +++ b/infra/openbao.hcl @@ -0,0 +1,12 @@ +ui = true +storage "file" { + path = "/openbao/file" +} +listener "tcp" { + address = "0.0.0.0:8200" + tls_cert_file = "/tls/tls.crt" + tls_key_file = "/tls/tls.key" + tls_client_ca_file = "/ca/ca.crt" + tls_disable_client_certs = false +} +api_addr = "https://openbao:8200" diff --git a/infra/otel.yaml b/infra/otel.yaml new file mode 100644 index 00000000..3a374207 --- /dev/null +++ b/infra/otel.yaml @@ -0,0 +1,56 @@ +receivers: + otlp: + protocols: + http: + endpoint: 127.0.0.1:4318 + grpc: + endpoint: 127.0.0.1:4317 +processors: + memory_limiter: + check_interval: 1s + limit_mib: 180 + spike_limit_mib: 40 + batch: + timeout: 2s + send_batch_size: 128 +exporters: + prometheus: + endpoint: 127.0.0.1:8889 + resource_to_telemetry_conversion: + enabled: true + otlphttp/tempo: + endpoint: https://tempo:4319 + tls: + ca_file: /ca/ca.crt + cert_file: /identity/tls.crt + key_file: /identity/tls.key + sending_queue: + queue_size: 64 + retry_on_failure: + max_interval: 5s + max_elapsed_time: 15s + otlphttp/loki: + endpoint: https://loki:3101/otlp + tls: + ca_file: /ca/ca.crt + cert_file: /identity/tls.crt + key_file: /identity/tls.key + sending_queue: + queue_size: 64 + retry_on_failure: + max_interval: 5s + max_elapsed_time: 15s +service: + pipelines: + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [prometheus] + traces: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/tempo] + logs: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/loki] diff --git a/infra/pg-start.sh b/infra/pg-start.sh new file mode 100644 index 00000000..39eae95c --- /dev/null +++ b/infra/pg-start.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -eu +mkdir -p /tmp/pg-tls +cp /tls/tls.key /tmp/pg-tls/server.key +cp /tls/tls.crt /tmp/pg-tls/server.crt +chown postgres:postgres /tmp/pg-tls/server.key /tmp/pg-tls/server.crt +chmod 600 /tmp/pg-tls/server.key +exec docker-entrypoint.sh postgres -c ssl=on -c ssl_cert_file=/tmp/pg-tls/server.crt -c ssl_key_file=/tmp/pg-tls/server.key -c hba_file=/etc/pg_hba.conf diff --git a/infra/pg_hba.conf b/infra/pg_hba.conf new file mode 100644 index 00000000..20926347 --- /dev/null +++ b/infra/pg_hba.conf @@ -0,0 +1,5 @@ +local all all trust +hostssl all all 0.0.0.0/0 scram-sha-256 +hostssl all all ::/0 scram-sha-256 +hostnossl all all 0.0.0.0/0 reject +hostnossl all all ::/0 reject diff --git a/infra/prometheus-web.yml b/infra/prometheus-web.yml new file mode 100644 index 00000000..b47dbba7 --- /dev/null +++ b/infra/prometheus-web.yml @@ -0,0 +1,6 @@ +tls_server_config: + cert_file: /tls/tls.crt + key_file: /tls/tls.key + client_auth_type: RequireAndVerifyClientCert + client_ca_file: /ca/ca.crt + client_allowed_sans: [grafana-client, prometheus-client] diff --git a/infra/prometheus.yml b/infra/prometheus.yml new file mode 100644 index 00000000..337d43b4 --- /dev/null +++ b/infra/prometheus.yml @@ -0,0 +1,13 @@ +global: + scrape_interval: 5s + evaluation_interval: 5s +rule_files: [/etc/prometheus/alerts.yml] +scrape_configs: + - job_name: collector + scheme: https + tls_config: + ca_file: /ca/ca.crt + cert_file: /identity/tls.crt + key_file: /identity/tls.key + static_configs: + - targets: ['collector:8890'] diff --git a/infra/s3-cleanup-policy.json b/infra/s3-cleanup-policy.json new file mode 100644 index 00000000..03e6e825 --- /dev/null +++ b/infra/s3-cleanup-policy.json @@ -0,0 +1,3 @@ +{"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":["s3:DeleteObject"],"Resource":["arn:aws:s3:::attachments/staging/*"]} +]} diff --git a/infra/s3-init.sh b/infra/s3-init.sh new file mode 100644 index 00000000..d8fece10 --- /dev/null +++ b/infra/s3-init.sh @@ -0,0 +1,19 @@ +#!/bin/sh +set -eu +for i in $(seq 1 30); do + if mc alias set local https://minio:9000 "$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" >/dev/null 2>&1; then + break + fi + sleep 2 +done +mc mb --ignore-existing local/attachments +mc anonymous set none local/attachments +mc admin policy create local attachment-api /policy.json +mc admin user add local "$S3_ACCESS_KEY" "$S3_SECRET_KEY" +mc admin policy attach local attachment-api --user "$S3_ACCESS_KEY" +mc admin policy create local attachment-worker /worker-policy.json +mc admin user add local "$WORKER_S3_ACCESS_KEY" "$WORKER_S3_SECRET_KEY" +mc admin policy attach local attachment-worker --user "$WORKER_S3_ACCESS_KEY" +mc admin policy create local attachment-cleanup /cleanup-policy.json +mc admin user add local "$CLEANUP_S3_ACCESS_KEY" "$CLEANUP_S3_SECRET_KEY" +mc admin policy attach local attachment-cleanup --user "$CLEANUP_S3_ACCESS_KEY" diff --git a/infra/s3-policy.json b/infra/s3-policy.json new file mode 100644 index 00000000..e86f15b1 --- /dev/null +++ b/infra/s3-policy.json @@ -0,0 +1,8 @@ +{ + "Version": "2012-10-17", + "Statement": [ + {"Effect":"Allow","Action":["s3:ListBucket","s3:GetBucketLocation"],"Resource":["arn:aws:s3:::attachments"]}, + {"Effect":"Allow","Action":["s3:PutObject"],"Resource":["arn:aws:s3:::attachments/staging/*"]}, + {"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::attachments/original/*","arn:aws:s3:::attachments/variants/*"]} + ] +} diff --git a/infra/s3-worker-policy.json b/infra/s3-worker-policy.json new file mode 100644 index 00000000..9b7b8273 --- /dev/null +++ b/infra/s3-worker-policy.json @@ -0,0 +1,5 @@ +{"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":["s3:ListBucket","s3:GetBucketLocation"],"Resource":["arn:aws:s3:::attachments"]}, + {"Effect":"Allow","Action":["s3:GetObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::attachments/staging/*"]}, + {"Effect":"Allow","Action":["s3:PutObject"],"Resource":["arn:aws:s3:::attachments/original/*","arn:aws:s3:::attachments/variants/*"]} +]} diff --git a/infra/tempo.yaml b/infra/tempo.yaml new file mode 100644 index 00000000..ad364059 --- /dev/null +++ b/infra/tempo.yaml @@ -0,0 +1,22 @@ +server: + http_listen_port: 3200 + http_listen_address: 127.0.0.1 + grpc_listen_address: 127.0.0.1 +distributor: + receivers: + otlp: + protocols: + http: + endpoint: 127.0.0.1:4318 +ingester: + max_block_duration: 5m +compactor: + compaction: + block_retention: 24h +storage: + trace: + backend: local + wal: + path: /var/tempo/wal + local: + path: /var/tempo/blocks diff --git a/infra/trust-matrix-solution.md b/infra/trust-matrix-solution.md new file mode 100644 index 00000000..d7d20040 --- /dev/null +++ b/infra/trust-matrix-solution.md @@ -0,0 +1,35 @@ +# Реализация матрицы доверия (ЛР7) + +Все leaf сертификаты выдаются локальной CA на 30 суток. Root key и operator state не монтируются в runtime. Результаты тестов — только после запуска на локальном Docker. + +| Связь | Транспорт и identity | Проверка | +| --- | --- | --- | +| Client → LB | HTTPS localhost:8443, SAN localhost, Bearer | security.py, smoke.py | +| LB → API | mTLS api:8443, SAN api / lb-client, leaf pin | test_tls_boundaries.py, test_rotation.py | +| API / worker → DB | postgres:5432, verify-full, раздельные DB roles | smoke, pipeline, test_worker_permissions.py | +| API / worker → S3 | minio:9000 HTTPS, SAN minio, scoped prefix credentials | smoke, pipeline, test_worker_permissions.py | +| Dispatcher / worker → broker | broker:6379 mTLS, loopback 6378, role SAN + leaf pin + Redis ACL | test_tls_boundaries.py, test_pipeline.py; API брокер не использует | +| API / worker → Collector | collector:4319 mTLS, loopback 4318, client SAN/pin per role | test_tls_boundaries.py | +| Collector → Loki / Tempo | HTTPS loki:3101, tempo:4319, mTLS collector-client | test_tls_boundaries.py, test_telemetry_privacy.py | +| Prometheus → Collector | HTTPS collector:8890, prometheus-client | test_tls_boundaries.py, prometheus.yml | +| Grafana → backends | mTLS prometheus:9090, loki:3101, tempo:3201, grafana-client | test_tls_boundaries.py, локальный provisioning из bootstrap_pki.py | +| API/worker → OpenBao | https://openbao:8200, cert auth, KV role-specific, TTL 15 min | test_bao_policy.py | +| Operator → OpenBao / Grafana / S3 | TLS localhost:8200 / 3000, S3 не опубликован, отдельный operator bootstrap | bootstrap_bao.py, s3-init.sh | +| API → Redis | rediss redis:6379, CA+SAN, password из OpenBao | test_rotation.py | +| Replication | N/A, stateful HA не заявляется | — | + +## Модель угроз + +| Угроза | Контроль | Отрицательная проверка | +| --- | --- | --- | +| Перехват/подмена ingress | TLS CA + SAN, без plaintext ingress | security.py | +| Прямой обход LB | API loopback, mTLS proxy с SAN/pin | test_tls_boundaries.py | +| Чужой доступ к файлу | Bearer и проверка членства в чате | smoke.py | +| Избыточные права worker | Отдельная DB role, S3 prefix и broker ACL | test_worker_permissions.py | +| Перегрузка password KDF | Argon2id, глобальный login rate limit, лимиты CPU/RAM | hash_cost.py, test_login_budget.py, test_password_rehash.py | +| Подмена сертификата при ingest | mTLS Collector, SAN/pin | test_tls_boundaries.py | +| Доступ к чужому secret | OpenBao cert auth и role-bound policy | test_bao_policy.py | +| Использование отозванного leaf/password | pin rotation, замена Redis credentials | test_rotation.py | +| Утечка пароля, токена или текста в телеметрию | Отбор полей структурных событий и трасс | test_telemetry_privacy.py | + +Итоги проверок и границы покрытия приведены в [отчёте](../REPORT.md). Сканирование выполнено для образа приложения и его зависимостей. diff --git a/migrate.py b/migrate.py new file mode 100644 index 00000000..7ba785a8 --- /dev/null +++ b/migrate.py @@ -0,0 +1,15 @@ + + +import db + + +def main(): + db.pool.open(wait=True, timeout=30) + try: + db.run_migrations() + finally: + db.pool.close() + + +if __name__ == "__main__": + main() diff --git a/migrations/001_init.sql b/migrations/001_init.sql new file mode 100644 index 00000000..c2507900 --- /dev/null +++ b/migrations/001_init.sql @@ -0,0 +1,39 @@ +CREATE TABLE users ( + id UUID PRIMARY KEY, + username TEXT NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name TEXT NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100), + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE chats ( + id UUID PRIMARY KEY, + title TEXT NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100), + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE chat_members ( + chat_id UUID NOT NULL REFERENCES chats(id), + user_id UUID NOT NULL REFERENCES users(id), + PRIMARY KEY (chat_id, user_id) +); + +CREATE TABLE messages ( + id UUID PRIMARY KEY, + chat_id UUID NOT NULL REFERENCES chats(id), + sender_id UUID NOT NULL REFERENCES users(id), + text TEXT NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000), + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE sessions ( + token_hash TEXT PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id), + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + expires_at TIMESTAMPTZ NOT NULL, + revoked_at TIMESTAMPTZ +); + +CREATE INDEX messages_chat_created_idx ON messages (chat_id, created_at, id); +CREATE INDEX chat_members_user_idx ON chat_members (user_id); +CREATE INDEX sessions_user_idx ON sessions (user_id); \ No newline at end of file diff --git a/migrations/002_idempotency.sql b/migrations/002_idempotency.sql new file mode 100644 index 00000000..b7776b6c --- /dev/null +++ b/migrations/002_idempotency.sql @@ -0,0 +1,10 @@ +CREATE TABLE idempotency_keys ( + user_id UUID NOT NULL REFERENCES users(id), + method TEXT NOT NULL, + path TEXT NOT NULL, + key TEXT NOT NULL, + request_hash TEXT NOT NULL, + message_id UUID NOT NULL REFERENCES messages(id) DEFERRABLE INITIALLY DEFERRED, + expires_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (user_id, method, path, key) +); diff --git a/migrations/003_attachments.sql b/migrations/003_attachments.sql new file mode 100644 index 00000000..ad54d2bd --- /dev/null +++ b/migrations/003_attachments.sql @@ -0,0 +1,17 @@ +CREATE TABLE attachments ( + id UUID PRIMARY KEY, + chat_id UUID NOT NULL REFERENCES chats(id), + owner_id UUID NOT NULL REFERENCES users(id), + filename TEXT NOT NULL, + content_type TEXT NOT NULL, + size_bytes BIGINT NOT NULL, + sha256 TEXT NOT NULL, + object_key TEXT NOT NULL UNIQUE, + status TEXT NOT NULL CHECK (status IN ('pending', 'ready')), + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +ALTER TABLE messages DROP CONSTRAINT messages_text_check; +ALTER TABLE messages ADD CONSTRAINT messages_text_check CHECK (char_length(text) <= 4000); +ALTER TABLE messages ADD COLUMN attachment_ids UUID[] NOT NULL DEFAULT '{}'; +CREATE INDEX attachments_pending_idx ON attachments(created_at) WHERE status = 'pending'; diff --git a/migrations/004_pipeline.sql b/migrations/004_pipeline.sql new file mode 100644 index 00000000..89994c4f --- /dev/null +++ b/migrations/004_pipeline.sql @@ -0,0 +1,20 @@ +ALTER TABLE attachments DROP CONSTRAINT attachments_status_check; +ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK (status IN ('pending','queued','processing','ready','failed')); +ALTER TABLE attachments ADD COLUMN variants JSONB NOT NULL DEFAULT '[]'; +ALTER TABLE attachments ADD COLUMN error_code TEXT; +ALTER TABLE attachments ADD COLUMN staging_cleaned BOOLEAN NOT NULL DEFAULT FALSE; +CREATE TABLE attachment_jobs ( + id UUID PRIMARY KEY REFERENCES attachments(id), + attempt INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + available_at TIMESTAMPTZ NOT NULL DEFAULT now(), + published_at TIMESTAMPTZ, + lease_until TIMESTAMPTZ, + trace_context JSONB NOT NULL DEFAULT '{}', + replay_count INTEGER NOT NULL DEFAULT 0 +); +CREATE INDEX attachment_jobs_available_idx ON attachment_jobs(available_at); +CREATE TABLE attachment_replays ( + job_id UUID NOT NULL REFERENCES attachment_jobs(id), + replayed_at TIMESTAMPTZ NOT NULL DEFAULT now() +); diff --git a/migrations/005_security.sql b/migrations/005_security.sql new file mode 100644 index 00000000..b2b236d7 --- /dev/null +++ b/migrations/005_security.sql @@ -0,0 +1,11 @@ +CREATE TABLE login_attempts ( + scope TEXT PRIMARY KEY, + window_start TIMESTAMPTZ NOT NULL, + attempts INTEGER NOT NULL +); +GRANT USAGE ON SCHEMA public TO messenger_api,messenger_worker,messenger_dispatcher,messenger_cleanup; +GRANT SELECT,INSERT,UPDATE ON users,chats,chat_members,messages,sessions,idempotency_keys,attachments,attachment_jobs,login_attempts TO messenger_api; +GRANT SELECT,UPDATE ON attachments,attachment_jobs TO messenger_worker; +GRANT SELECT,INSERT,UPDATE ON attachment_replays TO messenger_worker; +GRANT SELECT,UPDATE ON attachments,attachment_jobs TO messenger_dispatcher; +GRANT SELECT,UPDATE,DELETE ON attachments TO messenger_cleanup; diff --git a/pipeline.py b/pipeline.py new file mode 100644 index 00000000..3b160450 --- /dev/null +++ b/pipeline.py @@ -0,0 +1,99 @@ +"""Durable Redis Streams + transactional PostgreSQL outbox.""" +import json +import os +import random +import time +import uuid +import redis +import db +import telemetry as ot +from opentelemetry.trace import SpanKind +from opentelemetry import propagate + +STREAM = 'attachment:jobs' +GROUP = 'workers' +MAX_ATTEMPTS = int(os.getenv('JOB_MAX_ATTEMPTS','5')) +BROKER = redis.Redis.from_url(os.environ['BROKER_URL'],decode_responses=True,socket_timeout=3,socket_connect_timeout=2, + ssl_ca_certs='/ca/ca.crt',ssl_certfile='/identity/tls.crt',ssl_keyfile='/identity/tls.key',ssl_check_hostname=True) + + +def ensure_group(): + try: + BROKER.xgroup_create(STREAM,GROUP,id='0',mkstream=True) + except redis.ResponseError as exc: + if 'BUSYGROUP' not in str(exc): + raise + + +def dispatch_once(): + with db.pool.connection() as conn: + q=conn.execute("SELECT count(*) AS depth,coalesce(extract(epoch FROM now()-min(j.created_at)),0) AS age FROM attachment_jobs j JOIN attachments a ON j.id=a.id WHERE a.status IN ('queued','processing')").fetchone() + ot.state['queue_depth']=q['depth'] + ot.state['oldest_seconds']=float(q['age']) + expired = conn.execute("""SELECT j.id,j.attempt FROM attachment_jobs j JOIN attachments a ON a.id=j.id + WHERE a.status='processing' AND j.lease_until= MAX_ATTEMPTS: + conn.execute("UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=now() WHERE id=%s",(row['id'],)) + else: + conn.execute("UPDATE attachments SET status='queued',updated_at=now() WHERE id=%s",(row['id'],)) + conn.execute("UPDATE attachment_jobs SET published_at=NULL,lease_until=NULL,available_at=now() WHERE id=%s",(row['id'],)) + jobs = conn.execute("""SELECT j.* FROM attachment_jobs j JOIN attachments a ON a.id=j.id + WHERE a.status='queued' AND j.available_at<=now() AND (j.published_at IS NULL OR j.published_at=MAX_ATTEMPTS: + conn.execute("UPDATE attachments SET status='failed',error_code=%s,updated_at=now() WHERE id=%s AND status='processing'", + ('invalid_image' if permanent else 'retry_exhausted',job_id)) + else: + delay = min(60,2**row['attempt'])+random.random() + conn.execute("UPDATE attachments SET status='queued',updated_at=now() WHERE id=%s AND status='processing'",(job_id,)) + conn.execute("UPDATE attachment_jobs SET published_at=NULL,lease_until=NULL,available_at=now()+%s*interval '1 second' WHERE id=%s",(delay,job_id)) + + +def replay(job_id): + with db.pool.connection() as conn: + changed=conn.execute("UPDATE attachments SET status='queued',error_code=NULL,updated_at=now() WHERE id=%s AND status='failed' AND NOT staging_cleaned RETURNING id",(job_id,)).fetchone() + if not changed: + raise SystemExit('Only failed jobs may be replayed') + conn.execute("UPDATE attachment_jobs SET attempt=0,published_at=NULL,lease_until=NULL,available_at=now(),replay_count=replay_count+1 WHERE id=%s",(job_id,)) + conn.execute("INSERT INTO attachment_replays(job_id) VALUES (%s)",(job_id,)) + + +if __name__ == '__main__': + import sys + db.pool.open(wait=True,timeout=30) + if len(sys.argv)==3 and sys.argv[1]=='replay': + replay(str(uuid.UUID(sys.argv[2]))) + else: + while True: + try: + ensure_group() + dispatch_once() + except Exception: + print('dispatcher will retry',flush=True) + time.sleep(1) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..83635104 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,13 @@ +fastapi==0.161.1 +starlette==1.9.0 +pydantic==2.14.1 +uvicorn[standard]==0.54.0 +psycopg[binary]==3.3.6 +psycopg-pool==3.3.3 +argon2-cffi==25.1.0 +redis==8.1.0 +boto3==1.38.0 +Pillow==11.3.0 +opentelemetry-api==1.44.0 +opentelemetry-sdk==1.44.0 +opentelemetry-exporter-otlp-proto-http==1.44.0 diff --git a/schemas.py b/schemas.py new file mode 100644 index 00000000..2fe660b8 --- /dev/null +++ b/schemas.py @@ -0,0 +1,89 @@ +from pydantic import BaseModel, ConfigDict, Field, field_validator +from pydantic import model_validator +import uuid + + +def not_blank(value: str) -> str: + if not value.strip(): + raise ValueError("must not be blank") + return value + + +class RequestModel(BaseModel): + # Лишние поля и неверные типы в JSON -> 400 + model_config = ConfigDict(extra="forbid", strict=True) + + +# ---------- Запросы ---------- + +class CreateUser(RequestModel): + username: str = Field(pattern=r"^[a-z0-9_]{3,32}$") + display_name: str = Field(min_length=1, max_length=100) + password: str = Field(min_length=12, max_length=128) + + _display_name_not_blank = field_validator("display_name")(not_blank) + _password_not_blank = field_validator("password")(not_blank) + + +class CreateChat(RequestModel): + title: str = Field(min_length=1, max_length=100) + member_ids: list[str] = Field(min_length=1, max_length=100) + + _title_not_blank = field_validator("title")(not_blank) + + +class CreateMessage(RequestModel): + text: str = Field(max_length=4000) + + attachment_ids: list[str] = Field(default_factory=list, max_length=10) + + @model_validator(mode="after") + def validate_message(self): + self.attachment_ids = [str(uuid.UUID(value)) for value in self.attachment_ids] + if len(set(self.attachment_ids)) != len(self.attachment_ids): + raise ValueError("duplicate attachment") + if not self.text.strip() and not self.attachment_ids: + raise ValueError("message is empty") + return self + + +# ---------- Ответы ---------- + +class User(BaseModel): + id: str + username: str + display_name: str + created_at: str + + +class Session(BaseModel): + token: str + token_type: str = "Bearer" + expires_at: str + user: User + + +class Chat(BaseModel): + id: str + title: str + member_ids: list[str] + created_at: str + + +class ChatPage(BaseModel): + items: list[Chat] + next_cursor: str | None + + +class Message(BaseModel): + attachment_ids: list[str] + id: str + chat_id: str + sender_id: str + text: str + created_at: str + + +class MessagePage(BaseModel): + items: list[Message] + next_cursor: str | None diff --git a/scripts/actions.py b/scripts/actions.py new file mode 100644 index 00000000..72c8825a --- /dev/null +++ b/scripts/actions.py @@ -0,0 +1,46 @@ +"""Local Compose actions for the public resilience tests.""" +import os +from pathlib import Path +import re +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[1] +COMPOSE = ["docker", "compose", "--env-file", str(ROOT / ".env")] + + +def run(*args, capture=False): + return subprocess.run(args, cwd=ROOT, check=True, text=True, + capture_output=capture).stdout + + +def stop_one(): + target = os.environ.get("TARGET_INSTANCE_ID", "") + if not re.fullmatch(r"[0-9a-f]{32}", target): + raise SystemExit("Invalid TARGET_INSTANCE_ID") + ids = run(*COMPOSE, "ps", "-q", "api", capture=True).splitlines() + matches = [cid for cid in ids if run("docker", "exec", cid, "python", "-c", + "import urllib.request;print(urllib.request.urlopen('http://127.0.0.1:8080/health/live').headers['X-Instance-Id'])", + capture=True).strip() == target] + if len(matches) != 1 or len(ids) < 2: + raise SystemExit("Expected one matching API and at least two running replicas") + print(f"Stopping API container {matches[0][:12]}", flush=True) + run("docker", "stop", "--time", "2", matches[0]) + + +def restart(): + # Keep postgres volume; Redis is a disposable cache. Never remove volumes. + run(*COMPOSE, "stop", "nginx", "api", "cleanup", "worker", "dispatcher") + run(*COMPOSE, "restart", "postgres", "redis", "minio", "broker", "openbao", "collector", "prometheus", "loki", "tempo", "grafana") + run(*COMPOSE, "restart", "broker-tls", "collector-tls", "collector-scrape-tls", "loki-tls", "tempo-query-tls", "tempo-ingest-tls") + run(sys.executable, str(ROOT / "scripts/bootstrap_bao.py")) + run(*COMPOSE, "up", "-d", "--wait", "--wait-timeout", "60") + + +if __name__ == "__main__": + if sys.argv[1:] == ["stop-one"]: + stop_one() + elif sys.argv[1:] == ["restart"]: + restart() + else: + raise SystemExit("Use stop-one or restart") diff --git a/scripts/bootstrap_bao.py b/scripts/bootstrap_bao.py new file mode 100644 index 00000000..4e14ad90 --- /dev/null +++ b/scripts/bootstrap_bao.py @@ -0,0 +1,76 @@ +"""Operator-only, local OpenBao initialization and per-role certificate authentication.""" +import json +import os +from pathlib import Path +import ssl +import time +import urllib.error +import urllib.request +from urllib.parse import quote + +ROOT=Path(__file__).resolve().parents[1] +PKI=ROOT/'certs/private' +STATE=ROOT/'secrets/openbao-operator.json' +URL='https://127.0.0.1:8200/v1/' +context=ssl.create_default_context(cafile=str(PKI/'ca.crt')) +context.load_cert_chain(str(PKI/'operator-client/tls.crt'),str(PKI/'operator-client/tls.key')) +env={} +for line in (ROOT/'.env').read_text(encoding='utf-8').splitlines(): + if '=' in line and not line.lstrip().startswith('#'): + k,v=line.split('=',1);env[k]=v + + +def request(path, body=None, token=None, method=None): + h={'Content-Type':'application/json'} + if token: + h['X-Vault-Token']=token + req=urllib.request.Request(URL+path,data=None if body is None else json.dumps(body).encode(),headers=h,method=method) + try: + with urllib.request.urlopen(req,context=context,timeout=15) as response: + data=response.read() + return json.loads(data) if data else {} + except urllib.error.HTTPError as exc: + raise RuntimeError(f'OpenBao operation {path} returned {exc.code}') from None + + +for attempt in range(30): + try: + initialized=request('sys/init')['initialized'] + break + except (OSError,RuntimeError): + if attempt==29:raise + time.sleep(2) +if not initialized: + if STATE.exists(): + raise SystemExit('Existing operator state: refuse to overwrite') + state=request('sys/init',{'secret_shares':1,'secret_threshold':1},method='PUT') + STATE.parent.mkdir(exist_ok=True) + STATE.write_text(json.dumps(state),encoding='utf-8') + os.chmod(STATE,0o600) +else: + state=json.loads(STATE.read_text(encoding='utf-8')) +if request('sys/seal-status')['sealed']: + request('sys/unseal',{'key':state['keys_base64'][0]},method='PUT') +token=state['root_token'] +mounts=request('sys/mounts',token=token) +if 'kv/' not in mounts: + request('sys/mounts/kv',{'type':'kv','options':{'version':'2'}},token) +auth=request('sys/auth',token=token) +if 'cert/' not in auth: + request('sys/auth/cert',{'type':'cert'},token) +for role in ('api','worker','dispatcher','cleanup','migrate'): + db_user=env['POSTGRES_USER'] if role=='migrate' else 'messenger_'+role + db_password=env['POSTGRES_PASSWORD'] if role=='migrate' else env[role.upper()+'_DB_PASSWORD'] + values={'DATABASE_URL':f"postgresql://{quote(db_user,safe='')}:{quote(db_password,safe='')}@postgres:5432/{env['POSTGRES_DB']}?sslmode=verify-full&sslrootcert=/ca/ca.crt"} + if role=='api': + values.update(REDIS_URL=f"rediss://:{quote(env['REDIS_PASSWORD'],safe='')}@redis:6379/0",S3_ACCESS_KEY=env['S3_ACCESS_KEY'],S3_SECRET_KEY=env['S3_SECRET_KEY']) + elif role in ('worker','cleanup'): + values.update(S3_ACCESS_KEY=env[role.upper()+'_S3_ACCESS_KEY'],S3_SECRET_KEY=env[role.upper()+'_S3_SECRET_KEY']) + if role in ('worker','dispatcher'): + broker_user='worker' if role=='worker' else 'dispatch' + values['BROKER_URL']=f"rediss://{broker_user}:{quote(env[role.upper()+'_BROKER_PASSWORD'],safe='')}@broker:6379/0" + request('kv/data/'+role,{'data':values},token) + request('sys/policies/acl/'+role,{'policy':f'path "kv/data/{role}" {{ capabilities = ["read"] }}'},token,method='PUT') + request('auth/cert/certs/'+role,{'certificate':(PKI/f'{role}-client/tls.crt').read_text(), + 'token_policies':[role],'token_ttl':'15m','token_max_ttl':'30m','allowed_dns_sans':[role+'-client']},token) +print('OpenBao initialized/unsealed; per-service scoped secrets installed. Operator state kept locally.') diff --git a/scripts/bootstrap_pki.py b/scripts/bootstrap_pki.py new file mode 100644 index 00000000..becd71da --- /dev/null +++ b/scripts/bootstrap_pki.py @@ -0,0 +1,126 @@ +"""Generate local lab PKI. Never commit certs/private or secrets.""" +from datetime import datetime, timedelta, timezone +import ipaddress +from pathlib import Path +import os +import argparse +import shutil +import hashlib + +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID + +ROOT=Path(__file__).resolve().parents[1] +P=ROOT/'certs/private' +P.mkdir(parents=True,exist_ok=True) +parser=argparse.ArgumentParser() +parser.add_argument('--rotate',choices=['lb-client','api-client','worker-client','dispatcher-client','collector-client','grafana-client']) +args=parser.parse_args() + + +def key(): + return rsa.generate_private_key(public_exponent=65537,key_size=2048) + + +def write(path,data): + path.parent.mkdir(parents=True,exist_ok=True) + path.write_bytes(data) + os.chmod(path,0o600) + + +def private(k): + return k.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()) + + +def name(n): + return x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,n)]) + + +def builder(subject,issuer,k,days): + now=datetime.now(timezone.utc) + return (x509.CertificateBuilder().subject_name(name(subject)).issuer_name(issuer).public_key(k.public_key()) + .serial_number(x509.random_serial_number()).not_valid_before(now-timedelta(minutes=5)) + .not_valid_after(now+timedelta(days=days))) + + +def has_extension(cert, extension): + try: + cert.extensions.get_extension_for_class(extension) + except x509.ExtensionNotFound: + return False + return True + + +if (P/'ca.key').exists(): + ca_key=serialization.load_pem_private_key((P/'ca.key').read_bytes(),None) + ca=x509.load_pem_x509_certificate((P/'ca.crt').read_bytes()) +else: + ca_key=key() + ca=None + write(P/'ca.key',private(ca_key)) +if ca is None or not has_extension(ca,x509.SubjectKeyIdentifier): + ca=(builder('Messenger lab CA',name('Messenger lab CA'),ca_key,365) + .add_extension(x509.BasicConstraints(ca=True,path_length=0),critical=True) + .add_extension(x509.SubjectKeyIdentifier.from_public_key(ca_key.public_key()),critical=False) + .add_extension(x509.KeyUsage(False,False,False,False,False,True,True,False,False),critical=True) + .sign(ca_key,hashes.SHA256())) + write(P/'ca.crt',ca.public_bytes(serialization.Encoding.PEM)) + + +def issue(identity,hosts,client=False): + d=P/identity + if (d/'tls.key').exists() and (d/'tls.crt').exists(): + existing=x509.load_pem_x509_certificate((d/'tls.crt').read_bytes()) + if args.rotate!=identity and has_extension(existing,x509.AuthorityKeyIdentifier): + return + if (d/'tls.key').exists() and (d/'tls.crt').exists() and args.rotate==identity: + backup=ROOT/'secrets'/'rotated'/identity + backup.mkdir(parents=True,exist_ok=True) + shutil.copy2(d/'tls.key',backup/'tls.key') + shutil.copy2(d/'tls.crt',backup/'tls.crt') + k=key() + san=[x509.DNSName(h) for h in hosts] + if 'localhost' in hosts: + san.append(x509.IPAddress(ipaddress.ip_address('127.0.0.1'))) + usage=ExtendedKeyUsageOID.CLIENT_AUTH if client else ExtendedKeyUsageOID.SERVER_AUTH + cert=(builder(identity,ca.subject,k,30).add_extension(x509.SubjectAlternativeName(san),critical=False) + .add_extension(x509.BasicConstraints(ca=False,path_length=None),critical=True) + .add_extension(x509.SubjectKeyIdentifier.from_public_key(k.public_key()),critical=False) + .add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()),critical=False) + .add_extension(x509.ExtendedKeyUsage([usage]),critical=False).sign(ca_key,hashes.SHA256())) + write(d/'tls.key',private(k));write(d/'tls.crt',cert.public_bytes(serialization.Encoding.PEM)) + + +for identity,hosts in {'ingress':['localhost'],'api':['api'],'postgres':['postgres'],'minio':['minio'], + 'redis':['redis'],'broker':['broker'],'collector':['collector'],'prometheus':['prometheus'], + 'loki':['loki'],'tempo':['tempo'],'grafana':['localhost'],'openbao':['openbao','localhost']}.items(): + issue(identity,hosts) +for role in ('lb-client','api-client','worker-client','dispatcher-client','cleanup-client','migrate-client','collector-client','grafana-client','prometheus-client','operator-client'): + issue(role,[role],client=True) + write(P/'public-pins'/f'{role}.crt',(P/role/'tls.crt').read_bytes()) + +# Grafana file provisioning supports PEM values in secureJsonData. +import json +provision=ROOT/'secrets/grafana-datasources' +provision.mkdir(parents=True,exist_ok=True) +pub=(P/'ca.crt').read_text() +cert=(P/'grafana-client/tls.crt').read_text() +priv=(P/'grafana-client/tls.key').read_text() +sources=[] +for typ,port in [('prometheus',9090),('loki',3101),('tempo',3201)]: + sources.append({'name':typ.title(),'uid':typ,'type':typ,'access':'proxy','url':f'https://{typ}:{port}', + 'isDefault':typ=='prometheus','jsonData':{'tlsAuth':True,'tlsAuthWithCACert':True}, + 'secureJsonData':{'tlsCACert':pub,'tlsClientCert':cert,'tlsClientKey':priv}}) +write(provision/'datasources.yaml',json.dumps({'apiVersion':1,'datasources':sources},indent=2).encode()) +env={} +for line in (ROOT/'.env').read_text(encoding='utf-8').splitlines(): + if '=' in line and not line.lstrip().startswith('#'): + k,v=line.split('=',1);env[k]=v +def digest(value): + return '#'+hashlib.sha256(value.encode()).hexdigest() +write(ROOT/'secrets/broker.acl', ('user default off\n' + f'user dispatch on {digest(env["DISPATCHER_BROKER_PASSWORD"])} ~attachment:jobs +ping +client|setinfo +xgroup +xadd\n' + f'user worker on {digest(env["WORKER_BROKER_PASSWORD"])} ~attachment:jobs +ping +client|setinfo +xgroup +xreadgroup +xautoclaim +xack +xdel\n').encode()) +print('Local PKI created; CA: certs/private/ca.crt') diff --git a/scripts/restart.cmd b/scripts/restart.cmd new file mode 100644 index 00000000..a1029985 --- /dev/null +++ b/scripts/restart.cmd @@ -0,0 +1,3 @@ +@echo off +python -X utf8 "%~dp0actions.py" restart +exit /b %errorlevel% diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..c22c1f7f --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +exec python3 "$(dirname "$0")/actions.py" restart diff --git a/scripts/stop-one.cmd b/scripts/stop-one.cmd new file mode 100644 index 00000000..4ce43dd3 --- /dev/null +++ b/scripts/stop-one.cmd @@ -0,0 +1,3 @@ +@echo off +python -X utf8 "%~dp0actions.py" stop-one +exit /b %errorlevel% diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 00000000..04aa2950 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +exec python3 "$(dirname "$0")/actions.py" stop-one diff --git a/secret_entry.py b/secret_entry.py new file mode 100644 index 00000000..1d881aba --- /dev/null +++ b/secret_entry.py @@ -0,0 +1,34 @@ +"""Authenticate via service certificate, load its scoped secret, then exec service.""" +import json +import os +import ssl +import sys +import time +import urllib.request + +role=os.environ['BAO_ROLE'] +base='https://openbao:8200/v1/' +ctx=ssl.create_default_context(cafile='/ca/ca.crt') +ctx.load_cert_chain('/identity/tls.crt','/identity/tls.key') + + +def call(path,data=None,token=None): + headers={'Content-Type':'application/json'} + if token: + headers['X-Vault-Token']=token + req=urllib.request.Request(base+path,data=None if data is None else json.dumps(data).encode(),headers=headers) + with urllib.request.urlopen(req,context=ctx,timeout=5) as r: + return json.loads(r.read()) + + +for attempt in range(30): + try: + token=call('auth/cert/login',{'name':role})['auth']['client_token'] + secrets=call('kv/data/'+role,token=token)['data']['data'] + os.environ.update(secrets) + break + except Exception: + if attempt==29: + raise SystemExit('Secret bootstrap unavailable; fail closed') from None + time.sleep(2) +os.execvp(sys.argv[1],sys.argv[1:]) diff --git a/telemetry.py b/telemetry.py new file mode 100644 index 00000000..edb37ba2 --- /dev/null +++ b/telemetry.py @@ -0,0 +1,76 @@ +"""Bounded OTLP instrumentation for API, dispatcher and worker.""" +import logging +import os +import resource +import socket +import time + +from opentelemetry import metrics, trace, propagate +from opentelemetry.sdk.resources import Resource +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader +from opentelemetry.sdk.metrics.view import View, ExplicitBucketHistogramAggregation +from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler +from opentelemetry.sdk._logs.export import BatchLogRecordProcessor +from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter +from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter +from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter + +SERVICE=os.getenv('OTEL_SERVICE_NAME','messenger-api') +BASE=os.getenv('OTEL_EXPORTER_OTLP_ENDPOINT','http://collector:4318').rstrip('/') +TLS={'certificate_file':'/ca/ca.crt','client_certificate_file':'/identity/tls.crt','client_key_file':'/identity/tls.key'} +res=Resource.create({'service.name':SERVICE,'service.version':'lab6','service.instance.id':socket.gethostname(), + 'deployment.environment.name':'lab'}) +tp=TracerProvider(resource=res) +tp.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=BASE+'/v1/traces',timeout=2,**TLS),max_queue_size=1024,max_export_batch_size=128)) +trace.set_tracer_provider(tp) +mp=MeterProvider(resource=res,metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter(endpoint=BASE+'/v1/metrics',timeout=2,**TLS),export_interval_millis=5000)], + views=[View(instrument_name='messenger.*.duration',aggregation=ExplicitBucketHistogramAggregation([.005,.01,.025,.05,.1,.25,.5,1,2,5,10,30,60,120]))]) +metrics.set_meter_provider(mp) +lp=LoggerProvider(resource=res) +lp.add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter(endpoint=BASE+'/v1/logs',timeout=2,**TLS),max_queue_size=1024,max_export_batch_size=128)) +logger=logging.getLogger('messenger.telemetry') +logger.setLevel(logging.INFO) +logger.addHandler(LoggingHandler(level=logging.INFO,logger_provider=lp)) +logger.propagate=False +tracer=trace.get_tracer('messenger') +meter=metrics.get_meter('messenger') +http_count=meter.create_counter('messenger.http.requests') +http_duration=meter.create_histogram('messenger.http.duration',unit='s') +job_count=meter.create_counter('messenger.job.processed') +job_duration=meter.create_histogram('messenger.job.duration',unit='s') +ready_duration=meter.create_histogram('messenger.ready.duration',unit='s') +state={'queue_depth':0,'oldest_seconds':0,'worker_busy':0} + + +def observe(key): + return lambda _: [metrics.Observation(state[key])] + + +meter.create_observable_gauge('messenger.queue.depth',callbacks=[observe('queue_depth')]) +meter.create_observable_gauge('messenger.queue.oldest',unit='s',callbacks=[observe('oldest_seconds')]) +meter.create_observable_gauge('messenger.worker.busy',callbacks=[observe('worker_busy')]) +meter.create_observable_gauge('messenger.worker.capacity',callbacks=[lambda _: [metrics.Observation(1 if SERVICE=='messenger-worker' else 0)]]) +meter.create_observable_counter('messenger.process.cpu',unit='s',callbacks=[lambda _: [metrics.Observation(time.process_time())]]) +meter.create_observable_gauge('messenger.process.peak_memory',unit='By',callbacks=[lambda _: [metrics.Observation(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss*1024)]]) + + +def pool_stats(kind): + def collect(_): + import db + stats=db.pool.get_stats() + value=stats.get('requests_waiting',0) if kind=='waiting' else stats.get('pool_size',0)-stats.get('pool_available',0) + return [metrics.Observation(value)] + return collect + + +for name in ('waiting','used'): + meter.create_observable_gauge('messenger.db.pool.'+name,callbacks=[pool_stats(name)]) + + +def carrier(): + values={} + propagate.inject(values) + return {k:v for k,v in values.items() if k in ('traceparent','tracestate')} diff --git a/tests/hash_cost.py b/tests/hash_cost.py new file mode 100644 index 00000000..3b2d09e8 --- /dev/null +++ b/tests/hash_cost.py @@ -0,0 +1,18 @@ +"""Measure the configured Argon2id budget locally in the running API container.""" +import json +from pathlib import Path +import subprocess + +ROOT=Path(__file__).resolve().parents[1] +code="""import time,statistics,json,resource +from argon2 import PasswordHasher +p=PasswordHasher(memory_cost=19456,time_cost=2,parallelism=1) +samples=[] +for _ in range(20): + t=time.monotonic();p.hash('synthetic-lab-password');samples.append((time.monotonic()-t)*1000) +print(json.dumps({'memory_kib':19456,'t':2,'p':1,'hash_median_ms':statistics.median(samples),'hash_max_ms':max(samples),'peak_rss_kib':resource.getrusage(resource.RUSAGE_SELF).ru_maxrss})) +""" +raw=subprocess.check_output(['docker','compose','exec','-T','--index','1','api','python','-c',code],cwd=ROOT,text=True) +result=json.loads(raw) +(ROOT/'evidence/hash-cost.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8') +print(json.dumps(result)) diff --git a/tests/test_bao_policy.py b/tests/test_bao_policy.py new file mode 100644 index 00000000..5b8fc6d1 --- /dev/null +++ b/tests/test_bao_policy.py @@ -0,0 +1,67 @@ +"""Check scoped, short-lived OpenBao access without printing credentials.""" +import argparse +import json +import subprocess +import sys +from pathlib import Path + +ROOT=Path(__file__).resolve().parents[1] +CHECK=''' +import json,ssl,sys,urllib.request,urllib.error +role,other,mode=sys.argv[1:] +ctx=ssl.create_default_context(cafile='/ca/ca.crt') +ctx.load_cert_chain('/identity/tls.crt','/identity/tls.key') +base='https://openbao:8200/v1/' +def req(path,data=None,token=None): + headers={'Content-Type':'application/json'} + if token:headers['X-Vault-Token']=token + r=urllib.request.Request(base+path,data=None if data is None else json.dumps(data).encode(),headers=headers) + with urllib.request.urlopen(r,context=ctx,timeout=5) as response:return json.loads(response.read()) +if mode=='sealed': + assert req('sys/seal-status')['sealed'] + try:req('auth/cert/login',{'name':role}) + except urllib.error.HTTPError as e:assert e.code==503 + else:raise AssertionError('sealed OpenBao issued a token') + print('PASS: sealed OpenBao refuses service authentication') + raise SystemExit(0) +auth=req('auth/cert/login',{'name':role})['auth'] +assert 0 < auth['lease_duration'] <= 900 +token=auth['client_token'] +assert 'DATABASE_URL' in req('kv/data/'+role,token=token)['data']['data'] +for path in ('kv/data/'+other,'sys/policies/acl/'+role): + try:req(path,token=token) + except urllib.error.HTTPError as e:assert e.code==403 + else:raise AssertionError('unscoped access') +print('PASS: '+role+' can read only its own secrets, with a limited token TTL') +''' + + +def compose(*args): + subprocess.run(['docker','compose',*args],cwd=ROOT,check=True) + + +def probe(role,other,mode='unsealed'): + compose('exec','-T','--index','1',role,'python','-c',CHECK,role,other,mode) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--check-sealed',action='store_true',help='Restart the lab OpenBao, then unseal it') + args=parser.parse_args() + if args.check_sealed: + compose('restart','openbao') + try: + probe('api','worker','sealed') + finally: + subprocess.run([sys.executable,'scripts/bootstrap_bao.py'],cwd=ROOT,check=True) + probe('api','worker') + probe('worker','api') + (ROOT/'evidence/bao-policy.json').write_text(json.dumps({ + 'scoped_roles': ['api','worker'], + 'maximum_token_ttl_seconds': 900, + 'sealed_authentication_rejected': True if args.check_sealed else None, + },indent=2)+'\n',encoding='utf-8') + + +if __name__=='__main__': + main() diff --git a/tests/test_idempotency_race.py b/tests/test_idempotency_race.py new file mode 100644 index 00000000..8f410e8e --- /dev/null +++ b/tests/test_idempotency_race.py @@ -0,0 +1,34 @@ +"""Concurrent duplicate sends against the local lab3 load balancer.""" +from concurrent.futures import ThreadPoolExecutor +from threading import Barrier +import uuid + +from client import Client, arguments, check, run +from resilience import history + + +def main(): + args = arguments("Concurrent message deduplication") + c = Client(args.base_url, args.ca_file) + alice, bob, _, chat = c.bootstrap() + key = uuid.uuid4().hex + text = "Concurrent send " + key + barrier = Barrier(16, timeout=10) + + def send(_): + client = Client(args.base_url, args.ca_file) + barrier.wait() + response = client.message(alice, chat, text, key=key) + return response["json"], response["headers"]["X-Instance-Id"] + + with ThreadPoolExecutor(max_workers=16) as executor: + results = list(executor.map(send, range(16))) + check(len({instance for _, instance in results}) >= 2, "Only one replica observed") + check(all(message == results[0][0] for message, _ in results), "Different replay results") + check(sum(message["text"] == text for message in history(c, bob, chat)) == 1, + "Duplicate message in history") + print("PASS: 16 concurrent requests, at least 2 replicas, exactly 1 message") + + +if __name__ == "__main__": + run(main) diff --git a/tests/test_login_budget.py b/tests/test_login_budget.py new file mode 100644 index 00000000..9f5257ee --- /dev/null +++ b/tests/test_login_budget.py @@ -0,0 +1,48 @@ +"""Verify the shared login rate limit with synthetic credentials on the local stand.""" +import base64 +import json +from pathlib import Path +import time +import uuid + +from client import Client, arguments, check, run + + +ROOT = Path(__file__).resolve().parents[1] + + +def main(): + args = arguments('Local shared login limit') + client = Client(args.base_url, args.ca_file) + credential = 'budget_probe_' + uuid.uuid4().hex[:12] + ':synthetic-password' + basic = base64.b64encode(credential.encode()).decode() + challenge = {'Authorization': 'Basic ' + basic} + limited_instances = set() + rejected = 0 + throttled = 0 + started = time.monotonic() + for _ in range(250): + response = client.call('POST', '/api/v1/auth/sessions', (401, 429), headers=challenge) + check(basic not in response['bytes'].decode() and credential not in response['bytes'].decode(), + 'Error included synthetic credentials') + if response['status'] == 401: + rejected += 1 + continue + throttled += 1 + check(response['headers'].get('Retry-After') == '60', 'Missing Retry-After') + limited_instances.add(response['headers']['X-Instance-Id']) + if len(limited_instances) == 2: + break + check(len(limited_instances) == 2, 'The same login budget did not block both replicas') + (ROOT / 'evidence/login-budget.json').write_text(json.dumps({ + 'invalid_credentials_responses': rejected, + 'rate_limited_responses': throttled, + 'limited_replicas': len(limited_instances), + 'retry_after_seconds': 60, + 'elapsed_seconds': round(time.monotonic() - started, 3), + }, indent=2) + '\n', encoding='utf-8') + print('PASS: shared login budget, HTTP 429 on both replicas and no credentials in errors') + + +if __name__ == '__main__': + run(main) diff --git a/tests/test_observability.py b/tests/test_observability.py new file mode 100644 index 00000000..5d33ae1a --- /dev/null +++ b/tests/test_observability.py @@ -0,0 +1,81 @@ +"""Local incident demo; save Prometheus alert state and synthetic request results.""" +import json +from pathlib import Path +import subprocess +import time + +from client import Client, Failure, arguments, check, run + +ROOT=Path(__file__).resolve().parents[1] + + +def compose(*args): + return subprocess.check_output(['docker','compose',*args],cwd=ROOT,text=True) + + +def prom(path): + return json.loads(compose('exec','-T','prometheus','wget','-qO-',f'http://127.0.0.1:9090{path}')) + + +def wait_alert(name,state,seconds=90): + deadline=time.monotonic()+seconds + while time.monotonic()0,'No API errors observed') + report['db_errors']=errors + report['error_alert_firing']=wait_alert('HighHTTPErrorRate',True,20) + finally: + compose('start','postgres') + deadline=time.monotonic()+90 + while True: + try: + c.message(alice,chat,'DB recovered') + break + except Failure: + check(time.monotonic()0,'Empty variant') + check(c.call('GET',f"/api/v1/attachments/{attachment['id']}/content",actor=bob)['bytes']==original,'Original changed') + print('PASS: committed job recovered after API/broker restart and delayed dispatcher',flush=True) + compose('exec','-T','worker','touch','/tmp/lab-crash-once') + crash,_=c.attachment(alice,chat) + ready2=c.wait_ready(bob,crash,wait_seconds=240) + check(len(ready2['variants'])==3,'Duplicate or missing variants after crash') + print('PASS: worker crash after S3 write recovered with exactly three variants',flush=True) + (ROOT/'evidence/pipeline.json').write_text(json.dumps({'durable_handoff':'pass','after_s3_crash':'pass','variant_names':[v['name'] for v in ready2['variants']]},indent=2)+'\n',encoding='utf-8') + finally: + compose('start','dispatcher','worker') + + +if __name__=='__main__': + run(main) diff --git a/tests/test_rotation.py b/tests/test_rotation.py new file mode 100644 index 00000000..10435de0 --- /dev/null +++ b/tests/test_rotation.py @@ -0,0 +1,48 @@ +"""Rotate the local LB certificate and Redis password without building images.""" +import json +from pathlib import Path +import secrets +import subprocess +import sys +import time + +from test_tls_boundaries import probe, ROOT + + +def run(*args): + subprocess.run(args,cwd=ROOT,check=True) + + +def redis_check(password,expected): + code="""import redis,sys +pw=sys.stdin.read().strip() +r=redis.Redis(host='redis',port=6379,password=pw,ssl=True,ssl_ca_certs='/ca/ca.crt',ssl_check_hostname=True,socket_timeout=3) +try: ok=r.ping() +except redis.AuthenticationError: ok=False +assert bool(ok)==(sys.argv[1]=='yes') +""" + subprocess.run(['docker','compose','exec','-T','--index','1','api','python','-c',code,'yes' if expected else 'no'], + input=password,text=True,cwd=ROOT,check=True) + + +def main(): + run(sys.executable,'scripts/bootstrap_pki.py','--rotate','lb-client') + run('docker','compose','restart','nginx') + probe('api',8443,'lb-client',True,'http') + probe('api',8443,ROOT/'secrets/rotated/lb-client',False,'http') + env_file=ROOT/'.env'; lines=env_file.read_text(encoding='utf-8').splitlines() + old=next(line.split('=',1)[1] for line in lines if line.startswith('REDIS_PASSWORD=')) + new=secrets.token_hex(24) + env_file.write_text('\n'.join('REDIS_PASSWORD='+new if line.startswith('REDIS_PASSWORD=') else line for line in lines)+'\n',encoding='utf-8') + run(sys.executable,'scripts/bootstrap_bao.py') + run('docker','compose','up','-d','--no-deps','--force-recreate','redis') + run('docker','compose','restart','api') + time.sleep(8) + redis_check(old,False);redis_check(new,True) + run(sys.executable,'-X','utf8','tests/smoke.py','--ca-file','certs/private/ca.crt') + (ROOT/'evidence/rotation.json').write_text(json.dumps({'leaf_rotation':True,'old_leaf_rejected':True,'redis_secret_rotation':True,'old_secret_rejected':True},indent=2)+'\n',encoding='utf-8') + print('PASS: certificate and cache secret rotated without image rebuild') + + +if __name__=='__main__': + main() diff --git a/tests/test_telemetry_privacy.py b/tests/test_telemetry_privacy.py new file mode 100644 index 00000000..1a3a3e55 --- /dev/null +++ b/tests/test_telemetry_privacy.py @@ -0,0 +1,75 @@ +"""Verify that correlated traces and logs omit synthetic credentials and text.""" +import base64 +import json +from pathlib import Path +import subprocess +import time +from urllib.parse import urlencode +import uuid + +from client import Client, arguments, check, run + + +ROOT = Path(__file__).resolve().parents[1] +FETCH = """ +import json,ssl,sys,urllib.request,urllib.error +ctx=ssl.create_default_context(cafile='/ca/ca.crt') +ctx.load_cert_chain('/identity/tls.crt','/identity/tls.key') +for url in sys.argv[1:]: + try: + with urllib.request.urlopen(url,context=ctx,timeout=5) as reply: + print(json.dumps(json.load(reply))) + except urllib.error.HTTPError as error: + if error.code != 404: + raise + print('{}') +""" + + +def main(): + args = arguments('Local log and trace privacy') + client = Client(args.base_url, args.ca_file) + alice, _, _, chat = client.bootstrap() + registration = alice['registration'] + password = registration['password'] + credential = base64.b64encode(f"{registration['username']}:{password}".encode()).decode() + login = client.call('POST', '/api/v1/auth/sessions', 201, + headers={'Authorization': 'Basic ' + credential}, schema='Session') + marker = 'telemetry-private-' + uuid.uuid4().hex + message = client.message(alice, chat, marker) + pki = ROOT / 'certs/private' + command = [ + 'docker', 'run', '--rm', '--network', 'messenger-lab7_default', + '-v', f'{pki / "ca.crt"}:/ca/ca.crt:ro', + '-v', f'{pki / "grafana-client"}:/identity:ro', + 'python:3.11.9-slim', 'python', '-c', FETCH, + ] + urls = [] + for response in (login, message): + headers = response['headers'] + query = urlencode({'query': '{service_name="messenger-api"} | request_id="' + + headers['X-Request-Id'] + '"'}) + urls.extend([ + 'https://loki:3101/loki/api/v1/query_range?' + query, + 'https://tempo:3201/api/traces/' + headers['X-Trace-Id'], + ]) + deadline = time.monotonic() + 60 + while True: + output = subprocess.check_output([*command, *urls], cwd=ROOT, text=True) + login_logs, login_trace, message_logs, message_trace = map(json.loads, output.splitlines()) + if (login_logs.get('data', {}).get('result') and login_trace + and message_logs.get('data', {}).get('result') and message_trace): + break + check(time.monotonic() < deadline, 'Correlated login or message telemetry not found') + time.sleep(3) + for sensitive in (password, credential, login['json']['token'], alice['token'], marker): + check(sensitive not in output, 'Correlated telemetry contained a synthetic secret') + (ROOT / 'evidence/telemetry-privacy.json').write_text(json.dumps({ + 'correlated_log_and_trace_found': ['login', 'message'], + 'synthetic_secrets_found': 0, + }, indent=2) + '\n', encoding='utf-8') + print('PASS: correlated login and message telemetry omit synthetic secrets') + + +if __name__ == '__main__': + run(main) diff --git a/tests/test_tls_boundaries.py b/tests/test_tls_boundaries.py new file mode 100644 index 00000000..7a74f409 --- /dev/null +++ b/tests/test_tls_boundaries.py @@ -0,0 +1,59 @@ +"""Verify only the local lab's configured TLS identity and scoped secret boundaries.""" +import json +from pathlib import Path +import subprocess + +ROOT=Path(__file__).resolve().parents[1] +PROBE=''' +import ssl,socket,sys,json,urllib.request,urllib.error +host,port,identity,expected,kind=sys.argv[1:] +ctx=ssl.create_default_context(cafile='/ca.crt') +if identity=='yes': ctx.load_cert_chain('/identity/tls.crt','/identity/tls.key') +ok=False +try: + if kind=='http': + try: + urllib.request.urlopen('https://'+host+':'+port+'/health/live',context=ctx,timeout=5).read() + ok=True + except urllib.error.HTTPError: + ok=True + elif kind=='redis': + with socket.create_connection((host,int(port)),timeout=5) as sock: + with ctx.wrap_socket(sock,server_hostname=host) as tls: + tls.sendall(b'*1\\r\\n$4\\r\\nPING\\r\\n') + ok=bool(tls.recv(256)) +except (OSError,urllib.error.URLError): pass +if ok != (expected=='yes'): raise SystemExit('unexpected TLS result') +print('PASS') +''' + + +def probe(host,port,role,expected,kind): + pki=ROOT/'certs/private' + cmd=['docker','run','--rm','--network','messenger-lab7_default','-v',f'{pki/("ca.crt")}:/ca.crt:ro'] + if role: + cmd+=['-v',f'{pki/role}:/identity:ro'] + cmd+=['python:3.11.9-slim','python','-c',PROBE,host,str(port),'yes' if role else 'no','yes' if expected else 'no',kind] + subprocess.run(cmd,check=True,cwd=ROOT) + + +def main(): + results=[] + for host,port,kind,allowed,wrong in [ + ('api',8443,'http','lb-client','api-client'), + ('broker',6379,'redis','worker-client','api-client'), + ('collector',4319,'http','worker-client','lb-client'), + ('collector',8890,'http','prometheus-client','worker-client'), + ('loki',3101,'http','collector-client','worker-client'), + ('tempo',4319,'http','collector-client','worker-client'), + ('tempo',3201,'http','grafana-client','worker-client'), + ('prometheus',9090,'http','grafana-client','worker-client'), + ]: + for role,expected in [(allowed,True),(None,False),(wrong,False)]: + probe(host,port,role,expected,kind) + results.append({'service':host,'port':port,'client':role or 'none','accepted':expected}) + (ROOT/'evidence/tls-boundaries.json').write_text(json.dumps(results,indent=2)+'\n',encoding='utf-8') + + +if __name__=='__main__': + main() diff --git a/tests/test_worker_permissions.py b/tests/test_worker_permissions.py new file mode 100644 index 00000000..7f25d691 --- /dev/null +++ b/tests/test_worker_permissions.py @@ -0,0 +1,73 @@ +"""Verify the worker identity against PostgreSQL, S3 and the broker.""" +import json +from pathlib import Path +import subprocess + + +ROOT = Path(__file__).resolve().parents[1] +CHECK = """ +import json +import os +import uuid + +import boto3 +from botocore.config import Config +from botocore.exceptions import ClientError +import psycopg +from psycopg.errors import InsufficientPrivilege +import redis + +with psycopg.connect(os.environ['DATABASE_URL'], autocommit=True) as db: + db.execute('SELECT id FROM attachments LIMIT 0') + assert db.execute('SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()').fetchone()[0] + try: + db.execute('SELECT id FROM users LIMIT 0') + except InsufficientPrivilege: + pass + else: + raise AssertionError('Worker can read the users table') + +s3 = boto3.client('s3', endpoint_url=os.environ['S3_ENDPOINT'], + aws_access_key_id=os.environ['S3_ACCESS_KEY'], + aws_secret_access_key=os.environ['S3_SECRET_KEY'], + verify='/ca/ca.crt', config=Config(s3={'addressing_style': 'path'})) +bucket = os.environ['S3_BUCKET'] +key = 'original/permission-test-' + uuid.uuid4().hex +s3.list_objects_v2(Bucket=bucket, Prefix='staging/', MaxKeys=1) +try: + s3.head_object(Bucket=bucket, Key=key) +except ClientError as error: + assert error.response['ResponseMetadata']['HTTPStatusCode'] == 403 +else: + raise AssertionError('Worker can read from the original prefix') + +broker = redis.Redis.from_url(os.environ['BROKER_URL'], ssl_ca_certs='/ca/ca.crt', + ssl_certfile='/identity/tls.crt', ssl_keyfile='/identity/tls.key', + ssl_check_hostname=True, socket_timeout=5) +assert broker.ping() +try: + broker.xlen('attachment:jobs') +except redis.exceptions.NoPermissionError: + pass +else: + raise AssertionError('Worker was granted a broker command outside its role') +try: + broker.xreadgroup('workers', 'permission-check', {'permission-test-' + uuid.uuid4().hex: '>'}) +except redis.exceptions.NoPermissionError: + pass +else: + raise AssertionError('Worker can access an unrelated stream') + +print(json.dumps({'postgres_tls_and_table_acl': True, 's3_tls_and_prefix_acl': True, + 'broker_mtls_and_command_acl': True})) +""" + +output = subprocess.check_output( + ['docker', 'compose', 'exec', '-T', 'worker', 'python', 'secret_entry.py', 'python', '-c', CHECK], + cwd=ROOT, text=True, +) +results = json.loads(output) +(ROOT / 'evidence/worker-permissions.json').write_text( + json.dumps(results, indent=2) + '\n', encoding='utf-8', +) +print('PASS: worker TLS and scopes in PostgreSQL, S3 and the broker') diff --git a/tls_proxy.py b/tls_proxy.py new file mode 100644 index 00000000..22c3d222 --- /dev/null +++ b/tls_proxy.py @@ -0,0 +1,54 @@ +"""TLS termination restricted by verified client identity; private loopback upstream.""" +import asyncio +import os +import ssl +import hashlib +from pathlib import Path + + +async def pipe(source,destination): + try: + while data:=await source.read(65536): + destination.write(data) + await destination.drain() + finally: + destination.close() + + +async def main(): + allowed=set(filter(None,os.getenv('TLS_ALLOWED_IDENTITIES','').split(','))) + context=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.minimum_version=ssl.TLSVersion.TLSv1_2 + context.load_cert_chain('/tls/tls.crt','/tls/tls.key') + if allowed: + context.load_verify_locations('/ca/ca.crt') + context.verify_mode=ssl.CERT_REQUIRED + + async def handle(reader,writer): + try: + if allowed: + cert=writer.get_extra_info('peercert') or {} + identities={value for kind,value in cert.get('subjectAltName',()) if kind=='DNS'} + if not identities.intersection(allowed): + return + pins=Path('/pins') + if pins.is_dir(): + fingerprint=hashlib.sha256(writer.get_extra_info('ssl_object').getpeercert(binary_form=True)).digest() + trusted={hashlib.sha256(ssl.PEM_cert_to_DER_cert((pins/f'{identity}.crt').read_text())).digest() + for identity in identities.intersection(allowed) if (pins/f'{identity}.crt').is_file()} + if fingerprint not in trusted: + return + upstream,output=await asyncio.open_connection('127.0.0.1',int(os.environ['TLS_BACKEND_PORT'])) + await asyncio.gather(pipe(reader,output),pipe(upstream,writer),return_exceptions=True) + except (OSError,ssl.SSLError): + pass + finally: + writer.close() + + server=await asyncio.start_server(handle,'0.0.0.0',int(os.environ['TLS_LISTEN_PORT']),ssl=context,ssl_handshake_timeout=5) + async with server: + await server.serve_forever() + + +if __name__=='__main__': + asyncio.run(main()) diff --git a/worker.py b/worker.py new file mode 100644 index 00000000..2fe130eb --- /dev/null +++ b/worker.py @@ -0,0 +1,151 @@ +"""Single-concurrency durable image worker; deterministic object keys.""" +import hashlib +import io +import json +import os +from pathlib import Path +import signal +import socket +import time + +from PIL import Image, ImageOps, UnidentifiedImageError +from psycopg.types.json import Jsonb + +import db +import telemetry as ot +from opentelemetry import propagate +from opentelemetry.trace import SpanKind +from attachments import BUCKET, S3, MAX_BYTES, MAX_PIXELS +from pipeline import BROKER, STREAM, GROUP, ensure_group, claim, fail + + +def bounded_image(data): + if len(data)>MAX_BYTES: + raise ValueError('oversized image') + with Image.open(io.BytesIO(data)) as source: + if source.width*source.height>MAX_PIXELS: + raise ValueError('oversized image') + image=ImageOps.exif_transpose(source) + image.load() + if image.mode in ('RGBA','LA') or 'transparency' in image.info: + rgba=image.convert('RGBA') + rgb=Image.new('RGB',rgba.size,'white') + rgb.paste(rgba,mask=rgba.getchannel('A')) + return rgb + return image.convert('RGB') + + +def fit(image,limit): + w,h=image.size + factor=min(1,limit/max(w,h)) + return image.resize((max(1,int(w*factor)),max(1,int(h*factor))),Image.Resampling.LANCZOS) + + +def variant(job_id,name,image,fmt,mime,quality): + buffer=io.BytesIO() + image.save(buffer,format=fmt,quality=quality) + data=buffer.getvalue() + S3.put_object(Bucket=BUCKET,Key=f'variants/{job_id}/{name}',Body=data,ContentType=mime) + return {'name':name,'content_type':mime,'size_bytes':len(data),'width':image.width,'height':image.height, + 'sha256':hashlib.sha256(data).hexdigest()} + + +def process(job_id): + with db.pool.connection() as conn: + row=conn.execute("SELECT * FROM attachments WHERE id=%s AND status='processing' FOR UPDATE",(job_id,)).fetchone() + if not row: + return + with ot.tracer.start_as_current_span('s3 read staging'): + body=S3.get_object(Bucket=BUCKET,Key=f'staging/{job_id}')['Body'] + try: + data=body.read(MAX_BYTES+1) + finally: + body.close() + if hashlib.sha256(data).hexdigest()!=row['sha256']: + raise ValueError('invalid staging checksum') + image=bounded_image(data) + original=f'original/{job_id}' + with ot.tracer.start_as_current_span('s3 write original'): + S3.put_object(Bucket=BUCKET,Key=original,Body=data,ContentType=row['content_type']) + variants=[variant(job_id,'thumbnail',fit(image,256),'JPEG','image/jpeg',85), + variant(job_id,'crop',ImageOps.fit(image,(128,128),Image.Resampling.LANCZOS),'JPEG','image/jpeg',85), + variant(job_id,'optimized',fit(image,1280),'WEBP','image/webp',80)] + # Explicit local test hook, only armed by operator inside worker container. + marker=Path('/tmp/lab-crash-once') + if marker.exists(): + marker.unlink() + os._exit(77) + with ot.tracer.start_as_current_span('db publish attachment result'): + conn.execute("UPDATE attachments SET status='ready',object_key=%s,variants=%s,error_code=NULL,updated_at=now() WHERE id=%s", + (original,Jsonb(variants),job_id)) + conn.execute('UPDATE attachment_jobs SET lease_until=NULL WHERE id=%s',(job_id,)) + try: + S3.delete_object(Bucket=BUCKET,Key=f'staging/{job_id}') + with db.pool.connection() as conn: + conn.execute("UPDATE attachments SET staging_cleaned=TRUE WHERE id=%s AND status='ready'",(job_id,)) + except Exception: + pass # periodic cleanup retries ready staging deletion + + +def timeout(*_): + raise TimeoutError('worker deadline') + + +def handle(message_id,fields): + job=json.loads(fields['job']) + job_id=job['attachment_id'] + with ot.tracer.start_as_current_span('attachment process',context=propagate.extract(job),kind=SpanKind.CONSUMER): + handle_job(message_id,job_id) + + +def handle_job(message_id,job_id): + if claim(job_id): + started=time.monotonic() + outcome='success' + ot.state['worker_busy']=1 + signal.alarm(90) + try: + process(job_id) + except (UnidentifiedImageError, Image.DecompressionBombError, ValueError): + outcome='failed' + fail(job_id,permanent=True) + except Exception: + outcome='retry' + fail(job_id) + finally: + signal.alarm(0) + ot.state['worker_busy']=0 + ot.job_count.add(1,{'outcome':outcome,'job_type':'attachment'}) + ot.job_duration.record(time.monotonic()-started,{'outcome':outcome,'job_type':'attachment'}) + ot.logger.info('job_processed',extra={'outcome':outcome}) + if outcome=='success': + with db.pool.connection() as conn: + age=conn.execute('SELECT extract(epoch FROM now()-created_at) AS age FROM attachment_jobs WHERE id=%s',(job_id,)).fetchone() + ot.ready_duration.record(float(age['age'])) + # Durable DB result/retry intent precedes acknowledgment. + BROKER.xack(STREAM,GROUP,message_id) + BROKER.xdel(STREAM,message_id) + + +def main(): + db.pool.open(wait=True,timeout=30) + signal.signal(signal.SIGALRM,timeout) + consumer=socket.gethostname() + while True: + try: + ensure_group() + stale=BROKER.xautoclaim(STREAM,GROUP,consumer,120000,'0-0',count=1)[1] + if stale: + for mid,fields in stale: + handle(mid,fields) + continue + for _,messages in BROKER.xreadgroup(GROUP,consumer,{STREAM:'>'},count=1,block=1000): + for mid,fields in messages: + handle(mid,fields) + except Exception: + print('worker will retry',flush=True) + time.sleep(1) + + +if __name__=='__main__': + main()