Complete lab 7 TLS and secret management
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
+4
-16
@@ -1,20 +1,8 @@
|
|||||||
.git
|
.git
|
||||||
.github
|
|
||||||
.env
|
.env
|
||||||
.env.*
|
.local
|
||||||
!.env.example
|
|
||||||
secrets
|
|
||||||
certs
|
|
||||||
volumes
|
|
||||||
data
|
|
||||||
backups
|
|
||||||
*.key
|
|
||||||
*.pem
|
|
||||||
*.p12
|
|
||||||
*.pfx
|
|
||||||
*.jks
|
|
||||||
.venv
|
.venv
|
||||||
__pycache__
|
__pycache__
|
||||||
node_modules
|
*.py[cod]
|
||||||
evidence
|
*.pem
|
||||||
.DS_Store
|
*.key
|
||||||
|
|||||||
+3
-41
@@ -1,41 +1,3 @@
|
|||||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
# Do not put credentials in this template. Run python3 scripts/bootstrap.py.
|
||||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
# The bootstrap creates an ignored .env with locally generated passwords and keys.
|
||||||
APP_HOST=0.0.0.0
|
PUBLIC_PORT=8443
|
||||||
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
|
|
||||||
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
|
|
||||||
|
|||||||
@@ -1,18 +1,28 @@
|
|||||||
## Лабораторная 7
|
## Лабораторная 7
|
||||||
|
|
||||||
Автор / группа: TODO
|
Автор / группа: Бахрамов Бахрам, БПИ2303
|
||||||
Целевая оценка (3/4/5): TODO
|
Целевая оценка: 3
|
||||||
Трек 5, если заявлен: TODO
|
Трек 5: не заявлен
|
||||||
|
|
||||||
Что реализовано и что перенесено: TODO
|
### Реализация
|
||||||
Команды запуска из чистого clone: TODO
|
|
||||||
Результаты проверок и ссылка на REPORT.md: TODO
|
|
||||||
Ограничения / известные ошибки: TODO
|
|
||||||
Источники и использование ИИ: TODO
|
|
||||||
|
|
||||||
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
Перенесён REST-мессенджер из предыдущих работ. Добавлены HTTPS ingress, обязательное mTLS HAProxy→обе API-реплики с URI SAN allowlist, PostgreSQL TLS и раздельные роли, HTTPS S3 с bucket scopes, AMQPS с раздельными Rabbit ACL, OpenBao non-dev/AppRole/KV policies, защищённый OTLP и локальная наблюдаемость. Полное описание и границы уровня 3: [REPORT.md](REPORT.md), [trust matrix](contracts/trust-matrix.md), [threat model](security/THREAT_MODEL.md).
|
||||||
- [ ] Контракт и публичные тесты не ослаблены.
|
|
||||||
- [ ] make check и make test выполнены; приложен реальный вывод.
|
### Воспроизводимость
|
||||||
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
|
|
||||||
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
```sh
|
||||||
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
python3 scripts/bootstrap.py
|
||||||
|
make check
|
||||||
|
make test BASE_URL=https://localhost:8443 CA_FILE=.local/pki/external-ca.crt
|
||||||
|
make verify
|
||||||
|
```
|
||||||
|
|
||||||
|
Текущий результат и фактические команды: [evidence/verification.txt](evidence/verification.txt).
|
||||||
|
|
||||||
|
### Проверки и ограничения
|
||||||
|
|
||||||
|
Smoke, TLS/mTLS отрицательные проверки, AppRole/DB/S3/Rabbit ACL, worker retry/redelivery, persistence, отказ одной API-реплики, storage failure и telemetry проверяются `make verify`. Проверки не отключают TLS trust. Один host, статические credentials в KV и отсутствие автоматической ротации — задокументированные ограничения; уровень 4/5 не заявлен.
|
||||||
|
|
||||||
|
Использование ИИ: ИИ применялся при анализе задания, реализации/отладке и подготовке документации. Автор проверил результат и готов объяснить его на защите.
|
||||||
|
|
||||||
|
Все секреты и private keys находятся в `.env`/`.local` и исключены из Git; перед отправкой staged diff проверен.
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ certs/private/
|
|||||||
*.pfx
|
*.pfx
|
||||||
*.jks
|
*.jks
|
||||||
*.pem
|
*.pem
|
||||||
|
*.srl
|
||||||
*.tfstate*
|
*.tfstate*
|
||||||
volumes/
|
volumes/
|
||||||
data/
|
data/
|
||||||
@@ -30,3 +31,4 @@ coverage/
|
|||||||
.vscode/
|
.vscode/
|
||||||
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
||||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||||
|
.local/
|
||||||
|
|||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
FROM python:3.12.10-slim
|
||||||
|
WORKDIR /srv
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
COPY app app
|
||||||
|
COPY contracts contracts
|
||||||
|
COPY migrations migrations
|
||||||
|
COPY tests tests
|
||||||
|
RUN useradd --uid 10001 --create-home api
|
||||||
|
USER api
|
||||||
|
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--timeout-graceful-shutdown", "5"]
|
||||||
@@ -1,13 +1,23 @@
|
|||||||
PYTHON ?= python3
|
PYTHON ?= python3
|
||||||
BASE_URL ?= https://localhost:8443
|
BASE_URL ?= https://localhost:8443
|
||||||
CA_FILE ?=
|
CA_FILE ?= .local/pki/external-ca.crt
|
||||||
ACTION_SCRIPT ?=
|
ACTION_SCRIPT ?=
|
||||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||||
|
|
||||||
.PHONY: help check validate test load test-persistence test-failover test-security
|
.PHONY: help check validate bootstrap up down test test-security test-observability load test-persistence test-failover worker-flow verify
|
||||||
|
|
||||||
help:
|
help:
|
||||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
@echo "bootstrap: create local PKI/secrets, initialize OpenBao and start the grade-3 stack"
|
||||||
|
@echo "check: offline contract checks; test: running API over verified HTTPS"
|
||||||
|
@echo "verify: full public and local negative checks; load: synthetic writes"
|
||||||
|
|
||||||
|
bootstrap:
|
||||||
|
$(PYTHON) scripts/bootstrap.py
|
||||||
|
|
||||||
|
up: bootstrap
|
||||||
|
|
||||||
|
down:
|
||||||
|
docker compose down
|
||||||
|
|
||||||
check:
|
check:
|
||||||
$(PYTHON) scripts/check_contract.py
|
$(PYTHON) scripts/check_contract.py
|
||||||
@@ -18,16 +28,26 @@ validate:
|
|||||||
test:
|
test:
|
||||||
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
|
test-security:
|
||||||
|
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
$(PYTHON) tests/security_runtime.py --base-url "$(BASE_URL)" --ca-file "$(CA_FILE)"
|
||||||
|
|
||||||
|
test-observability:
|
||||||
|
$(PYTHON) tests/observability.py
|
||||||
|
|
||||||
load:
|
load:
|
||||||
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
test-persistence:
|
test-persistence:
|
||||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to scripts/restart.sh"; exit 2)
|
||||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
test-failover:
|
test-failover:
|
||||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
|
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to scripts/stop-one.sh"; exit 2)
|
||||||
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
test-security:
|
worker-flow:
|
||||||
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/worker_flow.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
|
verify:
|
||||||
|
$(PYTHON) scripts/verify.py
|
||||||
|
|||||||
@@ -1,37 +1,56 @@
|
|||||||
# Отчёт — лабораторная 7
|
# Лабораторная 7 — TLS/mTLS, OpenBao и минимальные привилегии
|
||||||
|
|
||||||
- Автор, группа: TODO
|
Автор: Бахрамов Бахрам, БПИ2303. Целевая оценка: **3**. Исследовательский трек не заявлен.
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
Ветка сдачи: `solution/bpi2303-bakhramov`.
|
||||||
- Commit/PR: TODO после публикации
|
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Результат
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Перенесён REST-мессенджер из предыдущих работ: две API-реплики за HAProxy, PostgreSQL, приватные вложения SeaweedFS S3, RabbitMQ и отдельный worker. Внешний HTTPS проверяет локальную CA и hostname. HAProxy соединяется с каждой API-репликой по TLS с обязательным клиентским сертификатом; API дополнительно проверяет URI SAN `spiffe://mtusi2026/lab7/load-balancer`. API и worker читают свои секреты из OpenBao через AppRole и отдельные read-only KV policies.
|
||||||
|
|
||||||
## Архитектура и решения
|
Пароли хранятся как Argon2id (`m=19456, t=2, p=1`); в PostgreSQL сохраняется SHA-256 хеш session token, а не сам token. Общий для двух API rate limit хранится в PostgreSQL и отвечает `429` с `Retry-After`. Доступ к чату и вложениям основан на Bearer-сессии и членстве в чате.
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
Цель — уровень 3. Уровень 4 не заявлен: для него здесь не реализованы ротация секретов/сертификатов с доказанным отзывом, mTLS к RabbitMQ и расширенный жизненный цикл identity. Приватные локальные файлы bootstrap защищены правами ОС, но их безопасное резервирование остаётся ответственностью оператора этого учебного хоста.
|
||||||
|
|
||||||
## Доказательства критериев
|
## Запуск с чистого clone
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
Требуются Docker Engine/Desktop с Compose v2, Python 3 и OpenSSL. Не копируйте реальные `.env`, `.local` или приватные ключи из другой машины.
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
```sh
|
||||||
|
python3 scripts/bootstrap.py
|
||||||
|
make check
|
||||||
|
make test BASE_URL=https://localhost:8443 CA_FILE=.local/pki/external-ca.crt
|
||||||
|
make verify
|
||||||
|
```
|
||||||
|
|
||||||
## Эксперименты и отказы
|
`scripts/bootstrap.py` создаёт локальные CA/сертификаты и случайные секреты, поднимает зависимости, инициализирует OpenBao в non-dev режиме, создаёт scoped AppRole, настраивает RabbitMQ ACL, приватные S3 buckets, миграции и запускает стенд. Если после полного выключения OpenBao остался sealed, повторите `python3 scripts/bootstrap.py` либо выполните `python3 scripts/unseal.py` из этой папки. Для обычного сохранения данных используйте `docker compose down`; **не** используйте `down -v`.
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
Скрипты тестов создают синтетические записи и не удаляют их. Полный `make verify` запускает smoke, отрицательные проверки, повторную доставку, retry, persistence, отказ одной API-реплики, отказ storage и наблюдаемость. Используйте отдельные volumes для повторной демонстрации на чистых данных.
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
Административные web/API порты привязаны к `127.0.0.1`: ingress 8443, OpenBao 8207, Prometheus 9097, Loki 3107, Tempo 3207, Grafana 3007. Для входа в Grafana используется пользователь `admin` и локальный `GRAFANA_PASSWORD` из игнорируемого `.env`. OTLP, API-реплики, DB, S3 и broker не опубликованы на host.
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| TODO | TODO | TODO | TODO |
|
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## Архитектура и границы
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
Клиент — HTTPS — HAProxy — mTLS — API-реплики. API/worker подключаются к PostgreSQL по TLS `verify-full` с раздельными DB-ролями, к SeaweedFS S3 по HTTPS и к RabbitMQ по AMQPS с отдельными credentials. API производит задания, worker читает их из одной durable queue. API/worker отправляют OTLP по mTLS в Collector; Collector использует mTLS к защищённым HTTP/gRPC endpoints Prometheus, Loki и Tempo. Grafana использует собственную клиентскую identity к backends.
|
||||||
|
|
||||||
|
OpenBao использует file storage на named volume, TLS listener и KV v2. AppRole токены имеют TTL 10 минут и максимум 30 минут; полученные API/worker secrets проверяются по allowlist полей и не передаются в container environment. Сами сервисные credentials доступны только в памяти процесса. Bootstrap/операторские recovery данные находятся в локальной игнорируемой директории `.local/openbao`, недоступной контейнеру OpenBao как mount. Два AppRole имеют раздельную read-only policy: `messenger/api` и `messenger/worker`.
|
||||||
|
|
||||||
|
Подробные разрешённые identities, порты и проверки приведены в [матрице доверия](contracts/trust-matrix.md); пути атак и остаточные риски — в [модели угроз](security/THREAT_MODEL.md).
|
||||||
|
|
||||||
|
## Доказательства
|
||||||
|
|
||||||
|
Публичный smoke проверяет регистрацию/сессии, авторизацию, чаты, сообщения, idempotency, вложения, приватный доступ и thumbnail. Дополнительные сценарии проверяют отказ TLS, обязательность и identity mTLS, ограничение OpenBao policy, DB/S3/Rabbit ACL, ограничение login rate, logout/expiry, сохранение данных при restart, последовательный отказ API и API/worker telemetry.
|
||||||
|
|
||||||
|
Фактические команды и итоги успешной проверки записаны в [`evidence/verification.txt`](evidence/verification.txt). Полный повторяемый набор — `make verify`. Проверки не отключают проверку CA/hostname и не меняют публичный контракт.
|
||||||
|
|
||||||
|
## Ограничения
|
||||||
|
|
||||||
|
- Один Docker host; HAProxy, PostgreSQL и SeaweedFS здесь остаются единичными точками отказа. Тест отказа API не проверяет отказ host или кластера.
|
||||||
|
- Локальные корневые CA, leaf private keys, OpenBao recovery material и `.env` не коммитятся. CA создаются со сроком 825 дней, service leaf — 90 дней; автоматической ротации/отзыва нет.
|
||||||
|
- RabbitMQ использует TLS с проверкой сервера и раздельные producer/consumer ACL; клиентские сертификаты к broker и Collector identity rollover относятся к уровню 4 и не заявлены.
|
||||||
|
- Безопасность bootstrap зависит от ОС-аккаунта и защиты диска оператора. При потере локального OpenBao recovery material стенд нельзя восстановить без повторной инициализации хранилища.
|
||||||
|
- SeaweedFS master/volume/filer образуют изолированную внутреннюю сеть; их служебный transport не публикуется на host. Это учебная локальная граница, не production-сеть.
|
||||||
|
- Исследовательский трек уровня 5 и dependency/image scan triage не выполнялись.
|
||||||
|
|
||||||
|
## Источники и использование ИИ
|
||||||
|
|
||||||
|
Контракт и рубрика: `README.md`, `COURSE.md`, `contracts/`, `tests/`. Для настройки OpenBao использованы его публичные материалы, ссылки приведены в README задания. ИИ использовался при анализе задания, разработке/отладке конфигураций и тестов, а также подготовке документации. Автору следует проверить и быть готовым объяснить каждое решение на защите.
|
||||||
|
|||||||
+457
@@ -0,0 +1,457 @@
|
|||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import socket
|
||||||
|
import uuid
|
||||||
|
import warnings
|
||||||
|
import hmac
|
||||||
|
import ssl
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
from app.secrets import load_secrets
|
||||||
|
load_secrets()
|
||||||
|
|
||||||
|
import boto3
|
||||||
|
import psycopg
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
from argon2 import PasswordHasher, exceptions as argon2_exceptions
|
||||||
|
from fastapi import FastAPI, Request
|
||||||
|
from fastapi.responses import JSONResponse, Response
|
||||||
|
from jsonschema import Draft202012Validator, FormatChecker
|
||||||
|
from PIL import Image, ImageOps
|
||||||
|
import pika
|
||||||
|
from cryptography import x509
|
||||||
|
from cryptography.x509.oid import ExtensionOID
|
||||||
|
from starlette.concurrency import run_in_threadpool
|
||||||
|
from opentelemetry import propagate
|
||||||
|
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||||
|
from app.telemetry import HTTP_DURATION, HTTP_REQUESTS, tracer
|
||||||
|
|
||||||
|
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
|
||||||
|
INSTANCE = os.getenv('APP_INSTANCE_ID', 'api')
|
||||||
|
LAB = int(os.getenv('LAB_NUMBER', '4'))
|
||||||
|
DSN = os.environ['DATABASE_URL']
|
||||||
|
BUCKET = os.getenv('S3_BUCKET', 'attachments')
|
||||||
|
STAGING_BUCKET = os.getenv('S3_STAGING_BUCKET', BUCKET+'-staging')
|
||||||
|
ORIGINAL_BUCKET = os.getenv('S3_ORIGINAL_BUCKET', BUCKET+'-original')
|
||||||
|
VARIANTS_BUCKET = os.getenv('S3_VARIANTS_BUCKET', BUCKET+'-variants')
|
||||||
|
ph = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||||
|
schemas = json.load(open('contracts/openapi.json'))['components']['schemas']
|
||||||
|
Image.MAX_IMAGE_PIXELS = 40_000_000
|
||||||
|
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
||||||
|
|
||||||
|
|
||||||
|
def s3():
|
||||||
|
return boto3.client('s3', endpoint_url=os.environ['S3_ENDPOINT'],
|
||||||
|
aws_access_key_id=os.environ['S3_ACCESS_KEY'],
|
||||||
|
aws_secret_access_key=os.environ['S3_SECRET_KEY'],
|
||||||
|
region_name='us-east-1',
|
||||||
|
verify=os.getenv('S3_CA_CERT') or True,
|
||||||
|
config=boto3.session.Config(connect_timeout=2, read_timeout=5, retries={'max_attempts': 0},
|
||||||
|
s3={'addressing_style':'path'}))
|
||||||
|
|
||||||
|
|
||||||
|
def now():
|
||||||
|
return datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
|
||||||
|
|
||||||
|
|
||||||
|
def publish_job(payload):
|
||||||
|
params = pika.URLParameters(os.environ['BROKER_URL'])
|
||||||
|
params.heartbeat = 30
|
||||||
|
params.blocked_connection_timeout = 5
|
||||||
|
tls = ssl.create_default_context(cafile=os.environ['BROKER_CA_CERT'])
|
||||||
|
tls.check_hostname = True
|
||||||
|
params.ssl_options = pika.SSLOptions(tls, server_hostname='broker')
|
||||||
|
connection = pika.BlockingConnection(params)
|
||||||
|
try:
|
||||||
|
channel = connection.channel()
|
||||||
|
channel.queue_declare(queue='attachment.process.v1', durable=True)
|
||||||
|
channel.confirm_delivery()
|
||||||
|
with tracer.start_as_current_span('rabbitmq.publish', context=propagate.extract(payload), kind=SpanKind.PRODUCER,
|
||||||
|
attributes={'messenger.job.type': payload['type']}):
|
||||||
|
headers = {}
|
||||||
|
propagate.inject(headers)
|
||||||
|
channel.basic_publish(
|
||||||
|
exchange='', routing_key='attachment.process.v1', body=json.dumps(payload).encode(),
|
||||||
|
properties=pika.BasicProperties(content_type='application/json', delivery_mode=2,
|
||||||
|
message_id=payload['job_id'], type=payload['type'], headers=headers))
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
|
||||||
|
def job_payload(job_id, attachment_id, attempt=1, trace_context=None):
|
||||||
|
payload = {'schema_version':1,'job_id':str(job_id),'type':'attachment.process.v1',
|
||||||
|
'attachment_id':str(attachment_id),'pipeline_version':1,'attempt':attempt,'created_at':now()}
|
||||||
|
if trace_context:
|
||||||
|
payload.update({key:trace_context[key] for key in ('traceparent','tracestate') if key in trace_context})
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def uid(value):
|
||||||
|
try:
|
||||||
|
return str(uuid.UUID(value))
|
||||||
|
except (ValueError, TypeError, AttributeError):
|
||||||
|
fail(400)
|
||||||
|
|
||||||
|
|
||||||
|
def fail(status):
|
||||||
|
raise APIError(status)
|
||||||
|
|
||||||
|
|
||||||
|
class APIError(Exception):
|
||||||
|
def __init__(self, status, retry_after=60):
|
||||||
|
self.status = status
|
||||||
|
self.retry_after = retry_after
|
||||||
|
|
||||||
|
|
||||||
|
CODES = {400: 'invalid_request', 401: 'unauthorized', 403: 'forbidden', 404: 'not_found',
|
||||||
|
409: 'conflict', 413: 'payload_too_large', 415: 'unsupported_media_type', 429: 'rate_limited',
|
||||||
|
503: 'unavailable', 500: 'internal_error'}
|
||||||
|
|
||||||
|
|
||||||
|
def error(status, request_id, path, retry_after=60):
|
||||||
|
code = CODES[status]
|
||||||
|
headers = {}
|
||||||
|
if status == 401:
|
||||||
|
headers['WWW-Authenticate'] = ('Basic realm="messenger", charset="UTF-8"'
|
||||||
|
if path.endswith('/auth/sessions') else 'Bearer realm="messenger"')
|
||||||
|
if status == 429:
|
||||||
|
headers['Retry-After'] = str(max(1,int(retry_after)))
|
||||||
|
return JSONResponse({'error': {'code': code, 'message': code, 'request_id': request_id}},
|
||||||
|
status_code=status, headers=headers)
|
||||||
|
|
||||||
|
|
||||||
|
def allowed_load_balancer(request):
|
||||||
|
chain=request.scope.get('extensions',{}).get('tls',{}).get('client_cert_chain',[])
|
||||||
|
if not chain:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
certificate=x509.load_pem_x509_certificate(chain[0].encode())
|
||||||
|
names=certificate.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME).value
|
||||||
|
return 'spiffe://mtusi2026/lab7/load-balancer' in names.get_values_for_type(x509.UniformResourceIdentifier)
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
@app.middleware('http')
|
||||||
|
async def headers_and_errors(request, call_next):
|
||||||
|
request_id = secrets.token_hex(16)
|
||||||
|
parent = propagate.extract(dict(request.headers))
|
||||||
|
started = time.perf_counter()
|
||||||
|
with tracer.start_as_current_span('http.server', context=parent, kind=SpanKind.SERVER,
|
||||||
|
attributes={'http.request.method': request.method}) as span:
|
||||||
|
try:
|
||||||
|
if LAB >= 7 and not allowed_load_balancer(request):
|
||||||
|
fail(403)
|
||||||
|
response = await call_next(request)
|
||||||
|
except APIError as exc:
|
||||||
|
response = error(exc.status, request_id, request.url.path, getattr(exc,'retry_after',60))
|
||||||
|
except (psycopg.OperationalError, psycopg.InterfaceError):
|
||||||
|
response = error(503, request_id, request.url.path)
|
||||||
|
except Exception as exc:
|
||||||
|
import logging
|
||||||
|
logging.error('request.failed', extra={'event':'request.failed','error_type':type(exc).__name__})
|
||||||
|
response = error(500, request_id, request.url.path)
|
||||||
|
route = getattr(request.scope.get('route'), 'path', 'unmatched')
|
||||||
|
status_class = f'{response.status_code // 100}xx'
|
||||||
|
span.set_attribute('http.route', route)
|
||||||
|
span.set_attribute('http.response.status_code', response.status_code)
|
||||||
|
attrs = {'method':request.method,'route':route,'status_class':status_class}
|
||||||
|
elapsed = time.perf_counter()-started
|
||||||
|
HTTP_REQUESTS.add(1, attrs)
|
||||||
|
HTTP_DURATION.record(elapsed, attrs)
|
||||||
|
import logging
|
||||||
|
logging.info('http.request.completed', extra={'event':'http.request.completed','request_id':request_id,
|
||||||
|
'method':request.method,'route':route,'status_class':status_class})
|
||||||
|
if response.status_code >= 500:
|
||||||
|
span.set_status(Status(StatusCode.ERROR))
|
||||||
|
response.headers['X-Request-Id'] = request_id
|
||||||
|
response.headers['X-Instance-Id'] = INSTANCE
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
def validate(body, name):
|
||||||
|
if not Draft202012Validator(schemas[name], format_checker=FormatChecker()).is_valid(body):
|
||||||
|
fail(400)
|
||||||
|
return body
|
||||||
|
|
||||||
|
|
||||||
|
def user(db, request):
|
||||||
|
auth = request.headers.get('authorization', '')
|
||||||
|
if not auth.startswith('Bearer '):
|
||||||
|
fail(401)
|
||||||
|
token = hashlib.sha256(auth[7:].encode()).hexdigest()
|
||||||
|
row = db.execute('SELECT u.doc FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.token=%s AND s.expires_at>now()', (token,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
fail(401)
|
||||||
|
return row[0]
|
||||||
|
|
||||||
|
|
||||||
|
def chat(db, ident, actor):
|
||||||
|
ident = uid(ident)
|
||||||
|
row = db.execute('SELECT doc FROM chats WHERE id=%s', (ident,)).fetchone()
|
||||||
|
if not row or actor['id'] not in row[0]['member_ids']:
|
||||||
|
fail(404)
|
||||||
|
return row[0]
|
||||||
|
|
||||||
|
|
||||||
|
def attachment(db, ident, actor):
|
||||||
|
row = db.execute('SELECT doc FROM attachments WHERE id=%s', (uid(ident),)).fetchone()
|
||||||
|
if not row:
|
||||||
|
fail(404)
|
||||||
|
chat(db, row[0]['chat_id'], actor)
|
||||||
|
return row[0]
|
||||||
|
|
||||||
|
|
||||||
|
def page(db, request, table, scope, actor):
|
||||||
|
raw = request.query_params.get('limit', '50')
|
||||||
|
if not re.fullmatch('[0-9]+', raw) or not 1 <= int(raw) <= 100:
|
||||||
|
fail(400)
|
||||||
|
limit = int(raw)
|
||||||
|
cursor = request.query_params.get('cursor')
|
||||||
|
after = None
|
||||||
|
if cursor:
|
||||||
|
try:
|
||||||
|
decoded = json.loads(base64.urlsafe_b64decode(cursor.encode()))
|
||||||
|
if len(decoded) != 3 or decoded[0] != scope:
|
||||||
|
fail(400)
|
||||||
|
datetime.fromisoformat(decoded[1].replace('Z', '+00:00'))
|
||||||
|
uid(decoded[2])
|
||||||
|
after = decoded[1:]
|
||||||
|
except Exception:
|
||||||
|
fail(400)
|
||||||
|
if table == 'chats':
|
||||||
|
where, args = "doc->'member_ids' ? %s", [actor['id']]
|
||||||
|
else:
|
||||||
|
where, args = "chat_id=%s", [scope]
|
||||||
|
if after:
|
||||||
|
where += " AND (doc->>'created_at',id)>(%s,%s::uuid)"
|
||||||
|
args += after
|
||||||
|
rows = db.execute(f"SELECT doc FROM {table} WHERE {where} ORDER BY doc->>'created_at',id LIMIT %s", args + [limit+1]).fetchall()
|
||||||
|
items = [r[0] for r in rows[:limit]]
|
||||||
|
next_cursor = None
|
||||||
|
if len(rows) > limit:
|
||||||
|
last = items[-1]
|
||||||
|
next_cursor = base64.urlsafe_b64encode(json.dumps([scope,last['created_at'],last['id']]).encode()).decode()
|
||||||
|
return {'items': items, 'next_cursor': next_cursor}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get('/health/live')
|
||||||
|
def live():
|
||||||
|
return {'status': 'ok'}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get('/health/ready')
|
||||||
|
def ready():
|
||||||
|
with psycopg.connect(DSN, connect_timeout=2) as db:
|
||||||
|
db.execute('SELECT count(*) FROM sessions')
|
||||||
|
if LAB >= 4:
|
||||||
|
try:
|
||||||
|
client=s3()
|
||||||
|
for bucket_name in (STAGING_BUCKET,ORIGINAL_BUCKET,VARIANTS_BUCKET):
|
||||||
|
client.list_objects_v2(Bucket=bucket_name,MaxKeys=0)
|
||||||
|
except Exception:
|
||||||
|
fail(503)
|
||||||
|
return {'status': 'ok'}
|
||||||
|
|
||||||
|
|
||||||
|
@app.api_route('/api/v1/{path:path}', methods=['GET', 'POST', 'DELETE'])
|
||||||
|
async def api(request: Request, path: str):
|
||||||
|
# Read bounded chunks before JSON parsing/image decoding.
|
||||||
|
limit = 10*1024*1024 if path.endswith('/attachments') else 65536
|
||||||
|
data = bytearray()
|
||||||
|
async for chunk in request.stream():
|
||||||
|
if len(data)+len(chunk) > limit:
|
||||||
|
fail(413)
|
||||||
|
data.extend(chunk)
|
||||||
|
return await run_in_threadpool(handle, request, path, bytes(data))
|
||||||
|
|
||||||
|
|
||||||
|
def handle(request, path, raw):
|
||||||
|
method = request.method
|
||||||
|
parts = path.split('/')
|
||||||
|
body = None
|
||||||
|
if method == 'POST' and path != 'auth/sessions' and not path.endswith('/attachments'):
|
||||||
|
try:
|
||||||
|
body = json.loads(raw)
|
||||||
|
except (ValueError, UnicodeError):
|
||||||
|
fail(400)
|
||||||
|
with psycopg.connect(DSN) as db:
|
||||||
|
if path == 'users' and method == 'POST':
|
||||||
|
validate(body, 'CreateUser')
|
||||||
|
if not body['display_name'].strip():
|
||||||
|
fail(400)
|
||||||
|
doc = {'id': str(uuid.uuid4()), 'username': body['username'], 'display_name': body['display_name'], 'created_at': now()}
|
||||||
|
hashed = ph.hash(body['password'])
|
||||||
|
if not db.execute('INSERT INTO users(id,username,password,doc) VALUES (%s,%s,%s,%s) ON CONFLICT(username) DO NOTHING RETURNING id', (doc['id'],doc['username'],hashed,Jsonb(doc))).fetchone():
|
||||||
|
fail(409)
|
||||||
|
return JSONResponse(doc, 201)
|
||||||
|
if path == 'auth/sessions' and method == 'POST':
|
||||||
|
auth = request.headers.get('authorization', '')
|
||||||
|
if not auth.startswith('Basic ') or raw:
|
||||||
|
fail(401)
|
||||||
|
try:
|
||||||
|
username, password = base64.b64decode(auth[6:], validate=True).decode().split(':',1)
|
||||||
|
except Exception:
|
||||||
|
fail(401)
|
||||||
|
rate_key=hmac.new(os.environ['LOGIN_RATE_HMAC_KEY'].encode(),
|
||||||
|
(str(request.client.host if request.client else 'unknown')+'\0'+username).encode(),
|
||||||
|
hashlib.sha256).hexdigest()
|
||||||
|
existing=db.execute("SELECT failures,window_started FROM login_rate_limits WHERE key_hash=%s",(rate_key,)).fetchone()
|
||||||
|
if existing and existing[0]>=5 and existing[1] > datetime.now(timezone.utc)-timedelta(seconds=60):
|
||||||
|
remaining=max(1,int((existing[1]+timedelta(seconds=60)-datetime.now(timezone.utc)).total_seconds()))
|
||||||
|
raise APIError(429,remaining)
|
||||||
|
row = db.execute('SELECT password,doc FROM users WHERE username=%s',(username,)).fetchone()
|
||||||
|
valid=False
|
||||||
|
if row:
|
||||||
|
try:
|
||||||
|
valid=ph.verify(row[0],password)
|
||||||
|
except (argon2_exceptions.VerifyMismatchError,argon2_exceptions.VerificationError,argon2_exceptions.InvalidHashError):
|
||||||
|
valid=False
|
||||||
|
if not valid:
|
||||||
|
db.execute("""INSERT INTO login_rate_limits(key_hash,window_started,failures) VALUES(%s,now(),1)
|
||||||
|
ON CONFLICT(key_hash) DO UPDATE SET
|
||||||
|
window_started=CASE WHEN login_rate_limits.window_started<=now()-interval '60 seconds' THEN now() ELSE login_rate_limits.window_started END,
|
||||||
|
failures=CASE WHEN login_rate_limits.window_started<=now()-interval '60 seconds' THEN 1 ELSE login_rate_limits.failures+1 END""",(rate_key,))
|
||||||
|
db.commit()
|
||||||
|
fail(401)
|
||||||
|
if ph.check_needs_rehash(row[0]):
|
||||||
|
db.execute('UPDATE users SET password=%s WHERE username=%s',(ph.hash(password),username))
|
||||||
|
db.execute('DELETE FROM login_rate_limits WHERE key_hash=%s',(rate_key,))
|
||||||
|
token = secrets.token_urlsafe(32)
|
||||||
|
expiry = datetime.now(timezone.utc)+timedelta(seconds=int(os.getenv('SESSION_TTL_SECONDS','3600')))
|
||||||
|
db.execute('INSERT INTO sessions VALUES(%s,%s,%s)', (hashlib.sha256(token.encode()).hexdigest(),row[1]['id'],expiry))
|
||||||
|
return JSONResponse({'token':token,'token_type':'Bearer','expires_at':expiry.isoformat().replace('+00:00','Z'),'user':row[1]},201)
|
||||||
|
actor = user(db, request)
|
||||||
|
if path == 'users/me' and method == 'GET':
|
||||||
|
return actor
|
||||||
|
if path == 'auth/sessions/current' and method == 'DELETE':
|
||||||
|
db.execute('DELETE FROM sessions WHERE token=%s',(hashlib.sha256(request.headers['authorization'][7:].encode()).hexdigest(),))
|
||||||
|
return Response(status_code=204)
|
||||||
|
if path == 'chats':
|
||||||
|
if method == 'GET':
|
||||||
|
return page(db,request,'chats','chats:'+actor['id'],actor)
|
||||||
|
if method == 'POST':
|
||||||
|
validate(body,'CreateChat')
|
||||||
|
if not body['title'].strip() or actor['id'] not in body['member_ids']:
|
||||||
|
fail(400)
|
||||||
|
for ident in body['member_ids']:
|
||||||
|
if not db.execute('SELECT id FROM users WHERE id=%s',(uid(ident),)).fetchone():
|
||||||
|
fail(400)
|
||||||
|
doc = dict(body,id=str(uuid.uuid4()),created_at=now())
|
||||||
|
db.execute('INSERT INTO chats VALUES(%s,%s)',(doc['id'],Jsonb(doc)))
|
||||||
|
return JSONResponse(doc,201)
|
||||||
|
if parts[0] == 'chats' and len(parts) >= 2:
|
||||||
|
current = chat(db, parts[1], actor)
|
||||||
|
if len(parts) == 2 and method == 'GET':
|
||||||
|
return current
|
||||||
|
if len(parts) == 3 and parts[2] == 'messages':
|
||||||
|
if method == 'GET':
|
||||||
|
return page(db,request,'messages',current['id'],actor)
|
||||||
|
if method == 'POST':
|
||||||
|
validate(body,'CreateMessage')
|
||||||
|
attachments = body.get('attachment_ids',[]) if LAB >= 4 else []
|
||||||
|
if not body['text'].strip() and not attachments:
|
||||||
|
fail(400)
|
||||||
|
key = request.headers.get('idempotency-key','')
|
||||||
|
if not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}',key):
|
||||||
|
fail(400)
|
||||||
|
for ident in attachments:
|
||||||
|
att = attachment(db,ident,actor)
|
||||||
|
if att['chat_id'] != current['id']:
|
||||||
|
fail(404)
|
||||||
|
if att['status'] == 'failed':
|
||||||
|
fail(409)
|
||||||
|
normalized = {'text':body['text'],'attachment_ids':attachments}
|
||||||
|
# A transaction-scoped shared lock serializes the entire lookup+insert.
|
||||||
|
scope = actor['id']+':'+current['id']+':'+key
|
||||||
|
db.execute('SELECT pg_advisory_xact_lock(hashtextextended(%s,0))',(scope,))
|
||||||
|
old = db.execute('SELECT body,doc FROM messages WHERE sender_id=%s AND chat_id=%s AND idem_key=%s AND saved_at>now()-interval \'24 hours\'',(actor['id'],current['id'],key)).fetchone()
|
||||||
|
if old:
|
||||||
|
if old[0] != normalized:
|
||||||
|
fail(409)
|
||||||
|
return JSONResponse(old[1],201)
|
||||||
|
doc = {'id':str(uuid.uuid4()),'chat_id':current['id'],'sender_id':actor['id'],'text':body['text'],'created_at':now()}
|
||||||
|
if LAB >= 4:
|
||||||
|
doc['attachment_ids'] = attachments
|
||||||
|
db.execute('INSERT INTO messages(id,chat_id,sender_id,idem_key,body,doc) VALUES(%s,%s,%s,%s,%s,%s)',(doc['id'],current['id'],actor['id'],key,Jsonb(normalized),Jsonb(doc)))
|
||||||
|
return JSONResponse(doc,201)
|
||||||
|
if LAB >= 4 and len(parts) == 3 and parts[2] == 'attachments' and method == 'POST':
|
||||||
|
filename = request.query_params.get('filename','')
|
||||||
|
if not 1 <= len(filename) <= 255 or any(c in '/\\' or ord(c)<32 or 127<=ord(c)<=159 for c in filename):
|
||||||
|
fail(400)
|
||||||
|
mime = request.headers.get('content-type','')
|
||||||
|
if mime not in ('image/png','image/jpeg'):
|
||||||
|
fail(415)
|
||||||
|
try:
|
||||||
|
with Image.open(io.BytesIO(raw)) as image:
|
||||||
|
if image.width*image.height > 40_000_000:
|
||||||
|
fail(413)
|
||||||
|
if image.format not in ('PNG','JPEG') or Image.MIME[image.format] != mime:
|
||||||
|
fail(415)
|
||||||
|
image.verify()
|
||||||
|
with Image.open(io.BytesIO(raw)) as image:
|
||||||
|
image.load()
|
||||||
|
except APIError:
|
||||||
|
raise
|
||||||
|
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||||
|
fail(413)
|
||||||
|
except Exception:
|
||||||
|
fail(415)
|
||||||
|
ident, job_id, stamp = str(uuid.uuid4()), str(uuid.uuid4()), now()
|
||||||
|
doc = {'id':ident,'chat_id':current['id'],'owner_id':actor['id'],'filename':filename,
|
||||||
|
'content_type':mime,'size_bytes':len(raw),'sha256':hashlib.sha256(raw).hexdigest(),
|
||||||
|
'status':'queued','variants':[],'error_code':None,'created_at':stamp,'updated_at':stamp}
|
||||||
|
stage_key = 'staging/'+ident
|
||||||
|
try:
|
||||||
|
s3().put_object(Bucket=STAGING_BUCKET,Key=stage_key,Body=raw,ContentType=mime)
|
||||||
|
except Exception:
|
||||||
|
fail(503)
|
||||||
|
trace_context = {}
|
||||||
|
propagate.inject(trace_context)
|
||||||
|
payload = job_payload(job_id,ident,trace_context=trace_context)
|
||||||
|
db.execute('INSERT INTO attachments(id,chat_id,doc,stage_key) VALUES(%s,%s,%s,%s)',
|
||||||
|
(ident,current['id'],Jsonb(doc),stage_key))
|
||||||
|
db.execute('INSERT INTO attachment_jobs(job_id,attachment_id,payload) VALUES(%s,%s,%s)',
|
||||||
|
(job_id,ident,Jsonb(payload)))
|
||||||
|
db.commit()
|
||||||
|
# Publisher confirms durable broker handoff. The PostgreSQL outbox remains
|
||||||
|
# recoverable if the broker is unavailable or the process exits here.
|
||||||
|
try:
|
||||||
|
publish_job(payload)
|
||||||
|
db.execute('UPDATE attachment_jobs SET published_at=now() WHERE job_id=%s AND published_at IS NULL',(job_id,))
|
||||||
|
except Exception as exc:
|
||||||
|
import logging
|
||||||
|
logging.error('Durable job publish failed (%s)',type(exc).__name__)
|
||||||
|
fail(503)
|
||||||
|
return JSONResponse(doc,202)
|
||||||
|
if LAB >= 4 and parts[0] == 'attachments' and len(parts) in (2,3) and method == 'GET':
|
||||||
|
doc = attachment(db,parts[1],actor)
|
||||||
|
if len(parts) == 2:
|
||||||
|
return doc
|
||||||
|
if parts[2] == 'content':
|
||||||
|
if doc['status'] in ('queued','processing','failed'):
|
||||||
|
fail(409)
|
||||||
|
variant = request.query_params.get('variant','original')
|
||||||
|
if variant == 'original':
|
||||||
|
bucket_name,key,content_type = ORIGINAL_BUCKET,'original/'+doc['id'],doc['content_type']
|
||||||
|
else:
|
||||||
|
selected = next((v for v in doc['variants'] if v['name']==variant),None)
|
||||||
|
if not selected:
|
||||||
|
fail(404)
|
||||||
|
bucket_name,key,content_type = VARIANTS_BUCKET,'variants/'+doc['id']+'/'+variant+'.jpg',selected['content_type']
|
||||||
|
try:
|
||||||
|
obj = s3().get_object(Bucket=bucket_name,Key=key)
|
||||||
|
try:
|
||||||
|
content = obj['Body'].read(10*1024*1024+1)
|
||||||
|
finally:
|
||||||
|
obj['Body'].close()
|
||||||
|
except Exception:
|
||||||
|
fail(503)
|
||||||
|
return Response(content,media_type=content_type)
|
||||||
|
fail(404)
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import os
|
||||||
|
import psycopg
|
||||||
|
with psycopg.connect(os.environ['DATABASE_URL']) as db:
|
||||||
|
db.execute(open('migrations/001_init.sql').read())
|
||||||
|
db.execute('REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC')
|
||||||
|
db.execute('GRANT CONNECT ON DATABASE messenger TO messenger_api,messenger_worker')
|
||||||
|
db.execute('GRANT USAGE ON SCHEMA public TO messenger_api,messenger_worker')
|
||||||
|
db.execute('GRANT SELECT,INSERT,UPDATE ON users TO messenger_api')
|
||||||
|
db.execute('GRANT SELECT,INSERT,DELETE ON sessions TO messenger_api')
|
||||||
|
db.execute('GRANT SELECT,INSERT ON chats,messages TO messenger_api')
|
||||||
|
db.execute('GRANT SELECT,INSERT,UPDATE ON attachments,attachment_jobs TO messenger_api')
|
||||||
|
db.execute('GRANT SELECT,INSERT,UPDATE,DELETE ON login_rate_limits TO messenger_api')
|
||||||
|
db.execute('GRANT SELECT,UPDATE ON attachments,attachment_jobs TO messenger_worker')
|
||||||
|
print('Migration complete')
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"""Idempotently create the private attachment buckets with the bootstrap identity."""
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
|
||||||
|
import boto3
|
||||||
|
from botocore.exceptions import ClientError
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
client = boto3.client(
|
||||||
|
's3',
|
||||||
|
endpoint_url=os.environ['S3_ENDPOINT'],
|
||||||
|
aws_access_key_id=os.environ['S3_ADMIN_ACCESS_KEY'],
|
||||||
|
aws_secret_access_key=os.environ['S3_ADMIN_SECRET_KEY'],
|
||||||
|
region_name='us-east-1',
|
||||||
|
verify=os.environ['S3_CA_CERT'],
|
||||||
|
config=boto3.session.Config(s3={'addressing_style': 'path'}, retries={'max_attempts': 2}),
|
||||||
|
)
|
||||||
|
buckets = ('attachments-staging', 'attachments-original', 'attachments-variants')
|
||||||
|
last_error = None
|
||||||
|
for attempt in range(60):
|
||||||
|
try:
|
||||||
|
for bucket in buckets:
|
||||||
|
try:
|
||||||
|
client.head_bucket(Bucket=bucket)
|
||||||
|
except ClientError as exc:
|
||||||
|
if exc.response.get('ResponseMetadata', {}).get('HTTPStatusCode') != 404:
|
||||||
|
raise
|
||||||
|
try:
|
||||||
|
client.create_bucket(Bucket=bucket)
|
||||||
|
except ClientError as exc:
|
||||||
|
if exc.response.get('Error', {}).get('Code') not in ('BucketAlreadyOwnedByYou', 'BucketAlreadyExists'):
|
||||||
|
raise
|
||||||
|
print('PASS: private S3 buckets are provisioned: ' + ', '.join(buckets))
|
||||||
|
return
|
||||||
|
except Exception as exc:
|
||||||
|
last_error = exc
|
||||||
|
time.sleep(min(1 + attempt, 3))
|
||||||
|
raise RuntimeError('S3 bucket provisioning failed') from last_error
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""Fetch only the process-scoped runtime secret from OpenBao AppRole."""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
|
||||||
|
def load_secrets():
|
||||||
|
address=os.getenv('BAO_ADDR')
|
||||||
|
if not address:
|
||||||
|
return
|
||||||
|
ca_file=os.environ['BAO_CA_CERT']
|
||||||
|
role_id=open(os.environ['BAO_ROLE_ID_FILE'],encoding='utf-8').read().strip()
|
||||||
|
secret_id=open(os.environ['BAO_SECRET_ID_FILE'],encoding='utf-8').read().strip()
|
||||||
|
context=ssl.create_default_context(cafile=ca_file)
|
||||||
|
|
||||||
|
def request(path,body=None,token=None):
|
||||||
|
data=None if body is None else json.dumps(body).encode()
|
||||||
|
req=urllib.request.Request(address.rstrip('/')+'/v1/'+path,data=data,method='GET' if data is None else 'POST')
|
||||||
|
req.add_header('Content-Type','application/json')
|
||||||
|
if token:
|
||||||
|
req.add_header('X-Vault-Token',token)
|
||||||
|
with urllib.request.urlopen(req,context=context,timeout=5) as response:
|
||||||
|
return json.load(response)
|
||||||
|
|
||||||
|
try:
|
||||||
|
login=request('auth/approle/login',{'role_id':role_id,'secret_id':secret_id})
|
||||||
|
token=login['auth']['client_token']
|
||||||
|
secret=request('kv/data/'+os.environ['BAO_SECRET_PATH'],token=token)['data']['data']
|
||||||
|
allowed={'DATABASE_URL','S3_ACCESS_KEY','S3_SECRET_KEY','BROKER_URL','LOGIN_RATE_HMAC_KEY'}
|
||||||
|
if set(secret)-allowed or not allowed <= set(secret):
|
||||||
|
raise ValueError('unexpected secret fields')
|
||||||
|
for key,value in secret.items():
|
||||||
|
if not isinstance(value,str) or not value:
|
||||||
|
raise ValueError('invalid secret value')
|
||||||
|
os.environ[key]=value
|
||||||
|
except Exception:
|
||||||
|
raise RuntimeError('OpenBao service secret retrieval failed') from None
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""Uvicorn TLS server that exposes the verified peer certificate to ASGI."""
|
||||||
|
import ssl
|
||||||
|
|
||||||
|
import uvicorn
|
||||||
|
from uvicorn.protocols.http.h11_impl import H11Protocol
|
||||||
|
|
||||||
|
|
||||||
|
class CertificateAwareH11Protocol(H11Protocol):
|
||||||
|
def handle_events(self):
|
||||||
|
previous_cycle=getattr(self,'cycle',None)
|
||||||
|
super().handle_events()
|
||||||
|
cycle=getattr(self,'cycle',None)
|
||||||
|
if cycle is None or cycle is previous_cycle or cycle.scope.get('type')!='http':
|
||||||
|
return
|
||||||
|
ssl_object=self.transport.get_extra_info('ssl_object')
|
||||||
|
cert=ssl_object.getpeercert(binary_form=True) if ssl_object is not None else None
|
||||||
|
cycle.scope.setdefault('extensions',{})['tls']={
|
||||||
|
'client_cert_chain':[ssl.DER_cert_to_PEM_cert(cert)] if cert else []
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
uvicorn.run('app.main:app',host='0.0.0.0',port=8443,http=CertificateAwareH11Protocol,
|
||||||
|
ssl_certfile='/run/certs/api.crt',ssl_keyfile='/run/certs/api.key',
|
||||||
|
ssl_ca_certs='/run/certs/lb-client-ca.crt',ssl_cert_reqs=ssl.CERT_REQUIRED,
|
||||||
|
timeout_graceful_shutdown=5,proxy_headers=False,forwarded_allow_ips='')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"""Bounded-cardinality telemetry setup shared by the API and worker."""
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import sys
|
||||||
|
import atexit
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from opentelemetry import metrics, trace
|
||||||
|
from opentelemetry._logs import set_logger_provider
|
||||||
|
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||||
|
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||||
|
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||||
|
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||||
|
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||||
|
from opentelemetry.sdk.metrics import MeterProvider
|
||||||
|
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||||
|
from opentelemetry.sdk.resources import Resource
|
||||||
|
from opentelemetry.sdk.trace import TracerProvider
|
||||||
|
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||||
|
|
||||||
|
SERVICE = os.getenv('OTEL_SERVICE_NAME', 'messenger-api')
|
||||||
|
ENDPOINT = os.getenv('OTEL_EXPORTER_OTLP_ENDPOINT', 'http://otel-collector:4318').rstrip('/')
|
||||||
|
RESOURCE = Resource.create({
|
||||||
|
'service.name': SERVICE,
|
||||||
|
'service.version': '1.0.0',
|
||||||
|
'service.instance.id': socket.gethostname(),
|
||||||
|
'deployment.environment.name': os.getenv('APP_ENV', 'lab'),
|
||||||
|
})
|
||||||
|
|
||||||
|
trace_provider = TracerProvider(resource=RESOURCE)
|
||||||
|
trace_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=ENDPOINT + '/v1/traces', timeout=3)))
|
||||||
|
trace.set_tracer_provider(trace_provider)
|
||||||
|
|
||||||
|
metric_reader = PeriodicExportingMetricReader(
|
||||||
|
OTLPMetricExporter(endpoint=ENDPOINT + '/v1/metrics', timeout=3),
|
||||||
|
export_interval_millis=5000,
|
||||||
|
)
|
||||||
|
metrics.set_meter_provider(MeterProvider(resource=RESOURCE, metric_readers=[metric_reader]))
|
||||||
|
|
||||||
|
log_provider = LoggerProvider(resource=RESOURCE)
|
||||||
|
log_provider.add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter(endpoint=ENDPOINT + '/v1/logs', timeout=3)))
|
||||||
|
set_logger_provider(log_provider)
|
||||||
|
|
||||||
|
|
||||||
|
class StructuredFormatter(logging.Formatter):
|
||||||
|
"""Write a small allow-listed event record; never serialize request data."""
|
||||||
|
def format(self, record):
|
||||||
|
span_context = trace.get_current_span().get_span_context()
|
||||||
|
trace_id = f'{span_context.trace_id:032x}' if span_context.is_valid else None
|
||||||
|
span_id = f'{span_context.span_id:016x}' if span_context.is_valid else None
|
||||||
|
result = {
|
||||||
|
'timestamp': datetime.fromtimestamp(record.created, timezone.utc).isoformat(),
|
||||||
|
'severity': record.levelname,
|
||||||
|
'service': SERVICE,
|
||||||
|
'event': getattr(record, 'event', record.getMessage()),
|
||||||
|
'trace_id': trace_id,
|
||||||
|
'span_id': span_id,
|
||||||
|
}
|
||||||
|
for key in ('request_id', 'method', 'route', 'status_class', 'job_type', 'outcome', 'attempt', 'error_type'):
|
||||||
|
value = getattr(record, key, None)
|
||||||
|
if value is not None:
|
||||||
|
result[key] = value
|
||||||
|
return json.dumps(result, ensure_ascii=False, separators=(',', ':'))
|
||||||
|
|
||||||
|
|
||||||
|
root = logging.getLogger()
|
||||||
|
root.setLevel(logging.INFO)
|
||||||
|
root.handlers.clear()
|
||||||
|
stdout = logging.StreamHandler(sys.stdout)
|
||||||
|
stdout.setFormatter(StructuredFormatter())
|
||||||
|
root.addHandler(stdout)
|
||||||
|
root.addHandler(LoggingHandler(level=logging.INFO, logger_provider=log_provider))
|
||||||
|
|
||||||
|
tracer = trace.get_tracer('messenger')
|
||||||
|
meter = metrics.get_meter('messenger')
|
||||||
|
HTTP_REQUESTS = meter.create_counter('messenger_http_requests', unit='{request}', description='Completed HTTP requests')
|
||||||
|
HTTP_DURATION = meter.create_histogram('messenger_http_request_duration_seconds', unit='s', description='HTTP request duration')
|
||||||
|
JOBS_PROCESSED = meter.create_counter('messenger_jobs_processed', unit='{job}', description='Completed jobs by outcome')
|
||||||
|
JOB_DURATION = meter.create_histogram('messenger_job_processing_duration_seconds', unit='s', description='Worker processing duration')
|
||||||
|
|
||||||
|
|
||||||
|
def shutdown():
|
||||||
|
"""Flush bounded SDK batches on graceful process shutdown."""
|
||||||
|
log_provider.shutdown()
|
||||||
|
metrics.get_meter_provider().shutdown()
|
||||||
|
trace.get_tracer_provider().shutdown()
|
||||||
|
|
||||||
|
|
||||||
|
atexit.register(shutdown)
|
||||||
+229
@@ -0,0 +1,229 @@
|
|||||||
|
"""Durable RabbitMQ consumer and PostgreSQL outbox publisher."""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
import boto3
|
||||||
|
import pika
|
||||||
|
import psycopg
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
from PIL import Image, ImageOps
|
||||||
|
from jsonschema import Draft202012Validator, FormatChecker
|
||||||
|
from opentelemetry import propagate
|
||||||
|
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||||
|
from app.secrets import load_secrets
|
||||||
|
load_secrets()
|
||||||
|
from app.telemetry import JOB_DURATION, JOBS_PROCESSED, tracer
|
||||||
|
|
||||||
|
DSN = os.environ['DATABASE_URL']
|
||||||
|
BUCKET = os.getenv('S3_STAGING_BUCKET',os.getenv('S3_BUCKET','attachments')+'-staging')
|
||||||
|
STAGING_BUCKET = BUCKET
|
||||||
|
ORIGINAL_BUCKET = os.getenv('S3_ORIGINAL_BUCKET',BUCKET+'-original')
|
||||||
|
VARIANTS_BUCKET = os.getenv('S3_VARIANTS_BUCKET',BUCKET+'-variants')
|
||||||
|
QUEUE = 'attachment.process.v1'
|
||||||
|
MAX_ATTEMPTS = int(os.getenv('JOB_MAX_ATTEMPTS','5'))
|
||||||
|
MAX_BYTES = 10*1024*1024
|
||||||
|
Image.MAX_IMAGE_PIXELS = 40_000_000
|
||||||
|
schemas = json.load(open('contracts/jobs.schema.json'))
|
||||||
|
job_validator = Draft202012Validator(schemas,format_checker=FormatChecker())
|
||||||
|
|
||||||
|
|
||||||
|
def s3():
|
||||||
|
return boto3.client('s3',endpoint_url=os.environ['S3_ENDPOINT'],
|
||||||
|
aws_access_key_id=os.environ['S3_ACCESS_KEY'],aws_secret_access_key=os.environ['S3_SECRET_KEY'],
|
||||||
|
region_name='us-east-1',verify=os.getenv('S3_CA_CERT') or True,
|
||||||
|
config=boto3.session.Config(connect_timeout=2,read_timeout=10,retries={'max_attempts':0},
|
||||||
|
s3={'addressing_style':'path'}))
|
||||||
|
|
||||||
|
|
||||||
|
def broker():
|
||||||
|
params=pika.URLParameters(os.environ['BROKER_URL'])
|
||||||
|
params.heartbeat=30
|
||||||
|
params.blocked_connection_timeout=5
|
||||||
|
tls=ssl.create_default_context(cafile=os.environ['BROKER_CA_CERT'])
|
||||||
|
tls.check_hostname=True
|
||||||
|
params.ssl_options=pika.SSLOptions(tls,server_hostname='broker')
|
||||||
|
return pika.BlockingConnection(params)
|
||||||
|
|
||||||
|
|
||||||
|
def publish(payload):
|
||||||
|
connection=broker()
|
||||||
|
try:
|
||||||
|
channel=connection.channel()
|
||||||
|
channel.queue_declare(queue=QUEUE,durable=True)
|
||||||
|
channel.confirm_delivery()
|
||||||
|
parent=propagate.extract(payload)
|
||||||
|
with tracer.start_as_current_span('rabbitmq.publish',context=parent,kind=SpanKind.PRODUCER,
|
||||||
|
attributes={'messenger.job.type':payload['type']}):
|
||||||
|
headers={}
|
||||||
|
propagate.inject(headers)
|
||||||
|
channel.basic_publish('',QUEUE,json.dumps(payload).encode(),
|
||||||
|
pika.BasicProperties(content_type='application/json',delivery_mode=2,message_id=payload['job_id'],type=payload['type'],headers=headers))
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
|
||||||
|
def dispatch_outbox():
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
with psycopg.connect(DSN,connect_timeout=3) as db:
|
||||||
|
rows=db.execute("SELECT job_id,payload FROM attachment_jobs WHERE published_at IS NULL AND status IN ('queued','processing') ORDER BY created_at LIMIT 20").fetchall()
|
||||||
|
for job_id,payload in rows:
|
||||||
|
try:
|
||||||
|
publish(payload)
|
||||||
|
with psycopg.connect(DSN) as db:
|
||||||
|
db.execute('UPDATE attachment_jobs SET published_at=now() WHERE job_id=%s AND published_at IS NULL',(job_id,))
|
||||||
|
except Exception:
|
||||||
|
logging.warning('Outbox publish is pending for job %s',job_id)
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
logging.exception('Outbox scan failed')
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
|
||||||
|
def make_thumbnail(data):
|
||||||
|
with Image.open(BytesIO(data)) as source:
|
||||||
|
source.load()
|
||||||
|
image=ImageOps.exif_transpose(source)
|
||||||
|
image.thumbnail((256,256),Image.Resampling.LANCZOS)
|
||||||
|
if image.mode in ('RGBA','LA') or (image.mode=='P' and 'transparency' in image.info):
|
||||||
|
rgba=image.convert('RGBA')
|
||||||
|
background=Image.new('RGBA',rgba.size,'white')
|
||||||
|
background.alpha_composite(rgba)
|
||||||
|
image=background.convert('RGB')
|
||||||
|
else:
|
||||||
|
image=image.convert('RGB')
|
||||||
|
output=BytesIO()
|
||||||
|
image.save(output,format='JPEG',quality=85,optimize=True)
|
||||||
|
result=output.getvalue()
|
||||||
|
return result,image.width,image.height
|
||||||
|
|
||||||
|
|
||||||
|
def process(payload):
|
||||||
|
errors=list(job_validator.iter_errors(payload))
|
||||||
|
if errors:
|
||||||
|
raise ValueError('invalid_job')
|
||||||
|
job_id,ident=payload['job_id'],payload['attachment_id']
|
||||||
|
with psycopg.connect(DSN) as db:
|
||||||
|
row=db.execute('SELECT a.doc,a.stage_key,j.attempt,j.status FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id WHERE j.job_id=%s AND a.id=%s',(job_id,ident)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return 'orphan'
|
||||||
|
doc,stage_key,attempt,status=row
|
||||||
|
if doc['status']=='ready' or status=='done':
|
||||||
|
return 'done'
|
||||||
|
if doc['status']=='failed' or status=='failed':
|
||||||
|
return 'failed'
|
||||||
|
if attempt>=MAX_ATTEMPTS:
|
||||||
|
doc.update(status='failed',error_code='retry_exhausted',updated_at=__import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat().replace('+00:00','Z'))
|
||||||
|
db.execute("UPDATE attachments SET doc=%s WHERE id=%s",(Jsonb(doc),ident))
|
||||||
|
db.execute("UPDATE attachment_jobs SET status='failed',last_error='retry_exhausted' WHERE job_id=%s",(job_id,))
|
||||||
|
return 'failed'
|
||||||
|
attempt=max(attempt+1,payload['attempt'])
|
||||||
|
db.execute("UPDATE attachment_jobs SET status='processing',attempt=%s,last_error=NULL WHERE job_id=%s",(attempt,job_id))
|
||||||
|
doc.update(status='processing',updated_at=__import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat().replace('+00:00','Z'))
|
||||||
|
db.execute('UPDATE attachments SET doc=%s WHERE id=%s',(Jsonb(doc),ident))
|
||||||
|
db.commit()
|
||||||
|
client=s3()
|
||||||
|
obj=client.get_object(Bucket=STAGING_BUCKET,Key=stage_key)
|
||||||
|
try:
|
||||||
|
data=obj['Body'].read(MAX_BYTES+1)
|
||||||
|
finally:
|
||||||
|
obj['Body'].close()
|
||||||
|
if len(data)>MAX_BYTES or hashlib.sha256(data).hexdigest()!=doc['sha256']:
|
||||||
|
raise ValueError('invalid_image')
|
||||||
|
thumb,width,height=make_thumbnail(data)
|
||||||
|
client.put_object(Bucket=ORIGINAL_BUCKET,Key='original/'+ident,Body=data,ContentType=doc['content_type'])
|
||||||
|
client.put_object(Bucket=VARIANTS_BUCKET,Key='variants/'+ident+'/thumbnail.jpg',Body=thumb,ContentType='image/jpeg')
|
||||||
|
stamp=__import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat().replace('+00:00','Z')
|
||||||
|
variant={'name':'thumbnail','content_type':'image/jpeg','size_bytes':len(thumb),'width':width,'height':height,'sha256':hashlib.sha256(thumb).hexdigest()}
|
||||||
|
doc.update(status='ready',variants=[variant],error_code=None,updated_at=stamp)
|
||||||
|
# S3 writes are deterministic and idempotent; PostgreSQL publishes ready only
|
||||||
|
# after both objects exist. A redelivery safely overwrites those same keys.
|
||||||
|
with psycopg.connect(DSN) as db:
|
||||||
|
db.execute("UPDATE attachments SET doc=%s WHERE id=%s AND doc->>'status'!='ready'",(Jsonb(doc),ident))
|
||||||
|
db.execute("UPDATE attachment_jobs SET status='done',last_error=NULL WHERE job_id=%s",(job_id,))
|
||||||
|
try:
|
||||||
|
client.delete_object(Bucket=STAGING_BUCKET,Key=stage_key)
|
||||||
|
except Exception:
|
||||||
|
logging.warning('Finished attachment retained staging object %s',ident)
|
||||||
|
return 'done'
|
||||||
|
|
||||||
|
|
||||||
|
def callback(channel,method,properties,body):
|
||||||
|
started=time.perf_counter()
|
||||||
|
payload={}
|
||||||
|
outcome='failed'
|
||||||
|
try:
|
||||||
|
payload=json.loads(body)
|
||||||
|
parent=propagate.extract(properties.headers or {})
|
||||||
|
with tracer.start_as_current_span('attachment.process',context=parent,kind=SpanKind.CONSUMER,
|
||||||
|
attributes={'messenger.job.type':payload.get('type','unknown'),'messenger.job.attempt':int(payload.get('attempt',0))}) as span:
|
||||||
|
result=process(payload)
|
||||||
|
channel.basic_ack(method.delivery_tag)
|
||||||
|
outcome='success' if result=='done' else result
|
||||||
|
logging.info('worker.job.completed',extra={'event':'worker.job.completed','job_type':'attachment.process.v1','outcome':outcome,'attempt':int(payload.get('attempt',0))})
|
||||||
|
span.set_attribute('messenger.job.outcome',outcome)
|
||||||
|
except ValueError as exc:
|
||||||
|
try:
|
||||||
|
payload=json.loads(body)
|
||||||
|
job_id,ident=payload.get('job_id'),payload.get('attachment_id')
|
||||||
|
with psycopg.connect(DSN) as db:
|
||||||
|
row=db.execute('SELECT doc,attempt FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id WHERE j.job_id=%s',(job_id,)).fetchone()
|
||||||
|
if row:
|
||||||
|
doc,attempt=row
|
||||||
|
stamp=__import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat().replace('+00:00','Z')
|
||||||
|
if attempt>=MAX_ATTEMPTS:
|
||||||
|
doc.update(status='failed',error_code='invalid_image' if str(exc)=='invalid_image' else 'retry_exhausted',updated_at=stamp)
|
||||||
|
db.execute('UPDATE attachments SET doc=%s WHERE id=%s',(Jsonb(doc),ident))
|
||||||
|
db.execute("UPDATE attachment_jobs SET status='failed',last_error=%s WHERE job_id=%s",(str(exc)[:80],job_id))
|
||||||
|
channel.basic_ack(method.delivery_tag)
|
||||||
|
outcome='failed'
|
||||||
|
else:
|
||||||
|
doc.update(status='queued',error_code=None,updated_at=stamp)
|
||||||
|
db.execute('UPDATE attachments SET doc=%s WHERE id=%s',(Jsonb(doc),ident))
|
||||||
|
db.execute("UPDATE attachment_jobs SET status='queued',last_error=%s WHERE job_id=%s",(str(exc)[:80],job_id))
|
||||||
|
time.sleep(min(2**max(attempt-1,0),8))
|
||||||
|
channel.basic_nack(method.delivery_tag,requeue=True)
|
||||||
|
outcome='retry'
|
||||||
|
else:
|
||||||
|
channel.basic_ack(method.delivery_tag)
|
||||||
|
except Exception:
|
||||||
|
logging.error('worker.job.record_failure_failed')
|
||||||
|
channel.basic_nack(method.delivery_tag,requeue=True)
|
||||||
|
except Exception:
|
||||||
|
logging.error('worker.job.transient_failure')
|
||||||
|
try:
|
||||||
|
channel.basic_nack(method.delivery_tag,requeue=True)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
elapsed=time.perf_counter()-started
|
||||||
|
attrs={'job_type':'attachment.process.v1','outcome':outcome}
|
||||||
|
JOBS_PROCESSED.add(1,attrs)
|
||||||
|
JOB_DURATION.record(elapsed,attrs)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
threading.Thread(target=dispatch_outbox,daemon=True,name='outbox-publisher').start()
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
connection=broker()
|
||||||
|
channel=connection.channel()
|
||||||
|
channel.queue_declare(queue=QUEUE,durable=True)
|
||||||
|
channel.basic_qos(prefetch_count=1)
|
||||||
|
channel.basic_consume(queue=QUEUE,on_message_callback=callback,auto_ack=False)
|
||||||
|
logging.info('Worker consuming durable queue %s',QUEUE)
|
||||||
|
channel.start_consuming()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
logging.error('worker.broker.unavailable')
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
if __name__=='__main__':
|
||||||
|
main()
|
||||||
+519
@@ -0,0 +1,519 @@
|
|||||||
|
name: messenger-lab7
|
||||||
|
x-runtime: &runtime
|
||||||
|
LAB_NUMBER: "7"
|
||||||
|
BAO_ADDR: https://openbao:8200
|
||||||
|
BAO_CA_CERT: /run/certs/service-ca.crt
|
||||||
|
BAO_SECRET_PATH: messenger/api
|
||||||
|
S3_BUCKET: attachments
|
||||||
|
S3_STAGING_BUCKET: attachments-staging
|
||||||
|
S3_ORIGINAL_BUCKET: attachments-original
|
||||||
|
S3_VARIANTS_BUCKET: attachments-variants
|
||||||
|
S3_ENDPOINT: https://s3:8333
|
||||||
|
S3_CA_CERT: /run/certs/service-ca.crt
|
||||||
|
BROKER_CA_CERT: /run/certs/service-ca.crt
|
||||||
|
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||||
|
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||||
|
OTEL_SERVICE_NAME: messenger-api
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
||||||
|
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||||
|
OTEL_EXPORTER_OTLP_CERTIFICATE: /run/certs/service-ca.crt
|
||||||
|
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/certs/otel-api-client.crt
|
||||||
|
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/certs/otel-api-client.key
|
||||||
|
OTEL_EXPORTER_OTLP_INSECURE: "false"
|
||||||
|
OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=lab,service.version=1.0.0
|
||||||
|
APP_ENV: lab
|
||||||
|
PYTHONDONTWRITEBYTECODE: "1"
|
||||||
|
x-api: &api
|
||||||
|
build: .
|
||||||
|
user: "10001:10001"
|
||||||
|
environment: *runtime
|
||||||
|
command: ["python", "-m", "app.server"]
|
||||||
|
volumes: &api-volumes
|
||||||
|
- ./.local/approles/api-role-id:/run/approle/role-id:ro
|
||||||
|
- ./.local/approles/api-secret-id:/run/approle/secret-id:ro
|
||||||
|
- ./.local/pki/service-ca.crt:/run/certs/service-ca.crt:ro
|
||||||
|
- ./.local/pki/api.crt:/run/certs/api.crt:ro
|
||||||
|
- ./.local/pki/api.key:/run/certs/api.key:ro
|
||||||
|
- ./.local/pki/lb-client-ca.crt:/run/certs/lb-client-ca.crt:ro
|
||||||
|
- ./.local/pki/otel-api-client.crt:/run/certs/otel-api-client.crt:ro
|
||||||
|
- ./.local/pki/otel-api-client.key:/run/certs/otel-api-client.key:ro
|
||||||
|
networks: [app, db, s3, broker, bao, otel-ingest]
|
||||||
|
depends_on:
|
||||||
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
s3-init:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
openbao:
|
||||||
|
condition: service_started
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "python", "-c", "import socket; s=socket.create_connection(('127.0.0.1',8443),2); s.close()"]
|
||||||
|
interval: 3s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 10
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=64m"]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
stop_grace_period: 10s
|
||||||
|
mem_limit: 512m
|
||||||
|
cpus: 1.0
|
||||||
|
services:
|
||||||
|
bao-data-init:
|
||||||
|
image: alpine:3.21.3
|
||||||
|
user: "0:0"
|
||||||
|
entrypoint: ["/bin/sh", "-c"]
|
||||||
|
command: ["chown 100:1000 /data && chmod 700 /data"]
|
||||||
|
volumes:
|
||||||
|
- openbao_data:/data
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=8m"]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
cap_add: [CHOWN, FOWNER]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
mem_limit: 64m
|
||||||
|
cpus: 0.1
|
||||||
|
|
||||||
|
postgres-cert-init:
|
||||||
|
image: alpine:3.21.3
|
||||||
|
user: "0:0"
|
||||||
|
entrypoint: ["/bin/sh", "-c"]
|
||||||
|
command: ["cp /source/postgres.crt /tls/server.crt && cp /source/postgres.key /tls/server.key && chown 70:70 /tls/server.key /tls/server.crt && chmod 600 /tls/server.key && chmod 644 /tls/server.crt"]
|
||||||
|
volumes:
|
||||||
|
- ./.local/pki/postgres.crt:/source/postgres.crt:ro
|
||||||
|
- ./.local/pki/postgres.key:/source/postgres.key:ro
|
||||||
|
- postgres_tls:/tls
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=8m"]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
cap_add: [CHOWN, FOWNER]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
mem_limit: 64m
|
||||||
|
cpus: 0.1
|
||||||
|
|
||||||
|
postgres:
|
||||||
|
image: postgres:16.8-alpine
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: messenger
|
||||||
|
POSTGRES_USER: postgres
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_ADMIN_PASSWORD:?run scripts/bootstrap.py first}
|
||||||
|
POSTGRES_API_PASSWORD: ${POSTGRES_API_PASSWORD}
|
||||||
|
POSTGRES_WORKER_PASSWORD: ${POSTGRES_WORKER_PASSWORD}
|
||||||
|
command: ["postgres", "-c", "ssl=on", "-c", "ssl_min_protocol_version=TLSv1.2", "-c", "ssl_cert_file=/run/certs/server.crt", "-c", "ssl_key_file=/run/certs/server.key", "-c", "hba_file=/etc/postgresql/pg_hba.conf"]
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
- ./infra/postgres/init-users.sh:/docker-entrypoint-initdb.d/10-create-app-roles.sh:ro
|
||||||
|
- ./infra/postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf:ro
|
||||||
|
- postgres_tls:/run/certs:ro
|
||||||
|
networks: [db]
|
||||||
|
depends_on:
|
||||||
|
postgres-cert-init:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U postgres -d messenger"]
|
||||||
|
interval: 3s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 30
|
||||||
|
cap_drop: [ALL]
|
||||||
|
cap_add: [CHOWN, DAC_OVERRIDE, FOWNER, SETGID, SETUID]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
|
||||||
|
migrate:
|
||||||
|
build: .
|
||||||
|
user: "10001:10001"
|
||||||
|
command: ["python", "-m", "app.migrate"]
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: "postgresql://postgres:${POSTGRES_ADMIN_PASSWORD}@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/certs/service-ca.crt"
|
||||||
|
POSTGRES_API_PASSWORD: ${POSTGRES_API_PASSWORD}
|
||||||
|
POSTGRES_WORKER_PASSWORD: ${POSTGRES_WORKER_PASSWORD}
|
||||||
|
PYTHONDONTWRITEBYTECODE: "1"
|
||||||
|
volumes:
|
||||||
|
- ./.local/pki/service-ca.crt:/run/certs/service-ca.crt:ro
|
||||||
|
networks: [db]
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=32m"]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
mem_limit: 256m
|
||||||
|
cpus: 0.5
|
||||||
|
|
||||||
|
api1:
|
||||||
|
<<: *api
|
||||||
|
environment:
|
||||||
|
<<: *runtime
|
||||||
|
APP_INSTANCE_ID: api1
|
||||||
|
APP_ROLE: api
|
||||||
|
BAO_ROLE_ID_FILE: /run/approle/role-id
|
||||||
|
BAO_SECRET_ID_FILE: /run/approle/secret-id
|
||||||
|
volumes: *api-volumes
|
||||||
|
api2:
|
||||||
|
<<: *api
|
||||||
|
environment:
|
||||||
|
<<: *runtime
|
||||||
|
APP_INSTANCE_ID: api2
|
||||||
|
APP_ROLE: api
|
||||||
|
BAO_ROLE_ID_FILE: /run/approle/role-id
|
||||||
|
BAO_SECRET_ID_FILE: /run/approle/secret-id
|
||||||
|
volumes: *api-volumes
|
||||||
|
|
||||||
|
lb:
|
||||||
|
image: haproxy:3.0.10-alpine
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${PUBLIC_PORT:-8443}:8443"
|
||||||
|
volumes:
|
||||||
|
- ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||||
|
- ./.local/pki/ingress.pem:/run/certs/ingress.pem:ro
|
||||||
|
- ./.local/pki/lb-client.pem:/run/certs/lb-client.pem:ro
|
||||||
|
- ./.local/pki/service-ca.crt:/run/certs/service-ca.crt:ro
|
||||||
|
networks: [edge, app]
|
||||||
|
depends_on:
|
||||||
|
api1:
|
||||||
|
condition: service_healthy
|
||||||
|
api2:
|
||||||
|
condition: service_healthy
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=16m", "/var/lib/haproxy:rw,noexec,nosuid,size=16m"]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
mem_limit: 128m
|
||||||
|
cpus: 0.5
|
||||||
|
|
||||||
|
master:
|
||||||
|
image: chrislusf/seaweedfs:3.85
|
||||||
|
command: ["master", "-ip=master", "-ip.bind=0.0.0.0", "-port=9333"]
|
||||||
|
volumes:
|
||||||
|
- seaweed_master:/data
|
||||||
|
networks: [seaweed]
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=32m"]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
mem_limit: 384m
|
||||||
|
cpus: 0.5
|
||||||
|
|
||||||
|
volume:
|
||||||
|
image: chrislusf/seaweedfs:3.85
|
||||||
|
command: ["volume", "-ip=volume", "-ip.bind=0.0.0.0", "-mserver=master:9333", "-port=8080"]
|
||||||
|
volumes:
|
||||||
|
- seaweed_volume:/data
|
||||||
|
networks: [seaweed]
|
||||||
|
depends_on: [master]
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=32m"]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
|
||||||
|
filer:
|
||||||
|
image: chrislusf/seaweedfs:3.85
|
||||||
|
command: ["filer", "-ip=filer", "-ip.bind=0.0.0.0", "-master=master:9333", "-defaultStoreDir=/data"]
|
||||||
|
volumes:
|
||||||
|
- seaweed_filer:/data
|
||||||
|
networks: [seaweed]
|
||||||
|
depends_on: [master, volume]
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=32m"]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
mem_limit: 384m
|
||||||
|
cpus: 0.5
|
||||||
|
|
||||||
|
s3:
|
||||||
|
image: chrislusf/seaweedfs:3.85
|
||||||
|
command: ["s3", "-filer=filer:8888", "-ip.bind=0.0.0.0", "-port=0", "-port.https=8333", "-config=/etc/seaweedfs/s3.json"]
|
||||||
|
environment:
|
||||||
|
S3_CERT_FILE: /run/certs/s3.crt
|
||||||
|
S3_KEY_FILE: /run/certs/s3.key
|
||||||
|
volumes:
|
||||||
|
- ./.local/s3.json:/etc/seaweedfs/s3.json:ro
|
||||||
|
- ./.local/pki/s3.crt:/run/certs/s3.crt:ro
|
||||||
|
- ./.local/pki/s3.key:/run/certs/s3.key:ro
|
||||||
|
networks: [seaweed, s3]
|
||||||
|
depends_on: [filer]
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=32m"]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
mem_limit: 384m
|
||||||
|
cpus: 0.5
|
||||||
|
|
||||||
|
s3-init:
|
||||||
|
build: .
|
||||||
|
user: "10001:10001"
|
||||||
|
command: ["python", "-m", "app.s3_init"]
|
||||||
|
environment:
|
||||||
|
S3_ENDPOINT: https://s3:8333
|
||||||
|
S3_CA_CERT: /run/certs/service-ca.crt
|
||||||
|
S3_ADMIN_ACCESS_KEY: ${S3_ADMIN_ACCESS_KEY}
|
||||||
|
S3_ADMIN_SECRET_KEY: ${S3_ADMIN_SECRET_KEY}
|
||||||
|
volumes:
|
||||||
|
- ./.local/pki/service-ca.crt:/run/certs/service-ca.crt:ro
|
||||||
|
networks: [s3]
|
||||||
|
depends_on: [s3]
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=16m"]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
mem_limit: 128m
|
||||||
|
cpus: 0.25
|
||||||
|
|
||||||
|
broker:
|
||||||
|
image: rabbitmq:3.13.7-alpine
|
||||||
|
environment:
|
||||||
|
RABBITMQ_DEFAULT_USER: ${RABBIT_ADMIN_USER}
|
||||||
|
RABBITMQ_DEFAULT_PASS: ${RABBIT_ADMIN_PASSWORD}
|
||||||
|
RABBITMQ_DEFAULT_VHOST: /lab7
|
||||||
|
volumes:
|
||||||
|
- rabbitmq_data:/var/lib/rabbitmq
|
||||||
|
- ./infra/rabbitmq/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro
|
||||||
|
- ./.local/pki/service-ca.crt:/run/certs/service-ca.crt:ro
|
||||||
|
- ./.local/pki/broker.crt:/run/certs/broker.crt:ro
|
||||||
|
- ./.local/pki/broker.key:/run/certs/broker.key:ro
|
||||||
|
networks: [broker]
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "su-exec", "rabbitmq", "rabbitmq-diagnostics", "-q", "ping"]
|
||||||
|
interval: 3s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 30
|
||||||
|
stop_grace_period: 20s
|
||||||
|
mem_limit: 512m
|
||||||
|
cpus: 0.75
|
||||||
|
cap_drop: [ALL]
|
||||||
|
cap_add: [SETGID, SETUID]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
|
||||||
|
worker:
|
||||||
|
build: .
|
||||||
|
user: "10001:10001"
|
||||||
|
command: ["python", "-m", "app.worker"]
|
||||||
|
environment:
|
||||||
|
<<: *runtime
|
||||||
|
OTEL_SERVICE_NAME: messenger-worker
|
||||||
|
APP_ROLE: worker
|
||||||
|
BAO_ROLE_ID_FILE: /run/approle/role-id
|
||||||
|
BAO_SECRET_ID_FILE: /run/approle/secret-id
|
||||||
|
BAO_SECRET_PATH: messenger/worker
|
||||||
|
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/certs/otel-worker-client.crt
|
||||||
|
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/certs/otel-worker-client.key
|
||||||
|
volumes:
|
||||||
|
- ./.local/approles/worker-role-id:/run/approle/role-id:ro
|
||||||
|
- ./.local/approles/worker-secret-id:/run/approle/secret-id:ro
|
||||||
|
- ./.local/pki/service-ca.crt:/run/certs/service-ca.crt:ro
|
||||||
|
- ./.local/pki/otel-worker-client.crt:/run/certs/otel-worker-client.crt:ro
|
||||||
|
- ./.local/pki/otel-worker-client.key:/run/certs/otel-worker-client.key:ro
|
||||||
|
networks: [db, s3, broker, bao, otel-ingest]
|
||||||
|
depends_on:
|
||||||
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
s3-init:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
broker:
|
||||||
|
condition: service_healthy
|
||||||
|
openbao:
|
||||||
|
condition: service_started
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=64m"]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
stop_grace_period: 30s
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
|
||||||
|
openbao:
|
||||||
|
image: quay.io/openbao/openbao:2.2.0
|
||||||
|
command: ["server", "-config=/etc/openbao/config.hcl"]
|
||||||
|
depends_on:
|
||||||
|
bao-data-init:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:8207:8200"
|
||||||
|
volumes:
|
||||||
|
- openbao_data:/openbao/data
|
||||||
|
- ./infra/openbao/config.hcl:/etc/openbao/config.hcl:ro
|
||||||
|
- ./.local/pki/service-ca.crt:/run/certs/service-ca.crt:ro
|
||||||
|
- ./.local/pki/openbao.crt:/run/certs/openbao.crt:ro
|
||||||
|
- ./.local/pki/openbao.key:/run/certs/openbao.key:ro
|
||||||
|
networks: [bao, bao-admin]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
cap_add: [SETGID, SETUID]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
mem_limit: 384m
|
||||||
|
cpus: 0.5
|
||||||
|
|
||||||
|
otel-collector:
|
||||||
|
image: otel/opentelemetry-collector-contrib:0.120.0
|
||||||
|
command: ["--config=/etc/otelcol-contrib/config.yaml"]
|
||||||
|
volumes:
|
||||||
|
- ./infra/otel/collector.yaml:/etc/otelcol-contrib/config.yaml:ro
|
||||||
|
- ./.local/pki/service-ca.crt:/run/certs/service-ca.crt:ro
|
||||||
|
- ./.local/pki/otel-collector.crt:/run/certs/otel-collector.crt:ro
|
||||||
|
- ./.local/pki/otel-collector.key:/run/certs/otel-collector.key:ro
|
||||||
|
- ./.local/pki/otel-ingest-ca.crt:/run/certs/otel-ingest-ca.crt:ro
|
||||||
|
- ./.local/pki/backend-collector.crt:/run/certs/backend-collector.crt:ro
|
||||||
|
- ./.local/pki/backend-collector.key:/run/certs/backend-collector.key:ro
|
||||||
|
networks: [otel-ingest, telemetry]
|
||||||
|
depends_on: [prometheus, loki, tempo]
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=32m"]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
mem_limit: 384m
|
||||||
|
cpus: 0.5
|
||||||
|
|
||||||
|
prometheus:
|
||||||
|
image: prom/prometheus:v3.2.1
|
||||||
|
command: ["--config.file=/etc/prometheus/prometheus.yml", "--web.config.file=/etc/prometheus/web.yml", "--storage.tsdb.path=/prometheus", "--storage.tsdb.retention.time=7d", "--web.enable-otlp-receiver"]
|
||||||
|
volumes:
|
||||||
|
- ./infra/observability/prometheus.yml:/etc/prometheus/prometheus.yml:ro
|
||||||
|
- ./infra/observability/prometheus-web.yml:/etc/prometheus/web.yml:ro
|
||||||
|
- ./.local/pki/prometheus.crt:/run/certs/prometheus.crt:ro
|
||||||
|
- ./.local/pki/prometheus.key:/run/certs/prometheus.key:ro
|
||||||
|
- ./.local/pki/backend-client-ca.crt:/run/certs/backend-client-ca.crt:ro
|
||||||
|
- prometheus_data:/prometheus
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:9097:9090"
|
||||||
|
networks: [telemetry, telemetry-admin]
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=64m"]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
mem_limit: 512m
|
||||||
|
cpus: 0.75
|
||||||
|
|
||||||
|
loki:
|
||||||
|
image: grafana/loki:3.4.2
|
||||||
|
command: ["-config.file=/etc/loki/local-config.yaml"]
|
||||||
|
volumes:
|
||||||
|
- ./infra/observability/loki.yaml:/etc/loki/local-config.yaml:ro
|
||||||
|
- ./.local/pki/loki.crt:/run/certs/loki.crt:ro
|
||||||
|
- ./.local/pki/loki.key:/run/certs/loki.key:ro
|
||||||
|
- ./.local/pki/backend-client-ca.crt:/run/certs/backend-client-ca.crt:ro
|
||||||
|
- loki_data:/loki
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:3107:3100"
|
||||||
|
networks: [telemetry, telemetry-admin]
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=64m"]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
mem_limit: 512m
|
||||||
|
cpus: 0.75
|
||||||
|
|
||||||
|
tempo:
|
||||||
|
image: grafana/tempo:2.7.1
|
||||||
|
command: ["-config.file=/etc/tempo.yaml"]
|
||||||
|
volumes:
|
||||||
|
- ./infra/observability/tempo.yaml:/etc/tempo.yaml:ro
|
||||||
|
- ./.local/pki/tempo.crt:/run/certs/tempo.crt:ro
|
||||||
|
- ./.local/pki/tempo.key:/run/certs/tempo.key:ro
|
||||||
|
- ./.local/pki/service-ca.crt:/run/certs/service-ca.crt:ro
|
||||||
|
- ./.local/pki/backend-client-ca.crt:/run/certs/backend-client-ca.crt:ro
|
||||||
|
- tempo_data:/var/tempo
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:3207:3200"
|
||||||
|
networks: [telemetry, telemetry-admin]
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=64m"]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
mem_limit: 512m
|
||||||
|
cpus: 0.75
|
||||||
|
|
||||||
|
grafana:
|
||||||
|
image: grafana/grafana:11.5.2
|
||||||
|
environment:
|
||||||
|
GF_SECURITY_ADMIN_USER: admin
|
||||||
|
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_PASSWORD}
|
||||||
|
GF_USERS_ALLOW_SIGN_UP: "false"
|
||||||
|
GF_SERVER_CERT_FILE: /run/certs/grafana.crt
|
||||||
|
GF_SERVER_CERT_KEY: /run/certs/grafana.key
|
||||||
|
GF_SERVER_PROTOCOL: https
|
||||||
|
GF_SERVER_MIN_TLS_VERSION: TLS1.2
|
||||||
|
GF_SECURITY_COOKIE_SECURE: "true"
|
||||||
|
GF_SECURITY_COOKIE_SAMESITE: strict
|
||||||
|
GF_ANALYTICS_REPORTING_ENABLED: "false"
|
||||||
|
GF_ANALYTICS_CHECK_FOR_UPDATES: "false"
|
||||||
|
volumes:
|
||||||
|
- grafana_data:/var/lib/grafana
|
||||||
|
- ./infra/observability/grafana/grafana.ini:/etc/grafana/grafana.ini:ro
|
||||||
|
- ./infra/observability/grafana/provisioning/dashboards:/etc/grafana/provisioning/dashboards:ro
|
||||||
|
- ./.local/grafana/provisioning:/etc/grafana/provisioning/datasources:ro
|
||||||
|
- ./infra/observability/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||||
|
- ./.local/pki/grafana.crt:/run/certs/grafana.crt:ro
|
||||||
|
- ./.local/pki/grafana.key:/run/certs/grafana.key:ro
|
||||||
|
- ./.local/pki/service-ca.crt:/run/certs/service-ca.crt:ro
|
||||||
|
- ./.local/pki/backend-grafana.crt:/run/certs/backend-grafana.crt:ro
|
||||||
|
- ./.local/pki/backend-grafana.key:/run/certs/backend-grafana.key:ro
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:3007:3000"
|
||||||
|
networks: [telemetry, telemetry-admin]
|
||||||
|
depends_on: [prometheus, loki, tempo]
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=64m"]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
mem_limit: 512m
|
||||||
|
cpus: 0.75
|
||||||
|
|
||||||
|
tls-probe:
|
||||||
|
profiles: [security-test]
|
||||||
|
build: .
|
||||||
|
user: "10001:10001"
|
||||||
|
entrypoint: ["python", "tests/tls_probe.py"]
|
||||||
|
networks: [app]
|
||||||
|
volumes:
|
||||||
|
- ./.local/pki/service-ca.crt:/run/certs/service-ca.crt:ro
|
||||||
|
- ./.local/pki/foreign-client.crt:/run/certs/foreign-client.crt:ro
|
||||||
|
- ./.local/pki/foreign-client.key:/run/certs/foreign-client.key:ro
|
||||||
|
- ./.local/pki/untrusted-client.crt:/run/certs/untrusted-client.crt:ro
|
||||||
|
- ./.local/pki/untrusted-client.key:/run/certs/untrusted-client.key:ro
|
||||||
|
- ./.local/pki/lb-client.crt:/run/certs/lb-client.crt:ro
|
||||||
|
- ./.local/pki/lb-client.key:/run/certs/lb-client.key:ro
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=16m"]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
mem_limit: 128m
|
||||||
|
cpus: 0.25
|
||||||
|
|
||||||
|
networks:
|
||||||
|
edge:
|
||||||
|
app:
|
||||||
|
internal: true
|
||||||
|
db:
|
||||||
|
internal: true
|
||||||
|
s3:
|
||||||
|
internal: true
|
||||||
|
seaweed:
|
||||||
|
internal: true
|
||||||
|
broker:
|
||||||
|
internal: true
|
||||||
|
bao:
|
||||||
|
internal: true
|
||||||
|
bao-admin: {}
|
||||||
|
otel-ingest:
|
||||||
|
internal: true
|
||||||
|
telemetry:
|
||||||
|
internal: true
|
||||||
|
telemetry-admin: {}
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
|
postgres_tls:
|
||||||
|
seaweed_master:
|
||||||
|
seaweed_volume:
|
||||||
|
seaweed_filer:
|
||||||
|
rabbitmq_data:
|
||||||
|
openbao_data:
|
||||||
|
prometheus_data:
|
||||||
|
loki_data:
|
||||||
|
tempo_data:
|
||||||
|
grafana_data:
|
||||||
+33
-28
@@ -1,37 +1,42 @@
|
|||||||
# Матрица доверия — заполнить в решении lab7
|
# Матрица доверия — lab7
|
||||||
|
|
||||||
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать.
|
Публичные endpoints доступны только на loopback. Внутренние service endpoints доступны только участникам соответствующих Compose networks. Локальные CA/leaf создаёт `scripts/bootstrap.py` в `.local/pki`; сервисные private keys не хранятся в Git или Docker image. Сертификаты сервера проверяются по `service-ca` или `external-ca` и по hostname/SAN. Команды запускаются из корня репозитория, после `python3 scripts/bootstrap.py`.
|
||||||
|
|
||||||
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг |
|
| Связь | Порт / transport | CA, identity и разрешение | Срок / выдача | Положительная и отрицательная проверка |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- |
|
||||||
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO |
|
| Клиент → HAProxy ingress | host `127.0.0.1:8443`, HTTPS TLS 1.2+ | `external-ca`; SAN `localhost` и `127.0.0.1`; дальше Bearer session | leaf 90 дней; session по `SESSION_TTL_SECONDS` (3600 по умолчанию) | `make test CA_FILE=.local/pki/external-ca.crt`; `make test-security` проверяет недоверенный CA; `tests/security_runtime.py` проверяет expiry/logout |
|
||||||
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO |
|
| HAProxy → API 1/2 | Docker `app`, `8443`, HTTPS mTLS | HAProxy проверяет `service-ca` и hostname `api1`/`api2`; API требует `lb-client-ca` и allowlist URI SAN `spiffe://mtusi2026/lab7/load-balancer` | leaf 90 дней; новая пара создаётся bootstrap при отсутствии текущей | `python3 tests/security_runtime.py`: `trusted` → 200; `no-cert`/`untrusted-ca` → отказ handshake; `wrong-identity` (тот же доверенный CA) → 403. Прямых published API портов нет |
|
||||||
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO |
|
| API/worker → PostgreSQL | network `db`, TCP 5432, PostgreSQL TLS | сервер `service-ca`, hostname `postgres`, `sslmode=verify-full`; DB roles `messenger_api` и `messenger_worker` с разными table grants | DB passwords — случайные значения локального `.env`, передаются OpenBao KV; автоматическая ротация не заявлена | `tests/component_security.py` проверяет разрешённые роли и запрет чужих таблиц; общий smoke и persistence в `make verify` |
|
||||||
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO |
|
| API/worker → SeaweedFS S3 | network `s3`, HTTPS 8333 | сервер `service-ca`, hostname `s3`; отдельные AWS-compatible keys; staging/original/variants buckets и prefix ACL | ключи создаются локально и передаются через отдельные OpenBao paths; ротация не заявлена | `tests/component_security.py` проверяет запрещённый bucket/prefix; `tests/security.py` и `scripts/verify.py` проверяют чужой и anonymous доступ |
|
||||||
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO |
|
| API/worker → RabbitMQ | network `broker`, AMQPS 5671 | server `service-ca`, hostname `broker`; API producer и worker consumer — разные Rabbit users в `/lab7`; configure ограничен именем очереди, write — default exchange, read — queue для worker | credentials лежат в раздельных OpenBao secrets; rotation не заявлена | `tests/component_security.py` ожидает 403 при объявлении запрещённой очереди; `tests/worker_flow.py` проверяет доставку и безопасный повтор |
|
||||||
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO |
|
| API/worker → OTel Collector | network `otel-ingest`, OTLP/HTTP 4318 и gRPC 4317, TLS mTLS | Collector проверяет `otel-ingest-ca`; identities с URI SAN `/api` и `/worker`; API/worker проверяют `service-ca` и hostname `otel-collector` | client/server leaves 90 дней; авто-ротация не заявлена | `tests/observability.py` проверяет API/worker метрики, логи и traces через collector; входные порты не published |
|
||||||
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO |
|
| Collector → Prometheus | network `telemetry`, HTTPS 9090 OTLP receiver | `service-ca`; клиент `backend-collector`, разрешён URI SAN `spiffe://mtusi2026/lab7/otel-collector` | client leaf 90 дней | `tests/observability.py` проверяет запросы к Prometheus с валидной identity и наличие API/worker metrics |
|
||||||
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO |
|
| Collector → Loki | network `telemetry`, HTTPS 3100 OTLP | `service-ca`; client certificate `backend-collector` от `backend-client-ca` | client leaf 90 дней | `tests/observability.py` проверяет структурированные API/worker logs через mTLS |
|
||||||
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO |
|
| Collector → Tempo | network `telemetry`, OTLP/gRPC 4317 и HTTPS query 3200 | OTLP gRPC проверяет client `backend-collector`; query endpoint проверяет CA и client cert. Internal Tempo gRPC 9095 не published, остаётся внутри telemetry network | client leaf 90 дней | `tests/observability.py` проверяет API и worker traces, а также совместный trace через `traceparent` |
|
||||||
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO |
|
| Grafana → Prometheus/Loki/Tempo | network `telemetry`, HTTPS 9090/3100/3200 | `service-ca` + hostname; client `backend-grafana`; backend allowlist включает только collector и Grafana identities | client leaf 90 дней; Grafana password локальный из `.env` | `tests/observability.py` проверяет Grafana health, dashboard и запросы к защищённым backends |
|
||||||
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO |
|
| API/worker → OpenBao | network `bao`, HTTPS 8200 | `service-ca`, hostname `openbao`; уникальные API/worker AppRole SecretID, затем краткоживущий token; отдельные read-only KV v2 policies | token TTL 10 минут, max TTL 30 минут; SecretID TTL 720 часов; явная ротация/отзыв не заявлены | `tests/component_security.py` проверяет own-path read, cross-path read deny, write deny; проверить обе роли: `docker compose exec -T api1 python tests/component_security.py`, затем worker |
|
||||||
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO |
|
| Оператор → OpenBao/Grafana | host `127.0.0.1:8207` / `127.0.0.1:3007`, HTTPS | OpenBao TLS CA/SAN; root token и recovery shares только у локального оператора в `.local/openbao/operator.json` (режим каталога 0700, файл 0600); Grafana требует login/password | локальная operator recovery material без автоматического TTL; Grafana пароль в `.env` | bootstrap проверяет OpenBao policies и mTLS services; `curl`/браузер должен использовать локальные CA. Не публиковать operator файл и не вставлять secret в отчёт |
|
||||||
|
| Prometheus → app scrape | N/A | Scrape не используется: API и worker публикуют метрики через OTLP/mTLS, `scrape_configs` пуст | N/A | `tests/observability.py` проверяет фактические метрики в Prometheus OTLP receiver |
|
||||||
|
| API → Redis/Valkey | N/A | Сессии и общий login rate limit хранятся PostgreSQL; Redis не развёрнут | N/A | Не используется |
|
||||||
|
| Репликация DB/broker/S3 | N/A | В учебном Compose каждый сервис односайтовый; нет межузловой репликации | N/A | Устойчивость ограничена сохранностью volumes и проверкой restart; отказ всего Docker host не покрывается |
|
||||||
|
|
||||||
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
|
## Границы и plaintext
|
||||||
|
|
||||||
## Обязательные отрицательные проверки
|
SeaweedFS master/volume/filer служебные порты, OpenBao cluster port 8201 и Tempo внутренний gRPC 9095 не публикуются на host. SeaweedFS узлы используют незашифрованный transport внутри выделенной `seaweed` сети; ни API, ни worker, ни host clients не присоединены к ней. Это локальная доверенная граница compose-сети учебного стенда, не гарантия изоляции production-кластера. DB, S3, RabbitMQ, OpenBao, ingress, OTLP и внешние telemetry HTTP/gRPC interfaces используют TLS.
|
||||||
|
|
||||||
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен».
|
Healthchecks API открывают только TCP socket внутри Compose, не business endpoint; публичный health path всё равно проходит через HTTPS ingress. DB readiness выполняется внутри контейнера через `pg_isready`; bootstrap обращается к OpenBao через локальный TLS listener. Prometheus собирает сигналы через OTLP, а не незащищённый scrape.
|
||||||
2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех.
|
|
||||||
3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity.
|
|
||||||
4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity.
|
|
||||||
5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3.
|
|
||||||
6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить.
|
|
||||||
|
|
||||||
## Bootstrap и эксплуатация
|
## Отрицательные проверки
|
||||||
|
|
||||||
В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу.
|
1. Внешний HTTPS с правильной CA/hostname проходит; чужая CA отвергается `tests/security.py`.
|
||||||
|
2. Для API нет сертификата, сертификат чужого CA или доверенный сертификат с запрещённым URI SAN отвергаются; разрешённый LB identity проходит — `tests/security_runtime.py` и `tests/tls_probe.py`.
|
||||||
|
3. API не читает secret worker, не может записывать в KV; worker не читает secret API — `tests/component_security.py`.
|
||||||
|
4. DB роли и S3 identities не получают чужие table/bucket операции; Rabbit credentials не могут объявлять произвольную очередь — `tests/component_security.py`.
|
||||||
|
5. Пользователь вне чата не читает чат или его вложение; `X-User-Id` не переопределяет Bearer — публичный smoke.
|
||||||
|
6. Anonymous GET существующего объекта приватного bucket получает 401/403; upload при отключённом S3 завершается контролируемым 503 — `scripts/verify.py` и `tests/storage_failure.py`.
|
||||||
|
|
||||||
OpenBao не использует dev-mode. Выберите persistent storage и auth метод (например AppRole с короткоживущим SecretID/response wrapping, cert auth или иная обоснованная identity). Не подменяйте root token постоянной переменной BAO_TOKEN в приложении. Рабочие tokens имеют policy, TTL и renewal/re-auth сценарий. Статические KV secrets на 3 допустимы при реальном чтении через сервисную identity; динамические DB credentials — хорошее расширение, но не обязательное название технологии.
|
## Bootstrap и восстановление
|
||||||
|
|
||||||
Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap.
|
Оператор запускает `python3 scripts/bootstrap.py`. На первом запуске она создаёт CA, сертификаты, `.env`, OpenBao file storage и recovery shares. Recovery JSON остаётся в локальной директории `.local/openbao`, права `0700/0600`, не монтируется в приложения или контейнер OpenBao. Оператор должен защищать диск пользователя и сделать отдельную защищённую резервную копию recovery material; не помещать его в Git или PR. При рестарте OpenBao может потребоваться `python3 scripts/unseal.py`; затем bootstrap повторно устанавливает policies, обновляет AppRole credentials и поднимает стенд.
|
||||||
|
|
||||||
|
Уровень 4 не заявлен: срок действия leaf/SecretID ограничен, но автоматический renew/rotation и тест контролируемого отзыва не реализованы. При утечке API/worker SecretID оператор отзывает соответствующий AppRole SecretID, выпускает новый через bootstrap, затем пересоздаёт только соответствующие API/worker контейнеры. При потере operator recovery material file storage нельзя безопасно unseal; восстановление возможно только из защищённой резервной копии либо с новым пустым стендом.
|
||||||
|
|||||||
@@ -0,0 +1,402 @@
|
|||||||
|
python3 scripts/verify.py
|
||||||
|
Verification UTC: 2026-12-01T19:40:43.378517+00:00
|
||||||
|
|
||||||
|
$ docker compose config --quiet
|
||||||
|
|
||||||
|
$ /Library/Developer/CommandLineTools/usr/bin/python3 scripts/check_contract.py
|
||||||
|
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||||
|
|
||||||
|
$ docker compose ps
|
||||||
|
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||||
|
messenger-lab7-api1-1 messenger-lab7-api1 "python -m app.server" api1 8 minutes ago Up 37 seconds (healthy)
|
||||||
|
messenger-lab7-api2-1 messenger-lab7-api2 "python -m app.server" api2 8 minutes ago Up 26 seconds (healthy)
|
||||||
|
messenger-lab7-broker-1 rabbitmq:3.13.7-alpine "docker-entrypoint.s…" broker 37 minutes ago Up About a minute (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp
|
||||||
|
messenger-lab7-filer-1 chrislusf/seaweedfs:3.85 "/entrypoint.sh file…" filer 40 minutes ago Up 40 minutes 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
|
||||||
|
messenger-lab7-grafana-1 grafana/grafana:11.5.2 "/run.sh" grafana 32 minutes ago Up 22 minutes 127.0.0.1:3007->3000/tcp
|
||||||
|
messenger-lab7-lb-1 haproxy:3.0.10-alpine "docker-entrypoint.s…" lb 32 minutes ago Up About a minute 127.0.0.1:8443->8443/tcp
|
||||||
|
messenger-lab7-loki-1 grafana/loki:3.4.2 "/usr/bin/loki -conf…" loki 32 minutes ago Up 22 minutes 127.0.0.1:3107->3100/tcp
|
||||||
|
messenger-lab7-master-1 chrislusf/seaweedfs:3.85 "/entrypoint.sh mast…" master 40 minutes ago Up 40 minutes 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
|
||||||
|
messenger-lab7-openbao-1 quay.io/openbao/openbao:2.2.0 "docker-entrypoint.s…" openbao 33 minutes ago Up 33 minutes 127.0.0.1:8207->8200/tcp
|
||||||
|
messenger-lab7-otel-collector-1 otel/opentelemetry-collector-contrib:0.120.0 "/otelcol-contrib --…" otel-collector 32 minutes ago Up 21 minutes 4317-4318/tcp, 55678-55679/tcp
|
||||||
|
messenger-lab7-postgres-1 postgres:16.8-alpine "docker-entrypoint.s…" postgres 39 minutes ago Up About a minute (healthy) 5432/tcp
|
||||||
|
messenger-lab7-prometheus-1 prom/prometheus:v3.2.1 "/bin/prometheus --c…" prometheus 32 minutes ago Up 22 minutes 127.0.0.1:9097->9090/tcp
|
||||||
|
messenger-lab7-s3-1 chrislusf/seaweedfs:3.85 "/entrypoint.sh s3 -…" s3 40 minutes ago Up 19 seconds 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
|
||||||
|
messenger-lab7-tempo-1 grafana/tempo:2.7.1 "/tempo -config.file…" tempo 15 minutes ago Up 15 minutes 127.0.0.1:3207->3200/tcp
|
||||||
|
messenger-lab7-volume-1 chrislusf/seaweedfs:3.85 "/entrypoint.sh volu…" volume 40 minutes ago Up 40 minutes 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
|
||||||
|
messenger-lab7-worker-1 messenger-lab7-worker "python -m app.worker" worker 8 minutes ago Up About a minute
|
||||||
|
|
||||||
|
$ /Library/Developer/CommandLineTools/usr/bin/python3 tests/smoke.py --base-url https://localhost:8443 --ca-file /Users/bahram/Desktop/ВП/lab7/.local/pki/external-ca.crt
|
||||||
|
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
|
|
||||||
|
$ /Library/Developer/CommandLineTools/usr/bin/python3 tests/security.py --base-url https://localhost:8443 --ca-file /Users/bahram/Desktop/ВП/lab7/.local/pki/external-ca.crt
|
||||||
|
PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.
|
||||||
|
|
||||||
|
$ /Library/Developer/CommandLineTools/usr/bin/python3 tests/security_runtime.py --base-url https://localhost:8443 --ca-file /Users/bahram/Desktop/ВП/lab7/.local/pki/external-ca.crt
|
||||||
|
PASS: external HTTPS endpoint is trusted
|
||||||
|
Container messenger-lab7-tls-probe-run-23d5e24ebe17 Creating
|
||||||
|
Container messenger-lab7-tls-probe-run-23d5e24ebe17 Created
|
||||||
|
PASS: API returned expected status 200 for the allowlisted LB identity
|
||||||
|
Container messenger-lab7-tls-probe-run-30d15970f1be Creating
|
||||||
|
Container messenger-lab7-tls-probe-run-30d15970f1be Created
|
||||||
|
PASS: API rejected no-cert during TLS handshake
|
||||||
|
Container messenger-lab7-tls-probe-run-b30824c0aec6 Creating
|
||||||
|
Container messenger-lab7-tls-probe-run-b30824c0aec6 Created
|
||||||
|
PASS: API rejected untrusted-ca during TLS handshake
|
||||||
|
Container messenger-lab7-tls-probe-run-87f7cf7776f4 Creating
|
||||||
|
Container messenger-lab7-tls-probe-run-87f7cf7776f4 Created
|
||||||
|
PASS: API rejected a CA-signed certificate with the wrong SAN identity
|
||||||
|
PASS: login limiter returns 429 with Retry-After across shared database
|
||||||
|
PASS: password parameters, hashed session tokens, expiry and logout
|
||||||
|
PASS: AppRole reads its own secret only; cross-read and write denied
|
||||||
|
PASS: PostgreSQL role is limited to its assigned tables and actions
|
||||||
|
PASS: S3 identity cannot use a prefix outside its scoped policy
|
||||||
|
PASS: RabbitMQ identity is restricted to the attachment queue
|
||||||
|
PASS: AppRole reads its own secret only; cross-read and write denied
|
||||||
|
PASS: PostgreSQL role is limited to its assigned tables and actions
|
||||||
|
PASS: S3 identity cannot use a prefix outside its scoped policy
|
||||||
|
PASS: RabbitMQ identity is restricted to the attachment queue
|
||||||
|
PASS: API ports are private; non-root/read-only/cap-drop; no runtime credentials or Docker socket
|
||||||
|
|
||||||
|
$ /Library/Developer/CommandLineTools/usr/bin/python3 tests/acceptance_extra.py --base-url https://localhost:8443 --ca-file /Users/bahram/Desktop/ВП/lab7/.local/pki/external-ca.crt
|
||||||
|
PASS: 16 concurrent retries return one message
|
||||||
|
PASS: real JPEG roundtrip; >40 million pixels rejected; cross-chat attachment rejected
|
||||||
|
PASS: unsafe filename, MIME mismatch, corruption and byte limit
|
||||||
|
|
||||||
|
$ /Library/Developer/CommandLineTools/usr/bin/python3 tests/worker_flow.py --base-url https://localhost:8443 --ca-file /Users/bahram/Desktop/ВП/lab7/.local/pki/external-ca.crt
|
||||||
|
Container messenger-lab7-worker-1 Stopping
|
||||||
|
Container messenger-lab7-worker-1 Stopped
|
||||||
|
Container messenger-lab7-api1-1 Restarting
|
||||||
|
Container messenger-lab7-broker-1 Restarting
|
||||||
|
Container messenger-lab7-api2-1 Restarting
|
||||||
|
Container messenger-lab7-api2-1 Started
|
||||||
|
Container messenger-lab7-api1-1 Started
|
||||||
|
Container messenger-lab7-broker-1 Started
|
||||||
|
Container messenger-lab7-master-1 Running
|
||||||
|
Container messenger-lab7-s3-1 Running
|
||||||
|
Container messenger-lab7-postgres-1 Running
|
||||||
|
Container messenger-lab7-filer-1 Running
|
||||||
|
Container messenger-lab7-broker-1 Running
|
||||||
|
Container messenger-lab7-volume-1 Running
|
||||||
|
Container messenger-lab7-openbao-1 Running
|
||||||
|
Container messenger-lab7-bao-data-init-1 Starting
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Starting
|
||||||
|
Container messenger-lab7-s3-init-1 Starting
|
||||||
|
Container messenger-lab7-bao-data-init-1 Started
|
||||||
|
Container messenger-lab7-bao-data-init-1 Waiting
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Started
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Waiting
|
||||||
|
Container messenger-lab7-s3-init-1 Started
|
||||||
|
Container messenger-lab7-bao-data-init-1 Exited
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Exited
|
||||||
|
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-migrate-1 Waiting
|
||||||
|
Container messenger-lab7-s3-init-1 Waiting
|
||||||
|
Container messenger-lab7-postgres-1 Waiting
|
||||||
|
Container messenger-lab7-broker-1 Waiting
|
||||||
|
Container messenger-lab7-s3-init-1 Exited
|
||||||
|
Container messenger-lab7-postgres-1 Healthy
|
||||||
|
Container messenger-lab7-migrate-1 Exited
|
||||||
|
Container messenger-lab7-broker-1 Healthy
|
||||||
|
Container messenger-lab7-worker-1 Starting
|
||||||
|
Container messenger-lab7-worker-1 Started
|
||||||
|
Container messenger-lab7-postgres-1 Running
|
||||||
|
Container messenger-lab7-openbao-1 Running
|
||||||
|
Container messenger-lab7-volume-1 Running
|
||||||
|
Container messenger-lab7-master-1 Running
|
||||||
|
Container messenger-lab7-broker-1 Running
|
||||||
|
Container messenger-lab7-s3-1 Running
|
||||||
|
Container messenger-lab7-filer-1 Running
|
||||||
|
Container messenger-lab7-worker-1 Running
|
||||||
|
Container messenger-lab7-bao-data-init-1 Starting
|
||||||
|
Container messenger-lab7-s3-init-1 Starting
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Starting
|
||||||
|
Container messenger-lab7-bao-data-init-1 Started
|
||||||
|
Container messenger-lab7-bao-data-init-1 Waiting
|
||||||
|
Container messenger-lab7-s3-init-1 Started
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Started
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Waiting
|
||||||
|
Container messenger-lab7-bao-data-init-1 Exited
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Exited
|
||||||
|
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-postgres-1 Waiting
|
||||||
|
Container messenger-lab7-broker-1 Waiting
|
||||||
|
Container messenger-lab7-migrate-1 Waiting
|
||||||
|
Container messenger-lab7-s3-init-1 Waiting
|
||||||
|
Container messenger-lab7-migrate-1 Exited
|
||||||
|
Container messenger-lab7-s3-init-1 Exited
|
||||||
|
Container messenger-lab7-postgres-1 Healthy
|
||||||
|
Container messenger-lab7-broker-1 Healthy
|
||||||
|
PASS: stopped-worker upload returned 202, survived API/broker restart, and reached ready
|
||||||
|
PASS: original preserved; repeated job delivery produced one identical thumbnail
|
||||||
|
|
||||||
|
$ /Library/Developer/CommandLineTools/usr/bin/python3 tests/retry_limit.py --base-url https://localhost:8443 --ca-file /Users/bahram/Desktop/ВП/lab7/.local/pki/external-ca.crt
|
||||||
|
Container messenger-lab7-worker-1 Stopping
|
||||||
|
Container messenger-lab7-worker-1 Stopped
|
||||||
|
Container messenger-lab7-volume-1 Running
|
||||||
|
Container messenger-lab7-s3-1 Running
|
||||||
|
Container messenger-lab7-broker-1 Running
|
||||||
|
Container messenger-lab7-master-1 Running
|
||||||
|
Container messenger-lab7-postgres-1 Running
|
||||||
|
Container messenger-lab7-filer-1 Running
|
||||||
|
Container messenger-lab7-openbao-1 Running
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Starting
|
||||||
|
Container messenger-lab7-s3-init-1 Starting
|
||||||
|
Container messenger-lab7-bao-data-init-1 Starting
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Started
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Waiting
|
||||||
|
Container messenger-lab7-s3-init-1 Started
|
||||||
|
Container messenger-lab7-bao-data-init-1 Started
|
||||||
|
Container messenger-lab7-bao-data-init-1 Waiting
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Exited
|
||||||
|
Container messenger-lab7-postgres-1 Waiting
|
||||||
|
Container messenger-lab7-bao-data-init-1 Exited
|
||||||
|
Container messenger-lab7-postgres-1 Healthy
|
||||||
|
Container messenger-lab7-migrate-1 Starting
|
||||||
|
Container messenger-lab7-migrate-1 Started
|
||||||
|
Container messenger-lab7-postgres-1 Waiting
|
||||||
|
Container messenger-lab7-broker-1 Waiting
|
||||||
|
Container messenger-lab7-migrate-1 Waiting
|
||||||
|
Container messenger-lab7-s3-init-1 Waiting
|
||||||
|
Container messenger-lab7-migrate-1 Exited
|
||||||
|
Container messenger-lab7-s3-init-1 Exited
|
||||||
|
Container messenger-lab7-postgres-1 Healthy
|
||||||
|
Container messenger-lab7-broker-1 Healthy
|
||||||
|
Container messenger-lab7-worker-1 Starting
|
||||||
|
Container messenger-lab7-worker-1 Started
|
||||||
|
PASS: corrupt job ended as failed after bounded retries; content and message attachment are rejected
|
||||||
|
|
||||||
|
Before persistence:
|
||||||
|
|
||||||
|
$ docker inspect --format {{.Name}} {{.Config.Hostname}} {{.State.Status}} {{.State.StartedAt}} 9ec80934d8ea7c6286c47b31b8ab999ec807c1457fbf8b1338edeb1cdcf57b12 a211179fd5d90ab8d778734e8f98ba4d1fd6cdb5a653c7c5ea0d49210d1b1540 a26ef51cd8ac3cad017a7813369bfd37ac9911885a26a03790fe784216a5a01e a67a454b36fa1be5adaf19f691bab17264d491250399be35b7beb34be738d103 d37312ed572decc3919e3f1e7def5d607f756c2eaec8ac1a539499dbdc9ecc30 93323d99a9b78e20f2b317d0c54e012c61ef96bd0b0ddf8476e9d3c18f6f1ed6 affce763a5c75fe2adb515a07eb89eb782dde4fbdb6e836580e707c1815f173f 4feb5a97806ecbe986414c6257d331b5cb383a64503d8b04501265296498f114 9f3f1d2d68608acf7f2006ffd353dc22376a7875600fa4f0579615159043f594 42c9c0bfdfe5e0c53d679752eafa537d16e12d06cfd72d0fa938eb661aebc379 df8c606362feb0664ac84d96f85d1cbd642d268e8b7a53e1780dd55fd64894db bf3752876c74a743289b6747bb35aa3ec7bc4a262a2275510723354887e0f6ec ecf7a41ca7c38e325d91bf2500c30031a3181b89c12f9daac343923f9069338e ff3d179decf3050d37192c3f499fb22cb5a8636e555193a355aca9a85c032ce2 47f6a020a53f3beb438809715cd6278f1efbb93a026c48507930e7dfddace6b3 dbb3ec19939ffc02ec66c574b573f80b6e48b6225b2e9c253b4d155a32df365d
|
||||||
|
/messenger-lab7-api1-1 9ec80934d8ea running 2026-12-01T19:41:21.914484718Z
|
||||||
|
/messenger-lab7-api2-1 a211179fd5d9 running 2026-12-01T19:41:21.895739302Z
|
||||||
|
/messenger-lab7-broker-1 a26ef51cd8ac running 2026-12-01T19:41:22.385098677Z
|
||||||
|
/messenger-lab7-filer-1 a67a454b36fa running 2026-12-01T18:59:54.157556428Z
|
||||||
|
/messenger-lab7-grafana-1 d37312ed572d running 2026-12-01T19:18:26.032397262Z
|
||||||
|
/messenger-lab7-lb-1 93323d99a9b7 running 2026-12-01T19:39:07.963746212Z
|
||||||
|
/messenger-lab7-loki-1 affce763a5c7 running 2026-12-01T19:18:27.231422804Z
|
||||||
|
/messenger-lab7-master-1 4feb5a97806e running 2026-12-01T18:59:53.626396844Z
|
||||||
|
/messenger-lab7-openbao-1 9f3f1d2d6860 running 2026-12-01T19:07:19.747776259Z
|
||||||
|
/messenger-lab7-otel-collector-1 42c9c0bfdfe5 running 2026-12-01T19:18:59.900510541Z
|
||||||
|
/messenger-lab7-postgres-1 df8c606362fe running 2026-12-01T19:39:07.899624545Z
|
||||||
|
/messenger-lab7-prometheus-1 bf3752876c74 running 2026-12-01T19:18:26.007980637Z
|
||||||
|
/messenger-lab7-s3-1 ecf7a41ca7c3 running 2026-12-01T19:40:23.862150136Z
|
||||||
|
/messenger-lab7-tempo-1 ff3d179decf3 running 2026-12-01T19:25:35.540088211Z
|
||||||
|
/messenger-lab7-volume-1 47f6a020a53f running 2026-12-01T18:59:54.070516678Z
|
||||||
|
/messenger-lab7-worker-1 dbb3ec19939f running 2026-12-01T19:42:04.983433627Z
|
||||||
|
|
||||||
|
$ /Library/Developer/CommandLineTools/usr/bin/python3 tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url https://localhost:8443 --ca-file /Users/bahram/Desktop/ВП/lab7/.local/pki/external-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.
|
||||||
|
|
||||||
|
After persistence:
|
||||||
|
|
||||||
|
$ docker inspect --format {{.Name}} {{.Config.Hostname}} {{.State.Status}} {{.State.StartedAt}} 9ec80934d8ea7c6286c47b31b8ab999ec807c1457fbf8b1338edeb1cdcf57b12 a211179fd5d90ab8d778734e8f98ba4d1fd6cdb5a653c7c5ea0d49210d1b1540 a26ef51cd8ac3cad017a7813369bfd37ac9911885a26a03790fe784216a5a01e a67a454b36fa1be5adaf19f691bab17264d491250399be35b7beb34be738d103 d37312ed572decc3919e3f1e7def5d607f756c2eaec8ac1a539499dbdc9ecc30 93323d99a9b78e20f2b317d0c54e012c61ef96bd0b0ddf8476e9d3c18f6f1ed6 affce763a5c75fe2adb515a07eb89eb782dde4fbdb6e836580e707c1815f173f 4feb5a97806ecbe986414c6257d331b5cb383a64503d8b04501265296498f114 9f3f1d2d68608acf7f2006ffd353dc22376a7875600fa4f0579615159043f594 42c9c0bfdfe5e0c53d679752eafa537d16e12d06cfd72d0fa938eb661aebc379 df8c606362feb0664ac84d96f85d1cbd642d268e8b7a53e1780dd55fd64894db bf3752876c74a743289b6747bb35aa3ec7bc4a262a2275510723354887e0f6ec ecf7a41ca7c38e325d91bf2500c30031a3181b89c12f9daac343923f9069338e ff3d179decf3050d37192c3f499fb22cb5a8636e555193a355aca9a85c032ce2 47f6a020a53f3beb438809715cd6278f1efbb93a026c48507930e7dfddace6b3 dbb3ec19939ffc02ec66c574b573f80b6e48b6225b2e9c253b4d155a32df365d
|
||||||
|
/messenger-lab7-api1-1 9ec80934d8ea running 2026-12-01T19:42:22.540333594Z
|
||||||
|
/messenger-lab7-api2-1 a211179fd5d9 running 2026-12-01T19:42:22.519490635Z
|
||||||
|
/messenger-lab7-broker-1 a26ef51cd8ac running 2026-12-01T19:42:22.944234094Z
|
||||||
|
/messenger-lab7-filer-1 a67a454b36fa running 2026-12-01T18:59:54.157556428Z
|
||||||
|
/messenger-lab7-grafana-1 d37312ed572d running 2026-12-01T19:18:26.032397262Z
|
||||||
|
/messenger-lab7-lb-1 93323d99a9b7 running 2026-12-01T19:42:22.036360843Z
|
||||||
|
/messenger-lab7-loki-1 affce763a5c7 running 2026-12-01T19:18:27.231422804Z
|
||||||
|
/messenger-lab7-master-1 4feb5a97806e running 2026-12-01T18:59:53.626396844Z
|
||||||
|
/messenger-lab7-openbao-1 9f3f1d2d6860 running 2026-12-01T19:07:19.747776259Z
|
||||||
|
/messenger-lab7-otel-collector-1 42c9c0bfdfe5 running 2026-12-01T19:18:59.900510541Z
|
||||||
|
/messenger-lab7-postgres-1 df8c606362fe running 2026-12-01T19:42:21.96841951Z
|
||||||
|
/messenger-lab7-prometheus-1 bf3752876c74 running 2026-12-01T19:18:26.007980637Z
|
||||||
|
/messenger-lab7-s3-1 ecf7a41ca7c3 running 2026-12-01T19:42:22.014090135Z
|
||||||
|
/messenger-lab7-tempo-1 ff3d179decf3 running 2026-12-01T19:25:35.540088211Z
|
||||||
|
/messenger-lab7-volume-1 47f6a020a53f running 2026-12-01T18:59:54.070516678Z
|
||||||
|
/messenger-lab7-worker-1 dbb3ec19939f running 2026-12-01T19:42:52.054661968Z
|
||||||
|
|
||||||
|
$ /Library/Developer/CommandLineTools/usr/bin/python3 tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url https://localhost:8443 --ca-file /Users/bahram/Desktop/ВП/lab7/.local/pki/external-ca.crt
|
||||||
|
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
{"observed_instances_before": 2, "successful_writes": 69, "failed_attempts": 2, "first_recovery_seconds": 3.639}
|
||||||
|
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
|
||||||
|
$ docker inspect --format {{.Name}} {{.Config.Hostname}} {{.State.Status}} {{.State.StartedAt}} a211179fd5d90ab8d778734e8f98ba4d1fd6cdb5a653c7c5ea0d49210d1b1540 a26ef51cd8ac3cad017a7813369bfd37ac9911885a26a03790fe784216a5a01e a67a454b36fa1be5adaf19f691bab17264d491250399be35b7beb34be738d103 d37312ed572decc3919e3f1e7def5d607f756c2eaec8ac1a539499dbdc9ecc30 93323d99a9b78e20f2b317d0c54e012c61ef96bd0b0ddf8476e9d3c18f6f1ed6 affce763a5c75fe2adb515a07eb89eb782dde4fbdb6e836580e707c1815f173f 4feb5a97806ecbe986414c6257d331b5cb383a64503d8b04501265296498f114 9f3f1d2d68608acf7f2006ffd353dc22376a7875600fa4f0579615159043f594 42c9c0bfdfe5e0c53d679752eafa537d16e12d06cfd72d0fa938eb661aebc379 df8c606362feb0664ac84d96f85d1cbd642d268e8b7a53e1780dd55fd64894db bf3752876c74a743289b6747bb35aa3ec7bc4a262a2275510723354887e0f6ec ecf7a41ca7c38e325d91bf2500c30031a3181b89c12f9daac343923f9069338e ff3d179decf3050d37192c3f499fb22cb5a8636e555193a355aca9a85c032ce2 47f6a020a53f3beb438809715cd6278f1efbb93a026c48507930e7dfddace6b3 dbb3ec19939ffc02ec66c574b573f80b6e48b6225b2e9c253b4d155a32df365d
|
||||||
|
/messenger-lab7-api2-1 a211179fd5d9 running 2026-12-01T19:42:22.519490635Z
|
||||||
|
/messenger-lab7-broker-1 a26ef51cd8ac running 2026-12-01T19:42:22.944234094Z
|
||||||
|
/messenger-lab7-filer-1 a67a454b36fa running 2026-12-01T18:59:54.157556428Z
|
||||||
|
/messenger-lab7-grafana-1 d37312ed572d running 2026-12-01T19:18:26.032397262Z
|
||||||
|
/messenger-lab7-lb-1 93323d99a9b7 running 2026-12-01T19:42:22.036360843Z
|
||||||
|
/messenger-lab7-loki-1 affce763a5c7 running 2026-12-01T19:18:27.231422804Z
|
||||||
|
/messenger-lab7-master-1 4feb5a97806e running 2026-12-01T18:59:53.626396844Z
|
||||||
|
/messenger-lab7-openbao-1 9f3f1d2d6860 running 2026-12-01T19:07:19.747776259Z
|
||||||
|
/messenger-lab7-otel-collector-1 42c9c0bfdfe5 running 2026-12-01T19:18:59.900510541Z
|
||||||
|
/messenger-lab7-postgres-1 df8c606362fe running 2026-12-01T19:42:21.96841951Z
|
||||||
|
/messenger-lab7-prometheus-1 bf3752876c74 running 2026-12-01T19:18:26.007980637Z
|
||||||
|
/messenger-lab7-s3-1 ecf7a41ca7c3 running 2026-12-01T19:42:22.014090135Z
|
||||||
|
/messenger-lab7-tempo-1 ff3d179decf3 running 2026-12-01T19:25:35.540088211Z
|
||||||
|
/messenger-lab7-volume-1 47f6a020a53f running 2026-12-01T18:59:54.070516678Z
|
||||||
|
/messenger-lab7-worker-1 dbb3ec19939f running 2026-12-01T19:42:52.054661968Z
|
||||||
|
|
||||||
|
$ docker compose ps --all
|
||||||
|
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||||
|
messenger-lab7-api1-1 messenger-lab7-api1 "python -m app.server" api1 10 minutes ago Exited (0) 14 seconds ago
|
||||||
|
messenger-lab7-api2-1 messenger-lab7-api2 "python -m app.server" api2 10 minutes ago Up 47 seconds (healthy)
|
||||||
|
messenger-lab7-bao-data-init-1 alpine:3.21.3 "/bin/sh -c 'chown 1…" bao-data-init 35 minutes ago Exited (0) About a minute ago
|
||||||
|
messenger-lab7-broker-1 rabbitmq:3.13.7-alpine "docker-entrypoint.s…" broker 40 minutes ago Up 46 seconds (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp
|
||||||
|
messenger-lab7-filer-1 chrislusf/seaweedfs:3.85 "/entrypoint.sh file…" filer 43 minutes ago Up 43 minutes 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
|
||||||
|
messenger-lab7-grafana-1 grafana/grafana:11.5.2 "/run.sh" grafana 34 minutes ago Up 24 minutes 127.0.0.1:3007->3000/tcp
|
||||||
|
messenger-lab7-lb-1 haproxy:3.0.10-alpine "docker-entrypoint.s…" lb 34 minutes ago Up 47 seconds 127.0.0.1:8443->8443/tcp
|
||||||
|
messenger-lab7-loki-1 grafana/loki:3.4.2 "/usr/bin/loki -conf…" loki 34 minutes ago Up 24 minutes 127.0.0.1:3107->3100/tcp
|
||||||
|
messenger-lab7-master-1 chrislusf/seaweedfs:3.85 "/entrypoint.sh mast…" master 43 minutes ago Up 43 minutes 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
|
||||||
|
messenger-lab7-migrate-1 messenger-lab7-migrate "python -m app.migra…" migrate 10 minutes ago Exited (0) About a minute ago
|
||||||
|
messenger-lab7-openbao-1 quay.io/openbao/openbao:2.2.0 "docker-entrypoint.s…" openbao 35 minutes ago Up 35 minutes 127.0.0.1:8207->8200/tcp
|
||||||
|
messenger-lab7-otel-collector-1 otel/opentelemetry-collector-contrib:0.120.0 "/otelcol-contrib --…" otel-collector 34 minutes ago Up 24 minutes 4317-4318/tcp, 55678-55679/tcp
|
||||||
|
messenger-lab7-postgres-1 postgres:16.8-alpine "docker-entrypoint.s…" postgres 41 minutes ago Up 47 seconds (healthy) 5432/tcp
|
||||||
|
messenger-lab7-postgres-cert-init-1 alpine:3.21.3 "/bin/sh -c 'cp /sou…" postgres-cert-init 42 minutes ago Exited (0) About a minute ago
|
||||||
|
messenger-lab7-prometheus-1 prom/prometheus:v3.2.1 "/bin/prometheus --c…" prometheus 34 minutes ago Up 24 minutes 127.0.0.1:9097->9090/tcp
|
||||||
|
messenger-lab7-s3-1 chrislusf/seaweedfs:3.85 "/entrypoint.sh s3 -…" s3 43 minutes ago Up 47 seconds 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
|
||||||
|
messenger-lab7-s3-init-1 messenger-lab7-s3-init "python -m app.s3_in…" s3-init 10 minutes ago Exited (0) About a minute ago
|
||||||
|
messenger-lab7-tempo-1 grafana/tempo:2.7.1 "/tempo -config.file…" tempo 18 minutes ago Up 17 minutes 127.0.0.1:3207->3200/tcp
|
||||||
|
messenger-lab7-tls-probe-1 sha256:73b94be4df46cdf8aa8157542f752fc43658a56768c37736cca13ab6c77e93e7 "python tests/tls_pr…" tls-probe 34 minutes ago Exited (2) 30 minutes ago
|
||||||
|
messenger-lab7-volume-1 chrislusf/seaweedfs:3.85 "/entrypoint.sh volu…" volume 43 minutes ago Up 43 minutes 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
|
||||||
|
messenger-lab7-worker-1 messenger-lab7-worker "python -m app.worker" worker 10 minutes ago Up 17 seconds
|
||||||
|
|
||||||
|
$ docker compose up -d api1 api2 worker
|
||||||
|
Container messenger-lab7-s3-1 Running
|
||||||
|
Container messenger-lab7-openbao-1 Running
|
||||||
|
Container messenger-lab7-broker-1 Running
|
||||||
|
Container messenger-lab7-api2-1 Running
|
||||||
|
Container messenger-lab7-master-1 Running
|
||||||
|
Container messenger-lab7-worker-1 Running
|
||||||
|
Container messenger-lab7-postgres-1 Running
|
||||||
|
Container messenger-lab7-volume-1 Running
|
||||||
|
Container messenger-lab7-filer-1 Running
|
||||||
|
Container messenger-lab7-bao-data-init-1 Starting
|
||||||
|
Container messenger-lab7-s3-init-1 Starting
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Starting
|
||||||
|
Container messenger-lab7-bao-data-init-1 Started
|
||||||
|
Container messenger-lab7-bao-data-init-1 Waiting
|
||||||
|
Container messenger-lab7-s3-init-1 Started
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Started
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Waiting
|
||||||
|
Container messenger-lab7-bao-data-init-1 Exited
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Exited
|
||||||
|
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-postgres-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-postgres-1 Waiting
|
||||||
|
Container messenger-lab7-postgres-1 Waiting
|
||||||
|
Container messenger-lab7-migrate-1 Waiting
|
||||||
|
Container messenger-lab7-migrate-1 Waiting
|
||||||
|
Container messenger-lab7-s3-init-1 Waiting
|
||||||
|
Container messenger-lab7-s3-init-1 Exited
|
||||||
|
Container messenger-lab7-migrate-1 Exited
|
||||||
|
Container messenger-lab7-s3-init-1 Exited
|
||||||
|
Container messenger-lab7-postgres-1 Healthy
|
||||||
|
Container messenger-lab7-broker-1 Healthy
|
||||||
|
Container messenger-lab7-postgres-1 Healthy
|
||||||
|
Container messenger-lab7-s3-init-1 Exited
|
||||||
|
Container messenger-lab7-postgres-1 Healthy
|
||||||
|
Container messenger-lab7-api1-1 Starting
|
||||||
|
Container messenger-lab7-migrate-1 Exited
|
||||||
|
Container messenger-lab7-migrate-1 Exited
|
||||||
|
Container messenger-lab7-api1-1 Started
|
||||||
|
|
||||||
|
$ /Library/Developer/CommandLineTools/usr/bin/python3 tests/attachment_failover.py --base-url https://localhost:8443 --ca-file /Users/bahram/Desktop/ВП/lab7/.local/pki/external-ca.crt
|
||||||
|
Container messenger-lab7-api1-1 Stopping
|
||||||
|
Container messenger-lab7-api1-1 Stopped
|
||||||
|
PASS: api1 downloaded original via other API in 2.799 s; SHA-256 99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Starting
|
||||||
|
Container messenger-lab7-s3-init-1 Starting
|
||||||
|
Container messenger-lab7-bao-data-init-1 Starting
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Started
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Waiting
|
||||||
|
Container messenger-lab7-s3-init-1 Started
|
||||||
|
Container messenger-lab7-bao-data-init-1 Started
|
||||||
|
Container messenger-lab7-bao-data-init-1 Waiting
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Exited
|
||||||
|
Container messenger-lab7-postgres-1 Waiting
|
||||||
|
Container messenger-lab7-bao-data-init-1 Exited
|
||||||
|
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-postgres-1 Waiting
|
||||||
|
Container messenger-lab7-migrate-1 Waiting
|
||||||
|
Container messenger-lab7-migrate-1 Exited
|
||||||
|
Container messenger-lab7-s3-init-1 Exited
|
||||||
|
Container messenger-lab7-postgres-1 Healthy
|
||||||
|
Container messenger-lab7-api1-1 Starting
|
||||||
|
Container messenger-lab7-api1-1 Started
|
||||||
|
Container messenger-lab7-api2-1 Stopping
|
||||||
|
Container messenger-lab7-api2-1 Stopped
|
||||||
|
PASS: api2 downloaded original via other API in 1.894 s; SHA-256 99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Starting
|
||||||
|
Container messenger-lab7-s3-init-1 Starting
|
||||||
|
Container messenger-lab7-bao-data-init-1 Starting
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Started
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Waiting
|
||||||
|
Container messenger-lab7-s3-init-1 Started
|
||||||
|
Container messenger-lab7-bao-data-init-1 Started
|
||||||
|
Container messenger-lab7-bao-data-init-1 Waiting
|
||||||
|
Container messenger-lab7-postgres-cert-init-1 Exited
|
||||||
|
Container messenger-lab7-postgres-1 Waiting
|
||||||
|
Container messenger-lab7-bao-data-init-1 Exited
|
||||||
|
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-postgres-1 Waiting
|
||||||
|
Container messenger-lab7-migrate-1 Exited
|
||||||
|
Container messenger-lab7-s3-init-1 Exited
|
||||||
|
Container messenger-lab7-postgres-1 Healthy
|
||||||
|
Container messenger-lab7-api2-1 Starting
|
||||||
|
Container messenger-lab7-api2-1 Started
|
||||||
|
|
||||||
|
$ /Library/Developer/CommandLineTools/usr/bin/python3 tests/storage_failure.py --base-url https://localhost:8443 --ca-file /Users/bahram/Desktop/ВП/lab7/.local/pki/external-ca.crt
|
||||||
|
Container messenger-lab7-s3-1 Stopping
|
||||||
|
Container messenger-lab7-s3-1 Stopped
|
||||||
|
Container messenger-lab7-tls-probe-run-9e78ad2a9b26 Creating
|
||||||
|
Container messenger-lab7-tls-probe-run-9e78ad2a9b26 Created
|
||||||
|
PASS: API returned expected status 503 for the allowlisted LB identity
|
||||||
|
Container messenger-lab7-tls-probe-run-53b9da70fd81 Creating
|
||||||
|
Container messenger-lab7-tls-probe-run-53b9da70fd81 Created
|
||||||
|
PASS: API returned expected status 503 for the allowlisted LB identity
|
||||||
|
Container messenger-lab7-s3-1 Starting
|
||||||
|
Container messenger-lab7-s3-1 Started
|
||||||
|
PASS: S3 down returns 503 for readiness and upload
|
||||||
|
PASS: S3 restored
|
||||||
|
|
||||||
|
$ /Library/Developer/CommandLineTools/usr/bin/python3 tests/observability.py
|
||||||
|
PASS: protected Prometheus/Loki/Tempo; API and worker telemetry; correlated traces; Grafana dashboard
|
||||||
|
|
||||||
|
Checking private bucket from the application network
|
||||||
|
PASS: anonymous GET of existing private S3 object denied: 403
|
||||||
|
|
||||||
|
$ docker compose ps
|
||||||
|
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||||
|
messenger-lab7-api1-1 messenger-lab7-api1 "python -m app.server" api1 11 minutes ago Up 17 seconds (healthy)
|
||||||
|
messenger-lab7-api2-1 messenger-lab7-api2 "python -m app.server" api2 11 minutes ago Up 8 seconds (healthy)
|
||||||
|
messenger-lab7-broker-1 rabbitmq:3.13.7-alpine "docker-entrypoint.s…" broker 40 minutes ago Up About a minute (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp
|
||||||
|
messenger-lab7-filer-1 chrislusf/seaweedfs:3.85 "/entrypoint.sh file…" filer 43 minutes ago Up 43 minutes 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
|
||||||
|
messenger-lab7-grafana-1 grafana/grafana:11.5.2 "/run.sh" grafana 35 minutes ago Up 25 minutes 127.0.0.1:3007->3000/tcp
|
||||||
|
messenger-lab7-lb-1 haproxy:3.0.10-alpine "docker-entrypoint.s…" lb 35 minutes ago Up About a minute 127.0.0.1:8443->8443/tcp
|
||||||
|
messenger-lab7-loki-1 grafana/loki:3.4.2 "/usr/bin/loki -conf…" loki 35 minutes ago Up 25 minutes 127.0.0.1:3107->3100/tcp
|
||||||
|
messenger-lab7-master-1 chrislusf/seaweedfs:3.85 "/entrypoint.sh mast…" master 43 minutes ago Up 43 minutes 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
|
||||||
|
messenger-lab7-openbao-1 quay.io/openbao/openbao:2.2.0 "docker-entrypoint.s…" openbao 36 minutes ago Up 36 minutes 127.0.0.1:8207->8200/tcp
|
||||||
|
messenger-lab7-otel-collector-1 otel/opentelemetry-collector-contrib:0.120.0 "/otelcol-contrib --…" otel-collector 35 minutes ago Up 24 minutes 4317-4318/tcp, 55678-55679/tcp
|
||||||
|
messenger-lab7-postgres-1 postgres:16.8-alpine "docker-entrypoint.s…" postgres 42 minutes ago Up About a minute (healthy) 5432/tcp
|
||||||
|
messenger-lab7-prometheus-1 prom/prometheus:v3.2.1 "/bin/prometheus --c…" prometheus 35 minutes ago Up 25 minutes 127.0.0.1:9097->9090/tcp
|
||||||
|
messenger-lab7-s3-1 chrislusf/seaweedfs:3.85 "/entrypoint.sh s3 -…" s3 43 minutes ago Up Less than a second 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
|
||||||
|
messenger-lab7-tempo-1 grafana/tempo:2.7.1 "/tempo -config.file…" tempo 18 minutes ago Up 18 minutes 127.0.0.1:3207->3200/tcp
|
||||||
|
messenger-lab7-volume-1 chrislusf/seaweedfs:3.85 "/entrypoint.sh volu…" volume 43 minutes ago Up 43 minutes 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
|
||||||
|
messenger-lab7-worker-1 messenger-lab7-worker "python -m app.worker" worker 11 minutes ago Up 46 seconds
|
||||||
|
|
||||||
|
PASS: all recorded checks
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
global
|
||||||
|
log stdout format raw local0
|
||||||
|
maxconn 256
|
||||||
|
|
||||||
|
defaults
|
||||||
|
log global
|
||||||
|
mode http
|
||||||
|
timeout connect 2s
|
||||||
|
timeout client 30s
|
||||||
|
timeout server 30s
|
||||||
|
retries 2
|
||||||
|
option redispatch
|
||||||
|
|
||||||
|
resolvers docker
|
||||||
|
nameserver dns 127.0.0.11:53
|
||||||
|
resolve_retries 3
|
||||||
|
timeout resolve 1s
|
||||||
|
timeout retry 1s
|
||||||
|
hold valid 2s
|
||||||
|
|
||||||
|
frontend public_https
|
||||||
|
bind :8443 ssl crt /run/certs/ingress.pem alpn h2,http/1.1 ssl-min-ver TLSv1.2
|
||||||
|
http-response set-header Strict-Transport-Security "max-age=31536000"
|
||||||
|
http-response set-header X-Content-Type-Options nosniff
|
||||||
|
default_backend apis
|
||||||
|
|
||||||
|
backend apis
|
||||||
|
balance roundrobin
|
||||||
|
option httpchk GET /health/ready
|
||||||
|
http-check expect status 200
|
||||||
|
server api1 api1:8443 check inter 2s fall 2 rise 1 ssl verify required ca-file /run/certs/service-ca.crt crt /run/certs/lb-client.pem sni str(api1) verifyhost api1 resolvers docker init-addr libc,none
|
||||||
|
server api2 api2:8443 check inter 2s fall 2 rise 1 ssl verify required ca-file /run/certs/service-ca.crt crt /run/certs/lb-client.pem sni str(api2) verifyhost api2 resolvers docker init-addr libc,none
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"annotations": {"list": []},
|
||||||
|
"editable": false,
|
||||||
|
"fiscalYearStartMonth": 0,
|
||||||
|
"graphTooltip": 1,
|
||||||
|
"panels": [
|
||||||
|
{"datasource":{"type":"prometheus","uid":"prometheus"},"fieldConfig":{"defaults":{"unit":"reqps"},"overrides":[]},"gridPos":{"h":7,"w":12,"x":0,"y":0},"id":1,"targets":[{"expr":"sum(rate(messenger_http_requests_total[5m]))","refId":"A"}],"title":"HTTP requests per second","type":"timeseries"},
|
||||||
|
{"datasource":{"type":"prometheus","uid":"prometheus"},"fieldConfig":{"defaults":{"unit":"s"},"overrides":[]},"gridPos":{"h":7,"w":12,"x":12,"y":0},"id":2,"targets":[{"expr":"histogram_quantile(0.95, sum by (le) (rate(messenger_http_request_duration_seconds_bucket[5m])))","refId":"A"}],"title":"HTTP duration p95","type":"timeseries"},
|
||||||
|
{"datasource":{"type":"prometheus","uid":"prometheus"},"fieldConfig":{"defaults":{"unit":"reqps"},"overrides":[]},"gridPos":{"h":7,"w":12,"x":0,"y":7},"id":3,"targets":[{"expr":"sum(rate(messenger_http_requests_total{status_class=\"5xx\"}[5m]))","refId":"A"}],"title":"HTTP 5xx per second","type":"timeseries"},
|
||||||
|
{"datasource":{"type":"prometheus","uid":"prometheus"},"fieldConfig":{"defaults":{"unit":"ops"},"overrides":[]},"gridPos":{"h":7,"w":12,"x":12,"y":7},"id":4,"targets":[{"expr":"sum by (outcome) (rate(messenger_jobs_processed_total[5m]))","refId":"A"}],"title":"Worker jobs by outcome","type":"timeseries"},
|
||||||
|
{"datasource":{"type":"prometheus","uid":"prometheus"},"fieldConfig":{"defaults":{"unit":"s"},"overrides":[]},"gridPos":{"h":7,"w":12,"x":0,"y":14},"id":5,"targets":[{"expr":"histogram_quantile(0.95, sum by (le,outcome) (rate(messenger_job_processing_duration_seconds_bucket[5m])))","refId":"A"}],"title":"Worker duration p95","type":"timeseries"},
|
||||||
|
{"datasource":{"type":"loki","uid":"loki"},"gridPos":{"h":9,"w":24,"x":0,"y":21},"id":6,"targets":[{"expr":"{service_name=~\"messenger-api|messenger-worker\"}","queryType":"range","refId":"A"}],"title":"Structured API and worker logs","type":"logs"}
|
||||||
|
],
|
||||||
|
"refresh": "5s",
|
||||||
|
"schemaVersion": 39,
|
||||||
|
"tags": ["messenger","lab6"],
|
||||||
|
"templating": {"list": []},
|
||||||
|
"time": {"from":"now-15m","to":"now"},
|
||||||
|
"timepicker": {},
|
||||||
|
"timezone": "browser",
|
||||||
|
"title": "Messenger observability",
|
||||||
|
"uid": "messenger-observability",
|
||||||
|
"version": 1
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
{
|
||||||
|
"apiVersion": 1,
|
||||||
|
"datasources": [
|
||||||
|
{
|
||||||
|
"name": "Prometheus",
|
||||||
|
"uid": "prometheus",
|
||||||
|
"type": "prometheus",
|
||||||
|
"access": "proxy",
|
||||||
|
"url": "https://prometheus:9090",
|
||||||
|
"isDefault": true,
|
||||||
|
"editable": false,
|
||||||
|
"jsonData": {"tlsAuth": true, "tlsAuthWithCACert": true, "tlsSkipVerify": false},
|
||||||
|
"secureJsonData": {"tlsCACert": "@@CA@@", "tlsClientCert": "@@CLIENT_CERT@@", "tlsClientKey": "@@CLIENT_KEY@@"}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Loki",
|
||||||
|
"uid": "loki",
|
||||||
|
"type": "loki",
|
||||||
|
"access": "proxy",
|
||||||
|
"url": "https://loki:3100",
|
||||||
|
"editable": false,
|
||||||
|
"jsonData": {"tlsAuth": true, "tlsAuthWithCACert": true, "tlsSkipVerify": false},
|
||||||
|
"secureJsonData": {"tlsCACert": "@@CA@@", "tlsClientCert": "@@CLIENT_CERT@@", "tlsClientKey": "@@CLIENT_KEY@@"}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Tempo",
|
||||||
|
"uid": "tempo",
|
||||||
|
"type": "tempo",
|
||||||
|
"access": "proxy",
|
||||||
|
"url": "https://tempo:3200",
|
||||||
|
"editable": false,
|
||||||
|
"jsonData": {
|
||||||
|
"tlsAuth": true,
|
||||||
|
"tlsAuthWithCACert": true,
|
||||||
|
"tlsSkipVerify": false,
|
||||||
|
"tracesToLogsV2": {
|
||||||
|
"datasourceUid": "loki",
|
||||||
|
"spanStartTimeShift": "-1h",
|
||||||
|
"spanEndTimeShift": "1h",
|
||||||
|
"filterByTraceID": true,
|
||||||
|
"filterBySpanID": false,
|
||||||
|
"tags": [{"key":"service.name","value":"service"}]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"secureJsonData": {"tlsCACert": "@@CA@@", "tlsClientCert": "@@CLIENT_CERT@@", "tlsClientKey": "@@CLIENT_KEY@@"}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
[server]
|
||||||
|
protocol = https
|
||||||
|
http_port = 3000
|
||||||
|
http_addr = 0.0.0.0
|
||||||
|
cert_file = /run/certs/grafana.crt
|
||||||
|
cert_key = /run/certs/grafana.key
|
||||||
|
min_tls_version = TLS1.2
|
||||||
|
[security]
|
||||||
|
cookie_secure = true
|
||||||
|
cookie_samesite = strict
|
||||||
|
allow_embedding = false
|
||||||
|
[users]
|
||||||
|
allow_sign_up = false
|
||||||
|
[analytics]
|
||||||
|
reporting_enabled = false
|
||||||
|
check_for_updates = false
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
providers:
|
||||||
|
- name: Messenger
|
||||||
|
orgId: 1
|
||||||
|
folder: Messenger
|
||||||
|
type: file
|
||||||
|
disableDeletion: true
|
||||||
|
allowUiUpdates: false
|
||||||
|
options:
|
||||||
|
path: /var/lib/grafana/dashboards
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
datasources:
|
||||||
|
- name: Prometheus
|
||||||
|
uid: prometheus
|
||||||
|
type: prometheus
|
||||||
|
access: proxy
|
||||||
|
url: http://prometheus:9090
|
||||||
|
isDefault: true
|
||||||
|
editable: false
|
||||||
|
- name: Loki
|
||||||
|
uid: loki
|
||||||
|
type: loki
|
||||||
|
access: proxy
|
||||||
|
url: http://loki:3100
|
||||||
|
editable: false
|
||||||
|
- name: Tempo
|
||||||
|
uid: tempo
|
||||||
|
type: tempo
|
||||||
|
access: proxy
|
||||||
|
url: http://tempo:3200
|
||||||
|
editable: false
|
||||||
|
jsonData:
|
||||||
|
tracesToLogsV2:
|
||||||
|
datasourceUid: loki
|
||||||
|
spanStartTimeShift: "-1h"
|
||||||
|
spanEndTimeShift: "1h"
|
||||||
|
filterByTraceID: true
|
||||||
|
filterBySpanID: false
|
||||||
|
tags:
|
||||||
|
- key: service.name
|
||||||
|
value: service
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
auth_enabled: false
|
||||||
|
server:
|
||||||
|
http_listen_port: 3100
|
||||||
|
grpc_listen_port: 9096
|
||||||
|
tls_min_version: VersionTLS12
|
||||||
|
http_tls_config:
|
||||||
|
cert_file: /run/certs/loki.crt
|
||||||
|
key_file: /run/certs/loki.key
|
||||||
|
client_ca_file: /run/certs/backend-client-ca.crt
|
||||||
|
client_auth_type: RequireAndVerifyClientCert
|
||||||
|
common:
|
||||||
|
path_prefix: /loki
|
||||||
|
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
|
||||||
|
storage_config:
|
||||||
|
filesystem:
|
||||||
|
directory: /loki/chunks
|
||||||
|
tsdb_shipper:
|
||||||
|
active_index_directory: /loki/tsdb-index
|
||||||
|
cache_location: /loki/tsdb-cache
|
||||||
|
limits_config:
|
||||||
|
allow_structured_metadata: true
|
||||||
|
retention_period: 168h
|
||||||
|
compactor:
|
||||||
|
working_directory: /loki/compactor
|
||||||
|
retention_enabled: true
|
||||||
|
delete_request_store: filesystem
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
tls_server_config:
|
||||||
|
cert_file: /run/certs/prometheus.crt
|
||||||
|
key_file: /run/certs/prometheus.key
|
||||||
|
client_auth_type: RequireAndVerifyClientCert
|
||||||
|
client_ca_file: /run/certs/backend-client-ca.crt
|
||||||
|
client_allowed_sans:
|
||||||
|
- spiffe://mtusi2026/lab7/otel-collector
|
||||||
|
- spiffe://mtusi2026/lab7/grafana
|
||||||
|
min_version: TLS12
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
global:
|
||||||
|
scrape_interval: 15s
|
||||||
|
evaluation_interval: 15s
|
||||||
|
scrape_configs: []
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
server:
|
||||||
|
http_listen_port: 3200
|
||||||
|
grpc_listen_port: 9095
|
||||||
|
tls_min_version: VersionTLS12
|
||||||
|
http_tls_config:
|
||||||
|
cert_file: /run/certs/tempo.crt
|
||||||
|
key_file: /run/certs/tempo.key
|
||||||
|
client_auth_type: RequireAndVerifyClientCert
|
||||||
|
client_ca_file: /run/certs/backend-client-ca.crt
|
||||||
|
distributor:
|
||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
grpc:
|
||||||
|
endpoint: 0.0.0.0:4317
|
||||||
|
tls:
|
||||||
|
cert_file: /run/certs/tempo.crt
|
||||||
|
key_file: /run/certs/tempo.key
|
||||||
|
client_ca_file: /run/certs/backend-client-ca.crt
|
||||||
|
storage:
|
||||||
|
trace:
|
||||||
|
backend: local
|
||||||
|
wal:
|
||||||
|
path: /var/tempo/wal
|
||||||
|
local:
|
||||||
|
path: /var/tempo/blocks
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
ui = true
|
||||||
|
api_addr = "https://openbao:8200"
|
||||||
|
cluster_addr = "https://openbao:8201"
|
||||||
|
|
||||||
|
storage "file" {
|
||||||
|
path = "/openbao/data"
|
||||||
|
}
|
||||||
|
|
||||||
|
listener "tcp" {
|
||||||
|
address = "0.0.0.0:8200"
|
||||||
|
cluster_address = "0.0.0.0:8201"
|
||||||
|
tls_cert_file = "/run/certs/openbao.crt"
|
||||||
|
tls_key_file = "/run/certs/openbao.key"
|
||||||
|
tls_min_version = "tls12"
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
http:
|
||||||
|
endpoint: 0.0.0.0:4318
|
||||||
|
tls:
|
||||||
|
cert_file: /run/certs/otel-collector.crt
|
||||||
|
key_file: /run/certs/otel-collector.key
|
||||||
|
client_ca_file: /run/certs/otel-ingest-ca.crt
|
||||||
|
min_version: "1.2"
|
||||||
|
grpc:
|
||||||
|
endpoint: 0.0.0.0:4317
|
||||||
|
tls:
|
||||||
|
cert_file: /run/certs/otel-collector.crt
|
||||||
|
key_file: /run/certs/otel-collector.key
|
||||||
|
client_ca_file: /run/certs/otel-ingest-ca.crt
|
||||||
|
min_version: "1.2"
|
||||||
|
|
||||||
|
processors:
|
||||||
|
memory_limiter:
|
||||||
|
check_interval: 1s
|
||||||
|
limit_mib: 256
|
||||||
|
spike_limit_mib: 64
|
||||||
|
batch:
|
||||||
|
timeout: 2s
|
||||||
|
send_batch_size: 512
|
||||||
|
|
||||||
|
exporters:
|
||||||
|
otlphttp/prometheus:
|
||||||
|
endpoint: https://prometheus:9090/api/v1/otlp
|
||||||
|
tls:
|
||||||
|
ca_file: /run/certs/service-ca.crt
|
||||||
|
cert_file: /run/certs/backend-collector.crt
|
||||||
|
key_file: /run/certs/backend-collector.key
|
||||||
|
server_name_override: prometheus
|
||||||
|
otlphttp/loki:
|
||||||
|
endpoint: https://loki:3100/otlp
|
||||||
|
tls:
|
||||||
|
ca_file: /run/certs/service-ca.crt
|
||||||
|
cert_file: /run/certs/backend-collector.crt
|
||||||
|
key_file: /run/certs/backend-collector.key
|
||||||
|
server_name_override: loki
|
||||||
|
otlp/tempo:
|
||||||
|
endpoint: tempo:4317
|
||||||
|
tls:
|
||||||
|
ca_file: /run/certs/service-ca.crt
|
||||||
|
cert_file: /run/certs/backend-collector.crt
|
||||||
|
key_file: /run/certs/backend-collector.key
|
||||||
|
server_name_override: tempo
|
||||||
|
|
||||||
|
service:
|
||||||
|
pipelines:
|
||||||
|
metrics:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [otlphttp/prometheus]
|
||||||
|
traces:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [otlp/tempo]
|
||||||
|
logs:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [otlphttp/loki]
|
||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
psql --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" --set ON_ERROR_STOP=1 <<SQL
|
||||||
|
CREATE ROLE messenger_api LOGIN PASSWORD '$POSTGRES_API_PASSWORD';
|
||||||
|
CREATE ROLE messenger_worker LOGIN PASSWORD '$POSTGRES_WORKER_PASSWORD';
|
||||||
|
REVOKE ALL ON DATABASE messenger FROM PUBLIC;
|
||||||
|
SQL
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
listeners.tcp = none
|
||||||
|
listeners.ssl.default = 5671
|
||||||
|
ssl_options.cacertfile = /run/certs/service-ca.crt
|
||||||
|
ssl_options.certfile = /run/certs/broker.crt
|
||||||
|
ssl_options.keyfile = /run/certs/broker.key
|
||||||
|
ssl_options.verify = verify_none
|
||||||
|
ssl_options.fail_if_no_peer_cert = false
|
||||||
|
ssl_options.versions.1 = tlsv1.2
|
||||||
|
loopback_users.guest = true
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS users(id uuid PRIMARY KEY, username text NOT NULL UNIQUE, password text NOT NULL, doc jsonb NOT NULL);
|
||||||
|
CREATE TABLE IF NOT EXISTS sessions(token text PRIMARY KEY, user_id uuid NOT NULL REFERENCES users, expires_at timestamptz NOT NULL);
|
||||||
|
CREATE TABLE IF NOT EXISTS chats(id uuid PRIMARY KEY, doc jsonb NOT NULL);
|
||||||
|
CREATE TABLE IF NOT EXISTS messages(id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats, sender_id uuid NOT NULL REFERENCES users, idem_key text NOT NULL, body jsonb NOT NULL, doc jsonb NOT NULL, saved_at timestamptz NOT NULL DEFAULT now());
|
||||||
|
CREATE INDEX IF NOT EXISTS messages_replay ON messages(sender_id,chat_id,idem_key,saved_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS messages_page ON messages(chat_id,(doc->>'created_at'),id);
|
||||||
|
CREATE TABLE IF NOT EXISTS attachments(id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats, doc jsonb NOT NULL, stage_key text);
|
||||||
|
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS stage_key text;
|
||||||
|
CREATE TABLE IF NOT EXISTS attachment_jobs(
|
||||||
|
job_id uuid PRIMARY KEY,
|
||||||
|
attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id),
|
||||||
|
payload jsonb NOT NULL,
|
||||||
|
status text NOT NULL DEFAULT 'queued' CHECK(status IN ('queued','processing','done','failed')),
|
||||||
|
attempt integer NOT NULL DEFAULT 0,
|
||||||
|
published_at timestamptz,
|
||||||
|
last_error text,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS attachment_jobs_outbox ON attachment_jobs(created_at) WHERE published_at IS NULL;
|
||||||
|
CREATE TABLE IF NOT EXISTS login_rate_limits(
|
||||||
|
key_hash text PRIMARY KEY,
|
||||||
|
window_started timestamptz NOT NULL,
|
||||||
|
failures integer NOT NULL CHECK(failures>=0)
|
||||||
|
);
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
fastapi==0.115.12
|
||||||
|
uvicorn==0.34.2
|
||||||
|
psycopg[binary]==3.2.9
|
||||||
|
argon2-cffi==23.1.0
|
||||||
|
jsonschema==4.23.0
|
||||||
|
boto3==1.38.23
|
||||||
|
Pillow==11.2.1
|
||||||
|
pika==1.3.2
|
||||||
|
opentelemetry-api==1.30.0
|
||||||
|
opentelemetry-sdk==1.30.0
|
||||||
|
opentelemetry-exporter-otlp-proto-http==1.30.0
|
||||||
|
cryptography==44.0.2
|
||||||
Executable
+301
@@ -0,0 +1,301 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Create ignored local PKI/secrets, initialize OpenBao, and start the grade-3 stack."""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import secrets
|
||||||
|
import shutil
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
ROOT=Path(__file__).resolve().parents[1]
|
||||||
|
LOCAL=ROOT/'.local'
|
||||||
|
PKI=LOCAL/'pki'
|
||||||
|
BAO=LOCAL/'openbao'
|
||||||
|
ROLES=LOCAL/'approles'
|
||||||
|
ENV=ROOT/'.env'
|
||||||
|
|
||||||
|
|
||||||
|
def run(*args,stdout=None):
|
||||||
|
return subprocess.run(args,cwd=ROOT,check=True,stdout=stdout)
|
||||||
|
|
||||||
|
|
||||||
|
def write(path,data,mode=0o600):
|
||||||
|
path.parent.mkdir(parents=True,exist_ok=True)
|
||||||
|
path.write_text(data,encoding='utf-8')
|
||||||
|
path.chmod(mode)
|
||||||
|
|
||||||
|
|
||||||
|
def make_env():
|
||||||
|
required={'POSTGRES_ADMIN_PASSWORD','POSTGRES_API_PASSWORD','POSTGRES_WORKER_PASSWORD',
|
||||||
|
'S3_API_ACCESS_KEY','S3_API_SECRET_KEY','S3_WORKER_ACCESS_KEY','S3_WORKER_SECRET_KEY',
|
||||||
|
'S3_ADMIN_ACCESS_KEY','S3_ADMIN_SECRET_KEY','RABBIT_ADMIN_USER','RABBIT_ADMIN_PASSWORD',
|
||||||
|
'RABBIT_API_USER','RABBIT_API_PASSWORD','RABBIT_WORKER_USER','RABBIT_WORKER_PASSWORD','GRAFANA_PASSWORD'}
|
||||||
|
if ENV.exists():
|
||||||
|
existing=env_values()
|
||||||
|
if required <= set(existing) and all(existing[k] and 'CHANGE_ME' not in existing[k] for k in required):
|
||||||
|
return
|
||||||
|
values={
|
||||||
|
'PUBLIC_PORT':'8443','POSTGRES_ADMIN_PASSWORD':secrets.token_hex(32),
|
||||||
|
'POSTGRES_API_PASSWORD':secrets.token_hex(32),'POSTGRES_WORKER_PASSWORD':secrets.token_hex(32),
|
||||||
|
'S3_API_ACCESS_KEY':secrets.token_hex(12),'S3_API_SECRET_KEY':secrets.token_hex(32),
|
||||||
|
'S3_WORKER_ACCESS_KEY':secrets.token_hex(12),'S3_WORKER_SECRET_KEY':secrets.token_hex(32),
|
||||||
|
'S3_ADMIN_ACCESS_KEY':secrets.token_hex(12),'S3_ADMIN_SECRET_KEY':secrets.token_hex(32),
|
||||||
|
'RABBIT_ADMIN_USER':'lab7_operator','RABBIT_ADMIN_PASSWORD':secrets.token_hex(32),
|
||||||
|
'RABBIT_API_USER':'lab7_api','RABBIT_API_PASSWORD':secrets.token_hex(32),
|
||||||
|
'RABBIT_WORKER_USER':'lab7_worker','RABBIT_WORKER_PASSWORD':secrets.token_hex(32),
|
||||||
|
'GRAFANA_PASSWORD':secrets.token_hex(24),'SESSION_TTL_SECONDS':'3600','JOB_MAX_ATTEMPTS':'5'
|
||||||
|
}
|
||||||
|
write(ENV,'\n'.join(k+'='+v for k,v in values.items())+'\n')
|
||||||
|
|
||||||
|
|
||||||
|
def env_values():
|
||||||
|
result={}
|
||||||
|
for line in ENV.read_text().splitlines():
|
||||||
|
if line and not line.startswith('#') and '=' in line:
|
||||||
|
k,v=line.split('=',1); result[k]=v
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def openssl(*args):
|
||||||
|
subprocess.run(['openssl',*map(str,args)],cwd=ROOT,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||||
|
|
||||||
|
|
||||||
|
def create_ca(name):
|
||||||
|
key=PKI/(name+'.key'); cert=PKI/(name+'.crt')
|
||||||
|
if cert.exists() and key.exists(): return cert,key
|
||||||
|
openssl('genpkey','-algorithm','RSA','-pkeyopt','rsa_keygen_bits:3072','-out',key)
|
||||||
|
openssl('req','-x509','-new','-key',key,'-sha256','-days','825','-subj','/CN='+name,
|
||||||
|
'-addext','basicConstraints=critical,CA:TRUE','-addext','keyUsage=critical,keyCertSign,cRLSign','-out',cert)
|
||||||
|
key.chmod(0o600); cert.chmod(0o644)
|
||||||
|
return cert,key
|
||||||
|
|
||||||
|
|
||||||
|
def issue(name,ca_name,dns=(),ips=(),uris=()):
|
||||||
|
cert=PKI/(name+'.crt'); key=PKI/(name+'.key')
|
||||||
|
if cert.exists() and key.exists(): return cert,key
|
||||||
|
ca_cert=PKI/(ca_name+'.crt'); ca_key=PKI/(ca_name+'.key')
|
||||||
|
csr=PKI/(name+'.csr'); ext=PKI/(name+'.ext')
|
||||||
|
openssl('genpkey','-algorithm','RSA','-pkeyopt','rsa_keygen_bits:2048','-out',key)
|
||||||
|
openssl('req','-new','-key',key,'-subj','/CN='+name,'-out',csr)
|
||||||
|
sans=[]
|
||||||
|
sans.extend('DNS:'+x for x in dns); sans.extend('IP:'+x for x in ips); sans.extend('URI:'+x for x in uris)
|
||||||
|
lines=['basicConstraints=critical,CA:FALSE','keyUsage=critical,digitalSignature,keyEncipherment','extendedKeyUsage=serverAuth,clientAuth']
|
||||||
|
if sans: lines.append('subjectAltName='+','.join(sans))
|
||||||
|
write(ext,'\n'.join(lines)+'\n',0o600)
|
||||||
|
openssl('x509','-req','-in',csr,'-CA',ca_cert,'-CAkey',ca_key,'-CAcreateserial','-out',cert,'-days','90','-sha256','-extfile',ext)
|
||||||
|
key.chmod(0o644); cert.chmod(0o644); csr.unlink(missing_ok=True); ext.unlink(missing_ok=True)
|
||||||
|
return cert,key
|
||||||
|
|
||||||
|
|
||||||
|
def create_pki():
|
||||||
|
PKI.mkdir(parents=True,exist_ok=True); PKI.chmod(0o700)
|
||||||
|
create_ca('external-ca'); create_ca('service-ca'); create_ca('lb-client-ca')
|
||||||
|
create_ca('otel-ingest-ca'); create_ca('backend-client-ca')
|
||||||
|
issue('ingress','external-ca',dns=['localhost'],ips=['127.0.0.1'])
|
||||||
|
issue('api','service-ca',dns=['api1','api2','localhost'])
|
||||||
|
issue('postgres','service-ca',dns=['postgres'])
|
||||||
|
issue('s3','service-ca',dns=['s3'])
|
||||||
|
issue('broker','service-ca',dns=['broker'])
|
||||||
|
issue('openbao','service-ca',dns=['openbao','localhost'],ips=['127.0.0.1'])
|
||||||
|
for name in ('otel-collector','prometheus','loki','tempo','grafana'):
|
||||||
|
names=[name]
|
||||||
|
ips=[]
|
||||||
|
if name in ('prometheus','loki','tempo','grafana'):
|
||||||
|
names.append('localhost'); ips=['127.0.0.1']
|
||||||
|
issue(name,'service-ca',dns=names,ips=ips)
|
||||||
|
issue('lb-client','lb-client-ca',uris=['spiffe://mtusi2026/lab7/load-balancer'])
|
||||||
|
issue('foreign-client','lb-client-ca',uris=['spiffe://mtusi2026/lab7/unapproved'])
|
||||||
|
issue('untrusted-client','service-ca',uris=['spiffe://mtusi2026/lab7/untrusted'])
|
||||||
|
issue('otel-api-client','otel-ingest-ca',uris=['spiffe://mtusi2026/lab7/api'])
|
||||||
|
issue('otel-worker-client','otel-ingest-ca',uris=['spiffe://mtusi2026/lab7/worker'])
|
||||||
|
issue('backend-collector','backend-client-ca',uris=['spiffe://mtusi2026/lab7/otel-collector'])
|
||||||
|
issue('backend-grafana','backend-client-ca',uris=['spiffe://mtusi2026/lab7/grafana'])
|
||||||
|
for name in ('ingress','lb-client'):
|
||||||
|
cert,key=PKI/(name+'.crt'),PKI/(name+'.key')
|
||||||
|
write(PKI/(name+'.pem'),cert.read_text()+key.read_text(),0o600)
|
||||||
|
|
||||||
|
|
||||||
|
def create_s3_config(env):
|
||||||
|
def identity(name,access,secret,actions):
|
||||||
|
return {'name':name,'credentials':[{'accessKey':env[access],'secretKey':env[secret]}],'actions':actions}
|
||||||
|
staging='attachments-staging'; original='attachments-original'; variants='attachments-variants'
|
||||||
|
config={'identities':[
|
||||||
|
identity('api','S3_API_ACCESS_KEY','S3_API_SECRET_KEY',
|
||||||
|
['List:'+staging,'Write:'+staging,'List:'+original,'Read:'+original,'List:'+variants,'Read:'+variants]),
|
||||||
|
identity('worker','S3_WORKER_ACCESS_KEY','S3_WORKER_SECRET_KEY',
|
||||||
|
['Read:'+staging,'Write:'+staging,'Write:'+original,'Write:'+variants]),
|
||||||
|
identity('operator','S3_ADMIN_ACCESS_KEY','S3_ADMIN_SECRET_KEY',
|
||||||
|
['Admin:'+staging,'Admin:'+original,'Admin:'+variants])
|
||||||
|
]}
|
||||||
|
write(LOCAL/'s3.json',json.dumps(config,indent=2)+'\n')
|
||||||
|
|
||||||
|
|
||||||
|
def parse_body(error):
|
||||||
|
try: return json.loads(error.read().decode())
|
||||||
|
except Exception: return {}
|
||||||
|
|
||||||
|
|
||||||
|
def bao_request(path,method='GET',body=None,token=None):
|
||||||
|
context=ssl.create_default_context(cafile=str(PKI/'service-ca.crt'))
|
||||||
|
data=None if body is None else json.dumps(body).encode()
|
||||||
|
req=urllib.request.Request('https://localhost:8207/v1/'+path,data=data,method=method)
|
||||||
|
req.add_header('Content-Type','application/json')
|
||||||
|
if token: req.add_header('X-Vault-Token',token)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req,context=context,timeout=5) as response:
|
||||||
|
data=response.read()
|
||||||
|
return response.status,json.loads(data) if data else {}
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
return exc.code,parse_body(exc)
|
||||||
|
|
||||||
|
|
||||||
|
def wait_openbao():
|
||||||
|
deadline=time.time()+90
|
||||||
|
while time.time()<deadline:
|
||||||
|
try:
|
||||||
|
status,doc=bao_request('sys/health')
|
||||||
|
if doc: return status,doc
|
||||||
|
except Exception:
|
||||||
|
time.sleep(1)
|
||||||
|
raise RuntimeError('OpenBao TLS listener did not start')
|
||||||
|
|
||||||
|
|
||||||
|
def initialize_openbao(env):
|
||||||
|
BAO.mkdir(parents=True,exist_ok=True); BAO.chmod(0o700)
|
||||||
|
operator=BAO/'operator.json'
|
||||||
|
status,health=wait_openbao()
|
||||||
|
if not health.get('initialized'):
|
||||||
|
init_status,created=bao_request('sys/init','PUT',{'secret_shares':3,'secret_threshold':2})
|
||||||
|
if init_status!=200 or created.get('errors'):
|
||||||
|
raise RuntimeError('OpenBao initialization failed: '+str(created.get('errors',['unexpected response'])[0]))
|
||||||
|
created['keys']=created.get('keys_base64',created.get('keys',[]))
|
||||||
|
write(operator,json.dumps(created,indent=2)+'\n')
|
||||||
|
if not operator.exists():
|
||||||
|
raise RuntimeError('OpenBao is already initialized, but .local/openbao/operator.json is missing; restore operator recovery material')
|
||||||
|
data=json.loads(operator.read_text())
|
||||||
|
keys=data.get('keys') or data.get('keys_base64') or []
|
||||||
|
root=data.get('root_token')
|
||||||
|
if not root or len(keys)<2: raise RuntimeError('OpenBao operator recovery material is incomplete')
|
||||||
|
status,health=bao_request('sys/health')
|
||||||
|
if health.get('sealed',True):
|
||||||
|
for key in keys[:2]:
|
||||||
|
_,health=bao_request('sys/unseal','POST',{'key':key})
|
||||||
|
if health.get('sealed',True): raise RuntimeError('OpenBao remains sealed after operator unseal')
|
||||||
|
mounts=bao_request('sys/mounts',token=root)[1]
|
||||||
|
if 'kv/' not in mounts:
|
||||||
|
bao_request('sys/mounts/kv','POST',{'type':'kv','options':{'version':'2'}},root)
|
||||||
|
auth=bao_request('sys/auth',token=root)[1]
|
||||||
|
if 'approle/' not in auth:
|
||||||
|
bao_request('sys/auth/approle','POST',{'type':'approle'},root)
|
||||||
|
policies={
|
||||||
|
'api-runtime':'path "kv/data/messenger/api" { capabilities = ["read"] }',
|
||||||
|
'worker-runtime':'path "kv/data/messenger/worker" { capabilities = ["read"] }'
|
||||||
|
}
|
||||||
|
for name,policy in policies.items():
|
||||||
|
bao_request('sys/policies/acl/'+name,'PUT',{'policy':policy},root)
|
||||||
|
values={
|
||||||
|
'api':{
|
||||||
|
'DATABASE_URL':'postgresql://messenger_api:'+env['POSTGRES_API_PASSWORD']+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/certs/service-ca.crt',
|
||||||
|
'S3_ACCESS_KEY':env['S3_API_ACCESS_KEY'],'S3_SECRET_KEY':env['S3_API_SECRET_KEY'],
|
||||||
|
'BROKER_URL':'amqps://'+env['RABBIT_API_USER']+':'+env['RABBIT_API_PASSWORD']+'@broker:5671/%2Flab7',
|
||||||
|
'LOGIN_RATE_HMAC_KEY':secrets.token_hex(32)
|
||||||
|
},
|
||||||
|
'worker':{
|
||||||
|
'DATABASE_URL':'postgresql://messenger_worker:'+env['POSTGRES_WORKER_PASSWORD']+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/certs/service-ca.crt',
|
||||||
|
'S3_ACCESS_KEY':env['S3_WORKER_ACCESS_KEY'],'S3_SECRET_KEY':env['S3_WORKER_SECRET_KEY'],
|
||||||
|
'BROKER_URL':'amqps://'+env['RABBIT_WORKER_USER']+':'+env['RABBIT_WORKER_PASSWORD']+'@broker:5671/%2Flab7',
|
||||||
|
'LOGIN_RATE_HMAC_KEY':secrets.token_hex(32)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for service,secret in values.items():
|
||||||
|
bao_request('kv/data/messenger/'+service,'POST',{'data':secret},root)
|
||||||
|
role=service
|
||||||
|
bao_request('auth/approle/role/'+role,'POST',{
|
||||||
|
'token_policies':['api-runtime' if service=='api' else 'worker-runtime'],
|
||||||
|
'token_ttl':'10m','token_max_ttl':'30m','secret_id_ttl':'720h',
|
||||||
|
'secret_id_num_uses':0,'bind_secret_id':True
|
||||||
|
},root)
|
||||||
|
role_id=bao_request('auth/approle/role/'+role+'/role-id',token=root)[1]['data']['role_id']
|
||||||
|
secret_id=bao_request('auth/approle/role/'+role+'/secret-id','POST',{},root)[1]['data']['secret_id']
|
||||||
|
write(ROLES/(role+'-role-id'),role_id+'\n')
|
||||||
|
write(ROLES/(role+'-secret-id'),secret_id+'\n')
|
||||||
|
# Prove the runtime identity is read-only and cannot read the other service secret.
|
||||||
|
for service in ('api','worker'):
|
||||||
|
role_id=(ROLES/(service+'-role-id')).read_text().strip()
|
||||||
|
secret_id=(ROLES/(service+'-secret-id')).read_text().strip()
|
||||||
|
_,login=bao_request('auth/approle/login','POST',{'role_id':role_id,'secret_id':secret_id})
|
||||||
|
token=login['auth']['client_token']
|
||||||
|
target='messenger/'+('worker' if service=='api' else 'api')
|
||||||
|
denied,_=bao_request('kv/data/'+target,token=token)
|
||||||
|
if denied not in (403,404): raise RuntimeError('OpenBao cross-service policy denial was not enforced')
|
||||||
|
print('OpenBao initialized/unsealed; scoped API and worker AppRoles verified.')
|
||||||
|
|
||||||
|
|
||||||
|
def init_rabbit(env):
|
||||||
|
subprocess.run(['docker','compose','exec','-T','broker','su-exec','rabbitmq','rabbitmqctl','add_vhost','/lab7'],cwd=ROOT,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||||
|
queue=r'^attachment\.process\.v1$'
|
||||||
|
for user_key,pass_key,can_read in [('RABBIT_API_USER','RABBIT_API_PASSWORD',False),('RABBIT_WORKER_USER','RABBIT_WORKER_PASSWORD',True)]:
|
||||||
|
user=env[user_key]; password=env[pass_key]
|
||||||
|
added=subprocess.run(['docker','compose','exec','-T','broker','su-exec','rabbitmq','rabbitmqctl','add_user',user,password],cwd=ROOT,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||||
|
if added.returncode:
|
||||||
|
run('docker','compose','exec','-T','broker','su-exec','rabbitmq','rabbitmqctl','change_password',user,password,stdout=subprocess.DEVNULL)
|
||||||
|
run('docker','compose','exec','-T','broker','su-exec','rabbitmq','rabbitmqctl','set_permissions','-p','/lab7',user,
|
||||||
|
queue,r'^amq\.default$',queue if can_read else r'^$',stdout=subprocess.DEVNULL)
|
||||||
|
run('docker','compose','exec','-T','broker','su-exec','rabbitmq','rabbitmqctl','list_permissions','-p','/lab7',stdout=subprocess.DEVNULL)
|
||||||
|
|
||||||
|
|
||||||
|
def render_grafana():
|
||||||
|
cert=(PKI/'service-ca.crt').read_text()
|
||||||
|
client_cert=(PKI/'backend-grafana.crt').read_text()
|
||||||
|
client_key=(PKI/'backend-grafana.key').read_text()
|
||||||
|
source=ROOT/'infra/observability/grafana/datasources.json.template'
|
||||||
|
data=json.loads(source.read_text())
|
||||||
|
replacements={'@@CA@@':cert,'@@CLIENT_CERT@@':client_cert,'@@CLIENT_KEY@@':client_key}
|
||||||
|
def walk(v):
|
||||||
|
if isinstance(v,dict): return {k:walk(x) for k,x in v.items()}
|
||||||
|
if isinstance(v,list): return [walk(x) for x in v]
|
||||||
|
if isinstance(v,str) and v in replacements: return replacements[v]
|
||||||
|
return v
|
||||||
|
dest=LOCAL/'grafana/provisioning/datasources.json'
|
||||||
|
write(dest,json.dumps(walk(data),indent=2)+'\n',0o600)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
make_env(); create_pki(); env=env_values(); ROLES.mkdir(parents=True,exist_ok=True); ROLES.chmod(0o700)
|
||||||
|
create_s3_config(env)
|
||||||
|
# Create and start only the trust-anchor and stateful dependency services first.
|
||||||
|
run('docker','compose','--env-file','.env','up','-d','postgres-cert-init','postgres','openbao','broker','master','volume','filer','s3')
|
||||||
|
deadline=time.time()+120
|
||||||
|
while time.time()<deadline:
|
||||||
|
state=subprocess.run(['docker','compose','ps','--format','json','postgres','broker'],cwd=ROOT,stdout=subprocess.PIPE,text=True)
|
||||||
|
lines=[json.loads(line) for line in state.stdout.splitlines() if line.strip()]
|
||||||
|
if len(lines)==2 and all(x.get('Health')=='healthy' for x in lines): break
|
||||||
|
time.sleep(2)
|
||||||
|
else: raise RuntimeError('PostgreSQL or RabbitMQ did not become healthy')
|
||||||
|
initialize_openbao(env)
|
||||||
|
init_rabbit(env)
|
||||||
|
run('docker','compose','--env-file','.env','run','--rm','s3-init')
|
||||||
|
run('docker','compose','--env-file','.env','run','--rm','migrate')
|
||||||
|
render_grafana()
|
||||||
|
run('docker','compose','--env-file','.env','up','-d','--build')
|
||||||
|
print('Waiting for HTTPS ingress and internal mTLS health checks...')
|
||||||
|
context=ssl.create_default_context(cafile=str(PKI/'external-ca.crt'))
|
||||||
|
url='https://localhost:'+env['PUBLIC_PORT']+'/health/ready'
|
||||||
|
deadline=time.time()+120
|
||||||
|
while time.time()<deadline:
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(url,context=context,timeout=3) as response:
|
||||||
|
if response.status==200:
|
||||||
|
print('PASS: HTTPS ingress and required LB-to-API mTLS are ready.')
|
||||||
|
return
|
||||||
|
except Exception:
|
||||||
|
time.sleep(2)
|
||||||
|
raise RuntimeError('HTTPS ingress did not become ready; inspect docker compose logs')
|
||||||
|
|
||||||
|
if __name__=='__main__':
|
||||||
|
main()
|
||||||
Executable
+12
@@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
# Keep OpenBao unsealed; restart application stateful dependencies and services only.
|
||||||
|
docker compose restart postgres s3 broker api1 api2 worker lb
|
||||||
|
for _ in $(seq 1 60); do
|
||||||
|
if docker compose exec -T worker python -c "from app.secrets import load_secrets; load_secrets(); import psycopg,os; c=psycopg.connect(os.environ['DATABASE_URL']); c.execute('SELECT 1'); c.close()" >/dev/null 2>&1; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
exit 1
|
||||||
Executable
+15
@@ -0,0 +1,15 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}"
|
||||||
|
for service in api1 api2; do
|
||||||
|
cid=$(docker compose ps -q "$service")
|
||||||
|
[ -n "$cid" ] || continue
|
||||||
|
identity=$(docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' "$cid" | sed -n 's/^APP_INSTANCE_ID=//p')
|
||||||
|
if [ "$identity" = "$TARGET_INSTANCE_ID" ]; then
|
||||||
|
docker compose stop -t 2 "$service"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
echo 'Target instance not found' >&2
|
||||||
|
exit 1
|
||||||
Executable
+17
@@ -0,0 +1,17 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Unseal file-backed OpenBao with operator-held local recovery shares."""
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from bootstrap import BAO, bao_request
|
||||||
|
|
||||||
|
operator=json.loads((BAO/'operator.json').read_text())
|
||||||
|
keys=operator.get('keys') or operator.get('keys_base64') or []
|
||||||
|
if len(keys)<2: raise SystemExit('OpenBao operator recovery material is incomplete')
|
||||||
|
_,health=bao_request('sys/health')
|
||||||
|
if not health.get('sealed',True):
|
||||||
|
print('OpenBao is already unsealed.')
|
||||||
|
raise SystemExit(0)
|
||||||
|
for key in keys[:2]:
|
||||||
|
_,health=bao_request('sys/unseal','POST',{'key':key})
|
||||||
|
if health.get('sealed',True): raise SystemExit('OpenBao remains sealed; inspect operator recovery shares locally.')
|
||||||
|
print('OpenBao unsealed; operator shares were not printed.')
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Reproduce public acceptance, TLS-negative and local least-privilege checks."""
|
||||||
|
import datetime
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
os.chdir(ROOT)
|
||||||
|
PUBLIC_PORT = os.getenv('PUBLIC_PORT', '8443')
|
||||||
|
BASE_URL = 'https://localhost:' + PUBLIC_PORT
|
||||||
|
CA_FILE = str(ROOT / '.local' / 'pki' / 'external-ca.crt')
|
||||||
|
|
||||||
|
|
||||||
|
def command(*args):
|
||||||
|
print('\n$ ' + ' '.join(map(str, args)), flush=True)
|
||||||
|
subprocess.run(list(map(str, args)), check=True)
|
||||||
|
|
||||||
|
|
||||||
|
def wait():
|
||||||
|
context = ssl.create_default_context(cafile=CA_FILE)
|
||||||
|
for _ in range(120):
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(BASE_URL + '/health/ready', context=context, timeout=3) as response:
|
||||||
|
if response.status == 200:
|
||||||
|
status = subprocess.check_output(['docker', 'compose', 'ps', '--format', 'json', 'api1', 'api2'], text=True)
|
||||||
|
docs = [json.loads(line) for line in status.splitlines() if line.strip()]
|
||||||
|
if len(docs) == 2 and all(doc.get('Health') == 'healthy' for doc in docs):
|
||||||
|
return
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
time.sleep(1)
|
||||||
|
raise RuntimeError('HTTPS ingress or API replicas did not become ready')
|
||||||
|
|
||||||
|
|
||||||
|
def state():
|
||||||
|
ids = subprocess.check_output(['docker', 'compose', 'ps', '-q'], text=True).split()
|
||||||
|
if ids:
|
||||||
|
command('docker', 'inspect', '--format', '{{.Name}} {{.Config.Hostname}} {{.State.Status}} {{.State.StartedAt}}', *ids)
|
||||||
|
|
||||||
|
|
||||||
|
print('Verification UTC:', datetime.datetime.now(datetime.timezone.utc).isoformat(), flush=True)
|
||||||
|
command('docker', 'compose', 'config', '--quiet')
|
||||||
|
command(sys.executable, 'scripts/check_contract.py')
|
||||||
|
wait()
|
||||||
|
command('docker', 'compose', 'ps')
|
||||||
|
command(sys.executable, 'tests/smoke.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
|
||||||
|
command(sys.executable, 'tests/security.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
|
||||||
|
command(sys.executable, 'tests/security_runtime.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
|
||||||
|
command(sys.executable, 'tests/acceptance_extra.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
|
||||||
|
command(sys.executable, 'tests/worker_flow.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
|
||||||
|
command(sys.executable, 'tests/retry_limit.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
|
||||||
|
|
||||||
|
print('\nBefore persistence:', flush=True)
|
||||||
|
state()
|
||||||
|
command(sys.executable, 'tests/resilience.py', '--mode', 'persistence', '--action-script', 'scripts/restart.sh',
|
||||||
|
'--base-url', BASE_URL, '--ca-file', CA_FILE)
|
||||||
|
wait()
|
||||||
|
print('\nAfter persistence:', flush=True)
|
||||||
|
state()
|
||||||
|
command(sys.executable, 'tests/resilience.py', '--mode', 'failover', '--action-script', 'scripts/stop-one.sh',
|
||||||
|
'--base-url', BASE_URL, '--ca-file', CA_FILE)
|
||||||
|
state()
|
||||||
|
command('docker', 'compose', 'ps', '--all')
|
||||||
|
command('docker', 'compose', 'up', '-d', 'api1', 'api2', 'worker')
|
||||||
|
wait()
|
||||||
|
command(sys.executable, 'tests/attachment_failover.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
|
||||||
|
command(sys.executable, 'tests/storage_failure.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
|
||||||
|
wait()
|
||||||
|
command(sys.executable, 'tests/observability.py')
|
||||||
|
|
||||||
|
anonymous_probe = '''import os,ssl,psycopg,urllib.request,urllib.error
|
||||||
|
from app.secrets import load_secrets
|
||||||
|
load_secrets()
|
||||||
|
with psycopg.connect(os.environ['DATABASE_URL']) as db:
|
||||||
|
ident=str(db.execute("SELECT id FROM attachments WHERE doc->>'status'='ready' LIMIT 1").fetchone()[0])
|
||||||
|
url=os.environ['S3_ENDPOINT']+'/'+os.environ['S3_ORIGINAL_BUCKET']+'/original/'+ident
|
||||||
|
ctx=ssl.create_default_context(cafile=os.environ['S3_CA_CERT'])
|
||||||
|
try:
|
||||||
|
urllib.request.urlopen(url,context=ctx,timeout=5)
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
assert e.code in (401,403), e.code
|
||||||
|
print('PASS: anonymous GET of existing private S3 object denied:',e.code)
|
||||||
|
else:
|
||||||
|
raise AssertionError('Private object publicly accessible')
|
||||||
|
'''
|
||||||
|
print('\nChecking private bucket from the application network', flush=True)
|
||||||
|
subprocess.run(['docker', 'compose', 'exec', '-T', 'api1', 'python', '-c', anonymous_probe], check=True)
|
||||||
|
command('docker', 'compose', 'ps')
|
||||||
|
print('\nPASS: all recorded checks', flush=True)
|
||||||
@@ -1,19 +1,34 @@
|
|||||||
# Модель угроз — заполнить
|
# Модель угроз — lab7
|
||||||
|
|
||||||
## Активы и акторы
|
## Активы и акторы
|
||||||
|
|
||||||
TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда.
|
Активы: пароли пользователей, session tokens, сообщения и изображения, membership чатов, учётные данные PostgreSQL/S3/RabbitMQ, AppRole identities, CA и leaf private keys, OpenBao recovery material, логи/метрики/traces. В тестах используются только синтетические пользователи и изображения.
|
||||||
|
|
||||||
|
Акторы: внешний клиент в сети; участник одного чата; пользователь вне чата; скомпрометированная API-реплика или worker; оператор учебного host. Внешний клиент может отправлять произвольные HTTP запросы, подставлять `X-User-Id`, повторять запросы и приносить собственные сертификаты. Предполагается, что TLS и Docker daemon на host работают корректно. Атакующий с root-доступом к host, CA private key или операторским OpenBao shares выходит за границы защиты этого локального стенда.
|
||||||
|
|
||||||
## Границы доверия
|
## Границы доверия
|
||||||
|
|
||||||
TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача.
|
Клиент приходит только на loopback HTTPS HAProxy. HAProxy — единственный вход к API и предъявляет отдельный mTLS client certificate. API/worker подключаются к своим зависимостям с TLS-проверкой сервера, отдельными credentials и ограниченными правами. OpenBao file storage и его operator recovery материал принадлежат локальному оператору. API/worker получают secrets через AppRole и не получают root token. OTel Collector принимает OTLP только с mTLS identities API/worker; backends и Grafana используют отдельные client identities. Подробности и явные plaintext boundaries см. в [матрице доверия](../contracts/trust-matrix.md).
|
||||||
|
|
||||||
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение |
|
## Угрозы и контроли
|
||||||
|
|
||||||
|
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательная проверка | Остаточное ограничение |
|
||||||
| --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO | TODO |
|
| Пользователь вне чата перебирает известный UUID чата/вложения или подставляет `X-User-Id` в запрос участника | Доступ определяется Bearer session и membership, а не идентификатором из заголовка/URL | Общая auth dependency и проверки членства для metadata/content/link; сервер сам выводит sender | `make test`: outsider получает 404; `X-User-Id` другого пользователя не меняет Bearer identity; raw/неверная сессия получает 401 | Нет публичного удаления; созданные тестовые данные очищаются удалением отдельного volume |
|
||||||
|
| Внешний клиент подключается по HTTPS с чужой CA либо пытается обойти LB прямым вызовом API | Только доверенный ingress достигает бизнес API | Проверяемый TLS на ingress; API ports не published; API требует client cert и сверяет URI SAN с точной LB identity | `python3 tests/security_runtime.py --ca-file .local/pki/external-ca.crt`: доверенный client проходит, без сертификата/чужой CA — handshake отказ, доверенный cert с чужой identity — 403 | Host и Docker network остаются доверенной частью одного компьютера |
|
||||||
На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки.
|
| Злоумышленник получает AppRole token/SecretID API и пробует прочитать worker credentials или изменить KV | Сервис может читать только свой secret и не может менять secret store | Раздельные AppRole, short-lived token, read-only KV v2 policies, runtime allowlist ключей | `docker compose exec -T api1 python tests/component_security.py` проверяет собственный path = 200, другой path и write = 403 | SecretID долгоживущий (TTL 720 ч); автоматический rollover/revoke не заявлен для уровня 3 |
|
||||||
|
| Скомпрометированный API использует DB password для чтения/изменения worker-only таблиц либо destructive операции | API и worker ограничены таблицами/операциями своей роли | Отдельные PostgreSQL roles и grants; соединение `verify-full` через service CA | `tests/component_security.py` вызывает запрещённое действие и ожидает `InsufficientPrivilege` | PostgreSQL остаётся одним локальным процессом; администратор DB имеет полный доступ |
|
||||||
|
| Скомпрометированный API/worker читает или перезаписывает объекты вне своего S3 назначения | Приватные файлы доступны только сервисам с назначенным bucket/prefix правом | Разные S3 keys и policies; TLS; backend выдаёт файл только после авторизации по чату | `tests/component_security.py`, public smoke outsider checks и anonymous object check в `scripts/verify.py` | SeaweedFS master/volume/filer используют plaintext внутри отдельной локальной Compose сети |
|
||||||
|
| Скомпрометированный API/worker пытается читать произвольные очереди либо подделать/снять чужие задания | Rabbit identity разрешает только очередь `attachment.process.v1` и нужные операции producer/consumer | AMQPS с hostname check; разные API/worker users; ACL configure по queue name, default-exchange write, worker read | `tests/component_security.py` объявляет `forbidden.security.probe` и ожидает broker 403; `tests/worker_flow.py` проверяет реальные job delivery | Клиентский mTLS к RabbitMQ не входит в целевой уровень 3; credentials хранятся статически в OpenBao KV |
|
||||||
|
| Посторонний сервис отправляет произвольные telemetry данные или читает их без разрешённой identity | OTLP ingress и telemetry backends доступны только доверенным workload и Grafana | OTel receiver требует mTLS CA; API/worker имеют разные URI SAN; Prometheus/Loki/Tempo HTTP query endpoints требуют backend mTLS | `tests/observability.py` проверяет данные обеих identities и коррелированный API→worker trace; отсутствие client cert можно проверить TLS probe для OTLP входа | Автоматическая ротация ingest/backend identities и аудит expiry относятся к уровню 4 |
|
||||||
|
| S3 или broker недоступен во время upload; API пытается выдать ложный `ready` либо проглатывает отказ | Клиент видит контролируемый отказ, а вложение не объявляется готовым без сохранённых objects | Ограниченный timeout, durable outbox, broker publisher confirm, `ready` после сохранения обоих объектов | `tests/storage_failure.py` отключает S3 и ждёт 503; worker flow ждёт `ready` только после обработки | При полном отказе единственного DB/S3 host сервис недоступен; standby/backup не реализованы |
|
||||||
|
|
||||||
## Lifecycle и инциденты
|
## Lifecycle и инциденты
|
||||||
|
|
||||||
TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском.
|
`scripts/bootstrap.py` создаёт локальную PKI, random credentials, OpenBao non-dev file storage, policies/AppRole и сервисные контейнеры. Secrets, keys, operator token и unseal shares игнорируются Git и имеют права каталога 0700 / файла 0600. Recovery JSON остаётся на host, не монтируется в контейнеры; оператор защищает host аккаунт и размещает резервную копию recovery material отдельно от репозитория и Docker volumes.
|
||||||
|
|
||||||
|
AppRole выдаёт token с TTL 10 минут (максимум 30 минут); API/worker получают свой KV secret при старте и не сохраняют token. SecretID ограничен сроком 720 часов; повторный bootstrap перевыпускает его и пересоздаёт ограниченную identity. Service leaf сертификаты имеют срок 90 дней, CA — 825 дней. На уровне 3 automated renewal, seamless rotation и revoke test не заявлены. При подозрении на компрометацию сервисной identity оператор отзывает SecretID, выполняет bootstrap и перезапускает только затронутые app services; при компрометации CA/recovery material следует создать новый защищённый стенд, выпустить новую PKI и пересоздать сервисные credentials.
|
||||||
|
|
||||||
|
При рестарте контейнера OpenBao сохраняет file storage на named volume, но может стартовать sealed; оператор запускает `python3 scripts/unseal.py` либо `python3 scripts/bootstrap.py`, recovery shares не печатаются. Если OpenBao закрыт после старта приложения, текущее приложение продолжает использовать уже загруженные credentials; новый старт API/worker завершится ошибкой, а не переключится на plaintext или root token.
|
||||||
|
|
||||||
|
Модель не включает потерю/компрометацию Docker host, аппаратный TPM/HSM, кластерную отказоустойчивость, автоматическую ротацию, эксплуатацию zero-day в образах и независимый penetration test. Уровень 4/5 и image-scan triage не заявлены.
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
"""Additional grade-3 checks: concurrent replay and invalid uploads."""
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
import uuid
|
||||||
|
import struct
|
||||||
|
import zlib
|
||||||
|
import subprocess
|
||||||
|
from client import Client, LAB, arguments, check, run
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args = arguments('Extra acceptance checks')
|
||||||
|
c = Client(args.base_url,args.ca_file)
|
||||||
|
alice,bob,eve,chat = c.bootstrap()
|
||||||
|
key = uuid.uuid4().hex
|
||||||
|
def send(_):
|
||||||
|
return c.message(alice,chat,'Concurrent retry',key=key)['json']
|
||||||
|
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||||
|
results = list(pool.map(send,range(16)))
|
||||||
|
check(all(r==results[0] for r in results),'concurrent replay created different messages')
|
||||||
|
print('PASS: 16 concurrent retries return one message')
|
||||||
|
if LAB >= 4:
|
||||||
|
path = '/api/v1/chats/'+chat['id']+'/attachments'
|
||||||
|
content = open('tests/fixtures/sample.png','rb').read()
|
||||||
|
c.call('POST',path+'?filename=../x.png',400,actor=alice,raw=content,headers={'Content-Type':'image/png'})
|
||||||
|
c.call('POST',path+'?filename=x.jpg',415,actor=alice,raw=content,headers={'Content-Type':'image/jpeg'})
|
||||||
|
c.call('POST',path+'?filename=x.png',415,actor=alice,raw=b'broken',headers={'Content-Type':'image/png'})
|
||||||
|
c.call('POST',path+'?filename=x.png',413,actor=alice,raw=b'x'*(10485760+1),headers={'Content-Type':'image/png'})
|
||||||
|
# A real valid PNG >40 million pixels, highly compressible on the wire.
|
||||||
|
def chunk(kind, data):
|
||||||
|
return struct.pack('!I',len(data))+kind+data+struct.pack('!I',zlib.crc32(kind+data)&0xffffffff)
|
||||||
|
compressor = zlib.compressobj()
|
||||||
|
compressed = b''.join(compressor.compress(b'\0'*10001) for _ in range(4001))+compressor.flush()
|
||||||
|
huge = b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!IIBBBBB',10000,4001,8,0,0,0,0))+chunk(b'IDAT',compressed)+chunk(b'IEND',b'')
|
||||||
|
c.call('POST',path+'?filename=huge.png',413,actor=alice,raw=huge,headers={'Content-Type':'image/png'})
|
||||||
|
jpeg = subprocess.check_output(['docker','compose','exec','-T','api1','python','-c',"from PIL import Image; import sys; Image.new('RGB',(8,8),'red').save(sys.stdout.buffer,format='JPEG')"])
|
||||||
|
uploaded = c.call('POST',path+'?filename=real.jpg',202,actor=alice,raw=jpeg,headers={'Content-Type':'image/jpeg'},schema='Attachment')['json']
|
||||||
|
uploaded = c.wait_ready(bob,uploaded)
|
||||||
|
downloaded = c.call('GET','/api/v1/attachments/'+uploaded['id']+'/content',actor=bob)
|
||||||
|
check(downloaded['bytes']==jpeg,'JPEG original changed')
|
||||||
|
other = c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Another chat','member_ids':[alice['id']]},schema='Chat')['json']
|
||||||
|
c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=alice,body={'text':'','attachment_ids':[uploaded['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||||
|
print('PASS: real JPEG roundtrip; >40 million pixels rejected; cross-chat attachment rejected')
|
||||||
|
print('PASS: unsafe filename, MIME mismatch, corruption and byte limit')
|
||||||
|
|
||||||
|
if __name__=='__main__':
|
||||||
|
run(main)
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
"""Stop the API that accepted a file after its asynchronous job is ready."""
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
from client import Client, arguments, check, run
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args=arguments('Upload/download failover on both APIs')
|
||||||
|
c=Client(args.base_url,args.ca_file)
|
||||||
|
alice,bob,eve,chat=c.bootstrap()
|
||||||
|
content=open('tests/fixtures/sample.png','rb').read()
|
||||||
|
path='/api/v1/chats/'+chat['id']+'/attachments?filename=sample.png'
|
||||||
|
for service in ('api1','api2'):
|
||||||
|
cid=subprocess.check_output(['docker','compose','ps','-q',service],text=True).strip()
|
||||||
|
env=subprocess.check_output(['docker','inspect','--format','{{range .Config.Env}}{{println .}}{{end}}',cid],text=True)
|
||||||
|
target=next((line.split('=',1)[1] for line in env.splitlines() if line.startswith('APP_INSTANCE_ID=')),None)
|
||||||
|
check(bool(target),'API instance identity is missing')
|
||||||
|
for _ in range(20):
|
||||||
|
uploaded=c.call('POST',path,202,actor=alice,raw=content,headers={'Content-Type':'image/png'},schema='Attachment')
|
||||||
|
if uploaded['headers']['X-Instance-Id']==target: break
|
||||||
|
else: raise AssertionError('Target API not observed through LB')
|
||||||
|
att=uploaded['json']; c.wait_ready(alice,att)
|
||||||
|
c.message(alice,chat,'',attachments=[att['id']])
|
||||||
|
started=time.monotonic()
|
||||||
|
try:
|
||||||
|
subprocess.run(['scripts/stop-one.sh'],env=dict(os.environ,TARGET_INSTANCE_ID=target),check=True,stdout=subprocess.DEVNULL)
|
||||||
|
while time.monotonic()-started<10:
|
||||||
|
try: downloaded=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)
|
||||||
|
except Exception:
|
||||||
|
time.sleep(.2); continue
|
||||||
|
check(downloaded['headers']['X-Instance-Id']!=target,'stopped API still responds')
|
||||||
|
check(downloaded['bytes']==content,'original changed')
|
||||||
|
print('PASS:',service,'downloaded original via other API in',round(time.monotonic()-started,3),'s; SHA-256',hashlib.sha256(content).hexdigest(),flush=True)
|
||||||
|
break
|
||||||
|
else: raise AssertionError('Download did not recover within 10 seconds')
|
||||||
|
finally:
|
||||||
|
subprocess.run(['docker','compose','start',service],check=True)
|
||||||
|
for _ in range(30):
|
||||||
|
health=subprocess.check_output(['docker','inspect','--format','{{.State.Health.Status}}',cid],text=True).strip()
|
||||||
|
if health=='healthy': time.sleep(2); break
|
||||||
|
time.sleep(1)
|
||||||
|
else: raise AssertionError('API did not recover')
|
||||||
|
|
||||||
|
if __name__=='__main__': run(main)
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Run from the API/worker container to verify scoped runtime identities."""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
||||||
|
|
||||||
|
from app.secrets import load_secrets
|
||||||
|
load_secrets()
|
||||||
|
|
||||||
|
|
||||||
|
def bao(path,method='GET',body=None,token=None):
|
||||||
|
ctx=ssl.create_default_context(cafile=os.environ['BAO_CA_CERT'])
|
||||||
|
data=None if body is None else json.dumps(body).encode()
|
||||||
|
req=urllib.request.Request(os.environ['BAO_ADDR'].rstrip('/')+'/v1/'+path,data=data,method=method)
|
||||||
|
if token: req.add_header('X-Vault-Token',token)
|
||||||
|
if data: req.add_header('Content-Type','application/json')
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req,context=ctx,timeout=5) as r: return r.status,json.load(r)
|
||||||
|
except urllib.error.HTTPError as e: return e.code,{}
|
||||||
|
|
||||||
|
|
||||||
|
role=os.environ['APP_ROLE']
|
||||||
|
service_path='messenger/'+role
|
||||||
|
role_id=open(os.environ['BAO_ROLE_ID_FILE']).read().strip()
|
||||||
|
secret_id=open(os.environ['BAO_SECRET_ID_FILE']).read().strip()
|
||||||
|
_,login=bao('auth/approle/login','POST',{'role_id':role_id,'secret_id':secret_id})
|
||||||
|
token=login['auth']['client_token']
|
||||||
|
assert bao('kv/data/'+service_path,token=token)[0]==200
|
||||||
|
other='messenger/worker' if role=='api' else 'messenger/api'
|
||||||
|
assert bao('kv/data/'+other,token=token)[0]==403
|
||||||
|
assert bao('kv/data/'+service_path,'POST',{'data':{'probe':'denied'}},token)[0]==403
|
||||||
|
print('PASS: AppRole reads its own secret only; cross-read and write denied')
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from psycopg.errors import InsufficientPrivilege
|
||||||
|
with psycopg.connect(os.environ['DATABASE_URL']) as db:
|
||||||
|
if role=='api':
|
||||||
|
query='DELETE FROM attachments WHERE false'
|
||||||
|
else:
|
||||||
|
query='SELECT username FROM users LIMIT 1'
|
||||||
|
try:
|
||||||
|
db.execute(query)
|
||||||
|
except InsufficientPrivilege:
|
||||||
|
db.rollback()
|
||||||
|
else:
|
||||||
|
raise AssertionError('database role exceeded its table privileges')
|
||||||
|
print('PASS: PostgreSQL role is limited to its assigned tables and actions')
|
||||||
|
|
||||||
|
import boto3
|
||||||
|
from botocore.exceptions import ClientError
|
||||||
|
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=os.environ['S3_CA_CERT'],
|
||||||
|
config=boto3.session.Config(s3={'addressing_style':'path'}))
|
||||||
|
try:
|
||||||
|
original=os.environ['S3_ORIGINAL_BUCKET']
|
||||||
|
if role=='api': s3.put_object(Bucket=original,Key='security-probe',Body=b'')
|
||||||
|
else: s3.get_object(Bucket=original,Key='security-probe')
|
||||||
|
except ClientError as exc:
|
||||||
|
assert exc.response['ResponseMetadata']['HTTPStatusCode'] in (401,403)
|
||||||
|
else:
|
||||||
|
raise AssertionError('S3 identity accessed a forbidden prefix')
|
||||||
|
print('PASS: S3 identity cannot use a prefix outside its scoped policy')
|
||||||
|
|
||||||
|
import pika
|
||||||
|
params=pika.URLParameters(os.environ['BROKER_URL'])
|
||||||
|
params.ssl_options=pika.SSLOptions(ssl.create_default_context(cafile=os.environ['BROKER_CA_CERT']),'broker')
|
||||||
|
connection=pika.BlockingConnection(params)
|
||||||
|
channel=connection.channel()
|
||||||
|
try:
|
||||||
|
channel.queue_declare(queue='forbidden.security.probe',durable=True)
|
||||||
|
except pika.exceptions.ChannelClosedByBroker as exc:
|
||||||
|
assert exc.reply_code==403
|
||||||
|
else:
|
||||||
|
channel.close(); connection.close()
|
||||||
|
raise AssertionError('broker identity configured a queue outside its permission')
|
||||||
|
connection.close()
|
||||||
|
print('PASS: RabbitMQ identity is restricted to the attachment queue')
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
"""Verify the protected Prometheus, Loki, Tempo and Grafana endpoints."""
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import ssl
|
||||||
|
import time
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
PKI = ROOT / '.local' / 'pki'
|
||||||
|
PROM = os.getenv('PROM_URL', 'https://localhost:9097')
|
||||||
|
LOKI = os.getenv('LOKI_URL', 'https://localhost:3107')
|
||||||
|
TEMPO = os.getenv('TEMPO_URL', 'https://localhost:3207')
|
||||||
|
GRAFANA = os.getenv('GRAFANA_URL', 'https://localhost:3007')
|
||||||
|
|
||||||
|
|
||||||
|
def context_for(url):
|
||||||
|
context = ssl.create_default_context(cafile=str(PKI / 'service-ca.crt'))
|
||||||
|
if url.startswith((PROM, LOKI, TEMPO)):
|
||||||
|
context.load_cert_chain(str(PKI / 'backend-grafana.crt'), str(PKI / 'backend-grafana.key'))
|
||||||
|
return context
|
||||||
|
|
||||||
|
|
||||||
|
def get_json(url, auth=None):
|
||||||
|
request = urllib.request.Request(url)
|
||||||
|
if auth:
|
||||||
|
token = base64.b64encode((auth[0] + ':' + auth[1]).encode()).decode()
|
||||||
|
request.add_header('Authorization', 'Basic ' + token)
|
||||||
|
with urllib.request.urlopen(request, context=context_for(url), timeout=8) as response:
|
||||||
|
return json.load(response)
|
||||||
|
|
||||||
|
|
||||||
|
def grafana_password():
|
||||||
|
value = os.getenv('GRAFANA_PASSWORD')
|
||||||
|
if value:
|
||||||
|
return value
|
||||||
|
env_file = ROOT / '.env'
|
||||||
|
if env_file.exists():
|
||||||
|
for line in env_file.read_text().splitlines():
|
||||||
|
if line.startswith('GRAFANA_PASSWORD='):
|
||||||
|
return line.split('=', 1)[1]
|
||||||
|
return 'local-grafana-password-only'
|
||||||
|
|
||||||
|
|
||||||
|
def prom_value(expr):
|
||||||
|
doc = get_json(PROM + '/api/v1/query?' + urllib.parse.urlencode({'query': expr}))
|
||||||
|
assert doc['status'] == 'success', doc
|
||||||
|
result = doc['data']['result']
|
||||||
|
return float(result[0]['value'][1]) if result else 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
deadline = time.time() + 90
|
||||||
|
api_total = worker_total = 0.0
|
||||||
|
while time.time() < deadline:
|
||||||
|
try:
|
||||||
|
api_total = prom_value('sum(messenger_http_requests_total)')
|
||||||
|
worker_total = prom_value('sum(messenger_jobs_processed_total)')
|
||||||
|
if api_total > 0 and worker_total > 0:
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
time.sleep(2)
|
||||||
|
assert api_total > 0, 'API request metric not found in Prometheus'
|
||||||
|
assert worker_total > 0, 'worker job metric not found in Prometheus'
|
||||||
|
|
||||||
|
start = int((time.time() - 900) * 1_000_000_000)
|
||||||
|
end = time.time_ns()
|
||||||
|
q = '{service_name="messenger-api"} |= "http.request.completed"'
|
||||||
|
url = LOKI + '/loki/api/v1/query_range?' + urllib.parse.urlencode(
|
||||||
|
{'query': q, 'start': str(start), 'end': str(end), 'limit': '20', 'direction': 'backward'})
|
||||||
|
logs = get_json(url)
|
||||||
|
assert logs['status'] == 'success' and logs['data']['result'], 'API structured logs not found in Loki'
|
||||||
|
|
||||||
|
deadline = time.time() + 90
|
||||||
|
while time.time() < deadline:
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(TEMPO + '/ready', context=context_for(TEMPO), timeout=5) as response:
|
||||||
|
if response.status == 200:
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
time.sleep(2)
|
||||||
|
else:
|
||||||
|
raise AssertionError('Tempo did not become ready')
|
||||||
|
|
||||||
|
def trace_search(service):
|
||||||
|
params = {'tags': 'service.name=' + service, 'start': str(int(time.time() - 900)),
|
||||||
|
'end': str(int(time.time())), 'limit': '20'}
|
||||||
|
return get_json(TEMPO + '/api/search?' + urllib.parse.urlencode(params)).get('traces', [])
|
||||||
|
|
||||||
|
api_traces = worker_traces = []
|
||||||
|
deadline = time.time() + 90
|
||||||
|
while time.time() < deadline:
|
||||||
|
try:
|
||||||
|
api_traces = trace_search('messenger-api')
|
||||||
|
worker_traces = trace_search('messenger-worker')
|
||||||
|
if api_traces and worker_traces:
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
time.sleep(3)
|
||||||
|
assert api_traces, 'API traces not found in Tempo'
|
||||||
|
assert worker_traces, 'worker traces not found in Tempo'
|
||||||
|
|
||||||
|
correlated_trace = None
|
||||||
|
deadline = time.time() + 90
|
||||||
|
while time.time() < deadline and correlated_trace is None:
|
||||||
|
q = '{service_name="messenger-worker"} |= "worker.job.completed"'
|
||||||
|
params = {'query': q, 'start': str(int((time.time() - 900) * 1_000_000_000)),
|
||||||
|
'end': str(time.time_ns()), 'limit': '20', 'direction': 'backward'}
|
||||||
|
rows = get_json(LOKI + '/loki/api/v1/query_range?' + urllib.parse.urlencode(params))['data']['result']
|
||||||
|
for row in rows:
|
||||||
|
trace_id = row['stream'].get('trace_id')
|
||||||
|
if not trace_id:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
trace_doc = get_json(TEMPO + '/api/traces/' + trace_id)
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
services = set()
|
||||||
|
for batch in trace_doc.get('batches', []):
|
||||||
|
for attr in batch.get('resource', {}).get('attributes', []):
|
||||||
|
if attr.get('key') == 'service.name':
|
||||||
|
services.add(attr.get('value', {}).get('stringValue'))
|
||||||
|
if {'messenger-api', 'messenger-worker'} <= services:
|
||||||
|
correlated_trace = trace_id
|
||||||
|
break
|
||||||
|
if correlated_trace is None:
|
||||||
|
time.sleep(2)
|
||||||
|
assert correlated_trace, 'worker log trace is not correlated with API trace'
|
||||||
|
|
||||||
|
health = get_json(GRAFANA + '/api/health')
|
||||||
|
assert health.get('database') == 'ok', 'Grafana is not ready'
|
||||||
|
password = grafana_password()
|
||||||
|
dashboard = get_json(GRAFANA + '/api/dashboards/uid/messenger-observability', ('admin', password))
|
||||||
|
assert dashboard.get('dashboard', {}).get('uid') == 'messenger-observability', 'provisioned dashboard is missing'
|
||||||
|
|
||||||
|
print('PASS: protected Prometheus/Loki/Tempo; API and worker telemetry; correlated traces; Grafana dashboard')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""Inject a corrupt staged object and prove bounded failure is visible."""
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
from client import Client, arguments, check, run
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args=arguments('Bounded retry and safe failed state')
|
||||||
|
c=Client(args.base_url,args.ca_file,timeout=10)
|
||||||
|
alice,bob,eve,chat=c.bootstrap()
|
||||||
|
subprocess.run(['docker','compose','stop','worker'],check=True,stdout=subprocess.DEVNULL)
|
||||||
|
try:
|
||||||
|
att,original=c.attachment(alice,chat)
|
||||||
|
code="from app.worker import s3,BUCKET; import os,psycopg; c=psycopg.connect(os.environ['DATABASE_URL']); k=c.execute('SELECT stage_key FROM attachments WHERE id=%s',(\""+att['id']+"\",)).fetchone()[0]; s3().put_object(Bucket=BUCKET,Key=k,Body=b'corrupt image data',ContentType='image/png'); c.close()"
|
||||||
|
subprocess.run(['docker','compose','exec','-T','api1','python','-c',code],check=True,stdout=subprocess.DEVNULL)
|
||||||
|
finally:
|
||||||
|
subprocess.run(['docker','compose','up','-d','worker'],check=True,stdout=subprocess.DEVNULL)
|
||||||
|
deadline=time.monotonic()+60
|
||||||
|
while time.monotonic()<deadline:
|
||||||
|
att=c.call('GET','/api/v1/attachments/'+att['id'],actor=bob,schema='Attachment')['json']
|
||||||
|
if att['status']=='failed': break
|
||||||
|
time.sleep(.5)
|
||||||
|
check(att['status']=='failed','corrupt image did not reach bounded failed state')
|
||||||
|
check(att['error_code'] in ('invalid_image','retry_exhausted'),'unexpected public failure code')
|
||||||
|
c.call('GET','/api/v1/attachments/'+att['id']+'/content',409,actor=bob)
|
||||||
|
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',409,actor=alice,
|
||||||
|
body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':'failed-attachment-test'})
|
||||||
|
print('PASS: corrupt job ended as failed after bounded retries; content and message attachment are rejected')
|
||||||
|
|
||||||
|
if __name__=='__main__': run(main)
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Local negative checks for TLS identity, secret scope, ACL and session storage."""
|
||||||
|
import argparse
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from client import Client, check
|
||||||
|
|
||||||
|
ROOT=Path(__file__).resolve().parents[1]
|
||||||
|
PKI=ROOT/'.local/pki'
|
||||||
|
|
||||||
|
|
||||||
|
def probe(mode):
|
||||||
|
p=subprocess.run(['docker','compose','run','--rm','-T','--no-deps','tls-probe',
|
||||||
|
'--url','https://api1:8443','--mode',mode],cwd=ROOT,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
|
||||||
|
if p.returncode:
|
||||||
|
raise AssertionError('internal mTLS probe '+mode+' failed: '+p.stdout[-800:])
|
||||||
|
print(p.stdout.strip())
|
||||||
|
|
||||||
|
|
||||||
|
def psql(query):
|
||||||
|
return subprocess.check_output(['docker','compose','exec','-T','postgres','psql','-U','postgres','-d','messenger','-At','-c',query],cwd=ROOT,text=True).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser=argparse.ArgumentParser()
|
||||||
|
parser.add_argument('--base-url',default='https://localhost:8443')
|
||||||
|
parser.add_argument('--ca-file',default=str(PKI/'external-ca.crt'))
|
||||||
|
args=parser.parse_args()
|
||||||
|
c=Client(args.base_url,args.ca_file)
|
||||||
|
c.call('GET','/health/ready',schema='Health')
|
||||||
|
print('PASS: external HTTPS endpoint is trusted')
|
||||||
|
subprocess.run(['docker','compose','build','tls-probe'],cwd=ROOT,check=True,
|
||||||
|
stdout=subprocess.DEVNULL,stderr=subprocess.STDOUT)
|
||||||
|
for mode in ('trusted','no-cert','untrusted-ca','wrong-identity'):
|
||||||
|
probe(mode)
|
||||||
|
|
||||||
|
# The login rate table is shared in PostgreSQL, so both API replicas enforce it.
|
||||||
|
username='rate_'+uuid.uuid4().hex
|
||||||
|
auth='Basic '+base64.b64encode((username+':wrong-pass').encode()).decode()
|
||||||
|
for _ in range(5): c.call('POST','/api/v1/auth/sessions',401,headers={'Authorization':auth})
|
||||||
|
limited=c.call('POST','/api/v1/auth/sessions',429,headers={'Authorization':auth})
|
||||||
|
check(int(limited['headers'].get('Retry-After','0'))>=1,'429 response lacks Retry-After')
|
||||||
|
print('PASS: login limiter returns 429 with Retry-After across shared database')
|
||||||
|
|
||||||
|
user=c.user('hash')
|
||||||
|
stored=psql("SELECT password FROM users WHERE username='"+user['registration']['username']+"'")
|
||||||
|
check(bool(re.fullmatch(r'\$argon2id\$v=19\$m=19456,t=2,p=1\$[^$]+\$[^$]+',stored)), 'password is not Argon2id m=19456,t=2,p=1')
|
||||||
|
token_hash=hashlib.sha256(user['token'].encode()).hexdigest()
|
||||||
|
check(psql("SELECT count(*) FROM sessions WHERE token='"+token_hash+"'")=='1','session token hash is not stored')
|
||||||
|
check(psql("SELECT count(*) FROM sessions WHERE token='"+user['token']+"'")=='0','raw session token was stored')
|
||||||
|
expired=c.user('expiry')
|
||||||
|
expired_hash=hashlib.sha256(expired['token'].encode()).hexdigest()
|
||||||
|
check(psql("UPDATE sessions SET expires_at=now()-interval '1 second' WHERE token='"+expired_hash+"'")=='UPDATE 1','could not prepare expired-session probe')
|
||||||
|
c.call('GET','/api/v1/users/me',401,actor=expired)
|
||||||
|
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=user)
|
||||||
|
c.call('GET','/api/v1/users/me',401,actor=user)
|
||||||
|
print('PASS: password parameters, hashed session tokens, expiry and logout')
|
||||||
|
|
||||||
|
for service in ('api1','worker'):
|
||||||
|
r=subprocess.run(['docker','compose','exec','-T',service,'python','tests/component_security.py'],cwd=ROOT,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
|
||||||
|
if r.returncode: raise AssertionError(service+' component security checks failed: '+r.stdout[-1200:])
|
||||||
|
print(r.stdout.strip())
|
||||||
|
|
||||||
|
# API listeners are private and contain no database/S3/broker app credentials in container env.
|
||||||
|
docs=[json.loads(line) for line in subprocess.check_output(['docker','compose','ps','--format','json'],cwd=ROOT,text=True).splitlines() if line.strip()]
|
||||||
|
for service in ('api1','api2'):
|
||||||
|
doc=next(x for x in docs if x.get('Service')==service)
|
||||||
|
check(not doc.get('Publishers'),service+' published a direct API port')
|
||||||
|
cid=doc['ID']
|
||||||
|
config=json.loads(subprocess.check_output(['docker','inspect',cid],cwd=ROOT,text=True))[0]
|
||||||
|
check(config['Config']['User']=='10001:10001',service+' is not non-root')
|
||||||
|
host=config['HostConfig']
|
||||||
|
check(not host.get('Privileged') and host.get('ReadonlyRootfs'),service+' container hardening is missing')
|
||||||
|
check('ALL' in (host.get('CapDrop') or []),service+' did not drop capabilities')
|
||||||
|
env=config['Config'].get('Env',[])
|
||||||
|
check(not any(item.startswith(prefix+'=') for item in env for prefix in ('DATABASE_URL','S3_ACCESS_KEY','S3_SECRET_KEY','BROKER_URL','BAO_TOKEN')),
|
||||||
|
service+' contains a runtime credential in its environment')
|
||||||
|
check(not any('/var/run/docker.sock' in (item.get('Source','')+' '+item.get('Destination','')) for item in (config.get('Mounts') or [])),service+' has Docker socket access')
|
||||||
|
print('PASS: API ports are private; non-root/read-only/cap-drop; no runtime credentials or Docker socket')
|
||||||
|
|
||||||
|
if __name__=='__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""Check readiness and upload when S3 is unavailable; always restore S3."""
|
||||||
|
import subprocess
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from client import Client, arguments, run
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args = arguments('Storage failure')
|
||||||
|
c = Client(args.base_url,args.ca_file)
|
||||||
|
alice,bob,eve,chat = c.bootstrap()
|
||||||
|
data = open('tests/fixtures/sample.png','rb').read()
|
||||||
|
try:
|
||||||
|
subprocess.run(['docker','compose','stop','-t','2','s3'],check=True)
|
||||||
|
for path, probe in [('/health/ready', {'expected':503}),
|
||||||
|
('/api/v1/chats/'+chat['id']+'/attachments?filename=sample.png', {
|
||||||
|
'method':'POST','body_b64':base64.b64encode(data).decode(),
|
||||||
|
'headers':{'Content-Type':'image/png','Authorization':'Bearer '+alice['token']},'expected':503})]:
|
||||||
|
cmd=['docker','compose','run','--rm','-T','--no-deps','tls-probe','--url','https://api1:8443',
|
||||||
|
'--mode','trusted','--path',path]
|
||||||
|
subprocess.run(cmd,input=json.dumps(probe),text=True,check=True)
|
||||||
|
print('PASS: S3 down returns 503 for readiness and upload')
|
||||||
|
finally:
|
||||||
|
subprocess.run(['docker','compose','start','s3'],check=True)
|
||||||
|
for _ in range(60):
|
||||||
|
try:
|
||||||
|
c.call('GET','/health/ready')
|
||||||
|
print('PASS: S3 restored')
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
time.sleep(1)
|
||||||
|
else:
|
||||||
|
raise AssertionError('S3 did not recover')
|
||||||
|
|
||||||
|
if __name__=='__main__':
|
||||||
|
run(main)
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""One-shot in-network mTLS probe used by security_runtime.py."""
|
||||||
|
import argparse
|
||||||
|
import base64
|
||||||
|
import http.client
|
||||||
|
import json
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
p=argparse.ArgumentParser()
|
||||||
|
p.add_argument('--url',required=True)
|
||||||
|
p.add_argument('--path',default='/health/ready')
|
||||||
|
p.add_argument('--mode',choices=('trusted','no-cert','untrusted-ca','wrong-identity'),required=True)
|
||||||
|
a=p.parse_args()
|
||||||
|
ctx=ssl.create_default_context(cafile='/run/certs/service-ca.crt')
|
||||||
|
if a.mode=='trusted':
|
||||||
|
ctx.load_cert_chain('/run/certs/lb-client.crt','/run/certs/lb-client.key')
|
||||||
|
elif a.mode=='untrusted-ca':
|
||||||
|
ctx.load_cert_chain('/run/certs/untrusted-client.crt','/run/certs/untrusted-client.key')
|
||||||
|
elif a.mode=='wrong-identity':
|
||||||
|
ctx.load_cert_chain('/run/certs/foreign-client.crt','/run/certs/foreign-client.key')
|
||||||
|
try:
|
||||||
|
raw=sys.stdin.read() if not sys.stdin.isatty() else ''
|
||||||
|
probe=json.loads(raw) if raw.strip() else {}
|
||||||
|
headers=probe.get('headers',{})
|
||||||
|
body=base64.b64decode(probe['body_b64']) if probe.get('body_b64') else None
|
||||||
|
request=urllib.request.Request(a.url.rstrip('/')+a.path,data=body,headers=headers,method=probe.get('method','GET'))
|
||||||
|
with urllib.request.urlopen(request,context=ctx,timeout=5) as response:
|
||||||
|
status=response.status
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
status=exc.code
|
||||||
|
except http.client.RemoteDisconnected:
|
||||||
|
if a.mode in ('no-cert','untrusted-ca'):
|
||||||
|
print('PASS: API rejected '+a.mode+' during TLS handshake')
|
||||||
|
raise SystemExit(0)
|
||||||
|
raise SystemExit('FAIL: unexpected TLS peer disconnect')
|
||||||
|
except urllib.error.URLError as exc:
|
||||||
|
if a.mode in ('no-cert','untrusted-ca') and isinstance(exc.reason,(ssl.SSLError,ConnectionResetError,http.client.RemoteDisconnected)):
|
||||||
|
print('PASS: API rejected '+a.mode+' during TLS handshake')
|
||||||
|
raise SystemExit(0)
|
||||||
|
raise SystemExit('FAIL: unexpected TLS probe error: '+type(exc.reason).__name__)
|
||||||
|
expected=probe.get('expected',200) if 'probe' in locals() else 200
|
||||||
|
if a.mode=='trusted' and status==expected:
|
||||||
|
print('PASS: API returned expected status '+str(status)+' for the allowlisted LB identity')
|
||||||
|
elif a.mode=='wrong-identity' and status==403:
|
||||||
|
print('PASS: API rejected a CA-signed certificate with the wrong SAN identity')
|
||||||
|
else:
|
||||||
|
raise SystemExit('FAIL: '+a.mode+' probe returned HTTP '+str(status))
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"""Demonstrate durable handoff while the worker is stopped and redelivery safety."""
|
||||||
|
import subprocess
|
||||||
|
from client import Client, arguments, check, run
|
||||||
|
|
||||||
|
|
||||||
|
def compose(*args):
|
||||||
|
subprocess.run(['docker','compose',*args],check=True,stdout=subprocess.DEVNULL)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args=arguments('Durable async image processing acceptance flow')
|
||||||
|
c=Client(args.base_url,args.ca_file,timeout=10)
|
||||||
|
alice,bob,eve,chat=c.bootstrap()
|
||||||
|
compose('stop','worker')
|
||||||
|
try:
|
||||||
|
att,original=c.attachment(alice,chat)
|
||||||
|
check(att['status']=='queued','upload should be durably queued while worker is stopped')
|
||||||
|
c.call('GET','/api/v1/attachments/'+att['id']+'/content',409,actor=bob)
|
||||||
|
msg=c.message(alice,chat,'',attachments=[att['id']])['json']
|
||||||
|
check(msg['attachment_ids']==[att['id']],'queued attachment could not be linked to message')
|
||||||
|
compose('restart','broker','api1','api2')
|
||||||
|
compose('up','-d','worker')
|
||||||
|
ready=c.wait_ready(bob,att,wait_seconds=60)
|
||||||
|
check(ready['status']=='ready' and len(ready['variants'])==1,'worker did not publish one ready thumbnail')
|
||||||
|
original_read=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)
|
||||||
|
check(original_read['bytes']==original,'original changed during async processing')
|
||||||
|
thumb=ready['variants'][0]
|
||||||
|
content=c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant=thumbnail',actor=bob)
|
||||||
|
check(content['bytes'] and len(content['bytes'])==thumb['size_bytes'],'thumbnail bytes do not match metadata')
|
||||||
|
# Redeliver the exact logical job. The ready state and deterministic object
|
||||||
|
# keys make this a no-op; it cannot create another variant.
|
||||||
|
code="import psycopg,os; from app.worker import publish; c=psycopg.connect(os.environ['DATABASE_URL']); p=c.execute('SELECT payload FROM attachment_jobs WHERE attachment_id=%s',(\""+att['id']+"\",)).fetchone()[0]; publish(p); publish(p); c.close()"
|
||||||
|
subprocess.run(['docker','compose','exec','-T','worker','python','-c',code],check=True,stdout=subprocess.DEVNULL)
|
||||||
|
check(c.wait_ready(bob,att)['variants']==ready['variants'],'duplicate delivery changed ready result')
|
||||||
|
print('PASS: stopped-worker upload returned 202, survived API/broker restart, and reached ready')
|
||||||
|
print('PASS: original preserved; repeated job delivery produced one identical thumbnail')
|
||||||
|
finally:
|
||||||
|
compose('up','-d','worker')
|
||||||
|
|
||||||
|
if __name__=='__main__':
|
||||||
|
run(main)
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# План демонстрации — лабораторная 7
|
||||||
|
|
||||||
|
1. Выполнить `python3 scripts/bootstrap.py`, показать две healthy API-реплики и TLS ingress. Не показывать секреты из `.env` или `.local`.
|
||||||
|
2. Запустить публичный smoke с CA: `make test BASE_URL=https://localhost:8443 CA_FILE=.local/pki/external-ca.crt`.
|
||||||
|
3. Показать `python3 tests/security_runtime.py --ca-file .local/pki/external-ca.crt`: разрешённый LB certificate проходит; отсутствие cert, чужая CA и URI SAN другого сервиса отвергаются.
|
||||||
|
4. Показать own-path allow и cross-path/write deny для API и worker в `tests/component_security.py`; рядом — DB/S3 permissions и RabbitMQ queue ACL.
|
||||||
|
5. Показать rate limit `429`, session expiry/logout и hashed session token без печати самого token.
|
||||||
|
6. Остановить worker, загрузить вложение, убедиться в `queued` и `409` для content; восстановить worker, получить `ready`, сравнить hash исходника и thumbnail. Повторно доставить ту же job.
|
||||||
|
7. Показать restart с сохранёнными volumes, отказ одной API-реплики, предсказуемый `503` при отключённом S3 и последующее восстановление.
|
||||||
|
8. Открыть локальные Grafana (3007) и Prometheus/Loki/Tempo (3007/9097/3107/3207): показать API и worker metrics, structured logs и trace между API и worker.
|
||||||
|
9. Завершить `make verify`, затем показать ограниченную модель угроз и честные ограничения целевого уровня 3 в `REPORT.md`.
|
||||||
|
|
||||||
|
OpenBao root token, recovery shares, private keys, AppRole SecretID, пароли и session tokens на демонстрации не выводить. Уровень 4/5 не заявлен: автоматическая ротация/revoke lifecycle и исследовательский трек не входят в это решение.
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Сдача лабораторной 7
|
||||||
|
|
||||||
|
Автор: Бахрамов Бахрам, БПИ2303. Целевая оценка: 3.
|
||||||
|
|
||||||
|
Решение запускается из чистого clone командой `python3 scripts/bootstrap.py`. Команды и подробная схема находятся в [REPORT.md](REPORT.md). Передача выполняется отдельной веткой `solution/bpi2303-bakhramov` через PR из fork в `mtusi2026lab7`.
|
||||||
|
|
||||||
|
Проверки, требуемые для защиты, сведены в `make verify`; результат сохраняется в [evidence/verification.txt](evidence/verification.txt). В репозитории нет `.env`, `.local`, OpenBao operator token/shares, AppRole SecretID, CA private keys или service private keys. Публичный контракт и тесты не изменялись.
|
||||||
|
|
||||||
|
Использование ИИ: ИИ применялся при анализе задания, написании и отладке реализации/тестов, а также оформлении документации. Автор обязан самостоятельно проверить и объяснить принятое решение.
|
||||||
|
|
||||||
|
Ограничения: учебный single-host стенд, без кластерной отказоустойчивости, автоматической ротации credentials/certificates и завершённого трека уровня 5.
|
||||||
Reference in New Issue
Block a user